mirror of
https://github.com/streetwriters/notesnook.git
synced 2026-08-29 10:09:26 +02:00
Compare commits
258 Commits
3.3.15-bet
...
3.4.0-beta
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cf3f2fc3ce | ||
|
|
a62fea1a4b | ||
|
|
f83e894758 | ||
|
|
131f6c6d5f | ||
|
|
4e2fd9dde6 | ||
|
|
534cf883be | ||
|
|
92c1ca7b6f | ||
|
|
5fcad35cdc | ||
|
|
8a83a1af23 | ||
|
|
2b11fcea41 | ||
|
|
690c30eed3 | ||
|
|
3f0c24d27b | ||
|
|
71088fca99 | ||
|
|
d6f7f0c0be | ||
|
|
4044b68701 | ||
|
|
610ced00af | ||
|
|
8cc86284ee | ||
|
|
e4f1f2bfa7 | ||
|
|
1f7a64a42d | ||
|
|
2b1cd537e2 | ||
|
|
f9fecda1f1 | ||
|
|
769d92fa0c | ||
|
|
f6d5d3cebc | ||
|
|
74921ae1b3 | ||
|
|
f3ef277a52 | ||
|
|
d30ec4a19d | ||
|
|
40f2c88ead | ||
|
|
7fe410ae89 | ||
|
|
4cbdd085d6 | ||
|
|
24556dab83 | ||
|
|
206157b68b | ||
|
|
dd8116eba8 | ||
|
|
ae82a8c0a0 | ||
|
|
418e4517a5 | ||
|
|
9bd0f0ceb1 | ||
|
|
af4dc5e9ea | ||
|
|
71b03a90dd | ||
|
|
728e50cd13 | ||
|
|
c8e8935b34 | ||
|
|
61a56662eb | ||
|
|
21f4b906d7 | ||
|
|
d49d42b736 | ||
|
|
6efd1af0e9 | ||
|
|
267fe4e453 | ||
|
|
8189b2ead8 | ||
|
|
257ac8962c | ||
|
|
faea6635c6 | ||
|
|
537521d568 | ||
|
|
e3ed75461e | ||
|
|
f6b59eeb99 | ||
|
|
b58db58e13 | ||
|
|
195dc18a09 | ||
|
|
187086460d | ||
|
|
84655cec40 | ||
|
|
413ca61ef5 | ||
|
|
49b1dd46d1 | ||
|
|
76e14d4434 | ||
|
|
f828ab0314 | ||
|
|
8d3d173762 | ||
|
|
12644fce28 | ||
|
|
358b499d32 | ||
|
|
17864d3325 | ||
|
|
7b6165c8f0 | ||
|
|
02b96470bc | ||
|
|
c90a2f5179 | ||
|
|
7234128f78 | ||
|
|
27e070e555 | ||
|
|
539950bdc5 | ||
|
|
83280e7cee | ||
|
|
cee0275565 | ||
|
|
87bddf0037 | ||
|
|
e736e3d810 | ||
|
|
47b2569b29 | ||
|
|
692975d4a0 | ||
|
|
6a843a6457 | ||
|
|
a139bdad1e | ||
|
|
b5dc298d7d | ||
|
|
561477fb1a | ||
|
|
092f15406c | ||
|
|
543766d564 | ||
|
|
befcd0f112 | ||
|
|
8b92936d05 | ||
|
|
aec135de83 | ||
|
|
f9738168e5 | ||
|
|
9789edad4c | ||
|
|
b46e02753a | ||
|
|
5f74fcad0c | ||
|
|
e873b88dbd | ||
|
|
214f5b8a98 | ||
|
|
70cf17fdd5 | ||
|
|
7d557810cb | ||
|
|
ed24282703 | ||
|
|
e2cf3e81af | ||
|
|
28fa133b6d | ||
|
|
37893ced80 | ||
|
|
34b5005591 | ||
|
|
900c48292c | ||
|
|
302ae5ddb4 | ||
|
|
24fca08fdc | ||
|
|
2b0a1c6a78 | ||
|
|
91077dc132 | ||
|
|
fcba5f9c91 | ||
|
|
5909025976 | ||
|
|
273bbea938 | ||
|
|
36c44ad201 | ||
|
|
46f5a2d7a7 | ||
|
|
c2702efc7f | ||
|
|
c96d13d416 | ||
|
|
3d52a307ca | ||
|
|
9b359a91cc | ||
|
|
0af831d50b | ||
|
|
3efaeaeeb9 | ||
|
|
00a20dda48 | ||
|
|
ec45160b27 | ||
|
|
eda284ca25 | ||
|
|
1ed331b4bb | ||
|
|
ee74bb4fbf | ||
|
|
df104669a3 | ||
|
|
9621b43bf2 | ||
|
|
503c1a5c8d | ||
|
|
a2fa1d4d78 | ||
|
|
6c6ad9a766 | ||
|
|
fc8807f74d | ||
|
|
edec48f9d4 | ||
|
|
ce98551057 | ||
|
|
74a2cc5b19 | ||
|
|
9628a940e9 | ||
|
|
d48643cbb9 | ||
|
|
558beaf216 | ||
|
|
6cc5d2452b | ||
|
|
e934ef7ffd | ||
|
|
e2d8032ef4 | ||
|
|
81e6101fb5 | ||
|
|
070354920b | ||
|
|
32c825463f | ||
|
|
404168fb86 | ||
|
|
d5fa9fd02b | ||
|
|
6cc66d91be | ||
|
|
1172a8c67b | ||
|
|
0191e5be00 | ||
|
|
7f367389bb | ||
|
|
e94c757d5b | ||
|
|
20a3b3b95e | ||
|
|
9145ea4234 | ||
|
|
0fa79433bd | ||
|
|
5185273b38 | ||
|
|
eadd23de4d | ||
|
|
71d9738980 | ||
|
|
29e213ebe2 | ||
|
|
80328af888 | ||
|
|
5e83da5575 | ||
|
|
521afe90ca | ||
|
|
ee3b7b5d7d | ||
|
|
95a9775c26 | ||
|
|
93d1319b25 | ||
|
|
b2bac3808b | ||
|
|
ebf58e68cf | ||
|
|
dc3e909dfe | ||
|
|
bf09e9615a | ||
|
|
b2d30d47d6 | ||
|
|
b1296fd24f | ||
|
|
62d8c89300 | ||
|
|
80c44eee89 | ||
|
|
153eb126fc | ||
|
|
f1fc166713 | ||
|
|
dda36bb036 | ||
|
|
843ad08813 | ||
|
|
a0e3c923e4 | ||
|
|
3095b03b09 | ||
|
|
8eb7663f37 | ||
|
|
ea5a0e0a7c | ||
|
|
2b4ec5b03b | ||
|
|
59f7add065 | ||
|
|
9c7bfc2347 | ||
|
|
ef90f40be4 | ||
|
|
bca6a4f22c | ||
|
|
1d3e2b56b2 | ||
|
|
a93a20ed5b | ||
|
|
971a80c183 | ||
|
|
125b60facc | ||
|
|
ef99b47178 | ||
|
|
d65f870213 | ||
|
|
5b3f1c9de2 | ||
|
|
4afb090cb1 | ||
|
|
8cf6e65ed8 | ||
|
|
c85c51ec08 | ||
|
|
dbeabea6c5 | ||
|
|
dfbe2d0f0f | ||
|
|
ea2277ea4e | ||
|
|
ad78105a6e | ||
|
|
36584175e2 | ||
|
|
084b1fdfd2 | ||
|
|
bed091e20f | ||
|
|
4420663687 | ||
|
|
677ae82ffa | ||
|
|
48a3fac9e0 | ||
|
|
e797d37b01 | ||
|
|
ffafd2e787 | ||
|
|
8500c971eb | ||
|
|
46a67a56fb | ||
|
|
5dc62e6df2 | ||
|
|
4479d6cf56 | ||
|
|
1faaf1f6b1 | ||
|
|
1f33ef191a | ||
|
|
d5bf8a6e3c | ||
|
|
5c252c7843 | ||
|
|
d2e10ccaf6 | ||
|
|
89d2b6870f | ||
|
|
26a9086d96 | ||
|
|
9fc8e6b1e5 | ||
|
|
6718650619 | ||
|
|
a622949f23 | ||
|
|
5a2df5b2c1 | ||
|
|
ae751cdd65 | ||
|
|
0d00bb2866 | ||
|
|
4299965064 | ||
|
|
6f3fc8db3d | ||
|
|
db731856f8 | ||
|
|
217f1dd6d4 | ||
|
|
cf87929476 | ||
|
|
d343a0720e | ||
|
|
51bd58edb2 | ||
|
|
f778d83316 | ||
|
|
b169206c68 | ||
|
|
4cea69e71d | ||
|
|
04d422b411 | ||
|
|
49dec52aa0 | ||
|
|
b83a62814d | ||
|
|
ce5449f25a | ||
|
|
aa769a8921 | ||
|
|
a8d4e6c754 | ||
|
|
f2402cf086 | ||
|
|
07a481f002 | ||
|
|
f41638db6d | ||
|
|
82baf41d8e | ||
|
|
e60370d4dc | ||
|
|
3e412323ee | ||
|
|
d635c1a056 | ||
|
|
f02db2a024 | ||
|
|
8c74324ff8 | ||
|
|
f2230eb39b | ||
|
|
ab900ae5da | ||
|
|
1cf28c56c2 | ||
|
|
08cd33a0cf | ||
|
|
7b0d2a239d | ||
|
|
5d922d934c | ||
|
|
5bab9ea914 | ||
|
|
da06d7e636 | ||
|
|
aece140473 | ||
|
|
656f87e3c6 | ||
|
|
36a95616d9 | ||
|
|
60bdc4715d | ||
|
|
7da168ab52 | ||
|
|
8b17495f0e | ||
|
|
add1b8a68a | ||
|
|
0aeea965c0 | ||
|
|
b7d2865435 | ||
|
|
4a158b2547 |
30
.github/pull_request_template.md
vendored
Normal file
30
.github/pull_request_template.md
vendored
Normal file
@@ -0,0 +1,30 @@
|
||||
## Description
|
||||
<!-- Add a detailed summary of what this feature/bugfix does -->
|
||||
|
||||
## Type of Change
|
||||
- [ ] Bug fix
|
||||
- [ ] Feature
|
||||
|
||||
## Visuals
|
||||
- [ ] Attached relevant screenshots / screen recording / GIF
|
||||
- [ ] N/A (not a feature or no UI changes)
|
||||
|
||||
## Testing
|
||||
- [ ] Ran all E2E tests
|
||||
- [ ] Ran all integration tests
|
||||
- [ ] Added/updated tests for this change (if needed)
|
||||
- [ ] N/A (tests not needed — explanation provided below)
|
||||
|
||||
### If tests were not added, explain why
|
||||
<!-- explanation -->
|
||||
|
||||
## Platform
|
||||
<!-- Describe which platforms this PR is related to -->
|
||||
|
||||
- [ ] Web
|
||||
- [ ] Mobile
|
||||
- [ ] Desktop
|
||||
|
||||
## Sign-off
|
||||
- [ ] QA passed
|
||||
- [ ] UI/UX passed
|
||||
135
.github/workflows/android.preview.firebase.yml
vendored
Normal file
135
.github/workflows/android.preview.firebase.yml
vendored
Normal file
@@ -0,0 +1,135 @@
|
||||
name: Notesnook Android Preview
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
types: [opened, reopened, synchronize]
|
||||
branches: [master, beta]
|
||||
paths:
|
||||
- "apps/mobile/**"
|
||||
- "packages/**"
|
||||
- ".github/workflows/android.preview.firebase.yml"
|
||||
|
||||
jobs:
|
||||
authorize:
|
||||
environment: ${{ github.event_name == 'pull_request_target' &&
|
||||
github.event.pull_request.head.repo.full_name != github.repository &&
|
||||
'external' || 'internal' }}
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- run: echo true
|
||||
|
||||
build:
|
||||
needs: authorize
|
||||
runs-on: ubuntu-22.04
|
||||
env:
|
||||
STAGING_BUILD: true
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v2
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha || github.ref }}
|
||||
|
||||
- name: Setup Node
|
||||
uses: ./.github/actions/setup-node-with-cache
|
||||
|
||||
- name: Use specific Java version for the builds
|
||||
uses: joschi/setup-jdk@v2
|
||||
with:
|
||||
java-version: "17"
|
||||
architecture: "x64"
|
||||
|
||||
- name: Free Disk Space (Ubuntu)
|
||||
uses: jlumbroso/free-disk-space@main
|
||||
with:
|
||||
# this might remove tools that are actually needed,
|
||||
# if set to "true" but frees about 6 GB
|
||||
tool-cache: false
|
||||
|
||||
# all of these default to true, but feel free to set to
|
||||
# "false" if necessary for your workflow
|
||||
android: false
|
||||
dotnet: true
|
||||
haskell: true
|
||||
large-packages: true
|
||||
docker-images: true
|
||||
swap-storage: true
|
||||
|
||||
- name: Install node modules
|
||||
run: |
|
||||
npm ci --ignore-scripts --prefer-offline --no-audit
|
||||
npm run bootstrap -- --scope=mobile
|
||||
|
||||
- name: Make Gradlew Executable
|
||||
run: cd apps/mobile/android && chmod +x ./gradlew
|
||||
|
||||
- name: Get build number
|
||||
id: build-number
|
||||
run: echo "timestamp=$(($(date +%s) - 1774851180 ))" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Check for typescript errors
|
||||
run: |
|
||||
npm run tx mobile:build
|
||||
cd apps/mobile
|
||||
npx tsc --noEmit
|
||||
|
||||
- name: Build arm64-v8a apk
|
||||
run: |
|
||||
cd apps/mobile/android
|
||||
./gradlew assembleRelease -PreactNativeArchitectures=arm64-v8a -PstagingReleaseBuild=true -PprBuildNumber=${{ steps.build-number.outputs.timestamp }}
|
||||
|
||||
- name: Get app version
|
||||
id: package-version
|
||||
uses: saionaro/extract-package-version@master
|
||||
with:
|
||||
path: apps/mobile
|
||||
|
||||
- name: Publish to firebase CLI
|
||||
id: firebase-output
|
||||
uses: wzieba/Firebase-Distribution-Github-Action@v1
|
||||
with:
|
||||
appId: ${{secrets.FIREBASE_APP_ID}}
|
||||
serviceCredentialsFileContent: ${{ secrets.QA_SERVICE_ACCOUNT }}
|
||||
groups: testers
|
||||
file: apps/mobile/android/app/build/outputs/apk/release/app-arm64-v8a-release.apk
|
||||
releaseNotes: Preview for https://github.com/streetwriters/notesnook/pull/${{github.event.number}}
|
||||
|
||||
- name: Post or update PR comment
|
||||
uses: actions/github-script@v6
|
||||
env:
|
||||
preview_url: ${{ steps.firebase-output.outputs.TESTING_URI }}
|
||||
with:
|
||||
script: |
|
||||
const marker = '<!-- android-preview-comment -->';
|
||||
const prNumber = context.issue.number;
|
||||
const previewUrl = process.env.preview_url || '';
|
||||
const body = `${marker}\n**Android App Preview**\n\n${previewUrl || 'Preview URL unavailable — check workflow logs.'}\n\nCommit: ${process.env.GITHUB_SHA}\n`;
|
||||
const { data: comments } = await github.rest.issues.listComments({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: prNumber,
|
||||
});
|
||||
const existing = comments.find(c => c.body && c.body.includes(marker));
|
||||
if (existing) {
|
||||
await github.rest.issues.updateComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
comment_id: existing.id,
|
||||
body,
|
||||
});
|
||||
} else {
|
||||
await github.rest.issues.createComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: prNumber,
|
||||
body,
|
||||
});
|
||||
}
|
||||
|
||||
- name: Upload sourcemaps
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: sourcemaps
|
||||
path: |
|
||||
apps/mobile/android/app/build/generated/sourcemaps/**/*.map
|
||||
258
.github/workflows/desktop.preview.yml
vendored
Normal file
258
.github/workflows/desktop.preview.yml
vendored
Normal file
@@ -0,0 +1,258 @@
|
||||
name: Preview @notesnook/desktop
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, reopened, synchronize]
|
||||
branches: [master, beta]
|
||||
paths:
|
||||
- "apps/desktop/**"
|
||||
- "apps/web/**"
|
||||
- "packages/**"
|
||||
# re-run workflow if workflow file changes
|
||||
- ".github/workflows/desktop.preview.yml"
|
||||
|
||||
jobs:
|
||||
build:
|
||||
if: ${{ github.event.pull_request.head.repo.full_name == github.repository }}
|
||||
name: Build
|
||||
runs-on: ubuntu-22.04
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node
|
||||
uses: ./.github/actions/setup-node-with-cache
|
||||
|
||||
- name: Install packages
|
||||
run: |
|
||||
npm ci --ignore-scripts --prefer-offline --no-audit
|
||||
npm run bootstrap -- --scope=web
|
||||
npm run bootstrap -- --scope=desktop
|
||||
|
||||
- name: Install sqlite-better-trigram for all arch
|
||||
run: |
|
||||
npm i --cpu arm64 sqlite-better-trigram
|
||||
npm i --cpu x64 sqlite-better-trigram
|
||||
working-directory: ./apps/desktop
|
||||
|
||||
- name: Generate desktop build (stable)
|
||||
run: npm run tx @notesnook/web:build:desktop
|
||||
|
||||
- name: Build desktop bundle
|
||||
working-directory: ./apps/desktop
|
||||
run: npm run bundle
|
||||
|
||||
- name: Archive build artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: build
|
||||
path: apps/web/build/**/*
|
||||
|
||||
build-macos:
|
||||
name: Build for macOS
|
||||
needs: build
|
||||
runs-on: macos-14
|
||||
outputs:
|
||||
macos-artifact-url: ${{ steps.artifact-upload-step.outputs.artifact-url }}
|
||||
steps:
|
||||
- name: Check out Git repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node
|
||||
uses: ./.github/actions/setup-node-with-cache
|
||||
|
||||
- name: Install setuptools
|
||||
run: brew install python-setuptools
|
||||
|
||||
- name: Setup notarization
|
||||
run: |
|
||||
mkdir -p ~/private_keys/
|
||||
echo '${{ secrets.api_key }}' > ~/private_keys/AuthKey_${{ secrets.api_key_id }}.p8
|
||||
|
||||
- name: Collect app metadata
|
||||
id: app_metadata
|
||||
working-directory: ./apps/desktop
|
||||
run: |
|
||||
echo ::set-output name=apple_app_id::$(cat package.json | jq -r .appAppleId)
|
||||
echo ::set-output name=app_bundle_id::$(cat package.json | jq -r .build.appId)
|
||||
echo ::set-output name=app_version::$(cat package.json | jq -r .version)
|
||||
echo ::set-output name=bundle_version::$(cat package.json | jq -r .build.mac.bundleVersion)
|
||||
|
||||
- name: Download build
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: build
|
||||
path: ./apps/web/build
|
||||
|
||||
- name: Install packages
|
||||
run: |
|
||||
npm ci --ignore-scripts --prefer-offline --no-audit
|
||||
npm run bootstrap -- --scope=desktop
|
||||
|
||||
- name: Install sqlite-better-trigram for all arch
|
||||
run: |
|
||||
npm i --cpu arm64 sqlite-better-trigram
|
||||
npm i --cpu x64 sqlite-better-trigram
|
||||
working-directory: ./apps/desktop
|
||||
|
||||
- name: Install provisioning profile
|
||||
run: echo "${{ secrets.MAC_PROVISIONING_PROFILE }}" | base64 --decode > embedded.provisionprofile
|
||||
working-directory: ./apps/desktop
|
||||
|
||||
- name: Build dmg
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
CSC_LINK: ${{ secrets.mac_certs }}
|
||||
CSC_KEY_PASSWORD: ${{ secrets.mac_certs_password }}
|
||||
APPLE_API_KEY: ~/private_keys/AuthKey_${{ secrets.api_key_id }}.p8
|
||||
APPLE_API_KEY_ID: ${{ secrets.api_key_id }}
|
||||
APPLE_API_ISSUER: ${{ secrets.api_key_issuer_id }}
|
||||
CSC_FOR_PULL_REQUEST: true
|
||||
run: |
|
||||
npm run tx @notesnook/desktop:release
|
||||
cd apps/desktop
|
||||
yarn electron-builder --config=electron-builder.config.js --mac dmg --arm64 -p never
|
||||
|
||||
- name: Upload dmg artifact
|
||||
id: artifact-upload-step
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: macos-build
|
||||
path: apps/desktop/output/*.dmg
|
||||
|
||||
build-linux-x64:
|
||||
name: Build for Linux x64
|
||||
needs: build
|
||||
runs-on: ubuntu-22.04
|
||||
outputs:
|
||||
linux-x64-artifact-url: ${{ steps.artifact-upload-step.outputs.artifact-url }}
|
||||
steps:
|
||||
- name: Check out Git repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node
|
||||
uses: ./.github/actions/setup-node-with-cache
|
||||
|
||||
- name: Download build
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: build
|
||||
path: ./apps/web/build
|
||||
|
||||
- name: Install packages
|
||||
run: |
|
||||
npm ci --ignore-scripts --prefer-offline --no-audit
|
||||
npm run bootstrap -- --scope=desktop
|
||||
|
||||
- name: Install sqlite-better-trigram for all arch
|
||||
run: |
|
||||
npm i --cpu x64 sqlite-better-trigram
|
||||
working-directory: ./apps/desktop
|
||||
|
||||
- name: Build Electron wrapper
|
||||
run: npm run tx @notesnook/desktop:release
|
||||
|
||||
- name: Build AppImage
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: yarn electron-builder --config=electron-builder.config.js --linux AppImage:x64 -p never
|
||||
working-directory: ./apps/desktop
|
||||
|
||||
- name: Upload AppImage artifact
|
||||
id: artifact-upload-step
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: linux-x64-build
|
||||
path: apps/desktop/output/*.AppImage
|
||||
|
||||
build-windows:
|
||||
name: Build for Windows
|
||||
needs: build
|
||||
runs-on: windows-latest
|
||||
outputs:
|
||||
windows-artifact-url: ${{ steps.artifact-upload-step.outputs.artifact-url }}
|
||||
steps:
|
||||
- name: Check out Git repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node
|
||||
uses: ./.github/actions/setup-node-with-cache
|
||||
|
||||
- name: Download build
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: build
|
||||
path: ./apps/web/build
|
||||
|
||||
- name: Install packages
|
||||
run: |
|
||||
npm ci --ignore-scripts --prefer-offline --no-audit
|
||||
npm run bootstrap -- --scope=desktop
|
||||
|
||||
- name: Install sqlite-better-trigram for all arch
|
||||
run: |
|
||||
npm i --cpu arm64 sqlite-better-trigram
|
||||
npm i --cpu x64 sqlite-better-trigram
|
||||
|
||||
npm i --cpu arm64 sqlite3-fts5-html
|
||||
npm i --cpu x64 sqlite3-fts5-html
|
||||
working-directory: ./apps/desktop
|
||||
|
||||
- name: Build
|
||||
run: node scripts/execute.mjs @notesnook/desktop:release
|
||||
|
||||
- name: Publish
|
||||
env:
|
||||
NOTESNOOK_STAGING: true
|
||||
run: yarn electron-builder --config=electron-builder.config.js --win nsis:x64 --publish never
|
||||
working-directory: ./apps/desktop
|
||||
|
||||
- name: Upload exe artifact
|
||||
id: artifact-upload-step
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: windows-build
|
||||
path: apps/desktop/output/*.exe
|
||||
|
||||
post-pr-comment:
|
||||
name: Post PR comment with preview URLs
|
||||
needs: [build, build-macos, build-linux-x64, build-windows]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Post or update PR comment
|
||||
uses: actions/github-script@v6
|
||||
env:
|
||||
macos_artifact_url: ${{ needs.build-macos.outputs.macos-artifact-url }}
|
||||
linux_x64_artifact_url: ${{ needs.build-linux-x64.outputs.linux-x64-artifact-url }}
|
||||
windows_artifact_url: ${{ needs.build-windows.outputs.windows-artifact-url }}
|
||||
with:
|
||||
script: |
|
||||
const marker = '<!-- desktop-preview-comment -->';
|
||||
const prNumber = context.issue.number;
|
||||
const previewUrl = [
|
||||
{ platform: 'macOS', url: process.env.macos_artifact_url },
|
||||
{ platform: 'Linux x64', url: process.env.linux_x64_artifact_url },
|
||||
{ platform: 'Windows x64', url: process.env.windows_artifact_url },
|
||||
].filter(u => u.url).map(u => `- [${u.platform}](${u.url})`).join('\n');
|
||||
const body = `${marker}\n**Desktop Previews**\n\n${previewUrl || 'Preview URL unavailable — check workflow logs.'}\n\nCommit: ${process.env.GITHUB_SHA}\n`;
|
||||
const { data: comments } = await github.rest.issues.listComments({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: prNumber,
|
||||
});
|
||||
const existing = comments.find(c => c.body && c.body.includes(marker));
|
||||
if (existing) {
|
||||
await github.rest.issues.updateComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
comment_id: existing.id,
|
||||
body,
|
||||
});
|
||||
} else {
|
||||
await github.rest.issues.createComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: prNumber,
|
||||
body,
|
||||
});
|
||||
}
|
||||
168
.github/workflows/ios.preview.firebase.yml
vendored
Normal file
168
.github/workflows/ios.preview.firebase.yml
vendored
Normal file
@@ -0,0 +1,168 @@
|
||||
name: Notesnook iOS Preview
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
types: [opened, reopened, synchronize]
|
||||
branches: [master, beta]
|
||||
paths:
|
||||
- "apps/mobile/**"
|
||||
- "packages/**"
|
||||
- ".github/workflows/ios.preview.firebase.yml"
|
||||
|
||||
jobs:
|
||||
authorize:
|
||||
environment: ${{ github.event_name == 'pull_request_target' &&
|
||||
github.event.pull_request.head.repo.full_name != github.repository &&
|
||||
'external' || 'internal' }}
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- run: echo true
|
||||
|
||||
build:
|
||||
needs: authorize
|
||||
runs-on: macos-26
|
||||
timeout-minutes: 60
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha || github.ref }}
|
||||
|
||||
- name: Setup Node
|
||||
uses: ./.github/actions/setup-node-with-cache
|
||||
|
||||
- name: Setup Xcode
|
||||
uses: maxim-lobanov/setup-xcode@v1
|
||||
with:
|
||||
xcode-version: "26.1.1"
|
||||
|
||||
- name: Install node modules
|
||||
run: |
|
||||
npm ci --ignore-scripts --prefer-offline --no-audit
|
||||
npm run bootstrap -- --scope=mobile
|
||||
|
||||
- name: Build packages
|
||||
run: npm run tx @notesnook/mobile:build
|
||||
|
||||
- name: Cache Pods
|
||||
uses: actions/cache@v3
|
||||
id: pods-cache
|
||||
with:
|
||||
path: apps/mobile/ios/Pods
|
||||
key: ${{ runner.os }}-pods-${{ hashFiles('apps/mobile/ios/Podfile.lock') }}
|
||||
|
||||
- name: Install Pods
|
||||
run: |
|
||||
cd apps/mobile/ios
|
||||
pod install
|
||||
|
||||
- name: Check for typescript errors
|
||||
run: |
|
||||
npm run tx mobile:build
|
||||
cd apps/mobile
|
||||
npx tsc --noEmit
|
||||
|
||||
- name: Get marketing version
|
||||
id: marketing-version
|
||||
run: echo "version=$(grep "IOS_MARKETING_VERSION" apps/mobile/ios/build-configs/ios-build.staging.xcconfig | awk -F'=' '{print $2}' | xargs)" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Get build number
|
||||
id: build-number
|
||||
run: echo "timestamp=$(($(date +%s) - 1774851180 ))" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Make staging xcconfig active
|
||||
run: |
|
||||
cd apps/mobile/ios/build-configs
|
||||
./use-ios-build-config.sh staging --marketing-version ${{steps.marketing-version.outputs.version}} --build-number ${{steps.build-number.outputs.timestamp}}
|
||||
|
||||
- name: Build iOS App
|
||||
uses: ammarahm-ed/ios-build-action@master
|
||||
with:
|
||||
bundle-identifier: org.streetwriters.notesnook
|
||||
scheme: Notesnook
|
||||
configuration: "Release"
|
||||
export-options: apps/mobile/ios/ExportOptionsStaging.plist
|
||||
export-method: "ad-hoc"
|
||||
project-path: apps/mobile/ios/Notesnook.xcodeproj
|
||||
workspace-path: apps/mobile/ios/Notesnook.xcworkspace
|
||||
update-targets: |
|
||||
Notesnook
|
||||
Make Note
|
||||
NotesWidgetExtension
|
||||
disable-targets: Notesnook-tvOS,Notesnook-tvOSTests,NotesnookTests
|
||||
code-signing-identity: Apple Distribution
|
||||
team-id: ${{ secrets.APPLE_TEAM_ID }}
|
||||
p12-base64: ${{ secrets.APPLE_CERTIFICATE_P12 }}
|
||||
certificate-password: ${{ secrets.APPLE_CERTIFICATE_P12_PASSWORD }}
|
||||
app-store-connect-api-key-issuer-id: ${{ secrets.API_KEY_ISSUER_ID }}
|
||||
app-store-connect-api-key-id: ${{ secrets.APPSTORE_KEY_ID }}
|
||||
app-store-connect-api-key-base64: ${{ secrets.APPSTORE_CONNECT_API_KEY_BASE64 }}
|
||||
output-path: Notesnook.ipa
|
||||
mobileprovision-base64: |
|
||||
${{ secrets.APPLE_MOBILE_PROVISION_ADHOC_APP }}
|
||||
${{ secrets.APPLE_MOBILE_PROVISION_ADHOC_SHARE }}
|
||||
${{ secrets.APPLE_MOBILE_PROVISION_ADHOC_WIDGET }}
|
||||
|
||||
- name: Upload IPA artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: ios-preview-ipa
|
||||
path: Notesnook.ipa
|
||||
if-no-files-found: error
|
||||
retention-days: 1
|
||||
|
||||
publish:
|
||||
runs-on: ubuntu-latest
|
||||
needs: build
|
||||
timeout-minutes: 20
|
||||
|
||||
steps:
|
||||
- name: Download IPA artifact
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: ios-preview-ipa
|
||||
path: .
|
||||
|
||||
- name: Publish to firebase CLI
|
||||
id: firebase-output
|
||||
uses: wzieba/Firebase-Distribution-Github-Action@v1
|
||||
with:
|
||||
appId: ${{secrets.FIREBASE_IOS_APP_ID}}
|
||||
serviceCredentialsFileContent: ${{ secrets.QA_SERVICE_ACCOUNT }}
|
||||
groups: testers
|
||||
file: Notesnook.ipa
|
||||
releaseNotes: Preview for https://github.com/streetwriters/notesnook/pull/${{github.event.number}}
|
||||
|
||||
- name: Post or update PR comment
|
||||
uses: actions/github-script@v6
|
||||
env:
|
||||
preview_url: ${{ steps.firebase-output.outputs.TESTING_URI }}
|
||||
with:
|
||||
script: |
|
||||
const marker = '<!-- ios-preview-comment -->';
|
||||
const prNumber = context.issue.number;
|
||||
const previewUrl = process.env.preview_url || '';
|
||||
const body = `${marker}\n**iOS App Preview**\n\n${previewUrl || 'Preview URL unavailable — check workflow logs.'}\n\nCommit: ${process.env.GITHUB_SHA}\n`;
|
||||
const { data: comments } = await github.rest.issues.listComments({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: prNumber,
|
||||
});
|
||||
const existing = comments.find(c => c.body && c.body.includes(marker));
|
||||
if (existing) {
|
||||
await github.rest.issues.updateComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
comment_id: existing.id,
|
||||
body,
|
||||
});
|
||||
} else {
|
||||
await github.rest.issues.createComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: prNumber,
|
||||
body,
|
||||
});
|
||||
}
|
||||
40
.github/workflows/web.benchmarks.yml
vendored
40
.github/workflows/web.benchmarks.yml
vendored
@@ -1,40 +0,0 @@
|
||||
name: Benchmark @notesnook/web
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches:
|
||||
- "master"
|
||||
paths:
|
||||
- "apps/web/**"
|
||||
# re-run workflow if workflow file changes
|
||||
- ".github/workflows/web.benchmarks.yml"
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
bench:
|
||||
name: Bench
|
||||
runs-on: ubuntu-22.04
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node
|
||||
uses: ./.github/actions/setup-node-with-cache
|
||||
|
||||
- name: Install packages
|
||||
run: |
|
||||
npm ci --ignore-scripts --prefer-offline --no-audit
|
||||
npm run bootstrap -- --scope=web
|
||||
|
||||
- name: Build
|
||||
run: npm run build:web
|
||||
|
||||
- name: Install Playwright Browsers
|
||||
run: npx playwright install chromium --with-deps
|
||||
working-directory: apps/web
|
||||
|
||||
- name: Run benchmarks
|
||||
id: benchmark
|
||||
run: node __bench__/app.bench.mjs
|
||||
working-directory: apps/web
|
||||
80
.github/workflows/web.preview.yml
vendored
Normal file
80
.github/workflows/web.preview.yml
vendored
Normal file
@@ -0,0 +1,80 @@
|
||||
name: Notesnook Web PR Preview
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, reopened, synchronize]
|
||||
branches: [master, beta]
|
||||
paths:
|
||||
- "apps/web/**"
|
||||
- "packages/**"
|
||||
# re-run workflow if workflow file changes
|
||||
- ".github/workflows/web.preview.yml"
|
||||
|
||||
jobs:
|
||||
build-and-deploy:
|
||||
if: ${{ github.event.pull_request.head.repo.full_name == github.repository }}
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Node
|
||||
uses: ./.github/actions/setup-node-with-cache
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Build web
|
||||
run: npm run build:web
|
||||
|
||||
- name: Deploy to Cloudflare Pages
|
||||
id: deploy
|
||||
working-directory: ./apps/web
|
||||
run: |
|
||||
set -euo pipefail
|
||||
BRANCH=pr-${{ github.event.number }}-$(echo "${{ github.sha }}" | cut -c1-7)
|
||||
echo "Deploying branch: $BRANCH"
|
||||
DEPLOY_OUT=$(npx --yes wrangler pages deploy --project-name=notesnook-app --branch="$BRANCH" ./build 2>&1) || { echo "$DEPLOY_OUT"; exit 1; }
|
||||
echo "$DEPLOY_OUT"
|
||||
PREVIEW_URL=$(printf "%s" "$DEPLOY_OUT" | grep -Eo 'https?://[^ ]+' | head -1 || true)
|
||||
if [ -z "$PREVIEW_URL" ]; then
|
||||
echo "WARNING: could not parse preview URL from wrangler output"
|
||||
fi
|
||||
echo "preview_url=$PREVIEW_URL" >> $GITHUB_ENV
|
||||
|
||||
- name: Post or update PR comment
|
||||
uses: actions/github-script@v6
|
||||
env:
|
||||
preview_url: ${{ env.preview_url }}
|
||||
with:
|
||||
script: |
|
||||
const marker = '<!-- pages-preview-comment -->';
|
||||
const prNumber = context.issue.number;
|
||||
const previewUrl = process.env.preview_url || '';
|
||||
const body = `${marker}\n**Cloudflare Pages Preview**\n\n${previewUrl || 'Preview URL unavailable — check workflow logs.'}\n\nCommit: ${process.env.GITHUB_SHA}\n`;
|
||||
const { data: comments } = await github.rest.issues.listComments({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: prNumber,
|
||||
});
|
||||
const existing = comments.find(c => c.body && c.body.includes(marker));
|
||||
if (existing) {
|
||||
await github.rest.issues.updateComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
comment_id: existing.id,
|
||||
body,
|
||||
});
|
||||
} else {
|
||||
await github.rest.issues.createComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: prNumber,
|
||||
body,
|
||||
});
|
||||
}
|
||||
@@ -96,6 +96,7 @@ module.exports = {
|
||||
"node_modules/sodium-native/package.json"
|
||||
],
|
||||
afterPack: "./scripts/removeLocales.js",
|
||||
protocols: [{ name: "Notesnook", schemes: ["nn"] }],
|
||||
mac: {
|
||||
bundleVersion: "240",
|
||||
minimumSystemVersion: "10.12.0",
|
||||
@@ -181,6 +182,7 @@ module.exports = {
|
||||
icon: "assets/icons/app.icns",
|
||||
description: "Your private note taking space",
|
||||
executableName: linuxExecutableName,
|
||||
mimeTypes: ["x-scheme-handler/nn"],
|
||||
desktop: {
|
||||
desktopActions: {
|
||||
"new-note": {
|
||||
|
||||
4
apps/desktop/package-lock.json
generated
4
apps/desktop/package-lock.json
generated
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "@notesnook/desktop",
|
||||
"version": "3.3.9-beta.1",
|
||||
"version": "3.4.0-beta.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@notesnook/desktop",
|
||||
"version": "3.3.9-beta.1",
|
||||
"version": "3.4.0-beta.0",
|
||||
"hasInstallScript": true,
|
||||
"license": "GPL-3.0-or-later",
|
||||
"dependencies": {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"name": "@notesnook/desktop",
|
||||
"productName": "Notesnook",
|
||||
"description": "Your private note taking space",
|
||||
"version": "3.3.9-beta.1",
|
||||
"version": "3.4.0-beta.0",
|
||||
"appAppleId": "1544027013",
|
||||
"private": true,
|
||||
"main": "./dist/cjs/index.js",
|
||||
|
||||
@@ -27,6 +27,7 @@ import crypto from "crypto";
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
const root = path.join(__dirname, "..");
|
||||
const RUNNING_PROCESSES = [];
|
||||
const RESTARTABLE_PROCESSES = [];
|
||||
let lastBundleHash = null;
|
||||
@@ -36,7 +37,7 @@ const ENV = {
|
||||
FORCE_COLOR: "false",
|
||||
COLOR: "0"
|
||||
};
|
||||
process.chdir(path.join(__dirname, ".."));
|
||||
process.chdir(root);
|
||||
|
||||
await onChange(true);
|
||||
|
||||
@@ -55,13 +56,16 @@ async function onChange(first) {
|
||||
if (first) {
|
||||
await fs.rm("./build/", { force: true, recursive: true });
|
||||
|
||||
await exec("npm rebuild electron --verbose --foreground-scripts");
|
||||
await exec(
|
||||
"npm run postinstall --verbose",
|
||||
path.join(root, "node_modules", "electron")
|
||||
);
|
||||
|
||||
await exec("yarn electron-builder install-app-deps");
|
||||
await exec("yarn electron-builder install-app-deps", root);
|
||||
}
|
||||
|
||||
await exec(`yarn run bundle`);
|
||||
await exec(`yarn run build`);
|
||||
await exec(`yarn run bundle`, root);
|
||||
await exec(`yarn run build`, root);
|
||||
|
||||
if (await isBundleSame()) {
|
||||
console.log("Bundle is same. Doing nothing.");
|
||||
@@ -111,7 +115,7 @@ function spawnAndWaitUntil(cmd, cwd, predicate) {
|
||||
|
||||
async function exec(cmd, cwd) {
|
||||
try {
|
||||
console.log(">", cmd);
|
||||
console.log(">", cmd, cwd);
|
||||
|
||||
return execSync(cmd, {
|
||||
env: ENV,
|
||||
|
||||
@@ -24,21 +24,43 @@ import TypedEventEmitter from "typed-emitter";
|
||||
|
||||
export type AppEvents = {
|
||||
onCreateItem(name: "note" | "notebook" | "reminder"): void;
|
||||
onOpenLink(url: string): void;
|
||||
bridgeReady(): void;
|
||||
};
|
||||
|
||||
const emitter = new EventEmitter();
|
||||
const typedEmitter = emitter as TypedEventEmitter<AppEvents>;
|
||||
let isBridgeReady = false;
|
||||
const pendingEvents: { name: string; args: unknown[] }[] = [];
|
||||
const _emitter = new EventEmitter();
|
||||
const emitter = _emitter as TypedEventEmitter<AppEvents>;
|
||||
const t = initTRPC.create();
|
||||
|
||||
export const bridgeRouter = t.router({
|
||||
onCreateItem: createSubscription("onCreateItem")
|
||||
onCreateItem: createSubscription("onCreateItem"),
|
||||
onOpenLink: createSubscription("onOpenLink"),
|
||||
ready: t.procedure.query(() => {
|
||||
isBridgeReady = true;
|
||||
if (pendingEvents.length > 0) {
|
||||
console.log(
|
||||
"Emitting pending events",
|
||||
pendingEvents.map((e) => e.name)
|
||||
);
|
||||
pendingEvents.forEach((event) => {
|
||||
emitter.emit(event.name as any, ...(event.args as any[]));
|
||||
});
|
||||
pendingEvents.length = 0;
|
||||
}
|
||||
return true;
|
||||
})
|
||||
});
|
||||
|
||||
export const bridge: AppEvents = new Proxy({} as AppEvents, {
|
||||
get(_t, name) {
|
||||
if (typeof name === "symbol") return;
|
||||
return (...args: unknown[]) => {
|
||||
emitter.emit(name, ...args);
|
||||
if (!isBridgeReady) {
|
||||
pendingEvents.push({ name, args });
|
||||
return;
|
||||
}
|
||||
_emitter.emit(name, ...args);
|
||||
};
|
||||
}
|
||||
});
|
||||
@@ -49,9 +71,9 @@ function createSubscription<TName extends keyof AppEvents>(eventName: TName) {
|
||||
const listener: AppEvents[TName] = (...args: any[]) => {
|
||||
emit.next(args[0]);
|
||||
};
|
||||
typedEmitter.addListener(eventName, listener);
|
||||
emitter.addListener(eventName, listener);
|
||||
return () => {
|
||||
typedEmitter.removeListener(eventName, listener);
|
||||
emitter.removeListener(eventName, listener);
|
||||
};
|
||||
});
|
||||
});
|
||||
|
||||
@@ -252,6 +252,7 @@ export const osIntegrationRouter = t.router({
|
||||
if (menuItem) menu.append(menuItem);
|
||||
}
|
||||
if (menu.items.length > 0) menu.popup();
|
||||
menu.on("menu-will-close", () => emit.next([]));
|
||||
return () => {
|
||||
menu.removeAllListeners();
|
||||
menu.closePopup();
|
||||
|
||||
@@ -113,7 +113,8 @@ export class SQLite {
|
||||
};
|
||||
}
|
||||
} catch (e) {
|
||||
if (e instanceof Error) e.message += ` (query: ${sql})`;
|
||||
if (e instanceof Error)
|
||||
throw rewriteError(e, `${e.message} (query: ${sql})`);
|
||||
throw e;
|
||||
} finally {
|
||||
// Since SQLite 3.48.0 (SQLite3MC v2.0.2) it's not possible to load fts5
|
||||
@@ -212,3 +213,11 @@ function getExtensionPath(extensionName: string, entryPoint: string) {
|
||||
}
|
||||
return loadablePath;
|
||||
}
|
||||
|
||||
function rewriteError(e: Error, message: string) {
|
||||
const error = new Error(message);
|
||||
error.stack = e.stack;
|
||||
error.name = e.name;
|
||||
error.cause = e.cause;
|
||||
return error;
|
||||
}
|
||||
|
||||
@@ -34,6 +34,17 @@ export const windowRouter = t.router({
|
||||
}),
|
||||
maximized: t.procedure.query(() => globalThis.window?.isMaximized()),
|
||||
fullscreen: t.procedure.query(() => globalThis.window?.isFullScreen()),
|
||||
onClose: t.procedure.subscription(() => {
|
||||
return observable<void>((emit) => {
|
||||
function listener() {
|
||||
emit.next();
|
||||
}
|
||||
globalThis.window?.addListener("close", listener);
|
||||
return () => {
|
||||
globalThis.window?.removeListener("close", listener);
|
||||
};
|
||||
});
|
||||
}),
|
||||
onWindowStateChanged: t.procedure.subscription(() => {
|
||||
return observable<{ maximized: boolean; fullscreen: boolean }>((emit) => {
|
||||
function listener() {
|
||||
|
||||
@@ -52,6 +52,13 @@ locale.then(({ default: locale }) => {
|
||||
});
|
||||
setI18nGlobal(i18n);
|
||||
|
||||
const appHostnames = isDevelopment()
|
||||
? ["localhost", "127.0.0.1"]
|
||||
: ["app.notesnook.com"];
|
||||
// Pending nn:// link to open once the window is ready (used on Windows/Linux
|
||||
// when the app is launched via the nn:// protocol for the first time).
|
||||
let pendingNNLink: string | undefined = findNNLink(process.argv);
|
||||
|
||||
// only run a single instance
|
||||
if (!MAC_APP_STORE && !app.requestSingleInstanceLock()) {
|
||||
console.log("Another instance is already running!");
|
||||
@@ -173,10 +180,28 @@ async function createWindow() {
|
||||
return { action: "deny" };
|
||||
});
|
||||
|
||||
mainWindow.webContents.on("will-navigate", (event, url) => {
|
||||
try {
|
||||
const parsedUrl = new URL(url);
|
||||
if (!appHostnames.includes(parsedUrl.hostname)) {
|
||||
event.preventDefault();
|
||||
shell.openExternal(url);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("will-navigate: failed to parse URL", url, e);
|
||||
event.preventDefault();
|
||||
}
|
||||
});
|
||||
|
||||
nativeTheme.on("updated", () => {
|
||||
setupTray();
|
||||
setupJumplist();
|
||||
});
|
||||
|
||||
if (pendingNNLink) {
|
||||
bridge.onOpenLink(pendingNNLink);
|
||||
pendingNNLink = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
app.once("ready", async () => {
|
||||
@@ -196,6 +221,8 @@ app.once("ready", async () => {
|
||||
if (config.customDns) enableCustomDns();
|
||||
else disableCustomDns();
|
||||
|
||||
if (!MAC_APP_STORE) app.setAsDefaultProtocolClient("nn");
|
||||
|
||||
if (!isDevelopment()) registerProtocol();
|
||||
await createWindow();
|
||||
configureAutoUpdater();
|
||||
@@ -209,6 +236,12 @@ app.once("window-all-closed", () => {
|
||||
|
||||
app.on("second-instance", async (_ev, argv) => {
|
||||
if (!globalThis.window) return;
|
||||
const nnLink = findNNLink(argv);
|
||||
if (nnLink) {
|
||||
bridge.onOpenLink(nnLink);
|
||||
bringToFront();
|
||||
return;
|
||||
}
|
||||
const cliOptions = await parseArguments(argv);
|
||||
if (cliOptions.note) bridge.onCreateItem("note");
|
||||
if (cliOptions.notebook) bridge.onCreateItem("notebook");
|
||||
@@ -216,12 +249,29 @@ app.on("second-instance", async (_ev, argv) => {
|
||||
bringToFront();
|
||||
});
|
||||
|
||||
// macOS opens URLs via this event. The app may or may not be fully loaded yet.
|
||||
app.on("open-url", (event, url) => {
|
||||
event.preventDefault();
|
||||
if (!url.startsWith("nn://")) return;
|
||||
if (globalThis.window) {
|
||||
bridge.onOpenLink(url);
|
||||
bringToFront();
|
||||
} else {
|
||||
// Window not ready yet — store for when createWindow finishes loading.
|
||||
pendingNNLink = url;
|
||||
}
|
||||
});
|
||||
|
||||
app.on("activate", () => {
|
||||
if (globalThis.window === null) {
|
||||
createWindow();
|
||||
}
|
||||
});
|
||||
|
||||
function findNNLink(argv: string[]): string | undefined {
|
||||
return argv.find((arg) => arg.startsWith("nn://"));
|
||||
}
|
||||
|
||||
function createURL(options: CLIOptions, path = "/") {
|
||||
const url = new URL(isDevelopment() ? "http://localhost:3000" : PROTOCOL_URL);
|
||||
|
||||
@@ -232,7 +282,7 @@ function createURL(options: CLIOptions, path = "/") {
|
||||
else if (typeof options.note === "string")
|
||||
url.hash = `/notes/${options.note}/edit`;
|
||||
else if (typeof options.notebook === "string")
|
||||
url.hash = `/notebooks/${options.notebook}`;
|
||||
url.pathname = `/notebooks/${options.notebook}`;
|
||||
|
||||
return url;
|
||||
}
|
||||
|
||||
@@ -62,7 +62,17 @@ function registerProtocol() {
|
||||
headers: { "Content-Type": extensionToMimeType[fileExtension] }
|
||||
});
|
||||
} else {
|
||||
return net.fetch(request, { bypassCustomProtocolHandlers: true });
|
||||
const requestHeaders = new Headers(request.headers);
|
||||
if (!requestHeaders.has("referer"))
|
||||
requestHeaders.set("referer", PROTOCOL_URL);
|
||||
return await net.fetch(
|
||||
new Request(request, {
|
||||
headers: requestHeaders
|
||||
}),
|
||||
{
|
||||
bypassCustomProtocolHandlers: true
|
||||
}
|
||||
);
|
||||
}
|
||||
});
|
||||
console.info(`${SCHEME} protocol inteception "successful"`);
|
||||
|
||||
@@ -30,7 +30,7 @@ module.exports = {
|
||||
testBinaryPath:
|
||||
"android/app/build/outputs/apk/androidTest/debug/app-debug-androidTest.apk",
|
||||
build:
|
||||
"cd android ; ENVFILE=.env.test ./gradlew assembleDebug assembleAndroidTest -DtestBuildType=debug && cd ..",
|
||||
"cd android ; ENVFILE=.env.test ./gradlew assembleDebug assembleAndroidTest -DtestBuildType=debug -PreactNativeArchitectures=arm64-v8a && cd ..",
|
||||
reversePorts: [8081]
|
||||
},
|
||||
"android.release": {
|
||||
|
||||
@@ -3,10 +3,8 @@
|
||||
</p>
|
||||
|
||||
<h1 align="center">Notesnook Mobile</h1>
|
||||
<h3 align="center">The mobile app is built using React Native, Typescript & Javascript for both iOS & Android.</h3>
|
||||
<p align="center">
|
||||
<a href="#developer-guide">Developer guide</a> | <a href="#build-instructions">How to build?</a>
|
||||
</p>
|
||||
<h3 align="center">The mobile app is built with React Native for both iOS and Android.</h3>
|
||||
<p align="center"><a href="#build-instructions">Build instructions</a> | <a href="#developer-guide">Developer guide</a> | <a href="#running-e2e-tests-detox">E2E tests</a></p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://play.google.com/store/apps/details?id=com.streetwriters.notesnook">
|
||||
@@ -25,21 +23,21 @@
|
||||
|
||||
Requirements:
|
||||
|
||||
1. [Node.js](https://nodejs.org/en/download/)
|
||||
1. [Node.js](https://nodejs.org/en/download/) 20+ (the repo is pinned to Node `22.20.0` via Volta)
|
||||
2. [git](https://git-scm.com/downloads)
|
||||
3. NPM (not yarn or pnpm)
|
||||
4. [React Native](https://reactnative.dev/docs/environment-setup)
|
||||
3. `npm`
|
||||
4. [React Native environment setup](https://reactnative.dev/docs/set-up-your-environment)
|
||||
|
||||
To run the app locally, you will need to setup React Native on your system:
|
||||
To run the app locally, first complete React Native native tooling setup:
|
||||
|
||||
1. Open the official [environment setup guide here](https://reactnative.dev/docs/environment-setup)
|
||||
1. Open [React Native environment setup](https://reactnative.dev/docs/set-up-your-environment)
|
||||
2. Select `React Native CLI Quickstart`
|
||||
3. Select your OS & the platform to run the app on (iOS or Android)
|
||||
3. Select your OS and target platform(s): iOS and/or Android
|
||||
4. Follow the steps listed.
|
||||
|
||||
> Please keep in mind that **Expo is not supported**.
|
||||
> Expo is not used in this project.
|
||||
|
||||
Once you have completed the setup, the first step is to `clone` the monorepo:
|
||||
Clone the monorepo:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/streetwriters/notesnook.git
|
||||
@@ -48,26 +46,27 @@ git clone https://github.com/streetwriters/notesnook.git
|
||||
cd notesnook
|
||||
```
|
||||
|
||||
Once you are inside the `./notesnook` directory, run the preparation step:
|
||||
Install dependencies and bootstrap the mobile workspace:
|
||||
|
||||
```bash
|
||||
# this might take a while to complete
|
||||
npm install
|
||||
npm run bootstrap -- --scope=mobile
|
||||
```
|
||||
|
||||
### Running the app on Android
|
||||
|
||||
[Setup an Android emulator from Android Studio](https://developer.android.com/studio/run/managing-avds) if you haven't already, and then run the following command to start the app in the Emulator:
|
||||
[Set up an Android emulator from Android Studio](https://developer.android.com/studio/run/managing-avds) (or connect a physical device), then run:
|
||||
|
||||
```bash
|
||||
npm run start:android
|
||||
```
|
||||
|
||||
If you want to run the app on your phone, make sure to [enable USB debugging](https://developer.android.com/studio/debug/dev-options).
|
||||
If you are using a physical device, enable [USB debugging](https://developer.android.com/studio/debug/dev-options).
|
||||
|
||||
### Running the app on iOS
|
||||
|
||||
To run the app on iOS:
|
||||
Install CocoaPods dependencies first, then run the iOS app:
|
||||
|
||||
```bash
|
||||
# this might take a while to complete
|
||||
@@ -76,90 +75,87 @@ npm run prepare:ios
|
||||
npm run start:ios
|
||||
```
|
||||
|
||||
### Useful development commands
|
||||
|
||||
```bash
|
||||
# start Metro only
|
||||
npm run start:metro
|
||||
|
||||
# start Re.Pack bundler
|
||||
npm run start:repack
|
||||
```
|
||||
|
||||
## Developer guide
|
||||
|
||||
> This project is in a transition state between Javascript & Typescript. We are gradually porting everything over to Typescript, so if you can help with that, it'd be great!
|
||||
> The mobile app is a mixed TypeScript/JavaScript codebase.
|
||||
|
||||
### The tech stack
|
||||
|
||||
We try to keep the stack as lean as possible:
|
||||
|
||||
1. React Native
|
||||
2. Typescript/Javascript
|
||||
3. Zustand: State management
|
||||
4. Detox: Runs all our e2e tests
|
||||
5. React Native MMKV: Database & persistence
|
||||
6. libsodium: Encryption
|
||||
1. React Native `0.82`
|
||||
2. React `19`
|
||||
3. TypeScript + JavaScript
|
||||
4. Zustand (state management)
|
||||
5. Detox (end-to-end testing)
|
||||
6. libsodium (encryption)
|
||||
|
||||
### Project structure
|
||||
|
||||
The app codebase is distributed over two primary directories. `native/` and `app/`.
|
||||
Top-level directories in `apps/mobile/`:
|
||||
|
||||
- `native/`: Includes `android/` and `ios/` folders and everything related to react native core functionality like bundling, development, and packaging. Any react-native dependency with native code, i.e., android & ios folders, is installed here.
|
||||
- `app/`: Main React Native app source (`components`, `common`, `hooks`, `navigation`, `screens`, `services`, `stores`, `utils`, etc.)
|
||||
- `android/`: Android native project
|
||||
- `ios/`: iOS native project
|
||||
- `e2e/`: Detox test suite and config
|
||||
- `patches/`: `patch-package` patches
|
||||
- `scripts/`: Mobile-specific scripts
|
||||
|
||||
- `app/`: Includes all the app code other than the native part. All JS-only dependencies are installed here.
|
||||
- `components/`: Each component serves a specific purpose in the app UI. For example, the `Paragraph` component is used to render paragraphs in the app, and a `Header` component is used to render a `header` on all screens.
|
||||
- `common/`: Features that are integral to the app's functionality. For example, the notesnook core is initialized here.
|
||||
- `hooks/`: Hooks for different app logic
|
||||
- `navigation/`: Includes app navigation-specific code. Here the app navigation, editor & side menu are rendered side by side in fluid tabs.
|
||||
- `screens`: Navigator screens.
|
||||
- `services`: Parts of code that do a specific function. For example, the `sync` service runs Sync from anywhere in the app.
|
||||
- `stores`: We use `zustand` for global state management in the app. Multiple stores provide the state for different parts of the app.
|
||||
- `utils`: General purpose stuff such as constant values, utility functions, etc.
|
||||
## Running E2E tests (Detox)
|
||||
|
||||
There are several other folders at the root:
|
||||
Detox device defaults in this repo:
|
||||
|
||||
- `share/`: Code for the iOS Share Extension and Android widget.
|
||||
- `e2e/`: Detox End to end tests
|
||||
- `patches/`: Patches for various react native dependencies.
|
||||
|
||||
### Running the tests
|
||||
|
||||
When you are done making the required changes, you must run the tests to ensure you didn't break anything. We use Detox as the testing framework & the tests can be started as follows:
|
||||
- Android emulator: `Pixel_5_API_36`
|
||||
- iOS simulator: `iPhone 17 Pro Max`
|
||||
|
||||
### Android
|
||||
|
||||
To run the tests on Android, you will need to create an emulator device on your system:
|
||||
Build and run Android Detox tests:
|
||||
|
||||
```
|
||||
$ANDROID_HOME/tools/bin/avdmanager create avd -n Pixel_5_API_31 -d pixel --package "system-images;android-31;default;x86_64"
|
||||
```
|
||||
|
||||
If you face problems, follow the detailed guide in [Detox documentation](https://wix.github.io/Detox/docs/introduction/android-dev-env). Keep the emulator name set to `Pixel_5_API_31`.
|
||||
|
||||
Once you have created an emulator device, build the Android apks:
|
||||
|
||||
```
|
||||
```bash
|
||||
npm run build:android
|
||||
```
|
||||
|
||||
Finally, run the tests:
|
||||
|
||||
```
|
||||
npm run test:android
|
||||
```
|
||||
|
||||
For debug configuration:
|
||||
|
||||
```bash
|
||||
npm run build:android:debug
|
||||
npm run start:metro
|
||||
npm run test:android:debug
|
||||
```
|
||||
|
||||
### iOS
|
||||
|
||||
To run e2e tests on the iOS simulator, you must be on a Mac with XCode installed.
|
||||
|
||||
First, install [AppleSimulatorUtils](https://github.com/wix/AppleSimulatorUtils):
|
||||
Build and run iOS Detox tests:
|
||||
|
||||
```bash
|
||||
npm run build:ios
|
||||
npm run test:ios
|
||||
```
|
||||
|
||||
If simulator tooling is missing, install [AppleSimulatorUtils](https://github.com/wix/AppleSimulatorUtils):
|
||||
|
||||
```bash
|
||||
brew tap wix/brew
|
||||
brew install applesimutils
|
||||
```
|
||||
|
||||
Now build the iOS app for testing:
|
||||
## Release commands
|
||||
|
||||
```
|
||||
npm run build:ios
|
||||
```
|
||||
|
||||
Finally, run the tests:
|
||||
Android release helpers:
|
||||
|
||||
```bash
|
||||
npm run release:android
|
||||
npm run release:android:bundle
|
||||
```
|
||||
npm run test:ios
|
||||
```
|
||||
|
||||
All tests on iOS are configured to run on `iPhone 8` simulator.
|
||||
|
||||
@@ -5,6 +5,7 @@ apply plugin: 'kotlin-parcelize'
|
||||
|
||||
apply from: project(':react-native-config').projectDir.getPath() + "/dotenv.gradle"
|
||||
|
||||
|
||||
import com.android.build.OutputFile
|
||||
import groovy.json.JsonSlurper
|
||||
import org.apache.tools.ant.taskdefs.condition.Os
|
||||
@@ -94,6 +95,18 @@ def fdroidBuild() {
|
||||
return project.hasProperty("fdroidBuild") && project.fdroidBuild == "true"
|
||||
}
|
||||
|
||||
def prBuildNumber() {
|
||||
def value = project.getProperties().get("prBuildNumber")
|
||||
return value ? value : "1000"
|
||||
}
|
||||
|
||||
def stagingReleaseBuild() {
|
||||
// Enable with STAGING_BUILDtrue or -PstagingReleaseBuild=true
|
||||
def fromEnv = System.getenv("STAGING_BUILD") == "true"
|
||||
def fromProp = project.hasProperty("stagingReleaseBuild") && project.stagingReleaseBuild == "true"
|
||||
return fromEnv || fromProp
|
||||
}
|
||||
|
||||
def getNpmVersion() {
|
||||
def inputFile = file("$rootDir/../package.json")
|
||||
def jsonPackage = new JsonSlurper().parseText(inputFile.text)
|
||||
@@ -118,14 +131,17 @@ android {
|
||||
sourceCompatibility JavaVersion.VERSION_1_8
|
||||
targetCompatibility JavaVersion.VERSION_1_8
|
||||
}
|
||||
|
||||
namespace "com.streetwriters.notesnook"
|
||||
defaultConfig {
|
||||
applicationId "com.streetwriters.notesnook"
|
||||
minSdkVersion rootProject.ext.minSdkVersion
|
||||
targetSdkVersion rootProject.ext.targetSdkVersion
|
||||
multiDexEnabled true
|
||||
versionCode 3093
|
||||
if (project.hasProperty("prBuildNumber")) {
|
||||
versionCode Integer.parseInt(prBuildNumber())
|
||||
} else {
|
||||
versionCode 3100
|
||||
}
|
||||
versionName getNpmVersion()
|
||||
testBuildType System.getProperty('testBuildType', 'debug')
|
||||
testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
|
||||
@@ -192,6 +208,8 @@ android {
|
||||
output.versionCodeOverride =
|
||||
defaultConfig.versionCode * 5 + versionCodes.get(abi)
|
||||
println("Fdroid Version code: ${output.versionCodeOverride} for abi ${versionCodes.get(abi)}");
|
||||
} else if (stagingReleaseBuild()) {
|
||||
output.versionCodeOverride = defaultConfig.versionCode + versionCodes.get(abi)
|
||||
} else {
|
||||
if (isBuildingAAB) {
|
||||
output.versionCodeOverride = 4 * 1048576 + defaultConfig.versionCode
|
||||
@@ -233,7 +251,6 @@ dependencies {
|
||||
} else {
|
||||
implementation jscFlavor
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -155,6 +155,15 @@
|
||||
<data android:scheme="notesnook" />
|
||||
</intent-filter>
|
||||
|
||||
<intent-filter android:label="Notesnook">
|
||||
<action android:name="android.intent.action.VIEW" />
|
||||
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
<category android:name="android.intent.category.BROWSABLE" />
|
||||
|
||||
<data android:scheme="nn" />
|
||||
</intent-filter>
|
||||
|
||||
</activity>
|
||||
<activity
|
||||
android:name="com.facebook.react.devsupport.DevSettingsActivity"
|
||||
@@ -199,11 +208,7 @@
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<service
|
||||
android:name=".OnClearFromRecentService"
|
||||
android:enabled="true"
|
||||
android:exported="true"
|
||||
android:stopWithTask="false" />
|
||||
|
||||
<service android:name="com.asterinet.react.bgactions.RNBackgroundActionsTask" />
|
||||
|
||||
<service
|
||||
|
||||
@@ -39,28 +39,32 @@ public class BootTaskService extends HeadlessJsTaskService {
|
||||
|
||||
@Override
|
||||
public int onStartCommand(Intent intent, int flags, int startId) {
|
||||
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
|
||||
NotificationChannel channel = new NotificationChannel("com.streetwriters.notesnook",
|
||||
"Default",
|
||||
NotificationManager.IMPORTANCE_DEFAULT);
|
||||
try {
|
||||
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
|
||||
NotificationChannel channel = new NotificationChannel("com.streetwriters.notesnook",
|
||||
"Default",
|
||||
NotificationManager.IMPORTANCE_DEFAULT);
|
||||
|
||||
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);
|
||||
notification = new NotificationCompat.Builder(this, channel.getId())
|
||||
.setContentTitle("Sync on boot")
|
||||
.setContentText("")
|
||||
.setSmallIcon(R.drawable.ic_stat_name)
|
||||
.build();
|
||||
if (android.os.Build.VERSION.SDK_INT >= 34) {
|
||||
this.startForeground(
|
||||
1,
|
||||
notification,
|
||||
ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE);
|
||||
} else {
|
||||
this.startForeground(
|
||||
1,
|
||||
notification);
|
||||
}
|
||||
|
||||
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);
|
||||
notification = new NotificationCompat.Builder(this, channel.getId())
|
||||
.setContentTitle("Sync on boot")
|
||||
.setContentText("")
|
||||
.setSmallIcon(R.drawable.ic_stat_name)
|
||||
.build();
|
||||
if (android.os.Build.VERSION.SDK_INT >= 34) {
|
||||
this.startForeground(
|
||||
1,
|
||||
notification,
|
||||
ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE);
|
||||
} else {
|
||||
this.startForeground(
|
||||
1,
|
||||
notification);
|
||||
}
|
||||
|
||||
} catch (Exception ignored) {
|
||||
stopSelf(startId);
|
||||
}
|
||||
|
||||
return super.onStartCommand(intent, flags, startId);
|
||||
|
||||
@@ -28,10 +28,6 @@ public class MainActivity extends ReactActivity {
|
||||
WebView.setWebContentsDebuggingEnabled(true);
|
||||
}
|
||||
|
||||
try {
|
||||
startService(new Intent(getBaseContext(), OnClearFromRecentService.class));
|
||||
} catch (Exception ignored) {}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -33,7 +33,7 @@ public class NotePreviewWidget extends AppWidgetProvider {
|
||||
intent.putExtra(OpenNoteId, note.getId());
|
||||
intent.setAction(Intent.ACTION_VIEW);
|
||||
intent.putExtra(RCTNNativeModule.IntentType, "OpenNote");
|
||||
intent.setData(Uri.parse("https://app.notesnook.com/open_note?id=" + note.getId()));
|
||||
intent.setData(Uri.parse("nn://note/" + note.getId()));
|
||||
PendingIntent pendingIntent = PendingIntent.getActivity(context, appWidgetId, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE, getActivityOptionsBundle());
|
||||
views.setOnClickPendingIntent(R.id.open_note, pendingIntent);
|
||||
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
package com.streetwriters.notesnook;
|
||||
import android.app.Service;
|
||||
import android.content.Intent;
|
||||
import android.content.SharedPreferences;
|
||||
import android.os.IBinder;
|
||||
import android.util.Log;
|
||||
|
||||
public class OnClearFromRecentService extends Service {
|
||||
|
||||
@Override
|
||||
public IBinder onBind(Intent intent) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int onStartCommand(Intent intent, int flags, int startId) {
|
||||
return START_NOT_STICKY;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDestroy() {
|
||||
super.onDestroy();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onTaskRemoved(Intent rootIntent) {
|
||||
try {
|
||||
SharedPreferences appStateDetails = getApplicationContext().getSharedPreferences("appStateDetails", MODE_PRIVATE);
|
||||
SharedPreferences.Editor edit = appStateDetails.edit();
|
||||
edit.remove("appState");
|
||||
edit.apply();
|
||||
stopSelf();
|
||||
} catch (UnsatisfiedLinkError | Exception e) {
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -93,21 +93,6 @@ public class RCTNNativeModule extends ReactContextBaseJavaModule {
|
||||
}
|
||||
}
|
||||
|
||||
@ReactMethod
|
||||
public void setAppState(final String appState) {
|
||||
SharedPreferences appStateDetails = getReactApplicationContext().getSharedPreferences("appStateDetails", Context.MODE_PRIVATE);
|
||||
SharedPreferences.Editor edit = appStateDetails.edit();
|
||||
edit.putString("appState", appState);
|
||||
edit.apply();
|
||||
}
|
||||
|
||||
@ReactMethod(isBlockingSynchronousMethod = true)
|
||||
public String getAppState() {
|
||||
SharedPreferences appStateDetails = getReactApplicationContext().getSharedPreferences("appStateDetails", Context.MODE_PRIVATE);
|
||||
String appStateValue = appStateDetails.getString("appState", "");
|
||||
return appStateValue.isEmpty() ? null : appStateValue;
|
||||
}
|
||||
|
||||
@ReactMethod(isBlockingSynchronousMethod = true)
|
||||
public int getWidgetId() {
|
||||
return NotePreviewConfigureActivity.appWidgetId;
|
||||
@@ -259,7 +244,7 @@ public class RCTNNativeModule extends ReactContextBaseJavaModule {
|
||||
return;
|
||||
}
|
||||
|
||||
String uri = "https://app.notesnook.com/open_" + type + "?id=" + id;
|
||||
String uri = "nn://" + type + "/" + id;
|
||||
Intent intent = new Intent(Intent.ACTION_VIEW, android.net.Uri.parse(uri));
|
||||
intent.setPackage(mContext.getPackageName());
|
||||
|
||||
|
||||
@@ -4,4 +4,10 @@
|
||||
<domain includeSubdomains="true">10.0.2.2</domain>
|
||||
<domain includeSubdomains="true">localhost</domain>
|
||||
</domain-config>
|
||||
<base-config>
|
||||
<trust-anchors>
|
||||
<certificates src="system" />
|
||||
<certificates src="user" />
|
||||
</trust-anchors>
|
||||
</base-config>
|
||||
</network-security-config>
|
||||
@@ -36,6 +36,8 @@ allprojects {
|
||||
url "$rootDir/../node_modules/detox/Detox-android"
|
||||
}
|
||||
|
||||
google()
|
||||
mavenCentral()
|
||||
maven { url 'https://www.jitpack.io' }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
- Bug fixes and minor improvements
|
||||
- Inbox API is now in beta. Learn more about it at https://help.notesnook.com/inbox-api/getting-started
|
||||
- Added close all tabs button in editor
|
||||
- Deeplinking support for nn:// urls
|
||||
- Set default image compression mode in Settings -> Behavior
|
||||
- Minor bug fixes and performance improvements
|
||||
|
||||
Thank you for using Notesnook!
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
{
|
||||
"name": "Notesnook",
|
||||
"displayName": "Notesnook"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -127,8 +127,12 @@ export const withTheme = (Element: (props: any) => JSX.Element) => {
|
||||
.then((theme) => {
|
||||
if (theme) {
|
||||
theme.colorScheme === "dark"
|
||||
? useThemeStore.getState().setDarkTheme(theme)
|
||||
: useThemeStore.getState().setLightTheme(theme);
|
||||
? useThemeStore.setState({
|
||||
darkTheme: theme
|
||||
})
|
||||
: useThemeStore.setState({
|
||||
lightTheme: theme
|
||||
});
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
@@ -138,9 +142,9 @@ export const withTheme = (Element: (props: any) => JSX.Element) => {
|
||||
|
||||
const listener = Appearance.addChangeListener(({ colorScheme }) => {
|
||||
if (colorScheme && SettingsService.getProperty("useSystemTheme")) {
|
||||
useThemeStore
|
||||
.getState()
|
||||
.setColorScheme(colorScheme as "light" | "dark");
|
||||
useThemeStore.setState({
|
||||
colorScheme: colorScheme as "light" | "dark"
|
||||
});
|
||||
}
|
||||
});
|
||||
return () => {
|
||||
|
||||
@@ -205,8 +205,9 @@ export async function getDatabaseKey(appLockPassword?: string) {
|
||||
}
|
||||
|
||||
if (await Keychain.hasInternetCredentials("notesnook")) {
|
||||
const userKeyCredentials =
|
||||
await Keychain.getInternetCredentials("notesnook");
|
||||
const userKeyCredentials = await Keychain.getInternetCredentials(
|
||||
"notesnook"
|
||||
);
|
||||
|
||||
if (userKeyCredentials) {
|
||||
const userKeyCipher: Cipher = (await encrypt(
|
||||
|
||||
@@ -72,7 +72,7 @@ export async function setupDatabase(password?: string) {
|
||||
({
|
||||
compress: Gzip.deflate,
|
||||
decompress: Gzip.inflate
|
||||
}) as ICompressor,
|
||||
} as ICompressor),
|
||||
batchSize: 50,
|
||||
sqliteOptions: {
|
||||
dialect: (name) => ({
|
||||
|
||||
@@ -31,6 +31,7 @@ import {
|
||||
generateCryptoKeyFallback
|
||||
} from "./encryption";
|
||||
import { MMKV } from "./mmkv";
|
||||
import OpenPGP from "react-native-fast-openpgp";
|
||||
|
||||
export class KV {
|
||||
storage: MMKVInstance;
|
||||
@@ -136,11 +137,30 @@ export const Storage: IStorage = {
|
||||
clear(): Promise<void> {
|
||||
return DefaultStorage.clear();
|
||||
},
|
||||
generateCryptoKeyPair() {
|
||||
throw new Error("Not implemented");
|
||||
async generatePGPKeyPair() {
|
||||
const keys = await OpenPGP.generate({
|
||||
name: "NN",
|
||||
email: "NN@NN.NN"
|
||||
});
|
||||
return { publicKey: keys.publicKey, privateKey: keys.privateKey };
|
||||
},
|
||||
decryptAsymmetric() {
|
||||
throw new Error("Not implemented");
|
||||
async validatePGPKeyPair(keys) {
|
||||
try {
|
||||
const dummyData = JSON.stringify({
|
||||
favorite: true,
|
||||
title: "Hello world"
|
||||
});
|
||||
const encrypted = await OpenPGP.encrypt(dummyData, keys.publicKey);
|
||||
const decrypted = await OpenPGP.decrypt(encrypted, keys.privateKey, "");
|
||||
|
||||
return decrypted === dummyData;
|
||||
} catch (e) {
|
||||
console.error("PGP key pair validation error:", e);
|
||||
return false;
|
||||
}
|
||||
},
|
||||
async decryptPGPMessage(privateKeyArmored, encryptedMessage) {
|
||||
return await OpenPGP.decrypt(encryptedMessage, privateKeyArmored, "");
|
||||
},
|
||||
getAllKeys(): Promise<string[]> {
|
||||
return DefaultStorage.getAllKeys();
|
||||
|
||||
@@ -30,7 +30,8 @@ import {
|
||||
getCacheSize,
|
||||
hashBase64,
|
||||
readEncrypted,
|
||||
writeEncryptedBase64
|
||||
writeEncryptedBase64,
|
||||
bulkDeleteFiles
|
||||
} from "./io";
|
||||
import { uploadFile } from "./upload";
|
||||
import {
|
||||
@@ -61,5 +62,6 @@ export const FileStorage: IFileStorage = {
|
||||
exists,
|
||||
clearFileStorage,
|
||||
getUploadedFileSize,
|
||||
bulkExists
|
||||
bulkExists,
|
||||
bulkDeleteFiles
|
||||
};
|
||||
|
||||
@@ -30,7 +30,14 @@ import RNFetchBlob from "react-native-blob-util";
|
||||
import { eSendEvent } from "../../services/event-manager";
|
||||
import { IOS_APPGROUPID } from "../../utils/constants";
|
||||
import { DatabaseLogger, db } from "../database";
|
||||
import { ABYTES, cacheDir, cacheDirOld, getRandomId } from "./utils";
|
||||
import {
|
||||
ABYTES,
|
||||
cacheDir,
|
||||
cacheDirOld,
|
||||
getRandomId,
|
||||
isSuccessStatusCode,
|
||||
parseS3Error
|
||||
} from "./utils";
|
||||
|
||||
export async function readEncrypted<TOutputFormat extends DataFormat>(
|
||||
filename: string,
|
||||
@@ -102,16 +109,41 @@ export async function writeEncryptedBase64(
|
||||
};
|
||||
}
|
||||
|
||||
async function deleteLocalFile(filename: string) {
|
||||
try {
|
||||
await createCacheDir();
|
||||
let path = cacheDir + `/${filename}`;
|
||||
let exists = await RNFetchBlob.fs.exists(path);
|
||||
if (Platform.OS === "ios" && !exists) {
|
||||
const iosAppGroup =
|
||||
Platform.OS === "ios"
|
||||
? await (RNFetchBlob.fs as any).pathForAppGroup(IOS_APPGROUPID)
|
||||
: null;
|
||||
const appGroupPath = `${iosAppGroup}/${filename}`;
|
||||
if (await RNFetchBlob.fs.exists(appGroupPath)) {
|
||||
RNFetchBlob.fs.unlink(appGroupPath).catch(() => {
|
||||
/* empty */
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (exists) {
|
||||
RNFetchBlob.fs.unlink(path).catch(() => {
|
||||
/* empty */
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
DatabaseLogger.error(e as Error, "deleteLocalFile");
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteFile(
|
||||
filename: string,
|
||||
requestOptions?: RequestOptions
|
||||
): Promise<boolean> {
|
||||
await createCacheDir();
|
||||
const localFilePath = cacheDir + `/${filename}`;
|
||||
if (!requestOptions) {
|
||||
RNFetchBlob.fs.unlink(localFilePath).catch(() => {
|
||||
/* empty */
|
||||
});
|
||||
deleteLocalFile(filename);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -122,9 +154,7 @@ export async function deleteFile(
|
||||
const status = response.info().status;
|
||||
const ok = status >= 200 && status < 300;
|
||||
if (ok) {
|
||||
RNFetchBlob.fs.unlink(localFilePath).catch(() => {
|
||||
/* empty */
|
||||
});
|
||||
deleteLocalFile(filename);
|
||||
}
|
||||
return ok;
|
||||
} catch (e) {
|
||||
@@ -135,6 +165,49 @@ export async function deleteFile(
|
||||
}
|
||||
}
|
||||
|
||||
export async function bulkDeleteFiles(
|
||||
filenames: string[],
|
||||
requestOptions?: RequestOptions
|
||||
) {
|
||||
await createCacheDir();
|
||||
if (!requestOptions) {
|
||||
filenames.forEach((filename) => {
|
||||
deleteLocalFile(filename);
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
try {
|
||||
const { url, headers } = requestOptions;
|
||||
const response = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
...headers,
|
||||
"Content-Type": "application/json"
|
||||
},
|
||||
body: JSON.stringify({
|
||||
names: filenames
|
||||
})
|
||||
});
|
||||
|
||||
const result = isSuccessStatusCode(response.status);
|
||||
if (result) {
|
||||
filenames.forEach((filename) => {
|
||||
deleteLocalFile(filename);
|
||||
});
|
||||
} else {
|
||||
throw await response.text();
|
||||
}
|
||||
return result;
|
||||
} catch (e) {
|
||||
DatabaseLogger.error(
|
||||
typeof e === "string" ? parseS3Error(e as string) : (e as Error),
|
||||
"Could not bulk delete files"
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export async function clearFileStorage() {
|
||||
try {
|
||||
await createCacheDir();
|
||||
|
||||
@@ -33,6 +33,10 @@ import {
|
||||
} from "./utils";
|
||||
import Upload from "@ammarahmed/react-native-upload";
|
||||
import { CloudUploader } from "react-native-nitro-cloud-uploader";
|
||||
import { useUserStore } from "../../stores/use-user-store";
|
||||
import { sleep } from "../../utils/time";
|
||||
import { isFeatureAvailable } from "@notesnook/common";
|
||||
import { strings } from "@notesnook/intl";
|
||||
|
||||
// Upload constants
|
||||
const CHUNK_SIZE = 10 * 1024 * 1024; // 10 MB
|
||||
@@ -197,6 +201,20 @@ export async function uploadFile(
|
||||
const remoteFileSize = await getUploadedFileSize(filename);
|
||||
if (remoteFileSize === FileSizeResult.Error) return false;
|
||||
|
||||
const featureResult = await isFeatureAvailable(
|
||||
"fileSize",
|
||||
fileInfo.size || 0
|
||||
);
|
||||
|
||||
if (!featureResult.isAllowed) {
|
||||
ToastManager.show({
|
||||
heading: strings.fileTooLarge(),
|
||||
message: featureResult.error,
|
||||
type: "error"
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
if (
|
||||
remoteFileSize > FileSizeResult.Empty &&
|
||||
remoteFileSize === fileInfo.size
|
||||
@@ -212,6 +230,9 @@ export async function uploadFile(
|
||||
);
|
||||
|
||||
if (Platform.OS === "android") {
|
||||
useUserStore.setState({
|
||||
disableAppLockRequests: true
|
||||
});
|
||||
const status = await PermissionsAndroid.request(
|
||||
"android.permission.POST_NOTIFICATIONS"
|
||||
);
|
||||
@@ -221,6 +242,10 @@ export async function uploadFile(
|
||||
type: "info"
|
||||
});
|
||||
}
|
||||
await sleep(500);
|
||||
useUserStore.setState({
|
||||
disableAppLockRequests: false
|
||||
});
|
||||
}
|
||||
|
||||
let uploaded = false;
|
||||
|
||||
@@ -161,10 +161,10 @@ export async function checkUpload(
|
||||
size === 0
|
||||
? `File size is 0.`
|
||||
: size === -1
|
||||
? `File verification check failed.`
|
||||
: expectedSize !== decryptedLength
|
||||
? `File size mismatch. Expected ${size} bytes but got ${decryptedLength} bytes.`
|
||||
: undefined;
|
||||
? `File verification check failed.`
|
||||
: expectedSize !== decryptedLength
|
||||
? `File size mismatch. Expected ${size} bytes but got ${decryptedLength} bytes.`
|
||||
: undefined;
|
||||
if (error) throw new Error(error);
|
||||
}
|
||||
|
||||
@@ -193,3 +193,7 @@ export async function checkAndCreateDir(path: string) {
|
||||
export const santizeUri = (uri: string) => {
|
||||
return Platform.OS === "ios" ? decodeURI(uri).replace("file:///", "/") : uri;
|
||||
};
|
||||
|
||||
export function isSuccessStatusCode(statusCode: number) {
|
||||
return statusCode >= 200 && statusCode <= 299;
|
||||
}
|
||||
|
||||
@@ -239,8 +239,8 @@ const AppLocked = () => {
|
||||
deviceMode !== "mobile"
|
||||
? "50%"
|
||||
: Platform.OS == "ios"
|
||||
? "95%"
|
||||
: "100%",
|
||||
? "95%"
|
||||
: "100%",
|
||||
paddingHorizontal: 12,
|
||||
marginBottom: 30,
|
||||
marginTop: 15,
|
||||
|
||||
@@ -59,6 +59,7 @@ import Heading from "../ui/typography/heading";
|
||||
import Paragraph from "../ui/typography/paragraph";
|
||||
import { strings } from "@notesnook/intl";
|
||||
import { DefaultAppStyles } from "../../utils/styles";
|
||||
import Navigation from "../../services/navigation";
|
||||
|
||||
const Actions = ({
|
||||
attachment,
|
||||
@@ -304,9 +305,9 @@ const Actions = ({
|
||||
<Pressable
|
||||
onPress={async () => {
|
||||
eSendEvent(eCloseSheet, contextId);
|
||||
await sleep(150);
|
||||
close?.();
|
||||
eSendEvent(eCloseAttachmentDialog);
|
||||
await sleep(300);
|
||||
Navigation.navigate("FluidPanelsView");
|
||||
openNote(item, (item as any).type === "trash");
|
||||
}}
|
||||
style={{
|
||||
|
||||
@@ -28,7 +28,7 @@ import {
|
||||
import { strings } from "@notesnook/intl";
|
||||
import { useThemeColors } from "@notesnook/theme";
|
||||
import React, { useEffect, useRef, useState } from "react";
|
||||
import { ActivityIndicator, View } from "react-native";
|
||||
import { ActivityIndicator, FlatList, View } from "react-native";
|
||||
import { ScrollView } from "react-native-actions-sheet";
|
||||
import Icon from "react-native-vector-icons/MaterialCommunityIcons";
|
||||
import create from "zustand";
|
||||
@@ -313,6 +313,10 @@ export const AttachmentDialog = ({
|
||||
});
|
||||
};
|
||||
|
||||
db.attachments.orphaned.items().then((r) => {
|
||||
console.log(r);
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
{isSheet ? (
|
||||
@@ -509,7 +513,7 @@ export const AttachmentDialog = ({
|
||||
</ScrollView>
|
||||
</View>
|
||||
|
||||
<LegendList
|
||||
<FlatList
|
||||
renderScrollComponent={(props) => <ScrollView {...props} />}
|
||||
keyboardDismissMode="none"
|
||||
keyboardShouldPersistTaps="always"
|
||||
@@ -543,7 +547,6 @@ export const AttachmentDialog = ({
|
||||
}}
|
||||
/>
|
||||
}
|
||||
estimatedItemSize={50}
|
||||
data={loading ? [] : attachments?.placeholders || []}
|
||||
extraData={attachments}
|
||||
renderItem={renderItem}
|
||||
|
||||
@@ -195,8 +195,8 @@ export const Login = ({
|
||||
? "50%"
|
||||
: "49.99%"
|
||||
: focused
|
||||
? "100%"
|
||||
: "99.9%",
|
||||
? "100%"
|
||||
: "99.9%",
|
||||
backgroundColor: colors.primary.background,
|
||||
alignSelf: "center",
|
||||
paddingHorizontal: DDS.isTab ? 0 : DefaultAppStyles.GAP,
|
||||
|
||||
@@ -161,10 +161,10 @@ const FloatingButton = ({
|
||||
icon
|
||||
? icon
|
||||
: route.name === "Notebooks"
|
||||
? "notebook-plus"
|
||||
: route.name === "Trash"
|
||||
? "delete"
|
||||
: "plus"
|
||||
? "notebook-plus"
|
||||
: route.name === "Trash"
|
||||
? "delete"
|
||||
: "plus"
|
||||
}
|
||||
color={color || colors.primary.accent}
|
||||
size={size === "small" ? AppFontSize.xl : AppFontSize.xxxl}
|
||||
|
||||
@@ -136,8 +136,8 @@ const BaseDialog = ({
|
||||
backgroundColor: background
|
||||
? background
|
||||
: transparent
|
||||
? "transparent"
|
||||
: "rgba(0,0,0,0.3)"
|
||||
? "transparent"
|
||||
: "rgba(0,0,0,0.3)"
|
||||
}}
|
||||
>
|
||||
<KeyboardAvoidingView
|
||||
@@ -155,8 +155,8 @@ const BaseDialog = ({
|
||||
justifyContent: centered
|
||||
? "center"
|
||||
: bottom
|
||||
? "flex-end"
|
||||
: "flex-start"
|
||||
? "flex-end"
|
||||
: "flex-start"
|
||||
}
|
||||
]}
|
||||
>
|
||||
|
||||
@@ -201,14 +201,12 @@ export const AppLockPassword = () => {
|
||||
accountPass
|
||||
? strings.enterAccountPassword()
|
||||
: mode === "change"
|
||||
? keyboardType === "pin"
|
||||
? strings.newPin()
|
||||
: strings.newPassword()
|
||||
: `${
|
||||
keyboardType === "pin"
|
||||
? strings.pin()
|
||||
: strings.password()
|
||||
}`
|
||||
? keyboardType === "pin"
|
||||
? strings.newPin()
|
||||
: strings.newPassword()
|
||||
: `${
|
||||
keyboardType === "pin" ? strings.pin() : strings.password()
|
||||
}`
|
||||
}
|
||||
/>
|
||||
|
||||
@@ -385,8 +383,8 @@ export const AppLockPassword = () => {
|
||||
mode === "remove"
|
||||
? strings.remove()
|
||||
: mode === "change"
|
||||
? strings.change()
|
||||
: strings.save()
|
||||
? strings.change()
|
||||
: strings.save()
|
||||
}
|
||||
negativeTitle={strings.cancel()}
|
||||
positiveType="transparent"
|
||||
|
||||
@@ -35,6 +35,7 @@ import { Button } from "../../ui/button";
|
||||
import { IconButton } from "../../ui/icon-button";
|
||||
import { Notice } from "../../ui/notice";
|
||||
import Paragraph from "../../ui/typography/paragraph";
|
||||
import SettingsService from "../../../services/settings";
|
||||
|
||||
export default function AttachImage({
|
||||
response,
|
||||
@@ -201,6 +202,17 @@ AttachImage.present = (response: ImageType[], context?: string) => {
|
||||
| undefined
|
||||
>((resolve) => {
|
||||
let resolved = false;
|
||||
|
||||
const imageCompressionSetting =
|
||||
SettingsService.getProperty("imageCompression");
|
||||
|
||||
if (imageCompressionSetting !== "ask-every-time") {
|
||||
resolve({
|
||||
compress: imageCompressionSetting === "enabled" ? true : false
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
presentSheet({
|
||||
context: context,
|
||||
component: (ref, close, update) => (
|
||||
|
||||
@@ -28,6 +28,7 @@ import { DDS } from "../../../services/device-detection";
|
||||
import {
|
||||
ToastManager,
|
||||
Vault,
|
||||
VaultRequestType,
|
||||
eSendEvent,
|
||||
eSubscribeEvent,
|
||||
eUnSubscribeEvent
|
||||
@@ -55,151 +56,119 @@ import Seperator from "../../ui/seperator";
|
||||
import Paragraph from "../../ui/typography/paragraph";
|
||||
import { strings } from "@notesnook/intl";
|
||||
import { DefaultAppStyles } from "../../../utils/styles";
|
||||
import { Note, NoteContent, VAULT_ERRORS } from "@notesnook/core";
|
||||
import {
|
||||
isEncryptedContent,
|
||||
Note,
|
||||
NoteContent,
|
||||
VAULT_ERRORS
|
||||
} from "@notesnook/core";
|
||||
import { useThemeColors } from "@notesnook/theme";
|
||||
|
||||
type VaultDialogData = {
|
||||
item: Note;
|
||||
} & Partial<Omit<Vault, "item">>;
|
||||
|
||||
interface VaultDialogState {
|
||||
visible: boolean;
|
||||
wrongPassword: boolean;
|
||||
loading: boolean;
|
||||
note?: Note;
|
||||
vault: boolean;
|
||||
locked: boolean;
|
||||
permanant: boolean;
|
||||
goToEditor: boolean;
|
||||
share: boolean;
|
||||
passwordsDontMatch: boolean;
|
||||
deleteNote: boolean;
|
||||
focusIndex: number | null;
|
||||
biometricUnlock: boolean;
|
||||
isBiometryEnrolled: boolean;
|
||||
isBiometryAvailable: boolean;
|
||||
fingerprintAccess: boolean;
|
||||
changePassword: boolean;
|
||||
copyNote: boolean;
|
||||
revokeFingerprintAccess: boolean;
|
||||
title: string;
|
||||
description: string | null;
|
||||
clearVault: boolean;
|
||||
deleteVault: boolean;
|
||||
deleteAll: boolean;
|
||||
noteLocked: boolean;
|
||||
novault: boolean;
|
||||
customActionTitle: string | null;
|
||||
customActionParagraph: string | null;
|
||||
customAction: boolean;
|
||||
onUnlock?: (
|
||||
item: Note & {
|
||||
content?: NoteContent<false>;
|
||||
},
|
||||
password: string
|
||||
) => void;
|
||||
}
|
||||
|
||||
export const VaultDialog: React.FC = () => {
|
||||
const { colors } = useThemeColors();
|
||||
|
||||
const [state, setState] = useState<VaultDialogState>({
|
||||
visible: false,
|
||||
wrongPassword: false,
|
||||
loading: false,
|
||||
note: undefined,
|
||||
vault: false,
|
||||
locked: true,
|
||||
permanant: false,
|
||||
goToEditor: false,
|
||||
share: false,
|
||||
passwordsDontMatch: false,
|
||||
deleteNote: false,
|
||||
focusIndex: null,
|
||||
biometricUnlock: false,
|
||||
isBiometryEnrolled: false,
|
||||
isBiometryAvailable: false,
|
||||
fingerprintAccess: false,
|
||||
changePassword: false,
|
||||
copyNote: false,
|
||||
revokeFingerprintAccess: false,
|
||||
title: strings.goToEditor(),
|
||||
description: null,
|
||||
clearVault: false,
|
||||
deleteVault: false,
|
||||
deleteAll: false,
|
||||
noteLocked: false,
|
||||
novault: false,
|
||||
customActionTitle: null,
|
||||
customActionParagraph: null,
|
||||
customAction: false,
|
||||
onUnlock: undefined
|
||||
});
|
||||
// UI State
|
||||
const [visible, setVisible] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [wrongPassword, setWrongPassword] = useState(false);
|
||||
const [passwordsDontMatch, setPasswordsDontMatch] = useState(false);
|
||||
const [deleteAll, setDeleteAll] = useState(false);
|
||||
const [biometricUnlock, setBiometricUnlock] = useState(false);
|
||||
const [isBiometryAvailable, setIsBiometryAvailable] = useState(false);
|
||||
const [isBiometryEnrolled, setIsBiometryEnrolled] = useState(false);
|
||||
|
||||
// Refs for non-UI state
|
||||
const requestTypeRef = useRef<VaultRequestType | null>(null);
|
||||
const noteRef = useRef<Note | undefined>(undefined);
|
||||
const titleRef = useRef<string>(strings.goToEditor());
|
||||
const descriptionRef = useRef<string | null>(null);
|
||||
const paragraphRef = useRef<string | null>(null);
|
||||
const buttonTitleRef = useRef<string | null>(null);
|
||||
const positiveButtonTypeRef = useRef<"errorShade" | "transparent" | "accent">(
|
||||
"transparent"
|
||||
);
|
||||
const customActionTitleRef = useRef<string | null>(null);
|
||||
const customActionParagraphRef = useRef<string | null>(null);
|
||||
const noteLockedRef = useRef(false);
|
||||
const onUnlockRef = useRef<
|
||||
| ((
|
||||
item: Note & {
|
||||
content?: NoteContent<false>;
|
||||
},
|
||||
password: string
|
||||
) => void)
|
||||
| undefined
|
||||
>(undefined);
|
||||
|
||||
// Input refs
|
||||
const passInputRef = useRef<TextInput>(null);
|
||||
const confirmPassRef = useRef<TextInput>(null);
|
||||
const changePassInputRef = useRef<TextInput>(null);
|
||||
|
||||
// Password refs
|
||||
const passwordRef = useRef<string | null>(null);
|
||||
const confirmPasswordRef = useRef<string | null>(null);
|
||||
const newPasswordRef = useRef<string | null>(null);
|
||||
|
||||
const open = useCallback(async (data: VaultDialogData) => {
|
||||
const open = useCallback(async (data: Vault) => {
|
||||
const biometry = await BiometricService.isBiometryAvailable();
|
||||
const available = !!biometry;
|
||||
const fingerprint = await BiometricService.hasInternetCredentials();
|
||||
|
||||
const noteLocked = data.item
|
||||
? await db.vaults.itemExists(data.item)
|
||||
: false;
|
||||
if (data.item) {
|
||||
const locked = await db.vaults.itemExists(data.item);
|
||||
noteLockedRef.current = locked;
|
||||
if (!locked) {
|
||||
const content = await db.content.findByNoteId(data.item!.id);
|
||||
if (content && isEncryptedContent(content)) {
|
||||
noteLockedRef.current = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
note: data.item,
|
||||
novault: data.novault || false,
|
||||
locked: data.locked || false,
|
||||
permanant: data.permanant || false,
|
||||
goToEditor: data.goToEditor || false,
|
||||
share: data.share || false,
|
||||
deleteNote: data.deleteNote || false,
|
||||
copyNote: data.copyNote || false,
|
||||
isBiometryAvailable: available,
|
||||
biometricUnlock: fingerprint,
|
||||
isBiometryEnrolled: fingerprint,
|
||||
fingerprintAccess: data.fingerprintAccess || false,
|
||||
changePassword: data.changePassword || false,
|
||||
revokeFingerprintAccess: data.revokeFingerprintAccess || false,
|
||||
title: data.title || strings.goToEditor(),
|
||||
description: data.description || null,
|
||||
clearVault: data.clearVault || false,
|
||||
deleteVault: data.deleteVault || false,
|
||||
noteLocked,
|
||||
customActionTitle: data.customActionTitle || null,
|
||||
customActionParagraph: data.customActionParagraph || null,
|
||||
customAction: !!(data.customActionTitle && data.customActionParagraph),
|
||||
onUnlock: data.onUnlock
|
||||
}));
|
||||
// Set refs
|
||||
noteRef.current = data.item;
|
||||
titleRef.current = data.title || strings.goToEditor();
|
||||
descriptionRef.current = data.description || null;
|
||||
paragraphRef.current = data.paragraph || null;
|
||||
buttonTitleRef.current = data.buttonTitle || null;
|
||||
positiveButtonTypeRef.current = data.positiveButtonType || "transparent";
|
||||
customActionTitleRef.current = data.customActionTitle || null;
|
||||
customActionParagraphRef.current = data.customActionParagraph || null;
|
||||
onUnlockRef.current = data.onUnlock;
|
||||
requestTypeRef.current = data.requestType;
|
||||
|
||||
if (
|
||||
// Set UI state
|
||||
setIsBiometryAvailable(available);
|
||||
setIsBiometryEnrolled(fingerprint);
|
||||
setBiometricUnlock(fingerprint);
|
||||
setWrongPassword(false);
|
||||
setPasswordsDontMatch(false);
|
||||
setDeleteAll(false);
|
||||
setLoading(false);
|
||||
|
||||
// Auto-unlock with fingerprint if applicable
|
||||
const canAutoUnlock =
|
||||
fingerprint &&
|
||||
data.novault &&
|
||||
!data.fingerprintAccess &&
|
||||
!data.revokeFingerprintAccess &&
|
||||
!data.changePassword &&
|
||||
!data.clearVault &&
|
||||
!data.deleteVault &&
|
||||
!data.customActionTitle
|
||||
) {
|
||||
data.requestType !== VaultRequestType.EnableFingerprint &&
|
||||
data.requestType !== VaultRequestType.RevokeFingerprint &&
|
||||
data.requestType !== VaultRequestType.ChangePassword &&
|
||||
data.requestType !== VaultRequestType.ClearVault &&
|
||||
data.requestType !== VaultRequestType.DeleteVault &&
|
||||
data.requestType !== VaultRequestType.CustomAction &&
|
||||
data.requestType !== VaultRequestType.PermanentUnlock;
|
||||
|
||||
if (canAutoUnlock) {
|
||||
await onPressFingerprintAuth(data.title, data.description);
|
||||
} else {
|
||||
setState((prev) => ({ ...prev, visible: true }));
|
||||
setVisible(true);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const close = useCallback(() => {
|
||||
if (state.loading) {
|
||||
if (loading) {
|
||||
ToastManager.show({
|
||||
heading: state.title,
|
||||
heading: titleRef.current,
|
||||
message: strings.pleaseWait() + "...",
|
||||
type: "success",
|
||||
context: "local"
|
||||
@@ -209,46 +178,37 @@ export const VaultDialog: React.FC = () => {
|
||||
|
||||
Navigation.queueRoutesForUpdate();
|
||||
|
||||
// Reset password refs
|
||||
passwordRef.current = null;
|
||||
confirmPasswordRef.current = null;
|
||||
newPasswordRef.current = null;
|
||||
|
||||
setState({
|
||||
visible: false,
|
||||
wrongPassword: false,
|
||||
loading: false,
|
||||
note: undefined,
|
||||
vault: false,
|
||||
locked: false,
|
||||
permanant: false,
|
||||
goToEditor: false,
|
||||
share: false,
|
||||
passwordsDontMatch: false,
|
||||
deleteNote: false,
|
||||
focusIndex: null,
|
||||
biometricUnlock: false,
|
||||
isBiometryEnrolled: false,
|
||||
isBiometryAvailable: false,
|
||||
fingerprintAccess: false,
|
||||
changePassword: false,
|
||||
copyNote: false,
|
||||
revokeFingerprintAccess: false,
|
||||
title: strings.goToEditor(),
|
||||
description: null,
|
||||
clearVault: false,
|
||||
deleteVault: false,
|
||||
deleteAll: false,
|
||||
noteLocked: false,
|
||||
novault: false,
|
||||
customActionTitle: null,
|
||||
customActionParagraph: null,
|
||||
customAction: false,
|
||||
onUnlock: undefined
|
||||
});
|
||||
}, [state.loading, state.title]);
|
||||
// Reset refs
|
||||
requestTypeRef.current = null;
|
||||
noteRef.current = undefined;
|
||||
titleRef.current = strings.goToEditor();
|
||||
descriptionRef.current = null;
|
||||
paragraphRef.current = null;
|
||||
buttonTitleRef.current = null;
|
||||
positiveButtonTypeRef.current = "transparent";
|
||||
customActionTitleRef.current = null;
|
||||
customActionParagraphRef.current = null;
|
||||
noteLockedRef.current = false;
|
||||
onUnlockRef.current = undefined;
|
||||
|
||||
// Reset UI state
|
||||
setVisible(false);
|
||||
setLoading(false);
|
||||
setWrongPassword(false);
|
||||
setPasswordsDontMatch(false);
|
||||
setDeleteAll(false);
|
||||
setBiometricUnlock(false);
|
||||
setIsBiometryAvailable(false);
|
||||
setIsBiometryEnrolled(false);
|
||||
}, [loading]);
|
||||
|
||||
const deleteVault = useCallback(async () => {
|
||||
setState((prev) => ({ ...prev, loading: true }));
|
||||
setLoading(true);
|
||||
try {
|
||||
let verified = true;
|
||||
if (await db.user.getUser()) {
|
||||
@@ -256,7 +216,7 @@ export const VaultDialog: React.FC = () => {
|
||||
}
|
||||
if (verified) {
|
||||
let noteIds: string[] = [];
|
||||
if (state.deleteAll) {
|
||||
if (deleteAll) {
|
||||
const vault = await db.vaults.default();
|
||||
const relations = await db.relations
|
||||
.from(
|
||||
@@ -269,9 +229,9 @@ export const VaultDialog: React.FC = () => {
|
||||
.get();
|
||||
noteIds = relations.map((item) => item.toId);
|
||||
}
|
||||
await db.vault.delete(state.deleteAll);
|
||||
await db.vault.delete(deleteAll);
|
||||
|
||||
if (state.deleteAll) {
|
||||
if (deleteAll) {
|
||||
noteIds.forEach((id) => {
|
||||
eSendEvent(
|
||||
eUpdateNoteInEditor,
|
||||
@@ -284,7 +244,7 @@ export const VaultDialog: React.FC = () => {
|
||||
});
|
||||
}
|
||||
eSendEvent("vaultUpdated");
|
||||
setState((prev) => ({ ...prev, loading: false }));
|
||||
setLoading(false);
|
||||
setTimeout(() => {
|
||||
close();
|
||||
}, 100);
|
||||
@@ -298,10 +258,10 @@ export const VaultDialog: React.FC = () => {
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
}, [state.deleteAll, close]);
|
||||
}, [deleteAll, close]);
|
||||
|
||||
const clearVault = useCallback(async () => {
|
||||
setState((prev) => ({ ...prev, loading: true }));
|
||||
setLoading(true);
|
||||
try {
|
||||
const vault = await db.vaults.default();
|
||||
const relations = await db.relations.from(vault!, "note").get();
|
||||
@@ -319,7 +279,7 @@ export const VaultDialog: React.FC = () => {
|
||||
true
|
||||
);
|
||||
});
|
||||
setState((prev) => ({ ...prev, loading: false }));
|
||||
setLoading(false);
|
||||
close();
|
||||
eSendEvent("vaultUpdated");
|
||||
} catch (e) {
|
||||
@@ -329,7 +289,7 @@ export const VaultDialog: React.FC = () => {
|
||||
context: "local"
|
||||
});
|
||||
}
|
||||
setState((prev) => ({ ...prev, loading: false }));
|
||||
setLoading(false);
|
||||
}, [close]);
|
||||
|
||||
const lockNote = useCallback(async () => {
|
||||
@@ -341,9 +301,9 @@ export const VaultDialog: React.FC = () => {
|
||||
});
|
||||
return;
|
||||
} else {
|
||||
await db.vault.add(state.note!.id);
|
||||
await db.vault.add(noteRef.current!.id);
|
||||
|
||||
eSendEvent(eUpdateNoteInEditor, state.note, true);
|
||||
eSendEvent(eUpdateNoteInEditor, noteRef.current, true);
|
||||
|
||||
close();
|
||||
ToastManager.show({
|
||||
@@ -351,26 +311,29 @@ export const VaultDialog: React.FC = () => {
|
||||
type: "error",
|
||||
context: "local"
|
||||
});
|
||||
setState((prev) => ({ ...prev, loading: false }));
|
||||
setLoading(false);
|
||||
}
|
||||
}, [state.note, close]);
|
||||
}, [close]);
|
||||
|
||||
const permanantUnlock = useCallback(() => {
|
||||
db.vault
|
||||
.remove(state.note!.id, passwordRef.current || "")
|
||||
.then(() => {
|
||||
.remove(noteRef.current!.id, passwordRef.current || "")
|
||||
.then(async () => {
|
||||
ToastManager.show({
|
||||
heading: strings.noteUnlocked(),
|
||||
type: "success",
|
||||
context: "global"
|
||||
});
|
||||
eSendEvent(eUpdateNoteInEditor, state.note, true);
|
||||
eSendEvent(eUpdateNoteInEditor, noteRef.current, true);
|
||||
if (biometricUnlock && !isBiometryEnrolled) {
|
||||
await enrollFingerprint(passwordRef.current || "");
|
||||
}
|
||||
close();
|
||||
})
|
||||
.catch((e) => {
|
||||
takeErrorAction();
|
||||
});
|
||||
}, [state.note, close]);
|
||||
}, [close, biometricUnlock, isBiometryEnrolled]);
|
||||
|
||||
const openInEditor = useCallback(
|
||||
(note: Note & { content?: NoteContent<false> }) => {
|
||||
@@ -418,20 +381,17 @@ export const VaultDialog: React.FC = () => {
|
||||
|
||||
const deleteNote = useCallback(async () => {
|
||||
try {
|
||||
await db.vault.remove(state.note!.id, passwordRef.current || "");
|
||||
await deleteItems("note", [state.note!.id]);
|
||||
await db.vault.remove(noteRef.current!.id, passwordRef.current || "");
|
||||
await deleteItems("note", [noteRef.current!.id]);
|
||||
close();
|
||||
} catch (e) {
|
||||
takeErrorAction();
|
||||
}
|
||||
}, [state.note, close]);
|
||||
}, [close]);
|
||||
|
||||
const takeErrorAction = useCallback(() => {
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
wrongPassword: true,
|
||||
visible: true
|
||||
}));
|
||||
setWrongPassword(true);
|
||||
setVisible(true);
|
||||
setTimeout(() => {
|
||||
ToastManager.show({
|
||||
heading: strings.passwordIncorrect(),
|
||||
@@ -445,39 +405,41 @@ export const VaultDialog: React.FC = () => {
|
||||
try {
|
||||
if (!passwordRef.current) throw new Error("Invalid password");
|
||||
|
||||
const note = await db.vault.open(state.note!.id, passwordRef.current);
|
||||
const note = await db.vault.open(
|
||||
noteRef.current!.id,
|
||||
passwordRef.current
|
||||
);
|
||||
if (!note) throw new Error("Failed to unlock note.");
|
||||
if (state.biometricUnlock && !state.isBiometryEnrolled) {
|
||||
if (biometricUnlock && !isBiometryEnrolled) {
|
||||
await enrollFingerprint(passwordRef.current || "");
|
||||
}
|
||||
|
||||
if (state.goToEditor) {
|
||||
const requestType = requestTypeRef.current;
|
||||
|
||||
if (requestType === VaultRequestType.GoToEditor) {
|
||||
openInEditor(note);
|
||||
} else if (state.share) {
|
||||
} else if (requestType === VaultRequestType.ShareNote) {
|
||||
await shareNote(note);
|
||||
} else if (state.deleteNote) {
|
||||
} else if (requestType === VaultRequestType.DeleteNote) {
|
||||
await deleteNote();
|
||||
} else if (state.copyNote) {
|
||||
} else if (requestType === VaultRequestType.CopyNote) {
|
||||
await copyNote(note);
|
||||
} else if (state.customAction && state.onUnlock) {
|
||||
} else if (
|
||||
requestType === VaultRequestType.CustomAction &&
|
||||
onUnlockRef.current
|
||||
) {
|
||||
const password = passwordRef.current;
|
||||
const unlock = onUnlockRef.current;
|
||||
close();
|
||||
await sleep(300);
|
||||
state.onUnlock(note, password);
|
||||
await sleep(500);
|
||||
unlock(note, password);
|
||||
}
|
||||
} catch (e) {
|
||||
takeErrorAction();
|
||||
}
|
||||
}, [
|
||||
state.note,
|
||||
state.biometricUnlock,
|
||||
state.isBiometryEnrolled,
|
||||
state.goToEditor,
|
||||
state.share,
|
||||
state.deleteNote,
|
||||
state.copyNote,
|
||||
state.customAction,
|
||||
state.onUnlock,
|
||||
biometricUnlock,
|
||||
isBiometryEnrolled,
|
||||
openInEditor,
|
||||
shareNote,
|
||||
deleteNote,
|
||||
@@ -495,20 +457,20 @@ export const VaultDialog: React.FC = () => {
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (state.permanant) {
|
||||
if (requestTypeRef.current === VaultRequestType.PermanentUnlock) {
|
||||
permanantUnlock();
|
||||
} else {
|
||||
await openNote();
|
||||
}
|
||||
}, [state.permanant, permanantUnlock, openNote]);
|
||||
}, [permanantUnlock, openNote]);
|
||||
|
||||
const enrollFingerprint = useCallback(
|
||||
async (password: string) => {
|
||||
setState((prev) => ({ ...prev, loading: true }));
|
||||
setLoading(true);
|
||||
try {
|
||||
await db.vault.unlock(password);
|
||||
await BiometricService.storeCredentials(password);
|
||||
setState((prev) => ({ ...prev, loading: false }));
|
||||
setLoading(false);
|
||||
eSendEvent("vaultUpdated");
|
||||
ToastManager.show({
|
||||
heading: strings.biometricUnlockEnabled(),
|
||||
@@ -523,7 +485,7 @@ export const VaultDialog: React.FC = () => {
|
||||
type: "error",
|
||||
context: "local"
|
||||
});
|
||||
setState((prev) => ({ ...prev, loading: false }));
|
||||
setLoading(false);
|
||||
}
|
||||
},
|
||||
[close]
|
||||
@@ -532,13 +494,13 @@ export const VaultDialog: React.FC = () => {
|
||||
const createVault = useCallback(async () => {
|
||||
await db.vault.create(passwordRef.current || "");
|
||||
|
||||
if (state.biometricUnlock) {
|
||||
if (biometricUnlock) {
|
||||
await enrollFingerprint(passwordRef.current || "");
|
||||
}
|
||||
if (state.note?.id) {
|
||||
await db.vault.add(state.note.id);
|
||||
eSendEvent(eUpdateNoteInEditor, state.note, true);
|
||||
setState((prev) => ({ ...prev, loading: false }));
|
||||
if (noteRef.current?.id) {
|
||||
await db.vault.add(noteRef.current.id);
|
||||
eSendEvent(eUpdateNoteInEditor, noteRef.current, true);
|
||||
setLoading(false);
|
||||
ToastManager.show({
|
||||
heading: strings.noteLocked(),
|
||||
type: "success",
|
||||
@@ -554,7 +516,7 @@ export const VaultDialog: React.FC = () => {
|
||||
close();
|
||||
}
|
||||
eSendEvent("vaultUpdated");
|
||||
}, [state.biometricUnlock, state.note, enrollFingerprint, close]);
|
||||
}, [biometricUnlock, enrollFingerprint, close]);
|
||||
|
||||
const revokeFingerprintAccess = useCallback(async () => {
|
||||
try {
|
||||
@@ -578,8 +540,8 @@ export const VaultDialog: React.FC = () => {
|
||||
async (title?: string, description?: string) => {
|
||||
try {
|
||||
const credentials = await BiometricService.getCredentials(
|
||||
title || state.title,
|
||||
description || state.description || ""
|
||||
title || titleRef.current,
|
||||
description || descriptionRef.current || ""
|
||||
);
|
||||
|
||||
if (!credentials) throw new Error("Failed to get user credentials");
|
||||
@@ -590,22 +552,25 @@ export const VaultDialog: React.FC = () => {
|
||||
} else {
|
||||
eSendEvent(eCloseActionSheet);
|
||||
await sleep(300);
|
||||
setState((prev) => ({ ...prev, visible: true }));
|
||||
setVisible(true);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
},
|
||||
[state.title, state.description]
|
||||
[]
|
||||
);
|
||||
|
||||
const onPress = useCallback(async () => {
|
||||
if (state.revokeFingerprintAccess) {
|
||||
const requestType = requestTypeRef.current;
|
||||
|
||||
if (requestType === VaultRequestType.RevokeFingerprint) {
|
||||
await revokeFingerprintAccess();
|
||||
close();
|
||||
return;
|
||||
}
|
||||
if (state.loading) return;
|
||||
|
||||
if (loading) return;
|
||||
|
||||
if (!passwordRef.current) {
|
||||
ToastManager.show({
|
||||
@@ -616,26 +581,26 @@ export const VaultDialog: React.FC = () => {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!state.novault) {
|
||||
if (requestType === VaultRequestType.CreateVault) {
|
||||
if (passwordRef.current !== confirmPasswordRef.current) {
|
||||
ToastManager.show({
|
||||
heading: strings.passwordNotMatched(),
|
||||
type: "error",
|
||||
context: "local"
|
||||
});
|
||||
setState((prev) => ({ ...prev, passwordsDontMatch: true }));
|
||||
setPasswordsDontMatch(true);
|
||||
return;
|
||||
}
|
||||
|
||||
createVault();
|
||||
} else if (state.changePassword) {
|
||||
setState((prev) => ({ ...prev, loading: true }));
|
||||
} else if (requestType === VaultRequestType.ChangePassword) {
|
||||
setLoading(true);
|
||||
|
||||
db.vault
|
||||
.changePassword(passwordRef.current, newPasswordRef.current || "")
|
||||
.then(() => {
|
||||
setState((prev) => ({ ...prev, loading: false }));
|
||||
if (state.biometricUnlock) {
|
||||
setLoading(false);
|
||||
if (biometricUnlock) {
|
||||
enrollFingerprint(newPasswordRef.current || "");
|
||||
}
|
||||
ToastManager.show({
|
||||
@@ -646,7 +611,7 @@ export const VaultDialog: React.FC = () => {
|
||||
close();
|
||||
})
|
||||
.catch((e) => {
|
||||
setState((prev) => ({ ...prev, loading: false }));
|
||||
setLoading(false);
|
||||
if (e.message === VAULT_ERRORS.wrongPassword) {
|
||||
ToastManager.show({
|
||||
heading: strings.passwordIncorrect(),
|
||||
@@ -657,50 +622,62 @@ export const VaultDialog: React.FC = () => {
|
||||
ToastManager.error(e);
|
||||
}
|
||||
});
|
||||
} else if (state.locked) {
|
||||
} else if (requestType === VaultRequestType.LockNote) {
|
||||
if (!passwordRef.current || passwordRef.current.trim() === "") {
|
||||
ToastManager.show({
|
||||
heading: strings.passwordIncorrect(),
|
||||
type: "error",
|
||||
context: "local"
|
||||
});
|
||||
setState((prev) => ({ ...prev, wrongPassword: true }));
|
||||
setWrongPassword(true);
|
||||
return;
|
||||
}
|
||||
if (state.noteLocked) {
|
||||
db.vault
|
||||
.unlock(passwordRef.current)
|
||||
.then(async (unlocked) => {
|
||||
if (unlocked) {
|
||||
setWrongPassword(false);
|
||||
await lockNote();
|
||||
} else {
|
||||
takeErrorAction();
|
||||
}
|
||||
})
|
||||
.catch((e) => {
|
||||
takeErrorAction();
|
||||
});
|
||||
} else if (
|
||||
requestType === VaultRequestType.UnlockNote ||
|
||||
requestType === VaultRequestType.PermanentUnlock ||
|
||||
requestType === VaultRequestType.GoToEditor ||
|
||||
requestType === VaultRequestType.ShareNote ||
|
||||
requestType === VaultRequestType.CopyNote ||
|
||||
requestType === VaultRequestType.DeleteNote ||
|
||||
requestType === VaultRequestType.CustomAction
|
||||
) {
|
||||
if (!passwordRef.current || passwordRef.current.trim() === "") {
|
||||
ToastManager.show({
|
||||
heading: strings.passwordIncorrect(),
|
||||
type: "error",
|
||||
context: "local"
|
||||
});
|
||||
setWrongPassword(true);
|
||||
return;
|
||||
}
|
||||
if (noteLockedRef.current) {
|
||||
await unlockNote();
|
||||
} else {
|
||||
db.vault
|
||||
.unlock(passwordRef.current)
|
||||
.then(async () => {
|
||||
setState((prev) => ({ ...prev, wrongPassword: false }));
|
||||
await lockNote();
|
||||
})
|
||||
.catch((e) => {
|
||||
takeErrorAction();
|
||||
});
|
||||
console.log("Error: Note should be locked for this operation");
|
||||
}
|
||||
} else if (state.fingerprintAccess) {
|
||||
} else if (requestType === VaultRequestType.EnableFingerprint) {
|
||||
enrollFingerprint(passwordRef.current);
|
||||
} else if (state.clearVault) {
|
||||
} else if (requestType === VaultRequestType.ClearVault) {
|
||||
await clearVault();
|
||||
} else if (state.deleteVault) {
|
||||
} else if (requestType === VaultRequestType.DeleteVault) {
|
||||
await deleteVault();
|
||||
} else if (state.customAction) {
|
||||
await unlockNote();
|
||||
}
|
||||
}, [
|
||||
state.revokeFingerprintAccess,
|
||||
state.loading,
|
||||
state.novault,
|
||||
state.changePassword,
|
||||
state.locked,
|
||||
state.noteLocked,
|
||||
state.fingerprintAccess,
|
||||
state.clearVault,
|
||||
state.deleteVault,
|
||||
state.customAction,
|
||||
state.biometricUnlock,
|
||||
loading,
|
||||
biometricUnlock,
|
||||
revokeFingerprintAccess,
|
||||
close,
|
||||
createVault,
|
||||
@@ -722,23 +699,21 @@ export const VaultDialog: React.FC = () => {
|
||||
};
|
||||
}, [open, close]);
|
||||
|
||||
if (!state.visible) return null;
|
||||
if (!visible) return null;
|
||||
|
||||
const {
|
||||
note,
|
||||
novault,
|
||||
deleteNote: shouldDeleteNote,
|
||||
share,
|
||||
goToEditor,
|
||||
fingerprintAccess,
|
||||
changePassword,
|
||||
loading,
|
||||
deleteVault: shouldDeleteVault,
|
||||
clearVault: shouldClearVault,
|
||||
customAction,
|
||||
customActionTitle,
|
||||
customActionParagraph
|
||||
} = state;
|
||||
const requestType = requestTypeRef.current;
|
||||
const isCreateVault = requestType === VaultRequestType.CreateVault;
|
||||
const isChangePassword = requestType === VaultRequestType.ChangePassword;
|
||||
const isClearVault = requestType === VaultRequestType.ClearVault;
|
||||
const isDeleteVault = requestType === VaultRequestType.DeleteVault;
|
||||
const isRevokeFingerprint =
|
||||
requestType === VaultRequestType.RevokeFingerprint;
|
||||
const isEnableFingerprint =
|
||||
requestType === VaultRequestType.EnableFingerprint;
|
||||
const isCustomAction = requestType === VaultRequestType.CustomAction;
|
||||
const isDeleteNote = requestType === VaultRequestType.DeleteNote;
|
||||
const isShareNote = requestType === VaultRequestType.ShareNote;
|
||||
const isGoToEditor = requestType === VaultRequestType.GoToEditor;
|
||||
|
||||
return (
|
||||
<BaseDialog
|
||||
@@ -760,8 +735,10 @@ export const VaultDialog: React.FC = () => {
|
||||
}}
|
||||
>
|
||||
<DialogHeader
|
||||
title={state.title}
|
||||
paragraph={customActionParagraph || ""}
|
||||
title={titleRef.current}
|
||||
paragraph={
|
||||
paragraphRef.current || customActionParagraphRef.current || ""
|
||||
}
|
||||
icon="shield"
|
||||
padding={12}
|
||||
/>
|
||||
@@ -772,12 +749,12 @@ export const VaultDialog: React.FC = () => {
|
||||
paddingHorizontal: DefaultAppStyles.GAP
|
||||
}}
|
||||
>
|
||||
{(novault ||
|
||||
changePassword ||
|
||||
shouldClearVault ||
|
||||
shouldDeleteVault ||
|
||||
customAction) &&
|
||||
!state.revokeFingerprintAccess ? (
|
||||
{(isChangePassword ||
|
||||
isClearVault ||
|
||||
!isCreateVault ||
|
||||
isDeleteVault ||
|
||||
isCustomAction) &&
|
||||
!isRevokeFingerprint ? (
|
||||
<>
|
||||
<Input
|
||||
fwdRef={passInputRef}
|
||||
@@ -788,37 +765,40 @@ export const VaultDialog: React.FC = () => {
|
||||
passwordRef.current = value;
|
||||
}}
|
||||
marginBottom={
|
||||
!state.biometricUnlock ||
|
||||
!state.isBiometryEnrolled ||
|
||||
!novault ||
|
||||
changePassword ||
|
||||
customAction
|
||||
!biometricUnlock ||
|
||||
!isBiometryEnrolled ||
|
||||
isCreateVault ||
|
||||
isChangePassword ||
|
||||
isCustomAction
|
||||
? 0
|
||||
: 10
|
||||
}
|
||||
onSubmit={() => {
|
||||
if (changePassword) {
|
||||
if (isChangePassword) {
|
||||
confirmPassRef.current?.focus();
|
||||
} else {
|
||||
onPress();
|
||||
}
|
||||
}}
|
||||
autoComplete="password"
|
||||
returnKeyLabel={changePassword ? strings.next() : state.title}
|
||||
returnKeyType={changePassword ? "next" : "done"}
|
||||
returnKeyLabel={
|
||||
isChangePassword ? strings.next() : titleRef.current
|
||||
}
|
||||
returnKeyType={isChangePassword ? "next" : "done"}
|
||||
secureTextEntry
|
||||
placeholder={
|
||||
changePassword
|
||||
isChangePassword
|
||||
? strings.currentPassword()
|
||||
: strings.password()
|
||||
}
|
||||
/>
|
||||
|
||||
{!state.biometricUnlock ||
|
||||
!state.isBiometryEnrolled ||
|
||||
!novault ||
|
||||
changePassword ||
|
||||
customAction ? null : (
|
||||
{!biometricUnlock ||
|
||||
!isBiometryEnrolled ||
|
||||
!isBiometryAvailable ||
|
||||
isCreateVault ||
|
||||
isChangePassword ||
|
||||
isCustomAction ? null : (
|
||||
<Button
|
||||
onPress={() =>
|
||||
onPressFingerprintAuth(strings.unlockNote(), "")
|
||||
@@ -832,16 +812,11 @@ export const VaultDialog: React.FC = () => {
|
||||
</>
|
||||
) : null}
|
||||
|
||||
{shouldDeleteVault && (
|
||||
{isDeleteVault && (
|
||||
<Button
|
||||
onPress={() =>
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
deleteAll: !prev.deleteAll
|
||||
}))
|
||||
}
|
||||
onPress={() => setDeleteAll(!deleteAll)}
|
||||
icon={
|
||||
state.deleteAll
|
||||
deleteAll
|
||||
? "check-circle-outline"
|
||||
: "checkbox-blank-circle-outline"
|
||||
}
|
||||
@@ -854,7 +829,7 @@ export const VaultDialog: React.FC = () => {
|
||||
/>
|
||||
)}
|
||||
|
||||
{changePassword ? (
|
||||
{isChangePassword ? (
|
||||
<>
|
||||
<Seperator half />
|
||||
<Input
|
||||
@@ -877,7 +852,7 @@ export const VaultDialog: React.FC = () => {
|
||||
</>
|
||||
) : null}
|
||||
|
||||
{!novault ? (
|
||||
{isCreateVault ? (
|
||||
<View>
|
||||
<Input
|
||||
fwdRef={passInputRef}
|
||||
@@ -912,12 +887,9 @@ export const VaultDialog: React.FC = () => {
|
||||
onChangeText={(value) => {
|
||||
confirmPasswordRef.current = value;
|
||||
if (value !== passwordRef.current) {
|
||||
setState((prev) => ({ ...prev, passwordsDontMatch: true }));
|
||||
setPasswordsDontMatch(true);
|
||||
} else {
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
passwordsDontMatch: false
|
||||
}));
|
||||
setPasswordsDontMatch(false);
|
||||
}
|
||||
}}
|
||||
onSubmit={() => {
|
||||
@@ -928,22 +900,23 @@ export const VaultDialog: React.FC = () => {
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{state.biometricUnlock && !state.isBiometryEnrolled && novault ? (
|
||||
{biometricUnlock && !isBiometryEnrolled && !isCreateVault ? (
|
||||
<Paragraph>{strings.vaultEnableBiometrics()}</Paragraph>
|
||||
) : null}
|
||||
|
||||
{state.isBiometryAvailable &&
|
||||
!state.fingerprintAccess &&
|
||||
!shouldClearVault &&
|
||||
!shouldDeleteVault &&
|
||||
!customAction &&
|
||||
((!state.biometricUnlock && !changePassword) || !novault) ? (
|
||||
{!biometricUnlock &&
|
||||
!isBiometryEnrolled &&
|
||||
isBiometryAvailable &&
|
||||
(requestType === VaultRequestType.CopyNote ||
|
||||
requestType === VaultRequestType.DeleteNote ||
|
||||
requestType === VaultRequestType.ShareNote ||
|
||||
requestType === VaultRequestType.CustomAction ||
|
||||
requestType === VaultRequestType.GoToEditor ||
|
||||
requestType === VaultRequestType.PermanentUnlock ||
|
||||
requestType === VaultRequestType.LockNote) ? (
|
||||
<Button
|
||||
onPress={() => {
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
biometricUnlock: !prev.biometricUnlock
|
||||
}));
|
||||
setBiometricUnlock(!biometricUnlock);
|
||||
}}
|
||||
style={{
|
||||
marginTop: DefaultAppStyles.GAP_VERTICAL
|
||||
@@ -952,11 +925,9 @@ export const VaultDialog: React.FC = () => {
|
||||
width="100%"
|
||||
title={strings.unlockWithBiometrics()}
|
||||
iconColor={
|
||||
state.biometricUnlock
|
||||
? colors.selected.accent
|
||||
: colors.primary.icon
|
||||
biometricUnlock ? colors.selected.accent : colors.primary.icon
|
||||
}
|
||||
type={state.biometricUnlock ? "transparent" : "plain"}
|
||||
type={biometricUnlock ? "transparent" : "plain"}
|
||||
/>
|
||||
) : null}
|
||||
</View>
|
||||
@@ -965,34 +936,8 @@ export const VaultDialog: React.FC = () => {
|
||||
onPressNegative={close}
|
||||
onPressPositive={onPress}
|
||||
loading={loading}
|
||||
positiveType={
|
||||
shouldDeleteVault || shouldClearVault ? "errorShade" : "transparent"
|
||||
}
|
||||
positiveTitle={
|
||||
shouldDeleteVault
|
||||
? strings.delete()
|
||||
: shouldClearVault
|
||||
? strings.clear()
|
||||
: fingerprintAccess
|
||||
? strings.enable()
|
||||
: state.revokeFingerprintAccess
|
||||
? strings.revoke()
|
||||
: changePassword
|
||||
? strings.change()
|
||||
: customAction && customActionTitle
|
||||
? customActionTitle
|
||||
: state.noteLocked
|
||||
? shouldDeleteNote
|
||||
? strings.delete()
|
||||
: share
|
||||
? strings.share()
|
||||
: goToEditor
|
||||
? strings.open()
|
||||
: strings.unlock()
|
||||
: !note?.id
|
||||
? strings.create()
|
||||
: strings.lock()
|
||||
}
|
||||
positiveType={positiveButtonTypeRef.current}
|
||||
positiveTitle={buttonTitleRef.current || strings.unlock()}
|
||||
/>
|
||||
</View>
|
||||
<Toast context="local" />
|
||||
|
||||
@@ -40,7 +40,6 @@ import Animated, {
|
||||
withTiming
|
||||
} from "react-native-reanimated";
|
||||
import { useTabStore } from "../../screens/editor/tiptap/use-tab-store";
|
||||
import { getAppState } from "../../screens/editor/tiptap/utils";
|
||||
import { eSendEvent } from "../../services/event-manager";
|
||||
import { useSettingStore } from "../../stores/use-setting-store";
|
||||
import { eClearEditor } from "../../utils/events";
|
||||
@@ -84,18 +83,9 @@ export const FluidPanels = forwardRef<TabsRef, TabProps>(function FluidTabs(
|
||||
}: TabProps,
|
||||
ref
|
||||
) {
|
||||
const appState = useMemo(() => getAppState(), []);
|
||||
const deviceMode = useSettingStore((state) => state.deviceMode);
|
||||
const fullscreen = useSettingStore((state) => state.fullscreen);
|
||||
const translateX = useSharedValue(
|
||||
widths
|
||||
? appState &&
|
||||
appState?.movedAway === false &&
|
||||
useTabStore.getState().getCurrentNoteId()
|
||||
? widths.sidebar + widths.list
|
||||
: widths.sidebar
|
||||
: 0
|
||||
);
|
||||
const translateX = useSharedValue(widths ? widths.sidebar : 0);
|
||||
const startX = useSharedValue(0);
|
||||
const currentTab = useSharedValue(1);
|
||||
const previousTab = useSharedValue(1);
|
||||
@@ -125,10 +115,7 @@ export const FluidPanels = forwardRef<TabsRef, TabProps>(function FluidTabs(
|
||||
translateX.value = 0;
|
||||
} else {
|
||||
if (prevWidths.current?.sidebar !== widths.sidebar) {
|
||||
translateX.value =
|
||||
appState && appState?.movedAway === false
|
||||
? editorPosition
|
||||
: widths.sidebar;
|
||||
translateX.value = widths.sidebar;
|
||||
if (translateX.value === editorPosition) {
|
||||
onChangeTab?.({ i: 2, from: 1 });
|
||||
}
|
||||
@@ -136,15 +123,7 @@ export const FluidPanels = forwardRef<TabsRef, TabProps>(function FluidTabs(
|
||||
}
|
||||
isLoaded.current = true;
|
||||
prevWidths.current = widths;
|
||||
}, [
|
||||
deviceMode,
|
||||
widths,
|
||||
fullscreen,
|
||||
translateX,
|
||||
editorPosition,
|
||||
appState,
|
||||
onChangeTab
|
||||
]);
|
||||
}, [deviceMode, widths, fullscreen, translateX, editorPosition, onChangeTab]);
|
||||
|
||||
useEffect(() => {
|
||||
const sub = BackHandler.addEventListener("hardwareBackPress", () => {
|
||||
|
||||
@@ -32,9 +32,11 @@ import { eOnLoadNote, eShowMergeDialog } from "../../../utils/events";
|
||||
import { fluidTabsRef } from "../../../utils/global-refs";
|
||||
|
||||
import { NotebooksWithDateEdited, TagsWithDateEdited } from "@notesnook/common";
|
||||
import { useTabStore } from "../../../screens/editor/tiptap/use-tab-store";
|
||||
import { editorController } from "../../../screens/editor/tiptap/utils";
|
||||
import { RouteParams } from "../../../stores/use-navigation-store";
|
||||
import NotePreview from "../../note-history/preview";
|
||||
import SelectionWrapper, { selectItem } from "../selection-wrapper";
|
||||
import { RouteParams } from "../../../stores/use-navigation-store";
|
||||
|
||||
export const openNote = async (
|
||||
item: Note,
|
||||
@@ -63,11 +65,19 @@ export const openNote = async (
|
||||
component: <NotePreview note={item} content={content} />
|
||||
});
|
||||
} else {
|
||||
if (!useTabStore.getState().hasTabForNote(note.id!)) {
|
||||
editorController.current.commands.setLoading(
|
||||
true,
|
||||
useTabStore.getState().currentTab
|
||||
);
|
||||
}
|
||||
eSendEvent(eOnLoadNote, {
|
||||
item: note
|
||||
});
|
||||
if (!DDS.isTab) {
|
||||
fluidTabsRef.current?.goToPage("editor");
|
||||
setTimeout(() => {
|
||||
fluidTabsRef.current?.goToPage("editor");
|
||||
}, 32);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -77,10 +77,10 @@ export default function List(props: ListProps) {
|
||||
props.renderedInRoute === "Notes"
|
||||
? "home"
|
||||
: props.renderedInRoute === "Favorites"
|
||||
? "favorites"
|
||||
: props.renderedInRoute === "Trash" || props.dataType === "trash"
|
||||
? "trash"
|
||||
: `${props.dataType}s`;
|
||||
? "favorites"
|
||||
: props.renderedInRoute === "Trash" || props.dataType === "trash"
|
||||
? "trash"
|
||||
: `${props.dataType}s`;
|
||||
|
||||
const groupOptions = useGroupOptions(groupType);
|
||||
|
||||
|
||||
@@ -41,7 +41,8 @@ import {
|
||||
eSendEvent,
|
||||
eSubscribeEvent,
|
||||
eUnSubscribeEvent,
|
||||
openVault
|
||||
openVault,
|
||||
VaultRequestType
|
||||
} from "../../services/event-manager";
|
||||
import Navigation from "../../services/navigation";
|
||||
import Sync from "../../services/sync";
|
||||
@@ -59,6 +60,7 @@ import { IconButton } from "../ui/icon-button";
|
||||
import Seperator from "../ui/seperator";
|
||||
import Paragraph from "../ui/typography/paragraph";
|
||||
import { presentDialog } from "../dialog/functions";
|
||||
import { Cipher } from "@notesnook/crypto";
|
||||
|
||||
const MergeConflicts = () => {
|
||||
const { colors } = useThemeColors();
|
||||
@@ -83,12 +85,21 @@ const MergeConflicts = () => {
|
||||
dateEdited: contentToSave.dateEdited
|
||||
});
|
||||
|
||||
const noteLocked = await db.vaults.itemExists(note);
|
||||
const noteContent = await db.content.findByNoteId(note.id);
|
||||
|
||||
if (noteLocked) {
|
||||
await db.vault.save({
|
||||
...contentToSave,
|
||||
sessionId: `${Date.now()}`
|
||||
if (noteContent?.locked) {
|
||||
const selectedContent = contentToSave.conflicted
|
||||
? noteContent
|
||||
: noteContent.conflicted;
|
||||
|
||||
await db.content.add({
|
||||
id: note.contentId,
|
||||
dateResolved: noteContent?.conflicted?.dateModified || Date.now(),
|
||||
sessionId: `${Date.now()}`,
|
||||
data: selectedContent?.data as Cipher<"base64">,
|
||||
type: selectedContent?.type,
|
||||
locked: true,
|
||||
conflicted: undefined
|
||||
});
|
||||
} else {
|
||||
await db.content.add({
|
||||
@@ -128,14 +139,15 @@ const MergeConflicts = () => {
|
||||
let noteContent: UnencryptedContentItem;
|
||||
if (isLocked) {
|
||||
openVault({
|
||||
requestType: VaultRequestType.CustomAction,
|
||||
item: item,
|
||||
novault: true,
|
||||
customActionTitle: "Unlock note",
|
||||
customActionParagraph: "Unlock note to merge conflicts",
|
||||
title: strings.unlockNote(),
|
||||
customActionTitle: strings.unlockNote(),
|
||||
customActionParagraph: strings.unlockNoteToMergeConflicts(),
|
||||
buttonTitle: strings.unlock(),
|
||||
onUnlock: async (item, password) => {
|
||||
if (!item || !password) return;
|
||||
const currentContent = await db.content.get(item.contentId!);
|
||||
|
||||
try {
|
||||
noteContent = {
|
||||
...(await db.content.get(item.contentId!)),
|
||||
|
||||
@@ -183,6 +183,7 @@ const PayWall = (props: NavigationProps<"PayWall">) => {
|
||||
>
|
||||
<IconButton
|
||||
name="close"
|
||||
testID="paywall-close"
|
||||
color={colors.primary.icon}
|
||||
onPress={() => {
|
||||
Navigation.navigate("FluidPanelsView", {});
|
||||
@@ -1008,8 +1009,8 @@ const PricingPlanCard = ({
|
||||
: "monthly"
|
||||
}`
|
||||
: pricingPlans.isGithubRelease
|
||||
? (WebPlan?.period as string)
|
||||
: (product?.productId as string)
|
||||
? (WebPlan?.period as string)
|
||||
: (product?.productId as string)
|
||||
);
|
||||
setStep(Steps.buy);
|
||||
}}
|
||||
|
||||
@@ -33,7 +33,6 @@ import AppIcon from "../ui/AppIcon";
|
||||
import { Button } from "../ui/button";
|
||||
import { Pressable } from "../ui/pressable";
|
||||
import Paragraph from "../ui/typography/paragraph";
|
||||
import { Dialog } from "../dialog";
|
||||
|
||||
const TOP_BAR_ITEMS: ActionId[] = [
|
||||
"pin",
|
||||
@@ -43,7 +42,8 @@ const TOP_BAR_ITEMS: ActionId[] = [
|
||||
"publish",
|
||||
"local-only",
|
||||
"read-only",
|
||||
"pin-to-notifications"
|
||||
"pin-to-notifications",
|
||||
"spell-check"
|
||||
];
|
||||
|
||||
const BOTTOM_BAR_ITEMS: ActionId[] = [
|
||||
@@ -80,6 +80,8 @@ const COLUMN_BAR_ITEMS: ActionId[] = [
|
||||
"rename-color",
|
||||
"rename-tag",
|
||||
"launcher-shortcut",
|
||||
"copy-id",
|
||||
"copy-link",
|
||||
"restore",
|
||||
"trash",
|
||||
"delete"
|
||||
@@ -327,8 +329,9 @@ export const Items = ({
|
||||
|
||||
const getTopBarItemChunksOfFour = () => {
|
||||
const chunks = [];
|
||||
for (let i = 0; i < topBarItems.length; i += 5) {
|
||||
chunks.push(topBarItems.slice(i, i + 5));
|
||||
const itemCount = shouldShrink ? 4 : 5;
|
||||
for (let i = 0; i < topBarItems.length; i += itemCount) {
|
||||
chunks.push(topBarItems.slice(i, i + itemCount));
|
||||
}
|
||||
return chunks;
|
||||
};
|
||||
@@ -375,7 +378,8 @@ export const Items = ({
|
||||
style={{
|
||||
flexDirection: "row",
|
||||
paddingHorizontal: DefaultAppStyles.GAP,
|
||||
gap: 5
|
||||
gap: 5,
|
||||
width: width
|
||||
}}
|
||||
>
|
||||
{item.map(renderTopBarItem)}
|
||||
|
||||
169
apps/mobile/app/components/sheets/add-api-key/index.tsx
Normal file
169
apps/mobile/app/components/sheets/add-api-key/index.tsx
Normal file
@@ -0,0 +1,169 @@
|
||||
/*
|
||||
This file is part of the Notesnook project (https://notesnook.com/)
|
||||
|
||||
Copyright (C) 2023 Streetwriters (Private) Limited
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import React, { useRef, useState } from "react";
|
||||
import { View, ScrollView } from "react-native";
|
||||
import { strings } from "@notesnook/intl";
|
||||
import { db } from "../../../common/database";
|
||||
import { Button } from "../../ui/button";
|
||||
import Input from "../../ui/input";
|
||||
import Paragraph from "../../ui/typography/paragraph";
|
||||
import Heading from "../../ui/typography/heading";
|
||||
import { DefaultAppStyles } from "../../../utils/styles";
|
||||
import { AppFontSize } from "../../../utils/size";
|
||||
import { ToastManager, presentSheet } from "../../../services/event-manager";
|
||||
import { useThemeColors } from "@notesnook/theme";
|
||||
import { Pressable } from "../../ui/pressable";
|
||||
|
||||
const getExpiryOptions = () => [
|
||||
{ label: strings.expiryOneDay(), value: 24 * 60 * 60 * 1000 },
|
||||
{ label: strings.expiryOneWeek(), value: 7 * 24 * 60 * 60 * 1000 },
|
||||
{ label: strings.expiryOneMonth(), value: 30 * 24 * 60 * 60 * 1000 },
|
||||
{ label: strings.expiryOneYear(), value: 365 * 24 * 60 * 60 * 1000 },
|
||||
{ label: strings.never(), value: -1 }
|
||||
];
|
||||
|
||||
type AddApiKeySheetProps = {
|
||||
close?: (ctx?: string | undefined) => void;
|
||||
onAdd: () => void;
|
||||
};
|
||||
|
||||
export default function AddApiKeySheet({ close, onAdd }: AddApiKeySheetProps) {
|
||||
const { colors } = useThemeColors();
|
||||
const keyNameRef = useRef<string>("");
|
||||
const [selectedExpiry, setSelectedExpiry] = useState(
|
||||
getExpiryOptions()[2].value
|
||||
);
|
||||
const [isCreating, setIsCreating] = useState(false);
|
||||
|
||||
const handleCreate = async () => {
|
||||
try {
|
||||
if (!keyNameRef.current || !keyNameRef.current.trim()) {
|
||||
ToastManager.show({
|
||||
message: strings.enterKeyName(),
|
||||
type: "error"
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setIsCreating(true);
|
||||
await db.inboxApiKeys.create(keyNameRef.current, selectedExpiry);
|
||||
ToastManager.show({
|
||||
message: strings.apiKeyCreatedSuccessfully(),
|
||||
type: "success"
|
||||
});
|
||||
onAdd();
|
||||
close?.();
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "";
|
||||
ToastManager.show({
|
||||
message: strings.failedToCreateApiKey(message),
|
||||
type: "error"
|
||||
});
|
||||
} finally {
|
||||
setIsCreating(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<ScrollView
|
||||
contentContainerStyle={{
|
||||
paddingHorizontal: DefaultAppStyles.GAP,
|
||||
gap: DefaultAppStyles.GAP_VERTICAL,
|
||||
paddingTop: DefaultAppStyles.GAP_VERTICAL,
|
||||
paddingBottom: DefaultAppStyles.GAP_VERTICAL * 2
|
||||
}}
|
||||
>
|
||||
<View
|
||||
style={{
|
||||
flexDirection: "row",
|
||||
justifyContent: "space-between",
|
||||
alignItems: "center"
|
||||
}}
|
||||
>
|
||||
<Heading size={AppFontSize.xl}>{strings.createApiKey()}</Heading>
|
||||
</View>
|
||||
|
||||
<View style={{ gap: DefaultAppStyles.GAP_VERTICAL }}>
|
||||
<Paragraph size={AppFontSize.sm}>{strings.keyName()}</Paragraph>
|
||||
<Input
|
||||
placeholder={strings.exampleKeyName()}
|
||||
onChangeText={(text) => {
|
||||
keyNameRef.current = text;
|
||||
}}
|
||||
/>
|
||||
</View>
|
||||
|
||||
<View style={{ gap: DefaultAppStyles.GAP_VERTICAL }}>
|
||||
<Paragraph size={AppFontSize.sm}>{strings.expiresIn()}</Paragraph>
|
||||
<View
|
||||
style={{
|
||||
flexDirection: "row",
|
||||
flexWrap: "wrap",
|
||||
gap: DefaultAppStyles.GAP_SMALL
|
||||
}}
|
||||
>
|
||||
{getExpiryOptions().map((option) => (
|
||||
<Pressable
|
||||
key={option.label}
|
||||
onPress={() => setSelectedExpiry(option.value)}
|
||||
type={
|
||||
selectedExpiry === option.value ? "selected" : "transparent"
|
||||
}
|
||||
style={{
|
||||
paddingVertical: DefaultAppStyles.GAP_VERTICAL_SMALL,
|
||||
paddingHorizontal: DefaultAppStyles.GAP
|
||||
}}
|
||||
>
|
||||
<Paragraph
|
||||
size={AppFontSize.sm}
|
||||
color={
|
||||
selectedExpiry === option.value
|
||||
? colors.selected.paragraph
|
||||
: colors.primary.paragraph
|
||||
}
|
||||
>
|
||||
{option.label}
|
||||
</Paragraph>
|
||||
</Pressable>
|
||||
))}
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<Button
|
||||
title={isCreating ? strings.creating() : strings.create()}
|
||||
type="accent"
|
||||
width="100%"
|
||||
loading={isCreating}
|
||||
disabled={isCreating}
|
||||
onPress={handleCreate}
|
||||
style={{
|
||||
marginTop: DefaultAppStyles.GAP_VERTICAL
|
||||
}}
|
||||
/>
|
||||
</ScrollView>
|
||||
);
|
||||
}
|
||||
|
||||
AddApiKeySheet.present = (onAdd: () => void) => {
|
||||
presentSheet({
|
||||
component: (ref, close, update) => (
|
||||
<AddApiKeySheet close={close} onAdd={onAdd} />
|
||||
)
|
||||
});
|
||||
};
|
||||
@@ -356,7 +356,7 @@ const ProductItem = (props: {
|
||||
(product as RNIap.Subscription)?.productId
|
||||
) ||
|
||||
props.pricingPlans.user?.subscription?.productId ===
|
||||
(product as Plan).id);
|
||||
(product as Plan)?.id);
|
||||
|
||||
useEffect(() => {
|
||||
props.pricingPlans
|
||||
|
||||
@@ -33,11 +33,11 @@ import { editorController } from "../../../screens/editor/tiptap/utils";
|
||||
import { eSendEvent, presentSheet } from "../../../services/event-manager";
|
||||
import { eUnlockNote } from "../../../utils/events";
|
||||
import { AppFontSize } from "../../../utils/size";
|
||||
import { DefaultAppStyles } from "../../../utils/styles";
|
||||
import { IconButton } from "../../ui/icon-button";
|
||||
import { Pressable } from "../../ui/pressable";
|
||||
import Heading from "../../ui/typography/heading";
|
||||
import Paragraph from "../../ui/typography/paragraph";
|
||||
import { DefaultAppStyles } from "../../../utils/styles";
|
||||
|
||||
const TabItemComponent = (props: {
|
||||
tab: TabItem;
|
||||
@@ -102,9 +102,17 @@ const TabItemComponent = (props: {
|
||||
{props.tab.session?.noteLocked ? (
|
||||
<>
|
||||
{props.tab.session?.locked ? (
|
||||
<Icon size={AppFontSize.md} name="lock" />
|
||||
<Icon
|
||||
size={AppFontSize.md}
|
||||
name="lock"
|
||||
color={colors.primary.icon}
|
||||
/>
|
||||
) : (
|
||||
<Icon size={AppFontSize.md} name="lock-open-outline" />
|
||||
<Icon
|
||||
size={AppFontSize.md}
|
||||
name="lock-open-outline"
|
||||
color={colors.primary.icon}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
) : null}
|
||||
@@ -217,14 +225,24 @@ export default function EditorTabs({
|
||||
}}
|
||||
>
|
||||
<Heading size={AppFontSize.lg}>{strings.tabs()}</Heading>
|
||||
<IconButton
|
||||
onPress={() => {
|
||||
useTabStore.getState().newTab();
|
||||
close?.();
|
||||
}}
|
||||
name="plus"
|
||||
color={colors.primary.accent}
|
||||
/>
|
||||
<View style={{ flexDirection: "row", gap: DefaultAppStyles.GAP_SMALL }}>
|
||||
<IconButton
|
||||
onPress={() => {
|
||||
useTabStore.getState().clearAllTabs();
|
||||
close?.();
|
||||
}}
|
||||
name="close-box-multiple-outline"
|
||||
color={colors.primary.icon}
|
||||
/>
|
||||
<IconButton
|
||||
onPress={() => {
|
||||
useTabStore.getState().newTab();
|
||||
close?.();
|
||||
}}
|
||||
name="plus"
|
||||
color={colors.primary.accent}
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<FlatList
|
||||
@@ -245,4 +263,4 @@ EditorTabs.present = () => {
|
||||
presentSheet({
|
||||
component: (ref, close, update) => <EditorTabs close={close} />
|
||||
});
|
||||
};
|
||||
};
|
||||
@@ -118,8 +118,8 @@ const ListBlockItem = ({
|
||||
{item?.content.length > 200
|
||||
? item?.content.slice(0, 200) + "..."
|
||||
: !item.content || item.content.trim() === ""
|
||||
? strings.linkNoteEmptyBlock()
|
||||
: item.content}
|
||||
? strings.linkNoteEmptyBlock()
|
||||
: item.content}
|
||||
</Paragraph>
|
||||
|
||||
<View
|
||||
|
||||
@@ -17,7 +17,7 @@ You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import { hosts, Monograph, Note } from "@notesnook/core";
|
||||
import { Note } from "@notesnook/core";
|
||||
import { strings } from "@notesnook/intl";
|
||||
import { useThemeColors } from "@notesnook/theme";
|
||||
import Clipboard from "@react-native-clipboard/clipboard";
|
||||
@@ -53,15 +53,14 @@ async function fetchMonographData(noteId: string) {
|
||||
const monograph = monographId
|
||||
? await db.monographs.get(monographId)
|
||||
: undefined;
|
||||
const analyticsFeature = await isFeatureAvailable("monographAnalytics");
|
||||
const analytics =
|
||||
monographId && analyticsFeature
|
||||
? await db.monographs.analytics(monographId)
|
||||
: undefined;
|
||||
|
||||
const metadata = monographId
|
||||
? await db.monographs.metadata(monographId)
|
||||
: { publishUrl: "", analytics: { totalViews: 0 } };
|
||||
return {
|
||||
monograph,
|
||||
monographId,
|
||||
analytics
|
||||
metadata
|
||||
};
|
||||
}
|
||||
|
||||
@@ -86,8 +85,9 @@ const PublishNoteSheet = ({
|
||||
return fetchMonographData(note?.id);
|
||||
}, []);
|
||||
const monograph = monographData.result?.monograph;
|
||||
const metadata = monographData.result?.metadata;
|
||||
customTitle.current = monograph?.title || note.title || "";
|
||||
const publishUrl = monograph && `${hosts.MONOGRAPH_HOST}/${monograph?.id}`;
|
||||
const publishUrl = metadata?.publishUrl || monograph?.publishUrl || "";
|
||||
const isPublished = db.monographs.monograph(note?.id);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -382,7 +382,8 @@ const PublishNoteSheet = ({
|
||||
>
|
||||
<Paragraph size={AppFontSize.sm}>{strings.views()}</Paragraph>
|
||||
<Paragraph>
|
||||
{monographData?.result?.analytics?.totalViews || 0}
|
||||
{monographData?.result?.metadata?.analytics?.totalViews ||
|
||||
0}
|
||||
</Paragraph>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
@@ -202,7 +202,7 @@ const ListNoteItem = ({
|
||||
items: VirtualizedGrouping<Note> | undefined;
|
||||
onSelect: (item: Note, blockId?: string) => void;
|
||||
reference: Note;
|
||||
internalLinks: MutableRefObject<InternalLink<"note">[] | undefined>;
|
||||
internalLinks: MutableRefObject<InternalLink[] | undefined>;
|
||||
listType: "linkedNotes" | "referencedIn";
|
||||
}) => {
|
||||
const { colors } = useThemeColors();
|
||||
@@ -231,7 +231,10 @@ const ListNoteItem = ({
|
||||
internalLinks.current = await db.notes.internalLinks(reference.id);
|
||||
}
|
||||
const noteLinks = internalLinks.current.filter(
|
||||
(link) => link.id === item.id && link.params?.blockId
|
||||
(link) =>
|
||||
link.id === item.id &&
|
||||
link.type === "note" &&
|
||||
link.params?.blockId
|
||||
);
|
||||
|
||||
if (noteLinks.length) {
|
||||
@@ -239,7 +242,10 @@ const ListNoteItem = ({
|
||||
|
||||
setLinkedBlocks(
|
||||
blocks.filter((block) =>
|
||||
noteLinks.find((link) => block.id === link.params?.blockId)
|
||||
noteLinks.find(
|
||||
(link) =>
|
||||
link.type === "note" && block.id === link.params?.blockId
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
@@ -404,7 +410,7 @@ export const ReferencesList = ({ item, close }: ReferencesListProps) => {
|
||||
const { colors } = useThemeColors();
|
||||
const [items, setItems] = useState<VirtualizedGrouping<Note>>();
|
||||
const hasNoRelations = !items || items?.placeholders?.length === 0;
|
||||
const internalLinks = useRef<InternalLink<"note">[]>([]);
|
||||
const internalLinks = useRef<InternalLink[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
db.relations?.[tab === 0 ? "from" : "to"]?.(
|
||||
|
||||
@@ -114,8 +114,8 @@ export const UserSheet = () => {
|
||||
progress ? `(${progress.current})` : ""
|
||||
}`
|
||||
: lastSyncStatus === SyncStatus.Failed
|
||||
? strings.syncFailed()
|
||||
: strings.synced()}{" "}
|
||||
? strings.syncFailed()
|
||||
: strings.synced()}{" "}
|
||||
{!syncing ? (
|
||||
<TimeSince
|
||||
style={{
|
||||
@@ -139,8 +139,8 @@ export const UserSheet = () => {
|
||||
!user || lastSyncStatus === SyncStatus.Failed
|
||||
? colors.error.icon
|
||||
: isOffline
|
||||
? colors.static.orange
|
||||
: colors.success.icon
|
||||
? colors.static.orange
|
||||
: colors.success.icon
|
||||
}
|
||||
/>
|
||||
</Paragraph>
|
||||
|
||||
@@ -136,8 +136,8 @@ const SimpleTabView = ({
|
||||
{loadedKeysRef.current.has(route.key)
|
||||
? getSceneForRoute(route)
|
||||
: navigationState.index === routeIndex
|
||||
? getSceneForRoute(route)
|
||||
: null}
|
||||
? getSceneForRoute(route)
|
||||
: null}
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
@@ -435,8 +435,9 @@ const TabBar = (props: SimpleTabBarProps) => {
|
||||
color={colors.primary.icon}
|
||||
onPress={async () => {
|
||||
if (props.navigationState.index === 1) {
|
||||
const notebooksFeature =
|
||||
await isFeatureAvailable("notebooks");
|
||||
const notebooksFeature = await isFeatureAvailable(
|
||||
"notebooks"
|
||||
);
|
||||
if (!notebooksFeature.isAllowed) {
|
||||
PaywallSheet.present(notebooksFeature);
|
||||
return;
|
||||
|
||||
@@ -151,8 +151,8 @@ export function MenuItem({
|
||||
item.icon === "crown"
|
||||
? colors.static.yellow
|
||||
: isFocused
|
||||
? colors.selected.icon
|
||||
: colors.secondary.icon
|
||||
? colors.selected.icon
|
||||
: colors.secondary.icon
|
||||
}
|
||||
size={AppFontSize.md}
|
||||
/>
|
||||
|
||||
@@ -98,8 +98,8 @@ export const NotebookItem = ({
|
||||
item.depth === 0
|
||||
? undefined
|
||||
: item.depth < 6
|
||||
? 15 * item.depth
|
||||
: 15 * 5,
|
||||
? 15 * item.depth
|
||||
: 15 * 5,
|
||||
width: "100%",
|
||||
marginTop: 2
|
||||
}}
|
||||
@@ -187,8 +187,8 @@ export const NotebookItem = ({
|
||||
!item.hasChildren || disableExpand
|
||||
? "book-outline"
|
||||
: expanded
|
||||
? "chevron-down"
|
||||
: "chevron-right"
|
||||
? "chevron-down"
|
||||
: "chevron-right"
|
||||
}
|
||||
/>
|
||||
|
||||
@@ -241,6 +241,7 @@ export const NotebookItem = ({
|
||||
name="plus"
|
||||
size={AppFontSize.md}
|
||||
testID={`add-notebook-${index}`}
|
||||
color={colors.primary.icon}
|
||||
top={0}
|
||||
left={0}
|
||||
bottom={0}
|
||||
|
||||
@@ -303,7 +303,7 @@ export const SideMenuTags = () => {
|
||||
} catch (e) {
|
||||
DatabaseLogger.error(e);
|
||||
}
|
||||
}, 500);
|
||||
}, 100);
|
||||
}}
|
||||
placeholderTextColor={colors.primary.placeholder}
|
||||
/>
|
||||
|
||||
@@ -158,22 +158,22 @@ export const Toast = ({ context = "global" }) => {
|
||||
toastOptions.icon
|
||||
? toastOptions.icon
|
||||
: toastOptions.type === "success"
|
||||
? "check"
|
||||
: toastOptions.type === "info"
|
||||
? "information"
|
||||
: "close"
|
||||
? "check"
|
||||
: toastOptions.type === "info"
|
||||
? "information"
|
||||
: "close"
|
||||
}
|
||||
size={isFullToastMessage ? AppFontSize.xxxl : AppFontSize.xl}
|
||||
color={
|
||||
toastOptions?.icon
|
||||
? toastOptions?.icon
|
||||
: toastOptions.type === "error"
|
||||
? colors.error.icon
|
||||
: toastOptions.type === "info"
|
||||
? isDark
|
||||
? colors.static.white
|
||||
: colors.static.black
|
||||
: colors.success.icon
|
||||
? colors.error.icon
|
||||
: toastOptions.type === "info"
|
||||
? isDark
|
||||
? colors.static.white
|
||||
: colors.static.black
|
||||
: colors.success.icon
|
||||
}
|
||||
/>
|
||||
|
||||
|
||||
@@ -20,6 +20,7 @@ import { useThemeColors } from "@notesnook/theme";
|
||||
import React from "react";
|
||||
import { ColorValue, TextProps } from "react-native";
|
||||
import Icon from "react-native-vector-icons/MaterialCommunityIcons";
|
||||
import EvilIcon from "react-native-vector-icons/EvilIcons";
|
||||
import { AppFontSize } from "../../../utils/size";
|
||||
|
||||
export interface IconProps extends TextProps {
|
||||
@@ -43,11 +44,22 @@ export interface IconProps extends TextProps {
|
||||
*
|
||||
*/
|
||||
color?: ColorValue | number | undefined;
|
||||
|
||||
iconFamily?: "evilicons" | "material";
|
||||
}
|
||||
|
||||
export default function AppIcon(props: IconProps) {
|
||||
export default function AppIcon({
|
||||
iconFamily = "material",
|
||||
...props
|
||||
}: IconProps) {
|
||||
const { colors } = useThemeColors();
|
||||
return (
|
||||
return iconFamily === "evilicons" ? (
|
||||
<EvilIcon
|
||||
size={AppFontSize.md}
|
||||
color={colors.primary.icon}
|
||||
{...(props as any)}
|
||||
/>
|
||||
) : (
|
||||
<Icon
|
||||
size={AppFontSize.md}
|
||||
color={colors.primary.icon}
|
||||
|
||||
@@ -107,7 +107,7 @@ export const IconButton = ({
|
||||
color={
|
||||
restProps.disabled
|
||||
? RGB_Linear_Shade(-0.05, hexToRGBA(colors.secondary.background))
|
||||
: colors.static[color as never] || color
|
||||
: colors.static[color as never] || color || colors.primary.icon
|
||||
}
|
||||
size={size}
|
||||
/>
|
||||
|
||||
@@ -121,8 +121,8 @@ const Input = ({
|
||||
const color = error
|
||||
? colors.error.border
|
||||
: focus
|
||||
? customColor || colors.selected.border
|
||||
: colors.primary.border;
|
||||
? customColor || colors.selected.border
|
||||
: colors.primary.border;
|
||||
|
||||
const validate = async (value: string) => {
|
||||
if (!validationType) return;
|
||||
|
||||
@@ -48,7 +48,6 @@ export const Notice = ({
|
||||
<View
|
||||
style={{
|
||||
paddingHorizontal: DefaultAppStyles.GAP,
|
||||
paddingLeft: 5,
|
||||
paddingVertical: DefaultAppStyles.GAP_VERTICAL,
|
||||
flexDirection: "row",
|
||||
backgroundColor: colors.secondary.background,
|
||||
@@ -63,6 +62,9 @@ export const Notice = ({
|
||||
size={isSmall ? AppFontSize.md + 2 : AppFontSize.xxl}
|
||||
name={type}
|
||||
color={type === "alert" ? colors.error.icon : colors.primary.accent}
|
||||
style={{
|
||||
marginTop: isSmall ? 3 : 5
|
||||
}}
|
||||
/>
|
||||
<Paragraph
|
||||
style={{
|
||||
|
||||
@@ -268,8 +268,8 @@ export const Pressable = ({
|
||||
const opacity = customOpacity
|
||||
? customOpacity
|
||||
: type === "accent"
|
||||
? 1
|
||||
: colorOpacity;
|
||||
? 1
|
||||
: colorOpacity;
|
||||
const alpha = customAlpha ? customAlpha : isDark ? 0.03 : -0.03;
|
||||
const { fontScale } = useWindowDimensions();
|
||||
const growFactor = 1 + (fontScale - 1) / 8;
|
||||
|
||||
@@ -159,7 +159,7 @@ const SheetWrapper = ({
|
||||
{bottomPadding ? (
|
||||
<View
|
||||
style={{
|
||||
height: bottomInsets
|
||||
height: 10
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
@@ -21,6 +21,7 @@ import { isFeatureAvailable, useAreFeaturesAvailable } from "@notesnook/common";
|
||||
import {
|
||||
Color,
|
||||
createInternalLink,
|
||||
isEncryptedContent,
|
||||
Item,
|
||||
ItemReference,
|
||||
Note,
|
||||
@@ -54,7 +55,8 @@ import {
|
||||
eSubscribeEvent,
|
||||
openVault,
|
||||
presentSheet,
|
||||
ToastManager
|
||||
ToastManager,
|
||||
VaultRequestType
|
||||
} from "../services/event-manager";
|
||||
import Navigation from "../services/navigation";
|
||||
import Notifications from "../services/notifications";
|
||||
@@ -106,6 +108,7 @@ export type ActionId =
|
||||
| "attachments"
|
||||
| "history"
|
||||
| "copy-link"
|
||||
| "copy-id"
|
||||
| "reminders"
|
||||
| "lock-unlock"
|
||||
| "publish"
|
||||
@@ -120,7 +123,8 @@ export type ActionId =
|
||||
| "default-homepage"
|
||||
| "default-tag"
|
||||
| "launcher-shortcut"
|
||||
| "expiry-date";
|
||||
| "expiry-date"
|
||||
| "spell-check";
|
||||
|
||||
export type Action = {
|
||||
id: ActionId;
|
||||
@@ -220,7 +224,15 @@ export const useActions = ({
|
||||
|
||||
useEffect(() => {
|
||||
if (item.type === "note") {
|
||||
db.vaults.itemExists(item).then((locked) => setLocked(locked));
|
||||
db.vaults.itemExists(item).then(async (locked) => {
|
||||
setLocked(locked);
|
||||
if (!locked) {
|
||||
const content = await db.content.findByNoteId(item.id);
|
||||
if (content && isEncryptedContent(content)) {
|
||||
setLocked(true);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}, [item]);
|
||||
|
||||
@@ -408,12 +420,12 @@ export const useActions = ({
|
||||
|
||||
if (item.type === "note" && (await db.vaults.itemExists(item))) {
|
||||
openVault({
|
||||
deleteNote: true,
|
||||
novault: true,
|
||||
locked: true,
|
||||
requestType: VaultRequestType.DeleteNote,
|
||||
item: item,
|
||||
title: strings.deleteNote(),
|
||||
description: strings.unlockToDelete()
|
||||
description: strings.unlockToDelete(),
|
||||
buttonTitle: strings.delete(),
|
||||
positiveButtonType: "errorShade"
|
||||
});
|
||||
} else {
|
||||
try {
|
||||
@@ -867,11 +879,10 @@ export const useActions = ({
|
||||
close();
|
||||
await sleep(300);
|
||||
openVault({
|
||||
requestType: VaultRequestType.ShareNote,
|
||||
item: item,
|
||||
novault: true,
|
||||
locked: true,
|
||||
share: true,
|
||||
title: strings.shareNote()
|
||||
title: strings.shareNote(),
|
||||
buttonTitle: strings.share()
|
||||
});
|
||||
} else {
|
||||
processingId.current = "shareNote";
|
||||
@@ -896,11 +907,10 @@ export const useActions = ({
|
||||
close();
|
||||
await sleep(300);
|
||||
openVault({
|
||||
requestType: VaultRequestType.PermanentUnlock,
|
||||
item: item,
|
||||
novault: true,
|
||||
locked: true,
|
||||
permanant: true,
|
||||
title: strings.unlockNote()
|
||||
title: strings.unlockNote(),
|
||||
buttonTitle: strings.unlock()
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -918,17 +928,18 @@ export const useActions = ({
|
||||
switch ((e as Error).message) {
|
||||
case VAULT_ERRORS.noVault:
|
||||
openVault({
|
||||
requestType: VaultRequestType.CreateVault,
|
||||
item: item,
|
||||
novault: false,
|
||||
title: strings.createVault()
|
||||
title: strings.createVault(),
|
||||
buttonTitle: strings.lock()
|
||||
});
|
||||
break;
|
||||
case VAULT_ERRORS.vaultLocked:
|
||||
openVault({
|
||||
requestType: VaultRequestType.LockNote,
|
||||
item: item,
|
||||
novault: true,
|
||||
locked: true,
|
||||
title: strings.lockNote()
|
||||
title: strings.lockNote(),
|
||||
buttonTitle: strings.lock()
|
||||
});
|
||||
break;
|
||||
}
|
||||
@@ -949,11 +960,10 @@ export const useActions = ({
|
||||
close();
|
||||
await sleep(300);
|
||||
openVault({
|
||||
copyNote: true,
|
||||
novault: true,
|
||||
locked: true,
|
||||
requestType: VaultRequestType.CopyNote,
|
||||
item: item as Note,
|
||||
title: strings.copyNote()
|
||||
title: strings.copyNote(),
|
||||
buttonTitle: strings.copy()
|
||||
});
|
||||
} else {
|
||||
processingId.current = "copyContent";
|
||||
@@ -984,6 +994,28 @@ export const useActions = ({
|
||||
pro: true,
|
||||
activeColor: "orange"
|
||||
},
|
||||
{
|
||||
id: "spell-check",
|
||||
title: strings.spellCheck(),
|
||||
icon: "spellcheck",
|
||||
isToggle: true,
|
||||
checked: item.spellcheck,
|
||||
onPress: async () => {
|
||||
db.notes.spellcheck(!item.spellcheck, item.id);
|
||||
const note = await db.notes.note(item.id);
|
||||
if (note) {
|
||||
setItem(note);
|
||||
const tabs = useTabStore.getState().getTabsForNote(note.id);
|
||||
tabs.forEach((tab) => {
|
||||
useTabStore.getState().updateTab(tab.id, {
|
||||
session: {
|
||||
spellCheckDisabled: !note.spellcheck
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
id: "remove-from-notebook",
|
||||
title: strings.removeFromNotebook(),
|
||||
@@ -1003,20 +1035,6 @@ export const useActions = ({
|
||||
icon: "history",
|
||||
onPress: openHistory
|
||||
},
|
||||
{
|
||||
id: "copy-link",
|
||||
title: strings.copyLink(),
|
||||
icon: "link",
|
||||
onPress: () => {
|
||||
Clipboard.setString(createInternalLink("note", item.id));
|
||||
ToastManager.show({
|
||||
heading: strings.linkCopied(),
|
||||
message: createInternalLink("note", item.id),
|
||||
context: "local",
|
||||
type: "success"
|
||||
});
|
||||
}
|
||||
},
|
||||
{
|
||||
id: "reminders",
|
||||
title: strings.dataTypesPluralCamelCase.reminder(),
|
||||
@@ -1272,5 +1290,45 @@ export const useActions = ({
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
item.type === "tag" ||
|
||||
item.type === "note" ||
|
||||
item.type === "notebook" ||
|
||||
item.type === "color"
|
||||
) {
|
||||
actions.push({
|
||||
id: "copy-link",
|
||||
title: strings.copyLink(),
|
||||
icon: "link",
|
||||
onPress: () => {
|
||||
const link = createInternalLink(item.type, item.id);
|
||||
Clipboard.setString(link);
|
||||
ToastManager.show({
|
||||
heading: strings.linkCopied(),
|
||||
message: link,
|
||||
context: "local",
|
||||
type: "success"
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (item.type === "notebook" || item.type === "tag") {
|
||||
actions.push({
|
||||
id: "copy-id",
|
||||
title: strings.copyId(),
|
||||
icon: "identifier",
|
||||
onPress: () => {
|
||||
Clipboard.setString(item.id);
|
||||
ToastManager.show({
|
||||
heading: strings.idCopied(),
|
||||
message: item.id,
|
||||
context: "local",
|
||||
type: "success"
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return actions;
|
||||
};
|
||||
|
||||
@@ -25,11 +25,14 @@ import {
|
||||
SYNC_CHECK_IDS,
|
||||
SubscriptionPlan,
|
||||
SyncStatusEvent,
|
||||
User
|
||||
User,
|
||||
isInternalLink,
|
||||
parseInternalLink
|
||||
} from "@notesnook/core";
|
||||
import { strings } from "@notesnook/intl";
|
||||
import notifee from "@notifee/react-native";
|
||||
import NetInfo, { NetInfoSubscription } from "@react-native-community/netinfo";
|
||||
import dayjs from "dayjs";
|
||||
import React, { useCallback, useEffect, useRef } from "react";
|
||||
import {
|
||||
AppState,
|
||||
@@ -48,6 +51,7 @@ import * as RNIap from "react-native-iap";
|
||||
import { DatabaseLogger, db, setupDatabase } from "../common/database";
|
||||
import { initializeLogger } from "../common/database/logger";
|
||||
import { MMKV } from "../common/database/mmkv";
|
||||
import { deleteDCacheFiles } from "../common/filesystem/io";
|
||||
import { endProgress, startProgress } from "../components/dialogs/progress";
|
||||
import Migrate from "../components/sheets/migrate";
|
||||
import NewFeature from "../components/sheets/new-feature";
|
||||
@@ -58,11 +62,7 @@ import {
|
||||
resetTabStore,
|
||||
useTabStore
|
||||
} from "../screens/editor/tiptap/use-tab-store";
|
||||
import {
|
||||
clearAppState,
|
||||
editorController,
|
||||
editorState
|
||||
} from "../screens/editor/tiptap/utils";
|
||||
import { editorController, editorState } from "../screens/editor/tiptap/utils";
|
||||
import { useDragState } from "../screens/settings/editor/state";
|
||||
import BackupService from "../services/backup";
|
||||
import BiometricService from "../services/biometrics";
|
||||
@@ -89,6 +89,7 @@ import { clearAllStores, initAfterSync } from "../stores";
|
||||
import { refreshAllStores } from "../stores/create-db-collection-store";
|
||||
import { useAttachmentStore } from "../stores/use-attachment-store";
|
||||
import { useMessageStore } from "../stores/use-message-store";
|
||||
import { useRelationStore } from "../stores/use-relation-store";
|
||||
import { useSettingStore } from "../stores/use-setting-store";
|
||||
import { SyncStatus, useUserStore } from "../stores/use-user-store";
|
||||
import { updateStatusBarColor } from "../utils/colors";
|
||||
@@ -105,12 +106,8 @@ import {
|
||||
} from "../utils/events";
|
||||
import { getGithubVersion } from "../utils/github-version";
|
||||
import { fluidTabsRef } from "../utils/global-refs";
|
||||
import { NotesnookModule } from "../utils/notesnook-module";
|
||||
import { sleep } from "../utils/time";
|
||||
import useFeatureManager from "./use-feature-manager";
|
||||
import { deleteDCacheFiles } from "../common/filesystem/io";
|
||||
import dayjs from "dayjs";
|
||||
import { useRelationStore } from "../stores/use-relation-store";
|
||||
|
||||
const onCheckSyncStatus = async (type: SyncStatusEvent) => {
|
||||
const { disableSync, disableAutoSync } = SettingsService.get();
|
||||
@@ -169,17 +166,22 @@ const onAppOpenedFromURL = async (event: {
|
||||
}) => {
|
||||
const url = event.url;
|
||||
|
||||
const parsedLink = isInternalLink(url) ? parseInternalLink(url) : undefined;
|
||||
|
||||
try {
|
||||
if (url.startsWith("https://app.notesnook.com/account/verified")) {
|
||||
await onUserEmailVerified();
|
||||
} else if (url.startsWith("ShareMedia://QuickNoteWidget")) {
|
||||
clearAppState();
|
||||
editorState().movedAway = false;
|
||||
eSendEvent(eOnLoadNote, { newNote: true });
|
||||
fluidTabsRef.current?.goToPage("editor", false);
|
||||
return;
|
||||
} else if (url.startsWith("https://app.notesnook.com/open_note?")) {
|
||||
const id = new URL(url).searchParams.get("id");
|
||||
} else if (
|
||||
parsedLink?.type === "note" ||
|
||||
url.startsWith("https://app.notesnook.com/open_note?")
|
||||
) {
|
||||
const id = parsedLink?.id || new URL(url).searchParams.get("id");
|
||||
|
||||
if (id) {
|
||||
const note = await db.notes.note(id);
|
||||
if (note) {
|
||||
@@ -191,13 +193,15 @@ const onAppOpenedFromURL = async (event: {
|
||||
}
|
||||
}
|
||||
} else if (
|
||||
url.startsWith("https://app.notesnook.com/open_notebook?") &&
|
||||
(parsedLink?.type === "notebook" ||
|
||||
url.startsWith("https://app.notesnook.com/open_notebook?")) &&
|
||||
!event.isInitialUrl
|
||||
) {
|
||||
const id = new URL(url).searchParams.get("id");
|
||||
const id = parsedLink?.id || new URL(url).searchParams.get("id");
|
||||
if (id) {
|
||||
const notebook = await db.notebooks.notebook(id);
|
||||
if (notebook) {
|
||||
fluidTabsRef.current?.goToPage("home");
|
||||
Navigation.navigate("Notebook", {
|
||||
id: notebook.id,
|
||||
canGoBack: true,
|
||||
@@ -206,13 +210,15 @@ const onAppOpenedFromURL = async (event: {
|
||||
}
|
||||
}
|
||||
} else if (
|
||||
url.startsWith("https://app.notesnook.com/open_tag?") &&
|
||||
(parsedLink?.type === "tag" ||
|
||||
url.startsWith("https://app.notesnook.com/open_tag?")) &&
|
||||
!event.isInitialUrl
|
||||
) {
|
||||
const id = new URL(url).searchParams.get("id");
|
||||
const id = parsedLink?.id || new URL(url).searchParams.get("id");
|
||||
if (id) {
|
||||
const tag = await db.tags.tag(id);
|
||||
if (tag) {
|
||||
fluidTabsRef.current?.goToPage("home");
|
||||
Navigation.navigate("TaggedNotes", {
|
||||
type: "tag",
|
||||
id: tag.id,
|
||||
@@ -222,13 +228,15 @@ const onAppOpenedFromURL = async (event: {
|
||||
}
|
||||
}
|
||||
} else if (
|
||||
url.startsWith("https://app.notesnook.com/open_color?") &&
|
||||
(parsedLink?.type === "color" ||
|
||||
url.startsWith("https://app.notesnook.com/open_color?")) &&
|
||||
!event.isInitialUrl
|
||||
) {
|
||||
const id = new URL(url).searchParams.get("id");
|
||||
const id = parsedLink?.id || new URL(url).searchParams.get("id");
|
||||
if (id) {
|
||||
const color = await db.colors.color(id);
|
||||
if (color) {
|
||||
fluidTabsRef.current?.goToPage("home");
|
||||
Navigation.navigate("ColoredNotes", {
|
||||
type: "color",
|
||||
id: color.id,
|
||||
@@ -361,23 +369,6 @@ async function checkForShareExtensionLaunchedInBackground() {
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
async function saveEditorState() {
|
||||
if (!editorState().movedAway) {
|
||||
const id = useTabStore.getState().getCurrentNoteId();
|
||||
const note = id ? await db.notes.note(id) : undefined;
|
||||
const locked = note && (await db.vaults.itemExists(note));
|
||||
if (locked) return;
|
||||
const state = JSON.stringify({
|
||||
editing: editorState().currentlyEditing,
|
||||
movedAway: editorState().movedAway,
|
||||
timestamp: Date.now()
|
||||
});
|
||||
NotesnookModule.setAppState(state);
|
||||
} else {
|
||||
NotesnookModule.setAppState("");
|
||||
}
|
||||
}
|
||||
|
||||
const onSuccessfulSubscription = async (
|
||||
subscription: RNIap.ProductPurchase | RNIap.SubscriptionPurchase
|
||||
) => {
|
||||
@@ -563,6 +554,7 @@ export const useAppEvents = () => {
|
||||
initialUrl: string;
|
||||
backupDidWait: boolean;
|
||||
isConnectingSSE: boolean;
|
||||
attachmentsCachedOfflineMode: boolean;
|
||||
}>
|
||||
>({});
|
||||
|
||||
@@ -591,13 +583,13 @@ export const useAppEvents = () => {
|
||||
}, [isAppLoading, onSyncComplete]);
|
||||
|
||||
useEffect(() => {
|
||||
if (initialUrl) {
|
||||
if (initialUrl && !isAppLoading) {
|
||||
onAppOpenedFromURL({
|
||||
url: initialUrl!,
|
||||
isInitialUrl: true
|
||||
});
|
||||
}
|
||||
}, [initialUrl]);
|
||||
}, [initialUrl, isAppLoading]);
|
||||
|
||||
const subscribeToPurchaseListeners = useCallback(async () => {
|
||||
if (Platform.OS === "android") {
|
||||
@@ -657,7 +649,11 @@ export const useAppEvents = () => {
|
||||
}
|
||||
}
|
||||
|
||||
if (SettingsService.getProperty("offlineMode")) {
|
||||
if (
|
||||
SettingsService.getProperty("offlineMode") &&
|
||||
!refValues.current.attachmentsCachedOfflineMode
|
||||
) {
|
||||
refValues.current.attachmentsCachedOfflineMode = true;
|
||||
db.attachments.cacheAttachments().catch(() => {
|
||||
/* empty */
|
||||
});
|
||||
@@ -833,7 +829,6 @@ export const useAppEvents = () => {
|
||||
Sync.run("global", false, "full");
|
||||
reconnectSSE();
|
||||
await checkForShareExtensionLaunchedInBackground();
|
||||
NotesnookModule.setAppState("");
|
||||
let user = await db.user.getUser();
|
||||
if (user && !user?.isEmailConfirmed) {
|
||||
try {
|
||||
@@ -856,7 +851,6 @@ export const useAppEvents = () => {
|
||||
eSendEvent(eEditorReset);
|
||||
}
|
||||
} else {
|
||||
await saveEditorState();
|
||||
if (
|
||||
SettingsService.canLockAppInBackground() &&
|
||||
!useSettingStore.getState().requestBiometrics &&
|
||||
|
||||
@@ -60,23 +60,17 @@ export const useDBItem = <T extends keyof ItemTypeKey>(
|
||||
): [ItemTypeKey[T] | undefined, () => void] => {
|
||||
const [item, setItem] = useState<ItemTypeKey[T]>();
|
||||
const itemIdRef = useRef<string>(undefined);
|
||||
const prevIdOrIndexRef = useRef<string | number>(undefined);
|
||||
|
||||
if (prevIdOrIndexRef.current !== idOrIndex) {
|
||||
itemIdRef.current = undefined;
|
||||
prevIdOrIndexRef.current = idOrIndex;
|
||||
}
|
||||
const itemsRef = useRef(item);
|
||||
itemsRef.current = item;
|
||||
|
||||
useEffect(() => {
|
||||
const onUpdateItem = async (itemId?: string) => {
|
||||
if (typeof itemId === "string" && itemId !== itemIdRef.current) return;
|
||||
if (!isValidIdOrIndex(idOrIndex)) return;
|
||||
|
||||
let item: ItemTypeKey[T] | undefined = undefined;
|
||||
if (items && typeof idOrIndex === "number") {
|
||||
const item = (await items.item(idOrIndex))?.item;
|
||||
setItem(item);
|
||||
itemIdRef.current = item?.id;
|
||||
onItemUpdated?.(item);
|
||||
item = (await items.item(idOrIndex))?.item;
|
||||
} else {
|
||||
if (!(db as any)[type + "s"][type]) {
|
||||
console.warn(
|
||||
@@ -84,24 +78,30 @@ export const useDBItem = <T extends keyof ItemTypeKey>(
|
||||
`db.${type}s.${type}(id: string)`
|
||||
);
|
||||
} else {
|
||||
const item = await (db as any)[type + "s"]?.[type]?.(
|
||||
idOrIndex as string
|
||||
);
|
||||
setItem(item);
|
||||
itemIdRef.current = item.id;
|
||||
onItemUpdated?.(item);
|
||||
item = await (db as any)[type + "s"]?.[type]?.(idOrIndex as string);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if (
|
||||
itemsRef.current === item ||
|
||||
itemsRef.current?.dateModified === item?.dateModified
|
||||
)
|
||||
return;
|
||||
setItem(item);
|
||||
itemIdRef.current = item?.id;
|
||||
onItemUpdated?.(item);
|
||||
};
|
||||
let unsub: (() => void) | undefined;
|
||||
if (
|
||||
useSettingStore.getState().isAppLoading &&
|
||||
//@ts-ignore
|
||||
!globalThis["IS_SHARE_EXTENSION"]
|
||||
) {
|
||||
useSettingStore.subscribe((state) => {
|
||||
unsub = useSettingStore.subscribe((state) => {
|
||||
if (!state.isAppLoading) {
|
||||
onUpdateItem();
|
||||
unsub?.();
|
||||
unsub = undefined;
|
||||
}
|
||||
});
|
||||
} else {
|
||||
@@ -109,9 +109,10 @@ export const useDBItem = <T extends keyof ItemTypeKey>(
|
||||
}
|
||||
eSubscribeEvent(eDBItemUpdate, onUpdateItem);
|
||||
return () => {
|
||||
unsub?.();
|
||||
eUnSubscribeEvent(eDBItemUpdate, onUpdateItem);
|
||||
};
|
||||
}, [idOrIndex, type, items, onItemUpdated]);
|
||||
}, [idOrIndex, type, items]);
|
||||
|
||||
return [
|
||||
isValidIdOrIndex(idOrIndex) ? (item as ItemTypeKey[T]) : undefined,
|
||||
@@ -134,8 +135,9 @@ export const useNoteLocked = (noteId: string | undefined) => {
|
||||
//@ts-ignore
|
||||
!globalThis["IS_SHARE_EXTENSION"]
|
||||
) {
|
||||
useSettingStore.subscribe((state) => {
|
||||
let unsub = useSettingStore.subscribe((state) => {
|
||||
if (!state.isAppLoading) {
|
||||
unsub();
|
||||
db.vaults
|
||||
.itemExists({
|
||||
type: "note",
|
||||
@@ -181,25 +183,27 @@ export const useTotalNotes = (type: "notebook" | "tag" | "color") => {
|
||||
const [totalNotesById, setTotalNotesById] = useState<{
|
||||
[id: string]: number;
|
||||
}>({});
|
||||
const totalNotesRef = useRef(0);
|
||||
|
||||
const getTotalNotes = React.useCallback(
|
||||
(ids: string[]) => {
|
||||
if (!ids || !ids.length || !type) return;
|
||||
db.relations
|
||||
.from({ type: type, ids: ids as string[] }, ["note"])
|
||||
.get()
|
||||
.then((relations) => {
|
||||
const totalNotesById: any = {};
|
||||
for (const id of ids) {
|
||||
totalNotesById[id] = relations.filter(
|
||||
(relation) => relation.fromId === id && relation.toType === "note"
|
||||
)?.length;
|
||||
}
|
||||
setTotalNotesById(totalNotesById);
|
||||
});
|
||||
},
|
||||
[type]
|
||||
);
|
||||
const getTotalNotes = React.useCallback((ids: string[]) => {
|
||||
if (!ids || !ids.length || !type) return;
|
||||
db.relations
|
||||
.from({ type: type, ids: ids as string[] }, ["note"])
|
||||
.get()
|
||||
.then((relations) => {
|
||||
const totalNotesById: any = {};
|
||||
|
||||
for (const id of ids) {
|
||||
totalNotesById[id] = relations.filter(
|
||||
(relation) => relation.fromId === id && relation.toType === "note"
|
||||
)?.length;
|
||||
}
|
||||
|
||||
if (totalNotesById === totalNotesRef.current) return;
|
||||
totalNotesRef.current = totalNotesById;
|
||||
setTotalNotesById(totalNotesById);
|
||||
});
|
||||
}, []);
|
||||
|
||||
return {
|
||||
totalNotes: (id: string) => {
|
||||
|
||||
@@ -276,8 +276,8 @@ const usePricingPlans = (options?: PricingPlansOptions) => {
|
||||
(product as Plan).period === "yearly"
|
||||
? (product as Plan).price.gross
|
||||
: (product as Plan).period === "5-year"
|
||||
? (product as Plan).price.gross
|
||||
: (product as Plan).price.gross
|
||||
? (product as Plan).price.gross
|
||||
: (product as Plan).price.gross
|
||||
}`;
|
||||
}
|
||||
|
||||
@@ -432,8 +432,8 @@ const usePricingPlans = (options?: PricingPlansOptions) => {
|
||||
return period.endsWith("W")
|
||||
? "week"
|
||||
: period.endsWith("M")
|
||||
? "month"
|
||||
: "year";
|
||||
? "month"
|
||||
: "year";
|
||||
} else {
|
||||
const unit = (product as RNIap.SubscriptionIOS)
|
||||
?.subscriptionPeriodUnitIOS;
|
||||
@@ -475,8 +475,8 @@ const usePricingPlans = (options?: PricingPlansOptions) => {
|
||||
type: phase.billingPeriod.endsWith("W")
|
||||
? "week"
|
||||
: phase.billingPeriod.endsWith("M")
|
||||
? "month"
|
||||
: "year"
|
||||
? "month"
|
||||
: "year"
|
||||
};
|
||||
} else {
|
||||
const productIos = product as RNIap.SubscriptionIOS;
|
||||
@@ -607,8 +607,8 @@ const usePricingPlans = (options?: PricingPlansOptions) => {
|
||||
(product as Plan).period === "yearly"
|
||||
? ((product as Plan).price.gross / 12).toFixed(2)
|
||||
: (product as Plan).period === "5-year"
|
||||
? ((product as Plan).price.gross / (12 * 5)).toFixed(2)
|
||||
: (product as Plan).price.gross
|
||||
? ((product as Plan).price.gross / (12 * 5)).toFixed(2)
|
||||
: (product as Plan).price.gross
|
||||
}`;
|
||||
}
|
||||
|
||||
|
||||
@@ -21,7 +21,6 @@ import { useEffect } from "react";
|
||||
import { NativeEventEmitter, NativeModule } from "react-native";
|
||||
import { useRef } from "react";
|
||||
import { Platform } from "react-native";
|
||||
import { Linking } from "react-native";
|
||||
import deviceInfoModule from "react-native-device-info";
|
||||
import { strings } from "@notesnook/intl";
|
||||
const ShortcutsEmitter = new NativeEventEmitter(
|
||||
@@ -54,14 +53,9 @@ export const useShortcutManager = ({
|
||||
}, [shortcuts]);
|
||||
|
||||
useEffect(() => {
|
||||
Linking.getInitialURL().then((url) => {
|
||||
if (url?.startsWith("ShareMedia://QuickNoteWidget")) {
|
||||
onShortcutPressed(defaultShortcuts[0]);
|
||||
}
|
||||
});
|
||||
if (!isSupported()) return;
|
||||
Shortcuts.getInitialShortcut().then((shortcut) => {
|
||||
if (initialShortcutRecieved.current) return;
|
||||
if (initialShortcutRecieved.current || !shortcut) return;
|
||||
onShortcutPressed(shortcut);
|
||||
initialShortcutRecieved.current = true;
|
||||
});
|
||||
|
||||
@@ -47,12 +47,7 @@ import useGlobalSafeAreaInsets from "../hooks/use-global-safe-area-insets";
|
||||
import { useShortcutManager } from "../hooks/use-shortcut-manager";
|
||||
import { hideAllTooltips } from "../hooks/use-tooltip";
|
||||
import { useTabStore } from "../screens/editor/tiptap/use-tab-store";
|
||||
import {
|
||||
clearAppState,
|
||||
editorController,
|
||||
editorState,
|
||||
getAppState
|
||||
} from "../screens/editor/tiptap/utils";
|
||||
import { editorController, editorState } from "../screens/editor/tiptap/utils";
|
||||
import { DDS } from "../services/device-detection";
|
||||
import {
|
||||
eSendEvent,
|
||||
@@ -118,13 +113,9 @@ export const FluidPanelsView = React.memo(
|
||||
|
||||
useShortcutManager({
|
||||
onShortcutPressed: async (item) => {
|
||||
if (!item && getAppState()) {
|
||||
editorState().movedAway = false;
|
||||
fluidTabsRef.current?.goToPage("editor", false);
|
||||
return;
|
||||
}
|
||||
if (!item) return;
|
||||
|
||||
if (item?.type === "notesnook.action.newnote") {
|
||||
clearAppState();
|
||||
if (!fluidTabsRef.current) {
|
||||
setTimeout(() => {
|
||||
eSendEvent(eOnLoadNote, { newNote: true });
|
||||
@@ -205,7 +196,6 @@ export const FluidPanelsView = React.memo(
|
||||
eSendEvent(eCloseFullscreenEditor, current);
|
||||
}
|
||||
|
||||
const state = getAppState();
|
||||
setTimeout(() => {
|
||||
switch (current) {
|
||||
case "tablet":
|
||||
@@ -217,18 +207,10 @@ export const FluidPanelsView = React.memo(
|
||||
}
|
||||
break;
|
||||
case "mobile":
|
||||
if (
|
||||
state &&
|
||||
editorState().movedAway === false &&
|
||||
useTabStore.getState().getCurrentNoteId()
|
||||
) {
|
||||
fluidTabsRef.current?.goToPage("editor", false);
|
||||
} else {
|
||||
fluidTabsRef.current?.goToPage(
|
||||
fluidTabsRef.current?.page(),
|
||||
false
|
||||
);
|
||||
}
|
||||
fluidTabsRef.current?.goToPage(
|
||||
fluidTabsRef.current?.page(),
|
||||
false
|
||||
);
|
||||
break;
|
||||
}
|
||||
}, 0);
|
||||
|
||||
@@ -31,6 +31,7 @@ import { useSettingStore } from "../stores/use-setting-store";
|
||||
import { rootNavigatorRef } from "../utils/global-refs";
|
||||
import Navigation from "../services/navigation";
|
||||
import { isFeatureAvailable } from "@notesnook/common";
|
||||
import { isInternalLink, parseInternalLink } from "@notesnook/core";
|
||||
|
||||
const RootStack = createNativeStackNavigator();
|
||||
const AppStack = createNativeStackNavigator();
|
||||
@@ -63,10 +64,17 @@ const AppNavigation = React.memo(
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!home) {
|
||||
if (useSettingStore.getState().initialUrl) {
|
||||
const url = useSettingStore.getState().initialUrl;
|
||||
if (url?.startsWith("https://app.notesnook.com/open_notebook?")) {
|
||||
const id = new URL(url).searchParams.get("id");
|
||||
const url = useSettingStore.getState().initialUrl;
|
||||
if (url) {
|
||||
const parsedLink = isInternalLink(url)
|
||||
? parseInternalLink(url)
|
||||
: undefined;
|
||||
|
||||
if (
|
||||
parsedLink?.type === "notebook" ||
|
||||
url?.startsWith("https://app.notesnook.com/open_notebook?")
|
||||
) {
|
||||
const id = parsedLink?.id || new URL(url).searchParams.get("id");
|
||||
if (id) {
|
||||
setHome({
|
||||
name: "Notebook",
|
||||
@@ -76,8 +84,11 @@ const AppNavigation = React.memo(
|
||||
});
|
||||
return;
|
||||
}
|
||||
} else if (url?.startsWith("https://app.notesnook.com/open_tag?")) {
|
||||
const id = new URL(url).searchParams.get("id");
|
||||
} else if (
|
||||
parsedLink?.type === "tag" ||
|
||||
url?.startsWith("https://app.notesnook.com/open_tag?")
|
||||
) {
|
||||
const id = parsedLink?.id || new URL(url).searchParams.get("id");
|
||||
if (id) {
|
||||
setHome({
|
||||
name: "TaggedNotes",
|
||||
@@ -88,8 +99,11 @@ const AppNavigation = React.memo(
|
||||
});
|
||||
return;
|
||||
}
|
||||
} else if (url?.startsWith("https://app.notesnook.com/open_color?")) {
|
||||
const id = new URL(url).searchParams.get("id");
|
||||
} else if (
|
||||
parsedLink?.type === "color" ||
|
||||
url?.startsWith("https://app.notesnook.com/open_color?")
|
||||
) {
|
||||
const id = parsedLink?.id || new URL(url).searchParams.get("id");
|
||||
if (id) {
|
||||
setHome({
|
||||
name: "ColoredNotes",
|
||||
|
||||
@@ -400,45 +400,17 @@ export default function AddReminder(props: NavigationProps<"AddReminder">) {
|
||||
recurringMode === RecurringModes.Year
|
||||
? null
|
||||
: recurringMode === RecurringModes.Week
|
||||
? (weekFormat === "Mon" ? WeekDaysMon : WeekDays).map(
|
||||
(item) => (
|
||||
<Button
|
||||
key={strings.weekDayNamesShort[
|
||||
item as keyof typeof strings.weekDayNamesShort
|
||||
]()}
|
||||
title={strings.weekDayNamesShort[
|
||||
item as keyof typeof strings.weekDayNamesShort
|
||||
]()}
|
||||
type={
|
||||
selectedDays.indexOf(item) > -1
|
||||
? "selected"
|
||||
: "plain"
|
||||
}
|
||||
fontSize={AppFontSize.xs}
|
||||
style={{
|
||||
height: 40,
|
||||
borderRadius: 100,
|
||||
marginRight: 10
|
||||
}}
|
||||
onPress={() => {
|
||||
setSelectedDays((days) => {
|
||||
if (days.indexOf(item) > -1) {
|
||||
days.splice(days.indexOf(item), 1);
|
||||
return [...days];
|
||||
}
|
||||
days.push(item);
|
||||
return [...days];
|
||||
});
|
||||
}}
|
||||
/>
|
||||
)
|
||||
)
|
||||
: MonthDays.map((item, index) => (
|
||||
? (weekFormat === "Mon" ? WeekDaysMon : WeekDays).map(
|
||||
(item) => (
|
||||
<Button
|
||||
key={index + "monthday"}
|
||||
title={index + 1 + ""}
|
||||
key={strings.weekDayNamesShort[
|
||||
item as keyof typeof strings.weekDayNamesShort
|
||||
]()}
|
||||
title={strings.weekDayNamesShort[
|
||||
item as keyof typeof strings.weekDayNamesShort
|
||||
]()}
|
||||
type={
|
||||
selectedDays.indexOf(index + 1) > -1
|
||||
selectedDays.indexOf(item) > -1
|
||||
? "selected"
|
||||
: "plain"
|
||||
}
|
||||
@@ -450,16 +422,44 @@ export default function AddReminder(props: NavigationProps<"AddReminder">) {
|
||||
}}
|
||||
onPress={() => {
|
||||
setSelectedDays((days) => {
|
||||
if (days.indexOf(index + 1) > -1) {
|
||||
days.splice(days.indexOf(index + 1), 1);
|
||||
if (days.indexOf(item) > -1) {
|
||||
days.splice(days.indexOf(item), 1);
|
||||
return [...days];
|
||||
}
|
||||
days.push(index + 1);
|
||||
days.push(item);
|
||||
return [...days];
|
||||
});
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
)
|
||||
)
|
||||
: MonthDays.map((item, index) => (
|
||||
<Button
|
||||
key={index + "monthday"}
|
||||
title={index + 1 + ""}
|
||||
type={
|
||||
selectedDays.indexOf(index + 1) > -1
|
||||
? "selected"
|
||||
: "plain"
|
||||
}
|
||||
fontSize={AppFontSize.xs}
|
||||
style={{
|
||||
height: 40,
|
||||
borderRadius: 100,
|
||||
marginRight: 10
|
||||
}}
|
||||
onPress={() => {
|
||||
setSelectedDays((days) => {
|
||||
if (days.indexOf(index + 1) > -1) {
|
||||
days.splice(days.indexOf(index + 1), 1);
|
||||
return [...days];
|
||||
}
|
||||
days.push(index + 1);
|
||||
return [...days];
|
||||
});
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</ScrollView>
|
||||
</View>
|
||||
) : null}
|
||||
@@ -542,24 +542,24 @@ export default function AddReminder(props: NavigationProps<"AddReminder">) {
|
||||
dayjs(date).format("hh:mm A")
|
||||
)
|
||||
: recurringMode === RecurringModes.Year
|
||||
? strings.reminderRepeatStrings.year(
|
||||
dayjs(date).format("dddd, MMMM D, h:mm A")
|
||||
)
|
||||
: selectedDays.length === 7 &&
|
||||
recurringMode === RecurringModes.Week
|
||||
? strings.reminderRepeatStrings.week.daily(
|
||||
dayjs(date).format("hh:mm A")
|
||||
)
|
||||
: selectedDays.length === 0
|
||||
? strings.reminderRepeatStrings[
|
||||
recurringMode as "week" | "month"
|
||||
].selectDays()
|
||||
: strings.reminderRepeatStrings.repeats(
|
||||
repeatFrequency,
|
||||
recurringMode as string,
|
||||
getSelectedDaysText(selectedDays),
|
||||
dayjs(date).format("hh:mm A")
|
||||
)}
|
||||
? strings.reminderRepeatStrings.year(
|
||||
dayjs(date).format("dddd, MMMM D, h:mm A")
|
||||
)
|
||||
: selectedDays.length === 7 &&
|
||||
recurringMode === RecurringModes.Week
|
||||
? strings.reminderRepeatStrings.week.daily(
|
||||
dayjs(date).format("hh:mm A")
|
||||
)
|
||||
: selectedDays.length === 0
|
||||
? strings.reminderRepeatStrings[
|
||||
recurringMode as "week" | "month"
|
||||
].selectDays()
|
||||
: strings.reminderRepeatStrings.repeats(
|
||||
repeatFrequency,
|
||||
recurringMode as string,
|
||||
getSelectedDaysText(selectedDays),
|
||||
dayjs(date).format("hh:mm A")
|
||||
)}
|
||||
</Paragraph>
|
||||
</>
|
||||
</View>
|
||||
@@ -587,8 +587,8 @@ export default function AddReminder(props: NavigationProps<"AddReminder">) {
|
||||
mode === "Silent"
|
||||
? "minus-circle"
|
||||
: mode === "Vibrate"
|
||||
? "vibrate"
|
||||
: "volume-high"
|
||||
? "vibrate"
|
||||
: "volume-high"
|
||||
}
|
||||
fontSize={AppFontSize.xs}
|
||||
height={35}
|
||||
|
||||
@@ -183,6 +183,7 @@ const Editor = React.memo(
|
||||
hideKeyboardAccessoryView={false}
|
||||
allowsFullscreenVideo={true}
|
||||
allowFileAccessFromFileURLs={true}
|
||||
allowsInlineMediaPlayback
|
||||
allowUniversalAccessFromFileURLs={true}
|
||||
originWhitelist={["*"]}
|
||||
source={{
|
||||
|
||||
@@ -19,7 +19,6 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
import Sodium from "@ammarahmed/react-native-sodium";
|
||||
import { isFeatureAvailable } from "@notesnook/common";
|
||||
import { isImage } from "@notesnook/core";
|
||||
import { strings } from "@notesnook/intl";
|
||||
import {
|
||||
DocumentPickerOptions,
|
||||
@@ -90,6 +89,7 @@ const file = async (fileOptions: PickerOptions) => {
|
||||
message: featureResult.error,
|
||||
type: "error"
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (fileCopyUri.status === "error") {
|
||||
@@ -272,6 +272,7 @@ const handleImageResponse = async (
|
||||
message: featureResult.error,
|
||||
type: "error"
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const b64 = `data:${image.mime};base64, ` + image.data;
|
||||
|
||||
@@ -20,7 +20,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
/* eslint-disable no-case-declarations */
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
import { isFeatureAvailable, useAreFeaturesAvailable } from "@notesnook/common";
|
||||
import { ItemReference } from "@notesnook/core";
|
||||
import { ItemReference, parseInternalLink } from "@notesnook/core";
|
||||
import type { Attachment } from "@notesnook/editor";
|
||||
import { EditorEvents } from "@notesnook/editor-mobile/src/utils/editor-events";
|
||||
import { NativeEvents } from "@notesnook/editor-mobile/src/utils/native-events";
|
||||
@@ -532,17 +532,78 @@ export const useEditorEvents = (
|
||||
downloadAttachment((editorMessage.value as Attachment)?.hash, true);
|
||||
break;
|
||||
}
|
||||
case EditorEvents.getLinkData: {
|
||||
const url = (editorMessage.value as any)?.url as string;
|
||||
const link = parseInternalLink(url);
|
||||
if (!link) return;
|
||||
switch (link.type) {
|
||||
case "note":
|
||||
case "notebook":
|
||||
case "tag": {
|
||||
const table =
|
||||
link.type === "note"
|
||||
? "notes"
|
||||
: link.type === "notebook"
|
||||
? "notebooks"
|
||||
: "tags";
|
||||
const item = await db
|
||||
.sql()
|
||||
.selectFrom(table)
|
||||
.where("id", "=", link.id)
|
||||
.select("title")
|
||||
.executeTakeFirst();
|
||||
|
||||
editor.postMessage(NativeEvents.resolve, {
|
||||
resolverId: editorMessage.resolverId,
|
||||
data: {
|
||||
type: link.type,
|
||||
title: item?.title || ""
|
||||
}
|
||||
});
|
||||
break;
|
||||
}
|
||||
case "color": {
|
||||
const color = await db
|
||||
.sql()
|
||||
.selectFrom("colors")
|
||||
.where("id", "=", link.id)
|
||||
.select(["title", "colorCode"])
|
||||
.executeTakeFirst();
|
||||
|
||||
editor.postMessage(NativeEvents.resolve, {
|
||||
resolverId: editorMessage.resolverId,
|
||||
data: {
|
||||
type: "color",
|
||||
title: color?.title || "",
|
||||
metadata: {
|
||||
colorCode: color?.colorCode || ""
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case EditorEvents.getAttachmentData: {
|
||||
const attachment = (editorMessage.value as any)
|
||||
?.attachment as Attachment;
|
||||
const data = (editorMessage.value as any)?.attachment as Attachment;
|
||||
|
||||
const attachment = await db.attachments.attachment(data.hash);
|
||||
|
||||
if (!attachment) {
|
||||
editor.postMessage(NativeEvents.resolve, {
|
||||
resolverId: editorMessage.resolverId,
|
||||
data: undefined
|
||||
});
|
||||
break;
|
||||
}
|
||||
DatabaseLogger.log(
|
||||
`Getting attachment data: ${attachment?.hash} ${attachment?.type}`
|
||||
`Getting attachment data: ${attachment.mimeType} ${attachment.hash} ${data.type}`
|
||||
);
|
||||
downloadAttachment(attachment.hash, true, {
|
||||
base64: attachment.type === "image",
|
||||
text: attachment.type === "web-clip",
|
||||
base64:
|
||||
data.type === "image" || attachment.mimeType?.startsWith("audio"),
|
||||
text: data.type === "web-clip",
|
||||
silent: true,
|
||||
groupId: editor.note.current?.id,
|
||||
cache: true
|
||||
|
||||
@@ -69,14 +69,7 @@ import Commands from "./commands";
|
||||
import { SessionHistory } from "./session-history";
|
||||
import { EditorState, SavePayload } from "./types";
|
||||
import { TabSessionItem, syncTabs, useTabStore } from "./use-tab-store";
|
||||
import {
|
||||
clearAppState,
|
||||
defaultState,
|
||||
getAppState,
|
||||
isContentInvalid,
|
||||
isEditorLoaded,
|
||||
post
|
||||
} from "./utils";
|
||||
import { defaultState, isContentInvalid, isEditorLoaded, post } from "./utils";
|
||||
import { Linking } from "react-native";
|
||||
|
||||
const loadNoteMutex = new Mutex();
|
||||
@@ -167,7 +160,7 @@ export const useEditor = (
|
||||
const tags = useTagStore((state) => state.items);
|
||||
const insets = useGlobalSafeAreaInsets();
|
||||
const isDefaultEditor = editorId === "";
|
||||
const saveCount = useRef(0);
|
||||
const saveCount = useRef<Record<string, number>>({});
|
||||
const lastContentChangeTime = useRef<Record<string, number>>({});
|
||||
const lock = useRef(false);
|
||||
const currentLoadingNoteId = useRef<string>(undefined);
|
||||
@@ -253,9 +246,9 @@ export const useEditor = (
|
||||
clearTimeout(timers.current["loading-images" + noteId]);
|
||||
}
|
||||
|
||||
saveCount.current = 0;
|
||||
currentLoadingNoteId.current = undefined;
|
||||
lock.current = false;
|
||||
saveCount.current[tabId] = 0;
|
||||
resetContent && postMessage(NativeEvents.title, "", tabId);
|
||||
resetContent && (await commands.clearContent(tabId));
|
||||
resetContent && (await commands.clearTags(tabId));
|
||||
@@ -285,7 +278,8 @@ export const useEditor = (
|
||||
locked: undefined,
|
||||
readonly: undefined,
|
||||
scrollTop: undefined,
|
||||
selection: undefined
|
||||
selection: undefined,
|
||||
spellCheckDisabled: false
|
||||
}
|
||||
});
|
||||
return;
|
||||
@@ -388,7 +382,7 @@ export const useEditor = (
|
||||
|
||||
if (
|
||||
oldNote?.title !== currentNotes.current[id]?.title &&
|
||||
!noteData.title
|
||||
typeof noteData.title === "undefined"
|
||||
) {
|
||||
postMessage(
|
||||
NativeEvents.title,
|
||||
@@ -436,10 +430,9 @@ export const useEditor = (
|
||||
lastContentChangeTime.current[id] = note.dateEdited;
|
||||
|
||||
if (
|
||||
saveCount.current < 2 ||
|
||||
saveCount.current[tabId] < 2 ||
|
||||
currentNotes.current[id]?.title !== note.title ||
|
||||
currentNotes.current[id]?.headline?.slice(0, 200) !==
|
||||
note.headline?.slice(0, 200)
|
||||
currentNotes.current[id]?.headline !== note.headline
|
||||
) {
|
||||
Navigation.queueRoutesForUpdate();
|
||||
}
|
||||
@@ -455,7 +448,11 @@ export const useEditor = (
|
||||
currentNotes.current[id] = note;
|
||||
}
|
||||
|
||||
saveCount.current++;
|
||||
if (!saveCount.current[tabId]) {
|
||||
saveCount.current[tabId] = 1;
|
||||
} else {
|
||||
saveCount.current[tabId]++;
|
||||
}
|
||||
|
||||
clearTimeout(timers.current.onsave);
|
||||
timers.current.onsave = setTimeout(async () => {
|
||||
@@ -487,6 +484,17 @@ export const useEditor = (
|
||||
};
|
||||
} else if (note.contentId) {
|
||||
const rawContent = await db.content?.get(note.contentId);
|
||||
|
||||
if (rawContent && isEncryptedContent(rawContent)) {
|
||||
useTabStore.getState().updateTab(useTabStore.getState().currentTab, {
|
||||
session: {
|
||||
noteLocked: true,
|
||||
locked: true
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (rawContent && !isDeleted(rawContent) && !rawContent.locked) {
|
||||
currentContents.current[note.id] = {
|
||||
data: rawContent.data,
|
||||
@@ -553,6 +561,7 @@ export const useEditor = (
|
||||
useTabStore.getState().newTabSession(tabId, {});
|
||||
}
|
||||
}
|
||||
saveCount.current[tabId] = 0;
|
||||
|
||||
setTimeout(() => {
|
||||
if (state.current?.ready && !state.current.movedAway)
|
||||
@@ -640,6 +649,7 @@ export const useEditor = (
|
||||
session.noteLocked = isLockedNote;
|
||||
session.locked = tabLocked;
|
||||
session.readonly = item.readonly;
|
||||
session.spellCheckDisabled = !item.spellcheck;
|
||||
|
||||
const tab = useTabStore.getState().getTab(tabId!);
|
||||
|
||||
@@ -685,6 +695,7 @@ export const useEditor = (
|
||||
currentNotes.current[item.id] = item;
|
||||
|
||||
editorSessionHistory.newSession(item.id);
|
||||
saveCount.current[tabId] = 0;
|
||||
|
||||
await commands.setStatus(
|
||||
getFormattedDate(item.dateEdited, "date-time"),
|
||||
@@ -1014,22 +1025,11 @@ export const useEditor = (
|
||||
);
|
||||
|
||||
const restoreEditorState = useCallback(async () => {
|
||||
const appState = getAppState();
|
||||
if (!appState) return;
|
||||
state.current.isRestoringState = true;
|
||||
state.current.currentlyEditing = true;
|
||||
if (fluidTabsRef.current?.page() === "editor") {
|
||||
state.current.movedAway = false;
|
||||
}
|
||||
if (!state.current.editorStateRestored) {
|
||||
state.current.isRestoringState = true;
|
||||
if (!DDS.isTab) {
|
||||
fluidTabsRef.current?.goToPage("editor", false);
|
||||
}
|
||||
}
|
||||
|
||||
clearAppState();
|
||||
state.current.isRestoringState = false;
|
||||
}, []);
|
||||
|
||||
const onContentChanged = (noteId?: string) => {
|
||||
|
||||
@@ -86,6 +86,7 @@ export type TabSessionItem = {
|
||||
noteLocked?: boolean;
|
||||
locked?: boolean;
|
||||
readonly?: boolean;
|
||||
spellCheckDisabled: boolean;
|
||||
};
|
||||
|
||||
const TabSessionStorageKV = new MMKVLoader()
|
||||
@@ -187,6 +188,7 @@ export type TabStore = {
|
||||
focusEmptyTab: () => void;
|
||||
getCurrentNoteId: () => string | undefined;
|
||||
getTab: (tabId: string) => TabItem | undefined;
|
||||
clearAllTabs: () => void;
|
||||
newTabSession: (
|
||||
id: string,
|
||||
options?: Omit<Partial<TabSessionItem>, "id">
|
||||
@@ -208,7 +210,8 @@ const DEFAULT_TABS = {
|
||||
{
|
||||
id: "679da59a3924d4bd56d16d3f",
|
||||
session: {
|
||||
id: "679da5a5667a16db2353a062"
|
||||
id: "679da5a5667a16db2353a062",
|
||||
spellCheckDisabled: false
|
||||
}
|
||||
}
|
||||
],
|
||||
@@ -255,7 +258,7 @@ export const useTabStore = create<TabStore, any>(
|
||||
|
||||
const sessionId =
|
||||
oldSessionId &&
|
||||
tabSessionHistory.currentSessionId(tabId) === oldSessionId
|
||||
tabSessionHistory.currentSessionId(tabId) === oldSessionId
|
||||
? oldSessionId
|
||||
: tabSessionHistory.add(tabId, oldSessionId);
|
||||
|
||||
@@ -386,7 +389,7 @@ export const useTabStore = create<TabStore, any>(
|
||||
focusPreviewTab: (
|
||||
noteId: string,
|
||||
options: Omit<Partial<TabItem>, "id" | "noteId">
|
||||
) => {},
|
||||
) => { },
|
||||
|
||||
removeTab: (id: string) => {
|
||||
const index = get().tabs.findIndex((t) => t.id === id);
|
||||
@@ -482,6 +485,25 @@ export const useTabStore = create<TabStore, any>(
|
||||
},
|
||||
getTab: (tabId) => {
|
||||
return get().tabs.find((t) => t.id === tabId);
|
||||
},
|
||||
clearAllTabs: () => {
|
||||
const tabs = get().tabs;
|
||||
tabs.forEach((tab) => {
|
||||
const tabSessions = tabSessionHistory.getTabHistory(tab.id);
|
||||
tabSessions.back.forEach((id) => TabSessionStorage.remove(id));
|
||||
tabSessions.forward.forEach((id) => TabSessionStorage.remove(id));
|
||||
tabSessionHistory.clearStackForTab(tab.id);
|
||||
});
|
||||
|
||||
const id = getId();
|
||||
set({
|
||||
tabs: [{ id: id }],
|
||||
currentTab: id
|
||||
});
|
||||
history.history = [id];
|
||||
get().newTabSession(id);
|
||||
get().focusTab(id);
|
||||
syncTabs();
|
||||
}
|
||||
}),
|
||||
{
|
||||
|
||||
@@ -141,37 +141,9 @@ export function isContentInvalid(content: string | undefined) {
|
||||
);
|
||||
}
|
||||
|
||||
const canRestoreAppState = (appState: AppState) => {
|
||||
return appState.editing && Date.now() < appState.timestamp + 3600000;
|
||||
};
|
||||
|
||||
let appState: AppState | undefined;
|
||||
export function setAppState(state: AppState) {
|
||||
appState = state;
|
||||
}
|
||||
export function getAppState() {
|
||||
if (appState && canRestoreAppState(appState)) return appState as AppState;
|
||||
const json = NotesnookModule.getAppState();
|
||||
if (json) {
|
||||
appState = JSON.parse(json) as AppState;
|
||||
if (canRestoreAppState(appState)) {
|
||||
return appState;
|
||||
} else {
|
||||
clearAppState();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function clearAppState() {
|
||||
appState = undefined;
|
||||
NotesnookModule.setAppState("");
|
||||
}
|
||||
|
||||
export async function openInternalLink(url: string) {
|
||||
const data = parseInternalLink(url);
|
||||
if (!data?.id) return false;
|
||||
if (!data?.id || data.type !== "note") return false;
|
||||
if (
|
||||
data.id ===
|
||||
useTabStore.getState().getNoteIdForTab(useTabStore.getState().currentTab!)
|
||||
|
||||
@@ -237,8 +237,9 @@ const LinkNotebooks = (props: NavigationProps<"LinkNotebooks">) => {
|
||||
button={{
|
||||
icon: "plus",
|
||||
onPress: async () => {
|
||||
const notebooksFeature =
|
||||
await isFeatureAvailable("notebooks");
|
||||
const notebooksFeature = await isFeatureAvailable(
|
||||
"notebooks"
|
||||
);
|
||||
if (!notebooksFeature.isAllowed) {
|
||||
ToastManager.show({
|
||||
message: notebooksFeature.error,
|
||||
@@ -387,8 +388,8 @@ const NotebookItemWrapper = React.memo(
|
||||
!selected
|
||||
? "selected"
|
||||
: !state.initialState[item.notebook.id]
|
||||
? undefined
|
||||
: "deselected"
|
||||
? undefined
|
||||
: "deselected"
|
||||
);
|
||||
}}
|
||||
canDisableSelectionMode={false}
|
||||
|
||||
@@ -17,24 +17,22 @@ You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import { VirtualizedGrouping } from "@notesnook/core";
|
||||
import { sanitizeTag } from "@notesnook/core";
|
||||
import { Tag } from "@notesnook/core";
|
||||
import { LegendList } from "@legendapp/list";
|
||||
import { isFeatureAvailable } from "@notesnook/common";
|
||||
import { Tag, VirtualizedGrouping, sanitizeTag } from "@notesnook/core";
|
||||
import { strings } from "@notesnook/intl";
|
||||
import { useThemeColors } from "@notesnook/theme";
|
||||
import React, {
|
||||
RefObject,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState
|
||||
} from "react";
|
||||
import React, { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { TextInput, View } from "react-native";
|
||||
import { SafeAreaView } from "react-native-safe-area-context";
|
||||
import { TextInput, View, useWindowDimensions } from "react-native";
|
||||
import { ActionSheetRef } from "react-native-actions-sheet";
|
||||
import Icon from "react-native-vector-icons/MaterialCommunityIcons";
|
||||
import { db } from "../../common/database";
|
||||
import { useDBItem } from "../../hooks/use-db-item";
|
||||
import { Header } from "../../components/header";
|
||||
import Input from "../../components/ui/input";
|
||||
import { Pressable } from "../../components/ui/pressable";
|
||||
import Heading from "../../components/ui/typography/heading";
|
||||
import Paragraph from "../../components/ui/typography/paragraph";
|
||||
import { useNavigationFocus } from "../../hooks/use-navigation-focus";
|
||||
import { ToastManager } from "../../services/event-manager";
|
||||
import Navigation, { NavigationProps } from "../../services/navigation";
|
||||
import {
|
||||
@@ -43,17 +41,8 @@ import {
|
||||
} from "../../stores/item-selection-store";
|
||||
import { useRelationStore } from "../../stores/use-relation-store";
|
||||
import { useTagStore } from "../../stores/use-tag-store";
|
||||
import { defaultBorderRadius, AppFontSize } from "../../utils/size";
|
||||
import Input from "../../components/ui/input";
|
||||
import { Pressable } from "../../components/ui/pressable";
|
||||
import Heading from "../../components/ui/typography/heading";
|
||||
import Paragraph from "../../components/ui/typography/paragraph";
|
||||
import { strings } from "@notesnook/intl";
|
||||
import { AppFontSize, defaultBorderRadius } from "../../utils/size";
|
||||
import { DefaultAppStyles } from "../../utils/styles";
|
||||
import { Header } from "../../components/header";
|
||||
import { useNavigationFocus } from "../../hooks/use-navigation-focus";
|
||||
import { isFeatureAvailable } from "@notesnook/common";
|
||||
import { LegendList } from "@legendapp/list";
|
||||
|
||||
async function updateInitialSelectionState(items: string[]) {
|
||||
const relations = await db.relations
|
||||
@@ -92,13 +81,12 @@ const useTagItemSelection = createItemSelectionStore(true);
|
||||
const ManageTags = (props: NavigationProps<"ManageTags">) => {
|
||||
const { colors } = useThemeColors();
|
||||
const ids = props.route.params.ids || [];
|
||||
const [tags, setTags] = useState<VirtualizedGrouping<Tag>>();
|
||||
const [tags, setTags] = useState<Tag[]>();
|
||||
const [query, setQuery] = useState<string>();
|
||||
const inputRef = useRef<TextInput>(null);
|
||||
const [focus, setFocus] = useState(false);
|
||||
useNavigationFocus(props.navigation, { focusOnInit: true });
|
||||
const timerRef = useRef<NodeJS.Timeout>(undefined);
|
||||
const [queryExists, setQueryExists] = useState(false);
|
||||
const dimensions = useWindowDimensions();
|
||||
const refreshSelection = useCallback(() => {
|
||||
updateInitialSelectionState(ids).then((selection) => {
|
||||
useTagItemSelection.setState({
|
||||
@@ -109,18 +97,43 @@ const ManageTags = (props: NavigationProps<"ManageTags">) => {
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [ids, tags]);
|
||||
|
||||
const sortAndSetTags = useCallback(
|
||||
async (items: VirtualizedGrouping<Tag>) => {
|
||||
const tags = [];
|
||||
const noteTags = [];
|
||||
const assignedTags =
|
||||
ids.length > 1
|
||||
? []
|
||||
: await db.relations
|
||||
.to({ type: "note", id: ids[0] }, "tag")
|
||||
.resolve();
|
||||
|
||||
for (let i = 0; i < items.placeholders.length; i++) {
|
||||
const item = (await items.item(i)).item;
|
||||
if (item) {
|
||||
if (assignedTags.find((tag) => tag.id === item.id)) {
|
||||
noteTags.push(item);
|
||||
} else {
|
||||
tags.push(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
tags.splice(0, 0, ...noteTags);
|
||||
setTags(tags);
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
const refreshTags = useCallback(() => {
|
||||
if (query && query.trim() !== "") {
|
||||
db.lookup
|
||||
.tags(query)
|
||||
.sorted(db.settings.getGroupOptions("tags"))
|
||||
.then((items) => {
|
||||
setTags(items);
|
||||
});
|
||||
.then(sortAndSetTags);
|
||||
} else {
|
||||
db.tags.all.sorted(db.settings.getGroupOptions("tags")).then((items) => {
|
||||
setTags(items);
|
||||
});
|
||||
db.tags.all
|
||||
.sorted(db.settings.getGroupOptions("tags"))
|
||||
.then(sortAndSetTags);
|
||||
}
|
||||
}, [query]);
|
||||
|
||||
@@ -241,14 +254,10 @@ const ManageTags = (props: NavigationProps<"ManageTags">) => {
|
||||
);
|
||||
|
||||
const renderTag = useCallback(
|
||||
({ index }: { item: boolean; index: number }) => (
|
||||
<TagItem
|
||||
tags={tags as VirtualizedGrouping<Tag>}
|
||||
id={index}
|
||||
onPress={onPress}
|
||||
/>
|
||||
({ index, item }: { item: Tag; index: number }) => (
|
||||
<TagItem tag={item} onPress={onPress} />
|
||||
),
|
||||
[onPress, tags]
|
||||
[onPress]
|
||||
);
|
||||
|
||||
return (
|
||||
@@ -280,14 +289,11 @@ const ManageTags = (props: NavigationProps<"ManageTags">) => {
|
||||
fwdRef={inputRef}
|
||||
autoCapitalize="none"
|
||||
onChangeText={(v) => {
|
||||
setQuery(sanitizeTag(v));
|
||||
checkQueryExists(sanitizeTag(v));
|
||||
}}
|
||||
onFocusInput={() => {
|
||||
setFocus(true);
|
||||
}}
|
||||
onBlurInput={() => {
|
||||
setFocus(false);
|
||||
clearTimeout(timerRef.current);
|
||||
timerRef.current = setTimeout(() => {
|
||||
setQuery(sanitizeTag(v));
|
||||
checkQueryExists(sanitizeTag(v));
|
||||
}, 300);
|
||||
}}
|
||||
onSubmit={() => {
|
||||
onSubmit();
|
||||
@@ -324,7 +330,7 @@ const ManageTags = (props: NavigationProps<"ManageTags">) => {
|
||||
}}
|
||||
>
|
||||
<LegendList
|
||||
data={tags?.placeholders || []}
|
||||
data={tags || []}
|
||||
extraData={tags}
|
||||
keyboardShouldPersistTaps
|
||||
keyboardDismissMode="interactive"
|
||||
@@ -367,16 +373,13 @@ ManageTags.present = (ids?: string[]) => {
|
||||
export default ManageTags;
|
||||
|
||||
const TagItem = ({
|
||||
id,
|
||||
tags,
|
||||
onPress
|
||||
onPress,
|
||||
tag
|
||||
}: {
|
||||
id: string | number;
|
||||
tags: VirtualizedGrouping<Tag>;
|
||||
tag: Tag;
|
||||
onPress: (id: string) => void;
|
||||
}) => {
|
||||
const { colors } = useThemeColors();
|
||||
const [tag] = useDBItem(id, "tag", tags);
|
||||
const selection = useTagItemSelection((state) =>
|
||||
tag?.id ? state.selection[tag?.id] : false
|
||||
);
|
||||
@@ -414,15 +417,15 @@ const TagItem = ({
|
||||
selection === "selected"
|
||||
? "check-circle-outline"
|
||||
: selection === "intermediate"
|
||||
? "minus-circle-outline"
|
||||
: "checkbox-blank-circle-outline"
|
||||
? "minus-circle-outline"
|
||||
: "checkbox-blank-circle-outline"
|
||||
}
|
||||
name={
|
||||
selection === "selected"
|
||||
? "check-circle-outline"
|
||||
: selection === "intermediate"
|
||||
? "minus-circle-outline"
|
||||
: "checkbox-blank-circle-outline"
|
||||
? "minus-circle-outline"
|
||||
: "checkbox-blank-circle-outline"
|
||||
}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -242,8 +242,9 @@ export const MoveNotebook = (props: NavigationProps<"MoveNotebook">) => {
|
||||
button={{
|
||||
icon: "plus",
|
||||
onPress: async () => {
|
||||
const notebooksFeature =
|
||||
await isFeatureAvailable("notebooks");
|
||||
const notebooksFeature = await isFeatureAvailable(
|
||||
"notebooks"
|
||||
);
|
||||
if (!notebooksFeature.isAllowed) {
|
||||
ToastManager.show({
|
||||
message: notebooksFeature.error,
|
||||
|
||||
@@ -99,7 +99,7 @@ export const NotePreviewConfigure = () => {
|
||||
useEffect(() => {
|
||||
useSettingStore.getState().setDeviceMode("mobile");
|
||||
if (loading) return;
|
||||
db.notes.all.sorted(db.settings.getGroupOptions("notes")).then((notes) => {
|
||||
db.notes.all.sorted(db.settings.getGroupOptions("home")).then((notes) => {
|
||||
setItems(notes);
|
||||
});
|
||||
}, [loading]);
|
||||
@@ -141,7 +141,7 @@ export const NotePreviewConfigure = () => {
|
||||
bounceRef.current = setTimeout(() => {
|
||||
if (!value) {
|
||||
db.notes.all
|
||||
.sorted(db.settings.getGroupOptions("notes"))
|
||||
.sorted(db.settings.getGroupOptions("home"))
|
||||
.then((notes) => {
|
||||
setItems(notes);
|
||||
});
|
||||
@@ -149,7 +149,7 @@ export const NotePreviewConfigure = () => {
|
||||
}
|
||||
db.lookup
|
||||
.notes(value)
|
||||
.sorted()
|
||||
.sorted(db.settings.getGroupOptions("home"))
|
||||
.then((notes) => {
|
||||
setItems(notes);
|
||||
});
|
||||
|
||||
@@ -322,8 +322,8 @@ export const MFASetup = ({
|
||||
method?.id === "email"
|
||||
? user?.email
|
||||
: method?.id === "app"
|
||||
? authenticatorDetails?.sharedKey || ""
|
||||
: undefined
|
||||
? authenticatorDetails?.sharedKey || ""
|
||||
: undefined
|
||||
}
|
||||
multiline={method.id === "app"}
|
||||
onChangeText={(value) => {
|
||||
@@ -356,12 +356,12 @@ export const MFASetup = ({
|
||||
sending
|
||||
? null
|
||||
: method.id === "app"
|
||||
? strings.copy()
|
||||
: `${
|
||||
seconds
|
||||
? strings.resendCode(seconds as number)
|
||||
: strings.sendCode()
|
||||
}`
|
||||
? strings.copy()
|
||||
: `${
|
||||
seconds
|
||||
? strings.resendCode(seconds as number)
|
||||
: strings.sendCode()
|
||||
}`
|
||||
}
|
||||
/>
|
||||
)
|
||||
|
||||
@@ -36,9 +36,11 @@ import {
|
||||
WeekFormatPicker,
|
||||
FontPicker,
|
||||
HomePicker,
|
||||
ImageCompressionPicker,
|
||||
SidebarTabPicker,
|
||||
TimeFormatPicker,
|
||||
TrashIntervalPicker
|
||||
TrashIntervalPicker,
|
||||
VaultLockTimerPicker
|
||||
} from "./picker/pickers";
|
||||
import { RestoreBackup } from "./restore-backup";
|
||||
import { ServersConfiguration } from "./server-config";
|
||||
@@ -46,6 +48,7 @@ import SoundPicker from "./sound-picker";
|
||||
import ThemeSelector from "./theme-selector";
|
||||
import { TitleFormat } from "./title-format";
|
||||
import { NotesnookCircle } from "./notesnook-circle";
|
||||
import { ManageInboxKeys, InboxKeysList } from "./manage-inbox-keys";
|
||||
|
||||
export const components: { [name: string]: ReactElement } = {
|
||||
homeselector: <HomePicker />,
|
||||
@@ -61,8 +64,10 @@ export const components: { [name: string]: ReactElement } = {
|
||||
"time-format-selector": <TimeFormatPicker />,
|
||||
"day-format-selector": <DayFormatPicker />,
|
||||
"week-format-selector": <WeekFormatPicker />,
|
||||
"image-compression-picker": <ImageCompressionPicker />,
|
||||
"theme-selector": <ThemeSelector />,
|
||||
"applock-timer": <ApplockTimerPicker />,
|
||||
"vault-lock-timer": <VaultLockTimerPicker />,
|
||||
autobackupsattachments: <BackupWithAttachmentsReminderPicker />,
|
||||
backuprestore: <RestoreBackup />,
|
||||
"server-config": <ServersConfiguration />,
|
||||
@@ -75,5 +80,7 @@ export const components: { [name: string]: ReactElement } = {
|
||||
"sidebar-tab-selector": <SidebarTabPicker />,
|
||||
"change-password": <ChangePassword />,
|
||||
"change-email": <ChangeEmail />,
|
||||
"notesnook-circle": <NotesnookCircle />
|
||||
"notesnook-circle": <NotesnookCircle />,
|
||||
"manage-inbox-keys": <ManageInboxKeys />,
|
||||
"inbox-keys": <InboxKeysList />
|
||||
};
|
||||
|
||||
@@ -75,15 +75,15 @@ export default function DebugLogs() {
|
||||
item.level === LogLevel.Error || item.level === LogLevel.Fatal
|
||||
? hexToRGBA(colors.error.paragraph, 0.2)
|
||||
: item.level === LogLevel.Warn
|
||||
? hexToRGBA(colors.static.orange, 0.2)
|
||||
: "transparent";
|
||||
? hexToRGBA(colors.static.orange, 0.2)
|
||||
: "transparent";
|
||||
|
||||
const color =
|
||||
item.level === LogLevel.Error || item.level === LogLevel.Fatal
|
||||
? colors.error.paragraph
|
||||
: item.level === LogLevel.Warn
|
||||
? colors.static.black
|
||||
: colors.primary.paragraph;
|
||||
? colors.static.black
|
||||
: colors.primary.paragraph;
|
||||
|
||||
return !item ? null : (
|
||||
<TouchableOpacity
|
||||
|
||||
@@ -24,7 +24,6 @@ import Animated, { FadeInDown, FadeOutDown } from "react-native-reanimated";
|
||||
import { Button } from "../../../components/ui/button";
|
||||
import { Notice } from "../../../components/ui/notice";
|
||||
import Paragraph from "../../../components/ui/typography/paragraph";
|
||||
import PremiumService from "../../../services/premium";
|
||||
import { useThemeColors } from "@notesnook/theme";
|
||||
import { AppFontSize } from "../../../utils/size";
|
||||
import { Group } from "./group";
|
||||
@@ -41,7 +40,7 @@ export const ConfigureToolbar = () => {
|
||||
|
||||
const renderGroups = () => {
|
||||
return data?.map((item, index) => (
|
||||
<Group key={`group-${index}`} item={item} index={index} />
|
||||
<Group key={`group-${index}-${item.length}`} item={item} index={index} />
|
||||
));
|
||||
};
|
||||
|
||||
@@ -131,6 +130,7 @@ export const ConfigureToolbar = () => {
|
||||
style={{
|
||||
flex: 1
|
||||
}}
|
||||
key={preset}
|
||||
scrollEventThrottle={13}
|
||||
showsVerticalScrollIndicator={false}
|
||||
>
|
||||
|
||||
@@ -31,7 +31,7 @@ import { renderTool } from "./common";
|
||||
import { DraggableItem, useDragState } from "./state";
|
||||
import ToolSheet from "./tool-sheet";
|
||||
|
||||
import { useIsFeatureAvailable } from "@notesnook/common";
|
||||
import { isFeatureAvailable, useIsFeatureAvailable } from "@notesnook/common";
|
||||
import type { ToolId } from "@notesnook/editor";
|
||||
import { strings } from "@notesnook/intl";
|
||||
import Icon from "react-native-vector-icons/MaterialCommunityIcons";
|
||||
@@ -64,78 +64,87 @@ export const Group = ({
|
||||
const { colors } = useThemeColors();
|
||||
const featureAvailable = useIsFeatureAvailable("customToolbarPreset");
|
||||
|
||||
const onDrop = (data: DraxDragWithReceiverEventData) => {
|
||||
if (!featureAvailable?.isAllowed) {
|
||||
ToastManager.show({
|
||||
type: "info",
|
||||
message: featureAvailable?.error
|
||||
});
|
||||
return;
|
||||
}
|
||||
const isDroppedAbove = data.receiver.receiveOffsetRatio.y < 0.5;
|
||||
const dragged = data.dragged.payload;
|
||||
const reciever = data.receiver.payload;
|
||||
const _data = useDragState.getState().data.slice();
|
||||
|
||||
if (dragged.type === "group") {
|
||||
const fromIndex = dragged.index;
|
||||
const toIndex = isDroppedAbove
|
||||
? Math.max(0, reciever.index)
|
||||
: reciever.index + 1;
|
||||
|
||||
_data.splice(
|
||||
toIndex > fromIndex ? toIndex - 1 : toIndex,
|
||||
0,
|
||||
_data.splice(fromIndex, 1)[0]
|
||||
);
|
||||
}
|
||||
|
||||
// Always insert sub group at the end of the group.
|
||||
if (dragged.type === "subgroup") {
|
||||
const fromIndex = dragged.index;
|
||||
|
||||
const insertAt = _data[reciever.index] as string[];
|
||||
const insertFrom = _data[dragged.groupIndex] as string[];
|
||||
|
||||
if (typeof insertAt[insertAt.length - 1] !== "string") {
|
||||
setRecieving(false);
|
||||
return data.dragAbsolutePosition;
|
||||
const onDrop = React.useCallback(
|
||||
(data: DraxDragWithReceiverEventData) => {
|
||||
if (!featureAvailable?.isAllowed) {
|
||||
ToastManager.show({
|
||||
type: "info",
|
||||
message: featureAvailable?.error || strings.featureNotAvailable()
|
||||
});
|
||||
return;
|
||||
}
|
||||
insertAt.push(insertFrom.splice(fromIndex, 1)[0]);
|
||||
}
|
||||
const isDroppedAbove = data.receiver.receiveOffsetRatio.y < 0.5;
|
||||
const dragged = data.dragged.payload;
|
||||
const reciever = data.receiver.payload;
|
||||
const _data = useDragState.getState().data.slice();
|
||||
|
||||
if (dragged.type === "tool") {
|
||||
const insertFrom =
|
||||
typeof dragged.parentIndex === "number"
|
||||
? (_data[dragged.parentIndex][dragged.groupIndex] as string[])
|
||||
: (_data[dragged.groupIndex] as string[]);
|
||||
_data[groupIndex].push(insertFrom.splice(dragged.index, 1)[0] as ToolId);
|
||||
}
|
||||
if (dragged.type === "group") {
|
||||
const fromIndex = dragged.index;
|
||||
const toIndex = isDroppedAbove
|
||||
? Math.max(0, reciever.index)
|
||||
: reciever.index + 1;
|
||||
|
||||
setData(_data);
|
||||
setRecieving(false);
|
||||
return data.dragAbsolutePosition;
|
||||
};
|
||||
_data.splice(
|
||||
toIndex > fromIndex ? toIndex - 1 : toIndex,
|
||||
0,
|
||||
_data.splice(fromIndex, 1)[0]
|
||||
);
|
||||
}
|
||||
|
||||
const onRecieveData = (data: DraxDragWithReceiverEventData) => {
|
||||
setRecieving(true);
|
||||
if (data.dragged.payload.type !== "group")
|
||||
return setRecievePosition("below");
|
||||
if (data.receiver.receiveOffsetRatio.y < 0.5) {
|
||||
setRecievePosition("above");
|
||||
} else {
|
||||
setRecievePosition("below");
|
||||
}
|
||||
};
|
||||
// Always insert sub group at the end of the group.
|
||||
if (dragged.type === "subgroup") {
|
||||
const fromIndex = dragged.index;
|
||||
|
||||
const insertAt = _data[reciever.index] as string[];
|
||||
const insertFrom = _data[dragged.groupIndex] as string[];
|
||||
|
||||
if (typeof insertAt[insertAt.length - 1] !== "string") {
|
||||
setRecieving(false);
|
||||
return data.dragAbsolutePosition;
|
||||
}
|
||||
insertAt.push(insertFrom.splice(fromIndex, 1)[0]);
|
||||
}
|
||||
|
||||
if (dragged.type === "tool") {
|
||||
const insertFrom =
|
||||
typeof dragged.parentIndex === "number"
|
||||
? (_data[dragged.parentIndex][dragged.groupIndex] as string[])
|
||||
: (_data[dragged.groupIndex] as string[]);
|
||||
_data[groupIndex].push(
|
||||
insertFrom.splice(dragged.index, 1)[0] as ToolId
|
||||
);
|
||||
}
|
||||
|
||||
setData(_data);
|
||||
setRecieving(false);
|
||||
return data.dragAbsolutePosition;
|
||||
},
|
||||
[featureAvailable]
|
||||
);
|
||||
|
||||
const onRecieveData = React.useCallback(
|
||||
(data: DraxDragWithReceiverEventData) => {
|
||||
setRecieving(true);
|
||||
if (data.dragged.payload.type !== "group")
|
||||
return setRecievePosition("below");
|
||||
if (data.receiver.receiveOffsetRatio.y < 0.5) {
|
||||
setRecievePosition("above");
|
||||
} else {
|
||||
setRecievePosition("below");
|
||||
}
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
const buttons = [
|
||||
{
|
||||
name: "minus",
|
||||
onPress: () => {
|
||||
if (!featureAvailable?.isAllowed) {
|
||||
onPress: async () => {
|
||||
const feature = await isFeatureAvailable("customToolbarPreset");
|
||||
if (!feature.isAllowed) {
|
||||
ToastManager.show({
|
||||
type: "info",
|
||||
message: featureAvailable?.error
|
||||
message: feature?.error
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -157,11 +166,12 @@ export const Group = ({
|
||||
},
|
||||
{
|
||||
name: "plus",
|
||||
onPress: () => {
|
||||
if (!featureAvailable?.isAllowed) {
|
||||
onPress: async () => {
|
||||
const feature = await isFeatureAvailable("customToolbarPreset");
|
||||
if (!feature.isAllowed) {
|
||||
ToastManager.show({
|
||||
type: "info",
|
||||
message: featureAvailable?.error
|
||||
message: feature?.error
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -44,8 +44,8 @@ export default function ToolSheet({
|
||||
fwdRef: RefObject<ActionSheetRef>;
|
||||
}) {
|
||||
const { colors } = useThemeColors();
|
||||
const data = useDragState((state) => state.data);
|
||||
const ungrouped = getUngroupedTools(data) as ToolId[];
|
||||
const [data] = useDragState((state) => [state.data]);
|
||||
const ungrouped = getUngroupedTools( data) as ToolId[];
|
||||
|
||||
const renderTool = React.useCallback(
|
||||
(item: ToolId) => {
|
||||
@@ -114,7 +114,7 @@ export default function ToolSheet({
|
||||
return (
|
||||
<View
|
||||
style={{
|
||||
maxHeight: "100%",
|
||||
maxHeight: 400,
|
||||
padding: DefaultAppStyles.GAP
|
||||
}}
|
||||
>
|
||||
|
||||
@@ -33,7 +33,7 @@ import { DraggableItem, useDragState } from "./state";
|
||||
import ToolSheet from "./tool-sheet";
|
||||
import { findToolById, getToolIcon } from "./toolbar-definition";
|
||||
|
||||
import { useIsFeatureAvailable } from "@notesnook/common";
|
||||
import { isFeatureAvailable, useIsFeatureAvailable } from "@notesnook/common";
|
||||
import type { ToolId } from "@notesnook/editor";
|
||||
import { strings } from "@notesnook/intl";
|
||||
import Icon from "react-native-vector-icons/MaterialCommunityIcons";
|
||||
@@ -78,11 +78,12 @@ export const Tool = ({
|
||||
? [
|
||||
{
|
||||
name: "minus",
|
||||
onPress: () => {
|
||||
if (!featureAvailable?.isAllowed) {
|
||||
onPress: async () => {
|
||||
const feature = await isFeatureAvailable("customToolbarPreset");
|
||||
if (!feature.isAllowed) {
|
||||
ToastManager.show({
|
||||
type: "info",
|
||||
message: featureAvailable?.error
|
||||
message: feature?.error
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -102,11 +103,12 @@ export const Tool = ({
|
||||
},
|
||||
{
|
||||
name: "plus",
|
||||
onPress: () => {
|
||||
if (!featureAvailable?.isAllowed) {
|
||||
onPress: async () => {
|
||||
const feature = await isFeatureAvailable("customToolbarPreset");
|
||||
if (!feature.isAllowed) {
|
||||
ToastManager.show({
|
||||
type: "info",
|
||||
message: featureAvailable?.error
|
||||
message: feature?.error
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -122,11 +124,12 @@ export const Tool = ({
|
||||
: [
|
||||
{
|
||||
name: "minus",
|
||||
onPress: () => {
|
||||
if (!featureAvailable?.isAllowed) {
|
||||
onPress: async () => {
|
||||
const feature = await isFeatureAvailable("customToolbarPreset");
|
||||
if (!feature.isAllowed) {
|
||||
ToastManager.show({
|
||||
type: "info",
|
||||
message: featureAvailable?.error
|
||||
message: feature?.error
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -151,7 +154,7 @@ export const Tool = ({
|
||||
if (parentIndex === undefined && !isSubgroup) {
|
||||
btns.unshift({
|
||||
name: "unfold-less-horizontal",
|
||||
onPress: () => {
|
||||
onPress: async () => {
|
||||
if (groupIndex === undefined) return;
|
||||
const _data = useDragState.getState().data.slice();
|
||||
const hasSubGroup = Array.isArray(
|
||||
@@ -267,6 +270,7 @@ export const Tool = ({
|
||||
style={{
|
||||
paddingLeft: 30
|
||||
}}
|
||||
key={`subgroup-${item.length}-${groupIndex}-${index}-${parentIndex}`}
|
||||
>
|
||||
{renderGroup({ index, item, parentIndex: groupIndex })}
|
||||
</View>
|
||||
@@ -290,63 +294,69 @@ export const Tool = ({
|
||||
]
|
||||
);
|
||||
|
||||
const onDrop = (data: DraxDragWithReceiverEventData) => {
|
||||
if (!featureAvailable?.isAllowed) {
|
||||
ToastManager.show({
|
||||
type: "info",
|
||||
message: featureAvailable?.error
|
||||
});
|
||||
return;
|
||||
}
|
||||
const isDroppedAbove = data.receiver.receiveOffsetRatio.y < 0.5;
|
||||
const dragged = data.dragged.payload;
|
||||
const reciever = data.receiver.payload;
|
||||
const _data = useDragState.getState().data?.slice();
|
||||
if (!_data) return;
|
||||
const isFromSubgroup = typeof dragged?.parentIndex === "number";
|
||||
const isDroppedAtSubgroup = typeof reciever?.parentIndex === "number";
|
||||
|
||||
if (dragged.type === "tool") {
|
||||
const fromIndex = dragged.index;
|
||||
const toIndex = isDroppedAbove
|
||||
? Math.max(0, reciever.index)
|
||||
: reciever.index + 1;
|
||||
|
||||
const insertAt = isDroppedAtSubgroup
|
||||
? (_data[reciever.parentIndex][reciever.groupIndex] as string[])
|
||||
: (_data[reciever.groupIndex] as string[]);
|
||||
const insertFrom = isFromSubgroup
|
||||
? (_data[dragged.parentIndex][dragged.groupIndex] as string[])
|
||||
: (_data[dragged.groupIndex] as string[]);
|
||||
insertAt.splice(
|
||||
toIndex > fromIndex ? toIndex - 1 : toIndex,
|
||||
0,
|
||||
insertFrom.splice(fromIndex, 1)[0]
|
||||
);
|
||||
|
||||
// Remove the group or subgroup if it is empty.
|
||||
if (insertFrom.length === 0) {
|
||||
isFromSubgroup
|
||||
? _data[dragged.parentIndex].splice(
|
||||
_data[dragged.parentIndex].length - 1,
|
||||
1
|
||||
)
|
||||
: _data.splice(dragged.groupIndex, 1);
|
||||
const onDrop = React.useCallback(
|
||||
(data: DraxDragWithReceiverEventData) => {
|
||||
if (!featureAvailable?.isAllowed) {
|
||||
ToastManager.show({
|
||||
type: "info",
|
||||
message: featureAvailable?.error || strings.featureNotAvailable()
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
setData(_data);
|
||||
setRecieving(false);
|
||||
return data.dragAbsolutePosition;
|
||||
};
|
||||
const isDroppedAbove = data.receiver.receiveOffsetRatio.y < 0.5;
|
||||
const dragged = data.dragged.payload;
|
||||
const reciever = data.receiver.payload;
|
||||
const _data = useDragState.getState().data?.slice();
|
||||
if (!_data) return;
|
||||
const isFromSubgroup = typeof dragged?.parentIndex === "number";
|
||||
const isDroppedAtSubgroup = typeof reciever?.parentIndex === "number";
|
||||
|
||||
const onRecieveData = (data: DraxDragWithReceiverEventData) => {
|
||||
setRecieving(true);
|
||||
if (data.receiver.receiveOffsetRatio.y < 0.5) {
|
||||
setRecievePosition("above");
|
||||
} else {
|
||||
setRecievePosition("below");
|
||||
}
|
||||
};
|
||||
if (dragged.type === "tool") {
|
||||
const fromIndex = dragged.index;
|
||||
const toIndex = isDroppedAbove
|
||||
? Math.max(0, reciever.index)
|
||||
: reciever.index + 1;
|
||||
|
||||
const insertAt = isDroppedAtSubgroup
|
||||
? (_data[reciever.parentIndex][reciever.groupIndex] as string[])
|
||||
: (_data[reciever.groupIndex] as string[]);
|
||||
const insertFrom = isFromSubgroup
|
||||
? (_data[dragged.parentIndex][dragged.groupIndex] as string[])
|
||||
: (_data[dragged.groupIndex] as string[]);
|
||||
insertAt.splice(
|
||||
toIndex > fromIndex ? toIndex - 1 : toIndex,
|
||||
0,
|
||||
insertFrom.splice(fromIndex, 1)[0]
|
||||
);
|
||||
|
||||
// Remove the group or subgroup if it is empty.
|
||||
if (insertFrom.length === 0) {
|
||||
isFromSubgroup
|
||||
? _data[dragged.parentIndex].splice(
|
||||
_data[dragged.parentIndex].length - 1,
|
||||
1
|
||||
)
|
||||
: _data.splice(dragged.groupIndex, 1);
|
||||
}
|
||||
}
|
||||
setData(_data);
|
||||
setRecieving(false);
|
||||
return data.dragAbsolutePosition;
|
||||
},
|
||||
[featureAvailable]
|
||||
);
|
||||
|
||||
const onRecieveData = React.useCallback(
|
||||
(data: DraxDragWithReceiverEventData) => {
|
||||
setRecieving(true);
|
||||
if (data.receiver.receiveOffsetRatio.y < 0.5) {
|
||||
setRecievePosition("above");
|
||||
} else {
|
||||
setRecievePosition("below");
|
||||
}
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
return (
|
||||
<Animated.View layout={Layout}>
|
||||
|
||||
@@ -25,18 +25,18 @@ import {
|
||||
} from "@notesnook/editor/dist/cjs/toolbar/tool-definitions";
|
||||
import { ToolId } from "@notesnook/editor";
|
||||
|
||||
export const tools = getAllTools() as any;
|
||||
export const tools = () => getAllTools();
|
||||
export const presets: { [name: string]: ToolbarGroupDefinition[] } = {
|
||||
default: getDefaultPresets().default as any,
|
||||
minimal: getDefaultPresets().minimal as any,
|
||||
custom: []
|
||||
};
|
||||
|
||||
export function findToolById(id: keyof typeof tools): {
|
||||
export function findToolById(id: keyof ReturnType<typeof tools> ): {
|
||||
title: string;
|
||||
icon: string;
|
||||
} {
|
||||
return tools[id];
|
||||
return tools()[id];
|
||||
}
|
||||
|
||||
export function getToolIcon(id: ToolId, color: string) {
|
||||
@@ -51,13 +51,14 @@ export function getToolIcon(id: ToolId, color: string) {
|
||||
|
||||
export function getUngroupedTools(
|
||||
toolDefinition: (string | string[])[][]
|
||||
): string[] {
|
||||
const keys = Object.keys(tools);
|
||||
): string[] {
|
||||
const allTools = tools();
|
||||
const keys = Object.keys(allTools);
|
||||
|
||||
const ungrouped = [];
|
||||
const toolString = JSON.stringify(toolDefinition);
|
||||
for (const key of keys) {
|
||||
if (tools[key as ToolId].conditional) continue;
|
||||
if ((allTools[key as ToolId] as any).conditional) continue;
|
||||
if (!toolString.includes(key)) ungrouped.push(key);
|
||||
}
|
||||
|
||||
|
||||
@@ -61,6 +61,7 @@ const Home = ({
|
||||
/>
|
||||
<DelayLayout type="settings">
|
||||
<LegendList
|
||||
testID="settings-list"
|
||||
data={settingsGroups}
|
||||
keyExtractor={keyExtractor}
|
||||
renderItem={renderItem}
|
||||
|
||||
474
apps/mobile/app/screens/settings/manage-inbox-keys.tsx
Normal file
474
apps/mobile/app/screens/settings/manage-inbox-keys.tsx
Normal file
@@ -0,0 +1,474 @@
|
||||
import { usePromise } from "@notesnook/common";
|
||||
import { db } from "../../common/database";
|
||||
import { ActivityIndicator, ScrollView, View } from "react-native";
|
||||
import { Button } from "../../components/ui/button";
|
||||
import { strings } from "@notesnook/intl";
|
||||
import Input from "../../components/ui/input";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { SerializedKeyPair } from "@notesnook/crypto";
|
||||
import Paragraph from "../../components/ui/typography/paragraph";
|
||||
import { DefaultAppStyles } from "../../utils/styles";
|
||||
import { ToastManager } from "../../services/event-manager";
|
||||
import Navigation from "../../services/navigation";
|
||||
import { Storage } from "../../common/database/storage";
|
||||
import { Notice } from "../../components/ui/notice";
|
||||
import { presentDialog } from "../../components/dialog/functions";
|
||||
import { useSettingStore } from "../../stores/use-setting-store";
|
||||
import { InboxApiKey } from "@notesnook/core";
|
||||
import { IconButton } from "../../components/ui/icon-button";
|
||||
import Clipboard from "@react-native-clipboard/clipboard";
|
||||
import { useThemeColors } from "@notesnook/theme";
|
||||
import dayjs from "dayjs";
|
||||
import Heading from "../../components/ui/typography/heading";
|
||||
import { AppFontSize } from "../../utils/size";
|
||||
import AddApiKeySheet from "../../components/sheets/add-api-key";
|
||||
|
||||
const ManageInboxKeys = () => {
|
||||
const keys = usePromise(() => db.user.getInboxKeys());
|
||||
const keysEdited = useRef<SerializedKeyPair>(undefined);
|
||||
|
||||
if (keys.status === "fulfilled" && keys.value && !keysEdited.current) {
|
||||
keysEdited.current = keys.value;
|
||||
}
|
||||
|
||||
return (
|
||||
<ScrollView
|
||||
contentContainerStyle={{
|
||||
paddingHorizontal: DefaultAppStyles.GAP,
|
||||
gap: DefaultAppStyles.GAP_VERTICAL,
|
||||
marginTop: DefaultAppStyles.GAP_VERTICAL
|
||||
}}
|
||||
>
|
||||
<Notice type="alert" text={strings.changingInboxPgpKeysNotice()} />
|
||||
|
||||
<Paragraph>{strings.publicKey()}</Paragraph>
|
||||
<Input
|
||||
defaultValue={keysEdited.current?.publicKey}
|
||||
multiline
|
||||
onChangeText={(value) => {
|
||||
if (keysEdited.current) {
|
||||
keysEdited.current.publicKey = value;
|
||||
}
|
||||
}}
|
||||
style={{
|
||||
height: 150
|
||||
}}
|
||||
wrapperStyle={{
|
||||
height: 150
|
||||
}}
|
||||
/>
|
||||
<Paragraph>{strings.privateKey()}</Paragraph>
|
||||
<Input
|
||||
defaultValue={keysEdited.current?.privateKey}
|
||||
multiline
|
||||
onChangeText={(value) => {
|
||||
if (keysEdited.current) {
|
||||
keysEdited.current.privateKey = value;
|
||||
}
|
||||
}}
|
||||
style={{
|
||||
height: 150
|
||||
}}
|
||||
wrapperStyle={{
|
||||
height: 150
|
||||
}}
|
||||
/>
|
||||
<Button
|
||||
title={strings.save()}
|
||||
type="accent"
|
||||
width={"100%"}
|
||||
onPress={async () => {
|
||||
try {
|
||||
if (keysEdited.current) {
|
||||
const valid = await Storage.validatePGPKeyPair(
|
||||
keysEdited.current
|
||||
);
|
||||
|
||||
if (!valid) {
|
||||
ToastManager.show({
|
||||
message: strings.invalidPgpKeyPair(),
|
||||
type: "error"
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
presentDialog({
|
||||
title: strings.areYouSure(),
|
||||
paragraph: strings.changingInboxPgpKeysNotice(),
|
||||
positiveText: strings.yes(),
|
||||
negativeText: strings.no(),
|
||||
positivePress: async () => {
|
||||
db.user?.saveInboxKeys(keysEdited.current!);
|
||||
ToastManager.show({
|
||||
message: strings.inboxKeysSaved(),
|
||||
type: "success"
|
||||
});
|
||||
Navigation.goBack();
|
||||
return true;
|
||||
}
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
ToastManager.error(e as Error);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</ScrollView>
|
||||
);
|
||||
};
|
||||
|
||||
const InboxKeysList = () => {
|
||||
const inboxEnabled = useSettingStore((state) => state.inboxEnabled);
|
||||
const apiKeysPromise = usePromise(
|
||||
() => db.inboxApiKeys.get(),
|
||||
[inboxEnabled]
|
||||
);
|
||||
const { colors } = useThemeColors();
|
||||
|
||||
if (apiKeysPromise.status === "pending") {
|
||||
return (
|
||||
<View
|
||||
style={{
|
||||
flex: 1,
|
||||
justifyContent: "center",
|
||||
alignItems: "center",
|
||||
paddingHorizontal: DefaultAppStyles.GAP,
|
||||
gap: DefaultAppStyles.GAP_VERTICAL,
|
||||
width: "100%"
|
||||
}}
|
||||
>
|
||||
<ActivityIndicator size="small" color={colors.primary.accent} />
|
||||
<Paragraph color={colors.secondary.paragraph}>
|
||||
{strings.loadingApiKeys()}
|
||||
</Paragraph>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
if (apiKeysPromise.status === "rejected") {
|
||||
return (
|
||||
<View
|
||||
style={{
|
||||
flex: 1,
|
||||
justifyContent: "center",
|
||||
alignItems: "center",
|
||||
paddingHorizontal: DefaultAppStyles.GAP,
|
||||
gap: DefaultAppStyles.GAP_VERTICAL,
|
||||
width: "100%"
|
||||
}}
|
||||
>
|
||||
<Paragraph color={colors.error.paragraph}>
|
||||
{strings.failedToLoadApiKeys()}
|
||||
</Paragraph>
|
||||
<Button
|
||||
title={strings.retry()}
|
||||
type="accent"
|
||||
onPress={() => apiKeysPromise.refresh()}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const apiKeys = apiKeysPromise.value || [];
|
||||
|
||||
return (
|
||||
<ScrollView
|
||||
contentContainerStyle={{
|
||||
gap: DefaultAppStyles.GAP_VERTICAL,
|
||||
paddingVertical: DefaultAppStyles.GAP_VERTICAL,
|
||||
width: "100%",
|
||||
paddingHorizontal: DefaultAppStyles.GAP,
|
||||
paddingBottom: 50
|
||||
}}
|
||||
>
|
||||
{apiKeys.length === 0 ? (
|
||||
<View
|
||||
style={{
|
||||
padding: DefaultAppStyles.GAP * 2,
|
||||
borderWidth: 1,
|
||||
borderStyle: "dashed",
|
||||
borderColor: colors.secondary.border,
|
||||
borderRadius: 5,
|
||||
backgroundColor: colors.secondary.background,
|
||||
alignItems: "center"
|
||||
}}
|
||||
>
|
||||
<Paragraph color={colors.secondary.paragraph}>
|
||||
{strings.createFirstApiKey()}
|
||||
</Paragraph>
|
||||
</View>
|
||||
) : (
|
||||
<View style={{ gap: 0 }}>
|
||||
{apiKeys.map((key, i) => (
|
||||
<ApiKeyItem
|
||||
key={key.key}
|
||||
apiKey={key}
|
||||
onRevoke={() => apiKeysPromise.refresh()}
|
||||
isAtEnd={i === apiKeys.length - 1}
|
||||
/>
|
||||
))}
|
||||
|
||||
<Button
|
||||
title={strings.createKey()}
|
||||
type="accent"
|
||||
style={{
|
||||
paddingVertical: DefaultAppStyles.GAP_VERTICAL_SMALL,
|
||||
width: "100%"
|
||||
}}
|
||||
onPress={() => {
|
||||
if (apiKeys.length >= 10) {
|
||||
presentDialog({
|
||||
title: strings.apiKeysLimitReached(),
|
||||
paragraph: strings.apiKeysLimitReachedMessage(),
|
||||
positiveText: strings.ok()
|
||||
});
|
||||
} else {
|
||||
AddApiKeySheet.present(() => apiKeysPromise.refresh());
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</View>
|
||||
)}
|
||||
</ScrollView>
|
||||
);
|
||||
};
|
||||
|
||||
const VIEW_KEY_TIMEOUT = 15;
|
||||
|
||||
type ApiKeyItemProps = {
|
||||
apiKey: InboxApiKey;
|
||||
onRevoke: () => void;
|
||||
isAtEnd: boolean;
|
||||
};
|
||||
|
||||
function ApiKeyItem({ apiKey, onRevoke, isAtEnd }: ApiKeyItemProps) {
|
||||
const { colors } = useThemeColors();
|
||||
const [copied, setCopied] = useState(false);
|
||||
const [viewing, setViewing] = useState(false);
|
||||
const [isRevoking, setIsRevoking] = useState(false);
|
||||
const [secondsLeft, setSecondsLeft] = useState(VIEW_KEY_TIMEOUT);
|
||||
|
||||
async function viewKey() {
|
||||
presentDialog({
|
||||
title: strings.authenticateToViewApiKey(),
|
||||
paragraph: strings.enterPasswordToViewApiKey(),
|
||||
positiveText: strings.authenticate(),
|
||||
negativeText: strings.cancel(),
|
||||
input: true,
|
||||
secureTextEntry: true,
|
||||
inputPlaceholder: strings.accountPassword(),
|
||||
positivePress: async (value) => {
|
||||
try {
|
||||
const verified = await db.user.verifyPassword(value);
|
||||
if (!verified) {
|
||||
ToastManager.show({
|
||||
message: strings.invalidPassword(),
|
||||
type: "error"
|
||||
});
|
||||
return false;
|
||||
}
|
||||
setViewing(true);
|
||||
return true;
|
||||
} catch (error) {
|
||||
ToastManager.error(error as Error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function copyToClipboard() {
|
||||
if (!viewing) return;
|
||||
try {
|
||||
Clipboard.setString(apiKey.key);
|
||||
setCopied(true);
|
||||
ToastManager.show({
|
||||
message: strings.apiKeyCopiedToClipboard(),
|
||||
type: "success"
|
||||
});
|
||||
} catch (error) {
|
||||
ToastManager.show({
|
||||
message: strings.failedToCopyToClipboard(),
|
||||
type: "error"
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (copied) {
|
||||
const timer = setTimeout(() => {
|
||||
setCopied(false);
|
||||
}, 1000);
|
||||
return () => clearTimeout(timer);
|
||||
}
|
||||
}, [copied]);
|
||||
|
||||
useEffect(() => {
|
||||
if (viewing) {
|
||||
setSecondsLeft(VIEW_KEY_TIMEOUT);
|
||||
const interval = setInterval(() => {
|
||||
setSecondsLeft((prev) => {
|
||||
if (prev <= 1) {
|
||||
setViewing(false);
|
||||
return VIEW_KEY_TIMEOUT;
|
||||
}
|
||||
return prev - 1;
|
||||
});
|
||||
}, 1000);
|
||||
return () => clearInterval(interval);
|
||||
}
|
||||
}, [viewing]);
|
||||
|
||||
const isApiKeyExpired = Date.now() > apiKey.expiryDate;
|
||||
|
||||
return (
|
||||
<View
|
||||
style={{
|
||||
paddingVertical: DefaultAppStyles.GAP_VERTICAL,
|
||||
borderBottomWidth: isAtEnd ? 0 : 1,
|
||||
borderBottomColor: colors.secondary.border
|
||||
}}
|
||||
>
|
||||
<View
|
||||
style={{
|
||||
flexDirection: "column",
|
||||
gap: DefaultAppStyles.GAP_VERTICAL
|
||||
}}
|
||||
>
|
||||
<View
|
||||
style={{
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: DefaultAppStyles.GAP_SMALL
|
||||
}}
|
||||
>
|
||||
<Heading size={AppFontSize.md}>{apiKey.name}</Heading>
|
||||
{isApiKeyExpired && (
|
||||
<View
|
||||
style={{
|
||||
paddingVertical: 4,
|
||||
paddingHorizontal: 8,
|
||||
backgroundColor: colors.error.background,
|
||||
borderRadius: 5
|
||||
}}
|
||||
>
|
||||
<Paragraph
|
||||
color={colors.static.white}
|
||||
size={AppFontSize.xxs}
|
||||
style={{ fontWeight: "bold" }}
|
||||
>
|
||||
EXPIRED
|
||||
</Paragraph>
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
|
||||
<View style={{ gap: 4 }}>
|
||||
<Paragraph size={AppFontSize.xs} color={colors.secondary.paragraph}>
|
||||
{apiKey.lastUsedAt
|
||||
? `${strings.lastUsedOn()} ${dayjs(apiKey.lastUsedAt).format("MMM DD, YYYY")}`
|
||||
: strings.neverUsed()}
|
||||
</Paragraph>
|
||||
<Paragraph size={AppFontSize.xs} color={colors.secondary.paragraph}>
|
||||
{strings.createdOn()}{" "}
|
||||
{dayjs(apiKey.dateCreated).format("MMM DD, YYYY")}
|
||||
</Paragraph>
|
||||
<Paragraph size={AppFontSize.xs} color={colors.secondary.paragraph}>
|
||||
{apiKey.expiryDate === -1
|
||||
? strings.neverExpires()
|
||||
: `${isApiKeyExpired ? strings.expired() : strings.expiresOn()} ${dayjs(apiKey.expiryDate).format("MMM DD, YYYY")}`}
|
||||
</Paragraph>
|
||||
</View>
|
||||
|
||||
<View
|
||||
style={{
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: DefaultAppStyles.GAP_SMALL
|
||||
}}
|
||||
>
|
||||
<Input
|
||||
editable={false}
|
||||
value={
|
||||
viewing
|
||||
? apiKey.key
|
||||
: `${apiKey.key.slice(0, 10)}${"*".repeat(
|
||||
apiKey.key.length - 10
|
||||
)}`
|
||||
}
|
||||
style={{
|
||||
flex: 1,
|
||||
fontFamily: "monospace",
|
||||
fontSize: AppFontSize.xs
|
||||
}}
|
||||
wrapperStyle={{
|
||||
flex: 1
|
||||
}}
|
||||
/>
|
||||
{!viewing && (
|
||||
<IconButton
|
||||
name="eye-off-outline"
|
||||
color={colors.primary.icon}
|
||||
onPress={() => viewKey()}
|
||||
/>
|
||||
)}
|
||||
{viewing && (
|
||||
<>
|
||||
<Paragraph
|
||||
style={{
|
||||
fontFamily: "monospace",
|
||||
minWidth: 35,
|
||||
textAlign: "center"
|
||||
}}
|
||||
color={colors.primary.accent}
|
||||
>
|
||||
{secondsLeft}s
|
||||
</Paragraph>
|
||||
<IconButton
|
||||
name={copied ? "check" : "content-copy"}
|
||||
color={colors.primary.icon}
|
||||
onPress={() => copyToClipboard()}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
<IconButton
|
||||
name="delete-outline"
|
||||
color={colors.error.icon}
|
||||
disabled={isRevoking}
|
||||
onPress={async () => {
|
||||
presentDialog({
|
||||
title: strings.revokeInboxApiKey(apiKey.name),
|
||||
paragraph: strings.revokeApiKeyConfirmation(apiKey.name),
|
||||
positiveText: strings.revoke(),
|
||||
negativeText: strings.cancel(),
|
||||
positiveType: "error",
|
||||
positivePress: async () => {
|
||||
try {
|
||||
setIsRevoking(true);
|
||||
await db.inboxApiKeys.revoke(apiKey.key);
|
||||
onRevoke();
|
||||
ToastManager.show({
|
||||
message: strings.apiKeyRevoked(),
|
||||
type: "success"
|
||||
});
|
||||
return true;
|
||||
} catch (error) {
|
||||
ToastManager.show({
|
||||
message: strings.failedToRevokeApiKey(),
|
||||
type: "error"
|
||||
});
|
||||
return false;
|
||||
} finally {
|
||||
setIsRevoking(false);
|
||||
}
|
||||
}
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export { ManageInboxKeys, InboxKeysList };
|
||||
@@ -32,11 +32,11 @@ import { sleep } from "../../../utils/time";
|
||||
import { verifyUser } from "../functions";
|
||||
import { DefaultAppStyles } from "../../../utils/styles";
|
||||
|
||||
interface PickerOptions<T> {
|
||||
getValue: () => T;
|
||||
interface PickerOptions<T, B = any> {
|
||||
getValue: () => B;
|
||||
updateValue: (item: T) => Promise<void>;
|
||||
formatValue: (item: T) => any;
|
||||
compareValue: (current: T, item: T) => boolean;
|
||||
compareValue: (current: B, item: T) => boolean;
|
||||
getItemKey: (item: T) => string;
|
||||
options: T[];
|
||||
isFeatureAvailable: () => Promise<boolean>;
|
||||
@@ -170,7 +170,7 @@ export function SettingsPicker<T>({
|
||||
);
|
||||
}
|
||||
|
||||
export function createSettingsPicker<T>(props: PickerOptions<T>) {
|
||||
export function createSettingsPicker<T, B>(props: PickerOptions<T, B>) {
|
||||
const Selector = () => {
|
||||
return <SettingsPicker {...props} />;
|
||||
};
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user