mirror of
https://github.com/pewdiepie-archdaemon/odysseus.git
synced 2026-10-15 11:22:21 +02:00
refactor(notes): decompose Notes into feature-owned modules (#6713)
* refactor(notes): decompose Notes into feature-owned modules * fix(notes): avoid HTML interpolation in reminder picker * docs(notes): drop checkpoint archives, session logs and publication drafts The N0-N6 tarballs and raw pytest/node logs are not read by any script or test, and the logs carry absolute home-directory paths. Once squashed into dev they would stay in history for good. notes-pr.md and notes-issue.md were the drafts used to open #6712 and #6713, not documentation. notes-validation.md keeps the counts, the checkpoint hashes and implementation.sha256 as the record; local interpreter paths and the local Docker image name are replaced with portable placeholders. * fix(notes): keep the state store raw and stop masonry re-observing after close - state: writes built from views (filter, spread, splice) stored nested read-only views in the store, so structuredClone on a stored note threw DataCloneError. Store writes now unwrap nested views. - layout: a save that resolves after closePanel re-renders the leaving pane and re-created the masonry ResizeObserver that teardown had disposed. Skip creating it once Notes is closed. - index.js: drop 30 imported or declared names that were never used and group the imports at the top. Import order is unchanged. - Revert unrelated punctuation edits in .gitattributes and keep the header comment and docstring first in compare/vote.js and test_notes_dom_xss_helpers.py. Both fixes have a node test that fails on the previous head. * test(notes): make script rejection assertion case-insensitive Address CodeQL js/bad-tag-filter alert #1150 in test-only assertion and refresh Notes evidence manifest checksum. --------- Co-authored-by: Léo <leograndcontact@gmail.com>
This commit is contained in:
co-authored by
Léo
parent
9f8eae72fd
commit
f1a47f3812
@@ -36,3 +36,7 @@ static/lib/** -whitespace linguist-vendored
|
||||
*.ico binary
|
||||
*.woff binary
|
||||
*.woff2 binary
|
||||
|
||||
# Notes reference deployment modules.
|
||||
static/js/features/notes/** text eol=lf
|
||||
static/js/shared/ui/confetti.js text eol=lf
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
53dfddd71f02a9a60df42e3fb045bd1a80919d50870c0b77afe18a853f485bea .gitattributes
|
||||
867c6a4b025fefecb6ac4a91a38563a36107d9653599f64685e16a5be4fe7727 frontend/modules.json
|
||||
76de35ac93d72edb5dcd295e85c704af9b3f08c2fe9fdc56e0bcbebd4b322fd8 frontend/src/features/notes/application/agentActions.js
|
||||
37021f9643f6a3299d36b6021783a559e60ad84848ac2b12f0980b5034b6b9c4 frontend/src/features/notes/application/cardOperations.js
|
||||
fe3033db6ef316c6b15c6b01c0f202ee76a61ea2c5b6952b20144660ff17eb54 frontend/src/features/notes/application/checklistOperations.js
|
||||
85fc592724524bb5ff37d7e5e58a68fda9d7e645810b6c87a2d4dd3cb41f9dd5 frontend/src/features/notes/application/deletion.js
|
||||
ce38e7976ee315b198baebffe45f9a1f4e63d87affd9898ed5cf4bde37b903e7 frontend/src/features/notes/application/drafts.js
|
||||
6210915184c30f73911f144fe0d12a9935d6f2ce42cb2aaf6aeaa75614ca51a2 frontend/src/features/notes/application/queries.js
|
||||
0da923790f4036d5fe354df4e529feb4b96e178495cb951f269093c0a8347e4e frontend/src/features/notes/application/reminders.js
|
||||
8f95d086fc2e60beae32b9e9debba41b35448e1c5b4ac78e4989652ef2d44e35 frontend/src/features/notes/application/selection.js
|
||||
4ceb424b3b6e30a5f507804f42051be02390d4ce1f03ef284094e48825cde5c3 frontend/src/features/notes/application/state.js
|
||||
1c5d5af833aab91f71a34c11535885eb7bf9f751de5aa89f79defe0f696f20fb frontend/src/features/notes/application/submission.js
|
||||
1d58ea2d495c8d301c550eb9ba7f627c515a8784bcd105558d941522965e77b0 frontend/src/features/notes/application/workflows.js
|
||||
9ddbfb20e0a5564dd83365ad498286d68ef03fd60d632619ad4d9656e2f73c95 frontend/src/features/notes/domain/noteRules.js
|
||||
946ef7a98b0a2dbe329e8259250af11a11702c74fd997e17fb3aff007fbe40c9 frontend/src/features/notes/domain/recurrence.js
|
||||
25cf3a1cef5dbac0840aef513ffa010a9b08d206de96ce2527e6159a5454b555 frontend/src/features/notes/index.js
|
||||
8b186bbfbb003b8d738c80713e1cbb5c6924ee14119929c5ea65707b46076b0c frontend/src/features/notes/infrastructure/http.js
|
||||
c7552d1f4600ae721437892fc0a1e5a0332abe30082bd943cd13a379c9514fec frontend/src/features/notes/infrastructure/notifications.js
|
||||
ff91a55c55fbdd876c69d9ec10e4e992104c95b6d12d752d9745193fccbc646a frontend/src/features/notes/infrastructure/storage.js
|
||||
4ff6d69d04547a0325041f774c3bf0707d8b67982d59a221127e07dc9b01383c frontend/src/features/notes/ui/cardChecklist.js
|
||||
dd87f1929ef8a5d57fdf1ddb12a0a6be53d95be07946be54f946c6fe31ef80bc frontend/src/features/notes/ui/cardInteractions.js
|
||||
4ff661a65d88e810f346260a354070dba325d6beaa57d1c4e82e8bf09b894538 frontend/src/features/notes/ui/cardRendering.js
|
||||
113d4457f25291d15afb7fb6775ea063f24c9dac51bb0d262787c9e40705235b frontend/src/features/notes/ui/cardReorder.js
|
||||
eecafbd92076209fa41826820125fbe9ffa757d6d1bff018e9acc2ede2a18e72 frontend/src/features/notes/ui/checklist.js
|
||||
155ea3d70e653f38a62ff50fc5be6aee019d42e86d28753da9edb258ac7c93e1 frontend/src/features/notes/ui/checklistReorder.js
|
||||
5462fea63a2aa9d1fc07dca91b462f6ff24f352b05d99ea6feb437469c0e1f3e frontend/src/features/notes/ui/clipboard.js
|
||||
2619e5f8b15eb3057330ef220abe6bc354a496effc0df3d89385cdfef9242c86 frontend/src/features/notes/ui/colors.js
|
||||
11cf24e7e8e8954d764cb58d786fa6f6d71f84f1c6c5ba644d761e28cfdbaedf frontend/src/features/notes/ui/draftEditor.js
|
||||
f55d4eff7f550e183ecf240a45002936063dbb4eae153e11834da4cb6bd13d35 frontend/src/features/notes/ui/drawing.js
|
||||
f85c86e70b3a380449fe3c7ecc7a4e68946de320523f5edc8e33f8eab3f0a02a frontend/src/features/notes/ui/editor.js
|
||||
3946b8324ad8f0212621e526479668308e48b799bf0dbb608e5cd4626f6c1f03 frontend/src/features/notes/ui/filters.js
|
||||
a893d09e96fb98d13db8ae5c3fb8c5e7a040c62031dd961396a18b7ae2a82a38 frontend/src/features/notes/ui/layout.js
|
||||
8d8c62a87d4df134d3b9dd97eaf59d02c52f1a38f6bc2e109e8426081d453a8d frontend/src/features/notes/ui/lifecycle.js
|
||||
62ad9408cb139143168f2c5834ec56b83264c4daed3e84fa9b4b0a281712144c frontend/src/features/notes/ui/mobileEditor.js
|
||||
2a3ccbad103dcc880e4baf2b3aa3ece4df7b73752bd30078185f03227585148f frontend/src/features/notes/ui/mobileReorder.js
|
||||
856fe945cf697278f795b8753704119839fa12bc5e0e69e9dab57c4b4dd6d24e frontend/src/features/notes/ui/panel.js
|
||||
8aa081cb7341d9a67ef46c74da49aebd729e9b53a73d618b81c89566c874b507 frontend/src/features/notes/ui/quickAdd.js
|
||||
8a4f23a013f06876894e6544b49540b288007d0d7e4cddca955978588f47a64a frontend/src/features/notes/ui/reminderDisplay.js
|
||||
cb043be801ab40cf8141af6ff1ad788e69fef57a87960ca992071ad9ad29ad90 frontend/src/features/notes/ui/reminderPicker.js
|
||||
38f12ba7771589aa427f054f48919569dcee9abe0246e02b9767202adb854cdc frontend/src/features/notes/ui/selection.js
|
||||
2634f252b2899e2e70fc9fec37144b0cc9b0ed00724da81bfef74b1acf7c05b6 frontend/src/features/notes/ui/text.js
|
||||
d2655ef163825ce6c40d8ef46bc9dfc63a2aa19fb1a7e10b28002f79cb0db409 frontend/src/features/notes/ui/toolbar.js
|
||||
a0aa203e87814d0eebebb6b049776c3efd576f4a5c6e17e486c8a2893c9c21df frontend/src/features/notes/ui/windowLayout.js
|
||||
68f0cbe07c7b61fcaf92920cd47042c576ab27fd9553c971cff45c595c25d80a frontend/src/shared/ui/confetti.js
|
||||
c16fcde607dce2f10a1afd1f8845403a7d0b97a9d5a67ec7aa329c367ba585e8 scripts/verify_frontend_runtime.py
|
||||
c2e5de2b8ce168220bad4fcefed710e60eeb0dd3e992e76cd980f2c0ca52815a scripts/verify_notes_browser_runtime.py
|
||||
fa31d673c40f973490e9fac52130b4a915b944a7abdd217a9bd8d57e66d57ca6 static/js/compare/vote.js
|
||||
76de35ac93d72edb5dcd295e85c704af9b3f08c2fe9fdc56e0bcbebd4b322fd8 static/js/features/notes/application/agentActions.js
|
||||
37021f9643f6a3299d36b6021783a559e60ad84848ac2b12f0980b5034b6b9c4 static/js/features/notes/application/cardOperations.js
|
||||
fe3033db6ef316c6b15c6b01c0f202ee76a61ea2c5b6952b20144660ff17eb54 static/js/features/notes/application/checklistOperations.js
|
||||
85fc592724524bb5ff37d7e5e58a68fda9d7e645810b6c87a2d4dd3cb41f9dd5 static/js/features/notes/application/deletion.js
|
||||
ce38e7976ee315b198baebffe45f9a1f4e63d87affd9898ed5cf4bde37b903e7 static/js/features/notes/application/drafts.js
|
||||
6210915184c30f73911f144fe0d12a9935d6f2ce42cb2aaf6aeaa75614ca51a2 static/js/features/notes/application/queries.js
|
||||
0da923790f4036d5fe354df4e529feb4b96e178495cb951f269093c0a8347e4e static/js/features/notes/application/reminders.js
|
||||
8f95d086fc2e60beae32b9e9debba41b35448e1c5b4ac78e4989652ef2d44e35 static/js/features/notes/application/selection.js
|
||||
4ceb424b3b6e30a5f507804f42051be02390d4ce1f03ef284094e48825cde5c3 static/js/features/notes/application/state.js
|
||||
1c5d5af833aab91f71a34c11535885eb7bf9f751de5aa89f79defe0f696f20fb static/js/features/notes/application/submission.js
|
||||
1d58ea2d495c8d301c550eb9ba7f627c515a8784bcd105558d941522965e77b0 static/js/features/notes/application/workflows.js
|
||||
9ddbfb20e0a5564dd83365ad498286d68ef03fd60d632619ad4d9656e2f73c95 static/js/features/notes/domain/noteRules.js
|
||||
946ef7a98b0a2dbe329e8259250af11a11702c74fd997e17fb3aff007fbe40c9 static/js/features/notes/domain/recurrence.js
|
||||
25cf3a1cef5dbac0840aef513ffa010a9b08d206de96ce2527e6159a5454b555 static/js/features/notes/index.js
|
||||
8b186bbfbb003b8d738c80713e1cbb5c6924ee14119929c5ea65707b46076b0c static/js/features/notes/infrastructure/http.js
|
||||
c7552d1f4600ae721437892fc0a1e5a0332abe30082bd943cd13a379c9514fec static/js/features/notes/infrastructure/notifications.js
|
||||
ff91a55c55fbdd876c69d9ec10e4e992104c95b6d12d752d9745193fccbc646a static/js/features/notes/infrastructure/storage.js
|
||||
4ff6d69d04547a0325041f774c3bf0707d8b67982d59a221127e07dc9b01383c static/js/features/notes/ui/cardChecklist.js
|
||||
dd87f1929ef8a5d57fdf1ddb12a0a6be53d95be07946be54f946c6fe31ef80bc static/js/features/notes/ui/cardInteractions.js
|
||||
4ff661a65d88e810f346260a354070dba325d6beaa57d1c4e82e8bf09b894538 static/js/features/notes/ui/cardRendering.js
|
||||
113d4457f25291d15afb7fb6775ea063f24c9dac51bb0d262787c9e40705235b static/js/features/notes/ui/cardReorder.js
|
||||
eecafbd92076209fa41826820125fbe9ffa757d6d1bff018e9acc2ede2a18e72 static/js/features/notes/ui/checklist.js
|
||||
155ea3d70e653f38a62ff50fc5be6aee019d42e86d28753da9edb258ac7c93e1 static/js/features/notes/ui/checklistReorder.js
|
||||
5462fea63a2aa9d1fc07dca91b462f6ff24f352b05d99ea6feb437469c0e1f3e static/js/features/notes/ui/clipboard.js
|
||||
2619e5f8b15eb3057330ef220abe6bc354a496effc0df3d89385cdfef9242c86 static/js/features/notes/ui/colors.js
|
||||
11cf24e7e8e8954d764cb58d786fa6f6d71f84f1c6c5ba644d761e28cfdbaedf static/js/features/notes/ui/draftEditor.js
|
||||
f55d4eff7f550e183ecf240a45002936063dbb4eae153e11834da4cb6bd13d35 static/js/features/notes/ui/drawing.js
|
||||
f85c86e70b3a380449fe3c7ecc7a4e68946de320523f5edc8e33f8eab3f0a02a static/js/features/notes/ui/editor.js
|
||||
3946b8324ad8f0212621e526479668308e48b799bf0dbb608e5cd4626f6c1f03 static/js/features/notes/ui/filters.js
|
||||
a893d09e96fb98d13db8ae5c3fb8c5e7a040c62031dd961396a18b7ae2a82a38 static/js/features/notes/ui/layout.js
|
||||
8d8c62a87d4df134d3b9dd97eaf59d02c52f1a38f6bc2e109e8426081d453a8d static/js/features/notes/ui/lifecycle.js
|
||||
62ad9408cb139143168f2c5834ec56b83264c4daed3e84fa9b4b0a281712144c static/js/features/notes/ui/mobileEditor.js
|
||||
2a3ccbad103dcc880e4baf2b3aa3ece4df7b73752bd30078185f03227585148f static/js/features/notes/ui/mobileReorder.js
|
||||
856fe945cf697278f795b8753704119839fa12bc5e0e69e9dab57c4b4dd6d24e static/js/features/notes/ui/panel.js
|
||||
8aa081cb7341d9a67ef46c74da49aebd729e9b53a73d618b81c89566c874b507 static/js/features/notes/ui/quickAdd.js
|
||||
8a4f23a013f06876894e6544b49540b288007d0d7e4cddca955978588f47a64a static/js/features/notes/ui/reminderDisplay.js
|
||||
cb043be801ab40cf8141af6ff1ad788e69fef57a87960ca992071ad9ad29ad90 static/js/features/notes/ui/reminderPicker.js
|
||||
38f12ba7771589aa427f054f48919569dcee9abe0246e02b9767202adb854cdc static/js/features/notes/ui/selection.js
|
||||
2634f252b2899e2e70fc9fec37144b0cc9b0ed00724da81bfef74b1acf7c05b6 static/js/features/notes/ui/text.js
|
||||
d2655ef163825ce6c40d8ef46bc9dfc63a2aa19fb1a7e10b28002f79cb0db409 static/js/features/notes/ui/toolbar.js
|
||||
a0aa203e87814d0eebebb6b049776c3efd576f4a5c6e17e486c8a2893c9c21df static/js/features/notes/ui/windowLayout.js
|
||||
7f1a7961d586767298672fad71a0d627389e185f0fb28792a04d0b987e1d5c5c static/js/notes.js
|
||||
68f0cbe07c7b61fcaf92920cd47042c576ab27fd9553c971cff45c595c25d80a static/js/shared/ui/confetti.js
|
||||
97fd43c17f3cb1928947e24159a3b59dc81ef7dca95862e8a47154e9cb732f88 static/sw.js
|
||||
910cd5777564e9f6338b8a864a772beffea197dc476464171c180e7be96e572d tests/browser/notesNative.mjs
|
||||
ef4bc40a710919c81c582d3b9fe80376d0d5ae66fb9be3c293871a83ee360f97 tests/browser/notesOffline.mjs
|
||||
437ec2e9865b3e066bbec8d7595a0d947f1e503b96e7b4d819ec1bed86c9bb1e tests/browser/notesReference.mjs
|
||||
9af973a5d2fb08a5eed550be0198bef501af56802c3844b5d0bb8e718cc685cf tests/fixtures/notesRecurrenceBaseline.mjs
|
||||
859a5f442dc717f59993891c338cd6ae9d6e5e009392a2ee69ab0e3b063bb572 tests/helpers/notes_source.py
|
||||
739ffc3f20de8e2bdf1d513b17bf485f85821e9906109cdf8ffea04b81b0f1dd tests/notesApplication.test.mjs
|
||||
1946369be43177b19a44cd9ae4f90d64da6558d1a470f8e347b490a2188782be tests/notesCharacterization.test.mjs
|
||||
99f0cd92a30cf01c0ee6814f6684edeb80ebdb9a5ab96583244092865bfb6212 tests/notesDraftAutosave.test.mjs
|
||||
0417205809de16c7c7338ea80ba19ca844603b3e06655987226f5f83d962d18b tests/notesInfrastructure.test.mjs
|
||||
dcf7c2d33de9bb457f96af070354ecc3ab69669002bdc9c7c943bef1b3d2e9bc tests/notesRecurrence.test.mjs
|
||||
dd9a703465dde8f92625a3226ab52d20a02aa5d3415fbcc70609f69a372ccc12 tests/notesReminders.test.mjs
|
||||
5a9112569f226525faaf6603a9867620b47902534f9cd882c08f71f2f96614b2 tests/notesWorkflows.test.mjs
|
||||
35fb2bd1f02757b73188342ec00f1e97253b8ba8dfb577861675872a517bd949 tests/selectedNotesContext.test.mjs
|
||||
c6c64c2b695b84d00f8a80a980be00766175c482548c86484f991ef671ecfbe9 tests/test_notes_document_mutual_minimize.py
|
||||
02c2aeb856798d982e5debcb9c605172933b0216a039cf0d96cdd415b1e2ef83 tests/test_notes_dom_xss_helpers.py
|
||||
5a511c7a2ef5d28463df34f3462db9ce59575d624cf8181577bab2cc371b4f9f tests/test_notes_mobile_checklist_toggle_static.py
|
||||
1db10a0d344818459d64279da807ddefe9b866dfe560ac4b154b486dd1a5efc0 tests/test_notes_reference_browser.py
|
||||
49f466b1a717098aa25439b6ff9ef3ae3d027d9dd976212b165b0b99a582b952 tests/test_notes_reference_contracts_js.py
|
||||
c2d877a11eafcb99b24a1c89111e5df4453a62bc8cf7d26ae1118b25c4a5ace4 tests/test_notes_search_reset_on_reopen_js.py
|
||||
6d95f073421427b5e149ef1e85c8b5749095d00337f05960134552985f73e372 tests/test_notes_select_esc_listener_js.py
|
||||
b3118a4b40fcfcbb26ad9ccbcb332fc6ced873d8cad1160be38a286ad1e664a4 tests/test_notes_sidebar_new_note.py
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 60 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 28 KiB |
@@ -1,9 +1,10 @@
|
||||
# Odysseus frontend architecture handbook
|
||||
|
||||
Status: F1 foundation and continuation guide, pending review. The final Notes
|
||||
reference case study belongs to the comprehensive Notes draft PR; the recipient
|
||||
handoff follows its integration. This document must evolve with reviewed internal
|
||||
checkpoints and distinguish executed work from proposals.
|
||||
Status: F1 merged in PR #6701. The complete Notes reference is implemented as an
|
||||
unpublished review diff on `refactor/notes-reference-decomposition`. Read its
|
||||
[case study](notes-case-study.md), [module inventory](notes-module-inventory.md)
|
||||
and [validation receipts](notes-validation.md). Publication and the recipient's
|
||||
post-integration reproduction remain pending.
|
||||
|
||||
Read the [ADR](ADR-001-source-and-deployment.md), [assessment](assessment.md),
|
||||
[validation report](validation.md) and [Notes roadmap](notes-roadmap.md).
|
||||
@@ -90,6 +91,13 @@ existing objects and initialization timing when extracting a stateful module.
|
||||
Do not instantiate a new store in both the legacy facade and the feature API.
|
||||
Compatibility facades only forward the same live implementation.
|
||||
|
||||
The Notes reference uses internal read-only live views to preserve captured note
|
||||
identity across existing asynchronous completions. Its state owner supplies all
|
||||
mutations; the public index exposes operations without the store. Notes deliberately
|
||||
retains last-completion fetch ordering. Do not infer request-generation guards from
|
||||
its decomposition. Its page-owned reminders survive panel closure, and panel/editor
|
||||
listeners and observers have separate disposal scopes.
|
||||
|
||||
Document lifecycle scopes: page, authenticated user, session, mounted panel and
|
||||
editor/draft. Name owners of subscriptions, DOM listeners, timers, observers,
|
||||
pending requests and caches. Mounting must be idempotent; disposal releases the
|
||||
|
||||
@@ -0,0 +1,260 @@
|
||||
# Notes reference decomposition
|
||||
|
||||
Implementation started: 2026-10-13. Final validation: 2026-10-14.
|
||||
Foundation: [PR #6701](https://github.com/odysseus-dev/odysseus/pull/6701),
|
||||
`1cc56cb9d78f3e2399d1d61155b71d771a17b85b`. Branch was safely updated via
|
||||
non-destructive fast-forward to latest official `upstream/dev` at
|
||||
`86b886c611338282af6d4a717246ea4e256f58df`, incorporating PRs #6704 and #6693.
|
||||
Neither changed a file in the Notes diff. The independent AGY audit returned
|
||||
CONDITIONAL PASS; all pre-publication corrective actions (issue template conformance,
|
||||
PR template conformance, visual evidence paths, and em-dash removal) have been completed.
|
||||
|
||||
The entire implementation belongs to one Notes PR. N0 through N6 are internal
|
||||
checkpoints, not separate branches, commits or PRs. The [validation receipts](notes-validation.md),
|
||||
[module inventory](notes-module-inventory.md) and [changed-file inventory](notes-changed-files.md)
|
||||
accompany this case study.
|
||||
|
||||
## Responsibility map and size
|
||||
|
||||
The original `static/js/notes.js` contained 5,471 lines. It mixed mutable Notes
|
||||
data, view preferences, selection, undo, CRUD, date calculations, reminders,
|
||||
browser persistence, editor autosave, rendering, canvas tools and window management.
|
||||
Its import evaluated storage preferences and scheduled reminder initialization.
|
||||
|
||||
| Original responsibility | Maintained owner |
|
||||
| --- | --- |
|
||||
| Completion, tags, recurrence, date labels and serialization | `domain/recurrence.js`, `domain/noteRules.js` |
|
||||
| Notes data and selection/filter/editing state | `application/state.js`, instantiated once in `index.js` |
|
||||
| CRUD, undo and fetch completion ordering | `application/workflows.js`, `cardOperations.js`, `deletion.js` |
|
||||
| Checklist mutations and rollback | `application/checklistOperations.js` |
|
||||
| Editor optimistic submission and recovery | `application/submission.js` |
|
||||
| Serialized autosave and synchronous backup | `application/drafts.js`; form collection in `ui/draftEditor.js` |
|
||||
| Filtering, searching and ordering | `application/queries.js`; controls in `ui/filters.js` and `toolbar.js` |
|
||||
| Selected-note attachment and bulk requests | `application/selection.js`; controls in `ui/selection.js` |
|
||||
| Existing agent-solve workflow | `application/agentActions.js`, through supplied HTTP/session ports |
|
||||
| HTTP, persistence and browser notifications | `infrastructure/http.js`, `storage.js`, `notifications.js` |
|
||||
| Background scheduler and delivery decisions | `application/reminders.js` |
|
||||
| Panel mounting, closing, keyboard handling and navigation | `ui/panel.js` |
|
||||
| Docking, fullscreen bounds and stacking | `ui/windowLayout.js`, using existing shared capabilities |
|
||||
| Cards, card gestures, quick add and masonry | `ui/cardRendering.js`, `cardInteractions.js`, `cardChecklist.js`, `cardReorder.js`, `quickAdd.js`, `layout.js` |
|
||||
| Editor types, colors, reminders and checklists | `ui/editor.js`, `colors.js`, `reminderPicker.js`, `checklist.js` |
|
||||
| Drawing, local drawing undo and PNG upload | `ui/drawing.js` |
|
||||
| Mobile reader/editor and reorder gestures | `ui/mobileEditor.js`, `mobileReorder.js`, `checklistReorder.js` |
|
||||
| Clipboard, safe rendering and reminder display | `ui/clipboard.js`, `text.js`, `reminderDisplay.js` |
|
||||
| Owned document/window listener disposal | `ui/lifecycle.js`, with panel and observer disposal callbacks |
|
||||
| Composition and supported exports | `index.js`; five-line legacy facade at `static/js/notes.js` |
|
||||
|
||||
The feature has 41 maintained modules: two domain, eleven application, three
|
||||
infrastructure, twenty-four UI and one index. Source is counted once, excluding
|
||||
byte-identical deployment copies. Domain has 356 lines, application 826,
|
||||
infrastructure 112, UI 4,628, and composition 518: 6,440 maintained feature lines.
|
||||
The module inventory records final per-file counts. The legacy entry shrank
|
||||
from 5,471 to five lines. Interfaces and explicit composition increase the total
|
||||
source size; reducing total lines was not the architectural objective.
|
||||
|
||||
One 28-line stateless confetti renderer also moved to `shared/ui/confetti.js`.
|
||||
Notes and Compare both use it. Compare retains its existing `spawnConfetti` export,
|
||||
which is the same function as the shared export. This removes Notes' import of
|
||||
Compare's private voting implementation without migrating Compare itself.
|
||||
|
||||
## Dependency graph and composition
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
Legacy[Legacy Notes URL and window bridge] --> Index[Notes index: one composition]
|
||||
Index --> UI[Notes UI factories]
|
||||
Index --> App[Application workflows and state owner]
|
||||
Index --> Ports[HTTP, persistence and notification adapters]
|
||||
UI --> Rules[Pure domain rules]
|
||||
App --> Rules
|
||||
Index --> Shared[Existing shared UI capabilities and maintained confetti]
|
||||
```
|
||||
|
||||
Application modules receive adapters and feedback operations as arguments. They
|
||||
do not import browser infrastructure or DOM views. Pure domain modules receive
|
||||
the clock at the original read sites. UI consumes a read-only state view and
|
||||
application operations. Composition supplies callbacks between views and workflows;
|
||||
modules do not import the coordinator back. F1 rejects maintained-source cycles.
|
||||
|
||||
There are nine exact legacy-import exceptions, all on the Notes index. They bridge
|
||||
the existing UI, modal, color-picker, drag, tile, dock, stacking, Escape and tour-hint
|
||||
capabilities at their existing URLs. Their removal condition is migration of the
|
||||
corresponding shared responsibility to maintained source with its identity and
|
||||
lifecycle contract verified. No new feature imports another feature's private internals.
|
||||
|
||||
## State and asynchronous ownership
|
||||
|
||||
`createNotesState` is called once. It owns the Notes collection, selection IDs,
|
||||
editing ID, search, filters, archive/view flags, loading and dismissed-reminder time.
|
||||
Neither the facade nor reminders create a second collection. The public feature API
|
||||
does not expose this store.
|
||||
|
||||
Internal views are read-only live views rather than detached snapshots. This choice
|
||||
preserves captured note identity: an existing asynchronous rollback still acts on
|
||||
the same captured note. Array/object writes and selection mutations must use the
|
||||
state owner's operations. Workflow-local undo queues and serialized draft promises,
|
||||
and UI-local canvas undo/gesture state, are not competing Notes stores.
|
||||
|
||||
Fetches retain the original last-completion behavior. An earlier request that
|
||||
finishes later can overwrite a later request's result. Tests pin this behavior;
|
||||
generation guards would be a separate behavioral change. Submission also retains
|
||||
the original first-temporary-note replacement rule. Multiple simultaneous creations
|
||||
need a separately reviewed correlation fix, not a silent change during extraction.
|
||||
|
||||
Archive, unarchive, pin, item edit/remove/add, delete and undo preserve their original
|
||||
optimistic ordering and rollback. Animation callbacks remain view-owned. Drawing
|
||||
save keeps the existing button guard around its asynchronous PNG upload. Draft writes
|
||||
are serialized per editor; a completed older save cannot clear a newer local draft.
|
||||
|
||||
Reminder scans still use the originally loaded Notes collection, not a second
|
||||
all-active cache. An archived-only collection or a failure-cleared list can defer
|
||||
active reminders until an active refresh/reopen. The timer remains alive when the
|
||||
panel closes, but extraction does not redesign this inherited data-availability
|
||||
limitation. Review such a change separately from scheduler/state ownership.
|
||||
|
||||
## Public compatibility
|
||||
|
||||
The import URL remains `/static/js/notes.js?v=20260911notesselectioncancel1`.
|
||||
App, Chat stream updates, Chat note links and Documents continue using their existing
|
||||
imports. Calendar and Documents retain their window bridge calls. HTML and app
|
||||
bootstrap code are unchanged. The service worker retains the exact legacy entry.
|
||||
|
||||
The legacy namespace still exports `openPanel`, `closePanel`, `togglePanel`,
|
||||
`isPanelOpen`, `openNote`, `newNote`, `refreshDueBadge`, `dismissFiredReminderDot`,
|
||||
`openNotes`, `closeNotes`, `isNotesOpen`, and `default`.
|
||||
The default object's ten methods are unchanged; `dismissFiredReminderDot` remains
|
||||
named-only. Aliases refer to the same functions, including those on the default
|
||||
object. `openNote` and `refreshDueBadge` remain async; function arities are pinned.
|
||||
|
||||
`window.notesModule` is exactly the default controller. The canonical unversioned
|
||||
feature index and both tested legacy entry URLs share the same controller and
|
||||
operations. The default object retains its existing mutability. A different legacy
|
||||
URL has its own ESM namespace, as native ESM requires, but creates no second store
|
||||
or scheduler because it forwards to the same canonical index.
|
||||
|
||||
The canonical index additionally exports `startNotesBackground` for explicit
|
||||
activation. The compatibility facade invokes it once through an idempotent start
|
||||
operation. Existing consumers need no change. Remove the facade only after every
|
||||
consumer, global bridge, bootstrap and offline reference has migrated together.
|
||||
|
||||
## Protected selected Notes/Todos integration
|
||||
|
||||
The sender dispatches `odysseus:notes-context-selected` on `window` with
|
||||
`{ noteIds, accepted: false }`. Dispatch and acknowledgement remain synchronous.
|
||||
Chat owns acceptance, its session/pending selection, the context indicator and
|
||||
the `selected_note_ids` send payload. Notes exits selection only after acceptance.
|
||||
Rejected selections stay selected and display the existing feedback.
|
||||
|
||||
No Chat internals were imported or changed. Existing session lifecycle events still
|
||||
transfer a pending selection on materialization, restore selections on chat switches,
|
||||
and reset them for a new chat. Backend ID validation and owner filtering remain
|
||||
authoritative. Unit/backend tests cover these contracts; the real authenticated
|
||||
browser probe verifies rejection, pending-chat acceptance, the actual indicator and
|
||||
new-chat reset. Live model execution is not part of that probe.
|
||||
|
||||
## Persistence and HTTP contracts
|
||||
|
||||
| Key | Preserved format |
|
||||
| --- | --- |
|
||||
| `odysseus-notes-view` | `list` or `grid` |
|
||||
| `odysseus-notes-labels-collapsed` | `1` or `0` |
|
||||
| `odysseus-notes-first-open-hint-v1` | Existing first-open marker |
|
||||
| `odysseus-notes-reminder-fired` | JSON array of IDs |
|
||||
| `odysseus-notes-reminder-glowed` | JSON array of IDs |
|
||||
| `odysseus-notes-reminder-pending-highlight` | JSON array of IDs |
|
||||
| `odysseus-notes-reminder-active-highlight` | JSON array of IDs |
|
||||
| `odysseus-notes-reminder-dismissed-at` | Decimal millisecond timestamp |
|
||||
| `odysseus-note-draft-<id>` and `odysseus-note-draft-__new__` | Existing JSON draft fields and `_ts` |
|
||||
|
||||
CRUD, reorder, upload, reminder firing, default-chat lookup, session creation and
|
||||
chat-stream requests keep their URLs, methods, credentials, payloads and error
|
||||
interpretation. Uploads retain `files` and optional `gallery_id` multipart fields.
|
||||
The agent-solve stream still disables `manage_notes` and drains without switching
|
||||
the user's chat. No backend implementation changed.
|
||||
|
||||
Storage backup failures still warn once; failed network saves keep recoverable
|
||||
drafts, including intentionally empty text. Draft JSON does not serialize a canvas
|
||||
bitmap. A drawing remains ephemeral until its explicit PNG upload, as before.
|
||||
|
||||
## Lifecycle scopes and explicit corrections
|
||||
|
||||
| Scope | Owner and disposal |
|
||||
| --- | --- |
|
||||
| Browser page | One reminder startup timeout and interval; page termination ends them. The reminder factory also has explicit disposal. |
|
||||
| Open panel | Capture/bubble keyboard handlers, reorder listeners and masonry observer; both close paths dispose them. |
|
||||
| Editor/canvas | Local DOM handlers and draft workflow; drawing's window listener is released when its canvas detaches or the panel closes. |
|
||||
| Mobile editor/gesture | Overlay and document touch handlers; owner replacement and panel disposal remove handlers and reset registration flags. |
|
||||
| Menus/hints | Notes portals close with the panel; shared dismiss functions unregister their Escape/tour lifetimes. |
|
||||
| File picker | Existing completion or 30-second cleanup owns the temporary input. |
|
||||
|
||||
Two implementation corrections follow the user's explicit lifecycle requirements.
|
||||
The original close paths canceled the supposedly background reminder interval.
|
||||
The new page-owned interval survives closing/minimizing Notes, while retaining the
|
||||
3-second startup delay, 30-second period and immediate first check. Closing a panel
|
||||
also releases owned observers/listeners, pending hold timers, active Notes gestures
|
||||
and portals; late panel fetch callbacks do
|
||||
not recreate UI on a detached panel. Network completion/state ordering is preserved.
|
||||
|
||||
Shared drag/window utilities continue owning their own active-gesture handlers.
|
||||
They were not moved into Notes. Idle open/close and editor replacement are verified;
|
||||
every possible interleaving with an active shared window drag was not tested.
|
||||
|
||||
## Source and deployment
|
||||
|
||||
Every maintained source is registered in `frontend/modules.json` and copied without
|
||||
rewriting imports. Notes sources map to `static/js/features/notes/` at the same
|
||||
relative paths. Shared confetti maps to `static/js/shared/ui/confetti.js`.
|
||||
Repository-owned LF attributes and byte parity cover all 43 maintained modules,
|
||||
including the unchanged F1 proof. The legacy facade is an authored compatibility
|
||||
entry, not a second implementation.
|
||||
|
||||
All new outputs join exact service-worker precache arrays. A real offline test also
|
||||
found eight previously missing exact legacy URLs in the Notes graph; those entries
|
||||
are now included. The eager Notes graph has 57 exact runtime URLs. Cache naming
|
||||
follows the repository's `odysseus-v659-notes-reference` convention. Root offline
|
||||
reload remains outside certification because the existing worker scope is `/static/`.
|
||||
|
||||
Python startup and Docker serve the committed static graph without maintained
|
||||
source or frontend tooling. The publisher is a development check/copy operation,
|
||||
not a runtime compiler or an atomic deployment system.
|
||||
|
||||
## Checkpoints, rollback and lessons
|
||||
|
||||
[Checkpoint receipts](notes-validation.md#internal-checkpoints) record the actual
|
||||
checks and local snapshot hashes. These intermediate snapshots are engineering
|
||||
evidence, not standalone release artifacts. N5 includes bounded editor, cards,
|
||||
checklist, drawing, mobile, toolbar and window reviews on the same branch.
|
||||
|
||||
The N3 mechanical state rewrite initially confused canvas-local and feature undo
|
||||
bindings. The N5 drawing test found it; the canvas binding was restored and the
|
||||
same drawing/undo interaction was replayed against the original implementation.
|
||||
Use scope-aware transformations and test each stateful UI responsibility before
|
||||
accepting a broad rewrite. Source parsing alone does not prove semantic equivalence.
|
||||
|
||||
For rollback, reconstruct the prior complete artifact from its revision/snapshot
|
||||
in a fresh temporary directory, run parity/graph/behavior checks there, then publish
|
||||
the matching static graph and service worker as a unit through the authorized
|
||||
release process. Restore the whole facade/source/output/manifest set, not just
|
||||
`notes.js`. No schema or storage-key migration needs reversal. Do not reset a dirty
|
||||
worktree or delete unrelated outputs. The validation report gives a non-destructive
|
||||
snapshot reproduction recipe.
|
||||
|
||||
For the next maintainer:
|
||||
|
||||
1. Start with the module inventory and the state/workflow contracts, then reproduce
|
||||
the focused tests, offline test and isolated native browser probe.
|
||||
2. Review the explicit timer/lifecycle corrections separately from unchanged
|
||||
business rules. Inspect both maintained source and byte-identical deployment.
|
||||
3. Resolve or track the reproduced upstream CI failures and the open PR overlaps
|
||||
before authorizing publication. Create/link the dedicated issue, then publish
|
||||
exactly one Notes PR targeting official `dev`.
|
||||
4. Record the integrated revision and independent recipient reproduction to complete
|
||||
H. The designated maintainer can then apply this method to future features.
|
||||
|
||||
For Calendar, Documents, Email and later monoliths, characterize actual exports,
|
||||
URL identities, state writers, clock reads, I/O and lifecycle first. Extract pure
|
||||
rules, then adapters, then a single state owner/workflows. Use explicit callback
|
||||
ports to break coordinator cycles. Split UI by interactions and resource lifetime,
|
||||
not by arbitrary line ranges. Transfer source/output ownership and offline URLs
|
||||
with each boundary, and preserve source-sensitive assertions at their new owner.
|
||||
Those feature migrations are not part of this implementation.
|
||||
@@ -0,0 +1,165 @@
|
||||
# Notes complete changed-file inventory
|
||||
|
||||
Changed files in PR #6713 (`refactor/notes-reference-decomposition`) against
|
||||
`dev`. 121 files: 16 modified and 105 added. No files are deleted. Deployment copies
|
||||
are byte-identical to their registered maintained sources. Image files are review
|
||||
evidence, not production dependencies.
|
||||
|
||||
The unchanged foundation worktree, backend, app bootstrap, HTML, CSS, dependency
|
||||
lockfiles, Dockerfile and CI workflow are outside this diff. The only Compare
|
||||
change delegates its existing stateless confetti export to maintained shared UI.
|
||||
|
||||
## Maintained source (42)
|
||||
|
||||
| Status | File |
|
||||
| --- | --- |
|
||||
| A | [frontend/src/features/notes/application/agentActions.js](../../frontend/src/features/notes/application/agentActions.js) |
|
||||
| A | [frontend/src/features/notes/application/cardOperations.js](../../frontend/src/features/notes/application/cardOperations.js) |
|
||||
| A | [frontend/src/features/notes/application/checklistOperations.js](../../frontend/src/features/notes/application/checklistOperations.js) |
|
||||
| A | [frontend/src/features/notes/application/deletion.js](../../frontend/src/features/notes/application/deletion.js) |
|
||||
| A | [frontend/src/features/notes/application/drafts.js](../../frontend/src/features/notes/application/drafts.js) |
|
||||
| A | [frontend/src/features/notes/application/queries.js](../../frontend/src/features/notes/application/queries.js) |
|
||||
| A | [frontend/src/features/notes/application/reminders.js](../../frontend/src/features/notes/application/reminders.js) |
|
||||
| A | [frontend/src/features/notes/application/selection.js](../../frontend/src/features/notes/application/selection.js) |
|
||||
| A | [frontend/src/features/notes/application/state.js](../../frontend/src/features/notes/application/state.js) |
|
||||
| A | [frontend/src/features/notes/application/submission.js](../../frontend/src/features/notes/application/submission.js) |
|
||||
| A | [frontend/src/features/notes/application/workflows.js](../../frontend/src/features/notes/application/workflows.js) |
|
||||
| A | [frontend/src/features/notes/domain/noteRules.js](../../frontend/src/features/notes/domain/noteRules.js) |
|
||||
| A | [frontend/src/features/notes/domain/recurrence.js](../../frontend/src/features/notes/domain/recurrence.js) |
|
||||
| A | [frontend/src/features/notes/index.js](../../frontend/src/features/notes/index.js) |
|
||||
| A | [frontend/src/features/notes/infrastructure/http.js](../../frontend/src/features/notes/infrastructure/http.js) |
|
||||
| A | [frontend/src/features/notes/infrastructure/notifications.js](../../frontend/src/features/notes/infrastructure/notifications.js) |
|
||||
| A | [frontend/src/features/notes/infrastructure/storage.js](../../frontend/src/features/notes/infrastructure/storage.js) |
|
||||
| A | [frontend/src/features/notes/ui/cardChecklist.js](../../frontend/src/features/notes/ui/cardChecklist.js) |
|
||||
| A | [frontend/src/features/notes/ui/cardInteractions.js](../../frontend/src/features/notes/ui/cardInteractions.js) |
|
||||
| A | [frontend/src/features/notes/ui/cardRendering.js](../../frontend/src/features/notes/ui/cardRendering.js) |
|
||||
| A | [frontend/src/features/notes/ui/cardReorder.js](../../frontend/src/features/notes/ui/cardReorder.js) |
|
||||
| A | [frontend/src/features/notes/ui/checklist.js](../../frontend/src/features/notes/ui/checklist.js) |
|
||||
| A | [frontend/src/features/notes/ui/checklistReorder.js](../../frontend/src/features/notes/ui/checklistReorder.js) |
|
||||
| A | [frontend/src/features/notes/ui/clipboard.js](../../frontend/src/features/notes/ui/clipboard.js) |
|
||||
| A | [frontend/src/features/notes/ui/colors.js](../../frontend/src/features/notes/ui/colors.js) |
|
||||
| A | [frontend/src/features/notes/ui/draftEditor.js](../../frontend/src/features/notes/ui/draftEditor.js) |
|
||||
| A | [frontend/src/features/notes/ui/drawing.js](../../frontend/src/features/notes/ui/drawing.js) |
|
||||
| A | [frontend/src/features/notes/ui/editor.js](../../frontend/src/features/notes/ui/editor.js) |
|
||||
| A | [frontend/src/features/notes/ui/filters.js](../../frontend/src/features/notes/ui/filters.js) |
|
||||
| A | [frontend/src/features/notes/ui/layout.js](../../frontend/src/features/notes/ui/layout.js) |
|
||||
| A | [frontend/src/features/notes/ui/lifecycle.js](../../frontend/src/features/notes/ui/lifecycle.js) |
|
||||
| A | [frontend/src/features/notes/ui/mobileEditor.js](../../frontend/src/features/notes/ui/mobileEditor.js) |
|
||||
| A | [frontend/src/features/notes/ui/mobileReorder.js](../../frontend/src/features/notes/ui/mobileReorder.js) |
|
||||
| A | [frontend/src/features/notes/ui/panel.js](../../frontend/src/features/notes/ui/panel.js) |
|
||||
| A | [frontend/src/features/notes/ui/quickAdd.js](../../frontend/src/features/notes/ui/quickAdd.js) |
|
||||
| A | [frontend/src/features/notes/ui/reminderDisplay.js](../../frontend/src/features/notes/ui/reminderDisplay.js) |
|
||||
| A | [frontend/src/features/notes/ui/reminderPicker.js](../../frontend/src/features/notes/ui/reminderPicker.js) |
|
||||
| A | [frontend/src/features/notes/ui/selection.js](../../frontend/src/features/notes/ui/selection.js) |
|
||||
| A | [frontend/src/features/notes/ui/text.js](../../frontend/src/features/notes/ui/text.js) |
|
||||
| A | [frontend/src/features/notes/ui/toolbar.js](../../frontend/src/features/notes/ui/toolbar.js) |
|
||||
| A | [frontend/src/features/notes/ui/windowLayout.js](../../frontend/src/features/notes/ui/windowLayout.js) |
|
||||
| A | [frontend/src/shared/ui/confetti.js](../../frontend/src/shared/ui/confetti.js) |
|
||||
|
||||
## Deployment copies (42)
|
||||
|
||||
| Status | File |
|
||||
| --- | --- |
|
||||
| A | [static/js/features/notes/application/agentActions.js](../../static/js/features/notes/application/agentActions.js) |
|
||||
| A | [static/js/features/notes/application/cardOperations.js](../../static/js/features/notes/application/cardOperations.js) |
|
||||
| A | [static/js/features/notes/application/checklistOperations.js](../../static/js/features/notes/application/checklistOperations.js) |
|
||||
| A | [static/js/features/notes/application/deletion.js](../../static/js/features/notes/application/deletion.js) |
|
||||
| A | [static/js/features/notes/application/drafts.js](../../static/js/features/notes/application/drafts.js) |
|
||||
| A | [static/js/features/notes/application/queries.js](../../static/js/features/notes/application/queries.js) |
|
||||
| A | [static/js/features/notes/application/reminders.js](../../static/js/features/notes/application/reminders.js) |
|
||||
| A | [static/js/features/notes/application/selection.js](../../static/js/features/notes/application/selection.js) |
|
||||
| A | [static/js/features/notes/application/state.js](../../static/js/features/notes/application/state.js) |
|
||||
| A | [static/js/features/notes/application/submission.js](../../static/js/features/notes/application/submission.js) |
|
||||
| A | [static/js/features/notes/application/workflows.js](../../static/js/features/notes/application/workflows.js) |
|
||||
| A | [static/js/features/notes/domain/noteRules.js](../../static/js/features/notes/domain/noteRules.js) |
|
||||
| A | [static/js/features/notes/domain/recurrence.js](../../static/js/features/notes/domain/recurrence.js) |
|
||||
| A | [static/js/features/notes/index.js](../../static/js/features/notes/index.js) |
|
||||
| A | [static/js/features/notes/infrastructure/http.js](../../static/js/features/notes/infrastructure/http.js) |
|
||||
| A | [static/js/features/notes/infrastructure/notifications.js](../../static/js/features/notes/infrastructure/notifications.js) |
|
||||
| A | [static/js/features/notes/infrastructure/storage.js](../../static/js/features/notes/infrastructure/storage.js) |
|
||||
| A | [static/js/features/notes/ui/cardChecklist.js](../../static/js/features/notes/ui/cardChecklist.js) |
|
||||
| A | [static/js/features/notes/ui/cardInteractions.js](../../static/js/features/notes/ui/cardInteractions.js) |
|
||||
| A | [static/js/features/notes/ui/cardRendering.js](../../static/js/features/notes/ui/cardRendering.js) |
|
||||
| A | [static/js/features/notes/ui/cardReorder.js](../../static/js/features/notes/ui/cardReorder.js) |
|
||||
| A | [static/js/features/notes/ui/checklist.js](../../static/js/features/notes/ui/checklist.js) |
|
||||
| A | [static/js/features/notes/ui/checklistReorder.js](../../static/js/features/notes/ui/checklistReorder.js) |
|
||||
| A | [static/js/features/notes/ui/clipboard.js](../../static/js/features/notes/ui/clipboard.js) |
|
||||
| A | [static/js/features/notes/ui/colors.js](../../static/js/features/notes/ui/colors.js) |
|
||||
| A | [static/js/features/notes/ui/draftEditor.js](../../static/js/features/notes/ui/draftEditor.js) |
|
||||
| A | [static/js/features/notes/ui/drawing.js](../../static/js/features/notes/ui/drawing.js) |
|
||||
| A | [static/js/features/notes/ui/editor.js](../../static/js/features/notes/ui/editor.js) |
|
||||
| A | [static/js/features/notes/ui/filters.js](../../static/js/features/notes/ui/filters.js) |
|
||||
| A | [static/js/features/notes/ui/layout.js](../../static/js/features/notes/ui/layout.js) |
|
||||
| A | [static/js/features/notes/ui/lifecycle.js](../../static/js/features/notes/ui/lifecycle.js) |
|
||||
| A | [static/js/features/notes/ui/mobileEditor.js](../../static/js/features/notes/ui/mobileEditor.js) |
|
||||
| A | [static/js/features/notes/ui/mobileReorder.js](../../static/js/features/notes/ui/mobileReorder.js) |
|
||||
| A | [static/js/features/notes/ui/panel.js](../../static/js/features/notes/ui/panel.js) |
|
||||
| A | [static/js/features/notes/ui/quickAdd.js](../../static/js/features/notes/ui/quickAdd.js) |
|
||||
| A | [static/js/features/notes/ui/reminderDisplay.js](../../static/js/features/notes/ui/reminderDisplay.js) |
|
||||
| A | [static/js/features/notes/ui/reminderPicker.js](../../static/js/features/notes/ui/reminderPicker.js) |
|
||||
| A | [static/js/features/notes/ui/selection.js](../../static/js/features/notes/ui/selection.js) |
|
||||
| A | [static/js/features/notes/ui/text.js](../../static/js/features/notes/ui/text.js) |
|
||||
| A | [static/js/features/notes/ui/toolbar.js](../../static/js/features/notes/ui/toolbar.js) |
|
||||
| A | [static/js/features/notes/ui/windowLayout.js](../../static/js/features/notes/ui/windowLayout.js) |
|
||||
| A | [static/js/shared/ui/confetti.js](../../static/js/shared/ui/confetti.js) |
|
||||
|
||||
## Compatibility and deployment configuration (5)
|
||||
|
||||
| Status | File |
|
||||
| --- | --- |
|
||||
| M | [.gitattributes](../../.gitattributes) |
|
||||
| M | [frontend/modules.json](../../frontend/modules.json) |
|
||||
| M | [static/js/compare/vote.js](../../static/js/compare/vote.js) |
|
||||
| M | [static/js/notes.js](../../static/js/notes.js) |
|
||||
| M | [static/sw.js](../../static/sw.js) |
|
||||
|
||||
## Tests (21)
|
||||
|
||||
| Status | File |
|
||||
| --- | --- |
|
||||
| A | [tests/browser/notesNative.mjs](../../tests/browser/notesNative.mjs) |
|
||||
| A | [tests/browser/notesOffline.mjs](../../tests/browser/notesOffline.mjs) |
|
||||
| A | [tests/browser/notesReference.mjs](../../tests/browser/notesReference.mjs) |
|
||||
| A | [tests/fixtures/notesRecurrenceBaseline.mjs](../../tests/fixtures/notesRecurrenceBaseline.mjs) |
|
||||
| A | [tests/helpers/notes_source.py](../../tests/helpers/notes_source.py) |
|
||||
| A | [tests/notesApplication.test.mjs](../../tests/notesApplication.test.mjs) |
|
||||
| A | [tests/notesCharacterization.test.mjs](../../tests/notesCharacterization.test.mjs) |
|
||||
| M | [tests/notesDraftAutosave.test.mjs](../../tests/notesDraftAutosave.test.mjs) |
|
||||
| A | [tests/notesInfrastructure.test.mjs](../../tests/notesInfrastructure.test.mjs) |
|
||||
| A | [tests/notesRecurrence.test.mjs](../../tests/notesRecurrence.test.mjs) |
|
||||
| A | [tests/notesReminders.test.mjs](../../tests/notesReminders.test.mjs) |
|
||||
| A | [tests/notesWorkflows.test.mjs](../../tests/notesWorkflows.test.mjs) |
|
||||
| M | [tests/selectedNotesContext.test.mjs](../../tests/selectedNotesContext.test.mjs) |
|
||||
| M | [tests/test_notes_document_mutual_minimize.py](../../tests/test_notes_document_mutual_minimize.py) |
|
||||
| M | [tests/test_notes_dom_xss_helpers.py](../../tests/test_notes_dom_xss_helpers.py) |
|
||||
| M | [tests/test_notes_mobile_checklist_toggle_static.py](../../tests/test_notes_mobile_checklist_toggle_static.py) |
|
||||
| A | [tests/test_notes_reference_browser.py](../../tests/test_notes_reference_browser.py) |
|
||||
| A | [tests/test_notes_reference_contracts_js.py](../../tests/test_notes_reference_contracts_js.py) |
|
||||
| M | [tests/test_notes_search_reset_on_reopen_js.py](../../tests/test_notes_search_reset_on_reopen_js.py) |
|
||||
| M | [tests/test_notes_select_esc_listener_js.py](../../tests/test_notes_select_esc_listener_js.py) |
|
||||
| M | [tests/test_notes_sidebar_new_note.py](../../tests/test_notes_sidebar_new_note.py) |
|
||||
|
||||
## Runtime validation (2)
|
||||
|
||||
| Status | File |
|
||||
| --- | --- |
|
||||
| M | [scripts/verify_frontend_runtime.py](../../scripts/verify_frontend_runtime.py) |
|
||||
| A | [scripts/verify_notes_browser_runtime.py](../../scripts/verify_notes_browser_runtime.py) |
|
||||
|
||||
## Documentation and execution receipts (9)
|
||||
|
||||
| Status | File |
|
||||
| --- | --- |
|
||||
| A | [docs/frontend-architecture/evidence/notes/implementation.sha256](../../docs/frontend-architecture/evidence/notes/implementation.sha256) |
|
||||
| A | [docs/frontend-architecture/evidence/notes/native-desktop.png](../../docs/frontend-architecture/evidence/notes/native-desktop.png) |
|
||||
| A | [docs/frontend-architecture/evidence/notes/native-mobile.png](../../docs/frontend-architecture/evidence/notes/native-mobile.png) |
|
||||
| M | [docs/frontend-architecture/handbook.md](../../docs/frontend-architecture/handbook.md) |
|
||||
| A | [docs/frontend-architecture/notes-case-study.md](../../docs/frontend-architecture/notes-case-study.md) |
|
||||
| A | [docs/frontend-architecture/notes-changed-files.md](../../docs/frontend-architecture/notes-changed-files.md) |
|
||||
| A | [docs/frontend-architecture/notes-module-inventory.md](../../docs/frontend-architecture/notes-module-inventory.md) |
|
||||
| M | [docs/frontend-architecture/notes-roadmap.md](../../docs/frontend-architecture/notes-roadmap.md) |
|
||||
| A | [docs/frontend-architecture/notes-validation.md](../../docs/frontend-architecture/notes-validation.md) |
|
||||
|
||||
See [the case study](notes-case-study.md) for ownership and handoff,
|
||||
[the module inventory](notes-module-inventory.md) for line counts, and
|
||||
[the validation report](notes-validation.md) for exact executed checks.
|
||||
@@ -0,0 +1,56 @@
|
||||
# Notes source and deployment inventory
|
||||
|
||||
The feature has 41 maintained modules. The unchanged F1 action-menu proof and
|
||||
shared confetti bring the full manifest to 43. Outputs are copied byte-for-byte;
|
||||
count maintained source once. The legacy entry is a five-line compatibility facade.
|
||||
|
||||
| Source under frontend/src | Deployment under static | Lines | Layer |
|
||||
| --- | --- | ---: | --- |
|
||||
| [features/notes/application/agentActions.js](../../frontend/src/features/notes/application/agentActions.js) | [js/features/notes/application/agentActions.js](../../static/js/features/notes/application/agentActions.js) | 67 | application |
|
||||
| [features/notes/application/cardOperations.js](../../frontend/src/features/notes/application/cardOperations.js) | [js/features/notes/application/cardOperations.js](../../static/js/features/notes/application/cardOperations.js) | 79 | application |
|
||||
| [features/notes/application/checklistOperations.js](../../frontend/src/features/notes/application/checklistOperations.js) | [js/features/notes/application/checklistOperations.js](../../static/js/features/notes/application/checklistOperations.js) | 68 | application |
|
||||
| [features/notes/application/deletion.js](../../frontend/src/features/notes/application/deletion.js) | [js/features/notes/application/deletion.js](../../static/js/features/notes/application/deletion.js) | 51 | application |
|
||||
| [features/notes/application/drafts.js](../../frontend/src/features/notes/application/drafts.js) | [js/features/notes/application/drafts.js](../../static/js/features/notes/application/drafts.js) | 55 | application |
|
||||
| [features/notes/application/queries.js](../../frontend/src/features/notes/application/queries.js) | [js/features/notes/application/queries.js](../../static/js/features/notes/application/queries.js) | 66 | application |
|
||||
| [features/notes/application/reminders.js](../../frontend/src/features/notes/application/reminders.js) | [js/features/notes/application/reminders.js](../../static/js/features/notes/application/reminders.js) | 182 | application |
|
||||
| [features/notes/application/selection.js](../../frontend/src/features/notes/application/selection.js) | [js/features/notes/application/selection.js](../../static/js/features/notes/application/selection.js) | 39 | application |
|
||||
| [features/notes/application/state.js](../../frontend/src/features/notes/application/state.js) | [js/features/notes/application/state.js](../../static/js/features/notes/application/state.js) | 72 | application |
|
||||
| [features/notes/application/submission.js](../../frontend/src/features/notes/application/submission.js) | [js/features/notes/application/submission.js](../../static/js/features/notes/application/submission.js) | 69 | application |
|
||||
| [features/notes/application/workflows.js](../../frontend/src/features/notes/application/workflows.js) | [js/features/notes/application/workflows.js](../../static/js/features/notes/application/workflows.js) | 78 | application |
|
||||
| [features/notes/domain/noteRules.js](../../frontend/src/features/notes/domain/noteRules.js) | [js/features/notes/domain/noteRules.js](../../static/js/features/notes/domain/noteRules.js) | 87 | domain |
|
||||
| [features/notes/domain/recurrence.js](../../frontend/src/features/notes/domain/recurrence.js) | [js/features/notes/domain/recurrence.js](../../static/js/features/notes/domain/recurrence.js) | 269 | domain |
|
||||
| [features/notes/index.js](../../frontend/src/features/notes/index.js) | [js/features/notes/index.js](../../static/js/features/notes/index.js) | 518 | composition |
|
||||
| [features/notes/infrastructure/http.js](../../frontend/src/features/notes/infrastructure/http.js) | [js/features/notes/infrastructure/http.js](../../static/js/features/notes/infrastructure/http.js) | 29 | infrastructure |
|
||||
| [features/notes/infrastructure/notifications.js](../../frontend/src/features/notes/infrastructure/notifications.js) | [js/features/notes/infrastructure/notifications.js](../../static/js/features/notes/infrastructure/notifications.js) | 20 | infrastructure |
|
||||
| [features/notes/infrastructure/storage.js](../../frontend/src/features/notes/infrastructure/storage.js) | [js/features/notes/infrastructure/storage.js](../../static/js/features/notes/infrastructure/storage.js) | 63 | infrastructure |
|
||||
| [features/notes/ui/cardChecklist.js](../../frontend/src/features/notes/ui/cardChecklist.js) | [js/features/notes/ui/cardChecklist.js](../../static/js/features/notes/ui/cardChecklist.js) | 148 | ui |
|
||||
| [features/notes/ui/cardInteractions.js](../../frontend/src/features/notes/ui/cardInteractions.js) | [js/features/notes/ui/cardInteractions.js](../../static/js/features/notes/ui/cardInteractions.js) | 337 | ui |
|
||||
| [features/notes/ui/cardRendering.js](../../frontend/src/features/notes/ui/cardRendering.js) | [js/features/notes/ui/cardRendering.js](../../static/js/features/notes/ui/cardRendering.js) | 244 | ui |
|
||||
| [features/notes/ui/cardReorder.js](../../frontend/src/features/notes/ui/cardReorder.js) | [js/features/notes/ui/cardReorder.js](../../static/js/features/notes/ui/cardReorder.js) | 181 | ui |
|
||||
| [features/notes/ui/checklist.js](../../frontend/src/features/notes/ui/checklist.js) | [js/features/notes/ui/checklist.js](../../static/js/features/notes/ui/checklist.js) | 190 | ui |
|
||||
| [features/notes/ui/checklistReorder.js](../../frontend/src/features/notes/ui/checklistReorder.js) | [js/features/notes/ui/checklistReorder.js](../../static/js/features/notes/ui/checklistReorder.js) | 111 | ui |
|
||||
| [features/notes/ui/clipboard.js](../../frontend/src/features/notes/ui/clipboard.js) | [js/features/notes/ui/clipboard.js](../../static/js/features/notes/ui/clipboard.js) | 82 | ui |
|
||||
| [features/notes/ui/colors.js](../../frontend/src/features/notes/ui/colors.js) | [js/features/notes/ui/colors.js](../../static/js/features/notes/ui/colors.js) | 111 | ui |
|
||||
| [features/notes/ui/draftEditor.js](../../frontend/src/features/notes/ui/draftEditor.js) | [js/features/notes/ui/draftEditor.js](../../static/js/features/notes/ui/draftEditor.js) | 67 | ui |
|
||||
| [features/notes/ui/drawing.js](../../frontend/src/features/notes/ui/drawing.js) | [js/features/notes/ui/drawing.js](../../static/js/features/notes/ui/drawing.js) | 442 | ui |
|
||||
| [features/notes/ui/editor.js](../../frontend/src/features/notes/ui/editor.js) | [js/features/notes/ui/editor.js](../../static/js/features/notes/ui/editor.js) | 518 | ui |
|
||||
| [features/notes/ui/filters.js](../../frontend/src/features/notes/ui/filters.js) | [js/features/notes/ui/filters.js](../../static/js/features/notes/ui/filters.js) | 139 | ui |
|
||||
| [features/notes/ui/layout.js](../../frontend/src/features/notes/ui/layout.js) | [js/features/notes/ui/layout.js](../../static/js/features/notes/ui/layout.js) | 120 | ui |
|
||||
| [features/notes/ui/lifecycle.js](../../frontend/src/features/notes/ui/lifecycle.js) | [js/features/notes/ui/lifecycle.js](../../static/js/features/notes/ui/lifecycle.js) | 36 | ui |
|
||||
| [features/notes/ui/mobileEditor.js](../../frontend/src/features/notes/ui/mobileEditor.js) | [js/features/notes/ui/mobileEditor.js](../../static/js/features/notes/ui/mobileEditor.js) | 257 | ui |
|
||||
| [features/notes/ui/mobileReorder.js](../../frontend/src/features/notes/ui/mobileReorder.js) | [js/features/notes/ui/mobileReorder.js](../../static/js/features/notes/ui/mobileReorder.js) | 214 | ui |
|
||||
| [features/notes/ui/panel.js](../../frontend/src/features/notes/ui/panel.js) | [js/features/notes/ui/panel.js](../../static/js/features/notes/ui/panel.js) | 506 | ui |
|
||||
| [features/notes/ui/quickAdd.js](../../frontend/src/features/notes/ui/quickAdd.js) | [js/features/notes/ui/quickAdd.js](../../static/js/features/notes/ui/quickAdd.js) | 170 | ui |
|
||||
| [features/notes/ui/reminderDisplay.js](../../frontend/src/features/notes/ui/reminderDisplay.js) | [js/features/notes/ui/reminderDisplay.js](../../static/js/features/notes/ui/reminderDisplay.js) | 129 | ui |
|
||||
| [features/notes/ui/reminderPicker.js](../../frontend/src/features/notes/ui/reminderPicker.js) | [js/features/notes/ui/reminderPicker.js](../../static/js/features/notes/ui/reminderPicker.js) | 334 | ui |
|
||||
| [features/notes/ui/selection.js](../../frontend/src/features/notes/ui/selection.js) | [js/features/notes/ui/selection.js](../../static/js/features/notes/ui/selection.js) | 61 | ui |
|
||||
| [features/notes/ui/text.js](../../frontend/src/features/notes/ui/text.js) | [js/features/notes/ui/text.js](../../static/js/features/notes/ui/text.js) | 39 | ui |
|
||||
| [features/notes/ui/toolbar.js](../../frontend/src/features/notes/ui/toolbar.js) | [js/features/notes/ui/toolbar.js](../../static/js/features/notes/ui/toolbar.js) | 78 | ui |
|
||||
| [features/notes/ui/windowLayout.js](../../frontend/src/features/notes/ui/windowLayout.js) | [js/features/notes/ui/windowLayout.js](../../static/js/features/notes/ui/windowLayout.js) | 114 | ui |
|
||||
| [shared/ui/confetti.js](../../frontend/src/shared/ui/confetti.js) | [js/shared/ui/confetti.js](../../static/js/shared/ui/confetti.js) | 28 | shared UI |
|
||||
|
||||
Maintained Notes feature total: 6440 lines. Original entry: 5,471 lines.
|
||||
Legacy facade after decomposition: five lines. Shared confetti: 28 lines.
|
||||
|
||||
See [the case study](notes-case-study.md) for responsibilities and public/state/lifecycle
|
||||
contracts, and [the validation report](notes-validation.md) for executed evidence.
|
||||
@@ -1,15 +1,20 @@
|
||||
# Notes reference decomposition roadmap
|
||||
|
||||
Status: planning only. F1 changes no Notes implementation. Begin after the
|
||||
foundation has been reviewed and integrated into official `upstream/dev`.
|
||||
The reference program ends after Notes integration and the completed H handoff.
|
||||
Status: N0 through N6 implemented as an unpublished Notes review diff after F1
|
||||
merged in PR #6701. Actual decisions, interfaces, module ownership, checkpoint
|
||||
receipts and execution limits are in the [case study](notes-case-study.md) and
|
||||
[validation report](notes-validation.md). The proposal below retains the original
|
||||
responsibility map for comparison. Notes integration and the recipient's independent
|
||||
H reproduction remain pending.
|
||||
F1 remains an entirely separate foundation-only PR. The complete Notes
|
||||
decomposition, regression tests, compatibility validation and final reference
|
||||
case study belong to one comprehensive draft PR targeting official `dev`.
|
||||
|
||||
## Verified current responsibility and compatibility map
|
||||
|
||||
Baseline: `8feb50e89468235cd3e0986da80edbd3acaf2c40`.
|
||||
Historical assessment baseline: `8feb50e89468235cd3e0986da80edbd3acaf2c40`.
|
||||
The implementation starts from merged F1 at
|
||||
`1cc56cb9d78f3e2399d1d61155b71d771a17b85b`.
|
||||
The module is `static/js/notes.js`, about 5,470 lines, with browser identity
|
||||
`/static/js/notes.js?v=20260911notesselectioncancel1`. Preserve that identity across
|
||||
the app import, HTML, SW and lazy consumers until a separately reviewed migration
|
||||
|
||||
@@ -0,0 +1,261 @@
|
||||
# Notes implementation validation and checkpoint receipts
|
||||
|
||||
Implementation baseline: `1cc56cb9d78f3e2399d1d61155b71d771a17b85b`, updated via
|
||||
non-destructive fast-forward to latest official `upstream/dev` at
|
||||
`86b886c611338282af6d4a717246ea4e256f58df` (incorporating PRs #6704 and #6693).
|
||||
Independent AGY audit returned CONDITIONAL PASS. Pre-publication corrective
|
||||
pass verified issue template, PR template, visual evidence paths, and em-dash removal.
|
||||
The official integration branch is `dev`. Tracking issue #6712; PR #6713.
|
||||
|
||||
## Final executed evidence
|
||||
|
||||
| Check | Result |
|
||||
| --- | --- |
|
||||
| Notes Python tests, discovered by filename, plus F1 publication/graph/offline/loader tests | 172 passed, one release-smoke skip without `APP_PORT` |
|
||||
| Node architecture, Notes oracle, domain, infrastructure, application, reminders, drafts, selection and workflow tests | 46 passed |
|
||||
| Native Python lifespan/static distribution probe | Passed for every mapped output, with source/Node absent |
|
||||
| Existing Docker image distribution probe | Passed with networking disabled and candidate files mounted read-only |
|
||||
| Real authenticated native app, desktop and touch-mobile | Passed CRUD persistence, owner identity, actual Chat selected-context indicator/reset and the original release smoke scenario |
|
||||
| Real Chromium first evaluation of Notes offline | Passed; every maintained output cached, facade/canonical API identity shared |
|
||||
| Source/output parity and F1 boundaries | Passed, 43 maintained modules and nine composition-only legacy exceptions |
|
||||
| Foundation-based full pytest execution | 13 failed, 13,909 passed, 60 skipped, six subtests passed, 192 warnings, 517.04 seconds |
|
||||
| Targeted unchanged F1 baseline reproduction | Same 13 failures, 77 passed, six warnings |
|
||||
| Targeted untouched latest `dev` reproduction | Three inherited failures, 87 passed, six warnings |
|
||||
| Final indexed latest `dev` plus Notes overlay, full pytest | Three same-environment baseline failures, 13,923 passed, 60 skipped, six subtests passed, 192 warnings, 512.09 seconds |
|
||||
| Untouched latest `dev` readiness checks, without the prewarm override | Five passed |
|
||||
|
||||
The foundation-based full repository result is not green. Its failures reproduce against
|
||||
the unchanged foundation in a disposable archive, with the same interpreter and
|
||||
closed Chroma port. None was disabled, relabeled or fixed in this Notes change.
|
||||
The focused Notes suite and required source/deployment gates are green. The final
|
||||
code/test overlay is fingerprinted in [implementation.sha256](evidence/notes/implementation.sha256).
|
||||
The only post-full-suite test-source edit removes a terminal
|
||||
blank line from the browser wrapper; its content was compared ignoring terminal
|
||||
whitespace and all three focused contract/browser checks passed again. Raw command
|
||||
outputs are kept out of the repository; the counts above are the record.
|
||||
|
||||
The first full run reported 19 failures. Six were introduced validation issues:
|
||||
the SW cache name did not follow the existing numeric convention; a temporary
|
||||
probe environment input was not registered by the configuration-reference checker;
|
||||
and a Notes source assertion still expected the original default object spelling.
|
||||
The cache name now follows the convention, the probe passes its output list as a
|
||||
command argument, and the assertion verifies the new public binding. All 58 tests
|
||||
in those affected files passed after correction. The foundation-based full run has only the
|
||||
13 reproduced baseline failures below.
|
||||
|
||||
### Reproduced baseline failures
|
||||
|
||||
- `tests/test_aux_llm_owner_scope.py::test_auto_compaction_utility_endpoint_keeps_chat_owner`
|
||||
- `tests/test_chatgpt_reasoning_and_grouping.py::test_history_and_chat_routes_support_reasoning_effort`
|
||||
- `tests/test_containment_enforcement.py::test_namespace_handshake_closes_model_stdin`
|
||||
- `tests/test_containment_enforcement.py::test_execution_environment_cannot_replace_probed_bwrap[False]`
|
||||
- `tests/test_context_compactor.py::TestMaybeCompactFourthMessage::test_does_not_crash_on_none_content_turn`
|
||||
- `tests/test_context_compactor.py::TestMaybeCompactFourthMessage::test_handles_multimodal_list_content`
|
||||
- `tests/test_css_computed_style_snapshot.py::test_computed_styles_match_the_committed_baseline`
|
||||
- `tests/test_history_compact_tool_calls.py::test_manual_compact_tolerates_chatmessage_with_none_content`
|
||||
- `tests/test_history_compact_tool_calls.py::test_manual_compact_tolerates_dict_message_with_none_content`
|
||||
- `tests/test_history_compact_tool_calls.py::test_registered_manual_compact_route_tolerates_none_content`
|
||||
- `tests/test_history_compact_tool_calls.py::test_registered_manual_compact_route_uses_session_owner`
|
||||
- `tests/test_model_helper_owner_scope.py::test_history_compact_resolves_with_owner_scope`
|
||||
- `tests/test_readiness.py::test_tool_index_is_reported_but_not_critical_by_default`
|
||||
|
||||
These cover existing compaction fixtures/source assertions, namespace containment,
|
||||
settings-row CSS baseline drift and readiness expectations. The baseline reproduction used
|
||||
`git archive` into `/tmp/odysseus-notes-baseline-OitxsU`, not another branch/worktree.
|
||||
|
||||
## Reproducible commands
|
||||
|
||||
### Latest integration target
|
||||
|
||||
Final upstream inspection found `86b886c611338282af6d4a717246ea4e256f58df`.
|
||||
PR #6704 repairs ten of the foundation's reproduced failures; PR #6693 adds
|
||||
remote-only skill gating. Neither changes a file owned by the Notes diff.
|
||||
The branch remains on the requested foundation, with no merge or rebase.
|
||||
An archive of that latest target plus the exact final Notes code/test overlay is
|
||||
validated in `/tmp/odysseus-notes-latest-VmZrgC` using the same full-suite command.
|
||||
The fixture has a local Git index, initialized from the latest target and updated
|
||||
with the review files, but no commit. This enables the tracked-publication checks.
|
||||
The first archive-only attempt had one Git-metadata failure and seven checkout-only
|
||||
skips. Both affected files subsequently passed all 19 tests with metadata present;
|
||||
the complete suite was then rerun in that indexed fixture.
|
||||
An untouched archive at `/tmp/odysseus-notes-latest-baseline-mfE4ss` reproduced
|
||||
the remaining two containment failures and the readiness failure: three failed,
|
||||
87 passed.
|
||||
|
||||
These are reproduced local-environment failures, not a claim that official CI is
|
||||
currently failing. The readiness assertion expects prewarming enabled, whereas
|
||||
the full-run safety command explicitly sets `ODYSSEUS_TOOL_INDEX_PREWARM=0`.
|
||||
With that override absent, all five readiness tests pass on untouched latest `dev`.
|
||||
The two namespace tests receive extra `Failed to create stream fd` stderr in this
|
||||
host's contained process output. That same output occurs without the Notes overlay;
|
||||
no backend containment code was changed or a failing assertion weakened.
|
||||
Reproduce those two checks on the supported CI runner before claiming a green
|
||||
full-suite certification.
|
||||
|
||||
In the final indexed full-suite run the only failures are `test_namespace_handshake_closes_model_stdin`,
|
||||
`test_execution_environment_cannot_replace_probed_bwrap[False]`, and
|
||||
`test_tool_index_is_reported_but_not_critical_by_default`. The missing-Git-metadata
|
||||
publication failure and the seven checkout-only skips are absent from this run.
|
||||
No Notes regression was reported. Feature code matched N6 at publication. Later
|
||||
commits on the PR changed `ui/reminderPicker.js` (date input value assigned through
|
||||
the DOM property) and, after review, `index.js`, `ui/layout.js` and
|
||||
`application/state.js`; `implementation.sha256` covers the current files.
|
||||
|
||||
To reproduce the integration rehearsal, extract the latest target with `git archive`
|
||||
into a fresh fixture and copy only files in the changed-file inventory on top.
|
||||
Do not overlay foundation files that are unchanged in this PR. Install the locked
|
||||
development dependencies in the fixture, then run the commands below there.
|
||||
|
||||
While this review diff is uncommitted, this prepares an equivalent Linux fixture
|
||||
without changing either task worktree:
|
||||
|
||||
```sh
|
||||
notes_fixture=$(mktemp -d /tmp/ody-notes-integration-XXXXXX)
|
||||
git archive 86b886c611338282af6d4a717246ea4e256f58df | tar -x -C "$notes_fixture"
|
||||
{ git diff --name-only -z; git ls-files --others --exclude-standard -z; } |
|
||||
tar --null -T - -cf - | tar -xf - -C "$notes_fixture"
|
||||
git -C "$notes_fixture" init -q
|
||||
git -C "$notes_fixture" fetch --no-write-fetch-head "$PWD" 86b886c611338282af6d4a717246ea4e256f58df
|
||||
git -C "$notes_fixture" read-tree 86b886c611338282af6d4a717246ea4e256f58df
|
||||
(cd "$notes_fixture" && npm ci --ignore-scripts --no-audit --no-fund && git add --all)
|
||||
# Run the validation commands below from notes_fixture, using an isolated Python environment.
|
||||
```
|
||||
|
||||
Use a real dependency directory for this recipe; a symlink named `node_modules`
|
||||
can bypass the repository's directory-only ignore pattern. No checkpoint or
|
||||
fixture commit is needed. After integration, validate the actual integrated checkout
|
||||
directly, rather than relying on the uncommitted-diff recipe.
|
||||
|
||||
### Commands
|
||||
|
||||
Use the actual tested interpreter, or install the repository requirements in your
|
||||
own isolated virtualenv. Node development dependencies were installed with the
|
||||
existing lockfile and `npm ci --ignore-scripts --no-audit --no-fund`.
|
||||
|
||||
```sh
|
||||
python3 scripts/build_frontend.py
|
||||
python3 scripts/build_frontend.py --check
|
||||
node scripts/check_frontend.mjs
|
||||
node scripts/check_frontend.mjs --inventory
|
||||
|
||||
ENDPOINT_URL=http://127.0.0.1:1 node --test \
|
||||
tests/frontendArchitecture.test.mjs tests/noteTestOracle.test.mjs \
|
||||
tests/notesDraftAutosave.test.mjs tests/selectedNotesContext.test.mjs \
|
||||
tests/notesCharacterization.test.mjs tests/notesRecurrence.test.mjs \
|
||||
tests/notesInfrastructure.test.mjs tests/notesApplication.test.mjs \
|
||||
tests/notesReminders.test.mjs tests/notesWorkflows.test.mjs
|
||||
|
||||
CHROMADB_HOST=127.0.0.1 CHROMADB_PORT=1 \
|
||||
python -m pytest -q -rs \
|
||||
$(rg --files tests -g 'test_*note*.py') \
|
||||
tests/test_frontend_build.py tests/test_frontend_foundation_offline_js.py \
|
||||
tests/test_frontend_module_graph.py tests/test_frontend_module_version_parity.py \
|
||||
tests/test_panel_loader_js.py
|
||||
|
||||
python scripts/verify_frontend_runtime.py
|
||||
python scripts/verify_notes_browser_runtime.py
|
||||
|
||||
docker run --rm --network none \
|
||||
--mount type=bind,src="$PWD",dst=/candidate,readonly \
|
||||
--workdir /candidate --entrypoint python \
|
||||
<existing-odysseus-image> scripts/verify_frontend_runtime.py
|
||||
|
||||
CHROMADB_HOST=127.0.0.1 CHROMADB_PORT=1 \
|
||||
ODYSSEUS_STARTUP_WARMUPS=0 ODYSSEUS_TOOL_INDEX_PREWARM=0 \
|
||||
python -m pytest -q -rfs
|
||||
|
||||
git diff --check
|
||||
```
|
||||
|
||||
`ENDPOINT_URL` satisfies the existing oracle's import configuration; its endpoint-
|
||||
driving main does not run in these unit tests. Port 1 is the closed loopback target
|
||||
used for pytest; the two runtime scripts reserve their own non-listening Chroma port.
|
||||
The native browser script creates a private distribution/database and a temporary
|
||||
authenticated user, then terminates the server and removes that fixture. It uses
|
||||
the real application and Notes API rather than mocked browser routes.
|
||||
|
||||
The deterministic browser harness uses stub API responses and the real Notes ESM,
|
||||
DOM and stylesheet graph. It verifies namespace/default methods and arities,
|
||||
aliases, remount/search reset, rejected/accepted attachments, draft persistence,
|
||||
drawing/undo and listener/portal cleanup. It also checks larger-touch reorder after
|
||||
re-render, active-drag close cleanup and cancellation of a mobile selection hold.
|
||||
It includes the mobile viewport meta tag,
|
||||
tap-to-read/edit behavior and the existing selection jiggle. The original monolith
|
||||
can be replayed with `NOTES_BASELINE=1`; it is read from the frozen F1 revision.
|
||||
|
||||
## Browser and packaging evidence
|
||||
|
||||
Actual app screenshots: [desktop](evidence/notes/native-desktop.png) and
|
||||
[mobile](evidence/notes/native-mobile.png). These are Chromium screenshots of the
|
||||
disposable authenticated app at 1440 x 1000 and 390 x 844, not rendered mockups.
|
||||
The deterministic before/after fixture had an identical mobile PNG and only 14
|
||||
changed desktop pixels in the header region; no layout/style change was observed.
|
||||
CSS, app bootstrap and HTML have no implementation diff.
|
||||
|
||||
The native and Docker distribution probe serves all manifest outputs without
|
||||
`frontend/`, `node_modules/` or Node on the server path. It checks response bytes,
|
||||
JS MIME, revalidation, CSP, shell startup, static confinement and source-tree 404.
|
||||
Docker used existing image
|
||||
`sha256:cc2d47e2327d573af01c6b027f23d2ab0f2ee9b85d658e9eb8065bd02b9c3515`.
|
||||
This is not a fresh Dockerfile build or deployment.
|
||||
|
||||
Tested locally: Linux, Python 3.14.4, Node 22.23.1 and Playwright/Chromium 1.62.1.
|
||||
CI's exact Python 3.11/Node 20 pair, Firefox/WebKit, macOS/Windows executable builds,
|
||||
live model/email notification delivery and full root offline reload were not run.
|
||||
The Docker runtime uses its own existing dependency versions. Shared active-window
|
||||
gesture interleavings are not exhaustively covered. No broader platform certification
|
||||
is claimed.
|
||||
|
||||
The full-run safety overrides differ from official CI's plain pytest command.
|
||||
For the readiness default-contract check, use
|
||||
`env -u ODYSSEUS_TOOL_INDEX_PREWARM python -m pytest -q tests/test_readiness.py`.
|
||||
Keep explicit warmup/storage isolation on the disposable live-app probes.
|
||||
|
||||
## Internal checkpoints
|
||||
|
||||
Checkpoint snapshots are kept with the maintainer handoff, not in the repository.
|
||||
The hashes below identify them. They contain scoped source/output/facade/manifest/test
|
||||
overlays, not secrets or user data. Each starts from the same frozen baseline; they
|
||||
are not separate PRs or release candidates.
|
||||
|
||||
| Stage | Boundary and executed exit evidence | Snapshot SHA-256 |
|
||||
| --- | --- | --- |
|
||||
| N0 | Public/consumer/state/lifecycle map; 95 baseline Python and 11 Node passes; four new characterization tests; desktop/touch harness; 33 F1 publication/graph checks | `db0a2e6e68fec3442ce350ffb0acf47bcdf2a5266f7c64c2bf910a1c41c4fb62` |
|
||||
| N1 | Pure recurrence/date rules; eight Node and nine focused Python passes; differential oracle in four time zones; parity/boundaries | `fd0638470744706fbbd5787cb47bd2078a93c9b854139f89f8fdc169c1f353c6` |
|
||||
| N2 | HTTP/storage adapters; fourteen Node and seven focused Python passes; exact requests, keys and fallback contracts | `30826fb7972d1b9e3a790f97ee81f66dcb3dc58eb7d23e24d4f46e6d841b7c73` |
|
||||
| N3 | Single state owner and CRUD/undo boundary; ten Node and seven focused Python passes; read-only state and archive rollback | `4bc5293519b8438d0126a61887bea64195dcdb7d59bcfaaba8ed4ae8c38be439` |
|
||||
| N4 | Page-owned reminder workflow; four reminder contract tests and seven focused Python passes; singleton interval, catch-up, markers and fallback | `febb835c4958c8758e4b7c23ce89f3ec8d103c2cc28f89817d258b3791a9fcdf` |
|
||||
| N5 | Complete UI/application integration; 44 Node passes, targeted source guards and actual browser checks; drawing binding correction, read-only state and disposal | `e147f645bdb2161a4b1dc6cf10c36ba6d0c214d8e12fccb478835043eaaf3e94` |
|
||||
| N6 | Final facade, identity, exact offline graph, native/Docker checks, final editor-deletion/reorder ownership review, touch cleanup regression checks and maintainer review package | `c450e91f9fbfe5f0cd805e596b92a76383f22a74e9515ca3e3f6154aebf5f61f` |
|
||||
|
||||
The N6 overlay contained the final code, tests, manifest and attributes at
|
||||
publication, not the evidence directory itself. From the repository root, run
|
||||
`sha256sum -c docs/frontend-architecture/evidence/notes/implementation.sha256`
|
||||
to verify the current implementation files.
|
||||
|
||||
No checkpoint commits were made. To reproduce an overlay, create a fresh temporary
|
||||
directory, extract `git archive 1cc56cb9...` there, then extract the desired
|
||||
snapshot from the handoff on top. Install the locked test dependencies
|
||||
in that fixture and run its relevant commands. Begin from the baseline rather than
|
||||
overlaying snapshots onto a later dirty tree. For live rollback, release a complete
|
||||
matching artifact through the authorized release workflow.
|
||||
|
||||
Temporary mechanical extraction scripts are not part of the supported deliverable.
|
||||
They were archived locally, then removed. The first generated patch accidentally targeted
|
||||
the separate foundation worktree; only those edits were reversed, absolute paths
|
||||
were adopted, and that worktree's clean state was verified afterward.
|
||||
|
||||
## Open PR overlaps and handoff limits
|
||||
|
||||
The following remained open at the read-only GitHub refresh:
|
||||
|
||||
- [#6585](https://github.com/odysseus-dev/odysseus/pull/6585): optional Notes field removal in the backend. Existing null-field behavior is retained here.
|
||||
- [#6647](https://github.com/odysseus-dev/odysseus/pull/6647): read-only Notes intent routing.
|
||||
- [#6652](https://github.com/odysseus-dev/odysseus/pull/6652): `manage_notes` registry dispatch.
|
||||
- [#6470](https://github.com/odysseus-dev/odysseus/pull/6470): shared theme, typography, sidebar and modal changes.
|
||||
- [#6695](https://github.com/odysseus-dev/odysseus/pull/6695): extension system/platform integration.
|
||||
|
||||
Their changes were not merged or reimplemented. Shared UI exceptions, root-SW scope,
|
||||
the original last-completion fetch race, temporary-note correlation and canvas-draft
|
||||
limits are documented in the case study. Backend owner checks and PR #6495 contracts
|
||||
remain authoritative.
|
||||
@@ -4,6 +4,212 @@
|
||||
{
|
||||
"source": "shared/actionMenuOrder.js",
|
||||
"deployment": "js/actionMenuOrder.js"
|
||||
},
|
||||
{
|
||||
"source": "features/notes/domain/recurrence.js",
|
||||
"deployment": "js/features/notes/domain/recurrence.js"
|
||||
},
|
||||
{
|
||||
"source": "features/notes/infrastructure/http.js",
|
||||
"deployment": "js/features/notes/infrastructure/http.js"
|
||||
},
|
||||
{
|
||||
"source": "features/notes/infrastructure/storage.js",
|
||||
"deployment": "js/features/notes/infrastructure/storage.js"
|
||||
},
|
||||
{
|
||||
"source": "features/notes/application/state.js",
|
||||
"deployment": "js/features/notes/application/state.js"
|
||||
},
|
||||
{
|
||||
"source": "features/notes/application/workflows.js",
|
||||
"deployment": "js/features/notes/application/workflows.js"
|
||||
},
|
||||
{
|
||||
"source": "features/notes/application/reminders.js",
|
||||
"deployment": "js/features/notes/application/reminders.js"
|
||||
},
|
||||
{
|
||||
"source": "features/notes/infrastructure/notifications.js",
|
||||
"deployment": "js/features/notes/infrastructure/notifications.js"
|
||||
},
|
||||
{
|
||||
"source": "features/notes/ui/text.js",
|
||||
"deployment": "js/features/notes/ui/text.js"
|
||||
},
|
||||
{
|
||||
"source": "features/notes/ui/colors.js",
|
||||
"deployment": "js/features/notes/ui/colors.js"
|
||||
},
|
||||
{
|
||||
"source": "features/notes/ui/panel.js",
|
||||
"deployment": "js/features/notes/ui/panel.js"
|
||||
},
|
||||
{
|
||||
"source": "features/notes/ui/reminderDisplay.js",
|
||||
"deployment": "js/features/notes/ui/reminderDisplay.js"
|
||||
},
|
||||
{
|
||||
"source": "features/notes/ui/selection.js",
|
||||
"deployment": "js/features/notes/ui/selection.js"
|
||||
},
|
||||
{
|
||||
"source": "features/notes/ui/filters.js",
|
||||
"deployment": "js/features/notes/ui/filters.js"
|
||||
},
|
||||
{
|
||||
"source": "features/notes/ui/cardRendering.js",
|
||||
"deployment": "js/features/notes/ui/cardRendering.js"
|
||||
},
|
||||
{
|
||||
"source": "features/notes/ui/layout.js",
|
||||
"deployment": "js/features/notes/ui/layout.js"
|
||||
},
|
||||
{
|
||||
"source": "features/notes/ui/quickAdd.js",
|
||||
"deployment": "js/features/notes/ui/quickAdd.js"
|
||||
},
|
||||
{
|
||||
"source": "features/notes/ui/cardInteractions.js",
|
||||
"deployment": "js/features/notes/ui/cardInteractions.js"
|
||||
},
|
||||
{
|
||||
"source": "features/notes/ui/cardChecklist.js",
|
||||
"deployment": "js/features/notes/ui/cardChecklist.js"
|
||||
},
|
||||
{
|
||||
"source": "features/notes/ui/cardReorder.js",
|
||||
"deployment": "js/features/notes/ui/cardReorder.js"
|
||||
},
|
||||
{
|
||||
"source": "features/notes/ui/draftEditor.js",
|
||||
"deployment": "js/features/notes/ui/draftEditor.js"
|
||||
},
|
||||
{
|
||||
"source": "features/notes/ui/editor.js",
|
||||
"deployment": "js/features/notes/ui/editor.js"
|
||||
},
|
||||
{
|
||||
"source": "features/notes/ui/reminderPicker.js",
|
||||
"deployment": "js/features/notes/ui/reminderPicker.js"
|
||||
},
|
||||
{
|
||||
"source": "features/notes/ui/checklist.js",
|
||||
"deployment": "js/features/notes/ui/checklist.js"
|
||||
},
|
||||
{
|
||||
"source": "features/notes/ui/drawing.js",
|
||||
"deployment": "js/features/notes/ui/drawing.js"
|
||||
},
|
||||
{
|
||||
"source": "features/notes/ui/clipboard.js",
|
||||
"deployment": "js/features/notes/ui/clipboard.js"
|
||||
},
|
||||
{
|
||||
"source": "features/notes/ui/mobileEditor.js",
|
||||
"deployment": "js/features/notes/ui/mobileEditor.js"
|
||||
},
|
||||
{
|
||||
"source": "features/notes/ui/mobileReorder.js",
|
||||
"deployment": "js/features/notes/ui/mobileReorder.js"
|
||||
},
|
||||
{
|
||||
"source": "features/notes/ui/checklistReorder.js",
|
||||
"deployment": "js/features/notes/ui/checklistReorder.js"
|
||||
},
|
||||
{
|
||||
"source": "features/notes/application/queries.js",
|
||||
"deployment": "js/features/notes/application/queries.js"
|
||||
},
|
||||
{
|
||||
"source": "features/notes/application/agentActions.js",
|
||||
"deployment": "js/features/notes/application/agentActions.js"
|
||||
},
|
||||
{
|
||||
"source": "features/notes/application/deletion.js",
|
||||
"deployment": "js/features/notes/application/deletion.js"
|
||||
},
|
||||
{
|
||||
"source": "features/notes/domain/noteRules.js",
|
||||
"deployment": "js/features/notes/domain/noteRules.js"
|
||||
},
|
||||
{
|
||||
"source": "features/notes/index.js",
|
||||
"deployment": "js/features/notes/index.js",
|
||||
"legacyImports": [
|
||||
{
|
||||
"specifier": "/static/js/ui.js?v=20260916largetoolscroll1",
|
||||
"reason": "Existing shared UI/platform identity, injected at Notes composition. Remove when that shared responsibility migrates to maintained source."
|
||||
},
|
||||
{
|
||||
"specifier": "/static/js/modalManager.js",
|
||||
"reason": "Existing shared UI/platform identity, injected at Notes composition. Remove when that shared responsibility migrates to maintained source."
|
||||
},
|
||||
{
|
||||
"specifier": "/static/js/colorPicker.js?v=20260910eyedropper1",
|
||||
"reason": "Existing shared UI/platform identity, injected at Notes composition. Remove when that shared responsibility migrates to maintained source."
|
||||
},
|
||||
{
|
||||
"specifier": "/static/js/windowDrag.js",
|
||||
"reason": "Existing shared UI/platform identity, injected at Notes composition. Remove when that shared responsibility migrates to maintained source."
|
||||
},
|
||||
{
|
||||
"specifier": "/static/js/tileManager.js?v=20260910responsivebounds1",
|
||||
"reason": "Existing shared UI/platform identity, injected at Notes composition. Remove when that shared responsibility migrates to maintained source."
|
||||
},
|
||||
{
|
||||
"specifier": "/static/js/modalSnap.js",
|
||||
"reason": "Existing shared UI/platform identity, injected at Notes composition. Remove when that shared responsibility migrates to maintained source."
|
||||
},
|
||||
{
|
||||
"specifier": "/static/js/toolWindowZOrder.js",
|
||||
"reason": "Existing shared UI/platform identity, injected at Notes composition. Remove when that shared responsibility migrates to maintained source."
|
||||
},
|
||||
{
|
||||
"specifier": "/static/js/escMenuStack.js",
|
||||
"reason": "Existing shared UI/platform identity, injected at Notes composition. Remove when that shared responsibility migrates to maintained source."
|
||||
},
|
||||
{
|
||||
"specifier": "/static/js/tourHintDismiss.js",
|
||||
"reason": "Existing shared UI/platform identity, injected at Notes composition. Remove when that shared responsibility migrates to maintained source."
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"source": "features/notes/application/submission.js",
|
||||
"deployment": "js/features/notes/application/submission.js"
|
||||
},
|
||||
{
|
||||
"source": "features/notes/application/drafts.js",
|
||||
"deployment": "js/features/notes/application/drafts.js"
|
||||
},
|
||||
{
|
||||
"source": "features/notes/ui/lifecycle.js",
|
||||
"deployment": "js/features/notes/ui/lifecycle.js"
|
||||
},
|
||||
{
|
||||
"source": "features/notes/application/cardOperations.js",
|
||||
"deployment": "js/features/notes/application/cardOperations.js"
|
||||
},
|
||||
{
|
||||
"source": "features/notes/application/checklistOperations.js",
|
||||
"deployment": "js/features/notes/application/checklistOperations.js"
|
||||
},
|
||||
{
|
||||
"source": "features/notes/application/selection.js",
|
||||
"deployment": "js/features/notes/application/selection.js"
|
||||
},
|
||||
{
|
||||
"source": "features/notes/ui/toolbar.js",
|
||||
"deployment": "js/features/notes/ui/toolbar.js"
|
||||
},
|
||||
{
|
||||
"source": "features/notes/ui/windowLayout.js",
|
||||
"deployment": "js/features/notes/ui/windowLayout.js"
|
||||
},
|
||||
{
|
||||
"source": "shared/ui/confetti.js",
|
||||
"deployment": "js/shared/ui/confetti.js"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
/** Create an agent session, link it to a note and drain its background stream. */
|
||||
import { _noteToAgentPrompt } from '../domain/noteRules.js';
|
||||
export function createAgentActions({
|
||||
_patchNote,
|
||||
_renderNotes,
|
||||
api,
|
||||
app,
|
||||
createFormData,
|
||||
state,
|
||||
streamComplete,
|
||||
uiModule
|
||||
}) {
|
||||
async function _agentSolveNote(id) {
|
||||
const note = state.notes.find(n => n.id === id);
|
||||
if (!note) return;
|
||||
const prompt = _noteToAgentPrompt(note);
|
||||
if (!prompt) { uiModule.showToast('Nothing to solve — note is empty'); return; }
|
||||
try {
|
||||
const dc = await (await api.defaultChat()).json();
|
||||
if (!dc.endpoint_url || !dc.model) { uiModule.showError('No default chat model configured'); return; }
|
||||
|
||||
// 1. Create the session server-side (no UI switch). skip_validation
|
||||
// avoids re-probing : the default-chat endpoint is already known good.
|
||||
const label = (note.title || (Array.isArray(note.items) && note.items[0]?.text) || 'todo').slice(0, 40);
|
||||
const csFd = createFormData();
|
||||
csFd.append('name', 'Agent: ' + label);
|
||||
csFd.append('endpoint_url', dc.endpoint_url);
|
||||
csFd.append('model', dc.model);
|
||||
if (dc.endpoint_id) csFd.append('endpoint_id', dc.endpoint_id);
|
||||
csFd.append('skip_validation', 'true');
|
||||
const csRes = await api.createSession(csFd);
|
||||
if (!csRes.ok) { uiModule.showError('Could not create agent session'); return; }
|
||||
const sess = await csRes.json();
|
||||
const sid = sess.id;
|
||||
|
||||
// 2. Link the session to the note right away so the tag appears.
|
||||
const n = state.notes.find(x => x.id === id);
|
||||
if (n) app.mergeNote(n, { agent_session_id: sid });
|
||||
_renderNotes();
|
||||
_patchNote(id, { agent_session_id: sid }).catch(() => {});
|
||||
|
||||
// 3. Kick off the agent run in the background. POST to chat_stream in
|
||||
// agent mode and drain the SSE so the server runs the loop to
|
||||
// completion + saves : without rendering anything in the chat UI.
|
||||
const fd = createFormData();
|
||||
fd.append('message', prompt);
|
||||
fd.append('session', sid);
|
||||
fd.append('mode', 'agent');
|
||||
fd.append('disabled_tools', JSON.stringify(['manage_notes']));
|
||||
api.startChat(fd)
|
||||
.then(async (res) => {
|
||||
if (!res.ok || !res.body) return;
|
||||
const reader = res.body.getReader();
|
||||
// Drain to completion (server finishes + persists the run).
|
||||
while (true) { const { done } = await reader.read(); if (done) break; }
|
||||
streamComplete(sid);
|
||||
})
|
||||
.catch(() => {});
|
||||
|
||||
uiModule.showToast('Agent working in background — tap the Agent tag when ready');
|
||||
} catch (e) {
|
||||
uiModule.showError('Agent failed: ' + (e.message || e));
|
||||
}
|
||||
}
|
||||
|
||||
return { _agentSolveNote };
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
/** Optimistic card mutations and rollback. Animation completion is a UI-supplied boundary. */
|
||||
export function createCardOperations({
|
||||
app,
|
||||
api,
|
||||
effects,
|
||||
pushUndo,
|
||||
undoArchive
|
||||
}) {
|
||||
const state = app.state;
|
||||
function togglePin(id) {
|
||||
const note = state.notes.find(n => n.id === id);
|
||||
if (!note) return;
|
||||
const prevPinned = note.pinned, prevSortOrder = note.sort_order;
|
||||
app.mergeNote(note, { pinned: !prevPinned });
|
||||
const patch = { pinned: note.pinned };
|
||||
if (note.pinned) {
|
||||
const minPinned = state.notes.filter(n => n.pinned && n.id !== id).reduce((m, n) => Math.min(m, n.sort_order || 0), 0);
|
||||
app.mergeNote(note, { sort_order: minPinned - 1 });
|
||||
patch.sort_order = note.sort_order;
|
||||
}
|
||||
effects.render();
|
||||
api.patchNote(id, patch).catch(() => {
|
||||
app.mergeNote(note, { pinned: prevPinned, sort_order: prevSortOrder });
|
||||
effects.render(); effects.showError('Failed to pin');
|
||||
});
|
||||
}
|
||||
async function updateColor(id, color) {
|
||||
try {
|
||||
await api.patchNote(id, { color: color || null });
|
||||
const note = state.notes.find(n => n.id === id);
|
||||
if (note) app.mergeNote(note, { color });
|
||||
} catch { effects.showError('Failed to update color'); }
|
||||
}
|
||||
function stageArchive(id) {
|
||||
const index = state.notes.findIndex(n => n.id === id);
|
||||
if (index < 0) return null;
|
||||
const removed = app.removeNoteAt(index);
|
||||
const undo = () => undoArchive(removed, index);
|
||||
pushUndo({ label: 'archive', run: undo });
|
||||
return () => {
|
||||
effects.render();
|
||||
api.patchNote(id, { archived: true }).then(() => effects.archived(undo)).catch(() => {
|
||||
app.insertNoteAt(index, removed); effects.render(); effects.showError('Failed to archive');
|
||||
});
|
||||
};
|
||||
}
|
||||
function unarchive(id) {
|
||||
const index = state.notes.findIndex(n => n.id === id);
|
||||
if (index < 0) return;
|
||||
const removed = app.removeNoteAt(index);
|
||||
effects.render();
|
||||
api.patchNote(id, { archived: false }).then(() => effects.showToast('Unarchived')).catch(() => {
|
||||
app.insertNoteAt(index, removed); effects.render(); effects.showError('Failed to unarchive');
|
||||
});
|
||||
}
|
||||
function deleteOptimistically(id, toast = false) {
|
||||
const index = state.notes.findIndex(n => n.id === id);
|
||||
if (index < 0) return;
|
||||
const removed = app.removeNoteAt(index);
|
||||
effects.render();
|
||||
const deletion = api.deleteNote(id);
|
||||
const completion = toast ? deletion.then(() => effects.showToast('Deleted')) : deletion;
|
||||
completion.catch(() => {
|
||||
app.insertNoteAt(index, removed); effects.render(); effects.showError('Failed to delete');
|
||||
});
|
||||
}
|
||||
// Desktop deliberately persists without updating local sort_order, as before.
|
||||
function persistOrder(ids) { return api.reorder(ids); }
|
||||
async function commitMobileOrder(ids) {
|
||||
try {
|
||||
await api.reorder(ids);
|
||||
ids.forEach((id, index) => {
|
||||
const note = state.notes.find(note => note.id === id);
|
||||
if (note) app.mergeNote(note, { sort_order: index });
|
||||
});
|
||||
} catch (error) { console.warn('reorder failed', error); }
|
||||
}
|
||||
return { togglePin, updateColor, stageArchive, unarchive, deleteOptimistically, persistOrder, commitMobileOrder };
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
/** Checklist item workflows. Supplied feedback callbacks update the invoking view. */
|
||||
export function createChecklistOperations({
|
||||
app,
|
||||
api,
|
||||
effects,
|
||||
uid
|
||||
}) {
|
||||
const state = app.state;
|
||||
function itemNote(id, index) {
|
||||
const note = state.notes.find(n => n.id === id);
|
||||
return note && Array.isArray(note.items) && note.items[index] ? note : null;
|
||||
}
|
||||
function removeItem(id, index) {
|
||||
const note = itemNote(id, index);
|
||||
if (!note) return;
|
||||
const removed = note.items[index];
|
||||
app.mergeNote(note, { items: note.items.filter((_, i) => i !== index) });
|
||||
effects.render();
|
||||
api.patchNote(id, { items: note.items }).catch(() => {
|
||||
app.spliceItems(note, index, 0, removed); effects.render(); effects.showError('Failed to remove item');
|
||||
});
|
||||
}
|
||||
function editItem(note, index, text) {
|
||||
const oldText = (note.items[index].text || '').trim();
|
||||
if (text === oldText) { effects.render(); return; }
|
||||
const oldItem = note.items[index];
|
||||
if (!text) app.spliceItems(note, index, 1);
|
||||
else app.updateItem(note, index, { text });
|
||||
api.patchNote(note.id, { items: note.items }).catch(() => {
|
||||
if (!text) app.spliceItems(note, index, 0, oldItem);
|
||||
else app.updateItem(note, index, { text: oldText });
|
||||
effects.render(); effects.showError('Failed to update item');
|
||||
});
|
||||
effects.render();
|
||||
}
|
||||
function addItem(id, text, added) {
|
||||
const note = state.notes.find(n => n.id === id);
|
||||
if (!note) return;
|
||||
const items = Array.isArray(note.items) ? [...note.items] : [];
|
||||
items.push({ id: uid(), text, done: false });
|
||||
app.mergeNote(note, { items });
|
||||
added(); effects.render();
|
||||
return () => api.patchNote(id, { items }).catch(() => {
|
||||
app.mergeNote(note, { items: items.slice(0, -1) }); effects.render(); effects.showError('Failed to add item');
|
||||
});
|
||||
}
|
||||
function toggleItem(id, index, changed, completed) {
|
||||
const note = itemNote(id, index);
|
||||
if (!note) return;
|
||||
const wasDone = note.items.length > 0 && note.items.every(it => it.done);
|
||||
app.updateItem(note, index, { done: !note.items[index].done });
|
||||
changed(note.items[index].done);
|
||||
if (!wasDone && note.items.length > 0 && note.items.every(it => it.done)) completed();
|
||||
api.patchNote(id, { items: note.items }).catch(() => {
|
||||
app.updateItem(note, index, { done: !note.items[index].done }); changed(note.items[index].done);
|
||||
});
|
||||
}
|
||||
async function toggleTodayStep(id, index, changed, completed) {
|
||||
const note = itemNote(id, index);
|
||||
if (!note) return;
|
||||
app.updateItem(note, index, { done: !note.items[index].done }); changed();
|
||||
try {
|
||||
await api.patchNote(id, { items: note.items }); effects.render();
|
||||
if (note.items.every(it => it.done)) completed();
|
||||
} catch { app.updateItem(note, index, { done: !note.items[index].done }); }
|
||||
}
|
||||
return { removeItem, editItem, addItem, toggleItem, toggleTodayStep };
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
/** Confirmed deletion and past-reminder clearing workflows. */
|
||||
export function createDeletion({
|
||||
app,
|
||||
_deleteNoteApi,
|
||||
_fetchNotes,
|
||||
_isPastReminder,
|
||||
_renderNotes,
|
||||
effects,
|
||||
state
|
||||
}) {
|
||||
async function _deleteNote(id) {
|
||||
const ok = effects.styledConfirm
|
||||
? await effects.styledConfirm('Delete this note?', { confirmText: 'Delete', danger: true })
|
||||
: effects.confirm('Delete this note?');
|
||||
if (!ok) return;
|
||||
try { await _deleteNoteApi(id); await _fetchNotes(); _renderNotes(); effects.showToast('Deleted'); }
|
||||
catch (err) { effects.showError(err.message); }
|
||||
}
|
||||
|
||||
async function _clearPastReminders() {
|
||||
const targets = state.notes.filter(n => !n.archived && _isPastReminder(n));
|
||||
if (!targets.length) {
|
||||
effects.showToast?.('No past reminders to clear');
|
||||
return;
|
||||
}
|
||||
const ok = effects.styledConfirm
|
||||
? await effects.styledConfirm(`Delete ${targets.length} past reminder${targets.length === 1 ? '' : 's'}?`, { confirmText: 'Delete', danger: true })
|
||||
: effects.confirm(`Delete ${targets.length} past reminder${targets.length === 1 ? '' : 's'}?`);
|
||||
if (!ok) return;
|
||||
await Promise.all(targets.map(n => _deleteNoteApi(n.id).catch(() => {})));
|
||||
await _fetchNotes();
|
||||
_renderNotes();
|
||||
effects.showToast?.(`Cleared ${targets.length} past reminder${targets.length === 1 ? '' : 's'}`);
|
||||
}
|
||||
|
||||
async function deleteFromEditor(id) {
|
||||
const ok = effects.styledConfirm
|
||||
? await effects.styledConfirm('Delete this note?', { confirmText: 'Delete', danger: true })
|
||||
: effects.confirm('Delete this note?');
|
||||
if (!ok) return;
|
||||
const index = state.notes.findIndex(note => note.id === id);
|
||||
if (index >= 0) app.removeNoteAt(index);
|
||||
app.setEditingId(null);
|
||||
_renderNotes();
|
||||
_deleteNoteApi(id).then(() => effects.showToast('Deleted')).catch(() => {
|
||||
effects.showError('Failed to delete');
|
||||
_fetchNotes().then(() => _renderNotes());
|
||||
});
|
||||
}
|
||||
return { _deleteNote, _clearPastReminders, deleteFromEditor };
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
/** Serialized autosave and synchronous local draft backup. DOM collection is a supplied port. */
|
||||
export function createNotesDrafts({
|
||||
app,
|
||||
api,
|
||||
persistence,
|
||||
scheduler,
|
||||
effects
|
||||
}) {
|
||||
const state = app.state;
|
||||
const { _draftKey, _clearDraft } = persistence;
|
||||
function bindDraft({ collect, id, view }) {
|
||||
let t = null;
|
||||
let pending = Promise.resolve();
|
||||
let stopped = false;
|
||||
let warned = false;
|
||||
const save = () => {
|
||||
const d = collect();
|
||||
// An empty edit can be intentional: don't restore stale server text over it.
|
||||
try { persistence.setItem(_draftKey(id), JSON.stringify(d)); }
|
||||
catch {
|
||||
if (!warned) effects.showError('Draft backup unavailable. Keep this note open until saved.');
|
||||
warned = true;
|
||||
}
|
||||
return d;
|
||||
};
|
||||
const persist = (d) => {
|
||||
if (!id || id === '__new__' || d.note_type === 'draw') return pending;
|
||||
const { _ts, ...payload } = d;
|
||||
payload.label = [...new Set(payload.label.split(/\s+/).map(s => s.replace(/^#+/, '')).filter(Boolean))].join(' ') || null;
|
||||
pending = pending.then(async () => {
|
||||
try {
|
||||
await api.patchNote(id, payload);
|
||||
view.failed = false;
|
||||
const note = state.notes.find(n => n.id === id);
|
||||
if (note) app.mergeNote(note, payload);
|
||||
if (persistence.getItem(_draftKey(id)) === JSON.stringify(d)) _clearDraft(id);
|
||||
} catch {
|
||||
if (!view.failed) effects.showError('Note not synced. Your edits are kept on this device; retry Save.');
|
||||
view.failed = true;
|
||||
}
|
||||
});
|
||||
return pending;
|
||||
};
|
||||
const flush = () => { scheduler.clearTimeout(t); return save(); };
|
||||
const stop = () => { stopped = true; scheduler.clearTimeout(t); return pending; };
|
||||
const sched = () => {
|
||||
const d = save();
|
||||
if (stopped) return;
|
||||
scheduler.clearTimeout(t);
|
||||
t = scheduler.setTimeout(() => persist(d), 500);
|
||||
};
|
||||
return { flush, stop, schedule: sched };
|
||||
}
|
||||
return { bindDraft };
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
/** Application-owned filtering, searching and note ordering. */
|
||||
import { _noteTags, _visibleNoteTags, _nextGoalStep, _isCalendarReminderNote } from '../domain/noteRules.js';
|
||||
import { _hasTimeComponent } from '../domain/recurrence.js';
|
||||
export function createQueries({
|
||||
_hasActiveReminder,
|
||||
state
|
||||
}) {
|
||||
function _sortedVisibleNotes() {
|
||||
const displayNotes = _userVisibleNotes();
|
||||
let filtered = state.activeLabel ? displayNotes.filter(n => _noteTags(n).includes(state.activeLabel)) : displayNotes;
|
||||
if (state.activeFilter === 'reminders') {
|
||||
filtered = filtered.filter(n => n.due_date && _hasTimeComponent(n.due_date));
|
||||
} else if (state.activeFilter === 'no-reminders') {
|
||||
filtered = filtered.filter(n => !(n.due_date && _hasTimeComponent(n.due_date)));
|
||||
} else if (state.activeFilter === 'default') {
|
||||
filtered = filtered.filter(n => _visibleNoteTags(n).length === 0);
|
||||
} else if (state.activeFilter === 'goals') {
|
||||
filtered = filtered.filter(n => n.note_type === 'goal' && !n.archived);
|
||||
} else if (state.activeFilter === 'today') {
|
||||
// Today view: only goals that still have an unchecked step.
|
||||
filtered = filtered.filter(n => n.note_type === 'goal' && !n.archived && _nextGoalStep(n));
|
||||
}
|
||||
if (state.searchQuery) {
|
||||
filtered = filtered.filter(n => {
|
||||
const q = state.searchQuery;
|
||||
if ((n.title || '').toLowerCase().includes(q)) return true;
|
||||
if ((n.content || '').toLowerCase().includes(q)) return true;
|
||||
if ((n.label || '').toLowerCase().includes(q)) return true;
|
||||
if (Array.isArray(n.items) && n.items.some(it => (it.text || '').toLowerCase().includes(q))) return true;
|
||||
return false;
|
||||
});
|
||||
}
|
||||
const sorted = [...filtered].sort((a, b) => {
|
||||
// In reminders view: sort by due date ascending (soonest first)
|
||||
if (state.activeFilter === 'reminders') {
|
||||
const da = new Date(a.due_date || 0).getTime();
|
||||
const db = new Date(b.due_date || 0).getTime();
|
||||
return da - db;
|
||||
}
|
||||
// Archived view: newest archived first (ignore manual sort_order).
|
||||
if (state.showingArchived) {
|
||||
return new Date(b.updated_at || 0) - new Date(a.updated_at || 0);
|
||||
}
|
||||
if (a.pinned && !b.pinned) return -1;
|
||||
if (!a.pinned && b.pinned) return 1;
|
||||
// Active reminders (due date in the past, not done/archived) rank
|
||||
// immediately under the pinned block.
|
||||
const aActive = _hasActiveReminder(a);
|
||||
const bActive = _hasActiveReminder(b);
|
||||
if (aActive && !bActive) return -1;
|
||||
if (!aActive && bActive) return 1;
|
||||
const so = (a.sort_order || 0) - (b.sort_order || 0);
|
||||
if (so !== 0) return so;
|
||||
return new Date(b.updated_at || 0) - new Date(a.updated_at || 0);
|
||||
});
|
||||
|
||||
|
||||
return sorted;
|
||||
}
|
||||
|
||||
function _userVisibleNotes() {
|
||||
return state.notes.filter(n => !_isCalendarReminderNote(n));
|
||||
}
|
||||
|
||||
return { _sortedVisibleNotes, _userVisibleNotes };
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
/** Page-owned reminder scheduler and notification delivery workflow. */
|
||||
import { _hasTimeComponent, _isDueTodayOrOverdue, _advanceRecurring } from '../domain/recurrence.js';
|
||||
export function createNotesReminders({
|
||||
app,
|
||||
api,
|
||||
persistence,
|
||||
notifications,
|
||||
clock,
|
||||
scheduler,
|
||||
effects,
|
||||
fetchNotes,
|
||||
isNoteFullyDone,
|
||||
hasItems,
|
||||
dismissedKey
|
||||
}) {
|
||||
const state = app.state;
|
||||
const { _loadFiredReminders, _saveFiredReminders } = persistence;
|
||||
const _patchNote = api.patchNote;
|
||||
const _fetchNotes = fetchNotes;
|
||||
const _isNoteFullyDone = isNoteFullyDone;
|
||||
const _hasItems = hasItems;
|
||||
const REMINDER_DISMISSED_AT_KEY = dismissedKey;
|
||||
const _updateRailBadge = effects.badge;
|
||||
let _reminderTimer = null;
|
||||
let startupTimer = null;
|
||||
let started = false;
|
||||
let disposed = false;
|
||||
function _checkReminders() {
|
||||
if (!state.notes.length) return;
|
||||
const now = clock.now();
|
||||
const fired = _loadFiredReminders();
|
||||
let changed = false;
|
||||
for (const note of state.notes) {
|
||||
if (!note.due_date || note.archived) continue;
|
||||
if (!_hasTimeComponent(note.due_date)) continue;
|
||||
if (fired.has(note.id)) continue;
|
||||
const due = new Date(note.due_date).getTime();
|
||||
if (isNaN(due)) continue;
|
||||
if (due <= now && due > now - 60000) {
|
||||
_fireReminder(note);
|
||||
// Recurring? advance the due_date instead of marking as fired
|
||||
if (note.repeat && note.repeat !== 'none') {
|
||||
const next = _advanceRecurring(note.due_date, note.repeat, clock);
|
||||
if (next) {
|
||||
app.mergeNote(note, { due_date: next });
|
||||
_patchNote(note.id, { due_date: next }).catch(() => {});
|
||||
// Don't add to fired : new due_date is in the future
|
||||
continue;
|
||||
}
|
||||
}
|
||||
fired.add(note.id);
|
||||
changed = true;
|
||||
} else if (due <= now - 60000) {
|
||||
// Past, never seen : silently advance recurring or mark fired
|
||||
if (note.repeat && note.repeat !== 'none') {
|
||||
const next = _advanceRecurring(note.due_date, note.repeat, clock);
|
||||
if (next) {
|
||||
app.mergeNote(note, { due_date: next });
|
||||
_patchNote(note.id, { due_date: next }).catch(() => {});
|
||||
continue;
|
||||
}
|
||||
}
|
||||
fired.add(note.id);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if (changed) _saveFiredReminders(fired);
|
||||
// Always refresh badge : fired state may have changed visually without note mutation
|
||||
_updateRailBadge();
|
||||
}
|
||||
|
||||
function _fireReminder(note) {
|
||||
const title = note.title || 'Note reminder';
|
||||
// Include the verbatim note content so the email/notification actually
|
||||
// shows what to do, not just a count. Cap the per-item lines (8 max) and
|
||||
// total length so the body stays inbox-friendly.
|
||||
let rawBody;
|
||||
if (_hasItems(note)) {
|
||||
const pending = (note.items || [])
|
||||
.filter(i => !i.done && !i.checked)
|
||||
.map(i => (i.text || '').trim())
|
||||
.filter(Boolean);
|
||||
if (pending.length) {
|
||||
const shown = pending.slice(0, 8).map(t => `- ${t}`).join('\n');
|
||||
const extra = pending.length > 8 ? `\n…and ${pending.length - 8} more` : '';
|
||||
rawBody = `Pending (${pending.length}):\n${shown}${extra}`;
|
||||
} else {
|
||||
rawBody = `${(note.items || []).length} item${(note.items || []).length === 1 ? '' : 's'}`;
|
||||
}
|
||||
} else {
|
||||
rawBody = (note.content || '').slice(0, 400);
|
||||
}
|
||||
|
||||
// Ask the server to dispatch according to user settings. The server may
|
||||
// return an LLM-written synthesis line and/or send an email. We still show
|
||||
// a local browser notification so the user gets immediate feedback even if
|
||||
// the server path is disabled or slow.
|
||||
const showLocal = body => notifications.show(title, body, note.id);
|
||||
|
||||
// Fire-and-forget server dispatch. If synthesis comes back quickly enough,
|
||||
// use it as the notification body; otherwise the local notification has
|
||||
// already shown with the raw body.
|
||||
let shown = false;
|
||||
const timer = scheduler.setTimeout(() => { if (!shown) { shown = true; showLocal(rawBody); } }, 1500);
|
||||
|
||||
api.fireReminder({ note_id: note.id, title, body: rawBody })
|
||||
.then(r => r.ok ? r.json() : null)
|
||||
.then(data => {
|
||||
scheduler.clearTimeout(timer);
|
||||
if (shown) return;
|
||||
shown = true;
|
||||
const body = (data && data.synthesis) ? data.synthesis : rawBody;
|
||||
showLocal(body);
|
||||
})
|
||||
.catch(() => {
|
||||
scheduler.clearTimeout(timer);
|
||||
if (!shown) { shown = true; showLocal(rawBody); }
|
||||
});
|
||||
|
||||
// Pulse the card if visible; otherwise queue it so the next time the user
|
||||
// opens the notes panel the card gets a brief glow.
|
||||
effects.highlight(note.id);
|
||||
}
|
||||
|
||||
function _startReminderLoop() {
|
||||
if (disposed || _reminderTimer) return;
|
||||
_reminderTimer = scheduler.setInterval(_checkReminders, 30000);
|
||||
_checkReminders(); // run once immediately
|
||||
}
|
||||
|
||||
function _countDueReminders() {
|
||||
return state.notes.filter(n => !n.archived && _isDueTodayOrOverdue(n.due_date, clock) && !_isNoteFullyDone(n)).length;
|
||||
}
|
||||
|
||||
function _countFiredReminders() {
|
||||
// Reminders whose time has actually passed (not just date-today),
|
||||
// and which fired after the last user dismissal.
|
||||
const now = clock.now();
|
||||
return state.notes.filter(n => {
|
||||
if (n.archived || _isNoteFullyDone(n)) return false;
|
||||
if (!n.due_date || !_hasTimeComponent(n.due_date)) return false;
|
||||
const t = new Date(n.due_date).getTime();
|
||||
if (isNaN(t) || t > now) return false;
|
||||
return t > state.firedDotDismissedAt;
|
||||
}).length;
|
||||
}
|
||||
|
||||
function dismissFiredReminderDot() {
|
||||
app.setFiredDotDismissedAt(clock.now());
|
||||
try { persistence.setItem(REMINDER_DISMISSED_AT_KEY, String(state.firedDotDismissedAt)); } catch {}
|
||||
_updateRailBadge();
|
||||
}
|
||||
|
||||
async function refreshDueBadge(opts = {}) {
|
||||
// Usually lightweight, but callers that just created a note reminder can
|
||||
// force a refresh so the background reminder loop sees it immediately.
|
||||
if (opts.force || state.notes.length === 0) {
|
||||
try {
|
||||
const wasArchived = state.showingArchived;
|
||||
app.setShowingArchived(false);
|
||||
await _fetchNotes();
|
||||
app.setShowingArchived(wasArchived);
|
||||
} catch {}
|
||||
}
|
||||
_updateRailBadge();
|
||||
}
|
||||
|
||||
async function _initReminders() {
|
||||
try {
|
||||
const res = await api.listNotes(false);
|
||||
if (res.ok && !disposed) {
|
||||
const data = await res.json();
|
||||
app.replaceNotes(data.notes || data || []);
|
||||
_startReminderLoop();
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
|
||||
function start() { if (started || disposed) return; started = true; startupTimer = scheduler.setTimeout(_initReminders, 3000); }
|
||||
function dispose() { disposed = true; scheduler.clearTimeout(startupTimer); scheduler.clearInterval(_reminderTimer); _reminderTimer = null; }
|
||||
return { start, dispose, _checkReminders, _fireReminder, _startReminderLoop, _countDueReminders, _countFiredReminders, dismissFiredReminderDot, refreshDueBadge, _initReminders };
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/** Selected-note attachment retains synchronous acceptance; bulk requests retain partial-failure behavior. */
|
||||
export function createSelectionOperations({
|
||||
app,
|
||||
api,
|
||||
effects,
|
||||
sendContext,
|
||||
exitSelection,
|
||||
fetchNotes
|
||||
}) {
|
||||
const state = app.state;
|
||||
function attachSelected() {
|
||||
const ids = [...state.selectedIds];
|
||||
if (!ids.length) return;
|
||||
const detail = { noteIds: ids, accepted: false };
|
||||
sendContext(detail);
|
||||
if (!detail.accepted) {
|
||||
effects.showToast('Choose a chat or model before attaching notes');
|
||||
return;
|
||||
}
|
||||
exitSelection();
|
||||
}
|
||||
async function archiveSelected() {
|
||||
const ids = [...state.selectedIds];
|
||||
if (!ids.length) return;
|
||||
await Promise.all(ids.map(id => api.patchNote(id, { archived: true }).catch(() => {})));
|
||||
exitSelection(); await fetchNotes(); effects.render(); effects.showToast(`Archived ${ids.length}`);
|
||||
}
|
||||
async function deleteSelected() {
|
||||
const ids = [...state.selectedIds];
|
||||
if (!ids.length) return;
|
||||
if (effects.styledConfirm) {
|
||||
const ok = await effects.styledConfirm(`Delete ${ids.length} note${ids.length === 1 ? '' : 's'}?`, { confirmText: 'Delete', danger: true });
|
||||
if (!ok) return;
|
||||
}
|
||||
await Promise.all(ids.map(id => api.deleteNote(id).catch(() => {})));
|
||||
exitSelection(); await fetchNotes(); effects.render(); effects.showToast(`Deleted ${ids.length}`);
|
||||
}
|
||||
return { attachSelected, archiveSelected, deleteSelected };
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
/** The sole Notes state owner. Views have live read-only access; writes use operations. */
|
||||
export function createNotesState(initial = {}) {
|
||||
const values = {
|
||||
open: false, notes: [], editingId: null, selectedIds: new Set(),
|
||||
activeLabel: null, activeFilter: null, reminderChipNext: 'reminders', searchQuery: '',
|
||||
viewMode: initial.viewMode || 'list', showingArchived: false, selectMode: false,
|
||||
suppressNextNoteTapId: null, labelsCollapsed: !!initial.labelsCollapsed,
|
||||
loading: false, firedDotDismissedAt: initial.firedDotDismissedAt || 0,
|
||||
};
|
||||
// Preserve captured note identity across asynchronous completions without
|
||||
// giving a view a writable reference to the application store.
|
||||
const views = new WeakMap(), targets = new WeakMap();
|
||||
const unwrap = value => targets.get(value) || value;
|
||||
// Copies built from views (spread, filter, map) still hold nested views;
|
||||
// store only raw data so the owner never keeps its own read-only views.
|
||||
function unwrapDeep(value, seen = new WeakSet()) {
|
||||
if (!value || typeof value !== 'object') return value;
|
||||
if (targets.has(value)) return targets.get(value);
|
||||
if (seen.has(value)) return value;
|
||||
seen.add(value);
|
||||
if (Array.isArray(value)) value.forEach((item, index) => { value[index] = unwrapDeep(item, seen); });
|
||||
else if (Object.getPrototypeOf(value) === Object.prototype) for (const key of Object.keys(value)) value[key] = unwrapDeep(value[key], seen);
|
||||
return value;
|
||||
}
|
||||
function readonly(value) {
|
||||
if (!value || typeof value !== 'object') return value;
|
||||
if (targets.has(value)) return value;
|
||||
if (views.has(value)) return views.get(value);
|
||||
const view = new Proxy(value, {
|
||||
get(target, key) {
|
||||
if (target instanceof Set) {
|
||||
if (['add', 'delete', 'clear'].includes(key)) return () => { throw new TypeError('Use Notes selection operations'); };
|
||||
if (key === 'valueOf') return () => views.get(target);
|
||||
if (key === 'forEach') return (callback, thisArg) => target.forEach(value => callback.call(thisArg, value, value, views.get(target)));
|
||||
const member = Reflect.get(target, key, target);
|
||||
return typeof member === 'function' ? member.bind(target) : member;
|
||||
}
|
||||
return readonly(Reflect.get(target, key));
|
||||
},
|
||||
set() { throw new TypeError('Use Notes state operations'); },
|
||||
deleteProperty() { throw new TypeError('Use Notes state operations'); },
|
||||
defineProperty() { throw new TypeError('Use Notes state operations'); },
|
||||
setPrototypeOf() { throw new TypeError('Use Notes state operations'); },
|
||||
preventExtensions() { throw new TypeError('Use Notes state operations'); },
|
||||
getOwnPropertyDescriptor(target, key) {
|
||||
const descriptor = Reflect.getOwnPropertyDescriptor(target, key);
|
||||
if (descriptor && 'value' in descriptor) return { ...descriptor, value: readonly(descriptor.value) };
|
||||
return descriptor;
|
||||
},
|
||||
});
|
||||
views.set(value, view); targets.set(view, value);
|
||||
return view;
|
||||
}
|
||||
const state = Object.freeze(Object.fromEntries(Object.keys(values).map(key => [key, () => readonly(values[key])])));
|
||||
const view = Object.freeze(Object.defineProperties({}, Object.fromEntries(Object.entries(state).map(([key, get]) => [key, { get, enumerable: true }]))));
|
||||
return {
|
||||
state: view,
|
||||
setOpen: value => { values.open = value; },
|
||||
setEditingId: value => { values.editingId = value; },
|
||||
setActiveLabel: value => { values.activeLabel = value; },
|
||||
setActiveFilter: value => { values.activeFilter = value; },
|
||||
setReminderChipNext: value => { values.reminderChipNext = value; },
|
||||
setSearchQuery: value => { values.searchQuery = value; },
|
||||
setViewMode: value => { values.viewMode = value; },
|
||||
setShowingArchived: value => { values.showingArchived = value; },
|
||||
setSelectMode: value => { values.selectMode = value; },
|
||||
setSuppressNextNoteTapId: value => { values.suppressNextNoteTapId = value; },
|
||||
setLabelsCollapsed: value => { values.labelsCollapsed = value; },
|
||||
setLoading: value => { values.loading = value; },
|
||||
setFiredDotDismissedAt: value => { values.firedDotDismissedAt = value; },
|
||||
replaceNotes: notes => { values.notes = notes; },
|
||||
removeNoteAt: index => readonly(values.notes.splice(index, 1)[0]),
|
||||
insertNoteAt: (index, note) => { values.notes.splice(index, 0, unwrapDeep(note)); },
|
||||
prependNote: note => { values.notes.unshift(unwrapDeep(note)); },
|
||||
replaceNoteAt: (index, note) => { values.notes[index] = unwrapDeep(note); },
|
||||
mergeNote: (note, patch) => { for (const [key, value] of Object.entries(patch)) unwrap(note)[key] = unwrapDeep(value); },
|
||||
updateItem: (note, index, patch) => { Object.assign(unwrap(unwrap(note).items[index]), unwrapDeep({ ...patch })); },
|
||||
spliceItems: (note, ...args) => unwrap(unwrap(note).items).splice(...args.map(arg => unwrapDeep(arg))),
|
||||
selectId: id => { values.selectedIds.add(id); },
|
||||
deselectId: id => values.selectedIds.delete(id),
|
||||
clearSelection: () => values.selectedIds.clear(),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
/** Editor submission ordering, optimistic state, reminder rearming and save recovery. */
|
||||
export function createNotesSubmission({
|
||||
app,
|
||||
api,
|
||||
persistence,
|
||||
clock,
|
||||
uid,
|
||||
effects,
|
||||
fetchNotes
|
||||
}) {
|
||||
const state = app.state;
|
||||
const { _loadFiredReminders, _saveFiredReminders, _loadGlowedReminders, _saveGlowedReminders, _loadDraft, _clearDraft } = persistence;
|
||||
function submitNote(payload, note, isEdit) {
|
||||
// Reset fired reminder if due_date changed (so re-arm works), and also
|
||||
// clear the entry-glow seen flag so the new firing glows again on the
|
||||
// next time the user opens the panel.
|
||||
if (isEdit && note.due_date !== payload.due_date) {
|
||||
const fired = _loadFiredReminders();
|
||||
fired.delete(note.id);
|
||||
_saveFiredReminders(fired);
|
||||
const glowed = _loadGlowedReminders();
|
||||
glowed.delete(note.id);
|
||||
_saveGlowedReminders(glowed);
|
||||
effects.clearGlow(note.id);
|
||||
}
|
||||
// Edited notes move to the top of their section (under pinned). Compute
|
||||
// sort_order = (min unpinned sort_order) - 1 so the saved note sorts above
|
||||
// siblings; the pin block keeps its own ordering above this.
|
||||
if (!payload.pinned) {
|
||||
// Both edits AND newly-created notes anchor above the rest of the
|
||||
// unpinned section. Without this, freshly created notes sit at the
|
||||
// bottom because manually-reordered siblings already carry negative
|
||||
// sort_order values.
|
||||
const minUnpinned = state.notes
|
||||
.filter(n => !n.pinned && (!isEdit || n.id !== note.id))
|
||||
.reduce((m, n) => Math.min(m, n.sort_order || 0), 0);
|
||||
payload.sort_order = minUnpinned - 1;
|
||||
}
|
||||
// Optimistic update : update local state first, render, then save in background
|
||||
app.setEditingId(null);
|
||||
const draftId = isEdit ? note.id : '__new__';
|
||||
const submittedDraft = JSON.stringify(_loadDraft(draftId));
|
||||
if (isEdit) {
|
||||
const idx = state.notes.findIndex(n => n.id === note.id);
|
||||
if (idx >= 0) app.replaceNoteAt(idx, { ...state.notes[idx], ...payload });
|
||||
} else {
|
||||
app.prependNote({ ...payload, id: 'tmp_' + uid(), created_at: new Date(clock.now()).toISOString(), updated_at: new Date(clock.now()).toISOString() });
|
||||
}
|
||||
effects.render();
|
||||
// Background save
|
||||
api.saveNote(payload).then(saved => {
|
||||
if (JSON.stringify(_loadDraft(draftId)) === submittedDraft) _clearDraft(draftId);
|
||||
if (!isEdit && saved && saved.id) {
|
||||
// Replace temp ID with real one from server. AND re-render : the
|
||||
// existing card's `data-note-id="tmp_xxx"` is stale after Object.assign
|
||||
// bumps the in-memory id, so all subsequent clicks (edit, done, copy,
|
||||
// archive, delete) silently fail to find the note in `_notes`.
|
||||
const tmp = state.notes.find(n => n.id.startsWith('tmp_'));
|
||||
if (tmp) app.mergeNote(tmp, saved);
|
||||
effects.render();
|
||||
}
|
||||
}).catch(err => {
|
||||
effects.showError('Save failed: ' + err.message);
|
||||
fetchNotes().then(() => effects.render());
|
||||
});
|
||||
|
||||
}
|
||||
return { submitNote };
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
/** Notes CRUD, optimistic archive and in-memory undo workflows. */
|
||||
export function createNotesWorkflows({
|
||||
app,
|
||||
api,
|
||||
effects
|
||||
}) {
|
||||
const state = app.state;
|
||||
const _undoStack = [];
|
||||
const _renderNotes = effects.render;
|
||||
const _patchNote = api.patchNote;
|
||||
const uiModule = effects;
|
||||
function _pushUndo(entry) {
|
||||
_undoStack.push(entry);
|
||||
if (_undoStack.length > 20) _undoStack.shift();
|
||||
}
|
||||
|
||||
function _popAndRunUndo() {
|
||||
const entry = _undoStack.pop();
|
||||
if (entry) entry.run();
|
||||
return !!entry;
|
||||
}
|
||||
|
||||
function _undoArchive(note, prevIdx) {
|
||||
// Re-insert at original position and clear archived flag on the server.
|
||||
const safeIdx = Math.min(Math.max(prevIdx, 0), state.notes.length);
|
||||
app.insertNoteAt(safeIdx, { ...note, archived: false });
|
||||
_renderNotes();
|
||||
_patchNote(note.id, { archived: false }).catch(() => {
|
||||
// Roll back local insertion if the server refuses
|
||||
const i = state.notes.findIndex(n => n.id === note.id);
|
||||
if (i >= 0) app.removeNoteAt(i);
|
||||
_renderNotes();
|
||||
uiModule.showError('Undo failed');
|
||||
});
|
||||
}
|
||||
|
||||
function _archiveNoteById(id, { card = null, celebrate = false } = {}) {
|
||||
if (!id) return false;
|
||||
const idx = state.notes.findIndex(n => n.id === id);
|
||||
if (idx < 0) return false;
|
||||
const note = state.notes[idx];
|
||||
if (celebrate && card && note) effects.celebrateArchive(note, card);
|
||||
const removed = app.removeNoteAt(idx);
|
||||
app.setEditingId(null);
|
||||
_renderNotes();
|
||||
const undo = () => _undoArchive(removed, idx);
|
||||
_pushUndo({ label: 'archive', run: undo });
|
||||
_patchNote(id, { archived: true }).then(() => {
|
||||
effects.archived(undo);
|
||||
}).catch(() => {
|
||||
app.insertNoteAt(idx, removed);
|
||||
_renderNotes();
|
||||
uiModule.showError('Failed to archive');
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
async function _fetchNotes() {
|
||||
app.setLoading(true);
|
||||
try {
|
||||
const res = await api.listNotes(state.showingArchived);
|
||||
if (!res.ok) { app.replaceNotes([]); return; }
|
||||
const data = await res.json();
|
||||
app.replaceNotes(data.notes || data || []);
|
||||
} catch (e) {
|
||||
console.error('Failed to fetch notes:', e);
|
||||
app.replaceNotes([]);
|
||||
} finally {
|
||||
app.setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
function _saveNote(note) { return api.saveNote(note); }
|
||||
|
||||
function _deleteNoteApi(id) { return api.deleteNote(id); }
|
||||
|
||||
return { _pushUndo, _popAndRunUndo, _undoArchive, _archiveNoteById, _fetchNotes, _saveNote, _deleteNoteApi, _patchNote, undoCount: () => _undoStack.length };
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
/** Pure Notes completion, tags, reminder and serialization rules. */
|
||||
import { _hasTimeComponent } from './recurrence.js';
|
||||
export function _isCalendarReminderNote(n) {
|
||||
return n && n.source === 'calendar' && n.label === 'calendar';
|
||||
}
|
||||
|
||||
export function _hasActiveReminder(n, clock) {
|
||||
if (!n || n.archived || _isNoteFullyDone(n)) return false;
|
||||
if (!n.due_date) return false;
|
||||
const t = new Date(n.due_date).getTime();
|
||||
return !isNaN(t) && t <= clock.now();
|
||||
}
|
||||
|
||||
export function _isNoteFullyDone(note) {
|
||||
if (_hasItems(note) && Array.isArray(note.items) && note.items.length > 0) {
|
||||
return note.items.every(it => it.done);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function _hasItems(note) {
|
||||
return note && (note.note_type === 'todo' || note.note_type === 'goal' || note.note_type === 'checklist');
|
||||
}
|
||||
|
||||
export function _goalProgress(note) {
|
||||
if (!Array.isArray(note?.items) || note.items.length === 0) return '';
|
||||
const done = note.items.filter(it => it.done).length;
|
||||
return ` ${done}/${note.items.length}`;
|
||||
}
|
||||
|
||||
export function _nextGoalStep(note) {
|
||||
if (!Array.isArray(note?.items)) return null;
|
||||
for (let i = 0; i < note.items.length; i++) {
|
||||
if (!note.items[i].done) return { idx: i, item: note.items[i] };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function _noteTags(n) {
|
||||
const tags = [];
|
||||
if (n?.label) tags.push(...n.label.trim().split(/\s+/).filter(Boolean));
|
||||
if (n?.due_date && _hasTimeComponent(n.due_date)) tags.push('reminder');
|
||||
return [...new Set(tags.map(t => t.replace(/^#+/, '').trim()).filter(Boolean))];
|
||||
}
|
||||
|
||||
export function _visibleNoteTags(n) {
|
||||
return _noteTags(n).filter(t => t !== 'reminder');
|
||||
}
|
||||
|
||||
export function _isPastReminder(n, clock) {
|
||||
if (!n?.due_date || !_hasTimeComponent(n.due_date)) return false;
|
||||
const due = new Date(n.due_date).getTime();
|
||||
return !isNaN(due) && due <= clock.now();
|
||||
}
|
||||
|
||||
export function _serializeNoteForCopy(note) {
|
||||
const lines = [];
|
||||
if (note.title) lines.push(note.title);
|
||||
if (note.content) lines.push(note.content);
|
||||
if (Array.isArray(note.items) && note.items.length) {
|
||||
if (lines.length) lines.push('');
|
||||
for (const it of note.items) {
|
||||
if (!it || !(it.text || '').trim()) continue;
|
||||
lines.push(`- [${it.done ? 'x' : ' '}] ${(it.text || '').trim()}`);
|
||||
}
|
||||
}
|
||||
return lines.join('\n').trim();
|
||||
}
|
||||
|
||||
export function _noteToAgentPrompt(note) {
|
||||
const parts = [];
|
||||
if ((note.title || '').trim()) parts.push(note.title.trim());
|
||||
if ((note.content || '').trim()) parts.push(note.content.trim());
|
||||
if (Array.isArray(note.items)) {
|
||||
note.items.filter(it => !it.done && (it.text || '').trim())
|
||||
.forEach(it => parts.push('- ' + it.text.trim()));
|
||||
}
|
||||
const body = parts.join('\n');
|
||||
return body ? `Help me get this done:\n\n${body}\n\nThe source note is read-only. Do not edit, replace, or update it.` : '';
|
||||
}
|
||||
|
||||
export function _standardVisualVariant(note) {
|
||||
const source = String(note?.id || note?.title || note?.created_at || 'standard-note');
|
||||
let hash = 0;
|
||||
for (let i = 0; i < source.length; i++) hash = ((hash << 5) - hash + source.charCodeAt(i)) | 0;
|
||||
return Math.abs(hash) % 5;
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
// Local-time date and recurrence rules. Callers supply the clock at the original read sites.
|
||||
export const _ORDINALS = ['1st', '2nd', '3rd', '4th', '5th'];
|
||||
export const _DAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
|
||||
export function _hasTimeComponent(dateStr) {
|
||||
return typeof dateStr === 'string' && /T\d{2}:\d{2}/.test(dateStr);
|
||||
}
|
||||
|
||||
export function _formatDueDate(dateStr, clock) {
|
||||
if (!dateStr) return '';
|
||||
const d = new Date(dateStr);
|
||||
if (isNaN(d)) return '';
|
||||
const now = new Date(clock.now());
|
||||
const hasTime = _hasTimeComponent(dateStr);
|
||||
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
|
||||
const due = new Date(d.getFullYear(), d.getMonth(), d.getDate());
|
||||
const diffDays = Math.round((due - today) / 86400000);
|
||||
const timeStr = hasTime ? d.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' }) : '';
|
||||
if (hasTime && d < now) return 'overdue';
|
||||
if (!hasTime && diffDays < 0) return 'overdue';
|
||||
if (diffDays === 0) return hasTime ? timeStr : 'today';
|
||||
if (diffDays === 1) return hasTime ? `tmrw ${timeStr}` : 'tomorrow';
|
||||
const dateLabel = d.toLocaleDateString([], { month: 'short', day: 'numeric' });
|
||||
return hasTime ? `${dateLabel} ${timeStr}` : dateLabel;
|
||||
}
|
||||
|
||||
export function _isDueOverdue(dateStr, clock) {
|
||||
if (!dateStr) return false;
|
||||
const d = new Date(dateStr);
|
||||
if (isNaN(d)) return false;
|
||||
if (_hasTimeComponent(dateStr)) return d < new Date(clock.now());
|
||||
return d < new Date(new Date(clock.now()).toDateString());
|
||||
}
|
||||
|
||||
export function _isDueTodayOrOverdue(dateStr, clock) {
|
||||
if (!dateStr) return false;
|
||||
const d = new Date(dateStr);
|
||||
const now = new Date(clock.now());
|
||||
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
|
||||
const due = new Date(d.getFullYear(), d.getMonth(), d.getDate());
|
||||
return due <= today;
|
||||
}
|
||||
|
||||
export function _laterTodayDate(clock) {
|
||||
const now = new Date(clock.now());
|
||||
const eight = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 18, 0); // 6pm today
|
||||
// If less than 1 hour before 6pm, push to "in 3 hours" instead
|
||||
if (eight - now < 60 * 60 * 1000) return new Date(now.getTime() + 3 * 60 * 60 * 1000);
|
||||
return eight;
|
||||
}
|
||||
|
||||
export function _tomorrowDate(clock) {
|
||||
const t = new Date(clock.now());
|
||||
t.setDate(t.getDate() + 1);
|
||||
t.setHours(8, 0, 0, 0);
|
||||
return t;
|
||||
}
|
||||
|
||||
export function _nextWeekDate(clock) {
|
||||
const t = new Date(clock.now());
|
||||
const daysUntilMon = (8 - t.getDay()) % 7 || 7;
|
||||
t.setDate(t.getDate() + daysUntilMon);
|
||||
t.setHours(8, 0, 0, 0);
|
||||
return t;
|
||||
}
|
||||
|
||||
export function _toLocalDatetimeStr(d) {
|
||||
// Format as YYYY-MM-DDTHH:MM (local, no TZ)
|
||||
const pad = n => String(n).padStart(2, '0');
|
||||
return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
||||
}
|
||||
|
||||
export function _formatReminderTag(dateStr, clock) {
|
||||
if (!dateStr) return '';
|
||||
const d = new Date(dateStr);
|
||||
if (isNaN(d)) return '';
|
||||
const now = new Date(clock.now());
|
||||
const sameDay = d.toDateString() === now.toDateString();
|
||||
const tomorrow = new Date(now); tomorrow.setDate(tomorrow.getDate() + 1);
|
||||
const isTomorrow = d.toDateString() === tomorrow.toDateString();
|
||||
const time = d.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' });
|
||||
if (sameDay) return `Today, ${time}`;
|
||||
if (isTomorrow) return `Tomorrow, ${time}`;
|
||||
const dateLabel = d.toLocaleDateString([], { month: 'short', day: 'numeric' });
|
||||
return `${dateLabel}, ${time}`;
|
||||
}
|
||||
|
||||
export function _nthWeekdayLabel(d) {
|
||||
const n = Math.ceil(d.getDate() / 7); // 1..5
|
||||
return `${_ORDINALS[n - 1] || `${n}th`} ${_DAYS[d.getDay()]}`;
|
||||
}
|
||||
|
||||
export function _isLastWeekdayOfMonth(d) {
|
||||
const test = new Date(d);
|
||||
test.setDate(d.getDate() + 7);
|
||||
return test.getMonth() !== d.getMonth();
|
||||
}
|
||||
|
||||
export function _nthWeekdayOfMonth(year, month, weekday, n) {
|
||||
const first = new Date(year, month, 1);
|
||||
const offset = (weekday - first.getDay() + 7) % 7;
|
||||
let day = 1 + offset + (n - 1) * 7;
|
||||
// Last day of month
|
||||
const lastDay = new Date(year, month + 1, 0).getDate();
|
||||
if (day > lastDay) day -= 7;
|
||||
return new Date(year, month, day, 0, 0, 0);
|
||||
}
|
||||
|
||||
export function _lastWeekdayOfMonth(year, month, weekday) {
|
||||
const lastDay = new Date(year, month + 1, 0);
|
||||
const back = (lastDay.getDay() - weekday + 7) % 7;
|
||||
return new Date(year, month, lastDay.getDate() - back, 0, 0, 0);
|
||||
}
|
||||
|
||||
export function _snapToRepeat(currentDate, normRepeat, clock) {
|
||||
const hh = currentDate.getHours();
|
||||
const mm = currentDate.getMinutes();
|
||||
const now = clock.now();
|
||||
const anchor = currentDate.getTime() > now ? currentDate : new Date(clock.now());
|
||||
const parts = normRepeat.split(':');
|
||||
const kind = parts[0];
|
||||
if (kind === 'weekly') {
|
||||
const targetWd = parseInt(parts[1], 10);
|
||||
if (isNaN(targetWd)) return null;
|
||||
const d = new Date(anchor.getFullYear(), anchor.getMonth(), anchor.getDate(), hh, mm, 0, 0);
|
||||
const delta = (targetWd - d.getDay() + 7) % 7;
|
||||
d.setDate(d.getDate() + delta);
|
||||
if (d.getTime() <= now) d.setDate(d.getDate() + 7);
|
||||
return d;
|
||||
}
|
||||
if (kind === 'monthly') {
|
||||
const sub = parts[1];
|
||||
let y = anchor.getFullYear();
|
||||
let m = anchor.getMonth();
|
||||
// Walk forward up to 14 months to find the next matching slot.
|
||||
for (let tries = 0; tries < 14; tries++) {
|
||||
let target;
|
||||
if (sub === 'day') {
|
||||
const wantDay = parseInt(parts[2], 10);
|
||||
if (isNaN(wantDay)) return null;
|
||||
const lastDay = new Date(y, m + 1, 0).getDate();
|
||||
target = new Date(y, m, Math.min(wantDay, lastDay));
|
||||
} else if (sub === 'nth') {
|
||||
const n = parseInt(parts[2], 10);
|
||||
const wd = parseInt(parts[3], 10);
|
||||
if (isNaN(n) || isNaN(wd)) return null;
|
||||
target = _nthWeekdayOfMonth(y, m, wd, n);
|
||||
} else if (sub === 'last') {
|
||||
const wd = parseInt(parts[2], 10);
|
||||
if (isNaN(wd)) return null;
|
||||
target = _lastWeekdayOfMonth(y, m, wd);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
target.setHours(hh, mm, 0, 0);
|
||||
if (target.getTime() > now && target.getTime() >= anchor.getTime()) return target;
|
||||
m++;
|
||||
if (m > 11) { m = 0; y++; }
|
||||
}
|
||||
return null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function _formatRepeatLabel(repeat, originalDate) {
|
||||
if (!repeat || repeat === 'none') return '';
|
||||
const norm = _normalizeRepeat(repeat, originalDate);
|
||||
if (norm === 'daily') return 'Daily';
|
||||
if (norm === 'yearly') return 'Yearly';
|
||||
const parts = norm.split(':');
|
||||
if (parts[0] === 'weekly') {
|
||||
const wd = parseInt(parts[1], 10);
|
||||
if (isNaN(wd)) return 'Weekly';
|
||||
return `Weekly on ${_DAYS[wd]}s`;
|
||||
}
|
||||
if (parts[0] === 'monthly') {
|
||||
if (parts[1] === 'day') return `Monthly on day ${parts[2]}`;
|
||||
if (parts[1] === 'nth') {
|
||||
const n = parseInt(parts[2], 10);
|
||||
const wd = parseInt(parts[3], 10);
|
||||
return `Monthly on ${_ORDINALS[n - 1] || `${n}th`} ${_DAYS[wd]}`;
|
||||
}
|
||||
if (parts[1] === 'last') {
|
||||
const wd = parseInt(parts[2], 10);
|
||||
return `Monthly on last ${_DAYS[wd]}`;
|
||||
}
|
||||
}
|
||||
return norm;
|
||||
}
|
||||
|
||||
export function _normalizeRepeat(repeat, originalDate) {
|
||||
if (!repeat || repeat === 'none') return 'none';
|
||||
if (repeat === 'daily' || repeat === 'yearly') return repeat;
|
||||
if (/^(weekly|monthly):/.test(repeat)) return repeat;
|
||||
// Legacy bare values: derive params from the original date
|
||||
const wd = originalDate.getDay();
|
||||
const n = Math.ceil(originalDate.getDate() / 7);
|
||||
if (repeat === 'weekly') return `weekly:${wd}`;
|
||||
if (repeat === 'monthly') return `monthly:day:${originalDate.getDate()}`;
|
||||
if (repeat === 'monthly_nth_weekday') return `monthly:nth:${n}:${wd}`;
|
||||
if (repeat === 'monthly_last_weekday') return `monthly:last:${wd}`;
|
||||
return repeat;
|
||||
}
|
||||
|
||||
export function _advanceRecurring(dateStr, repeat, clock) {
|
||||
const orig = new Date(dateStr);
|
||||
const hh = orig.getHours();
|
||||
const mm = orig.getMinutes();
|
||||
let d = new Date(orig);
|
||||
const norm = _normalizeRepeat(repeat, orig);
|
||||
if (norm === 'none') return null;
|
||||
|
||||
function step() {
|
||||
if (norm === 'daily') {
|
||||
d.setDate(d.getDate() + 1);
|
||||
return;
|
||||
}
|
||||
if (norm === 'yearly') {
|
||||
d.setFullYear(d.getFullYear() + 1);
|
||||
return;
|
||||
}
|
||||
const parts = norm.split(':');
|
||||
const kind = parts[0];
|
||||
if (kind === 'weekly') {
|
||||
// Snap to the requested weekday in the next 1-7 days
|
||||
const targetWd = parseInt(parts[1], 10);
|
||||
let delta = (targetWd - d.getDay() + 7) % 7;
|
||||
if (delta === 0) delta = 7;
|
||||
d.setDate(d.getDate() + delta);
|
||||
d.setHours(hh, mm, 0, 0);
|
||||
return;
|
||||
}
|
||||
if (kind === 'monthly') {
|
||||
const sub = parts[1];
|
||||
const ny = d.getFullYear() + (d.getMonth() === 11 ? 1 : 0);
|
||||
const nm = (d.getMonth() + 1) % 12;
|
||||
let target;
|
||||
if (sub === 'day') {
|
||||
const wantDay = parseInt(parts[2], 10);
|
||||
const lastDay = new Date(ny, nm + 1, 0).getDate();
|
||||
target = new Date(ny, nm, Math.min(wantDay, lastDay));
|
||||
} else if (sub === 'nth') {
|
||||
const n = parseInt(parts[2], 10);
|
||||
const wd = parseInt(parts[3], 10);
|
||||
target = _nthWeekdayOfMonth(ny, nm, wd, n);
|
||||
} else if (sub === 'last') {
|
||||
const wd = parseInt(parts[2], 10);
|
||||
target = _lastWeekdayOfMonth(ny, nm, wd);
|
||||
} else {
|
||||
d = null; return;
|
||||
}
|
||||
target.setHours(hh, mm, 0, 0);
|
||||
d = target;
|
||||
return;
|
||||
}
|
||||
d = null;
|
||||
}
|
||||
|
||||
step();
|
||||
if (d === null) return null;
|
||||
const now = clock.now();
|
||||
// Cap catch-up to avoid runaway on a malformed/very-old date.
|
||||
let guard = 5000;
|
||||
while (d.getTime() <= now) {
|
||||
if (--guard <= 0) return null;
|
||||
step();
|
||||
if (d === null) return null;
|
||||
}
|
||||
return _toLocalDatetimeStr(d);
|
||||
}
|
||||
@@ -0,0 +1,503 @@
|
||||
/** Notes composition and intentional public API. The legacy entry activates compatibility startup. */
|
||||
import { createSelectionOperations } from './application/selection.js';
|
||||
import { createToolbar } from './ui/toolbar.js';
|
||||
import { createWindowLayout } from './ui/windowLayout.js';
|
||||
import { createCardOperations } from './application/cardOperations.js';
|
||||
import { createChecklistOperations } from './application/checklistOperations.js';
|
||||
import { createNotesSubmission } from './application/submission.js';
|
||||
import { createNotesDrafts } from './application/drafts.js';
|
||||
import { createNotesLifecycle } from './ui/lifecycle.js';
|
||||
import * as noteRules from './domain/noteRules.js';
|
||||
import { createText } from './ui/text.js';
|
||||
import { createColors } from './ui/colors.js';
|
||||
import { createPanel } from './ui/panel.js';
|
||||
import { createReminderDisplay } from './ui/reminderDisplay.js';
|
||||
import { createSelection } from './ui/selection.js';
|
||||
import { createFilters } from './ui/filters.js';
|
||||
import { createCardRendering } from './ui/cardRendering.js';
|
||||
import { createLayout } from './ui/layout.js';
|
||||
import { createQuickAdd } from './ui/quickAdd.js';
|
||||
import { createCardInteractions } from './ui/cardInteractions.js';
|
||||
import { createCardChecklist } from './ui/cardChecklist.js';
|
||||
import { createCardReorder } from './ui/cardReorder.js';
|
||||
import { createDraftEditor } from './ui/draftEditor.js';
|
||||
import { createEditor } from './ui/editor.js';
|
||||
import { createReminderPicker } from './ui/reminderPicker.js';
|
||||
import { createChecklist } from './ui/checklist.js';
|
||||
import { createDrawing } from './ui/drawing.js';
|
||||
import { createClipboard } from './ui/clipboard.js';
|
||||
import { createMobileEditor } from './ui/mobileEditor.js';
|
||||
import { createMobileReorder } from './ui/mobileReorder.js';
|
||||
import { createChecklistReorder } from './ui/checklistReorder.js';
|
||||
import { createQueries } from './application/queries.js';
|
||||
import { createAgentActions } from './application/agentActions.js';
|
||||
import { createDeletion } from './application/deletion.js';
|
||||
import { createNotesReminders } from './application/reminders.js';
|
||||
import { createNotesNotifications } from './infrastructure/notifications.js';
|
||||
import { createNotesState } from './application/state.js';
|
||||
import { createNotesWorkflows } from './application/workflows.js';
|
||||
import { createNotesApi } from './infrastructure/http.js';
|
||||
import { createNotesPersistence, REMINDER_DISMISSED_AT_KEY, NOTES_FIRST_OPEN_HINT_KEY, NOTES_LABELS_COLLAPSED_KEY } from './infrastructure/storage.js';
|
||||
import * as dates from './domain/recurrence.js';
|
||||
import uiModule from '/static/js/ui.js?v=20260916largetoolscroll1';
|
||||
import { spawnConfetti } from '/static/js/shared/ui/confetti.js';
|
||||
import * as Modals from '/static/js/modalManager.js';
|
||||
import { attachColorPicker } from '/static/js/colorPicker.js?v=20260910eyedropper1';
|
||||
import { makeWindowDraggable } from '/static/js/windowDrag.js';
|
||||
import { snapModalToZone } from '/static/js/tileManager.js?v=20260910responsivebounds1';
|
||||
import { applyEdgeDock, clearDockSide } from '/static/js/modalSnap.js';
|
||||
import { topToolWindowZ, topPortalZ } from '/static/js/toolWindowZOrder.js';
|
||||
import { bindMenuDismiss, dismissOrRemove } from '/static/js/escMenuStack.js';
|
||||
import { bindTourHintDismiss } from '/static/js/tourHintDismiss.js';
|
||||
|
||||
const api = createNotesApi({ origin: window.location.origin, request: (...args) => fetch(...args) });
|
||||
const persistence = createNotesPersistence({ storage: typeof localStorage === 'undefined' ? undefined : localStorage });
|
||||
const { _loadPendingHighlights, _loadGlowedReminders, _saveGlowedReminders, _loadActiveHighlights, _saveActiveHighlights, _savePendingHighlights, _loadFiredReminders, _saveFiredReminders, _draftKey, _loadDraft, _clearDraft } = persistence;
|
||||
const clock = { now: () => Date.now() };
|
||||
const app = createNotesState({
|
||||
viewMode: (typeof localStorage !== 'undefined' && localStorage.getItem('odysseus-notes-view')) || 'list',
|
||||
labelsCollapsed: typeof localStorage !== 'undefined' && localStorage.getItem(NOTES_LABELS_COLLAPSED_KEY) === '1',
|
||||
firedDotDismissedAt: (() => { try { const v = parseInt(persistence.getItem(REMINDER_DISMISSED_AT_KEY) || '0', 10); return Number.isFinite(v) && v > 0 ? v : 0; } catch { return 0; } })(),
|
||||
});
|
||||
const state = app.state;
|
||||
const lifecycle = createNotesLifecycle();
|
||||
const scheduler = { setTimeout: (...args) => setTimeout(...args), clearTimeout: id => clearTimeout(id), setInterval: (...args) => setInterval(...args), clearInterval: id => clearInterval(id) };
|
||||
const notifications = createNotesNotifications({ browser: window, notify: window.Notification, openPanel: () => openPanel(), toast: title => uiModule?.showToast?.(title) });
|
||||
const reminders = createNotesReminders({
|
||||
app,
|
||||
api,
|
||||
persistence,
|
||||
notifications,
|
||||
clock,
|
||||
scheduler,
|
||||
fetchNotes: () => _fetchNotes(),
|
||||
isNoteFullyDone: note => _isNoteFullyDone(note),
|
||||
hasItems: note => _hasItems(note),
|
||||
dismissedKey: REMINDER_DISMISSED_AT_KEY,
|
||||
effects: { badge: () => _updateRailBadge(), highlight: id => {
|
||||
_setReminderCardGlow(id, true);
|
||||
const card = document.querySelector(`.note-card[data-note-id="${id}"]`);
|
||||
if (card) { card.classList.add('note-card-reminder-fired'); setTimeout(() => card.classList.remove('note-card-reminder-fired'), 3000); }
|
||||
else _queuePendingHighlight(id);
|
||||
} }
|
||||
});
|
||||
const workflows = createNotesWorkflows({
|
||||
app,
|
||||
api,
|
||||
effects: {
|
||||
render: () => _renderNotes(),
|
||||
showError: (...args) => uiModule.showError(...args),
|
||||
archived: undo => uiModule.showToast('Archived', { duration: 6000, action: 'Undo', actionIcon: _NOTE_UNDO_ICON, onAction: undo, actionHint: 'Ctrl+Z' }),
|
||||
celebrateArchive: (note, card) => { if (_hasItems(note) && !(note.items || []).some(i => !i.done)) { const r = card.getBoundingClientRect(); spawnConfetti(r.left + r.width / 2, r.top + r.height / 2, 80); } },
|
||||
}
|
||||
});
|
||||
const _NOTE_UNDO_ICON = '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:middle;"><polyline points="9 14 4 9 9 4"/><path d="M4 9h11a5 5 0 0 1 5 5v0a5 5 0 0 1-5 5H9"/></svg>';
|
||||
function _pushUndo(entry) { return workflows._pushUndo(entry); }
|
||||
function _popAndRunUndo() { return workflows._popAndRunUndo(); }
|
||||
function _undoArchive(note, prevIdx) { return workflows._undoArchive(note, prevIdx); }
|
||||
function _archiveNoteById(id, options) { return workflows._archiveNoteById(id, options); }
|
||||
function _fetchNotes() { return workflows._fetchNotes(); }
|
||||
|
||||
function _deleteNoteApi(id) { return workflows._deleteNoteApi(id); }
|
||||
function _patchNote(id, patch) { return workflows._patchNote(id, patch); }
|
||||
function _uid() { return Math.random().toString(36).slice(2, 10); }
|
||||
function _formatDueDate(dateStr) { return dates._formatDueDate(dateStr, clock); }
|
||||
function _isDueOverdue(dateStr) { return dates._isDueOverdue(dateStr, clock); }
|
||||
|
||||
function _laterTodayDate() { return dates._laterTodayDate(clock); }
|
||||
function _tomorrowDate() { return dates._tomorrowDate(clock); }
|
||||
function _nextWeekDate() { return dates._nextWeekDate(clock); }
|
||||
function _formatReminderTag(dateStr) { return dates._formatReminderTag(dateStr, clock); }
|
||||
function _snapToRepeat(currentDate, normRepeat) { return dates._snapToRepeat(currentDate, normRepeat, clock); }
|
||||
function _ensureNotificationPermission() { return notifications.ensurePermission(); }
|
||||
|
||||
function _startReminderLoop() { return reminders._startReminderLoop(); }
|
||||
|
||||
function _countFiredReminders() { return reminders._countFiredReminders(); }
|
||||
|
||||
function _hasActiveReminder(...args) { return noteRules._hasActiveReminder(...args, clock); }
|
||||
const _isNoteFullyDone = noteRules._isNoteFullyDone;
|
||||
const _hasItems = noteRules._hasItems;
|
||||
function _isPastReminder(...args) { return noteRules._isPastReminder(...args, clock); }
|
||||
function _esc(...args) { return text._esc(...args); }
|
||||
|
||||
function _safeImgSrc(...args) { return text._safeImgSrc(...args); }
|
||||
function _linkify(...args) { return text._linkify(...args); }
|
||||
function _isBgImage(...args) { return colors._isBgImage(...args); }
|
||||
|
||||
function _dotBg(...args) { return colors._dotBg(...args); }
|
||||
function _dotIsActive(...args) { return colors._dotIsActive(...args); }
|
||||
function _customColorStyle(...args) { return colors._customColorStyle(...args); }
|
||||
function _pickCustomBgImage(...args) { return colors._pickCustomBgImage(...args); }
|
||||
function _wireFormColors(...args) { return colors._wireFormColors(...args); }
|
||||
|
||||
function openPanel(...args) { return panel.openPanel(...args); }
|
||||
|
||||
function _smoothScrollToNoteCard(...args) { return panel._smoothScrollToNoteCard(...args); }
|
||||
function _clearViewedReminderGlows(...args) { return reminderDisplay._clearViewedReminderGlows(...args); }
|
||||
function _setReminderCardGlow(...args) { return reminderDisplay._setReminderCardGlow(...args); }
|
||||
function _queuePendingHighlight(...args) { return reminderDisplay._queuePendingHighlight(...args); }
|
||||
function _flushPendingHighlights(...args) { return reminderDisplay._flushPendingHighlights(...args); }
|
||||
function _updateRailBadge(...args) { return reminderDisplay._updateRailBadge(...args); }
|
||||
function _enterSelectMode(...args) { return selection._enterSelectMode(...args); }
|
||||
function _exitSelectMode(...args) { return selection._exitSelectMode(...args); }
|
||||
function _updateBulkBar(...args) { return selection._updateBulkBar(...args); }
|
||||
|
||||
function _renderLabelsInto(...args) { return filters._renderLabelsInto(...args); }
|
||||
function _renderLoadingSkeleton(...args) { return cardRendering._renderLoadingSkeleton(...args); }
|
||||
function _renderNotes(...args) { return cardRendering._renderNotes(...args); }
|
||||
function _captureCardPositions(...args) { return layout._captureCardPositions(...args); }
|
||||
function _animateReflow(...args) { return layout._animateReflow(...args); }
|
||||
function _applyMasonry(...args) { return layout._applyMasonry(...args); }
|
||||
function _renderQuickAdd(...args) { return quickAdd._renderQuickAdd(...args); }
|
||||
|
||||
function _editNote(...args) { return quickAdd._editNote(...args); }
|
||||
function _bindCardEvents(...args) { return cardInteractions._bindCardEvents(...args); }
|
||||
function _wireCardChecklist(...args) { return cardChecklist._wireCardChecklist(...args); }
|
||||
function _wireTodayView(...args) { return cardChecklist._wireTodayView(...args); }
|
||||
function _wireCardReorder(...args) { return cardReorder._wireCardReorder(...args); }
|
||||
|
||||
function _wireDraftAutosave(...args) { return draftEditor._wireDraftAutosave(...args); }
|
||||
function _commitOpenInPlaceEditor(...args) { return draftEditor._commitOpenInPlaceEditor(...args); }
|
||||
function _applyDraftToNote(...args) { return draftEditor._applyDraftToNote(...args); }
|
||||
function _buildForm(...args) { return editor._buildForm(...args); }
|
||||
function _wireReminderPicker(...args) { return reminderPicker._wireReminderPicker(...args); }
|
||||
function _buildGoalHtml(...args) { return checklist._buildGoalHtml(...args); }
|
||||
function _wireGoalForm(...args) { return checklist._wireGoalForm(...args); }
|
||||
function _buildChecklistHtml(...args) { return checklist._buildChecklistHtml(...args); }
|
||||
function _wireRow(...args) { return checklist._wireRow(...args); }
|
||||
function _wireChecklist(...args) { return checklist._wireChecklist(...args); }
|
||||
function _collectItems(...args) { return checklist._collectItems(...args); }
|
||||
function _buildDrawHtml(...args) { return drawing._buildDrawHtml(...args); }
|
||||
function _wireCanvas(...args) { return drawing._wireCanvas(...args); }
|
||||
function _uploadCanvasAsPng(...args) { return drawing._uploadCanvasAsPng(...args); }
|
||||
function _openNoteCornerMenu(...args) { return clipboard._openNoteCornerMenu(...args); }
|
||||
function _copyNote(...args) { return clipboard._copyNote(...args); }
|
||||
function _isNotesMobileMode(...args) { return mobileEditor._isNotesMobileMode(...args); }
|
||||
function _openMobileFullscreenEdit(...args) { return mobileEditor._openMobileFullscreenEdit(...args); }
|
||||
function _closeMobileFullscreenEdit(...args) { return mobileEditor._closeMobileFullscreenEdit(...args); }
|
||||
|
||||
function _bindLongPressDrag(...args) { return mobileReorder._bindLongPressDrag(...args); }
|
||||
|
||||
function _wireChecklistTouchReorder(...args) { return checklistReorder._wireChecklistTouchReorder(...args); }
|
||||
|
||||
function _sortedVisibleNotes(...args) { return queries._sortedVisibleNotes(...args); }
|
||||
function _userVisibleNotes(...args) { return queries._userVisibleNotes(...args); }
|
||||
function _agentSolveNote(...args) { return agentActions._agentSolveNote(...args); }
|
||||
|
||||
function _clearPastReminders(...args) { return deletion._clearPastReminders(...args); }
|
||||
const text = createText({
|
||||
uiModule
|
||||
});
|
||||
const colors = createColors({
|
||||
api
|
||||
});
|
||||
const { COLORS, COLOR_HEX } = colors;
|
||||
const windowLayout = createWindowLayout({
|
||||
makeWindowDraggable,
|
||||
snapModalToZone,
|
||||
clearDockSide,
|
||||
applyEdgeDock,
|
||||
topToolWindowZ
|
||||
});
|
||||
const toolbar = createToolbar({
|
||||
app,
|
||||
state,
|
||||
persistence,
|
||||
_renderNotes,
|
||||
_fetchNotes,
|
||||
_applyMasonry
|
||||
});
|
||||
const panel = createPanel({
|
||||
wireToolbar: toolbar.wireToolbar,
|
||||
wireSelectionActions: () => selection.wireSelectionActions(),
|
||||
_wireNotesWindow: windowLayout._wireNotesWindow,
|
||||
_restoreNotesSidebarDock: windowLayout._restoreNotesSidebarDock,
|
||||
_bringNotesToFront: windowLayout._bringNotesToFront,
|
||||
disposeUI: () => { layout.dispose(); mobileReorder.dispose(); checklistReorder.dispose(); lifecycle.dispose(); },
|
||||
lifecycle,
|
||||
Modals,
|
||||
NOTES_FIRST_OPEN_HINT_KEY,
|
||||
REMINDER_DISMISSED_AT_KEY,
|
||||
_clearViewedReminderGlows,
|
||||
_closeMobileFullscreenEdit,
|
||||
_commitOpenInPlaceEditor,
|
||||
_copyNote,
|
||||
_enterSelectMode,
|
||||
_exitSelectMode,
|
||||
_fetchNotes,
|
||||
_flushPendingHighlights,
|
||||
_isNotesMobileMode,
|
||||
_popAndRunUndo,
|
||||
_renderLoadingSkeleton,
|
||||
_renderNotes,
|
||||
_startReminderLoop,
|
||||
app,
|
||||
bindTourHintDismiss,
|
||||
dismissOrRemove,
|
||||
persistence,
|
||||
state,
|
||||
workflows
|
||||
});
|
||||
const reminderDisplay = createReminderDisplay({
|
||||
_countFiredReminders,
|
||||
_hasActiveReminder,
|
||||
_loadActiveHighlights,
|
||||
_loadGlowedReminders,
|
||||
_loadPendingHighlights,
|
||||
_saveActiveHighlights,
|
||||
_saveGlowedReminders,
|
||||
_savePendingHighlights,
|
||||
_smoothScrollToNoteCard,
|
||||
state
|
||||
});
|
||||
const selectionOperations = createSelectionOperations({
|
||||
app,
|
||||
api,
|
||||
fetchNotes: _fetchNotes,
|
||||
exitSelection: _exitSelectMode,
|
||||
sendContext: detail => window.dispatchEvent(new CustomEvent('odysseus:notes-context-selected', { detail })),
|
||||
effects: { render: _renderNotes, styledConfirm: uiModule.styledConfirm, showToast: (...args) => uiModule.showToast(...args) }
|
||||
});
|
||||
const selection = createSelection({
|
||||
operations: selectionOperations,
|
||||
_renderNotes,
|
||||
app,
|
||||
state
|
||||
});
|
||||
const filters = createFilters({
|
||||
NOTES_LABELS_COLLAPSED_KEY,
|
||||
_clearPastReminders,
|
||||
_esc,
|
||||
_isPastReminder,
|
||||
_renderNotes,
|
||||
_userVisibleNotes,
|
||||
app,
|
||||
persistence,
|
||||
state
|
||||
});
|
||||
const cardRendering = createCardRendering({
|
||||
COLORS,
|
||||
COLOR_HEX,
|
||||
_animateReflow,
|
||||
_applyMasonry,
|
||||
_bindCardEvents,
|
||||
_captureCardPositions,
|
||||
_customColorStyle,
|
||||
_dotBg,
|
||||
_dotIsActive,
|
||||
_esc,
|
||||
_formatDueDate,
|
||||
_formatReminderTag,
|
||||
_hasActiveReminder,
|
||||
_isBgImage,
|
||||
_isDueOverdue,
|
||||
_isNotesMobileMode,
|
||||
_linkify,
|
||||
_loadActiveHighlights,
|
||||
_renderLabelsInto,
|
||||
_renderQuickAdd,
|
||||
_safeImgSrc,
|
||||
_sortedVisibleNotes,
|
||||
_updateRailBadge,
|
||||
_wireTodayView,
|
||||
state,
|
||||
uiModule
|
||||
});
|
||||
const layout = createLayout({
|
||||
isOpen: () => state.open
|
||||
});
|
||||
const quickAdd = createQuickAdd({
|
||||
_applyDraftToNote,
|
||||
_applyMasonry,
|
||||
_buildForm,
|
||||
app,
|
||||
openPanel,
|
||||
state,
|
||||
uiModule
|
||||
});
|
||||
const cardOperations = createCardOperations({
|
||||
app,
|
||||
api,
|
||||
pushUndo: _pushUndo,
|
||||
undoArchive: _undoArchive,
|
||||
effects: { render: _renderNotes, showError: (...args) => uiModule.showError(...args), showToast: (...args) => uiModule.showToast(...args), archived: undo => uiModule.showToast('Archived', { duration: 6000, action: 'Undo', actionIcon: _NOTE_UNDO_ICON, onAction: undo, actionHint: 'Ctrl+Z' }) }
|
||||
});
|
||||
const checklistOperations = createChecklistOperations({
|
||||
app,
|
||||
api,
|
||||
uid: _uid,
|
||||
effects: { render: _renderNotes, showError: (...args) => uiModule.showError(...args) }
|
||||
});
|
||||
const cardInteractions = createCardInteractions({
|
||||
cardOperations,
|
||||
COLORS,
|
||||
_archiveNoteById,
|
||||
_bindLongPressDrag,
|
||||
_customColorStyle,
|
||||
_dotBg,
|
||||
_dotIsActive,
|
||||
_editNote,
|
||||
_isBgImage,
|
||||
_isNotesMobileMode,
|
||||
_openMobileFullscreenEdit,
|
||||
_openNoteCornerMenu,
|
||||
_pickCustomBgImage,
|
||||
_renderNotes,
|
||||
_setReminderCardGlow,
|
||||
_smoothScrollToNoteCard,
|
||||
_updateBulkBar,
|
||||
_wireCardChecklist,
|
||||
_wireCardReorder,
|
||||
app,
|
||||
spawnConfetti,
|
||||
state,
|
||||
uiModule
|
||||
});
|
||||
const cardChecklist = createCardChecklist({
|
||||
checklistOperations,
|
||||
_editNote,
|
||||
_renderNotes,
|
||||
app,
|
||||
spawnConfetti,
|
||||
state
|
||||
});
|
||||
const cardReorder = createCardReorder({
|
||||
persistOrder: cardOperations.persistOrder,
|
||||
lifecycle,
|
||||
_isNotesMobileMode,
|
||||
state
|
||||
});
|
||||
const draftEditor = createDraftEditor({
|
||||
bindDraft: (...args) => drafts.bindDraft(...args),
|
||||
_collectItems,
|
||||
_loadDraft
|
||||
});
|
||||
const editor = createEditor({
|
||||
deleteFromEditor: id => deletion.deleteFromEditor(id),
|
||||
submitNote: (...args) => submission.submitNote(...args),
|
||||
COLORS,
|
||||
_applyMasonry,
|
||||
_archiveNoteById,
|
||||
_buildChecklistHtml,
|
||||
_buildDrawHtml,
|
||||
_buildGoalHtml,
|
||||
_collectItems,
|
||||
_customColorStyle,
|
||||
_dotBg,
|
||||
_dotIsActive,
|
||||
_esc,
|
||||
_isBgImage,
|
||||
_renderNotes,
|
||||
_safeImgSrc,
|
||||
_uid,
|
||||
_uploadCanvasAsPng,
|
||||
_wireCanvas,
|
||||
_wireChecklist,
|
||||
_wireDraftAutosave,
|
||||
_wireFormColors,
|
||||
_wireGoalForm,
|
||||
_wireReminderPicker,
|
||||
api,
|
||||
app,
|
||||
state,
|
||||
uiModule
|
||||
});
|
||||
const reminderPicker = createReminderPicker({
|
||||
lifecycle,
|
||||
_ensureNotificationPermission,
|
||||
_esc,
|
||||
_formatReminderTag,
|
||||
_laterTodayDate,
|
||||
_nextWeekDate,
|
||||
_snapToRepeat,
|
||||
_tomorrowDate,
|
||||
bindMenuDismiss,
|
||||
dismissOrRemove
|
||||
});
|
||||
const checklist = createChecklist({
|
||||
_esc,
|
||||
_uid,
|
||||
spawnConfetti
|
||||
});
|
||||
const drawing = createDrawing({
|
||||
lifecycle,
|
||||
_safeImgSrc,
|
||||
api,
|
||||
attachColorPicker
|
||||
});
|
||||
const clipboard = createClipboard({
|
||||
_agentSolveNote,
|
||||
bindMenuDismiss,
|
||||
dismissOrRemove,
|
||||
state,
|
||||
topPortalZ,
|
||||
uiModule
|
||||
});
|
||||
const mobileEditor = createMobileEditor({
|
||||
_applyDraftToNote,
|
||||
_buildForm,
|
||||
_fetchNotes,
|
||||
_linkify,
|
||||
_renderNotes,
|
||||
_uid,
|
||||
_wireChecklistTouchReorder,
|
||||
_wireRow,
|
||||
app,
|
||||
state,
|
||||
uiModule
|
||||
});
|
||||
const mobileReorder = createMobileReorder({
|
||||
commitMobileOrder: cardOperations.commitMobileOrder,
|
||||
lifecycle,
|
||||
_applyMasonry,
|
||||
_enterSelectMode,
|
||||
app
|
||||
});
|
||||
const checklistReorder = createChecklistReorder({
|
||||
lifecycle
|
||||
});
|
||||
const queries = createQueries({
|
||||
_hasActiveReminder,
|
||||
state
|
||||
});
|
||||
const agentActions = createAgentActions({
|
||||
_patchNote,
|
||||
_renderNotes,
|
||||
api,
|
||||
app,
|
||||
createFormData: () => new FormData(),
|
||||
state,
|
||||
streamComplete: sid => { try { window.sessionModule?.markStreamComplete?.(sid); } catch {} },
|
||||
uiModule
|
||||
});
|
||||
const deletion = createDeletion({
|
||||
app,
|
||||
_deleteNoteApi,
|
||||
_fetchNotes,
|
||||
_isPastReminder,
|
||||
_renderNotes,
|
||||
effects: { styledConfirm: uiModule.styledConfirm, confirm: message => confirm(message), showToast: (...args) => uiModule.showToast(...args), showError: (...args) => uiModule.showError(...args) },
|
||||
state
|
||||
});
|
||||
const notesModule = { openPanel: panel.openPanel, closePanel: panel.closePanel, togglePanel: panel.togglePanel, isPanelOpen: panel.isPanelOpen, openNote: panel.openNote, newNote: quickAdd.newNote, openNotes: panel.openPanel, closeNotes: panel.closePanel, isNotesOpen: panel.isPanelOpen, refreshDueBadge: reminders.refreshDueBadge };
|
||||
const publicOpenPanel = panel.openPanel, publicClosePanel = panel.closePanel, publicTogglePanel = panel.togglePanel, publicIsPanelOpen = panel.isPanelOpen, publicOpenNote = panel.openNote, publicNewNote = quickAdd.newNote, publicRefreshDueBadge = reminders.refreshDueBadge, publicDismissFiredReminderDot = reminders.dismissFiredReminderDot;
|
||||
export { publicOpenPanel as openPanel, publicClosePanel as closePanel, publicTogglePanel as togglePanel, publicIsPanelOpen as isPanelOpen, publicOpenNote as openNote, publicNewNote as newNote, publicRefreshDueBadge as refreshDueBadge, publicDismissFiredReminderDot as dismissFiredReminderDot, publicOpenPanel as openNotes, publicClosePanel as closeNotes, publicIsPanelOpen as isNotesOpen };
|
||||
export function startNotesBackground() { reminders.start(); }
|
||||
export default notesModule;
|
||||
const submission = createNotesSubmission({
|
||||
app,
|
||||
api,
|
||||
persistence,
|
||||
clock,
|
||||
uid: _uid,
|
||||
fetchNotes: _fetchNotes,
|
||||
effects: { render: _renderNotes, showError: (...args) => uiModule.showError(...args), clearGlow: id => _setReminderCardGlow(id, false) }
|
||||
});
|
||||
const drafts = createNotesDrafts({
|
||||
app,
|
||||
api,
|
||||
persistence,
|
||||
scheduler,
|
||||
effects: { showError: (...args) => uiModule.showError(...args) }
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
/** Notes HTTP port. Response interpretation stays with the owning workflow. */
|
||||
export function createNotesApi({ origin, request }) {
|
||||
const json = (method, body) => ({ method, credentials: 'same-origin', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
|
||||
async function saveNote(note) {
|
||||
const response = await request(note.id ? `${origin}/api/notes/${note.id}` : `${origin}/api/notes`, json(note.id ? 'PUT' : 'POST', note));
|
||||
if (!response.ok) throw new Error('Failed to save note');
|
||||
return await response.json();
|
||||
}
|
||||
async function patchNote(id, patch) {
|
||||
const response = await request(`${origin}/api/notes/${id}`, json('PUT', patch));
|
||||
if (!response.ok) throw new Error('Failed to update note');
|
||||
return await response.json();
|
||||
}
|
||||
async function deleteNote(id) {
|
||||
const response = await request(`${origin}/api/notes/${id}`, { method: 'DELETE', credentials: 'same-origin' });
|
||||
if (!response.ok) throw new Error('HTTP ' + response.status);
|
||||
}
|
||||
return {
|
||||
saveNote, patchNote, deleteNote,
|
||||
listNotes: archived => request(`${origin}/api/notes${archived ? '?archived=true' : ''}`, { credentials: 'same-origin' }),
|
||||
reorder: ids => request(`${origin}/api/notes/reorder`, json('POST', { ids })),
|
||||
upload: body => request(`${origin}/api/upload`, { method: 'POST', body, credentials: 'same-origin' }),
|
||||
uploadUrl: id => `${origin}/api/upload/${id}`,
|
||||
fireReminder: body => request('/api/notes/fire-reminder', json('POST', body)),
|
||||
defaultChat: () => request(`${origin}/api/default-chat`, { credentials: 'same-origin' }),
|
||||
createSession: body => request(`${origin}/api/session`, { method: 'POST', body, credentials: 'same-origin' }),
|
||||
startChat: body => request(`${origin}/api/chat_stream`, { method: 'POST', body, credentials: 'same-origin' }),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
/** Browser notification permission/display port, independent of Notes rendering. */
|
||||
export function createNotesNotifications({ browser, notify, openPanel, toast }) {
|
||||
async function ensurePermission() {
|
||||
if (!('Notification' in browser)) return false;
|
||||
if (notify.permission === 'granted') return true;
|
||||
if (notify.permission === 'denied') return false;
|
||||
try { return await notify.requestPermission() === 'granted'; }
|
||||
catch { return false; }
|
||||
}
|
||||
function show(title, body, noteId) {
|
||||
if ('Notification' in browser && notify.permission === 'granted') {
|
||||
try {
|
||||
const notification = new notify(title, { body, tag: 'note-' + noteId, icon: '/static/favicon.ico' });
|
||||
notification.onclick = () => { browser.focus(); openPanel(); notification.close(); };
|
||||
} catch {}
|
||||
}
|
||||
toast(title);
|
||||
}
|
||||
return { ensurePermission, show };
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
/** Browser persistence and unchanged Notes key/serialization contracts. */
|
||||
export const REMINDER_FIRED_KEY = 'odysseus-notes-reminder-fired';
|
||||
export const REMINDER_GLOWED_KEY = 'odysseus-notes-reminder-glowed';
|
||||
export const REMINDER_PENDING_HIGHLIGHT_KEY = 'odysseus-notes-reminder-pending-highlight';
|
||||
export const REMINDER_ACTIVE_HIGHLIGHT_KEY = 'odysseus-notes-reminder-active-highlight';
|
||||
export const REMINDER_DISMISSED_AT_KEY = 'odysseus-notes-reminder-dismissed-at';
|
||||
export const NOTES_FIRST_OPEN_HINT_KEY = 'odysseus-notes-first-open-hint-v1';
|
||||
export const NOTES_LABELS_COLLAPSED_KEY = 'odysseus-notes-labels-collapsed';
|
||||
export const _DRAFT_PREFIX = 'odysseus-note-draft-';
|
||||
|
||||
export function createNotesPersistence({ storage: localStorage }) {
|
||||
function _loadPendingHighlights() {
|
||||
try { return new Set(JSON.parse(localStorage.getItem(REMINDER_PENDING_HIGHLIGHT_KEY) || '[]')); }
|
||||
catch { return new Set(); }
|
||||
}
|
||||
|
||||
function _loadGlowedReminders() {
|
||||
try { return new Set(JSON.parse(localStorage.getItem(REMINDER_GLOWED_KEY) || '[]')); }
|
||||
catch { return new Set(); }
|
||||
}
|
||||
|
||||
function _saveGlowedReminders(set) {
|
||||
try { localStorage.setItem(REMINDER_GLOWED_KEY, JSON.stringify([...set])); } catch {}
|
||||
}
|
||||
|
||||
function _loadActiveHighlights() {
|
||||
try { return new Set(JSON.parse(localStorage.getItem(REMINDER_ACTIVE_HIGHLIGHT_KEY) || '[]')); }
|
||||
catch { return new Set(); }
|
||||
}
|
||||
|
||||
function _saveActiveHighlights(set) {
|
||||
try { localStorage.setItem(REMINDER_ACTIVE_HIGHLIGHT_KEY, JSON.stringify([...set])); } catch {}
|
||||
}
|
||||
|
||||
function _savePendingHighlights(set) {
|
||||
try { localStorage.setItem(REMINDER_PENDING_HIGHLIGHT_KEY, JSON.stringify([...set])); }
|
||||
catch {}
|
||||
}
|
||||
|
||||
function _loadFiredReminders() {
|
||||
try { return new Set(JSON.parse(localStorage.getItem(REMINDER_FIRED_KEY) || '[]')); }
|
||||
catch { return new Set(); }
|
||||
}
|
||||
|
||||
function _saveFiredReminders(set) {
|
||||
try { localStorage.setItem(REMINDER_FIRED_KEY, JSON.stringify([...set])); }
|
||||
catch {}
|
||||
}
|
||||
|
||||
function _draftKey(id) { return _DRAFT_PREFIX + (id || '__new__'); }
|
||||
|
||||
function _loadDraft(id) {
|
||||
try { return JSON.parse(localStorage.getItem(_draftKey(id)) || 'null'); } catch { return null; }
|
||||
}
|
||||
|
||||
function _clearDraft(id) { try { localStorage.removeItem(_draftKey(id)); } catch {} }
|
||||
|
||||
return { _loadPendingHighlights, _loadGlowedReminders, _saveGlowedReminders, _loadActiveHighlights, _saveActiveHighlights, _savePendingHighlights, _loadFiredReminders, _saveFiredReminders, _draftKey, _loadDraft, _clearDraft,
|
||||
getItem: key => localStorage.getItem(key),
|
||||
setItem: (key, value) => localStorage.setItem(key, value),
|
||||
removeItem: key => localStorage.removeItem(key),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
/** Card checklist editing and Today-step interactions. */
|
||||
export function createCardChecklist({
|
||||
checklistOperations,
|
||||
_editNote,
|
||||
_renderNotes,
|
||||
app,
|
||||
spawnConfetti,
|
||||
state
|
||||
}) {
|
||||
function _wireCardChecklist(body) {
|
||||
// Remove a single checklist item (hover X)
|
||||
body.querySelectorAll('.note-checkbox-rm').forEach(btn => {
|
||||
btn.addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
if (state.selectMode) return;
|
||||
const noteId = btn.dataset.noteId;
|
||||
const idx = parseInt(btn.dataset.idx);
|
||||
checklistOperations.removeItem(noteId, idx);
|
||||
});
|
||||
});
|
||||
|
||||
function _startChecklistItemEdit(noteId, idx, span) {
|
||||
if (span.isContentEditable) return;
|
||||
const note = state.notes.find(n => n.id === noteId);
|
||||
if (!note || !Array.isArray(note.items) || !note.items[idx]) return;
|
||||
|
||||
span.textContent = note.items[idx].text || '';
|
||||
span.contentEditable = "true";
|
||||
span.spellcheck = false;
|
||||
span.focus();
|
||||
|
||||
const selection = window.getSelection();
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(span);
|
||||
selection.removeAllRanges();
|
||||
selection.addRange(range);
|
||||
|
||||
const save = () => {
|
||||
if (!span.isContentEditable) return;
|
||||
span.contentEditable = "false";
|
||||
const newText = span.textContent.trim();
|
||||
checklistOperations.editItem(note, idx, newText);
|
||||
};
|
||||
|
||||
const onKeydown = (e) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
save();
|
||||
} else if (e.key === 'Escape') {
|
||||
e.preventDefault();
|
||||
span.contentEditable = "false";
|
||||
_renderNotes();
|
||||
}
|
||||
};
|
||||
|
||||
span.addEventListener('blur', save, { once: true });
|
||||
span.addEventListener('keydown', onKeydown);
|
||||
}
|
||||
|
||||
// Edit a single checklist item (hover Edit button)
|
||||
body.querySelectorAll('.note-checkbox-edit').forEach(btn => {
|
||||
btn.addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
if (state.selectMode) return;
|
||||
const noteId = btn.dataset.noteId;
|
||||
const idx = parseInt(btn.dataset.idx);
|
||||
const span = btn.parentElement.querySelector('.note-check-text');
|
||||
if (span) _startChecklistItemEdit(noteId, idx, span);
|
||||
});
|
||||
});
|
||||
|
||||
// Prevent clicks from toggling the row while actively editing inline
|
||||
body.querySelectorAll('.note-check-text').forEach(span => {
|
||||
span.addEventListener('click', (e) => {
|
||||
if (span.isContentEditable) {
|
||||
e.stopPropagation();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Quick-add new checklist item (hover input at bottom of todo cards)
|
||||
body.querySelectorAll('.note-cl-quickadd-input').forEach(input => {
|
||||
input.addEventListener('click', (e) => e.stopPropagation());
|
||||
input.addEventListener('keydown', async (e) => {
|
||||
e.stopPropagation();
|
||||
if (e.key !== 'Enter') return;
|
||||
e.preventDefault();
|
||||
const text = input.value.trim();
|
||||
if (!text) return;
|
||||
const noteId = input.dataset.noteId;
|
||||
const persist = checklistOperations.addItem(noteId, text, () => { input.value = ''; });
|
||||
if (!persist) return;
|
||||
// Refocus the input on the same card
|
||||
setTimeout(() => {
|
||||
const next = document.querySelector(`.note-cl-quickadd-input[data-note-id="${noteId}"]`);
|
||||
if (next) next.focus();
|
||||
}, 0);
|
||||
persist();
|
||||
});
|
||||
});
|
||||
|
||||
// Checkboxes (dot toggle, optimistic) : disabled in select mode
|
||||
body.querySelectorAll('.note-checkbox').forEach(el => {
|
||||
el.addEventListener('click', (e) => {
|
||||
if (state.selectMode) return; // let card-level handler take over
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
const noteId = el.dataset.noteId;
|
||||
const idx = parseInt(el.dataset.idx);
|
||||
checklistOperations.toggleItem(noteId, idx, done => el.classList.toggle('done', done), () => {
|
||||
const card = el.closest('.note-card');
|
||||
if (card) { const r = card.getBoundingClientRect(); spawnConfetti(r.left + r.width / 2, r.top + r.height / 2, 60); }
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
}
|
||||
|
||||
function _wireTodayView(body) {
|
||||
body.querySelectorAll('.notes-today-row .note-check-dot').forEach(dot => {
|
||||
dot.addEventListener('click', async (e) => {
|
||||
e.stopPropagation();
|
||||
const id = dot.dataset.noteId;
|
||||
const idx = parseInt(dot.dataset.idx);
|
||||
const row = dot.closest('.notes-today-row');
|
||||
await checklistOperations.toggleTodayStep(id, idx, () => row?.classList.add('done'), () => {
|
||||
const r = (row || dot).getBoundingClientRect();
|
||||
spawnConfetti(r.left + r.width / 2, r.top + r.height / 2, 60);
|
||||
});
|
||||
});
|
||||
});
|
||||
body.querySelectorAll('.notes-today-title').forEach(el => {
|
||||
el.addEventListener('click', () => {
|
||||
const id = el.dataset.noteId;
|
||||
if (!id) return;
|
||||
// Drop the Today filter first so the regular card list is rendered;
|
||||
// _editNote needs to find a .note-card in the DOM to replace with
|
||||
// the editor form.
|
||||
app.setActiveFilter(null);
|
||||
_renderNotes();
|
||||
_editNote(id);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
return { _wireCardChecklist, _wireTodayView };
|
||||
}
|
||||
@@ -0,0 +1,337 @@
|
||||
/** Card taps, pin/color controls, menus and archive animation. */
|
||||
export function createCardInteractions({
|
||||
cardOperations,
|
||||
COLORS,
|
||||
_archiveNoteById,
|
||||
_bindLongPressDrag,
|
||||
_customColorStyle,
|
||||
_dotBg,
|
||||
_dotIsActive,
|
||||
_editNote,
|
||||
_isBgImage,
|
||||
_isNotesMobileMode,
|
||||
_openMobileFullscreenEdit,
|
||||
_openNoteCornerMenu,
|
||||
_pickCustomBgImage,
|
||||
_renderNotes,
|
||||
_setReminderCardGlow,
|
||||
_smoothScrollToNoteCard,
|
||||
_updateBulkBar,
|
||||
_wireCardChecklist,
|
||||
_wireCardReorder,
|
||||
app,
|
||||
spawnConfetti,
|
||||
state,
|
||||
uiModule
|
||||
}) {
|
||||
function _bindCardEvents(body) {
|
||||
// Skip completed leading rows so the first unfinished checklist item is
|
||||
// visible when a note preview has its own scroll area.
|
||||
requestAnimationFrame(() => {
|
||||
body.querySelectorAll('.note-checklist-preview').forEach(preview => {
|
||||
const firstPending = preview.querySelector('.note-checkbox:not(.done)');
|
||||
if (firstPending) preview.scrollTop = Math.max(0, firstPending.offsetTop - 4);
|
||||
});
|
||||
});
|
||||
const tapToEditOrSelect = (cardEl) => {
|
||||
const id = cardEl.dataset.noteId;
|
||||
// A long-press enters select mode and re-renders the card. Ignore the
|
||||
// synthetic click that mobile browsers emit when that same touch ends.
|
||||
if (state.suppressNextNoteTapId === id) {
|
||||
app.setSuppressNextNoteTapId(null);
|
||||
return;
|
||||
}
|
||||
if (state.selectMode) {
|
||||
const cb = cardEl.querySelector('.note-card-cb');
|
||||
if (cb) {
|
||||
cb.checked = !cb.checked;
|
||||
cb.dispatchEvent(new Event('change'));
|
||||
}
|
||||
} else if (_isNotesMobileMode()) {
|
||||
// Mobile: open the per-note fullscreen edit overlay instead of the
|
||||
// in-place form. Tiles on mobile are read-only previews.
|
||||
_openMobileFullscreenEdit(id, cardEl);
|
||||
} else {
|
||||
_editNote(id);
|
||||
}
|
||||
};
|
||||
// Mobile: long-press anywhere on a note card → enter Select mode and
|
||||
// select that card. Cancelled by movement (so it doesn't interfere with
|
||||
// vertical scrolling) or by lifting the finger before the timer fires.
|
||||
if (_isNotesMobileMode()) {
|
||||
body.querySelectorAll('.note-card').forEach(card => _bindLongPressDrag(card));
|
||||
}
|
||||
body.querySelectorAll('.note-card.note-card-reminder-fired-sticky').forEach(card => {
|
||||
card.addEventListener('click', () => _setReminderCardGlow(card.dataset.noteId, false), true);
|
||||
});
|
||||
// Click title : edit, or toggle select in select mode
|
||||
body.querySelectorAll('.note-card-title[data-action="edit"]').forEach(el => {
|
||||
el.addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
_smoothScrollToNoteCard(el.closest('.note-card'));
|
||||
tapToEditOrSelect(el.closest('.note-card'));
|
||||
});
|
||||
});
|
||||
// Click content : edit, or toggle select in select mode
|
||||
body.querySelectorAll('.note-content-preview').forEach(el => {
|
||||
el.addEventListener('click', (e) => { e.stopPropagation(); tapToEditOrSelect(el.closest('.note-card')); });
|
||||
});
|
||||
// A saved drawing is the note's primary content. Open its editor directly
|
||||
// when the preview is clicked, matching title/content preview behavior.
|
||||
body.querySelectorAll('.note-card-drawing .note-card-image').forEach(el => {
|
||||
el.addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
tapToEditOrSelect(el.closest('.note-card'));
|
||||
});
|
||||
});
|
||||
// Click empty area of checklist preview (not on checkbox/X) : edit
|
||||
body.querySelectorAll('.note-checklist-preview').forEach(el => {
|
||||
el.addEventListener('wheel', (e) => {
|
||||
const atTop = el.scrollTop <= 0;
|
||||
const atBottom = el.scrollTop + el.clientHeight >= el.scrollHeight - 1;
|
||||
if ((e.deltaY < 0 && atTop) || (e.deltaY > 0 && atBottom)) {
|
||||
const pane = el.closest('.notes-pane-body');
|
||||
if (pane) {
|
||||
pane.scrollTop += e.deltaY;
|
||||
e.preventDefault();
|
||||
}
|
||||
}
|
||||
}, { passive: false });
|
||||
el.addEventListener('click', (e) => {
|
||||
if (e.target.closest('.note-checkbox, .note-checkbox-rm, .note-cl-quickadd, input')) return;
|
||||
e.stopPropagation();
|
||||
tapToEditOrSelect(el.closest('.note-card'));
|
||||
});
|
||||
});
|
||||
// Clicking todo item text now toggles its checkbox : let the click bubble
|
||||
// up to the parent .note-checkbox row handler. To open the editor, the
|
||||
// user clicks the pencil corner.
|
||||
// (No-op block kept as a marker : removing the listener entirely means
|
||||
// clicks naturally bubble to the row toggle below.)
|
||||
// In select mode, clicking anywhere on the card toggles selection
|
||||
if (state.selectMode) {
|
||||
body.querySelectorAll('.note-card').forEach(card => {
|
||||
card.addEventListener('click', (e) => {
|
||||
if (e.target.closest('.note-card-cb')) return; // checkbox handles itself
|
||||
e.stopPropagation();
|
||||
tapToEditOrSelect(card);
|
||||
});
|
||||
});
|
||||
}
|
||||
// Mobile, non-select: tapping anywhere on the card body (not on an
|
||||
// interactive child : buttons, pin, checkbox, color dot, reminder pill,
|
||||
// agent tag, links) opens the fullscreen editor. Previously only the
|
||||
// title / content preview triggered edit, so padding + empty gutters were
|
||||
// dead zones that felt broken on mobile.
|
||||
if (_isNotesMobileMode() && !state.selectMode) {
|
||||
const _INTERACTIVE = 'button, a, input, label, .note-card-color-dot, .note-checkbox, .note-checkbox-rm, .note-cl-quickadd, .note-agent-tag, .note-card-pin, .note-card-corner-trash, .note-card-corner-menu, .note-card-corner-unarchive, .note-card-edit-corner, .note-card-reminder, .note-card-cb';
|
||||
body.querySelectorAll('.note-card').forEach(card => {
|
||||
card.addEventListener('click', (e) => {
|
||||
if (e.target.closest(_INTERACTIVE)) return;
|
||||
e.stopPropagation();
|
||||
tapToEditOrSelect(card);
|
||||
});
|
||||
});
|
||||
}
|
||||
// Multi-select checkbox (only in select mode)
|
||||
body.querySelectorAll('.note-card-cb').forEach(cb => {
|
||||
cb.addEventListener('click', (e) => e.stopPropagation());
|
||||
cb.addEventListener('change', () => {
|
||||
const id = cb.dataset.noteId;
|
||||
if (cb.checked) app.selectId(id);
|
||||
else app.deselectId(id);
|
||||
cb.closest('.note-card').classList.toggle('note-card-selected', cb.checked);
|
||||
_updateBulkBar();
|
||||
});
|
||||
});
|
||||
// Pin toggle (optimistic)
|
||||
body.querySelectorAll('.note-card-pin').forEach(btn => {
|
||||
btn.addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
const id = btn.dataset.noteId;
|
||||
cardOperations.togglePin(id);
|
||||
});
|
||||
});
|
||||
// Color picker
|
||||
const _applyCardColor = async (card, id, newColor) => {
|
||||
const isBg = _isBgImage(newColor);
|
||||
COLORS.forEach(c => { if (c.value && c.value !== 'custom') card.classList.remove('note-color-' + c.value); });
|
||||
if (newColor && !isBg) card.classList.add('note-color-' + newColor);
|
||||
if (isBg) card.setAttribute('style', _customColorStyle(newColor));
|
||||
else card.removeAttribute('style');
|
||||
card.querySelectorAll('.note-card-color-dot').forEach(d => {
|
||||
d.classList.toggle('active', _dotIsActive(d.dataset.color, newColor));
|
||||
d.style.background = _dotBg(d.dataset.color, newColor);
|
||||
});
|
||||
await cardOperations.updateColor(id, newColor);
|
||||
};
|
||||
body.querySelectorAll('.note-card-color-dot').forEach(dot => {
|
||||
dot.addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
const card = dot.closest('.note-card');
|
||||
const id = card.dataset.noteId;
|
||||
if (dot.dataset.color === 'custom') {
|
||||
_pickCustomBgImage().then(url => { if (url) _applyCardColor(card, id, 'bg:' + url); });
|
||||
return;
|
||||
}
|
||||
_applyCardColor(card, id, dot.dataset.color);
|
||||
});
|
||||
});
|
||||
// Plain pencil corner → open editor. The unarchive corner shares the
|
||||
// .note-card-edit-corner class for styling, so :not() keeps the edit
|
||||
// handler off it.
|
||||
body.querySelectorAll('.note-card-edit-corner:not(.note-card-unarchive-corner)').forEach(btn => {
|
||||
btn.addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
const id = btn.dataset.noteId;
|
||||
if (id) _editNote(id);
|
||||
});
|
||||
});
|
||||
// Copy corner : bottom-right, just left of the Done check. Shared with
|
||||
// the Ctrl/Cmd+C shortcut wired further down so both code paths run the
|
||||
// same serializer + feedback flash.
|
||||
// ⋯ corner menu : Copy + Agent (solve-this-todo).
|
||||
body.querySelectorAll('.note-card-corner-menu').forEach(btn => {
|
||||
btn.addEventListener('click', (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
_openNoteCornerMenu(btn);
|
||||
});
|
||||
});
|
||||
body.querySelectorAll('.note-card-label-chip').forEach(chip => {
|
||||
chip.addEventListener('click', (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
const label = chip.dataset.noteLabelFilter;
|
||||
if (!label) return;
|
||||
if (state.activeLabel === label && state.activeFilter === null) {
|
||||
app.setActiveLabel(null);
|
||||
} else {
|
||||
app.setActiveFilter(null);
|
||||
app.setActiveLabel(label);
|
||||
}
|
||||
_renderNotes();
|
||||
});
|
||||
});
|
||||
// Done (✓) at bottom-right : only visible on hover for active notes.
|
||||
body.querySelectorAll('.note-card-done').forEach(btn => {
|
||||
btn.addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
const id = btn.dataset.noteId;
|
||||
const card = btn.closest('.note-card');
|
||||
const idx = state.notes.findIndex(n => n.id === id);
|
||||
if (idx < 0) return;
|
||||
// Celebrate completion : same confetti shower the bulk-archive uses.
|
||||
if (card) {
|
||||
const r = card.getBoundingClientRect();
|
||||
spawnConfetti(r.left + r.width / 2, r.top + r.height / 2, 80);
|
||||
}
|
||||
const finish = cardOperations.stageArchive(id);
|
||||
if (!finish) return;
|
||||
if (card) {
|
||||
card.classList.add('note-card-sliding-out');
|
||||
let done = false;
|
||||
const once = () => { if (done) return; done = true; finish(); };
|
||||
card.addEventListener('transitionend', once, { once: true });
|
||||
setTimeout(once, 400);
|
||||
} else {
|
||||
finish();
|
||||
}
|
||||
});
|
||||
});
|
||||
// Unarchive corner : only visible in archive view.
|
||||
body.querySelectorAll('.note-card-corner-unarchive').forEach(btn => {
|
||||
btn.addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
const id = btn.dataset.noteId;
|
||||
cardOperations.unarchive(id);
|
||||
});
|
||||
});
|
||||
// Trash corner : archive view only. Permanent delete, no confirmation.
|
||||
body.querySelectorAll('.note-card-corner-trash').forEach(btn => {
|
||||
btn.addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
const id = btn.dataset.noteId;
|
||||
cardOperations.deleteOptimistically(id, true);
|
||||
});
|
||||
});
|
||||
|
||||
body.querySelectorAll('.note-card-archive').forEach(btn => {
|
||||
btn.addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
const id = btn.dataset.noteId;
|
||||
if (!id) return;
|
||||
const card = btn.closest('.note-card');
|
||||
let done = false;
|
||||
const finishRemove = () => {
|
||||
if (done) return;
|
||||
done = true;
|
||||
_archiveNoteById(id, { card, celebrate: true });
|
||||
};
|
||||
if (card) {
|
||||
card.classList.add('note-card-sliding-out');
|
||||
card.addEventListener('transitionend', finishRemove, { once: true });
|
||||
setTimeout(finishRemove, 400);
|
||||
} else {
|
||||
finishRemove();
|
||||
}
|
||||
});
|
||||
});
|
||||
// Unarchive (optimistic) : only present in archive view
|
||||
body.querySelectorAll('.note-card-unarchive').forEach(btn => {
|
||||
btn.addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
const id = btn.dataset.noteId;
|
||||
cardOperations.unarchive(id);
|
||||
});
|
||||
});
|
||||
// Delete (optimistic)
|
||||
body.querySelectorAll('.note-card-delete, .note-card-x').forEach(btn => {
|
||||
btn.addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
const id = btn.dataset.noteId;
|
||||
cardOperations.deleteOptimistically(id);
|
||||
});
|
||||
});
|
||||
// Copy entire checklist (title + items, markdown-style)
|
||||
body.querySelectorAll('.note-card-copy').forEach(btn => {
|
||||
btn.addEventListener('click', async (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
e.stopImmediatePropagation();
|
||||
const id = btn.dataset.noteId;
|
||||
const note = state.notes.find(n => n.id === id);
|
||||
if (!note) return;
|
||||
const lines = [];
|
||||
if (note.title) lines.push(note.title);
|
||||
if (note.content) lines.push(note.content);
|
||||
if (lines.length) lines.push('');
|
||||
for (const it of (note.items || [])) {
|
||||
if (!it || !(it.text || '').trim()) continue;
|
||||
lines.push(`- [${it.done ? 'x' : ' '}] ${(it.text || '').trim()}`);
|
||||
}
|
||||
const text = lines.join('\n').trim();
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
uiModule.showToast?.(`Copied ${(note.items || []).filter(i => (i?.text || '').trim()).length} items`);
|
||||
} catch {
|
||||
// Fallback for browsers blocking the async API
|
||||
const ta = document.createElement('textarea');
|
||||
ta.value = text;
|
||||
ta.style.position = 'fixed'; ta.style.left = '-9999px';
|
||||
document.body.appendChild(ta);
|
||||
ta.select();
|
||||
try { document.execCommand('copy'); uiModule.showToast?.('Copied'); }
|
||||
catch { uiModule.showError?.('Copy failed'); }
|
||||
ta.remove();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
_wireCardChecklist(body);
|
||||
_wireCardReorder(body);
|
||||
|
||||
}
|
||||
|
||||
return { _bindCardEvents };
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
/** Render note cards from application queries and read-only state. */
|
||||
import { _nextGoalStep, _goalProgress, _hasItems, _standardVisualVariant, _visibleNoteTags } from '../domain/noteRules.js';
|
||||
import { _hasTimeComponent, _formatRepeatLabel } from '../domain/recurrence.js';
|
||||
export function createCardRendering({
|
||||
COLORS,
|
||||
COLOR_HEX,
|
||||
_animateReflow,
|
||||
_applyMasonry,
|
||||
_bindCardEvents,
|
||||
_captureCardPositions,
|
||||
_customColorStyle,
|
||||
_dotBg,
|
||||
_dotIsActive,
|
||||
_esc,
|
||||
_formatDueDate,
|
||||
_formatReminderTag,
|
||||
_hasActiveReminder,
|
||||
_isBgImage,
|
||||
_isDueOverdue,
|
||||
_isNotesMobileMode,
|
||||
_linkify,
|
||||
_loadActiveHighlights,
|
||||
_renderLabelsInto,
|
||||
_renderQuickAdd,
|
||||
_safeImgSrc,
|
||||
_sortedVisibleNotes,
|
||||
_updateRailBadge,
|
||||
_wireTodayView,
|
||||
state,
|
||||
uiModule
|
||||
}) {
|
||||
function _renderLoadingSkeleton() {
|
||||
const body = document.querySelector('#notes-pane .notes-pane-body');
|
||||
if (!body) return;
|
||||
body.innerHTML = '';
|
||||
_renderLabelsInto(body);
|
||||
_renderQuickAdd(body);
|
||||
const skel = document.createElement('div');
|
||||
skel.className = 'notes-skeleton';
|
||||
skel.innerHTML = `
|
||||
<div class="notes-skeleton-card"></div>
|
||||
<div class="notes-skeleton-card"></div>
|
||||
<div class="notes-skeleton-card short"></div>
|
||||
<div class="notes-skeleton-card"></div>
|
||||
`;
|
||||
body.appendChild(skel);
|
||||
}
|
||||
|
||||
function _renderNotes() {
|
||||
_updateRailBadge();
|
||||
const body = document.querySelector('#notes-pane .notes-pane-body');
|
||||
if (!body) return;
|
||||
const prevPositions = _captureCardPositions();
|
||||
const activeReminderHighlights = _loadActiveHighlights();
|
||||
|
||||
const sorted = _sortedVisibleNotes();
|
||||
|
||||
let html = '';
|
||||
// Today view: render a compact card listing the next-unchecked step from
|
||||
// each active goal. Tapping a step toggles it done (same idx-based wiring
|
||||
// as regular checkboxes). Tapping the title opens the goal note for full
|
||||
// editing.
|
||||
if (state.activeFilter === 'today') {
|
||||
body.innerHTML = '';
|
||||
_renderLabelsInto(body);
|
||||
_renderQuickAdd(body);
|
||||
if (sorted.length === 0) {
|
||||
body.insertAdjacentHTML('beforeend', `<div class="notes-empty">All caught up — no pending goal steps right now.</div>`);
|
||||
} else {
|
||||
let todayHtml = `<div class="notes-today-wrap">
|
||||
<div class="notes-today-header">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>
|
||||
<span>Today · one step per goal</span>
|
||||
</div>
|
||||
<div class="notes-today-list">`;
|
||||
for (const note of sorted) {
|
||||
const next = _nextGoalStep(note);
|
||||
if (!next) continue;
|
||||
const progress = _goalProgress(note).trim();
|
||||
todayHtml += `<div class="notes-today-row" data-note-id="${note.id}">
|
||||
<span class="note-check-dot" data-note-id="${note.id}" data-idx="${next.idx}" title="Mark step done"></span>
|
||||
<div class="notes-today-text">
|
||||
<div class="notes-today-title" data-action="edit" data-note-id="${note.id}">${_esc(note.title || '(untitled goal)')}</div>
|
||||
<div class="notes-today-step">${_linkify(next.item.text || '')}</div>
|
||||
</div>
|
||||
<span class="notes-today-progress">${_esc(progress)}</span>
|
||||
</div>`;
|
||||
}
|
||||
todayHtml += `</div></div>`;
|
||||
body.insertAdjacentHTML('beforeend', todayHtml);
|
||||
}
|
||||
_wireTodayView(body);
|
||||
return;
|
||||
}
|
||||
for (const note of sorted) {
|
||||
if (state.editingId === note.id) continue; // skip : form is shown instead
|
||||
const borderColor = COLOR_HEX[note.color || ''] || 'var(--border)';
|
||||
const dueFmt = _formatDueDate(note.due_date);
|
||||
const overdue = _isDueOverdue(note.due_date);
|
||||
|
||||
let contentHtml = '';
|
||||
if (_hasItems(note) && Array.isArray(note.items)) {
|
||||
// Goal notes can carry a free-form description above the step list :
|
||||
// todos rarely do, but the same render works for both.
|
||||
if (note.note_type === 'goal' && (note.content || '').trim()) {
|
||||
const fullText = note.content || '';
|
||||
const preview = fullText.length > 300 ? fullText.slice(0, 300) + '…' : fullText;
|
||||
contentHtml += `<div class="note-goal-desc">${_esc(preview)}</div>`;
|
||||
}
|
||||
contentHtml += '<div class="note-checklist-preview">';
|
||||
// Show ALL items : the preview container is scrollable (CSS caps
|
||||
// its max-height + overflow-y:auto), so there's no need to truncate.
|
||||
for (let i = 0; i < note.items.length; i++) {
|
||||
const item = note.items[i];
|
||||
const doneClass = item.done ? ' done' : '';
|
||||
const indent = Math.min(item.indent || 0, 3);
|
||||
contentHtml += `<div class="note-checkbox${doneClass}" data-note-id="${note.id}" data-idx="${i}" style="padding-left:${indent * 16}px">
|
||||
<span class="note-check-dot" title="Mark done"></span>
|
||||
<span class="note-check-text">${_linkify(item.text)}</span>
|
||||
<button class="note-checkbox-edit" data-note-id="${note.id}" data-idx="${i}" title="Edit item">
|
||||
<svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
|
||||
</button>
|
||||
<button class="note-checkbox-rm" data-note-id="${note.id}" data-idx="${i}" title="Delete item">
|
||||
<svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
|
||||
</button>
|
||||
</div>`;
|
||||
}
|
||||
contentHtml += '</div>';
|
||||
} else {
|
||||
const fullText = note.content || '';
|
||||
const preview = fullText.length > 600 ? fullText.slice(0, 600) + '…' : fullText;
|
||||
// _linkify already calls _esc internally, so URLs become clickable
|
||||
// anchors (used by e.g. the "remind me to reply" email deep-link).
|
||||
contentHtml = preview ? `<div class="note-content-preview">${_linkify(preview)}</div>` : '';
|
||||
}
|
||||
|
||||
const isBg = _isBgImage(note.color);
|
||||
const cc = (note.color && !isBg) ? ' note-color-' + note.color : '';
|
||||
const cardStyle = isBg ? ` style="${_customColorStyle(note.color)}"` : '';
|
||||
const isStandard = !note.note_type || note.note_type === 'note';
|
||||
const visualClass = isStandard && !note.color ? ` note-standard note-standard-v${_standardVisualVariant(note)}` : '';
|
||||
const sel = state.selectedIds.has(note.id) ? ' note-card-selected' : '';
|
||||
const reminderTagHtml = note.due_date && _hasTimeComponent(note.due_date)
|
||||
? `<div class="note-card-reminder${overdue ? ' overdue' : ''}">
|
||||
<svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 0 1-3.46 0"/></svg>
|
||||
<span>${_esc(_formatReminderTag(note.due_date))}${note.repeat && note.repeat !== 'none' ? ' · ' + _esc(_formatRepeatLabel(note.repeat, new Date(note.due_date))) : ''}</span>
|
||||
</div>`
|
||||
: '';
|
||||
const noteTags = _visibleNoteTags(note);
|
||||
const dueBadge = dueFmt && !_hasTimeComponent(note.due_date) ? `<span class="note-due-inline${overdue ? ' note-due-overdue' : ''}">${dueFmt}</span>` : '';
|
||||
const colorDots = COLORS.map(c => `<span class="note-card-color-dot${_dotIsActive(c.value, note.color) ? ' active' : ''}" data-color="${c.value}" style="background:${_dotBg(c.value, note.color)}" title="${c.name || 'default'}"></span>`).join('');
|
||||
const goalClass = note.note_type === 'goal' ? ' note-card-goal' : '';
|
||||
const reminderGlowClass = activeReminderHighlights.has(note.id) && _hasActiveReminder(note) ? ' note-card-reminder-fired-sticky' : '';
|
||||
const goalPill = note.note_type === 'goal'
|
||||
? `<span class="note-goal-pill" title="AI-broken-down goal">
|
||||
<svg width="10" height="10" viewBox="0 0 24 24" fill="currentColor"><path d="M12 0L14.59 8.41L23 12L14.59 15.59L12 24L9.41 15.59L1 12L9.41 8.41Z"/></svg>
|
||||
Goal${_goalProgress(note)}
|
||||
</span>`
|
||||
: '';
|
||||
const drawingClass = note.note_type === 'draw' ? ' note-card-drawing' : '';
|
||||
html += `<div class="note-card${note.pinned ? ' note-card-pinned' : ''}${cc}${visualClass}${sel}${goalClass}${drawingClass}${reminderGlowClass}${state.selectMode ? ' note-card-selectmode' : ''}" draggable="${(state.selectMode || _isNotesMobileMode()) ? 'false' : 'true'}" data-note-id="${note.id}"${cardStyle}>
|
||||
${state.selectMode ? `<input type="checkbox" class="memory-select-cb note-card-cb" data-note-id="${note.id}" ${state.selectedIds.has(note.id) ? 'checked' : ''} />` : ''}
|
||||
${goalPill}
|
||||
<button class="note-card-pin${note.pinned ? ' active' : ''}" data-note-id="${note.id}" title="${note.pinned ? 'Unpin' : 'Pin'}">
|
||||
<svg width="16" height="16" viewBox="0 0 24 28" fill="${note.pinned ? 'currentColor' : 'none'}" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"${note.pinned ? ' style="color:var(--accent,var(--red));"' : ''}><g transform="rotate(${note.pinned ? 0 : 45} 12 14)" style="transition:transform 0.2s ease;"><line x1="12" y1="17" x2="12" y2="27"/><path d="M5 17h14v-1.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V6h1a2 2 0 0 0 0-4H8a2 2 0 0 0 0 4h1v4.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V17z"/></g></svg>
|
||||
</button>
|
||||
${state.showingArchived
|
||||
? `<button class="note-card-corner-trash" data-note-id="${note.id}" title="Delete forever" aria-label="Delete forever">
|
||||
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/><line x1="10" y1="11" x2="10" y2="17"/><line x1="14" y1="11" x2="14" y2="17"/></svg>
|
||||
</button>
|
||||
<button class="note-card-corner-unarchive" data-note-id="${note.id}" title="Unarchive" aria-label="Unarchive note">
|
||||
<svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 14l-5-5 5-5"/><path d="M4 9h11a5 5 0 0 1 5 5v0a5 5 0 0 1-5 5H9"/></svg>
|
||||
</button>`
|
||||
: `<button class="note-card-done" data-note-id="${note.id}" title="Mark done" aria-label="Mark done">
|
||||
<svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
|
||||
</button>
|
||||
${_hasItems(note) ? `<button class="note-card-copy note-card-copy-corner" data-note-id="${note.id}" title="Copy all items" aria-label="Copy all items">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
|
||||
</button>` : ''}`}
|
||||
<div class="note-card-header">
|
||||
<div class="note-card-title${note.title ? '' : ' empty'}" data-action="edit">${_esc(note.title || '')}</div>
|
||||
${dueBadge}
|
||||
</div>
|
||||
${_safeImgSrc(note.image_url) ? `<img class="note-card-image" src="${_esc(_safeImgSrc(note.image_url))}" alt="" draggable="false" />` : ''}
|
||||
${contentHtml}
|
||||
${_hasItems(note) ? `<div class="note-cl-quickadd"><input type="text" class="note-cl-quickadd-input" placeholder="+ Add item" data-note-id="${note.id}" /></div>` : ''}
|
||||
${reminderTagHtml}
|
||||
${noteTags.length ? `<div class="note-card-label">${noteTags.map(t => `<button type="button" class="note-card-label-chip" data-note-label-filter="${_esc(t)}" title="Filter #${_esc(t)}">#${_esc(t)}</button>`).join(' ')}</div>` : ''}
|
||||
<div class="note-card-actions">
|
||||
<div class="note-card-colors">${colorDots}</div>
|
||||
<span style="flex:1"></span>
|
||||
${state.showingArchived ? `
|
||||
<button class="note-card-action note-card-delete" data-note-id="${note.id}" title="Delete permanently">
|
||||
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/><line x1="10" y1="11" x2="10" y2="17"/><line x1="14" y1="11" x2="14" y2="17"/></svg>
|
||||
</button>
|
||||
<button class="note-card-action note-card-unarchive" data-note-id="${note.id}" title="Unarchive">
|
||||
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 12a9 9 0 1 0 3-6.7"/><polyline points="3 4 3 10 9 10"/></svg>
|
||||
</button>` : `
|
||||
${_hasItems(note) ? `
|
||||
<button class="note-card-action note-card-copy" data-note-id="${note.id}" title="Copy all items">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
|
||||
</button>` : ''}
|
||||
<button class="note-card-action note-card-archive" data-note-id="${note.id}" title="Save (archive)">
|
||||
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></svg>
|
||||
</button>
|
||||
<button class="note-card-action note-card-delete" data-note-id="${note.id}" title="Delete">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
|
||||
</button>
|
||||
<button class="note-card-action note-card-corner-menu" data-note-id="${note.id}" title="More" aria-label="More actions">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><circle cx="5" cy="12" r="1.7"/><circle cx="12" cy="12" r="1.7"/><circle cx="19" cy="12" r="1.7"/></svg>
|
||||
</button>`}
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
// Always render quick-add at top (collapsed unless user is typing)
|
||||
const existingForm = body.querySelector('.note-form');
|
||||
if (existingForm && state.editingId === '__new__') {
|
||||
// Keep the expanded form, replace cards after it
|
||||
const next = [...body.children].filter(c => c !== existingForm);
|
||||
next.forEach(c => c.remove());
|
||||
if (sorted.length === 0) {
|
||||
body.insertAdjacentHTML('beforeend', '<div class="notes-empty-msg">No notes <span style="vertical-align:-3px;margin-left:4px;">' + uiModule.emptyStateIcon('smiley') + '</span></div>');
|
||||
} else {
|
||||
existingForm.insertAdjacentHTML('afterend', html);
|
||||
}
|
||||
} else {
|
||||
body.innerHTML = '';
|
||||
_renderLabelsInto(body);
|
||||
_renderQuickAdd(body);
|
||||
if (sorted.length === 0) {
|
||||
body.insertAdjacentHTML('beforeend', '<div class="notes-empty-msg">No notes yet <span style="vertical-align:-3px;margin-left:4px;">' + uiModule.emptyStateIcon('smiley') + '</span></div>');
|
||||
} else {
|
||||
body.insertAdjacentHTML('beforeend', html);
|
||||
}
|
||||
}
|
||||
|
||||
_bindCardEvents(body);
|
||||
_animateReflow(prevPositions);
|
||||
_applyMasonry(body);
|
||||
}
|
||||
|
||||
return { _renderLoadingSkeleton, _renderNotes };
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
/** Desktop and large-touch-device card reorder gestures. */
|
||||
export function createCardReorder({
|
||||
lifecycle,
|
||||
_isNotesMobileMode,
|
||||
persistOrder,
|
||||
state
|
||||
}) {
|
||||
function _wireCardReorder(body) {
|
||||
lifecycle.release(body);
|
||||
// Drag-reorder notes on pointer/mouse devices. Mobile uses the custom
|
||||
// placeholder sorter below `_bindLongPressDrag`; native HTML5 dragging is
|
||||
// unreliable on touch browsers and can compete with the long-press flow.
|
||||
if (!_isNotesMobileMode()) {
|
||||
body.querySelectorAll('.note-card').forEach(card => {
|
||||
card.addEventListener('dragstart', (e) => {
|
||||
if (e.target.closest('.note-checkbox, .note-card-x, .note-card-select, .note-card-pin, .note-card-action, .note-card-color-dot, .note-card-title, .note-card-edit, .note-card-edit-corner, .note-card-done, .note-card-corner-menu, .note-agent-tag, .note-card-label-chip')) {
|
||||
e.preventDefault();
|
||||
return;
|
||||
}
|
||||
card.classList.add('dragging');
|
||||
body.classList.add('drag-active');
|
||||
e.dataTransfer.effectAllowed = 'move';
|
||||
try { e.dataTransfer.setData('text/plain', card.dataset.noteId); } catch {}
|
||||
});
|
||||
card.addEventListener('dragend', async () => {
|
||||
card.classList.remove('dragging');
|
||||
body.classList.remove('drag-active');
|
||||
body.querySelectorAll('.drop-before, .drop-after').forEach(el => el.classList.remove('drop-before', 'drop-after'));
|
||||
const ids = [...body.querySelectorAll('.note-card')].map(c => c.dataset.noteId);
|
||||
try { await persistOrder(ids); }
|
||||
catch {}
|
||||
});
|
||||
});
|
||||
}
|
||||
// Track which card we last swapped with so a single hover-over triggers
|
||||
// one swap, not a jitter as the pointer keeps moving inside the same card.
|
||||
let _lastSwapId = null;
|
||||
function _maybeSwap(dragging, clientX, clientY) {
|
||||
const target = document.elementFromPoint(clientX, clientY)?.closest('.note-card');
|
||||
if (!target || target === dragging || !body.contains(target)) return;
|
||||
const id = target.dataset.noteId;
|
||||
if (id === _lastSwapId) return;
|
||||
// FLIP across ALL siblings. In list view only `target` moves visually, but
|
||||
// in grid view (2-col) and when the pinned-section grid-column-start rule
|
||||
// shifts, several cards reflow at once. Capture every card's pre-swap rect,
|
||||
// do the DOM swap, then animate any that actually moved. The dragging card
|
||||
// is excluded : it's already finger-tracked via translate3d.
|
||||
const cards = [...body.querySelectorAll('.note-card')].filter(c => c !== dragging);
|
||||
const prevRects = new Map(cards.map(c => [c, c.getBoundingClientRect()]));
|
||||
const draggingNext = dragging.nextSibling === target ? dragging : dragging.nextSibling;
|
||||
body.insertBefore(dragging, target);
|
||||
body.insertBefore(target, draggingNext);
|
||||
for (const c of cards) {
|
||||
const prev = prevRects.get(c);
|
||||
const next = c.getBoundingClientRect();
|
||||
const dx = prev.left - next.left;
|
||||
const dy = prev.top - next.top;
|
||||
if (Math.abs(dx) < 0.5 && Math.abs(dy) < 0.5) continue;
|
||||
c.style.transition = 'none';
|
||||
c.style.transform = `translate(${dx}px, ${dy}px)`;
|
||||
requestAnimationFrame(() => {
|
||||
c.style.transition = 'transform 0.22s cubic-bezier(0.34, 1.2, 0.64, 1)';
|
||||
c.style.transform = '';
|
||||
c.addEventListener('transitionend', () => { c.style.transition = ''; }, { once: true });
|
||||
});
|
||||
}
|
||||
_lastSwapId = id;
|
||||
}
|
||||
lifecycle.listen(body, body, 'dragover', (e) => {
|
||||
e.preventDefault();
|
||||
const dragging = body.querySelector('.note-card.dragging');
|
||||
if (!dragging) return;
|
||||
_maybeSwap(dragging, e.clientX, e.clientY);
|
||||
});
|
||||
lifecycle.listen(body, body, 'dragend', () => { _lastSwapId = null; });
|
||||
|
||||
// Legacy touch drag for larger touch devices only. Phone-sized Notes uses
|
||||
// the placeholder sorter wired by `_bindLongPressDrag`; running both flows
|
||||
// makes one press start two independent drag sessions.
|
||||
if (!_isNotesMobileMode() && 'ontouchstart' in window) {
|
||||
let dragCard = null;
|
||||
let isDragging = false;
|
||||
let longPressTimer = null;
|
||||
let startX = 0, startY = 0;
|
||||
const LONG_PRESS_MS = 350;
|
||||
const MOVE_THRESHOLD_PX = 8;
|
||||
const _selectorSkip = '.note-checkbox, .note-card-x, .note-card-select, .note-card-pin, .note-card-action, .note-card-color-dot, .note-card-title, .note-card-edit, .note-card-edit-corner, .note-card-done, .note-card-corner-menu, .note-agent-tag, .note-card-label-chip, input, textarea, button, a';
|
||||
|
||||
// Anchor for the finger-follow transform. Recomputed after every swap so
|
||||
// the card stays under the finger across reorderings.
|
||||
let anchorX = 0, anchorY = 0;
|
||||
const _follow = (clientX, clientY) => {
|
||||
if (!dragCard) return;
|
||||
const dx = clientX - anchorX;
|
||||
const dy = clientY - anchorY;
|
||||
// Compose with the CSS .dragging transform (scale + rotate).
|
||||
dragCard.style.transform = `translate3d(${dx}px, ${dy}px, 0) scale(1.03) rotate(-0.6deg)`;
|
||||
};
|
||||
const _reanchor = (clientX, clientY) => {
|
||||
if (!dragCard) return;
|
||||
// Clear any prior translate so the card resettles in its natural slot,
|
||||
// then anchor at the finger's current position. Subsequent _follow calls
|
||||
// translate by (finger - anchor), keeping the finger at the same relative
|
||||
// spot on the card it had when we re-anchored.
|
||||
dragCard.style.transform = '';
|
||||
anchorX = clientX;
|
||||
anchorY = clientY;
|
||||
};
|
||||
|
||||
const _endDrag = (committed) => {
|
||||
clearTimeout(longPressTimer);
|
||||
longPressTimer = null;
|
||||
if (dragCard) {
|
||||
dragCard.classList.remove('dragging');
|
||||
dragCard.style.transform = '';
|
||||
}
|
||||
body.classList.remove('drag-active');
|
||||
_lastSwapId = null;
|
||||
if (isDragging) {
|
||||
document.documentElement.style.touchAction = '';
|
||||
if (committed) {
|
||||
const ids = [...body.querySelectorAll('.note-card')].map(c => c.dataset.noteId);
|
||||
persistOrder(ids).catch(() => {});
|
||||
}
|
||||
}
|
||||
dragCard = null;
|
||||
isDragging = false;
|
||||
};
|
||||
lifecycle.onDispose(body, () => _endDrag(false));
|
||||
|
||||
lifecycle.listen(body, body, 'touchstart', (e) => {
|
||||
if (state.selectMode) return;
|
||||
const card = e.target.closest('.note-card');
|
||||
if (!card) return;
|
||||
if (e.target.closest(_selectorSkip)) return;
|
||||
const t = e.touches[0];
|
||||
startX = t.clientX; startY = t.clientY;
|
||||
dragCard = card;
|
||||
longPressTimer = setTimeout(() => {
|
||||
if (!dragCard) return;
|
||||
isDragging = true;
|
||||
dragCard.classList.add('dragging');
|
||||
body.classList.add('drag-active');
|
||||
document.documentElement.style.touchAction = 'none';
|
||||
_reanchor(startX, startY);
|
||||
try { if (navigator.vibrate) navigator.vibrate(15); } catch {}
|
||||
}, LONG_PRESS_MS);
|
||||
}, { passive: true });
|
||||
|
||||
lifecycle.listen(body, body, 'touchmove', (e) => {
|
||||
if (!dragCard) return;
|
||||
const t = e.touches[0];
|
||||
if (!isDragging) {
|
||||
// Movement before long-press fires = user is scrolling; cancel pickup.
|
||||
if (Math.abs(t.clientX - startX) > MOVE_THRESHOLD_PX || Math.abs(t.clientY - startY) > MOVE_THRESHOLD_PX) {
|
||||
clearTimeout(longPressTimer);
|
||||
longPressTimer = null;
|
||||
dragCard = null;
|
||||
}
|
||||
return;
|
||||
}
|
||||
e.preventDefault();
|
||||
// Live-follow the finger first, then check for a swap. After a swap the
|
||||
// card's natural slot moves, so we re-anchor and re-apply the offset.
|
||||
_follow(t.clientX, t.clientY);
|
||||
const before = dragCard.parentNode && [...dragCard.parentNode.children].indexOf(dragCard);
|
||||
_maybeSwap(dragCard, t.clientX, t.clientY);
|
||||
const after = dragCard.parentNode && [...dragCard.parentNode.children].indexOf(dragCard);
|
||||
if (before !== after) {
|
||||
_reanchor(t.clientX, t.clientY);
|
||||
_follow(t.clientX, t.clientY);
|
||||
}
|
||||
}, { passive: false });
|
||||
|
||||
lifecycle.listen(body, body, 'touchend', () => _endDrag(true));
|
||||
lifecycle.listen(body, body, 'touchcancel', () => _endDrag(false));
|
||||
}
|
||||
}
|
||||
|
||||
return { _wireCardReorder };
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
/** Checklist rows, goal forms, keyboard input and item collection. */
|
||||
export function createChecklist({
|
||||
_esc,
|
||||
_uid,
|
||||
spawnConfetti
|
||||
}) {
|
||||
function _buildGoalHtml(note, items) {
|
||||
const desc = (note?.content || '').toString();
|
||||
return `
|
||||
<div class="note-form-goal">
|
||||
<textarea class="note-form-goal-desc" placeholder="Description (optional)" rows="3">${_esc(desc)}</textarea>
|
||||
${_buildChecklistHtml(items)}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
function _wireGoalForm(form, container) {
|
||||
if (!container) return;
|
||||
// _wireHashtag is a closure inside _buildForm : out of scope here. Inline
|
||||
// the same behavior (type "#foo " in the description → tag added to the
|
||||
// form's label input) so editing a goal note doesn't ReferenceError.
|
||||
const desc = container.querySelector('.note-form-goal-desc');
|
||||
const labelInput = form?.querySelector('.note-form-label');
|
||||
if (desc && labelInput) {
|
||||
const tagRe = /(^|\s)#([A-Za-z0-9][\w-]*)\s$/;
|
||||
desc.addEventListener('input', () => {
|
||||
const m = tagRe.exec(desc.value);
|
||||
if (!m) return;
|
||||
const tag = m[2];
|
||||
// Same dedup-after-stripping fix as the plain note hashtag handler.
|
||||
const existing = labelInput.value.trim().split(/\s+/).filter(Boolean);
|
||||
const stripped = existing.map(t => t.replace(/^#+/, ''));
|
||||
if (!stripped.includes(tag)) {
|
||||
existing.push('#' + tag);
|
||||
labelInput.value = existing.join(' ');
|
||||
labelInput.classList.add('flash-once');
|
||||
setTimeout(() => labelInput.classList.remove('flash-once'), 600);
|
||||
}
|
||||
const cut = desc.value.length - m[0].length + m[1].length;
|
||||
desc.value = desc.value.slice(0, cut);
|
||||
});
|
||||
}
|
||||
// Always wire the checklist. The previous gate on a `note-form-goal-fresh`
|
||||
// class was dead code : nothing ever set that class, so the editor never
|
||||
// hooked up add/drag/Tab.
|
||||
_wireChecklist(container);
|
||||
}
|
||||
|
||||
function _buildChecklistHtml(items) {
|
||||
let html = '<div class="note-checklist-inputs">';
|
||||
for (const item of items) {
|
||||
const indent = Math.min(item.indent || 0, 3);
|
||||
html += `<div class="note-cl-row${item.done ? ' done' : ''}" draggable="true" data-item-id="${item.id || _uid()}" data-indent="${indent}" style="padding-left:${indent * 16}px">
|
||||
<span class="note-cl-grip" title="Drag to reorder">⋮⋮</span>
|
||||
<span class="note-cl-dot"></span>
|
||||
<input type="text" class="note-cl-text" value="${_esc(item.text)}" placeholder="Item..." />
|
||||
<button type="button" class="note-cl-rm">×</button>
|
||||
</div>`;
|
||||
}
|
||||
// `type="button"` matters on mobile : without it some browsers treat
|
||||
// bare <button> as form-submit and the click handler never fires inside
|
||||
// certain containers. Also bumped tap target so fingers don't miss.
|
||||
html += `<button type="button" class="note-cl-add">+ Add</button></div>`;
|
||||
return html;
|
||||
}
|
||||
|
||||
function _wireRow(row, container) {
|
||||
row.querySelector('.note-cl-rm')?.addEventListener('click', () => row.remove());
|
||||
row.querySelector('.note-cl-dot')?.addEventListener('click', () => {
|
||||
const wasDone = row.classList.contains('done');
|
||||
row.classList.toggle('done');
|
||||
// The custom dot has no native input/change event. Notify the form so
|
||||
// mobile edit mode switches its action from Archive back to Update.
|
||||
container.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
const becameDone = !wasDone; // we just flipped it
|
||||
const dot = row.querySelector('.note-cl-dot');
|
||||
const dRect = (dot || row).getBoundingClientRect();
|
||||
// Small confetti burst on each fresh check so the user gets a
|
||||
// "well done" beat per item, not just the grand-finale on all-done.
|
||||
if (becameDone) {
|
||||
spawnConfetti(dRect.left + dRect.width / 2, dRect.top + dRect.height / 2, 16);
|
||||
}
|
||||
// Bigger burst when the whole list is now done.
|
||||
const rows = [...container.querySelectorAll('.note-cl-row')];
|
||||
const hasText = rows.some(r => (r.querySelector('.note-cl-text')?.value || '').trim().length > 0);
|
||||
if (hasText && rows.every(r => r.classList.contains('done') || !(r.querySelector('.note-cl-text')?.value || '').trim())) {
|
||||
spawnConfetti(dRect.left + dRect.width / 2, dRect.top + dRect.height / 2, 60);
|
||||
}
|
||||
});
|
||||
const txt = row.querySelector('.note-cl-text');
|
||||
txt?.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Enter') { e.preventDefault(); container.querySelector('.note-cl-add')?.click(); }
|
||||
else if (e.key === 'Tab') {
|
||||
e.preventDefault();
|
||||
const cur = parseInt(row.dataset.indent || '0');
|
||||
const next = e.shiftKey ? Math.max(0, cur - 1) : Math.min(3, cur + 1);
|
||||
row.dataset.indent = String(next);
|
||||
row.style.paddingLeft = (next * 16) + 'px';
|
||||
} else if (e.key === 'Backspace' && txt.value === '') {
|
||||
e.preventDefault();
|
||||
const prev = row.previousElementSibling;
|
||||
row.remove();
|
||||
if (prev && prev.classList.contains('note-cl-row')) prev.querySelector('.note-cl-text')?.focus();
|
||||
}
|
||||
});
|
||||
// Drag handlers
|
||||
row.addEventListener('dragstart', (e) => {
|
||||
row.classList.add('dragging');
|
||||
e.dataTransfer.effectAllowed = 'move';
|
||||
try { e.dataTransfer.setData('text/plain', row.dataset.itemId); } catch {}
|
||||
});
|
||||
row.addEventListener('dragend', () => {
|
||||
row.classList.remove('dragging');
|
||||
container.querySelectorAll('.drop-before, .drop-after').forEach(el => el.classList.remove('drop-before', 'drop-after'));
|
||||
});
|
||||
}
|
||||
|
||||
function _wireChecklist(container) {
|
||||
if (!container) return;
|
||||
// Delegate the + Add click off the container so re-renders + mobile
|
||||
// touch quirks don't leave the button dead. The previous direct
|
||||
// `addEventListener` on the button silently broke on mobile when
|
||||
// _wireChecklist ran more than once (or before the button was in DOM).
|
||||
if (!container._addDelegated) {
|
||||
container._addDelegated = true;
|
||||
container.addEventListener('click', (ev) => {
|
||||
const addBtn = ev.target.closest('.note-cl-add');
|
||||
if (!addBtn || !container.contains(addBtn)) return;
|
||||
ev.preventDefault();
|
||||
ev.stopPropagation();
|
||||
const inputs = container.querySelector('.note-checklist-inputs');
|
||||
if (!inputs) return;
|
||||
const row = document.createElement('div');
|
||||
row.className = 'note-cl-row';
|
||||
row.draggable = true;
|
||||
row.dataset.itemId = _uid();
|
||||
row.dataset.indent = '0';
|
||||
row.innerHTML = `<span class="note-cl-grip" title="Drag">⋮⋮</span><span class="note-cl-dot"></span><input type="text" class="note-cl-text" placeholder="Item..." /><button type="button" class="note-cl-rm">×</button>`;
|
||||
inputs.insertBefore(row, addBtn);
|
||||
row.querySelector('.note-cl-text').focus();
|
||||
_wireRow(row, container);
|
||||
});
|
||||
}
|
||||
container.querySelectorAll('.note-cl-row').forEach(row => _wireRow(row, container));
|
||||
|
||||
// Drag-over handler on the inputs container
|
||||
const inputs = container.querySelector('.note-checklist-inputs');
|
||||
if (inputs) {
|
||||
inputs.addEventListener('dragover', (e) => {
|
||||
e.preventDefault();
|
||||
const dragging = inputs.querySelector('.note-cl-row.dragging');
|
||||
if (!dragging) return;
|
||||
inputs.querySelectorAll('.drop-before, .drop-after').forEach(el => el.classList.remove('drop-before', 'drop-after'));
|
||||
const rows = [...inputs.querySelectorAll('.note-cl-row:not(.dragging)')];
|
||||
const after = rows.find(r => {
|
||||
const box = r.getBoundingClientRect();
|
||||
return e.clientY < box.top + box.height / 2;
|
||||
});
|
||||
if (after) {
|
||||
after.classList.add('drop-before');
|
||||
inputs.insertBefore(dragging, after);
|
||||
} else if (rows.length) {
|
||||
rows[rows.length - 1].classList.add('drop-after');
|
||||
inputs.insertBefore(dragging, container.querySelector('.note-cl-add'));
|
||||
}
|
||||
});
|
||||
inputs.addEventListener('dragleave', (e) => {
|
||||
if (!inputs.contains(e.relatedTarget)) {
|
||||
inputs.querySelectorAll('.drop-before, .drop-after').forEach(el => el.classList.remove('drop-before', 'drop-after'));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function _collectItems(form) {
|
||||
const items = [];
|
||||
form.querySelectorAll('.note-cl-row').forEach(row => {
|
||||
const text = row.querySelector('.note-cl-text')?.value?.trim();
|
||||
if (text) items.push({
|
||||
id: row.dataset.itemId || _uid(),
|
||||
text,
|
||||
done: row.classList.contains('done'),
|
||||
indent: parseInt(row.dataset.indent || '0'),
|
||||
});
|
||||
});
|
||||
return items;
|
||||
}
|
||||
|
||||
return { _buildGoalHtml, _wireGoalForm, _buildChecklistHtml, _wireRow, _wireChecklist, _collectItems };
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
/** Mobile checklist grip dragging and document listener ownership. */
|
||||
export function createChecklistReorder({
|
||||
lifecycle
|
||||
}) {
|
||||
let _clDrag = null;
|
||||
|
||||
let _clDocBound = false;
|
||||
let _clOwner = null;
|
||||
|
||||
function _wireChecklistTouchReorder(form) {
|
||||
const container = form.querySelector('.note-checklist-inputs');
|
||||
if (!container) return;
|
||||
container.querySelectorAll('.note-cl-grip').forEach(grip => {
|
||||
if (grip.dataset.touchBound === '1') return;
|
||||
grip.dataset.touchBound = '1';
|
||||
grip.addEventListener('touchstart', (e) => {
|
||||
if (e.touches.length !== 1) return;
|
||||
e.preventDefault();
|
||||
const row = grip.closest('.note-cl-row');
|
||||
if (!row) return;
|
||||
_beginChecklistGrab(row, container, e.touches[0]);
|
||||
}, { passive: false });
|
||||
});
|
||||
if (!_clDocBound || _clOwner !== form) {
|
||||
if (_clOwner) lifecycle.release(_clOwner);
|
||||
_clOwner = form;
|
||||
lifecycle.listen(form, document, 'touchmove', _onClTouchMove, { passive: false });
|
||||
lifecycle.listen(form, document, 'touchend', _onClTouchEnd, { passive: true });
|
||||
lifecycle.listen(form, document, 'touchcancel', _onClTouchEnd, { passive: true });
|
||||
_clDocBound = true;
|
||||
}
|
||||
}
|
||||
|
||||
function _beginChecklistGrab(row, container, touch) {
|
||||
if (_clDrag) return;
|
||||
const rect = row.getBoundingClientRect();
|
||||
const placeholder = document.createElement('div');
|
||||
placeholder.className = 'note-cl-row-placeholder';
|
||||
placeholder.style.height = rect.height + 'px';
|
||||
container.insertBefore(placeholder, row);
|
||||
|
||||
row.classList.add('note-cl-row-dragging');
|
||||
row.style.position = 'fixed';
|
||||
row.style.left = rect.left + 'px';
|
||||
row.style.top = rect.top + 'px';
|
||||
row.style.width = rect.width + 'px';
|
||||
row.style.zIndex = '10002';
|
||||
row.style.pointerEvents = 'none';
|
||||
|
||||
_clDrag = {
|
||||
row, placeholder, container,
|
||||
grabOffsetX: touch.clientX - rect.left,
|
||||
grabOffsetY: touch.clientY - rect.top,
|
||||
};
|
||||
try { navigator.vibrate?.(8); } catch {}
|
||||
}
|
||||
|
||||
function _onClTouchMove(e) {
|
||||
if (!_clDrag) return;
|
||||
if (e.touches.length !== 1) return;
|
||||
e.preventDefault();
|
||||
const t = e.touches[0];
|
||||
const { row, placeholder, container } = _clDrag;
|
||||
row.style.left = (t.clientX - _clDrag.grabOffsetX) + 'px';
|
||||
row.style.top = (t.clientY - _clDrag.grabOffsetY) + 'px';
|
||||
|
||||
const under = document.elementFromPoint(t.clientX, t.clientY);
|
||||
const target = under && under.closest
|
||||
? under.closest('.note-cl-row:not(.note-cl-row-dragging)')
|
||||
: null;
|
||||
if (!target || target === row) return;
|
||||
if (target.parentNode !== container) return;
|
||||
|
||||
const tRect = target.getBoundingClientRect();
|
||||
const targetMidY = tRect.top + tRect.height / 2;
|
||||
if (t.clientY < targetMidY) {
|
||||
if (placeholder.nextElementSibling !== target) {
|
||||
container.insertBefore(placeholder, target);
|
||||
}
|
||||
} else {
|
||||
if (target.nextElementSibling !== placeholder) {
|
||||
container.insertBefore(placeholder, target.nextElementSibling);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function _onClTouchEnd() {
|
||||
if (!_clDrag) return;
|
||||
const { row, placeholder } = _clDrag;
|
||||
_clDrag = null;
|
||||
const phRect = placeholder.getBoundingClientRect();
|
||||
row.style.transition = 'left 0.18s ease, top 0.18s ease';
|
||||
row.style.left = phRect.left + 'px';
|
||||
row.style.top = phRect.top + 'px';
|
||||
setTimeout(() => {
|
||||
placeholder.parentNode.insertBefore(row, placeholder);
|
||||
placeholder.remove();
|
||||
row.classList.remove('note-cl-row-dragging');
|
||||
row.style.cssText = '';
|
||||
// Order is persisted as part of the form's normal save (rows are
|
||||
// re-serialized in DOM order via _collectItems).
|
||||
}, 200);
|
||||
}
|
||||
|
||||
function dispose() {
|
||||
if (_clDrag) _onClTouchEnd();
|
||||
_clDocBound = false;
|
||||
_clOwner = null;
|
||||
}
|
||||
return { dispose, _wireChecklistTouchReorder, _beginChecklistGrab, _onClTouchMove, _onClTouchEnd };
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
/** Note clipboard feedback and the Copy/Agent corner menu. */
|
||||
import { _serializeNoteForCopy } from '../domain/noteRules.js';
|
||||
export function createClipboard({
|
||||
_agentSolveNote,
|
||||
bindMenuDismiss,
|
||||
dismissOrRemove,
|
||||
state,
|
||||
topPortalZ,
|
||||
uiModule
|
||||
}) {
|
||||
function _openNoteCornerMenu(btn) {
|
||||
document.querySelectorAll('.note-corner-menu-dropdown').forEach(dismissOrRemove);
|
||||
const id = btn.dataset.noteId;
|
||||
const note = state.notes.find(n => n.id === id);
|
||||
if (!note) return;
|
||||
const menu = document.createElement('div');
|
||||
menu.className = 'note-corner-menu-dropdown';
|
||||
menu.innerHTML = `
|
||||
<button type="button" class="ncm-item" data-act="copy">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
|
||||
<span>Copy</span>
|
||||
</button>
|
||||
<button type="button" class="ncm-item" data-act="agent">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 8V4H8"/><rect x="4" y="8" width="16" height="12" rx="2"/><path d="M2 14h2M20 14h2M15 13v2M9 13v2"/></svg>
|
||||
<span>${note.agent_session_id ? 'Re-run agent' : 'Agent: solve this'}</span>
|
||||
</button>`;
|
||||
document.body.appendChild(menu);
|
||||
const r = btn.getBoundingClientRect();
|
||||
// Right-align to the ⋯ button, clamped to the viewport.
|
||||
const mw = 168;
|
||||
let left = Math.min(r.right - mw, window.innerWidth - mw - 8);
|
||||
left = Math.max(8, left);
|
||||
// Drop down by default; flip up if there isn't room below (the button
|
||||
// sits at the card's bottom edge now).
|
||||
const mh = menu.offsetHeight || 96;
|
||||
const below = window.innerHeight - r.bottom;
|
||||
const top = (below < mh + 8 && r.top > mh + 8) ? (r.top - mh - 4) : (r.bottom + 4);
|
||||
menu.style.cssText += `position:fixed;z-index:${topPortalZ()};top:${Math.round(top)}px;left:${Math.round(left)}px;`;
|
||||
const close = bindMenuDismiss(menu, () => { menu.remove(); });
|
||||
menu.querySelector('[data-act="copy"]').addEventListener('click', () => { close(); _copyNote(id, btn); });
|
||||
menu.querySelector('[data-act="agent"]').addEventListener('click', () => { close(); _agentSolveNote(id); });
|
||||
}
|
||||
|
||||
async function _copyNote(noteId, btnEl) {
|
||||
const note = state.notes.find(n => n.id === noteId);
|
||||
if (!note) return false;
|
||||
const text = _serializeNoteForCopy(note);
|
||||
if (!text) return false;
|
||||
let ok = false;
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
ok = true;
|
||||
} catch {
|
||||
const ta = document.createElement('textarea');
|
||||
ta.value = text;
|
||||
ta.style.position = 'fixed'; ta.style.left = '-9999px';
|
||||
document.body.appendChild(ta);
|
||||
ta.select();
|
||||
try { ok = document.execCommand('copy'); } catch { ok = false; }
|
||||
ta.remove();
|
||||
}
|
||||
if (ok) {
|
||||
if (btnEl && !btnEl._copyFlashing) {
|
||||
const original = btnEl.innerHTML;
|
||||
btnEl._copyFlashing = true;
|
||||
btnEl.innerHTML = '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>';
|
||||
btnEl.classList.add('copied');
|
||||
setTimeout(() => {
|
||||
btnEl.innerHTML = original;
|
||||
btnEl.classList.remove('copied');
|
||||
btnEl._copyFlashing = false;
|
||||
}, 1200);
|
||||
}
|
||||
uiModule.showToast?.('Copied');
|
||||
} else {
|
||||
uiModule.showError?.('Copy failed');
|
||||
}
|
||||
return ok;
|
||||
}
|
||||
|
||||
return { _openNoteCornerMenu, _copyNote };
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
/** Note colors, custom background selection and form color controls. */
|
||||
export function createColors({
|
||||
api
|
||||
}) {
|
||||
const COLORS = [
|
||||
{ name: 'none', value: '' },
|
||||
{ name: 'red', value: 'red' },
|
||||
{ name: 'orange', value: 'orange' },
|
||||
{ name: 'yellow', value: 'yellow' },
|
||||
{ name: 'green', value: 'green' },
|
||||
{ name: 'blue', value: 'blue' },
|
||||
{ name: 'purple', value: 'purple' },
|
||||
{ name: 'custom', value: 'custom' }, // sentinel : clicking opens native color picker
|
||||
];
|
||||
|
||||
const COLOR_HEX = {
|
||||
'': 'var(--border)',
|
||||
// Pale/pastel palette : matches the calendar event color picker.
|
||||
red: '#f0b5ba',
|
||||
orange: '#e8ccb2',
|
||||
yellow: '#f2dfbd',
|
||||
green: '#cce0bc',
|
||||
blue: '#b0d7f7',
|
||||
purple: '#e2bcee',
|
||||
};
|
||||
|
||||
const _CUSTOM_GRADIENT = 'conic-gradient(from 0deg, #e06c75, #d19a66, #e5c07b, #98c379, #61afef, #c678dd, #e06c75)';
|
||||
|
||||
function _isBgImage(c) { return typeof c === 'string' && c.startsWith('bg:'); }
|
||||
|
||||
function _bgImageUrl(c) { return _isBgImage(c) ? c.slice(3) : ''; }
|
||||
|
||||
function _dotBg(value, noteColor) {
|
||||
if (value === 'custom') {
|
||||
const url = _bgImageUrl(noteColor);
|
||||
return url ? `center/cover no-repeat url('${url}')` : _CUSTOM_GRADIENT;
|
||||
}
|
||||
return COLOR_HEX[value];
|
||||
}
|
||||
|
||||
function _dotIsActive(value, noteColor) {
|
||||
if (value === 'custom') return _isBgImage(noteColor);
|
||||
return value === (noteColor || '');
|
||||
}
|
||||
|
||||
function _customColorStyle(c) {
|
||||
if (!_isBgImage(c)) return '';
|
||||
const url = _bgImageUrl(c);
|
||||
return `background-image: linear-gradient(color-mix(in srgb, var(--panel) 60%, transparent), color-mix(in srgb, var(--panel) 60%, transparent)), url('${url}'); background-size: cover; background-position: center; border-color: color-mix(in srgb, var(--fg) 25%, var(--border));`;
|
||||
}
|
||||
|
||||
function _pickCustomBgImage() {
|
||||
return new Promise(resolve => {
|
||||
const input = document.createElement('input');
|
||||
input.type = 'file';
|
||||
input.accept = 'image/*';
|
||||
input.style.cssText = 'position:fixed; left:-9999px; top:-9999px;';
|
||||
document.body.appendChild(input);
|
||||
let done = false;
|
||||
const finish = (v) => { if (done) return; done = true; input.remove(); resolve(v); };
|
||||
input.addEventListener('change', async () => {
|
||||
const file = input.files?.[0];
|
||||
if (!file) return finish(null);
|
||||
const fd = new FormData();
|
||||
fd.append('files', file);
|
||||
try {
|
||||
const res = await api.upload(fd);
|
||||
const data = await res.json();
|
||||
const fileId = data.files?.[0]?.id;
|
||||
if (!fileId) throw new Error('Upload failed');
|
||||
finish(api.uploadUrl(fileId));
|
||||
} catch { finish(null); }
|
||||
});
|
||||
// Best-effort cleanup if user dismisses the dialog.
|
||||
setTimeout(() => { if (!done && !input.files?.length) finish(null); }, 30000);
|
||||
input.click();
|
||||
});
|
||||
}
|
||||
|
||||
function _wireFormColors(form, setColor) {
|
||||
// Color dots : apply to entire form immediately
|
||||
const _applyFormColor = (newColor) => {
|
||||
const currentColor = newColor || '';
|
||||
setColor(currentColor);
|
||||
form.dataset.noteColor = currentColor;
|
||||
const isBg = _isBgImage(currentColor);
|
||||
COLORS.forEach(c => { if (c.value && c.value !== 'custom') form.classList.remove('note-color-' + c.value); });
|
||||
if (currentColor && !isBg) form.classList.add('note-color-' + currentColor);
|
||||
if (isBg) form.setAttribute('style', _customColorStyle(currentColor));
|
||||
else form.removeAttribute('style');
|
||||
form.querySelectorAll('.note-color-dot').forEach(d => {
|
||||
d.classList.toggle('active', _dotIsActive(d.dataset.color, currentColor));
|
||||
d.style.background = _dotBg(d.dataset.color, currentColor);
|
||||
});
|
||||
form.dispatchEvent(new Event('change', { bubbles: true }));
|
||||
};
|
||||
form.querySelectorAll('.note-color-dot').forEach(dot => {
|
||||
dot.addEventListener('click', () => {
|
||||
if (dot.dataset.color === 'custom') {
|
||||
_pickCustomBgImage().then(url => { if (url) _applyFormColor('bg:' + url); });
|
||||
return;
|
||||
}
|
||||
_applyFormColor(dot.dataset.color);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
}
|
||||
|
||||
return { COLORS, COLOR_HEX, _isBgImage, _bgImageUrl, _dotBg, _dotIsActive, _customColorStyle, _pickCustomBgImage, _wireFormColors };
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
/** Collect editor drafts, restore them and wire the autosave workflow. */
|
||||
export function createDraftEditor({
|
||||
bindDraft,
|
||||
_collectItems,
|
||||
_loadDraft
|
||||
}) {
|
||||
function _collectFormDraft(form) {
|
||||
if (!form) return null;
|
||||
const type = form.querySelector('.note-form-type-pill.active')?.dataset.type || form.dataset.noteType || 'note';
|
||||
const d = {
|
||||
_ts: Date.now(),
|
||||
note_type: type,
|
||||
color: form.dataset.noteColor || '',
|
||||
title: form.querySelector('.note-form-title')?.value || '',
|
||||
label: form.querySelector('.note-form-label')?.value || '',
|
||||
due_date: form.querySelector('.note-form-due')?.value || null,
|
||||
repeat: form.querySelector('.note-form-repeat')?.value || 'none',
|
||||
};
|
||||
if (type === 'note') d.content = form.querySelector('.note-form-content')?.value || '';
|
||||
else if (type === 'goal') { d.content = form.querySelector('.note-form-goal-desc')?.value || ''; d.items = _collectItems(form); }
|
||||
else d.items = _collectItems(form);
|
||||
return d;
|
||||
}
|
||||
|
||||
function _isDraftEmpty(d) {
|
||||
if (!d) return true;
|
||||
if ((d.title || '').trim()) return false;
|
||||
if ((d.content || '').trim()) return false;
|
||||
if (Array.isArray(d.items) && d.items.some(it => (it.text || '').trim())) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
function _wireDraftAutosave(form, id) {
|
||||
const view = {
|
||||
get failed() { return form._autosaveFailed; },
|
||||
set failed(value) { form._autosaveFailed = value; },
|
||||
};
|
||||
const draft = bindDraft({ collect: () => _collectFormDraft(form), id, view });
|
||||
form._flushDraft = draft.flush;
|
||||
form._stopDraftAutosave = draft.stop;
|
||||
form.addEventListener('input', draft.schedule);
|
||||
form.addEventListener('change', draft.schedule);
|
||||
form.addEventListener('click', event => {
|
||||
if (event.target.closest('.note-cl-dot, .note-cl-rm')) draft.schedule();
|
||||
});
|
||||
}
|
||||
|
||||
function _commitOpenInPlaceEditor() {
|
||||
const form = document.querySelector('#notes-pane .note-form');
|
||||
if (!form) return;
|
||||
const d = _collectFormDraft(form);
|
||||
if (_isDraftEmpty(d)) { form.querySelector('.note-form-cancel')?.click(); return; }
|
||||
form.querySelector('.note-form-save')?.click();
|
||||
}
|
||||
|
||||
function _applyDraftToNote(note, id) {
|
||||
const d = _loadDraft(id);
|
||||
if (!d) return { note, restored: false };
|
||||
const merged = { ...(note || {}) };
|
||||
['note_type', 'color', 'title', 'label', 'due_date', 'repeat', 'content', 'items'].forEach(k => {
|
||||
if (d[k] !== undefined) merged[k] = d[k];
|
||||
});
|
||||
return { note: merged, restored: true };
|
||||
}
|
||||
|
||||
return { _collectFormDraft, _isDraftEmpty, _wireDraftAutosave, _commitOpenInPlaceEditor, _applyDraftToNote };
|
||||
}
|
||||
@@ -0,0 +1,442 @@
|
||||
/** Canvas drawing tools, local drawing undo and PNG uploads. */
|
||||
export function createDrawing({
|
||||
lifecycle,
|
||||
_safeImgSrc,
|
||||
api,
|
||||
attachColorPicker
|
||||
}) {
|
||||
function _buildDrawHtml() {
|
||||
return `
|
||||
<div class="note-form-draw-wrap">
|
||||
<canvas class="note-form-canvas" width="600" height="320"></canvas>
|
||||
<div class="note-form-draw-toolbar">
|
||||
<input type="color" class="note-form-draw-color" title="Stroke color" value="#222222" />
|
||||
<label class="note-form-draw-tool note-form-draw-size-wrap" title="Stroke size">
|
||||
<input type="range" class="note-form-draw-size" min="1" max="24" value="3" />
|
||||
</label>
|
||||
<div class="note-form-draw-be" role="group">
|
||||
<button type="button" class="note-form-draw-be-btn note-form-draw-brush active" data-mode="pen" title="Brush">
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9.06 11.9l8.07-8.06a2.85 2.85 0 1 1 4.03 4.03l-8.06 8.08"/><path d="M7.07 14.94c-1.66 0-3 1.35-3 3.02 0 1.33-2.5 1.52-2 2.02 1.08 1.1 2.49 2.02 4 2.02 2.2 0 4-1.8 4-4.04 0-1.67-1.34-3.02-3-3.02z"/></svg>
|
||||
</button>
|
||||
<button type="button" class="note-form-draw-be-btn note-form-draw-eraser" data-mode="eraser" title="Eraser">
|
||||
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21"/><path d="M22 21H7"/><path d="m5 11 9 9"/></svg>
|
||||
</button>
|
||||
</div>
|
||||
<button type="button" class="note-form-draw-undo" title="Undo" aria-label="Undo">
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 14 4 9 9 4"></polyline><path d="M4 9h11a5 5 0 0 1 5 5v0a5 5 0 0 1-5 5H9"></path></svg>
|
||||
</button>
|
||||
<button type="button" class="note-form-draw-text" title="Add text — click to cycle size" aria-label="Add text">T<span class="note-form-draw-text-badge"></span></button>
|
||||
<button type="button" class="note-form-draw-line" title="Line — click to cycle size">
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="4" y1="20" x2="20" y2="4"/></svg>
|
||||
<span class="note-form-draw-shape-badge"></span>
|
||||
</button>
|
||||
<button type="button" class="note-form-draw-circle" title="Circle — click to cycle size">
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="9"/></svg>
|
||||
<span class="note-form-draw-shape-badge"></span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
function _wireCanvas(container, initialImageUrl) {
|
||||
const canvas = container.querySelector('.note-form-canvas');
|
||||
if (!canvas) return;
|
||||
const resolveThemeColor = (expression, fallback) => {
|
||||
const probe = document.createElement('span');
|
||||
probe.style.color = expression;
|
||||
probe.style.position = 'fixed';
|
||||
probe.style.visibility = 'hidden';
|
||||
document.body.appendChild(probe);
|
||||
const resolved = getComputedStyle(probe).color || fallback;
|
||||
probe.remove();
|
||||
return resolved;
|
||||
};
|
||||
const colorToHex = (color, fallback) => {
|
||||
try {
|
||||
const probe = document.createElement('canvas');
|
||||
probe.width = probe.height = 1;
|
||||
const probeCtx = probe.getContext('2d');
|
||||
probeCtx.fillStyle = color;
|
||||
probeCtx.fillRect(0, 0, 1, 1);
|
||||
const [r, g, b] = probeCtx.getImageData(0, 0, 1, 1).data;
|
||||
return `#${[r, g, b].map(v => v.toString(16).padStart(2, '0')).join('')}`;
|
||||
} catch { return fallback; }
|
||||
};
|
||||
const surfaceColor = resolveThemeColor('var(--panel, var(--bg))', '#282c34');
|
||||
const surfaceColorHex = colorToHex(surfaceColor, '#282c34');
|
||||
const highlightColor = colorToHex(
|
||||
resolveThemeColor('var(--accent, var(--red))', '#e06c75'),
|
||||
'#e06c75',
|
||||
);
|
||||
const colorInput = container.querySelector('.note-form-draw-color');
|
||||
if (colorInput) colorInput.value = highlightColor;
|
||||
// Bump the backing-store resolution for retina displays so strokes stay
|
||||
// crisp. Set only style.width : leaving style.height to auto so the canvas
|
||||
// scales uniformly via its intrinsic aspect ratio. If both CSS dimensions
|
||||
// are pinned, max-width:100% shrinks the width only, leaving rasterized
|
||||
// glyphs visibly stretched relative to their on-screen input.
|
||||
const dpr = Math.min(window.devicePixelRatio || 1, 2);
|
||||
const cssW = canvas.width;
|
||||
const cssH = canvas.height;
|
||||
// Fill the container up to the logical width (don't pin a hard 600px,
|
||||
// which on a narrow phone forces the card wider than the viewport and
|
||||
// pushes the drawing outside the note). _pos() scales pointer coords by
|
||||
// the actual displayed width, so accuracy is preserved at any size.
|
||||
canvas.style.width = '100%';
|
||||
canvas.style.maxWidth = cssW + 'px';
|
||||
canvas.style.height = 'auto';
|
||||
canvas.style.aspectRatio = cssW + ' / ' + cssH;
|
||||
canvas.width = cssW * dpr;
|
||||
canvas.height = cssH * dpr;
|
||||
const ctx = canvas.getContext('2d');
|
||||
ctx.scale(dpr, dpr);
|
||||
ctx.fillStyle = surfaceColor;
|
||||
ctx.fillRect(0, 0, cssW, cssH);
|
||||
ctx.lineCap = 'round';
|
||||
ctx.lineJoin = 'round';
|
||||
|
||||
// Load prior drawing as starting point so consecutive edits compose.
|
||||
const safeInitialImageUrl = _safeImgSrc(initialImageUrl);
|
||||
if (safeInitialImageUrl) {
|
||||
const img = new Image();
|
||||
img.crossOrigin = 'anonymous';
|
||||
img.onload = () => { try { ctx.drawImage(img, 0, 0, cssW, cssH); } catch {} };
|
||||
img.src = safeInitialImageUrl;
|
||||
// Float an X over the canvas so the user can blank it out and go back to
|
||||
// a clean draw surface. Removes itself once clicked.
|
||||
const wrap = container.querySelector('.note-form-draw-wrap');
|
||||
if (wrap && !wrap.querySelector('.note-form-draw-bg-rm')) {
|
||||
const rm = document.createElement('button');
|
||||
rm.type = 'button';
|
||||
rm.className = 'note-form-draw-bg-rm';
|
||||
rm.title = 'Clear photo (regular draw)';
|
||||
rm.innerHTML = '×';
|
||||
rm.addEventListener('click', (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
ctx.fillStyle = surfaceColor;
|
||||
ctx.fillRect(0, 0, cssW, cssH);
|
||||
rm.remove();
|
||||
});
|
||||
wrap.appendChild(rm);
|
||||
}
|
||||
}
|
||||
|
||||
// Swap the native browser color dialog for the in-house HSV picker
|
||||
// (same one used by Themes + the gallery editor). Existing `input` event
|
||||
// listeners + .value reads keep working : see colorPicker.js.
|
||||
if (colorInput) attachColorPicker(colorInput);
|
||||
const sizeInput = container.querySelector('.note-form-draw-size');
|
||||
const beSeg = container.querySelector('.note-form-draw-be');
|
||||
const brushBtn = container.querySelector('.note-form-draw-brush');
|
||||
const eraserBtn = container.querySelector('.note-form-draw-eraser');
|
||||
const textBtn = container.querySelector('.note-form-draw-text');
|
||||
const lineBtn = container.querySelector('.note-form-draw-line');
|
||||
const circleBtn = container.querySelector('.note-form-draw-circle');
|
||||
const undoBtn = container.querySelector('.note-form-draw-undo');
|
||||
// Single source of truth for what clicks/drags do. Other booleans are
|
||||
// derived from this so we never end up with conflicting "eraser AND text"
|
||||
// states (the bug that made T appear broken after using the eraser).
|
||||
// Modes: 'pen' | 'eraser' | 'text-s' | 'text-m' | 'text-l' | 'line' | 'circle'
|
||||
let mode = 'pen';
|
||||
let drawing = false;
|
||||
let last = null;
|
||||
// The text tool has three preset sizes (CSS px font-size).
|
||||
const TEXT_SIZES = { 's': 16, 'm': 26, 'l': 40 };
|
||||
// Line / circle stroke widths in logical pixels : three crisp options.
|
||||
const SHAPE_WIDTHS = { 's': 2, 'm': 5, 'l': 10 };
|
||||
// Snapshot taken at the start of a shape drag so the preview can repaint
|
||||
// cleanly on each move without accumulating intermediate strokes.
|
||||
let _shapeSnapshot = null;
|
||||
|
||||
// Per-canvas undo stack. We snapshot the bitmap (as ImageData) BEFORE each
|
||||
// operation : stroke, text commit, or future operations : and pop+restore
|
||||
// on Undo. Cap to 30 to keep memory bounded.
|
||||
const _undoStack = [];
|
||||
const UNDO_LIMIT = 30;
|
||||
const _syncUndoButton = () => {
|
||||
const available = _undoStack.length > 0;
|
||||
undoBtn?.classList.toggle('has-undo', available);
|
||||
undoBtn?.toggleAttribute('disabled', !available);
|
||||
undoBtn?.setAttribute('aria-disabled', available ? 'false' : 'true');
|
||||
};
|
||||
const _markCanvasDirty = () => container.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
const _snapshot = () => {
|
||||
try {
|
||||
const w = canvas.width, h = canvas.height;
|
||||
_undoStack.push(ctx.getImageData(0, 0, w, h));
|
||||
if (_undoStack.length > UNDO_LIMIT) _undoStack.shift();
|
||||
_syncUndoButton();
|
||||
} catch {}
|
||||
};
|
||||
const _undo = () => {
|
||||
const prev = _undoStack.pop();
|
||||
if (!prev) { _syncUndoButton(); return; }
|
||||
// Restore against the raw backing store: temporarily reset the active
|
||||
// ctx scale, paint the snapshot 1:1, then reapply our standard transform.
|
||||
ctx.save();
|
||||
ctx.setTransform(1, 0, 0, 1, 0, 0);
|
||||
ctx.putImageData(prev, 0, 0);
|
||||
ctx.restore();
|
||||
_markCanvasDirty();
|
||||
_syncUndoButton();
|
||||
};
|
||||
|
||||
const _pos = (e) => {
|
||||
// CSS can shrink the canvas (max-width:100%) without changing its logical
|
||||
// size, so compute the displayed-to-logical scale per axis. Pointer coords
|
||||
// are in CSS pixels; the dpr-scaled ctx expects logical (cssW × cssH).
|
||||
const r = canvas.getBoundingClientRect();
|
||||
const sx = cssW / r.width;
|
||||
const sy = cssH / r.height;
|
||||
const t = e.touches ? e.touches[0] : e;
|
||||
return { x: (t.clientX - r.left) * sx, y: (t.clientY - r.top) * sy };
|
||||
};
|
||||
const _begin = (e) => {
|
||||
if (mode.startsWith('text-')) {
|
||||
// Stop the event so the browser doesn't synthesize a follow-up click
|
||||
// that would blur the input we're about to create.
|
||||
e.preventDefault?.();
|
||||
e.stopPropagation?.();
|
||||
_openTextInput(e);
|
||||
return;
|
||||
}
|
||||
_snapshot();
|
||||
last = _pos(e);
|
||||
drawing = true;
|
||||
if (mode.startsWith('line-') || mode.startsWith('circle-')) {
|
||||
// Capture the backing pixels so the preview can replay each move from
|
||||
// the same starting state (otherwise live shapes accumulate).
|
||||
try { _shapeSnapshot = ctx.getImageData(0, 0, canvas.width, canvas.height); } catch {}
|
||||
return;
|
||||
}
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(last.x, last.y);
|
||||
};
|
||||
|
||||
// Drop an HTML input at the click position so the user can type, then
|
||||
// rasterize the text onto the canvas at blur/Enter. Mirrors how PDF form
|
||||
// annotations work in our doc editor.
|
||||
let _activeTextInput = null;
|
||||
const _openTextInput = (e) => {
|
||||
// Commit any prior pending input before starting a new one : otherwise
|
||||
// the first click leaves an orphaned input the user thinks "didn't work".
|
||||
if (_activeTextInput) { try { _activeTextInput.blur(); } catch {} }
|
||||
const r = canvas.getBoundingClientRect();
|
||||
const t = e.touches ? e.touches[0] : e;
|
||||
// Position is anchored to the wrap, not the canvas; since the canvas is
|
||||
// the first child of the wrap and the wrap has no padding, they share an
|
||||
// origin, so we offset from the canvas rect directly.
|
||||
const px = t.clientX - r.left;
|
||||
const py = t.clientY - r.top;
|
||||
const logical = _pos(e);
|
||||
// Size is decided by which T variant is active (S/M/L), not the stroke
|
||||
// slider : those are independent dials.
|
||||
const sizeKey = mode.startsWith('text-') ? mode.slice(-1) : 'm';
|
||||
const sizeCss = TEXT_SIZES[sizeKey] || TEXT_SIZES.m;
|
||||
const wrap = container.querySelector('.note-form-draw-wrap');
|
||||
if (!wrap) return;
|
||||
if (getComputedStyle(wrap).position === 'static') wrap.style.position = 'relative';
|
||||
const input = document.createElement('input');
|
||||
input.type = 'text';
|
||||
input.className = 'note-form-draw-textinput';
|
||||
input.placeholder = 'type then Enter';
|
||||
const color = colorInput?.value || '#222';
|
||||
const maxW = Math.max(120, Math.floor(r.width - px - 4));
|
||||
input.style.cssText = [
|
||||
'position:absolute',
|
||||
`left:${px}px`,
|
||||
`top:${Math.max(0, py - sizeCss * 0.7)}px`,
|
||||
`font:${sizeCss}px Arial, sans-serif`,
|
||||
`color:${color}`,
|
||||
'background:#ffffff',
|
||||
'border:2px solid var(--accent)',
|
||||
'border-radius:4px',
|
||||
'outline:none',
|
||||
'padding:2px 6px',
|
||||
'min-width:120px',
|
||||
`max-width:${maxW}px`,
|
||||
'z-index:1000',
|
||||
'box-shadow:0 2px 8px rgba(0,0,0,0.25)',
|
||||
'pointer-events:auto',
|
||||
].join(';');
|
||||
wrap.appendChild(input);
|
||||
_activeTextInput = input;
|
||||
// Focus synchronously so the call still counts as inside the user gesture
|
||||
// on iOS / Android, then re-focus on the next frame in case a competing
|
||||
// synthetic event (touch → click) moved focus away.
|
||||
input.focus();
|
||||
requestAnimationFrame(() => { if (document.activeElement !== input) input.focus(); });
|
||||
let committed = false;
|
||||
const commit = () => {
|
||||
if (committed) return;
|
||||
committed = true;
|
||||
const text = input.value;
|
||||
if (_activeTextInput === input) _activeTextInput = null;
|
||||
input.remove();
|
||||
if (!text) return;
|
||||
// Snapshot BEFORE rasterizing so Undo removes the text in one step.
|
||||
_snapshot();
|
||||
ctx.save();
|
||||
ctx.globalCompositeOperation = 'source-over';
|
||||
ctx.fillStyle = color;
|
||||
// Canvas now scales uniformly (style.height: auto), so a single ratio
|
||||
// suffices for picking the logical font size that matches what the
|
||||
// user just saw in the HTML input.
|
||||
const sx = cssW / r.width;
|
||||
const logicalSize = sizeCss * sx;
|
||||
ctx.font = `${logicalSize}px sans-serif`;
|
||||
ctx.textBaseline = 'top';
|
||||
ctx.fillText(text, logical.x, logical.y - logicalSize * 0.7);
|
||||
ctx.restore();
|
||||
_markCanvasDirty();
|
||||
};
|
||||
input.addEventListener('blur', commit);
|
||||
input.addEventListener('keydown', (ev) => {
|
||||
if (ev.key === 'Enter') { ev.preventDefault(); input.blur(); }
|
||||
else if (ev.key === 'Escape') { input.value = ''; input.blur(); }
|
||||
});
|
||||
};
|
||||
const _move = (e) => {
|
||||
if (!drawing) return;
|
||||
e.preventDefault?.();
|
||||
const p = _pos(e);
|
||||
if (mode.startsWith('line-') || mode.startsWith('circle-')) {
|
||||
// Restore the pre-shape bitmap, then redraw the preview shape from
|
||||
// anchor → current pointer.
|
||||
if (_shapeSnapshot) {
|
||||
ctx.save();
|
||||
ctx.setTransform(1, 0, 0, 1, 0, 0);
|
||||
ctx.putImageData(_shapeSnapshot, 0, 0);
|
||||
ctx.restore();
|
||||
}
|
||||
ctx.globalCompositeOperation = 'source-over';
|
||||
ctx.strokeStyle = colorInput?.value || '#222';
|
||||
const sizeKey = mode.slice(-1);
|
||||
ctx.lineWidth = SHAPE_WIDTHS[sizeKey] || SHAPE_WIDTHS.m;
|
||||
ctx.beginPath();
|
||||
if (mode.startsWith('line-')) {
|
||||
ctx.moveTo(last.x, last.y);
|
||||
ctx.lineTo(p.x, p.y);
|
||||
} else {
|
||||
const dx = p.x - last.x;
|
||||
const dy = p.y - last.y;
|
||||
const radius = Math.hypot(dx, dy);
|
||||
ctx.arc(last.x, last.y, radius, 0, Math.PI * 2);
|
||||
}
|
||||
ctx.stroke();
|
||||
return;
|
||||
}
|
||||
const erasing = mode === 'eraser';
|
||||
ctx.globalCompositeOperation = 'source-over';
|
||||
ctx.strokeStyle = erasing ? surfaceColor : (colorInput?.value || highlightColor);
|
||||
ctx.lineWidth = Number(sizeInput?.value || 3) * (erasing ? 2.5 : 1);
|
||||
ctx.lineTo(p.x, p.y);
|
||||
ctx.stroke();
|
||||
last = p;
|
||||
};
|
||||
const _end = () => {
|
||||
if (drawing) _markCanvasDirty();
|
||||
drawing = false; last = null; _shapeSnapshot = null;
|
||||
};
|
||||
|
||||
canvas.addEventListener('mousedown', _begin);
|
||||
canvas.addEventListener('mousemove', _move);
|
||||
lifecycle.listen(canvas, window, 'mouseup', _end);
|
||||
// Non-passive so text mode can preventDefault : otherwise the synthetic
|
||||
// mousedown/click that follows a touch can blur the freshly-created text
|
||||
// input on iOS Safari, making T look like a no-op.
|
||||
canvas.addEventListener('touchstart', (e) => { if (mode.startsWith('text-')) e.preventDefault(); _begin(e); }, { passive: false });
|
||||
canvas.addEventListener('touchmove', _move, { passive: false });
|
||||
canvas.addEventListener('touchend', _end);
|
||||
canvas.addEventListener('touchcancel', _end);
|
||||
|
||||
// Single mode setter : keeps the toolbar, swatch, and cursor in sync, and
|
||||
// makes sure exiting the eraser restores the user's chosen color whether
|
||||
// they exit by clicking another tool or by toggling eraser off.
|
||||
let _preEraseColor = null;
|
||||
const _setMode = (next) => {
|
||||
const wasEraser = mode === 'eraser';
|
||||
mode = next;
|
||||
const isEraser = next === 'eraser';
|
||||
const isPen = next === 'pen';
|
||||
const isText = next.startsWith('text-');
|
||||
// Swatch: theme surface while erasing, restored when leaving that mode.
|
||||
if (isEraser && !wasEraser && colorInput) {
|
||||
_preEraseColor = colorInput.value;
|
||||
colorInput.value = surfaceColorHex;
|
||||
} else if (!isEraser && wasEraser && colorInput && _preEraseColor) {
|
||||
colorInput.value = _preEraseColor;
|
||||
_preEraseColor = null;
|
||||
}
|
||||
// Brush/Eraser segmented pill : slides to the active side. When a non-
|
||||
// pen/eraser tool (T / line / circle) is active, neither half is
|
||||
// highlighted, but the pill still indicates which side the user was on
|
||||
// last so they can return with one click.
|
||||
const isLine = next.startsWith('line-');
|
||||
const isCircle = next.startsWith('circle-');
|
||||
beSeg?.classList.toggle('is-eraser', isEraser);
|
||||
brushBtn?.classList.toggle('active', isPen);
|
||||
eraserBtn?.classList.toggle('active', isEraser);
|
||||
textBtn?.classList.toggle('active', isText);
|
||||
lineBtn?.classList.toggle('active', isLine);
|
||||
circleBtn?.classList.toggle('active', isCircle);
|
||||
// Per-button size badges (S/M/L), driven off the mode suffix.
|
||||
const tBadge = textBtn?.querySelector('.note-form-draw-text-badge');
|
||||
if (tBadge) tBadge.textContent = isText ? next.slice(-1).toUpperCase() : '';
|
||||
const lBadge = lineBtn?.querySelector('.note-form-draw-shape-badge');
|
||||
if (lBadge) lBadge.textContent = isLine ? next.slice(-1).toUpperCase() : '';
|
||||
const cBadge = circleBtn?.querySelector('.note-form-draw-shape-badge');
|
||||
if (cBadge) cBadge.textContent = isCircle ? next.slice(-1).toUpperCase() : '';
|
||||
// Reflect the chosen size in the icon itself : thicker line/circle stroke
|
||||
// for M+L, larger T glyph for M+L. CSS rules read `.size-s/.size-m/.size-l`.
|
||||
const _sz = next.slice(-1);
|
||||
[textBtn, lineBtn, circleBtn].forEach(b => b?.classList.remove('size-s', 'size-m', 'size-l'));
|
||||
if (isText && /[sml]/.test(_sz)) textBtn?.classList.add('size-' + _sz);
|
||||
if (isLine && /[sml]/.test(_sz)) lineBtn?.classList.add('size-' + _sz);
|
||||
if (isCircle && /[sml]/.test(_sz)) circleBtn?.classList.add('size-' + _sz);
|
||||
canvas.style.cursor = isText ? 'text' : 'crosshair';
|
||||
};
|
||||
brushBtn?.addEventListener('click', () => _setMode('pen'));
|
||||
eraserBtn?.addEventListener('click', () => _setMode('eraser'));
|
||||
// T / Line / Circle: each cycles its own three sizes, then back to pen.
|
||||
const _cycle = (prefix) => {
|
||||
const seq = ['s', 'm', 'l'];
|
||||
if (!mode.startsWith(prefix)) return prefix + 's';
|
||||
const cur = mode.slice(-1);
|
||||
const next = seq[seq.indexOf(cur) + 1];
|
||||
return next ? prefix + next : 'pen';
|
||||
};
|
||||
textBtn?.addEventListener('click', () => _setMode(_cycle('text-')));
|
||||
lineBtn?.addEventListener('click', () => _setMode(_cycle('line-')));
|
||||
circleBtn?.addEventListener('click', () => _setMode(_cycle('circle-')));
|
||||
undoBtn?.addEventListener('click', () => _undo());
|
||||
_syncUndoButton();
|
||||
|
||||
// Stash so the save handler can read it later without re-resolving DOM.
|
||||
canvas._cssW = cssW;
|
||||
canvas._cssH = cssH;
|
||||
return canvas;
|
||||
}
|
||||
|
||||
async function _uploadCanvasAsPng(canvas, galleryId = null) {
|
||||
if (!canvas) return null;
|
||||
const blob = await new Promise(r => canvas.toBlob(r, 'image/png'));
|
||||
if (!blob) return null;
|
||||
const fd = new FormData();
|
||||
fd.append('files', blob, 'drawing.png');
|
||||
if (galleryId) fd.append('gallery_id', galleryId);
|
||||
try {
|
||||
const res = await api.upload(fd);
|
||||
const data = await res.json();
|
||||
const id = data.files?.[0]?.id;
|
||||
return id ? {
|
||||
url: api.uploadUrl(id),
|
||||
galleryId: data.files?.[0]?.gallery_id || null,
|
||||
} : null;
|
||||
} catch { return null; }
|
||||
}
|
||||
|
||||
return { _buildDrawHtml, _wireCanvas, _uploadCanvasAsPng };
|
||||
}
|
||||
@@ -0,0 +1,518 @@
|
||||
/** Build and wire note, checklist, goal and drawing editor forms. */
|
||||
export function createEditor({
|
||||
deleteFromEditor,
|
||||
submitNote,
|
||||
COLORS,
|
||||
_applyMasonry,
|
||||
_archiveNoteById,
|
||||
_buildChecklistHtml,
|
||||
_buildDrawHtml,
|
||||
_buildGoalHtml,
|
||||
_collectItems,
|
||||
_customColorStyle,
|
||||
_dotBg,
|
||||
_dotIsActive,
|
||||
_esc,
|
||||
_isBgImage,
|
||||
_renderNotes,
|
||||
_safeImgSrc,
|
||||
_uid,
|
||||
_uploadCanvasAsPng,
|
||||
_wireCanvas,
|
||||
_wireChecklist,
|
||||
_wireDraftAutosave,
|
||||
_wireFormColors,
|
||||
_wireGoalForm,
|
||||
_wireReminderPicker,
|
||||
api,
|
||||
app,
|
||||
state,
|
||||
uiModule
|
||||
}) {
|
||||
function _buildForm(note = null) {
|
||||
const isEdit = note && note.id;
|
||||
const type = note?.note_type === 'checklist' ? 'todo' : (note?.note_type || 'note');
|
||||
const color = note?.color || '';
|
||||
const items = note?.items || [{ id: _uid(), text: '', done: false }];
|
||||
|
||||
const form = document.createElement('div');
|
||||
form.className = 'note-form';
|
||||
form.dataset.noteType = type;
|
||||
form.dataset.noteColor = color || '';
|
||||
if (color && !_isBgImage(color)) form.classList.add('note-color-' + color);
|
||||
if (_isBgImage(color)) form.setAttribute('style', _customColorStyle(color));
|
||||
let currentImageUrl = _safeImgSrc(note?.image_url || '');
|
||||
form.innerHTML = `
|
||||
<div class="note-form-header">
|
||||
<input type="text" class="note-form-title" placeholder="Title" value="${_esc(note?.title || '')}" />
|
||||
<button type="button" class="note-form-icon-btn note-form-remind-btn${note?.due_date ? ' has-date' : ''}" title="Remind me">
|
||||
<svg width="31" height="31" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 0 1-3.46 0"/></svg>
|
||||
</button>
|
||||
<input type="hidden" class="note-form-due" value="${note?.due_date || ''}" />
|
||||
<input type="hidden" class="note-form-repeat" value="${note?.repeat || 'none'}" />
|
||||
</div>
|
||||
${currentImageUrl && type !== 'draw' ? `<div class="note-form-image-wrap"><img class="note-form-image" src="${_esc(currentImageUrl)}" draggable="false" /><button class="note-form-image-rm" title="Remove">×</button></div>` : ''}
|
||||
<div class="note-form-body">
|
||||
${type === 'note'
|
||||
? `<textarea class="note-form-content" placeholder="Take a note..." rows="4">${_esc(note?.content || '')}</textarea>`
|
||||
: type === 'draw'
|
||||
? _buildDrawHtml()
|
||||
: type === 'goal'
|
||||
? _buildGoalHtml(note, items)
|
||||
: _buildChecklistHtml(items)}
|
||||
</div>
|
||||
<div class="note-form-reminder-tags"></div>
|
||||
<div class="note-form-meta">
|
||||
<div class="note-form-type-seg${type === 'todo' ? ' is-todo' : type === 'draw' ? ' is-draw' : ''}" role="group">
|
||||
<button type="button" class="note-form-type-pill${type === 'note' ? ' active' : ''}" data-type="note">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="4" y1="6" x2="20" y2="6"/><line x1="4" y1="12" x2="20" y2="12"/><line x1="4" y1="18" x2="14" y2="18"/></svg>
|
||||
<span>Note</span>
|
||||
</button>
|
||||
<button type="button" class="note-form-type-pill${type === 'todo' ? ' active' : ''}" data-type="todo">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 11 12 14 22 4"/><path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"/></svg>
|
||||
<span>Todo</span>
|
||||
</button>
|
||||
<button type="button" class="note-form-type-pill${type === 'draw' ? ' active' : ''}" data-type="draw">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 19l7-7 3 3-7 7-3-3z"/><path d="M18 13l-1.5-7.5L2 2l3.5 14.5L13 18l5-5z"/><path d="M2 2l7.586 7.586"/><circle cx="11" cy="11" r="2"/></svg>
|
||||
<span>Draw</span>
|
||||
</button>
|
||||
</div>
|
||||
<button class="note-form-photo-btn" title="Attach photo">
|
||||
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>
|
||||
</button>
|
||||
<input type="file" class="note-form-photo-input" accept="image/*" capture="environment" style="display:none" />
|
||||
<div class="note-color-picker">
|
||||
${COLORS.map(c => `<span class="note-color-dot${_dotIsActive(c.value, color) ? ' active' : ''}" data-color="${c.value}" style="background:${_dotBg(c.value, color)}" title="${c.name || 'default'}"></span>`).join('')}
|
||||
</div>
|
||||
<input type="text" class="note-form-label" value="${_esc(note?.label || '')}" placeholder="#tag1 #tag2" title="Tag(s) — space-separated" />
|
||||
<div class="note-form-actions-group">
|
||||
${isEdit ? `
|
||||
<button type="button" class="note-form-text-btn note-form-archive-btn note-form-collapsible" title="Archive">
|
||||
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="3" width="20" height="5" rx="1"/><path d="M4 8v11a2 2 0 002 2h12a2 2 0 002-2V8"/><path d="M10 12h4"/></svg><span class="nft-label">Archive</span>
|
||||
</button>
|
||||
<button type="button" class="note-form-text-btn note-form-delete-btn note-form-collapsible danger" title="Delete">
|
||||
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/><line x1="10" y1="11" x2="10" y2="17"/><line x1="14" y1="11" x2="14" y2="17"/></svg><span class="nft-label">Delete</span>
|
||||
</button>
|
||||
` : ''}
|
||||
<span class="note-form-actions-spacer"></span>
|
||||
<button class="note-form-cancel note-form-text-btn note-form-collapsible" title="Close (keep changes)">
|
||||
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"><line x1="6" y1="6" x2="18" y2="18"/><line x1="18" y1="6" x2="6" y2="18"/></svg><span class="nft-label">Close</span>
|
||||
</button>
|
||||
<button class="note-form-save note-form-text-btn" title="${isEdit ? 'Update' : 'Save'}">
|
||||
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg><span class="nft-label">${isEdit ? 'Update' : 'Save'}</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
let currentType = type;
|
||||
let currentColor = color;
|
||||
// Stash original-form values so round-trips (Note→Todo→Note) restore the
|
||||
// user's hand-formatted text instead of a join of generated items. Same the
|
||||
// other way: if you started in todo, switch to note, switch back, items
|
||||
// come back unchanged.
|
||||
let _stashedNoteText = (type === 'note') ? (note?.content || '') : null;
|
||||
let _stashedTodoItems = (type === 'todo' && Array.isArray(note?.items)) ? note.items.slice() : null;
|
||||
// Goal mode kept its own pair of stashes (description + steps) so a
|
||||
// Todo→Goal→Todo round-trip wouldn't lose either side. The Goal pill in
|
||||
// the type picker was later removed, so the only entry point now is
|
||||
// *editing* an existing goal-typed note : but the switch handler still
|
||||
// accepts Goal→Todo/Note transitions (downgrading legacy goals), so
|
||||
// these stashes still earn their keep.
|
||||
let _stashedGoalDesc = (type === 'goal') ? (note?.content || '') : null;
|
||||
let _stashedGoalItems = (type === 'goal' && Array.isArray(note?.items)) ? note.items.slice() : null;
|
||||
|
||||
// Drawing also stashes the saved image URL so it survives Note↔Draw flips.
|
||||
let _stashedDrawUrl = (type === 'draw') ? (_safeImgSrc(note?.image_url) || null) : null;
|
||||
const _refreshFormLayout = () => {
|
||||
const body = form.closest('.notes-pane-body');
|
||||
if (!body) return;
|
||||
_applyMasonry(body);
|
||||
requestAnimationFrame(() => {
|
||||
_applyMasonry(body);
|
||||
requestAnimationFrame(() => _applyMasonry(body));
|
||||
});
|
||||
};
|
||||
|
||||
// Type segmented control : Note | Todo | Draw
|
||||
form.querySelectorAll('.note-form-type-pill').forEach(pill => {
|
||||
pill.addEventListener('click', () => {
|
||||
const newType = pill.dataset.type;
|
||||
if (newType === currentType) return;
|
||||
const bodyEl = form.querySelector('.note-form-body');
|
||||
// Stash whatever the user has in the current mode before swapping it
|
||||
// out, so a subsequent flip back restores their work.
|
||||
if (currentType === 'note') {
|
||||
_stashedNoteText = form.querySelector('.note-form-content')?.value || '';
|
||||
} else if (currentType === 'todo') {
|
||||
_stashedTodoItems = _collectItems(form);
|
||||
} else if (currentType === 'goal') {
|
||||
_stashedGoalDesc = form.querySelector('.note-form-goal-desc')?.value || '';
|
||||
_stashedGoalItems = _collectItems(form);
|
||||
} else if (currentType === 'draw') {
|
||||
const c = form.querySelector('.note-form-canvas');
|
||||
if (c) { try { _stashedDrawUrl = c.toDataURL('image/png'); } catch {} }
|
||||
}
|
||||
// Render the new mode's body and re-wire its inputs.
|
||||
if (newType === 'todo') {
|
||||
let nextItems;
|
||||
if (_stashedTodoItems && _stashedTodoItems.length) {
|
||||
nextItems = _stashedTodoItems;
|
||||
} else if (_stashedGoalItems && _stashedGoalItems.length) {
|
||||
// Going Goal→Todo keeps the AI-generated steps as a plain checklist.
|
||||
nextItems = _stashedGoalItems;
|
||||
} else if (_stashedNoteText) {
|
||||
const lines = _stashedNoteText.split('\n').map(s => s.trim()).filter(Boolean);
|
||||
nextItems = lines.length ? lines.map(t => ({ id: _uid(), text: t, done: false })) : [{ id: _uid(), text: '', done: false }];
|
||||
} else {
|
||||
nextItems = [{ id: _uid(), text: '', done: false }];
|
||||
}
|
||||
bodyEl.innerHTML = _buildChecklistHtml(nextItems);
|
||||
_wireChecklist(bodyEl);
|
||||
} else if (newType === 'draw') {
|
||||
bodyEl.innerHTML = _buildDrawHtml();
|
||||
// If the user just attached a photo (via the photo button) and then
|
||||
// toggled to Draw, paint that photo onto the canvas so they can draw
|
||||
// on top of it. _stashedDrawUrl wins if they were drawing earlier in
|
||||
// the same edit session.
|
||||
_wireCanvas(bodyEl, _stashedDrawUrl || currentImageUrl || _safeImgSrc(note?.image_url) || null);
|
||||
} else {
|
||||
const text = (_stashedNoteText !== null && _stashedNoteText !== undefined && _stashedNoteText !== '')
|
||||
? _stashedNoteText
|
||||
: (_stashedGoalDesc && _stashedGoalDesc)
|
||||
|| (_stashedTodoItems || _stashedGoalItems || []).map(i => i.text).join('\n');
|
||||
bodyEl.innerHTML = `<textarea class="note-form-content" placeholder="Take a note..." rows="4">${_esc(text)}</textarea>`;
|
||||
_wireHashtag(bodyEl.querySelector('.note-form-content'));
|
||||
}
|
||||
const focusEl = newType === 'note'
|
||||
? bodyEl.querySelector('.note-form-content')
|
||||
: newType === 'todo'
|
||||
? bodyEl.querySelector('.note-cl-text')
|
||||
: null;
|
||||
if (focusEl) {
|
||||
requestAnimationFrame(() => {
|
||||
focusEl.focus({ preventScroll: true });
|
||||
try {
|
||||
const end = focusEl.value.length;
|
||||
focusEl.setSelectionRange(end, end);
|
||||
} catch {}
|
||||
});
|
||||
}
|
||||
currentType = newType;
|
||||
const seg = form.querySelector('.note-form-type-seg');
|
||||
seg?.classList.toggle('is-todo', newType === 'todo');
|
||||
seg?.classList.toggle('is-draw', newType === 'draw');
|
||||
form.querySelectorAll('.note-form-type-pill').forEach(p => p.classList.toggle('active', p.dataset.type === newType));
|
||||
// The standalone image preview (form-image-wrap) and the canvas would
|
||||
// otherwise both show the same image_url when editing a drawn note.
|
||||
// Hide it in draw mode, restore it when leaving draw mode.
|
||||
const imgWrap = form.querySelector('.note-form-image-wrap');
|
||||
if (imgWrap) imgWrap.style.display = (newType === 'draw') ? 'none' : '';
|
||||
// The background-color dots set the note card's bg : they make no sense
|
||||
// for a drawn note (the canvas image IS the card content), so hide them.
|
||||
const bgPicker = form.querySelector('.note-color-picker');
|
||||
if (bgPicker) bgPicker.style.display = (newType === 'draw') ? 'none' : '';
|
||||
if (form.closest('.notes-pane.notes-view-grid') && window.matchMedia('(max-width: 768px)').matches) {
|
||||
form.style.gridColumn = '1 / -1';
|
||||
form.style.gridRowEnd = newType === 'draw' ? 'span 152' : 'span 64';
|
||||
}
|
||||
_refreshFormLayout();
|
||||
});
|
||||
});
|
||||
|
||||
// Slide a finger across the Note/Todo/Draw control to switch modes (mobile).
|
||||
// On touchmove we find the pill under the finger and click it : reusing the
|
||||
// pill click handler above, so the body re-renders + content stashing all
|
||||
// work. Only fires when crossing into a *different* pill.
|
||||
const _typeSeg = form.querySelector('.note-form-type-seg');
|
||||
if (_typeSeg) {
|
||||
let _sliding = false;
|
||||
const _activateAt = (x, y) => {
|
||||
const pill = document.elementFromPoint(x, y)?.closest?.('.note-form-type-pill');
|
||||
if (pill && !pill.classList.contains('active')) pill.click();
|
||||
};
|
||||
_typeSeg.addEventListener('touchstart', () => { _sliding = true; }, { passive: true });
|
||||
_typeSeg.addEventListener('touchmove', (e) => {
|
||||
if (_sliding && e.touches[0]) _activateAt(e.touches[0].clientX, e.touches[0].clientY);
|
||||
}, { passive: true });
|
||||
_typeSeg.addEventListener('touchend', () => { _sliding = false; });
|
||||
_typeSeg.addEventListener('touchcancel', () => { _sliding = false; });
|
||||
}
|
||||
|
||||
_wireFormColors(form, value => { currentColor = value; });
|
||||
|
||||
if (currentType === 'todo') _wireChecklist(form.querySelector('.note-form-body'));
|
||||
if (currentType === 'goal') _wireGoalForm(form, form.querySelector('.note-form-body'));
|
||||
if (currentType === 'draw') {
|
||||
_wireCanvas(form.querySelector('.note-form-body'), _safeImgSrc(note?.image_url) || null);
|
||||
// Same hides we apply on type-switch : keep them consistent on initial open.
|
||||
const _ip = form.querySelector('.note-form-image-wrap'); if (_ip) _ip.style.display = 'none';
|
||||
const _cp = form.querySelector('.note-color-picker'); if (_cp) _cp.style.display = 'none';
|
||||
}
|
||||
|
||||
// Auto-grow the plain-note textarea so editing longer notes is
|
||||
// comfortable : it expands with the content (up to a cap) instead of
|
||||
// staying a cramped 4-row box. The user can still drag-resize too.
|
||||
const _contentTa = form.querySelector('.note-form-content');
|
||||
if (_contentTa) {
|
||||
const _grow = () => {
|
||||
_contentTa.style.height = 'auto';
|
||||
// Inline form: cap at ~50vh so a huge note doesn't push the action
|
||||
// buttons off-screen. Fullscreen mobile overlay: the body scrolls and
|
||||
// there are no inline buttons crowding, so allow nearly the full height
|
||||
// : capping at 50vh there clipped longer notes ("part disappears").
|
||||
const inFullscreen = !!_contentTa.closest('.note-fullscreen-overlay');
|
||||
const max = Math.round(window.innerHeight * (inFullscreen ? 0.9 : 0.5));
|
||||
_contentTa.style.height = Math.min(_contentTa.scrollHeight, max) + 'px';
|
||||
};
|
||||
_contentTa.addEventListener('input', _grow);
|
||||
// Grow on open so existing content is fully visible. Run again after the
|
||||
// fullscreen overlay's open animation settles : measuring mid-animation
|
||||
// (the overlay starts scaled/transitioning) can under-size the box.
|
||||
setTimeout(_grow, 0);
|
||||
setTimeout(_grow, 360);
|
||||
}
|
||||
|
||||
_wireReminderPicker(form);
|
||||
|
||||
// Photo upload
|
||||
const photoBtn = form.querySelector('.note-form-photo-btn');
|
||||
const photoInput = form.querySelector('.note-form-photo-input');
|
||||
if (photoBtn && photoInput) {
|
||||
photoBtn.addEventListener('click', () => photoInput.click());
|
||||
photoInput.addEventListener('change', async () => {
|
||||
const file = photoInput.files?.[0];
|
||||
if (!file) return;
|
||||
const fd = new FormData();
|
||||
fd.append('files', file);
|
||||
try {
|
||||
const res = await api.upload(fd);
|
||||
const data = await res.json();
|
||||
const fileId = data.files?.[0]?.id;
|
||||
if (!fileId) throw new Error('Upload failed');
|
||||
currentImageUrl = api.uploadUrl(fileId);
|
||||
// Only ever keep the latest attached photo : drop any existing wrap
|
||||
// before inserting a fresh one. Picking a second photo replaces the
|
||||
// first instead of stacking.
|
||||
form.querySelector('.note-form-image-wrap')?.remove();
|
||||
const wrap = document.createElement('div');
|
||||
wrap.className = 'note-form-image-wrap';
|
||||
wrap.innerHTML = `<img class="note-form-image" draggable="false" /><button class="note-form-image-rm" title="Remove">×</button>`;
|
||||
// Insert AFTER the whole header (a flex-row), not after the
|
||||
// title input itself : otherwise the image lands as a sibling
|
||||
// of the title inside the header and flex puts them side-by-side.
|
||||
form.querySelector('.note-form-header').after(wrap);
|
||||
wrap.querySelector('.note-form-image-rm').addEventListener('click', () => { wrap.remove(); currentImageUrl = ''; });
|
||||
wrap.querySelector('img').src = currentImageUrl;
|
||||
} catch (err) { uiModule.showError('Image upload failed'); }
|
||||
photoInput.value = '';
|
||||
});
|
||||
}
|
||||
// Existing image remove
|
||||
form.querySelector('.note-form-image-rm')?.addEventListener('click', () => {
|
||||
form.querySelector('.note-form-image-wrap')?.remove();
|
||||
currentImageUrl = '';
|
||||
});
|
||||
|
||||
// Title Enter -> focus body (textarea or first checklist item)
|
||||
form.querySelector('.note-form-title').addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Enter' && !e.shiftKey && !e.ctrlKey && !e.metaKey) {
|
||||
e.preventDefault();
|
||||
const ta = form.querySelector('.note-form-content');
|
||||
if (ta) { ta.focus(); return; }
|
||||
const firstItem = form.querySelector('.note-cl-text');
|
||||
if (firstItem) firstItem.focus();
|
||||
}
|
||||
});
|
||||
|
||||
// Hashtag → label: typing "#foo " in title/content appends "foo" to the
|
||||
// space-separated tag list. Repeats are deduplicated, so #foo #foo only
|
||||
// keeps one. Tags already present in the label field are left alone.
|
||||
const labelInput = form.querySelector('.note-form-label');
|
||||
const _hashtagRe = /(^|\s)#([A-Za-z0-9][\w-]*)\s$/;
|
||||
function _wireHashtag(el) {
|
||||
if (!el || !labelInput) return;
|
||||
el.addEventListener('input', () => {
|
||||
const m = _hashtagRe.exec(el.value);
|
||||
if (!m) return;
|
||||
const tag = m[2];
|
||||
// Dedup against the stripped form : labelInput may already hold `#tag`
|
||||
// (after Enter normalised), so includes(tag) on the raw split would
|
||||
// miss the duplicate and append a bare `tag` next to `#tag`.
|
||||
const existing = labelInput.value.trim().split(/\s+/).filter(Boolean);
|
||||
const stripped = existing.map(t => t.replace(/^#+/, ''));
|
||||
if (!stripped.includes(tag)) {
|
||||
existing.push('#' + tag);
|
||||
labelInput.value = existing.join(' ');
|
||||
labelInput.classList.add('flash-once');
|
||||
setTimeout(() => labelInput.classList.remove('flash-once'), 600);
|
||||
}
|
||||
const cut = el.value.length - m[0].length + m[1].length;
|
||||
el.value = el.value.slice(0, cut);
|
||||
});
|
||||
}
|
||||
_wireHashtag(form.querySelector('.note-form-title'));
|
||||
_wireHashtag(form.querySelector('.note-form-content'));
|
||||
// Pressing Enter in the tag field commits the current word as its own tag
|
||||
// and parks the cursor after a trailing space, so the next word becomes a
|
||||
// separate tag rather than overwriting the previous one.
|
||||
labelInput?.addEventListener('keydown', (e) => {
|
||||
if (e.key !== 'Enter' || e.shiftKey || e.ctrlKey || e.metaKey) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
// Strip any leading #s the user typed, dedupe, then re-prepend exactly
|
||||
// one #. So typing "foo" or "#foo" both end up as "#foo " in the input;
|
||||
// the save handler keeps stripping #s before storing so DB stays clean.
|
||||
const tags = [...new Set(labelInput.value.split(/\s+/).map(t => t.replace(/^#+/, '').trim()).filter(Boolean))];
|
||||
if (!tags.length) return;
|
||||
labelInput.value = tags.map(t => '#' + t).join(' ') + ' ';
|
||||
labelInput.setSelectionRange(labelInput.value.length, labelInput.value.length);
|
||||
labelInput.classList.add('flash-once');
|
||||
setTimeout(() => labelInput.classList.remove('flash-once'), 600);
|
||||
});
|
||||
|
||||
// Shift+Enter (or Cmd/Ctrl+Enter) anywhere in the form -> save
|
||||
// Escape -> cancel edit
|
||||
form.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Enter' && (e.shiftKey || e.ctrlKey || e.metaKey)) {
|
||||
e.preventDefault();
|
||||
form.querySelector('.note-form-save')?.click();
|
||||
} else if (e.key === 'Escape') {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
form.querySelector('.note-form-cancel')?.click();
|
||||
}
|
||||
});
|
||||
|
||||
// Save. Prevent the button from stealing focus on press: on mobile, the
|
||||
// first tap would otherwise just blur the focused textarea/input (closing
|
||||
// the keyboard and shifting layout), so the tap never reached the button and
|
||||
// you had to tap "Done" twice. mousedown preventDefault keeps focus put while
|
||||
// still letting the click fire.
|
||||
const _saveBtnEl0 = form.querySelector('.note-form-save');
|
||||
_saveBtnEl0.addEventListener('mousedown', (e) => e.preventDefault());
|
||||
_saveBtnEl0.addEventListener('click', async () => {
|
||||
// Guard against spam-clicks: the drawing save AWAITS a canvas upload before
|
||||
// the optimistic re-render removes the form, so without this a slow upload
|
||||
// let repeated clicks create duplicate notes.
|
||||
const _saveBtn = form.querySelector('.note-form-save');
|
||||
if (_saveBtn._saving) return;
|
||||
// Mobile: when an existing note is opened and closed without edits, the
|
||||
// Update (✓) button morphs into Archive (set up below). Route the click
|
||||
// directly through the archive flow. Using a DOM .click() proxy here was
|
||||
// fragile on mobile because the real archive button can move from the
|
||||
// footer to the fullscreen header.
|
||||
if (_saveBtn.classList.contains('archive-mode')) {
|
||||
_archiveNoteById(note?.id);
|
||||
return;
|
||||
}
|
||||
_saveBtn._saving = true; _saveBtn.disabled = true; _saveBtn.style.opacity = '0.5';
|
||||
try {
|
||||
form._flushDraft?.();
|
||||
await form._stopDraftAutosave?.();
|
||||
form._flushDraft?.();
|
||||
const title = form.querySelector('.note-form-title').value.trim();
|
||||
// Normalize tag input: split on whitespace, strip leading #s, dedupe,
|
||||
// re-join with single spaces. Empty → null.
|
||||
const _rawLabel = form.querySelector('.note-form-label')?.value || '';
|
||||
const _tags = [...new Set(_rawLabel.split(/\s+/).map(t => t.replace(/^#+/, '').trim()).filter(Boolean))];
|
||||
if (form.querySelector('.note-form-due').value && !_tags.includes('reminder')) _tags.push('reminder');
|
||||
const labelVal = _tags.length ? _tags.join(' ') : null;
|
||||
const payload = {
|
||||
title,
|
||||
note_type: currentType,
|
||||
color: currentColor,
|
||||
label: labelVal,
|
||||
due_date: form.querySelector('.note-form-due').value || null,
|
||||
repeat: form.querySelector('.note-form-repeat')?.value || 'none',
|
||||
image_url: currentImageUrl || null,
|
||||
};
|
||||
if (currentType === 'note') {
|
||||
payload.content = form.querySelector('.note-form-content')?.value || '';
|
||||
} else if (currentType === 'draw') {
|
||||
// Upload the canvas PNG before saving so image_url points to a
|
||||
// persistent file. We block the save until upload completes : drawings
|
||||
// can't be re-rendered later without the URL.
|
||||
const canvas = form.querySelector('.note-form-canvas');
|
||||
const upload = await _uploadCanvasAsPng(canvas, note?.gallery_id || null);
|
||||
if (!upload?.url) { uiModule.showError('Failed to save drawing'); return; }
|
||||
payload.image_url = upload.url;
|
||||
if (upload.galleryId) payload.gallery_id = upload.galleryId;
|
||||
} else if (currentType === 'goal') {
|
||||
// Legacy: existing goal-type notes still edit through this branch.
|
||||
// No AI involvement : save as a normal note with description + items.
|
||||
payload.content = form.querySelector('.note-form-goal-desc')?.value || '';
|
||||
payload.items = _collectItems(form);
|
||||
} else {
|
||||
payload.items = _collectItems(form);
|
||||
}
|
||||
if (isEdit) payload.id = note.id;
|
||||
submitNote(payload, note, isEdit);
|
||||
} finally {
|
||||
// Re-enable on early returns / errors. On success the form is removed by
|
||||
// the optimistic re-render, so re-enabling the detached button is a no-op.
|
||||
_saveBtn._saving = false; _saveBtn.disabled = false; _saveBtn.style.opacity = '';
|
||||
}
|
||||
});
|
||||
|
||||
// Mobile-only: when editing an existing note, the Update (✓) button starts in
|
||||
// archive-mode (visually + behaviorally) and flips to Update on the first
|
||||
// edit. Lets the user tap a note to skim, then tap ✓ to archive without ever
|
||||
// touching a separate Archive button.
|
||||
if (isEdit && window.innerWidth <= 768) {
|
||||
const _saveLabelEl = _saveBtnEl0.querySelector('.nft-label');
|
||||
const _isFinishedTodo = () => {
|
||||
if (currentType !== 'todo') return false;
|
||||
const rows = [...form.querySelectorAll('.note-cl-row')];
|
||||
const withText = rows.filter(row => (row.querySelector('.note-cl-text')?.value || '').trim());
|
||||
return withText.length > 0 && withText.every(row => row.classList.contains('done'));
|
||||
};
|
||||
const _enterArchive = () => {
|
||||
_saveBtnEl0.classList.add('archive-mode');
|
||||
const label = _isFinishedTodo() ? 'Finish' : 'Archive';
|
||||
if (_saveLabelEl) _saveLabelEl.textContent = label;
|
||||
_saveBtnEl0.title = label;
|
||||
};
|
||||
const _enterUpdate = () => {
|
||||
if (!_saveBtnEl0.classList.contains('archive-mode')) return;
|
||||
_saveBtnEl0.classList.remove('archive-mode');
|
||||
if (_saveLabelEl) _saveLabelEl.textContent = 'Update';
|
||||
_saveBtnEl0.title = 'Update';
|
||||
};
|
||||
_enterArchive();
|
||||
form.addEventListener('input', _enterUpdate, true);
|
||||
form.addEventListener('change', _enterUpdate, true);
|
||||
// Checklist dots use a custom control and dispatch their update before
|
||||
// this click bubbles. Re-evaluate afterward so a fully completed todo
|
||||
// offers Finish (which archives/removes it from the active list).
|
||||
form.addEventListener('click', (event) => {
|
||||
if (!event.target.closest('.note-cl-dot')) return;
|
||||
setTimeout(() => {
|
||||
if (_isFinishedTodo()) _enterArchive();
|
||||
else _enterUpdate();
|
||||
}, 0);
|
||||
}, true);
|
||||
}
|
||||
|
||||
// Cancel
|
||||
form.querySelector('.note-form-cancel').addEventListener('click', () => { form._flushDraft?.(); app.setEditingId(null); _renderNotes(); });
|
||||
|
||||
// Archive / Delete : edit-mode-only buttons, mirror the (now-hidden) card actions.
|
||||
form.querySelector('.note-form-archive-btn')?.addEventListener('click', () => {
|
||||
if (!isEdit) return;
|
||||
_archiveNoteById(note.id);
|
||||
});
|
||||
form.querySelector('.note-form-delete-btn')?.addEventListener('click', () => {
|
||||
if (!isEdit) return;
|
||||
return deleteFromEditor(note.id);
|
||||
});
|
||||
|
||||
// Autosave a draft to persistence on every change so unsaved edits
|
||||
// survive connection loss / reload / accidental close.
|
||||
_wireDraftAutosave(form, isEdit ? note.id : '__new__');
|
||||
|
||||
return form;
|
||||
}
|
||||
|
||||
return { _buildForm };
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
/** Label chips, reminder/goal filters and collapsed tag-strip rendering. */
|
||||
import { _visibleNoteTags, _nextGoalStep } from '../domain/noteRules.js';
|
||||
import { _hasTimeComponent } from '../domain/recurrence.js';
|
||||
export function createFilters({
|
||||
NOTES_LABELS_COLLAPSED_KEY,
|
||||
_clearPastReminders,
|
||||
_esc,
|
||||
_isPastReminder,
|
||||
_renderNotes,
|
||||
_userVisibleNotes,
|
||||
app,
|
||||
persistence,
|
||||
state
|
||||
}) {
|
||||
function _renderLabels(root = document) {
|
||||
const bar = root.querySelector?.('.notes-labels-bar') || document.querySelector('.notes-labels-bar');
|
||||
if (!bar) return;
|
||||
if (state.labelsCollapsed) {
|
||||
bar.innerHTML = '';
|
||||
bar.style.display = 'none';
|
||||
return;
|
||||
}
|
||||
const visibleNotes = _userVisibleNotes();
|
||||
const labels = new Set();
|
||||
for (const n of visibleNotes) for (const t of _visibleNoteTags(n)) labels.add(t);
|
||||
const sortedLabels = [...labels].sort();
|
||||
// Count active reminders (not archived, has datetime due_date)
|
||||
const reminderCount = visibleNotes.filter(n => !n.archived && n.due_date && _hasTimeComponent(n.due_date)).length;
|
||||
const pastReminderCount = visibleNotes.filter(n => !n.archived && _isPastReminder(n)).length;
|
||||
const defaultCount = visibleNotes.filter(n => !n.archived && _visibleNoteTags(n).length === 0).length;
|
||||
// Active goals = non-archived goal notes. Today view lists pending steps
|
||||
// from each, so we surface the count next to the chip.
|
||||
const goalCount = visibleNotes.filter(n => n.note_type === 'goal' && !n.archived).length;
|
||||
const todayCount = visibleNotes.filter(n => n.note_type === 'goal' && !n.archived && _nextGoalStep(n)).length;
|
||||
const hasUsefulFilters = sortedLabels.length > 0 || reminderCount > 0 || goalCount > 0;
|
||||
const hasActiveFilter = state.activeLabel !== null || state.activeFilter !== null;
|
||||
if (!hasUsefulFilters && !hasActiveFilter) {
|
||||
bar.innerHTML = '';
|
||||
bar.style.display = 'none';
|
||||
return;
|
||||
}
|
||||
bar.style.display = '';
|
||||
const allActive = state.activeLabel === null && state.activeFilter === null;
|
||||
let html = `<button class="notes-label-chip${allActive ? ' active' : ''}" data-action="all">All</button>`;
|
||||
html += `<button class="notes-label-chip${state.activeFilter === 'default' ? ' active' : ''}" data-action="default" title="Show notes without tags">Default <span class="notes-label-chip-count">${defaultCount}</span></button>`;
|
||||
if (todayCount > 0) {
|
||||
const isOn = state.activeFilter === 'today';
|
||||
const icon = '<svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-1px;margin-right:2px"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>';
|
||||
html += `<button class="notes-label-chip notes-label-chip-today${isOn ? ' active' : ''}" data-action="today" title="Next step from every goal">${icon}Today <span class="notes-label-chip-count">${todayCount}</span></button>`;
|
||||
}
|
||||
if (goalCount > 0) {
|
||||
const isOn = state.activeFilter === 'goals';
|
||||
const icon = '<svg width="10" height="10" viewBox="0 0 24 24" fill="currentColor" style="vertical-align:-1px;margin-right:2px"><path d="M12 0L14.59 8.41L23 12L14.59 15.59L12 24L9.41 15.59L1 12L9.41 8.41Z"/></svg>';
|
||||
html += `<button class="notes-label-chip notes-label-chip-goals${isOn ? ' active' : ''}" data-action="goals" title="Show only goals">${icon}Goals <span class="notes-label-chip-count">${goalCount}</span></button>`;
|
||||
}
|
||||
const isReminderOn = state.activeFilter === 'reminders';
|
||||
const isReminderOff = state.activeFilter === 'no-reminders';
|
||||
const reminderCls = `notes-label-chip notes-label-chip-reminders${isReminderOn ? ' active' : ''}${isReminderOff ? ' active negated' : ''}`;
|
||||
const reminderIcon = isReminderOff
|
||||
// bell-off icon
|
||||
? '<svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-1px;margin-right:2px"><path d="M13.73 21a2 2 0 0 1-3.46 0"/><path d="M18.63 13A17.89 17.89 0 0 1 18 8"/><path d="M6.26 6.26A5.86 5.86 0 0 0 6 8c0 7-3 9-3 9h14"/><path d="M18 8a6 6 0 0 0-9.33-5"/><line x1="1" y1="1" x2="23" y2="23"/></svg>'
|
||||
: '<svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-1px;margin-right:2px"><path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 0 1-3.46 0"/></svg>';
|
||||
html += `<button class="${reminderCls}" data-action="reminders" title="${isReminderOn ? 'Showing only reminders — click to show all' : isReminderOff ? 'Hiding reminders — click to show only reminders' : 'Click to filter reminders'}">${reminderIcon}Reminders <span class="notes-label-chip-count">${reminderCount}</span></button>`;
|
||||
const showingReminders = state.activeFilter === 'reminders';
|
||||
if (showingReminders && pastReminderCount > 0) {
|
||||
html += `<button class="notes-label-chip notes-label-clear-past" data-action="clear-past-reminders" title="Delete reminders whose time has passed"><svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>Clear past <span class="notes-label-chip-count">${pastReminderCount}</span></button>`;
|
||||
}
|
||||
for (const lbl of sortedLabels) {
|
||||
html += `<button class="notes-label-chip${state.activeLabel === lbl ? ' active' : ''}" data-label="${_esc(lbl)}">#${_esc(lbl)}</button>`;
|
||||
}
|
||||
bar.innerHTML = html;
|
||||
bar.querySelectorAll('.notes-label-chip').forEach(chip => {
|
||||
chip.addEventListener('click', () => {
|
||||
if (chip.dataset.action === 'all') {
|
||||
app.setActiveLabel(null);
|
||||
app.setActiveFilter(null);
|
||||
} else if (chip.dataset.action === 'today') {
|
||||
app.setActiveLabel(null);
|
||||
app.setActiveFilter((state.activeFilter === 'today') ? null : 'today');
|
||||
} else if (chip.dataset.action === 'goals') {
|
||||
app.setActiveLabel(null);
|
||||
app.setActiveFilter((state.activeFilter === 'goals') ? null : 'goals');
|
||||
} else if (chip.dataset.action === 'default') {
|
||||
app.setActiveLabel(null);
|
||||
app.setActiveFilter((state.activeFilter === 'default') ? null : 'default');
|
||||
} else if (chip.dataset.action === 'reminders') {
|
||||
app.setActiveLabel(null);
|
||||
// Cycle: null → reminders → null → no-reminders → null → reminders → ...
|
||||
if (state.activeFilter === null) {
|
||||
app.setActiveFilter(state.reminderChipNext);
|
||||
app.setReminderChipNext((state.reminderChipNext === 'reminders') ? 'no-reminders' : 'reminders');
|
||||
} else {
|
||||
app.setActiveFilter(null);
|
||||
}
|
||||
} else if (chip.dataset.action === 'clear-past-reminders') {
|
||||
_clearPastReminders();
|
||||
return;
|
||||
} else {
|
||||
app.setActiveFilter(null);
|
||||
app.setActiveLabel(chip.dataset.label || null);
|
||||
}
|
||||
_renderNotes();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function _renderLabelsInto(_body) {
|
||||
if (!_body) return;
|
||||
const pane = _body.closest('.notes-pane');
|
||||
const toggleHost = pane?.querySelector('.notes-search-bar') || _body;
|
||||
let toggle = toggleHost.querySelector(':scope > .notes-label-toggle');
|
||||
if (!toggle) {
|
||||
toggle = document.createElement('button');
|
||||
toggle.type = 'button';
|
||||
toggle.className = 'notes-label-toggle cal-filter-toggle';
|
||||
toggle.addEventListener('click', () => {
|
||||
app.setLabelsCollapsed(!state.labelsCollapsed);
|
||||
try { persistence.setItem(NOTES_LABELS_COLLAPSED_KEY, state.labelsCollapsed ? '1' : '0'); } catch {}
|
||||
_renderNotes();
|
||||
});
|
||||
const selectButton = toggleHost.querySelector('#notes-select-btn');
|
||||
toggleHost.insertBefore(toggle, selectButton || null);
|
||||
}
|
||||
toggle.textContent = state.labelsCollapsed ? '+ Tags' : '− Tags';
|
||||
toggle.title = state.labelsCollapsed ? 'Show tags' : 'Hide tags';
|
||||
toggle.setAttribute('aria-expanded', state.labelsCollapsed ? 'false' : 'true');
|
||||
|
||||
// The shared chip scroller wraps this row once it is mounted.
|
||||
let bar = _body.querySelector('.notes-labels-bar');
|
||||
if (!bar) {
|
||||
bar = document.createElement('div');
|
||||
bar.className = 'notes-labels-bar';
|
||||
_body.appendChild(bar);
|
||||
}
|
||||
_renderLabels(_body);
|
||||
}
|
||||
|
||||
return { _renderLabels, _renderLabelsInto };
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
/** Card reflow animation and the owned masonry resize observer. */
|
||||
export function createLayout({ isOpen = () => true } = {}) {
|
||||
function _captureCardPositions() {
|
||||
const body = document.querySelector('#notes-pane .notes-pane-body');
|
||||
if (!body) return null;
|
||||
const positions = new Map();
|
||||
body.querySelectorAll('.note-card').forEach(card => {
|
||||
const id = card.dataset.noteId;
|
||||
if (id) positions.set(id, card.getBoundingClientRect());
|
||||
});
|
||||
return positions;
|
||||
}
|
||||
|
||||
function _animateReflow(prevPositions) {
|
||||
if (!prevPositions || !prevPositions.size) return;
|
||||
const body = document.querySelector('#notes-pane .notes-pane-body');
|
||||
if (!body || !body.isConnected) return;
|
||||
body.querySelectorAll('.note-card').forEach(card => {
|
||||
const id = card.dataset.noteId;
|
||||
const prev = prevPositions.get(id);
|
||||
if (!prev) return;
|
||||
const next = card.getBoundingClientRect();
|
||||
const dx = prev.left - next.left;
|
||||
const dy = prev.top - next.top;
|
||||
if (Math.abs(dx) < 1 && Math.abs(dy) < 1) return;
|
||||
// Invert: jump back to old position
|
||||
card.style.transition = 'none';
|
||||
card.style.transform = `translate(${dx}px, ${dy}px)`;
|
||||
// Play: animate to 0
|
||||
requestAnimationFrame(() => {
|
||||
card.style.transition = 'transform 0.25s cubic-bezier(0.34, 1.2, 0.64, 1)';
|
||||
card.style.transform = '';
|
||||
card.addEventListener('transitionend', () => {
|
||||
card.style.transition = '';
|
||||
}, { once: true });
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function _applyMasonry(body) {
|
||||
if (!body || !body.isConnected) return;
|
||||
const pane = body.closest('.notes-pane');
|
||||
const isGrid = pane?.classList.contains('notes-view-grid');
|
||||
const isMobileGrid = isGrid && window.matchMedia('(max-width: 768px)').matches;
|
||||
// Tear down any prior observer (defensive : _renderNotes wipes body.innerHTML).
|
||||
if (_masonryObserver) { try { _masonryObserver.disconnect(); } catch {} _masonryObserver = null; }
|
||||
// A save that resolves after close re-renders the leaving pane; don't
|
||||
// re-create the observer that panel teardown already disposed.
|
||||
if (!isOpen()) return;
|
||||
if (!isGrid) {
|
||||
// Clear any leftover inline spans so list view lays out normally.
|
||||
body.querySelectorAll('.note-card, .notes-label-toggle, .notes-labels-bar, .notes-quick-add, .note-form, .doclib-chip-scroll-frame:has(> .notes-labels-bar)').forEach(c => { c.style.gridRowEnd = ''; });
|
||||
return;
|
||||
}
|
||||
const ROW_PX = 4;
|
||||
const spanForHeight = (h) => Math.max(1, Math.ceil(h / ROW_PX));
|
||||
const recomputeFullRows = () => {
|
||||
const quickAdd = body.querySelector('.notes-quick-add');
|
||||
const labelsToggle = body.querySelector('.notes-label-toggle');
|
||||
const labelsBar = body.querySelector('.notes-labels-bar');
|
||||
const labelsLayout = labelsBar?.parentElement?.classList.contains('doclib-chip-scroll-frame')
|
||||
? labelsBar.parentElement
|
||||
: labelsBar;
|
||||
if (labelsToggle && getComputedStyle(labelsToggle).display !== 'none') {
|
||||
labelsToggle.style.gridRowEnd = `span ${Math.max(1, spanForHeight(labelsToggle.scrollHeight))}`;
|
||||
}
|
||||
if (labelsLayout && getComputedStyle(labelsLayout).display !== 'none') {
|
||||
const shave = isMobileGrid ? 4 : 0;
|
||||
labelsLayout.style.gridRowEnd = `span ${Math.max(1, spanForHeight(labelsLayout.scrollHeight) - shave)}`;
|
||||
}
|
||||
if (quickAdd) {
|
||||
const shave = isMobileGrid ? 4 : 0;
|
||||
quickAdd.style.gridRowEnd = `span ${Math.max(1, spanForHeight(quickAdd.scrollHeight + 10) - shave)}`;
|
||||
}
|
||||
body.querySelectorAll('.note-form').forEach(form => {
|
||||
form.style.gridColumn = '1 / -1';
|
||||
const isDrawForm = !!form.querySelector('.note-form-type-seg.is-draw');
|
||||
const minSpan = isMobileGrid ? (isDrawForm ? 104 : 64) : 1;
|
||||
const renderedHeight = form.getBoundingClientRect?.().height || 0;
|
||||
const drawReserve = isDrawForm && isMobileGrid ? 12 : 12;
|
||||
const measuredHeight = Math.max(form.scrollHeight, renderedHeight) + drawReserve;
|
||||
form.style.gridRowEnd = `span ${Math.max(minSpan, spanForHeight(measuredHeight))}`;
|
||||
});
|
||||
};
|
||||
const recompute = (card) => {
|
||||
// scrollHeight returns the natural content height : card.getBoundingClientRect()
|
||||
// would return the grid cell height (collapsed to 4px until the span is set,
|
||||
// which is the value we're trying to compute).
|
||||
const h = card.scrollHeight + (isMobileGrid ? 6 : 8);
|
||||
if (h <= 0) return;
|
||||
card.style.gridRowEnd = `span ${spanForHeight(h)}`;
|
||||
};
|
||||
recomputeFullRows();
|
||||
body.querySelectorAll('.note-card').forEach(recompute);
|
||||
// Watch masonry participants : content can grow (image load, todo edits,
|
||||
// quick-add/form expansion), and stale spans are what cause visual merging.
|
||||
if ('ResizeObserver' in window) {
|
||||
_masonryObserver = new ResizeObserver(entries => {
|
||||
let fullRowsChanged = false;
|
||||
for (const e of entries) {
|
||||
if (e.target.classList.contains('note-card')) recompute(e.target);
|
||||
else fullRowsChanged = true;
|
||||
}
|
||||
if (fullRowsChanged) recomputeFullRows();
|
||||
});
|
||||
body.querySelectorAll('.note-card').forEach(c => _masonryObserver.observe(c));
|
||||
body.querySelectorAll('.notes-label-toggle, .notes-quick-add, .note-form').forEach(c => _masonryObserver.observe(c));
|
||||
const labelsBar = body.querySelector('.notes-labels-bar');
|
||||
const labelsLayout = labelsBar?.parentElement?.classList.contains('doclib-chip-scroll-frame')
|
||||
? labelsBar.parentElement
|
||||
: labelsBar;
|
||||
if (labelsLayout) _masonryObserver.observe(labelsLayout);
|
||||
}
|
||||
}
|
||||
|
||||
let _masonryObserver = null;
|
||||
|
||||
function dispose() {
|
||||
_masonryObserver?.disconnect();
|
||||
_masonryObserver = null;
|
||||
}
|
||||
return { dispose, _captureCardPositions, _animateReflow, _applyMasonry };
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
/** Notes-owned document/window listeners. Detached editor/menu owners release their resources. */
|
||||
export function createNotesLifecycle() {
|
||||
const owners = new Map();
|
||||
let observer = null;
|
||||
function release(owner) {
|
||||
const entry = owners.get(owner);
|
||||
if (!entry) return;
|
||||
owners.delete(owner);
|
||||
for (const remove of entry.removers) remove();
|
||||
if (!owners.size) { observer?.disconnect(); observer = null; }
|
||||
}
|
||||
function onDispose(owner, remove) {
|
||||
if (!owner) throw new Error('Notes listener needs a lifecycle owner');
|
||||
let entry = owners.get(owner);
|
||||
if (!entry) {
|
||||
entry = { connected: owner.isConnected, removers: [] };
|
||||
owners.set(owner, entry);
|
||||
}
|
||||
entry.removers.push(remove);
|
||||
if (!observer) {
|
||||
observer = new MutationObserver(() => {
|
||||
for (const [node, scope] of owners) {
|
||||
if (node.isConnected) scope.connected = true;
|
||||
else if (scope.connected) release(node);
|
||||
}
|
||||
});
|
||||
observer.observe(document.body, { childList: true, subtree: true });
|
||||
}
|
||||
}
|
||||
function listen(owner, target, event, listener, options) {
|
||||
onDispose(owner, () => target.removeEventListener(event, listener, options));
|
||||
target.addEventListener(event, listener, options);
|
||||
}
|
||||
function dispose() { for (const owner of [...owners.keys()]) release(owner); }
|
||||
return { listen, onDispose, release, dispose };
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
/** Mobile fullscreen editing, link reader mode and return to the panel. */
|
||||
export function createMobileEditor({
|
||||
_applyDraftToNote,
|
||||
_buildForm,
|
||||
_fetchNotes,
|
||||
_linkify,
|
||||
_renderNotes,
|
||||
_uid,
|
||||
_wireChecklistTouchReorder,
|
||||
_wireRow,
|
||||
app,
|
||||
state,
|
||||
uiModule
|
||||
}) {
|
||||
function _isNotesMobileMode() {
|
||||
return ('ontouchstart' in window) && window.innerWidth <= 768;
|
||||
}
|
||||
|
||||
let _mobileFsOverlay = null;
|
||||
|
||||
let _mobileFsNoteId = null;
|
||||
|
||||
function _openMobileFullscreenEdit(id, fromCard) {
|
||||
const note = state.notes.find(n => n.id === id);
|
||||
if (!note) return;
|
||||
// Tear down any previous overlay (defensive).
|
||||
_closeMobileFullscreenEdit({ save: false });
|
||||
_mobileFsNoteId = id;
|
||||
app.setEditingId(id);
|
||||
|
||||
const overlay = document.createElement('div');
|
||||
overlay.className = 'note-fullscreen-overlay';
|
||||
overlay.innerHTML = `
|
||||
<div class="note-fullscreen-header">
|
||||
<button type="button" class="note-fullscreen-back" title="Back">
|
||||
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"></polyline></svg>
|
||||
</button>
|
||||
<div class="note-fullscreen-actions"></div>
|
||||
</div>
|
||||
<div class="note-fullscreen-body"></div>
|
||||
`;
|
||||
const body = overlay.querySelector('.note-fullscreen-body');
|
||||
// Reuse the same edit form the in-place flow builds. Save buttons,
|
||||
// checklist toggles, etc. all work as-is. Restore any unsaved draft.
|
||||
const { note: _n, restored } = _applyDraftToNote(note, id);
|
||||
const form = _buildForm(_n);
|
||||
body.appendChild(form);
|
||||
if (restored) uiModule.showToast('Restored unsaved changes');
|
||||
document.body.appendChild(overlay);
|
||||
_mobileFsOverlay = overlay;
|
||||
|
||||
// Animate up from the tapped tile's position so the transition reads
|
||||
// as a zoom rather than a hard cut.
|
||||
if (fromCard) {
|
||||
const r = fromCard.getBoundingClientRect();
|
||||
const vw = window.innerWidth, vh = window.innerHeight;
|
||||
overlay.style.transformOrigin =
|
||||
`${((r.left + r.width / 2) / vw) * 100}% ${((r.top + r.height / 2) / vh) * 100}%`;
|
||||
}
|
||||
overlay.classList.add('opening');
|
||||
requestAnimationFrame(() => overlay.classList.add('open'));
|
||||
|
||||
// Wire the back button : saves whatever the form has and closes.
|
||||
// mousedown preventDefault so it doesn't blur the input on first tap (which
|
||||
// would eat the tap and require a second one).
|
||||
const _backBtn = overlay.querySelector('.note-fullscreen-back');
|
||||
_backBtn.addEventListener('mousedown', (e) => e.preventDefault());
|
||||
_backBtn.addEventListener('click', () => {
|
||||
_closeMobileFullscreenEdit({ save: true });
|
||||
});
|
||||
|
||||
// The form's built-in Cancel only resets the in-place edit state; in
|
||||
// the overlay context it does nothing visible. Replace its handler so
|
||||
// Cancel actually dismisses the overlay without saving.
|
||||
const cancelBtn = form.querySelector('.note-form-cancel');
|
||||
if (cancelBtn) {
|
||||
const fresh = cancelBtn.cloneNode(true);
|
||||
cancelBtn.parentNode.replaceChild(fresh, cancelBtn);
|
||||
fresh.addEventListener('mousedown', (e) => e.preventDefault());
|
||||
fresh.addEventListener('click', (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
_closeMobileFullscreenEdit({ save: false });
|
||||
});
|
||||
}
|
||||
// The built-in Save handler does the API call + refresh, but doesn't
|
||||
// dismiss our overlay. Augment it (do NOT replace : the original is
|
||||
// async and we'd lose the API call) to schedule a close once the
|
||||
// save+render has had time to complete.
|
||||
const saveBtn = form.querySelector('.note-form-save');
|
||||
if (saveBtn) {
|
||||
saveBtn.addEventListener('click', () => {
|
||||
setTimeout(() => _closeMobileFullscreenEdit({ save: false }), 350);
|
||||
});
|
||||
}
|
||||
// Make the checklist row drag handle (⋮⋮) actually work on touch.
|
||||
// The form's default uses HTML5 native draggable which never fires
|
||||
// on iOS/Android. Wire touch-based reorder for any row inside the
|
||||
// overlay's checklist.
|
||||
_wireChecklistTouchReorder(form);
|
||||
|
||||
// For each todo row whose text contains a URL, swap the bare <input>
|
||||
// for a linkified <span> so URLs are tappable. Tapping anywhere that
|
||||
// ISN'T a link flips back to the input for editing.
|
||||
form.querySelectorAll('.note-cl-row').forEach(_addRowReadMode);
|
||||
|
||||
// Move only Delete from the form's footer actions row into the header.
|
||||
// Archive intentionally stays out of the header: the footer Update button
|
||||
// already morphs into the mobile Archive action for an untouched note.
|
||||
const headerActions = overlay.querySelector('.note-fullscreen-actions');
|
||||
const archiveBtn = form.querySelector('.note-form-archive-btn');
|
||||
const deleteBtn = form.querySelector('.note-form-delete-btn');
|
||||
if (headerActions && deleteBtn) {
|
||||
deleteBtn.classList.remove('note-form-collapsible');
|
||||
headerActions.appendChild(deleteBtn);
|
||||
}
|
||||
// The built-in archive/delete handlers re-render the notes grid but
|
||||
// leave THIS overlay sitting in front of it : looks like nothing
|
||||
// happened. Add follow-up listeners that close the overlay so the
|
||||
// user sees the action take effect.
|
||||
if (archiveBtn) {
|
||||
archiveBtn.addEventListener('click', () => {
|
||||
setTimeout(() => _closeMobileFullscreenEdit({ save: false }), 200);
|
||||
});
|
||||
}
|
||||
if (deleteBtn) {
|
||||
deleteBtn.addEventListener('click', () => {
|
||||
// Delete shows a styled confirm : give it room to resolve before
|
||||
// we try to dismiss the overlay.
|
||||
setTimeout(() => _closeMobileFullscreenEdit({ save: false }), 500);
|
||||
});
|
||||
}
|
||||
|
||||
// Tuck the tags input into the bottom actions row (Cancel / Update),
|
||||
// pinned to the LEFT. Frees the meta row of an extra wrapping line
|
||||
// and groups all the "exit" controls together.
|
||||
const actionsGroup = form.querySelector('.note-form-actions-group');
|
||||
const tagsInput = form.querySelector('.note-form-label');
|
||||
if (actionsGroup && tagsInput) {
|
||||
actionsGroup.insertBefore(tagsInput, actionsGroup.firstChild);
|
||||
}
|
||||
|
||||
// For checklist-type notes, move the photo (attach image) button into
|
||||
// the same row as the + Add button (right side) : keeps the meta row
|
||||
// tidy and puts the camera within thumb-reach of the active edit.
|
||||
const addBtn = form.querySelector('.note-cl-add');
|
||||
const photoBtn = form.querySelector('.note-form-photo-btn');
|
||||
if (addBtn && photoBtn) {
|
||||
const addRow = document.createElement('div');
|
||||
addRow.className = 'note-cl-add-row';
|
||||
addBtn.parentNode.insertBefore(addRow, addBtn);
|
||||
addRow.appendChild(addBtn);
|
||||
addRow.appendChild(photoBtn);
|
||||
// Tapping anywhere on the row (the empty gap, the dashed border,
|
||||
// the "+ Add" label) triggers add. The photo button keeps its own
|
||||
// click target so attach-image isn't ambushed.
|
||||
addRow.addEventListener('click', (e) => {
|
||||
if (e.target.closest('.note-form-photo-btn')) return;
|
||||
if (e.target === addBtn || addBtn.contains(e.target)) return;
|
||||
addBtn.click();
|
||||
});
|
||||
// The form's delegated "+ Add" handler does
|
||||
// inputs.insertBefore(newRow, addBtn)
|
||||
// : but addBtn is no longer a direct child of `.note-checklist-inputs`
|
||||
// now that we wrapped it. Bind a fresh handler that does the same
|
||||
// thing but inserts before the WRAPPING row, and stop propagation
|
||||
// so the broken delegate never runs.
|
||||
addBtn.addEventListener('click', (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
const inputs = form.querySelector('.note-checklist-inputs');
|
||||
if (!inputs) return;
|
||||
const newRow = document.createElement('div');
|
||||
newRow.className = 'note-cl-row';
|
||||
newRow.draggable = true;
|
||||
newRow.dataset.itemId = _uid();
|
||||
newRow.dataset.indent = '0';
|
||||
newRow.innerHTML = '<span class="note-cl-grip" title="Drag">⋮⋮</span><span class="note-cl-dot"></span><input type="text" class="note-cl-text" placeholder="Item..." /><button type="button" class="note-cl-rm">×</button>';
|
||||
inputs.insertBefore(newRow, addRow);
|
||||
_wireRow(newRow, inputs);
|
||||
// Touch reorder on the freshly-added row's grip.
|
||||
_wireChecklistTouchReorder(form);
|
||||
newRow.querySelector('.note-cl-text')?.focus();
|
||||
}, { capture: true });
|
||||
}
|
||||
|
||||
// Read-mode overlay for plain notes: render the content as a div with
|
||||
// clickable hyperlinks, layered above the textarea. Tapping anywhere
|
||||
// in the overlay that ISN'T a link hides the overlay and focuses the
|
||||
// textarea so the user can start editing. Tapping a link opens it.
|
||||
const ta = form.querySelector('.note-form-content');
|
||||
if (ta && (note.content || '').trim()) {
|
||||
const reader = document.createElement('div');
|
||||
reader.className = 'note-form-content-reader';
|
||||
reader.innerHTML = _linkify(note.content || '');
|
||||
ta.style.display = 'none';
|
||||
ta.insertAdjacentElement('beforebegin', reader);
|
||||
reader.addEventListener('click', (e) => {
|
||||
if (e.target.closest('a')) return; // let links open normally
|
||||
reader.remove();
|
||||
ta.style.display = '';
|
||||
// Let the browser place the cursor naturally : forcing
|
||||
// setSelectionRange right after focus() raced with the underlying
|
||||
// tap event and produced inconsistent cursor positions on mobile.
|
||||
ta.focus({ preventScroll: true });
|
||||
});
|
||||
}
|
||||
|
||||
// Opening an EXISTING note → read mode, no keyboard pop. Only a
|
||||
// brand-new note (created via the + button) should auto-focus an
|
||||
// input field. The user can tap the content to switch to edit.
|
||||
// (New-note creation flows through _createNote, not this function.)
|
||||
}
|
||||
|
||||
function _closeMobileFullscreenEdit(opts = {}) {
|
||||
if (!_mobileFsOverlay) return;
|
||||
const overlay = _mobileFsOverlay;
|
||||
overlay.querySelector('.note-form')?._flushDraft?.();
|
||||
_mobileFsOverlay = null;
|
||||
// If the form has a Save button, click it on close so edits aren't lost
|
||||
// when the user uses the back arrow instead of an explicit Save.
|
||||
if (opts.save) {
|
||||
const saveBtn = overlay.querySelector('.note-form-save, [data-action="save"]');
|
||||
if (saveBtn) try { saveBtn.click(); } catch {}
|
||||
}
|
||||
overlay.classList.remove('open');
|
||||
overlay.classList.add('closing');
|
||||
setTimeout(() => {
|
||||
if (overlay.parentNode) overlay.parentNode.removeChild(overlay);
|
||||
_mobileFsNoteId = null;
|
||||
app.setEditingId(null);
|
||||
// Refresh the grid so any save the user made is reflected.
|
||||
if (opts.save !== false) { _fetchNotes().then(_renderNotes).catch(() => {}); }
|
||||
}, 220);
|
||||
}
|
||||
|
||||
function _addRowReadMode(row) {
|
||||
const txt = row.querySelector('.note-cl-text');
|
||||
if (!txt) return;
|
||||
const val = txt.value || '';
|
||||
if (!/(https?:\/\/|www\.)/i.test(val)) return;
|
||||
if (row.querySelector('.note-cl-text-reader')) return; // already wired
|
||||
const span = document.createElement('span');
|
||||
span.className = 'note-cl-text-reader';
|
||||
span.innerHTML = _linkify(val);
|
||||
txt.style.display = 'none';
|
||||
txt.insertAdjacentElement('beforebegin', span);
|
||||
span.addEventListener('click', (e) => {
|
||||
if (e.target.closest('a')) return; // let the link open
|
||||
span.remove();
|
||||
txt.style.display = '';
|
||||
txt.focus({ preventScroll: true });
|
||||
});
|
||||
}
|
||||
|
||||
return { _isNotesMobileMode, _openMobileFullscreenEdit, _closeMobileFullscreenEdit, _addRowReadMode };
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
/** Mobile card long press, placeholder drag and reorder persistence. */
|
||||
export function createMobileReorder({
|
||||
lifecycle,
|
||||
_applyMasonry,
|
||||
_enterSelectMode,
|
||||
commitMobileOrder,
|
||||
app,
|
||||
}) {
|
||||
function _bindLongPressDrag(card) {
|
||||
let pressTimer = null;
|
||||
let startX = 0, startY = 0;
|
||||
let armed = false;
|
||||
const CANCEL_PX = 8;
|
||||
const HOLD_MS = 450;
|
||||
|
||||
card.addEventListener('touchstart', (e) => {
|
||||
// Don't fight scroll on touchpoints over real interactive children
|
||||
// (in mobile-mode they're CSS-hidden anyway, but be defensive).
|
||||
if (e.target.closest('button, input, a, .note-form')) return;
|
||||
if (e.touches.length !== 1) return;
|
||||
armed = true;
|
||||
startX = e.touches[0].clientX;
|
||||
startY = e.touches[0].clientY;
|
||||
pressTimer = setTimeout(() => {
|
||||
if (!armed) return;
|
||||
try { navigator.vibrate?.(15); } catch {}
|
||||
app.setSuppressNextNoteTapId(card.dataset.noteId);
|
||||
_enterSelectMode(card.dataset.noteId);
|
||||
}, HOLD_MS);
|
||||
}, { passive: true });
|
||||
card.addEventListener('touchmove', (e) => {
|
||||
if (!armed) return;
|
||||
const t = e.touches[0];
|
||||
if (Math.abs(t.clientX - startX) > CANCEL_PX || Math.abs(t.clientY - startY) > CANCEL_PX) {
|
||||
armed = false;
|
||||
if (pressTimer) { clearTimeout(pressTimer); pressTimer = null; }
|
||||
}
|
||||
}, { passive: true });
|
||||
const cancel = () => {
|
||||
armed = false;
|
||||
if (pressTimer) { clearTimeout(pressTimer); pressTimer = null; }
|
||||
};
|
||||
lifecycle.onDispose(card, cancel);
|
||||
card.addEventListener('touchend', cancel, { passive: true });
|
||||
card.addEventListener('touchcancel', cancel, { passive: true });
|
||||
}
|
||||
|
||||
let _dragState = null;
|
||||
|
||||
let _docDragHandlersBound = false;
|
||||
|
||||
function _enterDragMode(initialCard, initialTouch) {
|
||||
document.body.classList.add('notes-drag-mode');
|
||||
document.querySelectorAll('.note-card').forEach(_setupDragForCard);
|
||||
if (!_docDragHandlersBound) {
|
||||
lifecycle.listen(document.getElementById('notes-pane'), document, 'touchmove', _onDocTouchMove, { passive: false });
|
||||
lifecycle.listen(document.getElementById('notes-pane'), document, 'touchend', _onDocTouchEnd, { passive: true });
|
||||
lifecycle.listen(document.getElementById('notes-pane'), document, 'touchcancel', _onDocTouchEnd, { passive: true });
|
||||
_docDragHandlersBound = true;
|
||||
}
|
||||
// Auto-grab the card the user long-pressed : they're already holding
|
||||
// their finger on it, so begin the drag straight away. Releasing
|
||||
// (touchend) commits the reorder AND exits drag mode in one motion.
|
||||
if (initialCard && initialTouch) {
|
||||
_beginGrab(initialCard, initialTouch);
|
||||
}
|
||||
}
|
||||
|
||||
function _exitDragMode() {
|
||||
document.body.classList.remove('notes-drag-mode');
|
||||
if (_dragState) {
|
||||
// Defensive: if exit fires while a drag is in flight, snap the card back.
|
||||
_onDocTouchEnd();
|
||||
}
|
||||
// Leave _docDragHandlersBound true so re-entering drag mode reuses them.
|
||||
}
|
||||
|
||||
function _setupDragForCard(card) {
|
||||
if (card.dataset.dragBound === '1') return;
|
||||
card.dataset.dragBound = '1';
|
||||
card.addEventListener('touchstart', (e) => {
|
||||
if (!document.body.classList.contains('notes-drag-mode')) return;
|
||||
if (e.touches.length !== 1) return;
|
||||
if (_dragState) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
_beginGrab(card, e.touches[0]);
|
||||
}, { passive: false });
|
||||
}
|
||||
|
||||
function _beginGrab(card, touch) {
|
||||
const rect = card.getBoundingClientRect();
|
||||
const prevStyle = card.getAttribute('style') || '';
|
||||
// Placeholder fills the card's old slot so the grid layout doesn't reflow.
|
||||
const placeholder = document.createElement('div');
|
||||
placeholder.className = 'note-card-placeholder';
|
||||
placeholder.style.width = rect.width + 'px';
|
||||
placeholder.style.height = rect.height + 'px';
|
||||
placeholder.style.margin = getComputedStyle(card).margin;
|
||||
if (card.style.gridRowEnd) placeholder.style.gridRowEnd = card.style.gridRowEnd;
|
||||
const grid = card.parentNode;
|
||||
grid.insertBefore(placeholder, card);
|
||||
|
||||
// Detach the card visually : fixed-position, anchored to the finger.
|
||||
card.classList.add('note-card-dragging');
|
||||
card.style.position = 'fixed';
|
||||
card.style.left = rect.left + 'px';
|
||||
card.style.top = rect.top + 'px';
|
||||
card.style.width = rect.width + 'px';
|
||||
card.style.height = rect.height + 'px';
|
||||
card.style.margin = '0';
|
||||
card.style.zIndex = '10001';
|
||||
// pointer-events:none so elementFromPoint sees the card BENEATH the finger
|
||||
card.style.pointerEvents = 'none';
|
||||
|
||||
_dragState = {
|
||||
card, placeholder, grid, prevStyle,
|
||||
grabOffsetX: touch.clientX - rect.left,
|
||||
grabOffsetY: touch.clientY - rect.top,
|
||||
};
|
||||
try { navigator.vibrate?.(8); } catch {}
|
||||
}
|
||||
|
||||
function _onDocTouchMove(e) {
|
||||
if (!_dragState) return;
|
||||
if (e.touches.length !== 1) return;
|
||||
e.preventDefault();
|
||||
const touch = e.touches[0];
|
||||
const { card, placeholder, grid } = _dragState;
|
||||
card.style.left = (touch.clientX - _dragState.grabOffsetX) + 'px';
|
||||
const quickAdd = grid.querySelector('.notes-quick-add');
|
||||
const minTop = quickAdd ? quickAdd.getBoundingClientRect().bottom + 4 : grid.getBoundingClientRect().top;
|
||||
const maxTop = Math.max(minTop, window.innerHeight - card.getBoundingClientRect().height - 8);
|
||||
const nextTop = Math.max(minTop, Math.min(maxTop, touch.clientY - _dragState.grabOffsetY));
|
||||
card.style.top = nextTop + 'px';
|
||||
|
||||
const hitY = Math.max(minTop + 1, Math.min(window.innerHeight - 1, touch.clientY));
|
||||
const under = document.elementFromPoint(touch.clientX, hitY);
|
||||
const target = under && under.closest
|
||||
? under.closest('.note-card:not(.note-card-dragging)')
|
||||
: null;
|
||||
if (!target || target === card) return;
|
||||
if (target.parentNode !== grid) return;
|
||||
|
||||
// Move the PLACEHOLDER (not the card) above or below the target depending
|
||||
// on which half of the target the finger is in. This is the hysteresis
|
||||
// that stops the oscillation : once the placeholder moves past a card,
|
||||
// the cursor has to cross THAT card's midpoint in the other direction
|
||||
// to swap back.
|
||||
const tRect = target.getBoundingClientRect();
|
||||
const targetMidY = tRect.top + tRect.height / 2;
|
||||
if (touch.clientY < targetMidY) {
|
||||
if (placeholder.nextElementSibling !== target) {
|
||||
grid.insertBefore(placeholder, target);
|
||||
}
|
||||
} else {
|
||||
if (target.nextElementSibling !== placeholder) {
|
||||
grid.insertBefore(placeholder, target.nextElementSibling);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function _onDocTouchEnd() {
|
||||
if (!_dragState) return;
|
||||
const { card, placeholder, grid, prevStyle } = _dragState;
|
||||
_dragState = null;
|
||||
// Animate the card from its current fixed position to where the
|
||||
// placeholder sits, then re-parent and clear inline styles. Drag
|
||||
// mode auto-exits once the snap finishes : release = done.
|
||||
const phRect = placeholder.getBoundingClientRect();
|
||||
card.style.transition = 'left 0.2s ease, top 0.2s ease';
|
||||
card.style.left = phRect.left + 'px';
|
||||
card.style.top = phRect.top + 'px';
|
||||
setTimeout(() => {
|
||||
placeholder.parentNode.insertBefore(card, placeholder);
|
||||
placeholder.remove();
|
||||
card.classList.remove('note-card-dragging');
|
||||
// Restore the card's pre-drag inline styles. Mobile masonry stores
|
||||
// grid-row-end inline, and custom backgrounds use inline style too; wiping
|
||||
// cssText made dropped cards collapse into neighboring notes in grid view.
|
||||
if (prevStyle) card.setAttribute('style', prevStyle);
|
||||
else card.removeAttribute('style');
|
||||
_applyMasonry(grid);
|
||||
_commitNoteReorder();
|
||||
// One drag, one exit : release ends the rearrange session entirely.
|
||||
if (document.body.classList.contains('notes-drag-mode')) {
|
||||
document.body.classList.remove('notes-drag-mode');
|
||||
}
|
||||
}, 210);
|
||||
}
|
||||
|
||||
async function _commitNoteReorder() {
|
||||
const grid = document.querySelector('#notes-pane .notes-pane-body');
|
||||
if (!grid) return;
|
||||
const ids = Array.from(grid.querySelectorAll('.note-card')).map(c => c.dataset.noteId).filter(Boolean);
|
||||
if (!ids.length) return;
|
||||
await commitMobileOrder(ids);
|
||||
}
|
||||
|
||||
function dispose() {
|
||||
if (_dragState) {
|
||||
const { card, placeholder, prevStyle } = _dragState;
|
||||
_dragState = null;
|
||||
placeholder.parentNode?.insertBefore(card, placeholder);
|
||||
placeholder.remove();
|
||||
card.classList.remove('note-card-dragging');
|
||||
if (prevStyle) card.setAttribute('style', prevStyle);
|
||||
else card.removeAttribute('style');
|
||||
}
|
||||
document.body.classList.remove('notes-drag-mode');
|
||||
_docDragHandlersBound = false;
|
||||
}
|
||||
return { dispose, _bindLongPressDrag, _enterDragMode, _exitDragMode, _setupDragForCard, _beginGrab, _onDocTouchMove, _onDocTouchEnd, _commitNoteReorder };
|
||||
}
|
||||
@@ -0,0 +1,506 @@
|
||||
/** Panel mounting, keyboard handlers, minimization and note navigation. */
|
||||
export function createPanel({
|
||||
wireToolbar,
|
||||
wireSelectionActions,
|
||||
_wireNotesWindow,
|
||||
_restoreNotesSidebarDock,
|
||||
_bringNotesToFront,
|
||||
disposeUI,
|
||||
lifecycle,
|
||||
Modals,
|
||||
NOTES_FIRST_OPEN_HINT_KEY,
|
||||
REMINDER_DISMISSED_AT_KEY,
|
||||
_clearViewedReminderGlows,
|
||||
_closeMobileFullscreenEdit,
|
||||
_commitOpenInPlaceEditor,
|
||||
_copyNote,
|
||||
_enterSelectMode,
|
||||
_exitSelectMode,
|
||||
_fetchNotes,
|
||||
_flushPendingHighlights,
|
||||
_isNotesMobileMode,
|
||||
_popAndRunUndo,
|
||||
_renderLoadingSkeleton,
|
||||
_renderNotes,
|
||||
_startReminderLoop,
|
||||
app,
|
||||
bindTourHintDismiss,
|
||||
dismissOrRemove,
|
||||
persistence,
|
||||
state,
|
||||
workflows
|
||||
}) {
|
||||
function _forceCloseNotesPanel() {
|
||||
app.setOpen(false);
|
||||
app.setEditingId(null);
|
||||
try { _commitOpenInPlaceEditor(); } catch {}
|
||||
try { _closeMobileFullscreenEdit({ save: true }); } catch {}
|
||||
try { _clearViewedReminderGlows(); } catch {}
|
||||
if (_notesKeydownHandler) {
|
||||
document.removeEventListener('keydown', _notesKeydownHandler);
|
||||
_notesKeydownHandler = null;
|
||||
}
|
||||
if (_notesSelectEscHandler) {
|
||||
document.removeEventListener('keydown', _notesSelectEscHandler, true);
|
||||
_notesSelectEscHandler = null;
|
||||
}
|
||||
disposeOwnedPortals();
|
||||
disposeUI();
|
||||
document.body.classList.remove('notes-view', 'notes-mobile-mode', 'notes-drag-mode');
|
||||
document.getElementById('tool-notes-btn')?.classList.remove('active');
|
||||
try { Modals.unregister('notes-panel'); } catch {}
|
||||
try { document.getElementById('notes-pane')?.remove(); } catch {}
|
||||
try { document.getElementById('notes-pane-backdrop')?.remove(); } catch {}
|
||||
try { window._restoreSidebarIfRouteCollapsed?.(); } catch {}
|
||||
}
|
||||
|
||||
function _showNotesFirstOpenHint(pane) {
|
||||
if (!pane || typeof persistence === 'undefined') return;
|
||||
try {
|
||||
if (persistence.getItem(NOTES_FIRST_OPEN_HINT_KEY)) return;
|
||||
persistence.setItem(NOTES_FIRST_OPEN_HINT_KEY, '1');
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
|
||||
dismissOrRemove(document.getElementById('notes-first-open-hint'));
|
||||
const hint = document.createElement('div');
|
||||
hint.id = 'notes-first-open-hint';
|
||||
hint.className = 'tour-hint';
|
||||
hint.innerHTML = `
|
||||
<div class="tour-hint-text"><b>Notes</b> is your basic todo list, and also where reminders are managed.</div>
|
||||
<button type="button" class="tour-hint-dismiss">OK</button>
|
||||
`;
|
||||
document.body.appendChild(hint);
|
||||
|
||||
const place = () => {
|
||||
const r = pane.getBoundingClientRect();
|
||||
const hw = hint.offsetWidth || 260;
|
||||
hint.style.top = Math.max(12, r.top + 58) + 'px';
|
||||
hint.style.left = Math.min(window.innerWidth - hw - 12, Math.max(12, r.left + 18)) + 'px';
|
||||
};
|
||||
requestAnimationFrame(() => {
|
||||
place();
|
||||
hint.classList.add('tour-hint-in');
|
||||
});
|
||||
lifecycle.listen(hint, window, 'resize', place);
|
||||
bindTourHintDismiss(hint, {
|
||||
timeout: 6500,
|
||||
fade: 180,
|
||||
onDismiss: () => window.removeEventListener('resize', place),
|
||||
});
|
||||
}
|
||||
|
||||
function _ensureNotesChipRegistered() {
|
||||
if (Modals.isRegistered('notes-panel')) return;
|
||||
Modals.register('notes-panel', {
|
||||
railBtnId: 'rail-notes',
|
||||
sidebarBtnId: 'tool-notes-btn',
|
||||
restoreFn: () => { openPanel(); },
|
||||
closeFn: () => { _forceCloseNotesPanel(); },
|
||||
});
|
||||
}
|
||||
|
||||
function openPanel() {
|
||||
if (state.open) {
|
||||
_bringNotesToFront();
|
||||
return;
|
||||
}
|
||||
// Notes and the document editor occupy the same primary workspace. Preserve
|
||||
// an open document as a dock chip instead of allowing the two panes to stack
|
||||
// into a broken layout (or closing the user's document outright).
|
||||
try {
|
||||
if (window.documentModule?.isPanelOpen?.()) {
|
||||
window.documentModule.closePanel('down');
|
||||
}
|
||||
} catch (_) {}
|
||||
app.setOpen(true);
|
||||
app.setEditingId(null);
|
||||
app.setSearchQuery('');
|
||||
_clearViewedReminderGlows();
|
||||
app.setFiredDotDismissedAt(Date.now());
|
||||
try { persistence.setItem(REMINDER_DISMISSED_AT_KEY, String(state.firedDotDismissedAt)); } catch {}
|
||||
|
||||
const container = document.getElementById('chat-container');
|
||||
if (!container) return;
|
||||
|
||||
document.body.classList.add('notes-view');
|
||||
|
||||
// On mobile the notes panel takes the whole screen : auto-close the
|
||||
// sidebar so the panel isn't cropped underneath it.
|
||||
if (window.innerWidth <= 768) {
|
||||
const sb = document.getElementById('sidebar');
|
||||
if (sb) sb.classList.add('hidden');
|
||||
document.body.classList.add('sidebar-collapsed');
|
||||
}
|
||||
// Mobile mode: tiles become read-only previews (no inline checkbox /
|
||||
// edit / archive / etc.), tap opens a fullscreen edit overlay,
|
||||
// long-press enters drag-to-reorder mode. See _bindCardEvents +
|
||||
// .notes-mobile-mode CSS rules.
|
||||
if (_isNotesMobileMode()) document.body.classList.add('notes-mobile-mode');
|
||||
|
||||
// Toggle button state
|
||||
const btn = document.getElementById('tool-notes-btn');
|
||||
if (btn) btn.classList.add('active');
|
||||
|
||||
// Create panel
|
||||
const pane = document.createElement('div');
|
||||
pane.id = 'notes-pane';
|
||||
pane.className = 'notes-pane';
|
||||
pane.innerHTML = `
|
||||
<div class="notes-mobile-grabber" id="notes-mobile-grabber" aria-hidden="true"></div>
|
||||
<div class="notes-pane-header">
|
||||
<h4 class="notes-pane-title"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-2.5px;margin-right:6px"><path d="M5 3h10l4 4v14H5z"/><path d="M15 3v5h5"/><path d="M8 17.5 15.5 10l2.5 2.5L10.5 20H8z"/></svg>Notes</h4>
|
||||
<span style="flex:1"></span>
|
||||
<button id="notes-archive-toggle" class="doc-action-icon-btn notes-header-text-btn" title="View archive" style="opacity:0.8;gap:5px;">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="3" width="20" height="5" rx="1"/><path d="M4 8v11a2 2 0 002 2h12a2 2 0 002-2V8"/><path d="M10 12h4"/></svg>
|
||||
<span class="notes-header-btn-label">Archive</span>
|
||||
</button>
|
||||
<button id="notes-view-toggle" class="doc-action-icon-btn notes-header-text-btn" title="Toggle view" style="opacity:0.8;gap:5px;">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/></svg>
|
||||
<span class="notes-header-btn-label">Toggle</span>
|
||||
</button>
|
||||
<button id="notes-minimize-btn" class="modal-minimize-btn" title="Minimize" aria-label="Minimize notes" style="position:relative;left:2px;"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3.4" stroke-linecap="round" aria-hidden="true"><line x1="6" y1="18" x2="18" y2="18"/></svg></button>
|
||||
</div>
|
||||
<div class="notes-search-bar">
|
||||
<input type="text" id="notes-search" class="memory-search-input" placeholder="Search notes…" autocomplete="off" />
|
||||
<button id="notes-select-btn" class="notes-select-trigger" type="button">Select</button>
|
||||
</div>
|
||||
<div id="notes-bulk-bar" class="memory-bulk-bar hidden">
|
||||
<label class="memory-bulk-check-all"><input type="checkbox" id="notes-select-all" /> All</label>
|
||||
<span id="notes-selected-count">0 Selected</span>
|
||||
<span style="flex:1"></span>
|
||||
<button id="notes-send-agent" class="memory-toolbar-btn" disabled><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-2px;margin-right:5px;opacity:0.6"><path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"></path></svg>Send to Agent</button>
|
||||
<button id="notes-bulk-archive" class="memory-toolbar-btn" disabled>
|
||||
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-2px;margin-right:4px;"><rect x="2" y="3" width="20" height="5" rx="1"/><path d="M4 8v11a2 2 0 002 2h12a2 2 0 002-2V8"/><path d="M10 12h4"/></svg>Archive
|
||||
</button>
|
||||
<button id="notes-bulk-delete" class="memory-toolbar-btn danger" disabled>
|
||||
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-2px;margin-right:4px;"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/><line x1="10" y1="11" x2="10" y2="17"/><line x1="14" y1="11" x2="14" y2="17"/></svg>Delete
|
||||
</button>
|
||||
<button id="notes-bulk-cancel" class="memory-toolbar-btn active" title="Cancel selection" aria-label="Cancel selection">
|
||||
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
|
||||
</button>
|
||||
</div>
|
||||
<div class="notes-pane-body"></div>
|
||||
`;
|
||||
|
||||
// On mobile open as a full-screen bottom sheet (slide up), not the desktop
|
||||
// side panel. Set inline so it wins over the base .notes-pane rule regardless
|
||||
// of cascade specifics (the CSS @media override wasn't reliably applying,
|
||||
// which left it as a side panel squeezing the chat).
|
||||
if (window.innerWidth <= 768) {
|
||||
pane.style.position = 'fixed';
|
||||
pane.style.inset = '0';
|
||||
pane.style.width = '100%';
|
||||
pane.style.maxWidth = '100%';
|
||||
pane.style.zIndex = '170';
|
||||
pane.style.borderRadius = '14px 14px 0 0';
|
||||
pane.style.animation = 'sheet-enter 0.25s cubic-bezier(0.2, 0.8, 0.2, 1) both';
|
||||
pane.style.transformOrigin = 'bottom center';
|
||||
}
|
||||
|
||||
// Mount on body so Notes can behave like the other draggable windows. On
|
||||
// desktop it is immediately docked to the right by _restoreNotesSidebarDock.
|
||||
const backdrop = document.createElement('div');
|
||||
backdrop.className = 'notes-pane-backdrop';
|
||||
backdrop.id = 'notes-pane-backdrop';
|
||||
backdrop.addEventListener('click', (ev) => {
|
||||
if (ev.target === backdrop) closePanel('down');
|
||||
});
|
||||
backdrop.appendChild(pane);
|
||||
document.body.appendChild(backdrop);
|
||||
_wireNotesWindow(pane);
|
||||
_restoreNotesSidebarDock(pane);
|
||||
_bringNotesToFront(pane);
|
||||
|
||||
// Events
|
||||
// (Close chevron removed : swipe down on mobile, tool-rail toggle on desktop.)
|
||||
|
||||
// Mobile: swipe the grab handle / header down to dismiss (minimise to chip).
|
||||
// Mirrors the document sheet gesture : finger-following, velocity-based
|
||||
// dismiss, rubber-band on up-drag, spring snap-back.
|
||||
_wireNotesSwipeDismiss(pane.querySelector('.notes-mobile-grabber'), pane);
|
||||
_wireNotesSwipeDismiss(pane.querySelector('.notes-pane-header'), pane);
|
||||
|
||||
pane.addEventListener('pointerdown', () => _bringNotesToFront(pane), true);
|
||||
pane.addEventListener('focusin', () => _bringNotesToFront(pane), true);
|
||||
|
||||
const minBtn = document.getElementById('notes-minimize-btn');
|
||||
if (minBtn) minBtn.addEventListener('click', (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
closePanel('down');
|
||||
});
|
||||
wireToolbar(pane);
|
||||
// Select mode
|
||||
document.getElementById('notes-select-btn').addEventListener('click', () => {
|
||||
if (state.selectMode) _exitSelectMode(); else _enterSelectMode();
|
||||
});
|
||||
// Esc cancels select mode. Notes uses a toggle "Select" button rather
|
||||
// than a *-bulk-cancel button, so the global Esc-cancel handler in
|
||||
// keyboard-shortcuts.js can't reach it : handle it here. Capture phase
|
||||
// + stopPropagation so Esc cancels select instead of closing the panel.
|
||||
if (_notesSelectEscHandler) {
|
||||
document.removeEventListener('keydown', _notesSelectEscHandler, true);
|
||||
}
|
||||
_notesSelectEscHandler = (e) => {
|
||||
if (e.key === 'Escape' && state.selectMode) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
_exitSelectMode();
|
||||
}
|
||||
};
|
||||
document.addEventListener('keydown', _notesSelectEscHandler, true);
|
||||
wireSelectionActions();
|
||||
// Escape: exit select mode first (if active), otherwise close the panel.
|
||||
// Skip when the user is editing a form field : those have their own
|
||||
// ESC-to-cancel handlers and we don't want to nuke the whole panel
|
||||
// mid-edit.
|
||||
// Idempotent: remove any previous handler from a prior openPanel so
|
||||
// re-opening doesn't stack multiple handlers.
|
||||
if (_notesKeydownHandler) {
|
||||
document.removeEventListener('keydown', _notesKeydownHandler);
|
||||
_notesKeydownHandler = null;
|
||||
}
|
||||
_notesKeydownHandler = (e) => {
|
||||
if (!state.open) return;
|
||||
const t = e.target;
|
||||
const inField = t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable);
|
||||
// Ctrl/Cmd+Z anywhere in the panel : undo the last note action. Skip when
|
||||
// typing in a field so the browser's normal text-undo still works.
|
||||
if ((e.ctrlKey || e.metaKey) && (e.key === 'z' || e.key === 'Z') && !e.shiftKey) {
|
||||
if (inField) return;
|
||||
if (workflows.undoCount() === 0) return;
|
||||
e.preventDefault();
|
||||
_popAndRunUndo();
|
||||
return;
|
||||
}
|
||||
// Ctrl/Cmd+C while hovering a note card → copy that note. Skip when the
|
||||
// user is editing or has an active text selection (let the browser handle
|
||||
// a real text copy in that case).
|
||||
if ((e.ctrlKey || e.metaKey) && (e.key === 'c' || e.key === 'C') && !e.shiftKey && !e.altKey) {
|
||||
if (inField) return;
|
||||
const sel = window.getSelection?.();
|
||||
if (sel && sel.toString && sel.toString().length > 0) return;
|
||||
const hovered = document.querySelector('.note-card:hover');
|
||||
if (!hovered) return;
|
||||
const id = hovered.dataset.noteId;
|
||||
if (!id) return;
|
||||
e.preventDefault();
|
||||
// Flash the ⋯ menu button (copy now lives in that menu).
|
||||
const btn = hovered.querySelector('.note-card-corner-menu');
|
||||
_copyNote(id, btn);
|
||||
return;
|
||||
}
|
||||
if (e.key !== 'Escape') return;
|
||||
if (inField) return;
|
||||
if (state.selectMode) { _exitSelectMode(); return; }
|
||||
if (state.showingArchived) {
|
||||
// Mirror the archive toggle button: flip back to active notes.
|
||||
document.getElementById('notes-archive-toggle')?.click();
|
||||
return;
|
||||
}
|
||||
_forceCloseNotesPanel();
|
||||
};
|
||||
document.addEventListener('keydown', _notesKeydownHandler);
|
||||
|
||||
// Load : show skeleton immediately, then fetch
|
||||
_renderLoadingSkeleton();
|
||||
// Defer the highlight flush to the next frame so it runs *after* the cards
|
||||
// are committed to the DOM (and any FLIP animations have settled), giving
|
||||
// the querySelector lookups inside something to find.
|
||||
_fetchNotes().then(() => {
|
||||
if (!pane.isConnected || !state.open) { _startReminderLoop(); return; }
|
||||
_renderNotes();
|
||||
requestAnimationFrame(() => _flushPendingHighlights());
|
||||
_startReminderLoop();
|
||||
_showNotesFirstOpenHint(pane);
|
||||
});
|
||||
}
|
||||
|
||||
function closePanel(direction) {
|
||||
if (!state.open) return;
|
||||
app.setOpen(false);
|
||||
app.setEditingId(null);
|
||||
_clearViewedReminderGlows();
|
||||
const _minimize = direction === 'down';
|
||||
if (_minimize) {
|
||||
_ensureNotesChipRegistered();
|
||||
} else if (Modals.isRegistered('notes-panel')) {
|
||||
Modals.unregister('notes-panel');
|
||||
}
|
||||
|
||||
// Drop panel-owned keydown listeners. The reminder interval is page-owned.
|
||||
if (_notesKeydownHandler) {
|
||||
document.removeEventListener('keydown', _notesKeydownHandler);
|
||||
_notesKeydownHandler = null;
|
||||
}
|
||||
if (_notesSelectEscHandler) {
|
||||
document.removeEventListener('keydown', _notesSelectEscHandler, true);
|
||||
_notesSelectEscHandler = null;
|
||||
}
|
||||
|
||||
disposeOwnedPortals();
|
||||
disposeUI();
|
||||
document.body.classList.remove('notes-view');
|
||||
document.body.classList.remove('notes-mobile-mode');
|
||||
document.body.classList.remove('notes-drag-mode');
|
||||
// Closing the panel should PRESERVE in-progress edits, not drop them.
|
||||
// Commit any open in-place editor, and close the mobile fullscreen
|
||||
// overlay with save=true so the note is persisted.
|
||||
try { _commitOpenInPlaceEditor(); } catch {}
|
||||
_closeMobileFullscreenEdit({ save: true });
|
||||
// /notes route may have collapsed the wide sidebar to a rail; restore.
|
||||
try { window._restoreSidebarIfRouteCollapsed?.(); } catch (_) {}
|
||||
|
||||
const btn = document.getElementById('tool-notes-btn');
|
||||
if (btn) btn.classList.remove('active');
|
||||
|
||||
const pane = document.getElementById('notes-pane');
|
||||
const backdrop = document.getElementById('notes-pane-backdrop');
|
||||
if (pane) {
|
||||
// Scale-out + fade. Match the enter animation duration so close feels
|
||||
// like the same gesture played backwards.
|
||||
pane.classList.add('notes-pane-leaving');
|
||||
const _cleanup = () => {
|
||||
try { pane.remove(); } catch {}
|
||||
try { backdrop?.remove(); } catch {}
|
||||
};
|
||||
pane.addEventListener('animationend', _cleanup, { once: true });
|
||||
// Belt-and-braces: if animation is skipped (reduced motion / detached
|
||||
// tab) the listener won't fire; remove after the expected duration.
|
||||
setTimeout(_cleanup, 220);
|
||||
} else if (backdrop) {
|
||||
backdrop.remove();
|
||||
}
|
||||
// Show the dock chip for a swipe-down minimize (tap it to reopen).
|
||||
if (_minimize) { try { Modals.minimize('notes-panel'); } catch {} }
|
||||
}
|
||||
|
||||
function togglePanel() {
|
||||
if (state.open) closePanel();
|
||||
else openPanel();
|
||||
}
|
||||
|
||||
function isPanelOpen() { return state.open; }
|
||||
|
||||
async function openNote(noteId) {
|
||||
const wasOpen = !!(isPanelOpen && isPanelOpen());
|
||||
app.setShowingArchived(false);
|
||||
app.setActiveLabel(null);
|
||||
app.setActiveFilter(null);
|
||||
app.setSearchQuery('');
|
||||
if (!wasOpen) {
|
||||
openPanel();
|
||||
} else {
|
||||
_bringNotesToFront();
|
||||
const searchEl = document.getElementById('notes-search');
|
||||
if (searchEl) searchEl.value = '';
|
||||
const pane = document.getElementById('notes-pane');
|
||||
if (pane) pane.classList.remove('notes-pane-archive');
|
||||
const archiveBtn = document.getElementById('notes-archive-toggle');
|
||||
if (archiveBtn) archiveBtn.classList.remove('active');
|
||||
await _fetchNotes();
|
||||
_renderNotes();
|
||||
}
|
||||
// openPanel() kicks off _fetchNotes() asynchronously, so the cards for
|
||||
// newly-created notes may not be in the DOM yet. Poll until the card exists.
|
||||
if (!noteId) return;
|
||||
let tries = 0;
|
||||
const findAndFlash = () => {
|
||||
const card = document.querySelector(`.note-card[data-note-id="${noteId}"]`)
|
||||
|| document.querySelector(`.note-card[data-note-id^="${noteId.slice(0, 8)}"]`);
|
||||
if (card) {
|
||||
_smoothScrollToNoteCard(card);
|
||||
card.classList.add('note-card-flash');
|
||||
setTimeout(() => card.classList.remove('note-card-flash'), 1600);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
const tryNext = () => {
|
||||
if (findAndFlash()) return;
|
||||
if (++tries < 20) setTimeout(tryNext, 200);
|
||||
};
|
||||
setTimeout(tryNext, 120);
|
||||
}
|
||||
|
||||
let _notesKeydownHandler = null;
|
||||
|
||||
let _notesSelectEscHandler = null;
|
||||
|
||||
function _wireNotesSwipeDismiss(el, pane) {
|
||||
if (!el || !pane) return;
|
||||
const DISMISS_THRESHOLD = 50, VELOCITY_THRESHOLD = 0.3, RUBBER = 0.35;
|
||||
let startY = 0, startX = 0, lastY = 0, lastT = 0, velocity = 0;
|
||||
let dragging = false, cancelled = false;
|
||||
|
||||
el.addEventListener('touchstart', (e) => {
|
||||
if (window.innerWidth > 768 || e.touches.length !== 1) return;
|
||||
if (e.target.closest('button, input, select, label, textarea')) return;
|
||||
const t = e.touches[0];
|
||||
startY = t.clientY; startX = t.clientX; lastY = startY; lastT = e.timeStamp;
|
||||
velocity = 0; dragging = false; cancelled = false;
|
||||
}, { passive: true });
|
||||
|
||||
el.addEventListener('touchmove', (e) => {
|
||||
if (cancelled || window.innerWidth > 768) return;
|
||||
const t = e.touches[0];
|
||||
const dx = Math.abs(t.clientX - startX);
|
||||
const dy = t.clientY - startY;
|
||||
if (!dragging) {
|
||||
if (dx > 40 && dx > Math.abs(dy) * 2) { cancelled = true; return; }
|
||||
if (Math.abs(dy) > 8) {
|
||||
dragging = true;
|
||||
pane.style.animation = 'none';
|
||||
pane.style.transition = 'none';
|
||||
pane.style.willChange = 'transform';
|
||||
} else return;
|
||||
}
|
||||
const dt = e.timeStamp - lastT;
|
||||
if (dt > 0) velocity = velocity * 0.6 + ((t.clientY - lastY) / dt) * 0.4;
|
||||
lastY = t.clientY; lastT = e.timeStamp;
|
||||
e.preventDefault();
|
||||
pane.style.transform = dy > 0 ? `translateY(${dy}px)` : `translateY(${dy * RUBBER}px)`;
|
||||
}, { passive: false });
|
||||
|
||||
const endSwipe = () => {
|
||||
if (!dragging) return;
|
||||
dragging = false;
|
||||
pane.style.willChange = '';
|
||||
const dy = lastY - startY;
|
||||
if (dy > DISMISS_THRESHOLD || (dy > 20 && velocity > VELOCITY_THRESHOLD)) {
|
||||
// Slide fully off-screen, then minimise. Keep it translated down (don't
|
||||
// reset) so it doesn't flash back before closePanel removes it.
|
||||
pane.style.transition = 'transform 0.2s cubic-bezier(0.2, 0, 0.4, 1)';
|
||||
pane.style.transform = 'translateY(100%)';
|
||||
setTimeout(() => closePanel('down'), 200);
|
||||
} else {
|
||||
pane.style.transition = 'transform 0.25s cubic-bezier(0.2, 0.9, 0.3, 1.05)';
|
||||
pane.style.transform = '';
|
||||
setTimeout(() => { pane.style.transition = ''; }, 260);
|
||||
}
|
||||
};
|
||||
el.addEventListener('touchend', endSwipe, { passive: true });
|
||||
el.addEventListener('touchcancel', endSwipe, { passive: true });
|
||||
}
|
||||
|
||||
function _smoothScrollToNoteCard(card) {
|
||||
if (!card) return;
|
||||
const scroller = card.closest('.notes-pane-body');
|
||||
if (!scroller) {
|
||||
try { card.scrollIntoView({ block: 'center', behavior: 'smooth' }); } catch (_) {}
|
||||
return;
|
||||
}
|
||||
const scrollerRect = scroller.getBoundingClientRect();
|
||||
const cardRect = card.getBoundingClientRect();
|
||||
const delta = (cardRect.top - scrollerRect.top) - (scroller.clientHeight - cardRect.height) / 2;
|
||||
scroller.scrollTo({ top: Math.max(0, scroller.scrollTop + delta), behavior: 'smooth' });
|
||||
}
|
||||
|
||||
function disposeOwnedPortals() {
|
||||
document.querySelectorAll('.note-reminder-menu, .note-corner-menu-dropdown, #notes-first-open-hint').forEach(dismissOrRemove);
|
||||
}
|
||||
|
||||
return { _forceCloseNotesPanel, openPanel, closePanel, togglePanel, isPanelOpen, openNote, _smoothScrollToNoteCard };
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
/** Quick-add expansion, draft restoration and opening inline editors. */
|
||||
export function createQuickAdd({
|
||||
_applyDraftToNote,
|
||||
_applyMasonry,
|
||||
_buildForm,
|
||||
app,
|
||||
openPanel,
|
||||
state,
|
||||
uiModule
|
||||
}) {
|
||||
function _renderQuickAdd(body) {
|
||||
const wrap = document.createElement('div');
|
||||
wrap.className = 'notes-quick-add';
|
||||
// 2-pill Note/Todo toggle mirrors the full form's type-seg (minus Draw :
|
||||
// drawing happens in the expanded form). The pill that's active steers
|
||||
// both the placeholder and the type the form opens in.
|
||||
wrap.innerHTML = `
|
||||
<div class="notes-quick-type-seg is-todo" role="group" aria-label="New item type">
|
||||
<button type="button" class="notes-quick-type-pill" data-type="note" aria-label="Note" aria-pressed="false" title="Note">
|
||||
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><line x1="4" y1="6" x2="20" y2="6"/><line x1="4" y1="12" x2="20" y2="12"/><line x1="4" y1="18" x2="14" y2="18"/></svg>
|
||||
</button>
|
||||
<button type="button" class="notes-quick-type-pill active" data-type="todo" aria-label="To-do" aria-pressed="true" title="To-do">
|
||||
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="9 11 12 14 22 4"/><path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"/></svg>
|
||||
</button>
|
||||
</div>
|
||||
<input type="text" class="notes-quick-input" placeholder="Add a to-do…" />
|
||||
<button class="notes-quick-icon" data-action="photo" title="Attach photo">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>
|
||||
</button>
|
||||
`;
|
||||
body.appendChild(wrap);
|
||||
|
||||
const input = wrap.querySelector('.notes-quick-input');
|
||||
const seg = wrap.querySelector('.notes-quick-type-seg');
|
||||
let currentType = 'todo';
|
||||
const setType = (t) => {
|
||||
if (t !== 'note' && t !== 'todo') return;
|
||||
currentType = t;
|
||||
seg.classList.toggle('is-todo', t === 'todo');
|
||||
seg.classList.toggle('is-note', t === 'note');
|
||||
seg.querySelectorAll('.notes-quick-type-pill').forEach(p => {
|
||||
const on = p.dataset.type === t;
|
||||
p.classList.toggle('active', on);
|
||||
p.setAttribute('aria-pressed', on ? 'true' : 'false');
|
||||
});
|
||||
input.placeholder = t === 'note' ? 'Add a note…' : 'Add a to-do…';
|
||||
};
|
||||
seg.querySelectorAll('.notes-quick-type-pill').forEach(p => {
|
||||
p.addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
setType(p.dataset.type);
|
||||
});
|
||||
});
|
||||
// Click input or type → expand to full form
|
||||
const expandToForm = (initialType = 'note', initialText = '') => {
|
||||
app.setEditingId('__new__');
|
||||
const form = _buildForm({ note_type: initialType });
|
||||
form.classList.add('note-form-new');
|
||||
if (initialText) {
|
||||
const titleEl = form.querySelector('.note-form-title');
|
||||
if (titleEl) titleEl.value = initialText;
|
||||
}
|
||||
const mobileGrid = body.closest('.notes-pane')?.classList.contains('notes-view-grid')
|
||||
&& window.matchMedia('(max-width: 768px)').matches;
|
||||
if (mobileGrid) {
|
||||
form.style.gridColumn = '1 / -1';
|
||||
form.style.gridRowEnd = 'span 64';
|
||||
}
|
||||
wrap.replaceWith(form);
|
||||
_applyMasonry(body);
|
||||
requestAnimationFrame(() => _applyMasonry(body));
|
||||
const titleEl = form.querySelector('.note-form-title');
|
||||
if (titleEl) {
|
||||
titleEl.focus();
|
||||
// Move caret to end
|
||||
titleEl.setSelectionRange(titleEl.value.length, titleEl.value.length);
|
||||
}
|
||||
};
|
||||
// Expand only on real intent: a click directly on the input, or actual
|
||||
// typing. Focus alone : including focus stolen from a missed nearby
|
||||
// click : no longer creates an empty form.
|
||||
input.addEventListener('click', () => expandToForm(currentType, input.value));
|
||||
input.addEventListener('input', () => expandToForm(currentType, input.value));
|
||||
wrap.querySelector('[data-action="photo"]').addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
expandToForm(currentType);
|
||||
// Trigger photo input on the new form
|
||||
setTimeout(() => document.querySelector('.note-form-photo-btn')?.click(), 50);
|
||||
});
|
||||
}
|
||||
|
||||
function _createNote(type = 'todo') {
|
||||
const body = document.querySelector('#notes-pane .notes-pane-body');
|
||||
if (!body || state.editingId === '__new__') return;
|
||||
app.setEditingId('__new__');
|
||||
// Restore an unsaved new-note draft if one survived a prior close/loss.
|
||||
const { note: _n, restored } = _applyDraftToNote({ note_type: type }, '__new__');
|
||||
const form = _buildForm(_n);
|
||||
form.classList.add('note-form-new');
|
||||
body.prepend(form);
|
||||
const initialField = type === 'note'
|
||||
? form.querySelector('.note-form-content')
|
||||
: form.querySelector('.note-cl-text, .note-form-title');
|
||||
initialField?.focus();
|
||||
if (restored) uiModule.showToast('Restored unsaved note');
|
||||
}
|
||||
|
||||
function newNote() {
|
||||
if (!state.open) openPanel();
|
||||
requestAnimationFrame(() => _createNote('note'));
|
||||
}
|
||||
|
||||
function _editNote(id) {
|
||||
const note = state.notes.find(n => n.id === id);
|
||||
if (!note) return;
|
||||
app.setEditingId(id);
|
||||
const card = document.querySelector(`.note-card[data-note-id="${id}"]`);
|
||||
if (!card) return;
|
||||
// Restore an unsaved draft (from a prior connection loss / close) over
|
||||
// the saved note so the user picks up where they left off.
|
||||
const { note: _n, restored } = _applyDraftToNote(note, id);
|
||||
const form = _buildForm(_n);
|
||||
card.replaceWith(form);
|
||||
if (restored) uiModule.showToast('Restored unsaved changes');
|
||||
// Pinned notes live in the first masonry column : the edit form has
|
||||
// column-span:all, which can leave the form rendered above the fold or
|
||||
// visually buried under neighboring pinned cards. Bring it into view
|
||||
// (and onto a higher stacking context) so editing a pinned note always
|
||||
// pops to the top.
|
||||
form.style.position = 'relative';
|
||||
form.style.zIndex = '5';
|
||||
// Grid view: the form keeps the CSS default `grid-row-end: span 16` (64px)
|
||||
// after replaceWith, which is much shorter than the actual form. Recompute
|
||||
// masonry so the form gets the correct row span and cards below stop
|
||||
// overlapping it. ResizeObserver inside _applyMasonry keeps it in sync as
|
||||
// the user types / adds checklist items.
|
||||
const _body = form.closest('.notes-pane-body');
|
||||
if (_body) {
|
||||
_applyMasonry(_body);
|
||||
requestAnimationFrame(() => _applyMasonry(_body));
|
||||
}
|
||||
requestAnimationFrame(() => {
|
||||
try { form.scrollIntoView({ block: 'center', behavior: 'smooth' }); }
|
||||
catch { form.scrollIntoView(); }
|
||||
});
|
||||
// Pick the most useful field to focus. On phones especially, the user
|
||||
// taps Edit to type : landing in the title when there's already a title
|
||||
// (and likely a body to extend) loses momentum. Prefer the body textarea
|
||||
// for plain notes, the first checklist item for todos, fall back to title.
|
||||
const _focusBest = () => {
|
||||
if (note.note_type === 'note' || !note.note_type) {
|
||||
const ta = form.querySelector('.note-form-content');
|
||||
if (ta) { ta.focus(); try { ta.setSelectionRange(ta.value.length, ta.value.length); } catch {} return; }
|
||||
}
|
||||
if (note.note_type === 'todo' || note.note_type === 'goal' || note.note_type === 'checklist') {
|
||||
// Last non-empty checklist row, or the first row if all empty.
|
||||
const rows = form.querySelectorAll('.note-cl-row .note-cl-text');
|
||||
let target = null;
|
||||
for (const inp of rows) { if ((inp.value || '').trim()) target = inp; }
|
||||
target = target || rows[0];
|
||||
if (target) { target.focus(); try { target.setSelectionRange(target.value.length, target.value.length); } catch {} return; }
|
||||
}
|
||||
const titleEl = form.querySelector('.note-form-title');
|
||||
if (titleEl) titleEl.focus();
|
||||
};
|
||||
_focusBest();
|
||||
}
|
||||
|
||||
return { _renderQuickAdd, _createNote, newNote, _editNote };
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
/** Reminder badges, sticky card highlights and entry scrolling. */
|
||||
import { _isNoteFullyDone } from '../domain/noteRules.js';
|
||||
import { _hasTimeComponent } from '../domain/recurrence.js';
|
||||
export function createReminderDisplay({
|
||||
_countFiredReminders,
|
||||
_hasActiveReminder,
|
||||
_loadActiveHighlights,
|
||||
_loadGlowedReminders,
|
||||
_loadPendingHighlights,
|
||||
_saveActiveHighlights,
|
||||
_saveGlowedReminders,
|
||||
_savePendingHighlights,
|
||||
_smoothScrollToNoteCard,
|
||||
state
|
||||
}) {
|
||||
function _clearViewedReminderGlows() {
|
||||
const active = _loadActiveHighlights();
|
||||
if (!active.size) return;
|
||||
_saveActiveHighlights(new Set());
|
||||
document.querySelectorAll('.note-card-reminder-fired-sticky').forEach(card => {
|
||||
card.classList.remove('note-card-reminder-fired-sticky');
|
||||
});
|
||||
}
|
||||
|
||||
function _setReminderCardGlow(noteId, on = true) {
|
||||
if (!noteId) return;
|
||||
const active = _loadActiveHighlights();
|
||||
if (on) active.add(noteId);
|
||||
else active.delete(noteId);
|
||||
_saveActiveHighlights(active);
|
||||
document.querySelectorAll(`.note-card[data-note-id="${noteId}"]`).forEach(card => {
|
||||
card.classList.toggle('note-card-reminder-fired-sticky', on);
|
||||
});
|
||||
}
|
||||
|
||||
function _queuePendingHighlight(noteId) {
|
||||
const set = _loadPendingHighlights();
|
||||
set.add(noteId);
|
||||
_savePendingHighlights(set);
|
||||
}
|
||||
|
||||
function _flushPendingHighlights() {
|
||||
// Fresh firings (queued by the background loop while the panel was closed)
|
||||
// glow unconditionally : a notification just told the user something
|
||||
// happened, so we always point at the note even if it was glowed before.
|
||||
const queued = _loadPendingHighlights();
|
||||
const glowed = _loadGlowedReminders();
|
||||
const toGlow = new Set(queued);
|
||||
// For notes that are merely overdue at open time (no fresh firing event),
|
||||
// only glow the ones we haven't already shown : otherwise reopening the
|
||||
// panel keeps lighting up old reminders forever.
|
||||
for (const n of state.notes) {
|
||||
if (!_hasActiveReminder(n) || !_hasTimeComponent(n.due_date)) continue;
|
||||
if (queued.has(n.id) || !glowed.has(n.id)) toGlow.add(n.id);
|
||||
}
|
||||
// Always consume the queue.
|
||||
_savePendingHighlights(new Set());
|
||||
if (!toGlow.size) return;
|
||||
let firstCard = null;
|
||||
for (const id of toGlow) {
|
||||
const card = document.querySelector(`.note-card[data-note-id="${id}"]`);
|
||||
if (!card) continue;
|
||||
_setReminderCardGlow(id, true);
|
||||
if (!firstCard) firstCard = card;
|
||||
glowed.add(id);
|
||||
}
|
||||
_saveGlowedReminders(glowed);
|
||||
// Bring the first one into view so it can't get buried below the fold.
|
||||
if (firstCard) {
|
||||
requestAnimationFrame(() => {
|
||||
_smoothScrollToNoteCard(firstCard);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function _updateRailBadge() {
|
||||
const fired = _countFiredReminders();
|
||||
// Rail (mini sidebar) : only show the count when reminders have ACTUALLY
|
||||
// fired since the last dismissal (i.e. you haven't opened notes yet).
|
||||
// Showing every overdue note forever made the badge feel permanent.
|
||||
const railBtn = document.getElementById('rail-notes');
|
||||
if (railBtn) {
|
||||
let badge = railBtn.querySelector('.rail-notes-badge');
|
||||
if (fired > 0) {
|
||||
if (!badge) {
|
||||
badge = document.createElement('span');
|
||||
badge.className = 'rail-notes-badge';
|
||||
railBtn.appendChild(badge);
|
||||
}
|
||||
badge.textContent = fired > 99 ? '99+' : String(fired);
|
||||
badge.classList.add('fired');
|
||||
} else if (badge) {
|
||||
badge.remove();
|
||||
}
|
||||
}
|
||||
// Main sidebar button
|
||||
const sidebarBtn = document.getElementById('tool-notes-btn');
|
||||
if (sidebarBtn) {
|
||||
let dot = sidebarBtn.querySelector('.tool-notes-dot');
|
||||
if (fired > 0) {
|
||||
if (!dot) {
|
||||
dot = document.createElement('span');
|
||||
dot.className = 'tool-notes-dot';
|
||||
const newNoteBtn = sidebarBtn.querySelector('#notes-new-note-btn');
|
||||
sidebarBtn.insertBefore(dot, newNoteBtn || null);
|
||||
}
|
||||
} else if (dot) {
|
||||
dot.remove();
|
||||
}
|
||||
}
|
||||
// Individual note cards : pulse ones with fired reminders
|
||||
document.querySelectorAll('.note-card').forEach(card => {
|
||||
const id = card.dataset.noteId;
|
||||
const note = state.notes.find(n => n.id === id);
|
||||
if (!note || note.archived || _isNoteFullyDone(note)) {
|
||||
card.classList.remove('note-card-reminder-due');
|
||||
return;
|
||||
}
|
||||
if (note.due_date && _hasTimeComponent(note.due_date)) {
|
||||
const t = new Date(note.due_date).getTime();
|
||||
card.classList.toggle('note-card-reminder-due', !isNaN(t) && t <= Date.now());
|
||||
} else {
|
||||
card.classList.remove('note-card-reminder-due');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return { _clearViewedReminderGlows, _setReminderCardGlow, _queuePendingHighlight, _flushPendingHighlights, _updateRailBadge };
|
||||
}
|
||||
@@ -0,0 +1,335 @@
|
||||
/** Reminder date presets and recurrence picker interactions. */
|
||||
import { _formatRepeatLabel, _toLocalDatetimeStr, _normalizeRepeat, _DAYS, _ORDINALS } from '../domain/recurrence.js';
|
||||
export function createReminderPicker({
|
||||
lifecycle,
|
||||
_ensureNotificationPermission,
|
||||
_esc,
|
||||
_formatReminderTag,
|
||||
_laterTodayDate,
|
||||
_nextWeekDate,
|
||||
_snapToRepeat,
|
||||
_tomorrowDate,
|
||||
bindMenuDismiss,
|
||||
dismissOrRemove
|
||||
}) {
|
||||
function _wireReminderPicker(form) {
|
||||
// Reminder bell : opens dropdown menu
|
||||
const remindBtn = form.querySelector('.note-form-remind-btn');
|
||||
const dueInput = form.querySelector('.note-form-due');
|
||||
const repeatInput = form.querySelector('.note-form-repeat');
|
||||
const tagsEl = form.querySelector('.note-form-reminder-tags');
|
||||
|
||||
function _renderReminderTag() {
|
||||
if (!tagsEl) return;
|
||||
const v = dueInput.value;
|
||||
const rep = repeatInput.value || 'none';
|
||||
if (!v) { tagsEl.innerHTML = ''; return; }
|
||||
const label = _formatReminderTag(v);
|
||||
const repLabel = rep !== 'none' ? ` · ${_formatRepeatLabel(rep, new Date(v))}` : '';
|
||||
tagsEl.innerHTML = `<button class="note-reminder-tag" type="button" title="Edit reminder">
|
||||
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 0 1-3.46 0"/></svg>
|
||||
<span>${_esc(label)}${_esc(repLabel)}</span>
|
||||
<span class="note-reminder-tag-x" title="Remove">×</span>
|
||||
</button>`;
|
||||
tagsEl.querySelector('.note-reminder-tag').addEventListener('click', (e) => {
|
||||
if (e.target.classList.contains('note-reminder-tag-x')) {
|
||||
dueInput.value = '';
|
||||
repeatInput.value = 'none';
|
||||
_renderReminderTag();
|
||||
return;
|
||||
}
|
||||
_openReminderMenu(remindBtn || tagsEl, true);
|
||||
});
|
||||
}
|
||||
|
||||
function _openReminderMenu(anchor, isEdit = false) {
|
||||
// Close any existing menu
|
||||
document.querySelectorAll('.note-reminder-menu').forEach(m => m.remove());
|
||||
const menu = document.createElement('div');
|
||||
menu.className = 'note-reminder-menu';
|
||||
document.body.appendChild(menu);
|
||||
|
||||
const presetItems = [
|
||||
{ label: 'Later today', sub: _laterTodayDate().toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' }), action: () => _setReminder(_toLocalDatetimeStr(_laterTodayDate())) },
|
||||
{ label: 'Tomorrow', sub: _tomorrowDate().toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' }), action: () => _setReminder(_toLocalDatetimeStr(_tomorrowDate())) },
|
||||
{ label: 'Next week', sub: _nextWeekDate().toLocaleDateString([], { weekday: 'short' }) + ' ' + _nextWeekDate().toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' }), action: () => _setReminder(_toLocalDatetimeStr(_nextWeekDate())) },
|
||||
{ label: 'Select date and time', sub: '', action: () => _pickCustomDate() },
|
||||
];
|
||||
|
||||
// Sub-page state for the repeat picker. null = top page.
|
||||
// 'weekly' | 'monthly' | 'monthly_nth'
|
||||
let subMode = null;
|
||||
// Temporary state for monthly_nth so user can click N then weekday (or vice versa)
|
||||
// before committing.
|
||||
let nthDraft = { n: 0, w: -1 };
|
||||
|
||||
const DAY_SHORT = ['S', 'M', 'T', 'W', 'T', 'F', 'S'];
|
||||
|
||||
function getNorm() {
|
||||
if (!dueInput.value) return 'none';
|
||||
return _normalizeRepeat(repeatInput.value || 'none', new Date(dueInput.value));
|
||||
}
|
||||
|
||||
function commit(val) {
|
||||
repeatInput.value = val;
|
||||
_renderReminderTag();
|
||||
menu.remove();
|
||||
}
|
||||
|
||||
// Like commit, but first snaps dueInput.value forward to the next matching
|
||||
// slot for the chosen recurrence. Use for weekly/monthly variants where the
|
||||
// current due date may not match the chosen pattern (e.g. user picks
|
||||
// "weekly on Mondays" while the date is a Wednesday).
|
||||
function snapAndCommit(val) {
|
||||
if (dueInput.value) {
|
||||
const cur = new Date(dueInput.value);
|
||||
const norm = _normalizeRepeat(val, cur);
|
||||
const snapped = _snapToRepeat(cur, norm);
|
||||
if (snapped) {
|
||||
dueInput.value = _toLocalDatetimeStr(snapped);
|
||||
if (remindBtn) remindBtn.classList.add('has-date');
|
||||
}
|
||||
}
|
||||
commit(val);
|
||||
}
|
||||
|
||||
function reposition() {
|
||||
const rect = anchor.getBoundingClientRect();
|
||||
const vw = window.innerWidth;
|
||||
const vh = window.innerHeight;
|
||||
const mw = menu.offsetWidth || 220;
|
||||
const mh = menu.offsetHeight || 280;
|
||||
let top = rect.bottom + 4;
|
||||
let left = rect.left;
|
||||
if (top + mh > vh - 8) top = Math.max(8, rect.top - mh - 4);
|
||||
if (left + mw > vw - 8) left = Math.max(8, vw - mw - 8);
|
||||
if (left < 8) left = 8;
|
||||
menu.style.top = top + 'px';
|
||||
menu.style.left = left + 'px';
|
||||
}
|
||||
|
||||
function render() {
|
||||
let html = '';
|
||||
|
||||
if (subMode === null) {
|
||||
html += '<div class="note-reminder-menu-title">Remind me later</div>';
|
||||
for (let i = 0; i < presetItems.length; i++) {
|
||||
const it = presetItems[i];
|
||||
html += `<button class="note-reminder-menu-item" data-action="preset" data-i="${i}"><span>${it.label}</span><span class="note-reminder-menu-sub">${it.sub}</span></button>`;
|
||||
}
|
||||
if (isEdit && dueInput.value) {
|
||||
const norm = getNorm();
|
||||
html += '<div class="note-reminder-menu-divider"></div>';
|
||||
html += '<div class="note-reminder-menu-title">Repeat</div>';
|
||||
// None
|
||||
html += `<button class="note-reminder-menu-item${norm === 'none' ? ' active' : ''}" data-action="set" data-val="none"><span>Doesn't repeat</span>${norm === 'none' ? '<span class="note-reminder-menu-check">✓</span>' : ''}</button>`;
|
||||
// Daily
|
||||
html += `<button class="note-reminder-menu-item${norm === 'daily' ? ' active' : ''}" data-action="set" data-val="daily"><span>Daily</span>${norm === 'daily' ? '<span class="note-reminder-menu-check">✓</span>' : ''}</button>`;
|
||||
// Weekly →
|
||||
{
|
||||
const isW = norm.startsWith('weekly:');
|
||||
const wd = isW ? parseInt(norm.split(':')[1], 10) : null;
|
||||
const sub = isW && !isNaN(wd) ? `<span class="note-reminder-menu-sub">${_DAYS[wd]}</span>` : '';
|
||||
html += `<button class="note-reminder-menu-item${isW ? ' active' : ''}" data-action="sub" data-sub="weekly"><span>Weekly</span>${sub}<span class="note-reminder-menu-arrow">›</span></button>`;
|
||||
}
|
||||
// Monthly →
|
||||
{
|
||||
const isM = norm.startsWith('monthly:');
|
||||
const sub = isM ? `<span class="note-reminder-menu-sub">${_monthlyShortDescriptor(norm)}</span>` : '';
|
||||
html += `<button class="note-reminder-menu-item${isM ? ' active' : ''}" data-action="sub" data-sub="monthly"><span>Monthly</span>${sub}<span class="note-reminder-menu-arrow">›</span></button>`;
|
||||
}
|
||||
// Yearly
|
||||
html += `<button class="note-reminder-menu-item${norm === 'yearly' ? ' active' : ''}" data-action="set" data-val="yearly"><span>Yearly</span>${norm === 'yearly' ? '<span class="note-reminder-menu-check">✓</span>' : ''}</button>`;
|
||||
}
|
||||
} else if (subMode === 'weekly') {
|
||||
const norm = getNorm();
|
||||
const curWd = norm.startsWith('weekly:') ? parseInt(norm.split(':')[1], 10) : -1;
|
||||
html += `<button class="note-reminder-menu-back" data-action="back"><span class="note-reminder-menu-arrow-back">‹</span> Repeat</button>`;
|
||||
html += '<div class="note-reminder-menu-title">Weekly on…</div>';
|
||||
html += '<div class="note-reminder-weekday-row">';
|
||||
for (let i = 0; i < 7; i++) {
|
||||
html += `<button class="note-reminder-day-chip${curWd === i ? ' active' : ''}" data-action="weekly-pick" data-wd="${i}" title="${_DAYS[i]}">${DAY_SHORT[i]}</button>`;
|
||||
}
|
||||
html += '</div>';
|
||||
} else if (subMode === 'monthly') {
|
||||
const norm = getNorm();
|
||||
const dueDate = new Date(dueInput.value);
|
||||
const dayN = dueDate.getDate();
|
||||
html += `<button class="note-reminder-menu-back" data-action="back"><span class="note-reminder-menu-arrow-back">‹</span> Repeat</button>`;
|
||||
html += '<div class="note-reminder-menu-title">Monthly on…</div>';
|
||||
// Day N : uses the chosen date's day. Always offered.
|
||||
const dayVal = `monthly:day:${dayN}`;
|
||||
html += `<button class="note-reminder-menu-item${norm === dayVal ? ' active' : ''}" data-action="set" data-val="${dayVal}"><span>Day ${dayN} every month</span>${norm === dayVal ? '<span class="note-reminder-menu-check">✓</span>' : ''}</button>`;
|
||||
// Nth weekday →
|
||||
{
|
||||
const isNth = norm.startsWith('monthly:nth:');
|
||||
const sub = isNth ? `<span class="note-reminder-menu-sub">${_monthlyShortDescriptor(norm)}</span>` : '';
|
||||
html += `<button class="note-reminder-menu-item${isNth ? ' active' : ''}" data-action="sub" data-sub="monthly_nth"><span>Nth weekday</span>${sub}<span class="note-reminder-menu-arrow">›</span></button>`;
|
||||
}
|
||||
} else if (subMode === 'monthly_nth') {
|
||||
// Pick ordinal (1..4) and weekday (0..6); commit when both chosen.
|
||||
html += `<button class="note-reminder-menu-back" data-action="back-monthly"><span class="note-reminder-menu-arrow-back">‹</span> Monthly</button>`;
|
||||
html += '<div class="note-reminder-menu-title">Nth weekday of month</div>';
|
||||
html += '<div class="note-reminder-menu-sublabel">Which one</div>';
|
||||
html += '<div class="note-reminder-weekday-row">';
|
||||
for (let i = 1; i <= 4; i++) {
|
||||
html += `<button class="note-reminder-day-chip wide${nthDraft.n === i ? ' active' : ''}" data-action="nth-n" data-n="${i}">${_ORDINALS[i - 1]}</button>`;
|
||||
}
|
||||
html += '</div>';
|
||||
html += '<div class="note-reminder-menu-sublabel">Weekday</div>';
|
||||
html += '<div class="note-reminder-weekday-row">';
|
||||
for (let i = 0; i < 7; i++) {
|
||||
html += `<button class="note-reminder-day-chip${nthDraft.w === i ? ' active' : ''}" data-action="nth-w" data-wd="${i}" title="${_DAYS[i]}">${DAY_SHORT[i]}</button>`;
|
||||
}
|
||||
html += '</div>';
|
||||
html += '<div class="note-reminder-menu-divider"></div>';
|
||||
const ready = nthDraft.n > 0 && nthDraft.w >= 0;
|
||||
const lbl = ready ? `Save: ${_ORDINALS[nthDraft.n - 1]} ${_DAYS[nthDraft.w]}` : 'Pick week and weekday';
|
||||
html += `<button class="note-reminder-menu-item note-reminder-menu-confirm${ready ? '' : ' disabled'}" data-action="nth-save" ${ready ? '' : 'disabled'}><span>${lbl}</span></button>`;
|
||||
}
|
||||
|
||||
menu.innerHTML = html;
|
||||
reposition();
|
||||
wire();
|
||||
}
|
||||
|
||||
function wire() {
|
||||
menu.querySelectorAll('[data-action]').forEach(el => {
|
||||
el.addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
const a = el.dataset.action;
|
||||
if (a === 'preset') {
|
||||
const it = presetItems[parseInt(el.dataset.i, 10)];
|
||||
it.action();
|
||||
menu.remove();
|
||||
} else if (a === 'set') {
|
||||
snapAndCommit(el.dataset.val);
|
||||
} else if (a === 'sub') {
|
||||
subMode = el.dataset.sub;
|
||||
// Seed nth draft from saved value only on first entry : preserve
|
||||
// in-progress picks across back-trips (Nth → back → Nth again).
|
||||
if (subMode === 'monthly_nth' && nthDraft.n === 0 && nthDraft.w === -1) {
|
||||
const norm = getNorm();
|
||||
const m = norm.match(/^monthly:nth:(\d):(\d)$/);
|
||||
if (m) nthDraft = { n: parseInt(m[1], 10), w: parseInt(m[2], 10) };
|
||||
}
|
||||
render();
|
||||
} else if (a === 'back') {
|
||||
subMode = null;
|
||||
render();
|
||||
} else if (a === 'back-monthly') {
|
||||
subMode = 'monthly';
|
||||
render();
|
||||
} else if (a === 'weekly-pick') {
|
||||
snapAndCommit(`weekly:${el.dataset.wd}`);
|
||||
} else if (a === 'nth-n') {
|
||||
nthDraft.n = parseInt(el.dataset.n, 10);
|
||||
render();
|
||||
} else if (a === 'nth-w') {
|
||||
nthDraft.w = parseInt(el.dataset.wd, 10);
|
||||
render();
|
||||
} else if (a === 'nth-save') {
|
||||
if (nthDraft.n > 0 && nthDraft.w >= 0) {
|
||||
snapAndCommit(`monthly:nth:${nthDraft.n}:${nthDraft.w}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
render();
|
||||
// Click outside to close (single global handler attached after first paint)
|
||||
setTimeout(() => {
|
||||
const close = (e) => {
|
||||
if (!menu.isConnected) { document.removeEventListener('click', close); return; }
|
||||
if (!menu.contains(e.target)) { menu.remove(); document.removeEventListener('click', close); }
|
||||
};
|
||||
if (menu.isConnected) lifecycle.listen(menu, document, 'click', close);
|
||||
}, 0);
|
||||
}
|
||||
|
||||
function _monthlyShortDescriptor(norm) {
|
||||
const parts = norm.split(':');
|
||||
if (parts[1] === 'day') return `Day ${parts[2]}`;
|
||||
if (parts[1] === 'nth') {
|
||||
const n = parseInt(parts[2], 10);
|
||||
const wd = parseInt(parts[3], 10);
|
||||
return `${_ORDINALS[n - 1] || `${n}th`} ${_DAYS[wd].slice(0, 3)}`;
|
||||
}
|
||||
if (parts[1] === 'last') {
|
||||
const wd = parseInt(parts[2], 10);
|
||||
return `Last ${_DAYS[wd].slice(0, 3)}`;
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
function _setReminder(datetimeLocalStr) {
|
||||
dueInput.value = datetimeLocalStr;
|
||||
if (remindBtn) {
|
||||
remindBtn.classList.add('has-date');
|
||||
// Jingle the bell. CSS handles the animation; remove + reflow + re-add
|
||||
// so it replays every time the user sets/changes a reminder.
|
||||
const _bell = remindBtn.querySelector('svg');
|
||||
if (_bell) {
|
||||
_bell.classList.remove('jingling');
|
||||
void _bell.offsetWidth;
|
||||
_bell.classList.add('jingling');
|
||||
setTimeout(() => _bell.classList.remove('jingling'), 700);
|
||||
}
|
||||
}
|
||||
_renderReminderTag();
|
||||
_ensureNotificationPermission();
|
||||
}
|
||||
|
||||
function _pickCustomDate() {
|
||||
// Replace the dropdown menu with a small inline picker
|
||||
document.querySelectorAll('.note-reminder-menu').forEach(dismissOrRemove);
|
||||
const menu = document.createElement('div');
|
||||
menu.className = 'note-reminder-menu';
|
||||
const initial = dueInput.value || _toLocalDatetimeStr(_tomorrowDate());
|
||||
menu.innerHTML = `
|
||||
<div class="note-reminder-menu-title">Pick date and time</div>
|
||||
<div class="note-reminder-menu-picker">
|
||||
<input type="datetime-local" class="note-reminder-date-input" />
|
||||
</div>
|
||||
<div class="note-reminder-menu-divider"></div>
|
||||
<button class="note-reminder-menu-item note-reminder-menu-confirm">
|
||||
<span>Save</span>
|
||||
</button>
|
||||
`;
|
||||
document.body.appendChild(menu);
|
||||
// Position next to the bell button
|
||||
const anchor = remindBtn || form.querySelector('.note-form-reminder-tags');
|
||||
const rect = anchor.getBoundingClientRect();
|
||||
const vw = window.innerWidth;
|
||||
const vh = window.innerHeight;
|
||||
const mw = menu.offsetWidth || 240;
|
||||
const mh = menu.offsetHeight || 200;
|
||||
let top = rect.bottom + 4;
|
||||
let left = rect.left;
|
||||
if (top + mh > vh - 8) top = Math.max(8, rect.top - mh - 4);
|
||||
if (left + mw > vw - 8) left = Math.max(8, vw - mw - 8);
|
||||
if (left < 8) left = 8;
|
||||
menu.style.top = top + 'px';
|
||||
menu.style.left = left + 'px';
|
||||
const dInput = menu.querySelector('.note-reminder-date-input');
|
||||
dInput.value = initial;
|
||||
dInput.focus();
|
||||
if (typeof dInput.showPicker === 'function') {
|
||||
try { dInput.showPicker(); } catch {}
|
||||
}
|
||||
const close = bindMenuDismiss(menu, () => { menu.remove(); });
|
||||
menu.querySelector('.note-reminder-menu-confirm').addEventListener('click', () => {
|
||||
if (dInput.value) _setReminder(dInput.value);
|
||||
close();
|
||||
});
|
||||
}
|
||||
|
||||
if (remindBtn) remindBtn.addEventListener('click', (e) => { e.stopPropagation(); _openReminderMenu(remindBtn, !!dueInput.value); });
|
||||
_renderReminderTag();
|
||||
|
||||
|
||||
}
|
||||
|
||||
return { _wireReminderPicker };
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
/** Selection controls and view feedback for accepted attachments. */
|
||||
export function createSelection({
|
||||
operations,
|
||||
_renderNotes,
|
||||
app,
|
||||
state
|
||||
}) {
|
||||
function _enterSelectMode(initialId = null) {
|
||||
app.setSelectMode(true);
|
||||
app.clearSelection();
|
||||
if (initialId) app.selectId(initialId);
|
||||
const bar = document.getElementById('notes-bulk-bar');
|
||||
const btn = document.getElementById('notes-select-btn');
|
||||
if (bar) bar.classList.remove('hidden');
|
||||
if (btn) { btn.classList.add('active'); btn.textContent = 'Cancel'; }
|
||||
_renderNotes();
|
||||
_updateBulkBar();
|
||||
}
|
||||
|
||||
function _exitSelectMode() {
|
||||
app.setSelectMode(false);
|
||||
app.clearSelection();
|
||||
const bar = document.getElementById('notes-bulk-bar');
|
||||
const btn = document.getElementById('notes-select-btn');
|
||||
const all = document.getElementById('notes-select-all');
|
||||
if (bar) bar.classList.add('hidden');
|
||||
if (btn) { btn.classList.remove('active'); btn.textContent = 'Select'; }
|
||||
if (all) all.checked = false;
|
||||
_renderNotes();
|
||||
}
|
||||
|
||||
function _updateBulkBar() {
|
||||
const count = state.selectedIds.size;
|
||||
const countEl = document.getElementById('notes-selected-count');
|
||||
const sendAgentBtn = document.getElementById('notes-send-agent');
|
||||
const archiveBtn = document.getElementById('notes-bulk-archive');
|
||||
const deleteBtn = document.getElementById('notes-bulk-delete');
|
||||
const allEl = document.getElementById('notes-select-all');
|
||||
if (countEl) countEl.textContent = `${count} Selected`;
|
||||
if (sendAgentBtn) sendAgentBtn.disabled = count === 0;
|
||||
if (archiveBtn) archiveBtn.disabled = count === 0;
|
||||
if (deleteBtn) deleteBtn.disabled = count === 0;
|
||||
if (allEl) allEl.checked = state.notes.length > 0 && state.notes.every(n => state.selectedIds.has(n.id));
|
||||
// Toggle select-mode class so todo dots don't react to hover
|
||||
const pane = document.getElementById('notes-pane');
|
||||
if (pane) pane.classList.toggle('notes-select-mode', count > 0);
|
||||
}
|
||||
|
||||
function wireSelectionActions() {
|
||||
document.getElementById('notes-select-all').addEventListener('change', e => {
|
||||
if (e.target.checked) state.notes.forEach(n => app.selectId(n.id));
|
||||
else app.clearSelection();
|
||||
_renderNotes(); _updateBulkBar();
|
||||
});
|
||||
document.getElementById('notes-send-agent').addEventListener('click', operations.attachSelected);
|
||||
document.getElementById('notes-bulk-archive').addEventListener('click', operations.archiveSelected);
|
||||
document.getElementById('notes-bulk-delete').addEventListener('click', operations.deleteSelected);
|
||||
document.getElementById('notes-bulk-cancel').addEventListener('click', _exitSelectMode);
|
||||
}
|
||||
return { wireSelectionActions, _enterSelectMode, _exitSelectMode, _updateBulkBar };
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/** Escaping, safe image sources and link rendering. */
|
||||
export function createText({
|
||||
uiModule
|
||||
}) {
|
||||
function _esc(s) { return uiModule.esc ? uiModule.esc(s || '') : (s || '').replace(/</g, '<').replace(/>/g, '>'); }
|
||||
|
||||
function _attrEsc(s) {
|
||||
return String(s || '')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/`/g, '`');
|
||||
}
|
||||
|
||||
function _safeImgSrc(s) {
|
||||
const v = (s || '').trim();
|
||||
if (!v) return '';
|
||||
if (v.startsWith('/') || v.startsWith('./') || v.startsWith('../')) return v;
|
||||
if (/^https?:\/\//i.test(v) || /^data:image\/(?:png|jpe?g|gif|webp);base64,/i.test(v)) return v;
|
||||
return '';
|
||||
}
|
||||
|
||||
function _linkify(s) {
|
||||
const escaped = _esc(s);
|
||||
const urlRe = /\b((?:https?:\/\/|www\.)[^\s<>"']+[^\s<>"'.,;:!?\]])/g;
|
||||
return escaped.replace(urlRe, (m) => {
|
||||
let url = m;
|
||||
// Trim a trailing ')' that doesn't have a matching '(' inside the URL
|
||||
if (url.endsWith(')') && (url.match(/\(/g) || []).length < (url.match(/\)/g) || []).length) {
|
||||
url = url.slice(0, -1);
|
||||
}
|
||||
const href = url.startsWith('www.') ? `https://${url}` : url;
|
||||
return `<a href="${_attrEsc(href)}" class="note-link" target="_blank" rel="noopener noreferrer" onclick="event.stopPropagation()">${url}</a>` + (url !== m ? m.slice(url.length) : '');
|
||||
});
|
||||
}
|
||||
|
||||
return { _esc, _attrEsc, _safeImgSrc, _linkify };
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
/** Panel search, archive and list/grid controls. */
|
||||
export function createToolbar({
|
||||
app,
|
||||
state,
|
||||
persistence,
|
||||
_renderNotes,
|
||||
_fetchNotes,
|
||||
_applyMasonry
|
||||
}) {
|
||||
function wireToolbar(pane) {
|
||||
// Search
|
||||
const searchEl = document.getElementById('notes-search');
|
||||
if (searchEl) {
|
||||
searchEl.addEventListener('input', () => {
|
||||
app.setSearchQuery(searchEl.value.trim().toLowerCase());
|
||||
_renderNotes();
|
||||
});
|
||||
}
|
||||
|
||||
// View toggle
|
||||
const archiveBtn = document.getElementById('notes-archive-toggle');
|
||||
if (archiveBtn) {
|
||||
const ARCHIVE_ICON = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="3" width="20" height="5" rx="1"/><path d="M4 8v11a2 2 0 002 2h12a2 2 0 002-2V8"/><path d="M10 12h4"/></svg><span class="notes-header-btn-label">Archive</span>';
|
||||
const CLOSE_ICON = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><line x1="6" y1="6" x2="18" y2="18"/><line x1="18" y1="6" x2="6" y2="18"/></svg><span class="notes-header-btn-label">Archive</span>';
|
||||
const syncArchiveBtn = () => {
|
||||
archiveBtn.classList.toggle('active', state.showingArchived);
|
||||
archiveBtn.title = state.showingArchived ? 'Exit archive' : 'View archive';
|
||||
archiveBtn.style.opacity = state.showingArchived ? '1' : '0.8';
|
||||
// Swap to an X while in archive view so it doubles as a close-back-
|
||||
// to-active-notes toggle.
|
||||
archiveBtn.innerHTML = state.showingArchived ? CLOSE_ICON : ARCHIVE_ICON;
|
||||
// Tint the whole pane so it's obvious you're not in the active list.
|
||||
pane.classList.toggle('notes-pane-archive', state.showingArchived);
|
||||
};
|
||||
syncArchiveBtn();
|
||||
archiveBtn.addEventListener('click', async () => {
|
||||
app.setShowingArchived(!state.showingArchived);
|
||||
app.clearSelection();
|
||||
syncArchiveBtn();
|
||||
// Brief fade so the body content swap doesn't snap : the bg-tint
|
||||
// change is already eased by CSS transitions on .notes-pane*.
|
||||
const _bodyEl = document.querySelector('#notes-pane .notes-pane-body');
|
||||
if (_bodyEl) {
|
||||
_bodyEl.style.transition = 'opacity 0.18s ease';
|
||||
_bodyEl.style.opacity = '0.25';
|
||||
}
|
||||
await _fetchNotes();
|
||||
_renderNotes();
|
||||
if (_bodyEl) {
|
||||
requestAnimationFrame(() => {
|
||||
_bodyEl.style.opacity = '';
|
||||
_bodyEl.addEventListener('transitionend', () => { _bodyEl.style.transition = ''; }, { once: true });
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
const viewBtn = document.getElementById('notes-view-toggle');
|
||||
if (viewBtn) {
|
||||
pane.classList.toggle('notes-view-grid', state.viewMode === 'grid');
|
||||
// Label shows what you'll switch TO : "Grid" while in list, "List" while in grid.
|
||||
const _setViewLabel = () => {
|
||||
const lbl = viewBtn.querySelector('.notes-header-btn-label');
|
||||
if (lbl) lbl.textContent = state.viewMode === 'grid' ? 'List' : 'Grid';
|
||||
};
|
||||
_setViewLabel();
|
||||
requestAnimationFrame(() => _applyMasonry(document.querySelector('#notes-pane .notes-pane-body')));
|
||||
viewBtn.addEventListener('click', () => {
|
||||
app.setViewMode(state.viewMode === 'grid' ? 'list' : 'grid');
|
||||
try { persistence.setItem('odysseus-notes-view', state.viewMode); } catch {}
|
||||
pane.classList.toggle('notes-view-grid', state.viewMode === 'grid');
|
||||
_setViewLabel();
|
||||
requestAnimationFrame(() => _applyMasonry(document.querySelector('#notes-pane .notes-pane-body')));
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
return { wireToolbar };
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
/** Shared-window integration: safe fullscreen bounds, docking and stacking. */
|
||||
export function createWindowLayout({
|
||||
makeWindowDraggable,
|
||||
snapModalToZone,
|
||||
clearDockSide,
|
||||
applyEdgeDock,
|
||||
topToolWindowZ
|
||||
}) {
|
||||
function _notesFullscreenSafeRect() {
|
||||
const vw = window.innerWidth || document.documentElement.clientWidth || 0;
|
||||
const vh = window.innerHeight || document.documentElement.clientHeight || 0;
|
||||
let left = 0;
|
||||
let right = vw;
|
||||
|
||||
const sidebar = document.getElementById('sidebar');
|
||||
const rail = document.getElementById('icon-rail');
|
||||
const hamburgerRight = document.body.classList.contains('hamburger-right')
|
||||
|| sidebar?.classList.contains('right-side')
|
||||
|| rail?.classList.contains('right-side');
|
||||
|
||||
const reserve = (el) => {
|
||||
if (!el || getComputedStyle(el).display === 'none') return;
|
||||
const rect = el.getBoundingClientRect();
|
||||
if (rect.width <= 0 || rect.height <= 0) return;
|
||||
if (hamburgerRight) right = Math.min(right, rect.left);
|
||||
else left = Math.max(left, rect.right);
|
||||
};
|
||||
|
||||
if (sidebar && !sidebar.classList.contains('hidden')) reserve(sidebar);
|
||||
reserve(rail);
|
||||
|
||||
// The fixed hamburger can remain visible even when the rail/sidebar is
|
||||
// collapsed. Reserve its strip too so fullscreen Notes does not sit beneath it.
|
||||
const hamburger = document.getElementById('hamburger-btn');
|
||||
if (hamburger && getComputedStyle(hamburger).display !== 'none') {
|
||||
const rect = hamburger.getBoundingClientRect();
|
||||
const pad = 8;
|
||||
if (hamburgerRight) right = Math.min(right, rect.left - pad);
|
||||
else left = Math.max(left, rect.right + pad);
|
||||
}
|
||||
|
||||
left = Math.max(0, Math.min(left, vw - 80));
|
||||
right = Math.max(left + 80, Math.min(right, vw));
|
||||
return { left, top: 0, width: right - left, height: vh };
|
||||
}
|
||||
|
||||
function _wireNotesWindow(pane) {
|
||||
if (!pane || pane.dataset.windowDragWired === '1') return;
|
||||
const header = pane.querySelector('.notes-pane-header');
|
||||
if (!header) return;
|
||||
pane.dataset.windowDragWired = '1';
|
||||
makeWindowDraggable(pane, {
|
||||
content: pane,
|
||||
header,
|
||||
fsClass: 'notes-window-fullscreen',
|
||||
skipSelector: 'button, input, select, textarea, label, .notes-mobile-grabber',
|
||||
enableDock: true,
|
||||
enableLeftDock: true,
|
||||
onEnterFullscreen: () => {
|
||||
pane.classList.add('notes-window-fullscreen');
|
||||
snapModalToZone(pane, {
|
||||
name: 'fullscreen',
|
||||
rect: _notesFullscreenSafeRect(),
|
||||
});
|
||||
},
|
||||
onExitFullscreen: () => {
|
||||
_restoreNotesSidebarDock(pane);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function _clearNotesSnapStyles(pane) {
|
||||
if (!pane) return;
|
||||
const hadLeft = pane.classList.contains('modal-left-docked');
|
||||
const hadRight = pane.classList.contains('modal-right-docked');
|
||||
pane.classList.remove('notes-window-fullscreen', 'modal-left-docked', 'modal-right-docked');
|
||||
if (hadLeft) clearDockSide('left', pane);
|
||||
if (hadRight) clearDockSide('right', pane);
|
||||
['position', 'left', 'top', 'right', 'bottom', 'width', 'max-width', 'height',
|
||||
'max-height', 'margin', 'transform', 'border-radius']
|
||||
.forEach((prop) => pane.style.removeProperty(prop));
|
||||
delete pane.dataset._tilePreSnap;
|
||||
delete pane.dataset._tileZone;
|
||||
delete pane._preDockSnapshot;
|
||||
delete pane._dockSide;
|
||||
delete pane._dockSuspended;
|
||||
}
|
||||
|
||||
function _restoreNotesSidebarDock(pane) {
|
||||
if (!pane || window.innerWidth <= 768) return;
|
||||
_clearNotesSnapStyles(pane);
|
||||
if (!pane.isConnected) return;
|
||||
applyEdgeDock(pane, 'right');
|
||||
}
|
||||
|
||||
function _topToolWindowZ(exclude = null) {
|
||||
return topToolWindowZ({ exclude });
|
||||
}
|
||||
|
||||
function _bringNotesToFront(pane = document.getElementById('notes-pane')) {
|
||||
if (!pane) return;
|
||||
const backdrop = document.getElementById('notes-pane-backdrop') || pane.parentElement;
|
||||
const z = _topToolWindowZ(backdrop) + 1;
|
||||
if (backdrop) backdrop.style.setProperty('z-index', String(z), 'important');
|
||||
try {
|
||||
window.dispatchEvent(new CustomEvent('odysseus:modal-opened', {
|
||||
detail: { id: 'notes-panel', modal: pane },
|
||||
}));
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
|
||||
return { _wireNotesWindow, _restoreNotesSidebarDock, _bringNotesToFront };
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
/** Stateless celebration renderer shared by Notes and Compare. */
|
||||
export function spawnConfetti(cx, cy, count) {
|
||||
const colors = ['#ffd700', '#ff6b6b', '#5b8def', '#51cf66', '#ff922b', '#cc5de8', '#22b8cf', '#fff'];
|
||||
for (let i = 0; i < count; i++) {
|
||||
const el = document.createElement('div');
|
||||
el.className = 'confetti-piece';
|
||||
const color = colors[Math.floor(Math.random() * colors.length)];
|
||||
const size = 5 + Math.random() * 8;
|
||||
const isCircle = Math.random() > 0.5;
|
||||
el.style.width = size + 'px';
|
||||
el.style.height = (isCircle ? size : size * 0.6) + 'px';
|
||||
el.style.background = color;
|
||||
el.style.borderRadius = isCircle ? '50%' : '2px';
|
||||
el.style.left = cx + 'px';
|
||||
el.style.top = cy + 'px';
|
||||
const angle = Math.random() * Math.PI * 2;
|
||||
const speed = 60 + Math.random() * 160;
|
||||
const dx = Math.cos(angle) * speed;
|
||||
const dy = Math.sin(angle) * speed - 100;
|
||||
const duration = 1.0 + Math.random() * 1.0;
|
||||
el.animate([
|
||||
{ transform: 'translate(0, 0) rotate(0deg) scale(1)', opacity: 1 },
|
||||
{ transform: `translate(${dx}px, ${dy + 200}px) rotate(${400 + Math.random() * 400}deg) scale(0)`, opacity: 0 }
|
||||
], { duration: duration * 1000, easing: 'cubic-bezier(0.15, 0.6, 0.35, 1)', fill: 'forwards' });
|
||||
document.body.appendChild(el);
|
||||
setTimeout(() => el.remove(), duration * 1000 + 50);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verify the current Python runtime from an isolated distribution without frontend tooling."""
|
||||
import os
|
||||
import json
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import socket
|
||||
@@ -13,12 +14,20 @@ ROOT = Path(__file__).resolve().parents[1]
|
||||
PROBE = """
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import json
|
||||
import sys
|
||||
from starlette.testclient import TestClient
|
||||
from app import app
|
||||
assert not Path('frontend').exists()
|
||||
assert not Path('node_modules').exists()
|
||||
assert shutil.which('node') is None
|
||||
with TestClient(app) as client:
|
||||
for output in json.loads(sys.argv[1]):
|
||||
asset = client.get('/static/' + output)
|
||||
assert asset.status_code == 200, (output, asset.status_code)
|
||||
assert asset.content == Path('static', output).read_bytes(), output
|
||||
assert asset.headers['content-type'].startswith('text/javascript'), output
|
||||
assert asset.headers['cache-control'] == 'no-cache', output
|
||||
response = client.get('/static/js/actionMenuOrder.js')
|
||||
assert response.status_code == 200, response.status_code
|
||||
assert response.content == Path('static/js/actionMenuOrder.js').read_bytes()
|
||||
@@ -58,7 +67,10 @@ def main() -> int:
|
||||
)
|
||||
# A caller's Python search path must not import the original checkout.
|
||||
env.pop("PYTHONPATH", None)
|
||||
result = subprocess.run([sys.executable, "-c", PROBE], cwd=target, env=env, capture_output=True, text=True, timeout=60)
|
||||
outputs = [entry['deployment'] for entry in json.loads(
|
||||
(ROOT / 'frontend/modules.json').read_text(encoding='utf-8')
|
||||
)['modules']]
|
||||
result = subprocess.run([sys.executable, "-c", PROBE, json.dumps(outputs)], cwd=target, env=env, capture_output=True, text=True, timeout=60)
|
||||
print(result.stdout, end="")
|
||||
if result.returncode:
|
||||
print(result.stderr[-8000:], file=sys.stderr)
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run real Notes UI and API against a disposable native distribution and database."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
from urllib.request import urlopen
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def main():
|
||||
with tempfile.TemporaryDirectory(prefix="ody-notes-native-") as directory, socket.socket() as chroma_guard:
|
||||
target = Path(directory)
|
||||
for name in ("app.py", "HARNESS_VERSION"):
|
||||
shutil.copy2(ROOT / name, target / name)
|
||||
for name in ("core", "routes", "src", "services", "resources", "mcp_servers", "companion", "config", "static"):
|
||||
shutil.copytree(ROOT / name, target / name, ignore=shutil.ignore_patterns("__pycache__", ".env", "secrets.env*", "*.db", "*.sqlite*"))
|
||||
chroma_guard.bind(("127.0.0.1", 0))
|
||||
with socket.socket() as app_port:
|
||||
app_port.bind(("127.0.0.1", 0))
|
||||
port = app_port.getsockname()[1]
|
||||
env = dict(os.environ)
|
||||
env.update(
|
||||
ODYSSEUS_DATA_DIR=str(target / "data"),
|
||||
DATABASE_URL="sqlite:///" + str(target / "notes.db"), AUTH_ENABLED="true",
|
||||
ODYSSEUS_STARTUP_WARMUPS="0", ODYSSEUS_TOOL_INDEX_PREWARM="0",
|
||||
CHROMADB_HOST="127.0.0.1", CHROMADB_PORT=str(chroma_guard.getsockname()[1]),
|
||||
FASTEMBED_CACHE_PATH=str(target / "fastembed"),
|
||||
)
|
||||
env.pop("PYTHONPATH", None)
|
||||
server = subprocess.Popen(
|
||||
[sys.executable, "-m", "uvicorn", "app:app", "--host", "127.0.0.1", "--port", str(port)],
|
||||
cwd=target, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,
|
||||
)
|
||||
result = None
|
||||
try:
|
||||
origin = f"http://127.0.0.1:{port}"
|
||||
deadline = time.monotonic() + 45
|
||||
while time.monotonic() < deadline:
|
||||
if server.poll() is not None:
|
||||
raise RuntimeError("Disposable Notes server exited during startup")
|
||||
try:
|
||||
with urlopen(origin + "/", timeout=1) as response:
|
||||
if response.status == 200:
|
||||
break
|
||||
except OSError:
|
||||
time.sleep(0.1)
|
||||
else:
|
||||
raise RuntimeError("Disposable Notes server did not become ready")
|
||||
result = subprocess.run(
|
||||
["node", "tests/browser/notesNative.mjs"], cwd=ROOT,
|
||||
env=dict(os.environ, ODYSSEUS_NOTES_RUNTIME_ORIGIN=origin, NOTES_TEST_PYTHON=sys.executable),
|
||||
capture_output=True, text=True, timeout=120,
|
||||
)
|
||||
print(result.stdout, end="")
|
||||
if result.returncode:
|
||||
print(result.stderr, file=sys.stderr)
|
||||
return result.returncode
|
||||
finally:
|
||||
server.terminate()
|
||||
try:
|
||||
logs, _ = server.communicate(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
server.kill()
|
||||
logs, _ = server.communicate()
|
||||
if result is None or result.returncode:
|
||||
print(logs[-8000:], file=sys.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -1,4 +1,5 @@
|
||||
// compare/vote.js — voting, revealing, confetti
|
||||
import { spawnConfetti } from '../shared/ui/confetti.js';
|
||||
import Storage from '../storage.js';
|
||||
import state from './state.js';
|
||||
import { _modelDisplayNames } from './models.js';
|
||||
@@ -222,33 +223,4 @@ function handleVote(winnerIdx) {
|
||||
}
|
||||
}
|
||||
|
||||
/** Spawn confetti particles from a point. */
|
||||
function spawnConfetti(cx, cy, count) {
|
||||
const colors = ['#ffd700', '#ff6b6b', '#5b8def', '#51cf66', '#ff922b', '#cc5de8', '#22b8cf', '#fff'];
|
||||
for (let i = 0; i < count; i++) {
|
||||
const el = document.createElement('div');
|
||||
el.className = 'confetti-piece';
|
||||
const color = colors[Math.floor(Math.random() * colors.length)];
|
||||
const size = 5 + Math.random() * 8;
|
||||
const isCircle = Math.random() > 0.5;
|
||||
el.style.width = size + 'px';
|
||||
el.style.height = (isCircle ? size : size * 0.6) + 'px';
|
||||
el.style.background = color;
|
||||
el.style.borderRadius = isCircle ? '50%' : '2px';
|
||||
el.style.left = cx + 'px';
|
||||
el.style.top = cy + 'px';
|
||||
const angle = Math.random() * Math.PI * 2;
|
||||
const speed = 60 + Math.random() * 160;
|
||||
const dx = Math.cos(angle) * speed;
|
||||
const dy = Math.sin(angle) * speed - 100;
|
||||
const duration = 1.0 + Math.random() * 1.0;
|
||||
el.animate([
|
||||
{ transform: 'translate(0, 0) rotate(0deg) scale(1)', opacity: 1 },
|
||||
{ transform: `translate(${dx}px, ${dy + 200}px) rotate(${400 + Math.random() * 400}deg) scale(0)`, opacity: 0 }
|
||||
], { duration: duration * 1000, easing: 'cubic-bezier(0.15, 0.6, 0.35, 1)', fill: 'forwards' });
|
||||
document.body.appendChild(el);
|
||||
setTimeout(() => el.remove(), duration * 1000 + 50);
|
||||
}
|
||||
}
|
||||
|
||||
export { _saveVote, handleVote, buildVoteBar, addFinishBadge, spawnConfetti, registerCompareActions };
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
/** Create an agent session, link it to a note and drain its background stream. */
|
||||
import { _noteToAgentPrompt } from '../domain/noteRules.js';
|
||||
export function createAgentActions({
|
||||
_patchNote,
|
||||
_renderNotes,
|
||||
api,
|
||||
app,
|
||||
createFormData,
|
||||
state,
|
||||
streamComplete,
|
||||
uiModule
|
||||
}) {
|
||||
async function _agentSolveNote(id) {
|
||||
const note = state.notes.find(n => n.id === id);
|
||||
if (!note) return;
|
||||
const prompt = _noteToAgentPrompt(note);
|
||||
if (!prompt) { uiModule.showToast('Nothing to solve — note is empty'); return; }
|
||||
try {
|
||||
const dc = await (await api.defaultChat()).json();
|
||||
if (!dc.endpoint_url || !dc.model) { uiModule.showError('No default chat model configured'); return; }
|
||||
|
||||
// 1. Create the session server-side (no UI switch). skip_validation
|
||||
// avoids re-probing : the default-chat endpoint is already known good.
|
||||
const label = (note.title || (Array.isArray(note.items) && note.items[0]?.text) || 'todo').slice(0, 40);
|
||||
const csFd = createFormData();
|
||||
csFd.append('name', 'Agent: ' + label);
|
||||
csFd.append('endpoint_url', dc.endpoint_url);
|
||||
csFd.append('model', dc.model);
|
||||
if (dc.endpoint_id) csFd.append('endpoint_id', dc.endpoint_id);
|
||||
csFd.append('skip_validation', 'true');
|
||||
const csRes = await api.createSession(csFd);
|
||||
if (!csRes.ok) { uiModule.showError('Could not create agent session'); return; }
|
||||
const sess = await csRes.json();
|
||||
const sid = sess.id;
|
||||
|
||||
// 2. Link the session to the note right away so the tag appears.
|
||||
const n = state.notes.find(x => x.id === id);
|
||||
if (n) app.mergeNote(n, { agent_session_id: sid });
|
||||
_renderNotes();
|
||||
_patchNote(id, { agent_session_id: sid }).catch(() => {});
|
||||
|
||||
// 3. Kick off the agent run in the background. POST to chat_stream in
|
||||
// agent mode and drain the SSE so the server runs the loop to
|
||||
// completion + saves : without rendering anything in the chat UI.
|
||||
const fd = createFormData();
|
||||
fd.append('message', prompt);
|
||||
fd.append('session', sid);
|
||||
fd.append('mode', 'agent');
|
||||
fd.append('disabled_tools', JSON.stringify(['manage_notes']));
|
||||
api.startChat(fd)
|
||||
.then(async (res) => {
|
||||
if (!res.ok || !res.body) return;
|
||||
const reader = res.body.getReader();
|
||||
// Drain to completion (server finishes + persists the run).
|
||||
while (true) { const { done } = await reader.read(); if (done) break; }
|
||||
streamComplete(sid);
|
||||
})
|
||||
.catch(() => {});
|
||||
|
||||
uiModule.showToast('Agent working in background — tap the Agent tag when ready');
|
||||
} catch (e) {
|
||||
uiModule.showError('Agent failed: ' + (e.message || e));
|
||||
}
|
||||
}
|
||||
|
||||
return { _agentSolveNote };
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
/** Optimistic card mutations and rollback. Animation completion is a UI-supplied boundary. */
|
||||
export function createCardOperations({
|
||||
app,
|
||||
api,
|
||||
effects,
|
||||
pushUndo,
|
||||
undoArchive
|
||||
}) {
|
||||
const state = app.state;
|
||||
function togglePin(id) {
|
||||
const note = state.notes.find(n => n.id === id);
|
||||
if (!note) return;
|
||||
const prevPinned = note.pinned, prevSortOrder = note.sort_order;
|
||||
app.mergeNote(note, { pinned: !prevPinned });
|
||||
const patch = { pinned: note.pinned };
|
||||
if (note.pinned) {
|
||||
const minPinned = state.notes.filter(n => n.pinned && n.id !== id).reduce((m, n) => Math.min(m, n.sort_order || 0), 0);
|
||||
app.mergeNote(note, { sort_order: minPinned - 1 });
|
||||
patch.sort_order = note.sort_order;
|
||||
}
|
||||
effects.render();
|
||||
api.patchNote(id, patch).catch(() => {
|
||||
app.mergeNote(note, { pinned: prevPinned, sort_order: prevSortOrder });
|
||||
effects.render(); effects.showError('Failed to pin');
|
||||
});
|
||||
}
|
||||
async function updateColor(id, color) {
|
||||
try {
|
||||
await api.patchNote(id, { color: color || null });
|
||||
const note = state.notes.find(n => n.id === id);
|
||||
if (note) app.mergeNote(note, { color });
|
||||
} catch { effects.showError('Failed to update color'); }
|
||||
}
|
||||
function stageArchive(id) {
|
||||
const index = state.notes.findIndex(n => n.id === id);
|
||||
if (index < 0) return null;
|
||||
const removed = app.removeNoteAt(index);
|
||||
const undo = () => undoArchive(removed, index);
|
||||
pushUndo({ label: 'archive', run: undo });
|
||||
return () => {
|
||||
effects.render();
|
||||
api.patchNote(id, { archived: true }).then(() => effects.archived(undo)).catch(() => {
|
||||
app.insertNoteAt(index, removed); effects.render(); effects.showError('Failed to archive');
|
||||
});
|
||||
};
|
||||
}
|
||||
function unarchive(id) {
|
||||
const index = state.notes.findIndex(n => n.id === id);
|
||||
if (index < 0) return;
|
||||
const removed = app.removeNoteAt(index);
|
||||
effects.render();
|
||||
api.patchNote(id, { archived: false }).then(() => effects.showToast('Unarchived')).catch(() => {
|
||||
app.insertNoteAt(index, removed); effects.render(); effects.showError('Failed to unarchive');
|
||||
});
|
||||
}
|
||||
function deleteOptimistically(id, toast = false) {
|
||||
const index = state.notes.findIndex(n => n.id === id);
|
||||
if (index < 0) return;
|
||||
const removed = app.removeNoteAt(index);
|
||||
effects.render();
|
||||
const deletion = api.deleteNote(id);
|
||||
const completion = toast ? deletion.then(() => effects.showToast('Deleted')) : deletion;
|
||||
completion.catch(() => {
|
||||
app.insertNoteAt(index, removed); effects.render(); effects.showError('Failed to delete');
|
||||
});
|
||||
}
|
||||
// Desktop deliberately persists without updating local sort_order, as before.
|
||||
function persistOrder(ids) { return api.reorder(ids); }
|
||||
async function commitMobileOrder(ids) {
|
||||
try {
|
||||
await api.reorder(ids);
|
||||
ids.forEach((id, index) => {
|
||||
const note = state.notes.find(note => note.id === id);
|
||||
if (note) app.mergeNote(note, { sort_order: index });
|
||||
});
|
||||
} catch (error) { console.warn('reorder failed', error); }
|
||||
}
|
||||
return { togglePin, updateColor, stageArchive, unarchive, deleteOptimistically, persistOrder, commitMobileOrder };
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
/** Checklist item workflows. Supplied feedback callbacks update the invoking view. */
|
||||
export function createChecklistOperations({
|
||||
app,
|
||||
api,
|
||||
effects,
|
||||
uid
|
||||
}) {
|
||||
const state = app.state;
|
||||
function itemNote(id, index) {
|
||||
const note = state.notes.find(n => n.id === id);
|
||||
return note && Array.isArray(note.items) && note.items[index] ? note : null;
|
||||
}
|
||||
function removeItem(id, index) {
|
||||
const note = itemNote(id, index);
|
||||
if (!note) return;
|
||||
const removed = note.items[index];
|
||||
app.mergeNote(note, { items: note.items.filter((_, i) => i !== index) });
|
||||
effects.render();
|
||||
api.patchNote(id, { items: note.items }).catch(() => {
|
||||
app.spliceItems(note, index, 0, removed); effects.render(); effects.showError('Failed to remove item');
|
||||
});
|
||||
}
|
||||
function editItem(note, index, text) {
|
||||
const oldText = (note.items[index].text || '').trim();
|
||||
if (text === oldText) { effects.render(); return; }
|
||||
const oldItem = note.items[index];
|
||||
if (!text) app.spliceItems(note, index, 1);
|
||||
else app.updateItem(note, index, { text });
|
||||
api.patchNote(note.id, { items: note.items }).catch(() => {
|
||||
if (!text) app.spliceItems(note, index, 0, oldItem);
|
||||
else app.updateItem(note, index, { text: oldText });
|
||||
effects.render(); effects.showError('Failed to update item');
|
||||
});
|
||||
effects.render();
|
||||
}
|
||||
function addItem(id, text, added) {
|
||||
const note = state.notes.find(n => n.id === id);
|
||||
if (!note) return;
|
||||
const items = Array.isArray(note.items) ? [...note.items] : [];
|
||||
items.push({ id: uid(), text, done: false });
|
||||
app.mergeNote(note, { items });
|
||||
added(); effects.render();
|
||||
return () => api.patchNote(id, { items }).catch(() => {
|
||||
app.mergeNote(note, { items: items.slice(0, -1) }); effects.render(); effects.showError('Failed to add item');
|
||||
});
|
||||
}
|
||||
function toggleItem(id, index, changed, completed) {
|
||||
const note = itemNote(id, index);
|
||||
if (!note) return;
|
||||
const wasDone = note.items.length > 0 && note.items.every(it => it.done);
|
||||
app.updateItem(note, index, { done: !note.items[index].done });
|
||||
changed(note.items[index].done);
|
||||
if (!wasDone && note.items.length > 0 && note.items.every(it => it.done)) completed();
|
||||
api.patchNote(id, { items: note.items }).catch(() => {
|
||||
app.updateItem(note, index, { done: !note.items[index].done }); changed(note.items[index].done);
|
||||
});
|
||||
}
|
||||
async function toggleTodayStep(id, index, changed, completed) {
|
||||
const note = itemNote(id, index);
|
||||
if (!note) return;
|
||||
app.updateItem(note, index, { done: !note.items[index].done }); changed();
|
||||
try {
|
||||
await api.patchNote(id, { items: note.items }); effects.render();
|
||||
if (note.items.every(it => it.done)) completed();
|
||||
} catch { app.updateItem(note, index, { done: !note.items[index].done }); }
|
||||
}
|
||||
return { removeItem, editItem, addItem, toggleItem, toggleTodayStep };
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
/** Confirmed deletion and past-reminder clearing workflows. */
|
||||
export function createDeletion({
|
||||
app,
|
||||
_deleteNoteApi,
|
||||
_fetchNotes,
|
||||
_isPastReminder,
|
||||
_renderNotes,
|
||||
effects,
|
||||
state
|
||||
}) {
|
||||
async function _deleteNote(id) {
|
||||
const ok = effects.styledConfirm
|
||||
? await effects.styledConfirm('Delete this note?', { confirmText: 'Delete', danger: true })
|
||||
: effects.confirm('Delete this note?');
|
||||
if (!ok) return;
|
||||
try { await _deleteNoteApi(id); await _fetchNotes(); _renderNotes(); effects.showToast('Deleted'); }
|
||||
catch (err) { effects.showError(err.message); }
|
||||
}
|
||||
|
||||
async function _clearPastReminders() {
|
||||
const targets = state.notes.filter(n => !n.archived && _isPastReminder(n));
|
||||
if (!targets.length) {
|
||||
effects.showToast?.('No past reminders to clear');
|
||||
return;
|
||||
}
|
||||
const ok = effects.styledConfirm
|
||||
? await effects.styledConfirm(`Delete ${targets.length} past reminder${targets.length === 1 ? '' : 's'}?`, { confirmText: 'Delete', danger: true })
|
||||
: effects.confirm(`Delete ${targets.length} past reminder${targets.length === 1 ? '' : 's'}?`);
|
||||
if (!ok) return;
|
||||
await Promise.all(targets.map(n => _deleteNoteApi(n.id).catch(() => {})));
|
||||
await _fetchNotes();
|
||||
_renderNotes();
|
||||
effects.showToast?.(`Cleared ${targets.length} past reminder${targets.length === 1 ? '' : 's'}`);
|
||||
}
|
||||
|
||||
async function deleteFromEditor(id) {
|
||||
const ok = effects.styledConfirm
|
||||
? await effects.styledConfirm('Delete this note?', { confirmText: 'Delete', danger: true })
|
||||
: effects.confirm('Delete this note?');
|
||||
if (!ok) return;
|
||||
const index = state.notes.findIndex(note => note.id === id);
|
||||
if (index >= 0) app.removeNoteAt(index);
|
||||
app.setEditingId(null);
|
||||
_renderNotes();
|
||||
_deleteNoteApi(id).then(() => effects.showToast('Deleted')).catch(() => {
|
||||
effects.showError('Failed to delete');
|
||||
_fetchNotes().then(() => _renderNotes());
|
||||
});
|
||||
}
|
||||
return { _deleteNote, _clearPastReminders, deleteFromEditor };
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
/** Serialized autosave and synchronous local draft backup. DOM collection is a supplied port. */
|
||||
export function createNotesDrafts({
|
||||
app,
|
||||
api,
|
||||
persistence,
|
||||
scheduler,
|
||||
effects
|
||||
}) {
|
||||
const state = app.state;
|
||||
const { _draftKey, _clearDraft } = persistence;
|
||||
function bindDraft({ collect, id, view }) {
|
||||
let t = null;
|
||||
let pending = Promise.resolve();
|
||||
let stopped = false;
|
||||
let warned = false;
|
||||
const save = () => {
|
||||
const d = collect();
|
||||
// An empty edit can be intentional: don't restore stale server text over it.
|
||||
try { persistence.setItem(_draftKey(id), JSON.stringify(d)); }
|
||||
catch {
|
||||
if (!warned) effects.showError('Draft backup unavailable. Keep this note open until saved.');
|
||||
warned = true;
|
||||
}
|
||||
return d;
|
||||
};
|
||||
const persist = (d) => {
|
||||
if (!id || id === '__new__' || d.note_type === 'draw') return pending;
|
||||
const { _ts, ...payload } = d;
|
||||
payload.label = [...new Set(payload.label.split(/\s+/).map(s => s.replace(/^#+/, '')).filter(Boolean))].join(' ') || null;
|
||||
pending = pending.then(async () => {
|
||||
try {
|
||||
await api.patchNote(id, payload);
|
||||
view.failed = false;
|
||||
const note = state.notes.find(n => n.id === id);
|
||||
if (note) app.mergeNote(note, payload);
|
||||
if (persistence.getItem(_draftKey(id)) === JSON.stringify(d)) _clearDraft(id);
|
||||
} catch {
|
||||
if (!view.failed) effects.showError('Note not synced. Your edits are kept on this device; retry Save.');
|
||||
view.failed = true;
|
||||
}
|
||||
});
|
||||
return pending;
|
||||
};
|
||||
const flush = () => { scheduler.clearTimeout(t); return save(); };
|
||||
const stop = () => { stopped = true; scheduler.clearTimeout(t); return pending; };
|
||||
const sched = () => {
|
||||
const d = save();
|
||||
if (stopped) return;
|
||||
scheduler.clearTimeout(t);
|
||||
t = scheduler.setTimeout(() => persist(d), 500);
|
||||
};
|
||||
return { flush, stop, schedule: sched };
|
||||
}
|
||||
return { bindDraft };
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
/** Application-owned filtering, searching and note ordering. */
|
||||
import { _noteTags, _visibleNoteTags, _nextGoalStep, _isCalendarReminderNote } from '../domain/noteRules.js';
|
||||
import { _hasTimeComponent } from '../domain/recurrence.js';
|
||||
export function createQueries({
|
||||
_hasActiveReminder,
|
||||
state
|
||||
}) {
|
||||
function _sortedVisibleNotes() {
|
||||
const displayNotes = _userVisibleNotes();
|
||||
let filtered = state.activeLabel ? displayNotes.filter(n => _noteTags(n).includes(state.activeLabel)) : displayNotes;
|
||||
if (state.activeFilter === 'reminders') {
|
||||
filtered = filtered.filter(n => n.due_date && _hasTimeComponent(n.due_date));
|
||||
} else if (state.activeFilter === 'no-reminders') {
|
||||
filtered = filtered.filter(n => !(n.due_date && _hasTimeComponent(n.due_date)));
|
||||
} else if (state.activeFilter === 'default') {
|
||||
filtered = filtered.filter(n => _visibleNoteTags(n).length === 0);
|
||||
} else if (state.activeFilter === 'goals') {
|
||||
filtered = filtered.filter(n => n.note_type === 'goal' && !n.archived);
|
||||
} else if (state.activeFilter === 'today') {
|
||||
// Today view: only goals that still have an unchecked step.
|
||||
filtered = filtered.filter(n => n.note_type === 'goal' && !n.archived && _nextGoalStep(n));
|
||||
}
|
||||
if (state.searchQuery) {
|
||||
filtered = filtered.filter(n => {
|
||||
const q = state.searchQuery;
|
||||
if ((n.title || '').toLowerCase().includes(q)) return true;
|
||||
if ((n.content || '').toLowerCase().includes(q)) return true;
|
||||
if ((n.label || '').toLowerCase().includes(q)) return true;
|
||||
if (Array.isArray(n.items) && n.items.some(it => (it.text || '').toLowerCase().includes(q))) return true;
|
||||
return false;
|
||||
});
|
||||
}
|
||||
const sorted = [...filtered].sort((a, b) => {
|
||||
// In reminders view: sort by due date ascending (soonest first)
|
||||
if (state.activeFilter === 'reminders') {
|
||||
const da = new Date(a.due_date || 0).getTime();
|
||||
const db = new Date(b.due_date || 0).getTime();
|
||||
return da - db;
|
||||
}
|
||||
// Archived view: newest archived first (ignore manual sort_order).
|
||||
if (state.showingArchived) {
|
||||
return new Date(b.updated_at || 0) - new Date(a.updated_at || 0);
|
||||
}
|
||||
if (a.pinned && !b.pinned) return -1;
|
||||
if (!a.pinned && b.pinned) return 1;
|
||||
// Active reminders (due date in the past, not done/archived) rank
|
||||
// immediately under the pinned block.
|
||||
const aActive = _hasActiveReminder(a);
|
||||
const bActive = _hasActiveReminder(b);
|
||||
if (aActive && !bActive) return -1;
|
||||
if (!aActive && bActive) return 1;
|
||||
const so = (a.sort_order || 0) - (b.sort_order || 0);
|
||||
if (so !== 0) return so;
|
||||
return new Date(b.updated_at || 0) - new Date(a.updated_at || 0);
|
||||
});
|
||||
|
||||
|
||||
return sorted;
|
||||
}
|
||||
|
||||
function _userVisibleNotes() {
|
||||
return state.notes.filter(n => !_isCalendarReminderNote(n));
|
||||
}
|
||||
|
||||
return { _sortedVisibleNotes, _userVisibleNotes };
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
/** Page-owned reminder scheduler and notification delivery workflow. */
|
||||
import { _hasTimeComponent, _isDueTodayOrOverdue, _advanceRecurring } from '../domain/recurrence.js';
|
||||
export function createNotesReminders({
|
||||
app,
|
||||
api,
|
||||
persistence,
|
||||
notifications,
|
||||
clock,
|
||||
scheduler,
|
||||
effects,
|
||||
fetchNotes,
|
||||
isNoteFullyDone,
|
||||
hasItems,
|
||||
dismissedKey
|
||||
}) {
|
||||
const state = app.state;
|
||||
const { _loadFiredReminders, _saveFiredReminders } = persistence;
|
||||
const _patchNote = api.patchNote;
|
||||
const _fetchNotes = fetchNotes;
|
||||
const _isNoteFullyDone = isNoteFullyDone;
|
||||
const _hasItems = hasItems;
|
||||
const REMINDER_DISMISSED_AT_KEY = dismissedKey;
|
||||
const _updateRailBadge = effects.badge;
|
||||
let _reminderTimer = null;
|
||||
let startupTimer = null;
|
||||
let started = false;
|
||||
let disposed = false;
|
||||
function _checkReminders() {
|
||||
if (!state.notes.length) return;
|
||||
const now = clock.now();
|
||||
const fired = _loadFiredReminders();
|
||||
let changed = false;
|
||||
for (const note of state.notes) {
|
||||
if (!note.due_date || note.archived) continue;
|
||||
if (!_hasTimeComponent(note.due_date)) continue;
|
||||
if (fired.has(note.id)) continue;
|
||||
const due = new Date(note.due_date).getTime();
|
||||
if (isNaN(due)) continue;
|
||||
if (due <= now && due > now - 60000) {
|
||||
_fireReminder(note);
|
||||
// Recurring? advance the due_date instead of marking as fired
|
||||
if (note.repeat && note.repeat !== 'none') {
|
||||
const next = _advanceRecurring(note.due_date, note.repeat, clock);
|
||||
if (next) {
|
||||
app.mergeNote(note, { due_date: next });
|
||||
_patchNote(note.id, { due_date: next }).catch(() => {});
|
||||
// Don't add to fired : new due_date is in the future
|
||||
continue;
|
||||
}
|
||||
}
|
||||
fired.add(note.id);
|
||||
changed = true;
|
||||
} else if (due <= now - 60000) {
|
||||
// Past, never seen : silently advance recurring or mark fired
|
||||
if (note.repeat && note.repeat !== 'none') {
|
||||
const next = _advanceRecurring(note.due_date, note.repeat, clock);
|
||||
if (next) {
|
||||
app.mergeNote(note, { due_date: next });
|
||||
_patchNote(note.id, { due_date: next }).catch(() => {});
|
||||
continue;
|
||||
}
|
||||
}
|
||||
fired.add(note.id);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if (changed) _saveFiredReminders(fired);
|
||||
// Always refresh badge : fired state may have changed visually without note mutation
|
||||
_updateRailBadge();
|
||||
}
|
||||
|
||||
function _fireReminder(note) {
|
||||
const title = note.title || 'Note reminder';
|
||||
// Include the verbatim note content so the email/notification actually
|
||||
// shows what to do, not just a count. Cap the per-item lines (8 max) and
|
||||
// total length so the body stays inbox-friendly.
|
||||
let rawBody;
|
||||
if (_hasItems(note)) {
|
||||
const pending = (note.items || [])
|
||||
.filter(i => !i.done && !i.checked)
|
||||
.map(i => (i.text || '').trim())
|
||||
.filter(Boolean);
|
||||
if (pending.length) {
|
||||
const shown = pending.slice(0, 8).map(t => `- ${t}`).join('\n');
|
||||
const extra = pending.length > 8 ? `\n…and ${pending.length - 8} more` : '';
|
||||
rawBody = `Pending (${pending.length}):\n${shown}${extra}`;
|
||||
} else {
|
||||
rawBody = `${(note.items || []).length} item${(note.items || []).length === 1 ? '' : 's'}`;
|
||||
}
|
||||
} else {
|
||||
rawBody = (note.content || '').slice(0, 400);
|
||||
}
|
||||
|
||||
// Ask the server to dispatch according to user settings. The server may
|
||||
// return an LLM-written synthesis line and/or send an email. We still show
|
||||
// a local browser notification so the user gets immediate feedback even if
|
||||
// the server path is disabled or slow.
|
||||
const showLocal = body => notifications.show(title, body, note.id);
|
||||
|
||||
// Fire-and-forget server dispatch. If synthesis comes back quickly enough,
|
||||
// use it as the notification body; otherwise the local notification has
|
||||
// already shown with the raw body.
|
||||
let shown = false;
|
||||
const timer = scheduler.setTimeout(() => { if (!shown) { shown = true; showLocal(rawBody); } }, 1500);
|
||||
|
||||
api.fireReminder({ note_id: note.id, title, body: rawBody })
|
||||
.then(r => r.ok ? r.json() : null)
|
||||
.then(data => {
|
||||
scheduler.clearTimeout(timer);
|
||||
if (shown) return;
|
||||
shown = true;
|
||||
const body = (data && data.synthesis) ? data.synthesis : rawBody;
|
||||
showLocal(body);
|
||||
})
|
||||
.catch(() => {
|
||||
scheduler.clearTimeout(timer);
|
||||
if (!shown) { shown = true; showLocal(rawBody); }
|
||||
});
|
||||
|
||||
// Pulse the card if visible; otherwise queue it so the next time the user
|
||||
// opens the notes panel the card gets a brief glow.
|
||||
effects.highlight(note.id);
|
||||
}
|
||||
|
||||
function _startReminderLoop() {
|
||||
if (disposed || _reminderTimer) return;
|
||||
_reminderTimer = scheduler.setInterval(_checkReminders, 30000);
|
||||
_checkReminders(); // run once immediately
|
||||
}
|
||||
|
||||
function _countDueReminders() {
|
||||
return state.notes.filter(n => !n.archived && _isDueTodayOrOverdue(n.due_date, clock) && !_isNoteFullyDone(n)).length;
|
||||
}
|
||||
|
||||
function _countFiredReminders() {
|
||||
// Reminders whose time has actually passed (not just date-today),
|
||||
// and which fired after the last user dismissal.
|
||||
const now = clock.now();
|
||||
return state.notes.filter(n => {
|
||||
if (n.archived || _isNoteFullyDone(n)) return false;
|
||||
if (!n.due_date || !_hasTimeComponent(n.due_date)) return false;
|
||||
const t = new Date(n.due_date).getTime();
|
||||
if (isNaN(t) || t > now) return false;
|
||||
return t > state.firedDotDismissedAt;
|
||||
}).length;
|
||||
}
|
||||
|
||||
function dismissFiredReminderDot() {
|
||||
app.setFiredDotDismissedAt(clock.now());
|
||||
try { persistence.setItem(REMINDER_DISMISSED_AT_KEY, String(state.firedDotDismissedAt)); } catch {}
|
||||
_updateRailBadge();
|
||||
}
|
||||
|
||||
async function refreshDueBadge(opts = {}) {
|
||||
// Usually lightweight, but callers that just created a note reminder can
|
||||
// force a refresh so the background reminder loop sees it immediately.
|
||||
if (opts.force || state.notes.length === 0) {
|
||||
try {
|
||||
const wasArchived = state.showingArchived;
|
||||
app.setShowingArchived(false);
|
||||
await _fetchNotes();
|
||||
app.setShowingArchived(wasArchived);
|
||||
} catch {}
|
||||
}
|
||||
_updateRailBadge();
|
||||
}
|
||||
|
||||
async function _initReminders() {
|
||||
try {
|
||||
const res = await api.listNotes(false);
|
||||
if (res.ok && !disposed) {
|
||||
const data = await res.json();
|
||||
app.replaceNotes(data.notes || data || []);
|
||||
_startReminderLoop();
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
|
||||
function start() { if (started || disposed) return; started = true; startupTimer = scheduler.setTimeout(_initReminders, 3000); }
|
||||
function dispose() { disposed = true; scheduler.clearTimeout(startupTimer); scheduler.clearInterval(_reminderTimer); _reminderTimer = null; }
|
||||
return { start, dispose, _checkReminders, _fireReminder, _startReminderLoop, _countDueReminders, _countFiredReminders, dismissFiredReminderDot, refreshDueBadge, _initReminders };
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/** Selected-note attachment retains synchronous acceptance; bulk requests retain partial-failure behavior. */
|
||||
export function createSelectionOperations({
|
||||
app,
|
||||
api,
|
||||
effects,
|
||||
sendContext,
|
||||
exitSelection,
|
||||
fetchNotes
|
||||
}) {
|
||||
const state = app.state;
|
||||
function attachSelected() {
|
||||
const ids = [...state.selectedIds];
|
||||
if (!ids.length) return;
|
||||
const detail = { noteIds: ids, accepted: false };
|
||||
sendContext(detail);
|
||||
if (!detail.accepted) {
|
||||
effects.showToast('Choose a chat or model before attaching notes');
|
||||
return;
|
||||
}
|
||||
exitSelection();
|
||||
}
|
||||
async function archiveSelected() {
|
||||
const ids = [...state.selectedIds];
|
||||
if (!ids.length) return;
|
||||
await Promise.all(ids.map(id => api.patchNote(id, { archived: true }).catch(() => {})));
|
||||
exitSelection(); await fetchNotes(); effects.render(); effects.showToast(`Archived ${ids.length}`);
|
||||
}
|
||||
async function deleteSelected() {
|
||||
const ids = [...state.selectedIds];
|
||||
if (!ids.length) return;
|
||||
if (effects.styledConfirm) {
|
||||
const ok = await effects.styledConfirm(`Delete ${ids.length} note${ids.length === 1 ? '' : 's'}?`, { confirmText: 'Delete', danger: true });
|
||||
if (!ok) return;
|
||||
}
|
||||
await Promise.all(ids.map(id => api.deleteNote(id).catch(() => {})));
|
||||
exitSelection(); await fetchNotes(); effects.render(); effects.showToast(`Deleted ${ids.length}`);
|
||||
}
|
||||
return { attachSelected, archiveSelected, deleteSelected };
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
/** The sole Notes state owner. Views have live read-only access; writes use operations. */
|
||||
export function createNotesState(initial = {}) {
|
||||
const values = {
|
||||
open: false, notes: [], editingId: null, selectedIds: new Set(),
|
||||
activeLabel: null, activeFilter: null, reminderChipNext: 'reminders', searchQuery: '',
|
||||
viewMode: initial.viewMode || 'list', showingArchived: false, selectMode: false,
|
||||
suppressNextNoteTapId: null, labelsCollapsed: !!initial.labelsCollapsed,
|
||||
loading: false, firedDotDismissedAt: initial.firedDotDismissedAt || 0,
|
||||
};
|
||||
// Preserve captured note identity across asynchronous completions without
|
||||
// giving a view a writable reference to the application store.
|
||||
const views = new WeakMap(), targets = new WeakMap();
|
||||
const unwrap = value => targets.get(value) || value;
|
||||
// Copies built from views (spread, filter, map) still hold nested views;
|
||||
// store only raw data so the owner never keeps its own read-only views.
|
||||
function unwrapDeep(value, seen = new WeakSet()) {
|
||||
if (!value || typeof value !== 'object') return value;
|
||||
if (targets.has(value)) return targets.get(value);
|
||||
if (seen.has(value)) return value;
|
||||
seen.add(value);
|
||||
if (Array.isArray(value)) value.forEach((item, index) => { value[index] = unwrapDeep(item, seen); });
|
||||
else if (Object.getPrototypeOf(value) === Object.prototype) for (const key of Object.keys(value)) value[key] = unwrapDeep(value[key], seen);
|
||||
return value;
|
||||
}
|
||||
function readonly(value) {
|
||||
if (!value || typeof value !== 'object') return value;
|
||||
if (targets.has(value)) return value;
|
||||
if (views.has(value)) return views.get(value);
|
||||
const view = new Proxy(value, {
|
||||
get(target, key) {
|
||||
if (target instanceof Set) {
|
||||
if (['add', 'delete', 'clear'].includes(key)) return () => { throw new TypeError('Use Notes selection operations'); };
|
||||
if (key === 'valueOf') return () => views.get(target);
|
||||
if (key === 'forEach') return (callback, thisArg) => target.forEach(value => callback.call(thisArg, value, value, views.get(target)));
|
||||
const member = Reflect.get(target, key, target);
|
||||
return typeof member === 'function' ? member.bind(target) : member;
|
||||
}
|
||||
return readonly(Reflect.get(target, key));
|
||||
},
|
||||
set() { throw new TypeError('Use Notes state operations'); },
|
||||
deleteProperty() { throw new TypeError('Use Notes state operations'); },
|
||||
defineProperty() { throw new TypeError('Use Notes state operations'); },
|
||||
setPrototypeOf() { throw new TypeError('Use Notes state operations'); },
|
||||
preventExtensions() { throw new TypeError('Use Notes state operations'); },
|
||||
getOwnPropertyDescriptor(target, key) {
|
||||
const descriptor = Reflect.getOwnPropertyDescriptor(target, key);
|
||||
if (descriptor && 'value' in descriptor) return { ...descriptor, value: readonly(descriptor.value) };
|
||||
return descriptor;
|
||||
},
|
||||
});
|
||||
views.set(value, view); targets.set(view, value);
|
||||
return view;
|
||||
}
|
||||
const state = Object.freeze(Object.fromEntries(Object.keys(values).map(key => [key, () => readonly(values[key])])));
|
||||
const view = Object.freeze(Object.defineProperties({}, Object.fromEntries(Object.entries(state).map(([key, get]) => [key, { get, enumerable: true }]))));
|
||||
return {
|
||||
state: view,
|
||||
setOpen: value => { values.open = value; },
|
||||
setEditingId: value => { values.editingId = value; },
|
||||
setActiveLabel: value => { values.activeLabel = value; },
|
||||
setActiveFilter: value => { values.activeFilter = value; },
|
||||
setReminderChipNext: value => { values.reminderChipNext = value; },
|
||||
setSearchQuery: value => { values.searchQuery = value; },
|
||||
setViewMode: value => { values.viewMode = value; },
|
||||
setShowingArchived: value => { values.showingArchived = value; },
|
||||
setSelectMode: value => { values.selectMode = value; },
|
||||
setSuppressNextNoteTapId: value => { values.suppressNextNoteTapId = value; },
|
||||
setLabelsCollapsed: value => { values.labelsCollapsed = value; },
|
||||
setLoading: value => { values.loading = value; },
|
||||
setFiredDotDismissedAt: value => { values.firedDotDismissedAt = value; },
|
||||
replaceNotes: notes => { values.notes = notes; },
|
||||
removeNoteAt: index => readonly(values.notes.splice(index, 1)[0]),
|
||||
insertNoteAt: (index, note) => { values.notes.splice(index, 0, unwrapDeep(note)); },
|
||||
prependNote: note => { values.notes.unshift(unwrapDeep(note)); },
|
||||
replaceNoteAt: (index, note) => { values.notes[index] = unwrapDeep(note); },
|
||||
mergeNote: (note, patch) => { for (const [key, value] of Object.entries(patch)) unwrap(note)[key] = unwrapDeep(value); },
|
||||
updateItem: (note, index, patch) => { Object.assign(unwrap(unwrap(note).items[index]), unwrapDeep({ ...patch })); },
|
||||
spliceItems: (note, ...args) => unwrap(unwrap(note).items).splice(...args.map(arg => unwrapDeep(arg))),
|
||||
selectId: id => { values.selectedIds.add(id); },
|
||||
deselectId: id => values.selectedIds.delete(id),
|
||||
clearSelection: () => values.selectedIds.clear(),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
/** Editor submission ordering, optimistic state, reminder rearming and save recovery. */
|
||||
export function createNotesSubmission({
|
||||
app,
|
||||
api,
|
||||
persistence,
|
||||
clock,
|
||||
uid,
|
||||
effects,
|
||||
fetchNotes
|
||||
}) {
|
||||
const state = app.state;
|
||||
const { _loadFiredReminders, _saveFiredReminders, _loadGlowedReminders, _saveGlowedReminders, _loadDraft, _clearDraft } = persistence;
|
||||
function submitNote(payload, note, isEdit) {
|
||||
// Reset fired reminder if due_date changed (so re-arm works), and also
|
||||
// clear the entry-glow seen flag so the new firing glows again on the
|
||||
// next time the user opens the panel.
|
||||
if (isEdit && note.due_date !== payload.due_date) {
|
||||
const fired = _loadFiredReminders();
|
||||
fired.delete(note.id);
|
||||
_saveFiredReminders(fired);
|
||||
const glowed = _loadGlowedReminders();
|
||||
glowed.delete(note.id);
|
||||
_saveGlowedReminders(glowed);
|
||||
effects.clearGlow(note.id);
|
||||
}
|
||||
// Edited notes move to the top of their section (under pinned). Compute
|
||||
// sort_order = (min unpinned sort_order) - 1 so the saved note sorts above
|
||||
// siblings; the pin block keeps its own ordering above this.
|
||||
if (!payload.pinned) {
|
||||
// Both edits AND newly-created notes anchor above the rest of the
|
||||
// unpinned section. Without this, freshly created notes sit at the
|
||||
// bottom because manually-reordered siblings already carry negative
|
||||
// sort_order values.
|
||||
const minUnpinned = state.notes
|
||||
.filter(n => !n.pinned && (!isEdit || n.id !== note.id))
|
||||
.reduce((m, n) => Math.min(m, n.sort_order || 0), 0);
|
||||
payload.sort_order = minUnpinned - 1;
|
||||
}
|
||||
// Optimistic update : update local state first, render, then save in background
|
||||
app.setEditingId(null);
|
||||
const draftId = isEdit ? note.id : '__new__';
|
||||
const submittedDraft = JSON.stringify(_loadDraft(draftId));
|
||||
if (isEdit) {
|
||||
const idx = state.notes.findIndex(n => n.id === note.id);
|
||||
if (idx >= 0) app.replaceNoteAt(idx, { ...state.notes[idx], ...payload });
|
||||
} else {
|
||||
app.prependNote({ ...payload, id: 'tmp_' + uid(), created_at: new Date(clock.now()).toISOString(), updated_at: new Date(clock.now()).toISOString() });
|
||||
}
|
||||
effects.render();
|
||||
// Background save
|
||||
api.saveNote(payload).then(saved => {
|
||||
if (JSON.stringify(_loadDraft(draftId)) === submittedDraft) _clearDraft(draftId);
|
||||
if (!isEdit && saved && saved.id) {
|
||||
// Replace temp ID with real one from server. AND re-render : the
|
||||
// existing card's `data-note-id="tmp_xxx"` is stale after Object.assign
|
||||
// bumps the in-memory id, so all subsequent clicks (edit, done, copy,
|
||||
// archive, delete) silently fail to find the note in `_notes`.
|
||||
const tmp = state.notes.find(n => n.id.startsWith('tmp_'));
|
||||
if (tmp) app.mergeNote(tmp, saved);
|
||||
effects.render();
|
||||
}
|
||||
}).catch(err => {
|
||||
effects.showError('Save failed: ' + err.message);
|
||||
fetchNotes().then(() => effects.render());
|
||||
});
|
||||
|
||||
}
|
||||
return { submitNote };
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
/** Notes CRUD, optimistic archive and in-memory undo workflows. */
|
||||
export function createNotesWorkflows({
|
||||
app,
|
||||
api,
|
||||
effects
|
||||
}) {
|
||||
const state = app.state;
|
||||
const _undoStack = [];
|
||||
const _renderNotes = effects.render;
|
||||
const _patchNote = api.patchNote;
|
||||
const uiModule = effects;
|
||||
function _pushUndo(entry) {
|
||||
_undoStack.push(entry);
|
||||
if (_undoStack.length > 20) _undoStack.shift();
|
||||
}
|
||||
|
||||
function _popAndRunUndo() {
|
||||
const entry = _undoStack.pop();
|
||||
if (entry) entry.run();
|
||||
return !!entry;
|
||||
}
|
||||
|
||||
function _undoArchive(note, prevIdx) {
|
||||
// Re-insert at original position and clear archived flag on the server.
|
||||
const safeIdx = Math.min(Math.max(prevIdx, 0), state.notes.length);
|
||||
app.insertNoteAt(safeIdx, { ...note, archived: false });
|
||||
_renderNotes();
|
||||
_patchNote(note.id, { archived: false }).catch(() => {
|
||||
// Roll back local insertion if the server refuses
|
||||
const i = state.notes.findIndex(n => n.id === note.id);
|
||||
if (i >= 0) app.removeNoteAt(i);
|
||||
_renderNotes();
|
||||
uiModule.showError('Undo failed');
|
||||
});
|
||||
}
|
||||
|
||||
function _archiveNoteById(id, { card = null, celebrate = false } = {}) {
|
||||
if (!id) return false;
|
||||
const idx = state.notes.findIndex(n => n.id === id);
|
||||
if (idx < 0) return false;
|
||||
const note = state.notes[idx];
|
||||
if (celebrate && card && note) effects.celebrateArchive(note, card);
|
||||
const removed = app.removeNoteAt(idx);
|
||||
app.setEditingId(null);
|
||||
_renderNotes();
|
||||
const undo = () => _undoArchive(removed, idx);
|
||||
_pushUndo({ label: 'archive', run: undo });
|
||||
_patchNote(id, { archived: true }).then(() => {
|
||||
effects.archived(undo);
|
||||
}).catch(() => {
|
||||
app.insertNoteAt(idx, removed);
|
||||
_renderNotes();
|
||||
uiModule.showError('Failed to archive');
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
async function _fetchNotes() {
|
||||
app.setLoading(true);
|
||||
try {
|
||||
const res = await api.listNotes(state.showingArchived);
|
||||
if (!res.ok) { app.replaceNotes([]); return; }
|
||||
const data = await res.json();
|
||||
app.replaceNotes(data.notes || data || []);
|
||||
} catch (e) {
|
||||
console.error('Failed to fetch notes:', e);
|
||||
app.replaceNotes([]);
|
||||
} finally {
|
||||
app.setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
function _saveNote(note) { return api.saveNote(note); }
|
||||
|
||||
function _deleteNoteApi(id) { return api.deleteNote(id); }
|
||||
|
||||
return { _pushUndo, _popAndRunUndo, _undoArchive, _archiveNoteById, _fetchNotes, _saveNote, _deleteNoteApi, _patchNote, undoCount: () => _undoStack.length };
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
/** Pure Notes completion, tags, reminder and serialization rules. */
|
||||
import { _hasTimeComponent } from './recurrence.js';
|
||||
export function _isCalendarReminderNote(n) {
|
||||
return n && n.source === 'calendar' && n.label === 'calendar';
|
||||
}
|
||||
|
||||
export function _hasActiveReminder(n, clock) {
|
||||
if (!n || n.archived || _isNoteFullyDone(n)) return false;
|
||||
if (!n.due_date) return false;
|
||||
const t = new Date(n.due_date).getTime();
|
||||
return !isNaN(t) && t <= clock.now();
|
||||
}
|
||||
|
||||
export function _isNoteFullyDone(note) {
|
||||
if (_hasItems(note) && Array.isArray(note.items) && note.items.length > 0) {
|
||||
return note.items.every(it => it.done);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function _hasItems(note) {
|
||||
return note && (note.note_type === 'todo' || note.note_type === 'goal' || note.note_type === 'checklist');
|
||||
}
|
||||
|
||||
export function _goalProgress(note) {
|
||||
if (!Array.isArray(note?.items) || note.items.length === 0) return '';
|
||||
const done = note.items.filter(it => it.done).length;
|
||||
return ` ${done}/${note.items.length}`;
|
||||
}
|
||||
|
||||
export function _nextGoalStep(note) {
|
||||
if (!Array.isArray(note?.items)) return null;
|
||||
for (let i = 0; i < note.items.length; i++) {
|
||||
if (!note.items[i].done) return { idx: i, item: note.items[i] };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function _noteTags(n) {
|
||||
const tags = [];
|
||||
if (n?.label) tags.push(...n.label.trim().split(/\s+/).filter(Boolean));
|
||||
if (n?.due_date && _hasTimeComponent(n.due_date)) tags.push('reminder');
|
||||
return [...new Set(tags.map(t => t.replace(/^#+/, '').trim()).filter(Boolean))];
|
||||
}
|
||||
|
||||
export function _visibleNoteTags(n) {
|
||||
return _noteTags(n).filter(t => t !== 'reminder');
|
||||
}
|
||||
|
||||
export function _isPastReminder(n, clock) {
|
||||
if (!n?.due_date || !_hasTimeComponent(n.due_date)) return false;
|
||||
const due = new Date(n.due_date).getTime();
|
||||
return !isNaN(due) && due <= clock.now();
|
||||
}
|
||||
|
||||
export function _serializeNoteForCopy(note) {
|
||||
const lines = [];
|
||||
if (note.title) lines.push(note.title);
|
||||
if (note.content) lines.push(note.content);
|
||||
if (Array.isArray(note.items) && note.items.length) {
|
||||
if (lines.length) lines.push('');
|
||||
for (const it of note.items) {
|
||||
if (!it || !(it.text || '').trim()) continue;
|
||||
lines.push(`- [${it.done ? 'x' : ' '}] ${(it.text || '').trim()}`);
|
||||
}
|
||||
}
|
||||
return lines.join('\n').trim();
|
||||
}
|
||||
|
||||
export function _noteToAgentPrompt(note) {
|
||||
const parts = [];
|
||||
if ((note.title || '').trim()) parts.push(note.title.trim());
|
||||
if ((note.content || '').trim()) parts.push(note.content.trim());
|
||||
if (Array.isArray(note.items)) {
|
||||
note.items.filter(it => !it.done && (it.text || '').trim())
|
||||
.forEach(it => parts.push('- ' + it.text.trim()));
|
||||
}
|
||||
const body = parts.join('\n');
|
||||
return body ? `Help me get this done:\n\n${body}\n\nThe source note is read-only. Do not edit, replace, or update it.` : '';
|
||||
}
|
||||
|
||||
export function _standardVisualVariant(note) {
|
||||
const source = String(note?.id || note?.title || note?.created_at || 'standard-note');
|
||||
let hash = 0;
|
||||
for (let i = 0; i < source.length; i++) hash = ((hash << 5) - hash + source.charCodeAt(i)) | 0;
|
||||
return Math.abs(hash) % 5;
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
// Local-time date and recurrence rules. Callers supply the clock at the original read sites.
|
||||
export const _ORDINALS = ['1st', '2nd', '3rd', '4th', '5th'];
|
||||
export const _DAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
|
||||
export function _hasTimeComponent(dateStr) {
|
||||
return typeof dateStr === 'string' && /T\d{2}:\d{2}/.test(dateStr);
|
||||
}
|
||||
|
||||
export function _formatDueDate(dateStr, clock) {
|
||||
if (!dateStr) return '';
|
||||
const d = new Date(dateStr);
|
||||
if (isNaN(d)) return '';
|
||||
const now = new Date(clock.now());
|
||||
const hasTime = _hasTimeComponent(dateStr);
|
||||
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
|
||||
const due = new Date(d.getFullYear(), d.getMonth(), d.getDate());
|
||||
const diffDays = Math.round((due - today) / 86400000);
|
||||
const timeStr = hasTime ? d.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' }) : '';
|
||||
if (hasTime && d < now) return 'overdue';
|
||||
if (!hasTime && diffDays < 0) return 'overdue';
|
||||
if (diffDays === 0) return hasTime ? timeStr : 'today';
|
||||
if (diffDays === 1) return hasTime ? `tmrw ${timeStr}` : 'tomorrow';
|
||||
const dateLabel = d.toLocaleDateString([], { month: 'short', day: 'numeric' });
|
||||
return hasTime ? `${dateLabel} ${timeStr}` : dateLabel;
|
||||
}
|
||||
|
||||
export function _isDueOverdue(dateStr, clock) {
|
||||
if (!dateStr) return false;
|
||||
const d = new Date(dateStr);
|
||||
if (isNaN(d)) return false;
|
||||
if (_hasTimeComponent(dateStr)) return d < new Date(clock.now());
|
||||
return d < new Date(new Date(clock.now()).toDateString());
|
||||
}
|
||||
|
||||
export function _isDueTodayOrOverdue(dateStr, clock) {
|
||||
if (!dateStr) return false;
|
||||
const d = new Date(dateStr);
|
||||
const now = new Date(clock.now());
|
||||
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
|
||||
const due = new Date(d.getFullYear(), d.getMonth(), d.getDate());
|
||||
return due <= today;
|
||||
}
|
||||
|
||||
export function _laterTodayDate(clock) {
|
||||
const now = new Date(clock.now());
|
||||
const eight = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 18, 0); // 6pm today
|
||||
// If less than 1 hour before 6pm, push to "in 3 hours" instead
|
||||
if (eight - now < 60 * 60 * 1000) return new Date(now.getTime() + 3 * 60 * 60 * 1000);
|
||||
return eight;
|
||||
}
|
||||
|
||||
export function _tomorrowDate(clock) {
|
||||
const t = new Date(clock.now());
|
||||
t.setDate(t.getDate() + 1);
|
||||
t.setHours(8, 0, 0, 0);
|
||||
return t;
|
||||
}
|
||||
|
||||
export function _nextWeekDate(clock) {
|
||||
const t = new Date(clock.now());
|
||||
const daysUntilMon = (8 - t.getDay()) % 7 || 7;
|
||||
t.setDate(t.getDate() + daysUntilMon);
|
||||
t.setHours(8, 0, 0, 0);
|
||||
return t;
|
||||
}
|
||||
|
||||
export function _toLocalDatetimeStr(d) {
|
||||
// Format as YYYY-MM-DDTHH:MM (local, no TZ)
|
||||
const pad = n => String(n).padStart(2, '0');
|
||||
return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
||||
}
|
||||
|
||||
export function _formatReminderTag(dateStr, clock) {
|
||||
if (!dateStr) return '';
|
||||
const d = new Date(dateStr);
|
||||
if (isNaN(d)) return '';
|
||||
const now = new Date(clock.now());
|
||||
const sameDay = d.toDateString() === now.toDateString();
|
||||
const tomorrow = new Date(now); tomorrow.setDate(tomorrow.getDate() + 1);
|
||||
const isTomorrow = d.toDateString() === tomorrow.toDateString();
|
||||
const time = d.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' });
|
||||
if (sameDay) return `Today, ${time}`;
|
||||
if (isTomorrow) return `Tomorrow, ${time}`;
|
||||
const dateLabel = d.toLocaleDateString([], { month: 'short', day: 'numeric' });
|
||||
return `${dateLabel}, ${time}`;
|
||||
}
|
||||
|
||||
export function _nthWeekdayLabel(d) {
|
||||
const n = Math.ceil(d.getDate() / 7); // 1..5
|
||||
return `${_ORDINALS[n - 1] || `${n}th`} ${_DAYS[d.getDay()]}`;
|
||||
}
|
||||
|
||||
export function _isLastWeekdayOfMonth(d) {
|
||||
const test = new Date(d);
|
||||
test.setDate(d.getDate() + 7);
|
||||
return test.getMonth() !== d.getMonth();
|
||||
}
|
||||
|
||||
export function _nthWeekdayOfMonth(year, month, weekday, n) {
|
||||
const first = new Date(year, month, 1);
|
||||
const offset = (weekday - first.getDay() + 7) % 7;
|
||||
let day = 1 + offset + (n - 1) * 7;
|
||||
// Last day of month
|
||||
const lastDay = new Date(year, month + 1, 0).getDate();
|
||||
if (day > lastDay) day -= 7;
|
||||
return new Date(year, month, day, 0, 0, 0);
|
||||
}
|
||||
|
||||
export function _lastWeekdayOfMonth(year, month, weekday) {
|
||||
const lastDay = new Date(year, month + 1, 0);
|
||||
const back = (lastDay.getDay() - weekday + 7) % 7;
|
||||
return new Date(year, month, lastDay.getDate() - back, 0, 0, 0);
|
||||
}
|
||||
|
||||
export function _snapToRepeat(currentDate, normRepeat, clock) {
|
||||
const hh = currentDate.getHours();
|
||||
const mm = currentDate.getMinutes();
|
||||
const now = clock.now();
|
||||
const anchor = currentDate.getTime() > now ? currentDate : new Date(clock.now());
|
||||
const parts = normRepeat.split(':');
|
||||
const kind = parts[0];
|
||||
if (kind === 'weekly') {
|
||||
const targetWd = parseInt(parts[1], 10);
|
||||
if (isNaN(targetWd)) return null;
|
||||
const d = new Date(anchor.getFullYear(), anchor.getMonth(), anchor.getDate(), hh, mm, 0, 0);
|
||||
const delta = (targetWd - d.getDay() + 7) % 7;
|
||||
d.setDate(d.getDate() + delta);
|
||||
if (d.getTime() <= now) d.setDate(d.getDate() + 7);
|
||||
return d;
|
||||
}
|
||||
if (kind === 'monthly') {
|
||||
const sub = parts[1];
|
||||
let y = anchor.getFullYear();
|
||||
let m = anchor.getMonth();
|
||||
// Walk forward up to 14 months to find the next matching slot.
|
||||
for (let tries = 0; tries < 14; tries++) {
|
||||
let target;
|
||||
if (sub === 'day') {
|
||||
const wantDay = parseInt(parts[2], 10);
|
||||
if (isNaN(wantDay)) return null;
|
||||
const lastDay = new Date(y, m + 1, 0).getDate();
|
||||
target = new Date(y, m, Math.min(wantDay, lastDay));
|
||||
} else if (sub === 'nth') {
|
||||
const n = parseInt(parts[2], 10);
|
||||
const wd = parseInt(parts[3], 10);
|
||||
if (isNaN(n) || isNaN(wd)) return null;
|
||||
target = _nthWeekdayOfMonth(y, m, wd, n);
|
||||
} else if (sub === 'last') {
|
||||
const wd = parseInt(parts[2], 10);
|
||||
if (isNaN(wd)) return null;
|
||||
target = _lastWeekdayOfMonth(y, m, wd);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
target.setHours(hh, mm, 0, 0);
|
||||
if (target.getTime() > now && target.getTime() >= anchor.getTime()) return target;
|
||||
m++;
|
||||
if (m > 11) { m = 0; y++; }
|
||||
}
|
||||
return null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function _formatRepeatLabel(repeat, originalDate) {
|
||||
if (!repeat || repeat === 'none') return '';
|
||||
const norm = _normalizeRepeat(repeat, originalDate);
|
||||
if (norm === 'daily') return 'Daily';
|
||||
if (norm === 'yearly') return 'Yearly';
|
||||
const parts = norm.split(':');
|
||||
if (parts[0] === 'weekly') {
|
||||
const wd = parseInt(parts[1], 10);
|
||||
if (isNaN(wd)) return 'Weekly';
|
||||
return `Weekly on ${_DAYS[wd]}s`;
|
||||
}
|
||||
if (parts[0] === 'monthly') {
|
||||
if (parts[1] === 'day') return `Monthly on day ${parts[2]}`;
|
||||
if (parts[1] === 'nth') {
|
||||
const n = parseInt(parts[2], 10);
|
||||
const wd = parseInt(parts[3], 10);
|
||||
return `Monthly on ${_ORDINALS[n - 1] || `${n}th`} ${_DAYS[wd]}`;
|
||||
}
|
||||
if (parts[1] === 'last') {
|
||||
const wd = parseInt(parts[2], 10);
|
||||
return `Monthly on last ${_DAYS[wd]}`;
|
||||
}
|
||||
}
|
||||
return norm;
|
||||
}
|
||||
|
||||
export function _normalizeRepeat(repeat, originalDate) {
|
||||
if (!repeat || repeat === 'none') return 'none';
|
||||
if (repeat === 'daily' || repeat === 'yearly') return repeat;
|
||||
if (/^(weekly|monthly):/.test(repeat)) return repeat;
|
||||
// Legacy bare values: derive params from the original date
|
||||
const wd = originalDate.getDay();
|
||||
const n = Math.ceil(originalDate.getDate() / 7);
|
||||
if (repeat === 'weekly') return `weekly:${wd}`;
|
||||
if (repeat === 'monthly') return `monthly:day:${originalDate.getDate()}`;
|
||||
if (repeat === 'monthly_nth_weekday') return `monthly:nth:${n}:${wd}`;
|
||||
if (repeat === 'monthly_last_weekday') return `monthly:last:${wd}`;
|
||||
return repeat;
|
||||
}
|
||||
|
||||
export function _advanceRecurring(dateStr, repeat, clock) {
|
||||
const orig = new Date(dateStr);
|
||||
const hh = orig.getHours();
|
||||
const mm = orig.getMinutes();
|
||||
let d = new Date(orig);
|
||||
const norm = _normalizeRepeat(repeat, orig);
|
||||
if (norm === 'none') return null;
|
||||
|
||||
function step() {
|
||||
if (norm === 'daily') {
|
||||
d.setDate(d.getDate() + 1);
|
||||
return;
|
||||
}
|
||||
if (norm === 'yearly') {
|
||||
d.setFullYear(d.getFullYear() + 1);
|
||||
return;
|
||||
}
|
||||
const parts = norm.split(':');
|
||||
const kind = parts[0];
|
||||
if (kind === 'weekly') {
|
||||
// Snap to the requested weekday in the next 1-7 days
|
||||
const targetWd = parseInt(parts[1], 10);
|
||||
let delta = (targetWd - d.getDay() + 7) % 7;
|
||||
if (delta === 0) delta = 7;
|
||||
d.setDate(d.getDate() + delta);
|
||||
d.setHours(hh, mm, 0, 0);
|
||||
return;
|
||||
}
|
||||
if (kind === 'monthly') {
|
||||
const sub = parts[1];
|
||||
const ny = d.getFullYear() + (d.getMonth() === 11 ? 1 : 0);
|
||||
const nm = (d.getMonth() + 1) % 12;
|
||||
let target;
|
||||
if (sub === 'day') {
|
||||
const wantDay = parseInt(parts[2], 10);
|
||||
const lastDay = new Date(ny, nm + 1, 0).getDate();
|
||||
target = new Date(ny, nm, Math.min(wantDay, lastDay));
|
||||
} else if (sub === 'nth') {
|
||||
const n = parseInt(parts[2], 10);
|
||||
const wd = parseInt(parts[3], 10);
|
||||
target = _nthWeekdayOfMonth(ny, nm, wd, n);
|
||||
} else if (sub === 'last') {
|
||||
const wd = parseInt(parts[2], 10);
|
||||
target = _lastWeekdayOfMonth(ny, nm, wd);
|
||||
} else {
|
||||
d = null; return;
|
||||
}
|
||||
target.setHours(hh, mm, 0, 0);
|
||||
d = target;
|
||||
return;
|
||||
}
|
||||
d = null;
|
||||
}
|
||||
|
||||
step();
|
||||
if (d === null) return null;
|
||||
const now = clock.now();
|
||||
// Cap catch-up to avoid runaway on a malformed/very-old date.
|
||||
let guard = 5000;
|
||||
while (d.getTime() <= now) {
|
||||
if (--guard <= 0) return null;
|
||||
step();
|
||||
if (d === null) return null;
|
||||
}
|
||||
return _toLocalDatetimeStr(d);
|
||||
}
|
||||
@@ -0,0 +1,503 @@
|
||||
/** Notes composition and intentional public API. The legacy entry activates compatibility startup. */
|
||||
import { createSelectionOperations } from './application/selection.js';
|
||||
import { createToolbar } from './ui/toolbar.js';
|
||||
import { createWindowLayout } from './ui/windowLayout.js';
|
||||
import { createCardOperations } from './application/cardOperations.js';
|
||||
import { createChecklistOperations } from './application/checklistOperations.js';
|
||||
import { createNotesSubmission } from './application/submission.js';
|
||||
import { createNotesDrafts } from './application/drafts.js';
|
||||
import { createNotesLifecycle } from './ui/lifecycle.js';
|
||||
import * as noteRules from './domain/noteRules.js';
|
||||
import { createText } from './ui/text.js';
|
||||
import { createColors } from './ui/colors.js';
|
||||
import { createPanel } from './ui/panel.js';
|
||||
import { createReminderDisplay } from './ui/reminderDisplay.js';
|
||||
import { createSelection } from './ui/selection.js';
|
||||
import { createFilters } from './ui/filters.js';
|
||||
import { createCardRendering } from './ui/cardRendering.js';
|
||||
import { createLayout } from './ui/layout.js';
|
||||
import { createQuickAdd } from './ui/quickAdd.js';
|
||||
import { createCardInteractions } from './ui/cardInteractions.js';
|
||||
import { createCardChecklist } from './ui/cardChecklist.js';
|
||||
import { createCardReorder } from './ui/cardReorder.js';
|
||||
import { createDraftEditor } from './ui/draftEditor.js';
|
||||
import { createEditor } from './ui/editor.js';
|
||||
import { createReminderPicker } from './ui/reminderPicker.js';
|
||||
import { createChecklist } from './ui/checklist.js';
|
||||
import { createDrawing } from './ui/drawing.js';
|
||||
import { createClipboard } from './ui/clipboard.js';
|
||||
import { createMobileEditor } from './ui/mobileEditor.js';
|
||||
import { createMobileReorder } from './ui/mobileReorder.js';
|
||||
import { createChecklistReorder } from './ui/checklistReorder.js';
|
||||
import { createQueries } from './application/queries.js';
|
||||
import { createAgentActions } from './application/agentActions.js';
|
||||
import { createDeletion } from './application/deletion.js';
|
||||
import { createNotesReminders } from './application/reminders.js';
|
||||
import { createNotesNotifications } from './infrastructure/notifications.js';
|
||||
import { createNotesState } from './application/state.js';
|
||||
import { createNotesWorkflows } from './application/workflows.js';
|
||||
import { createNotesApi } from './infrastructure/http.js';
|
||||
import { createNotesPersistence, REMINDER_DISMISSED_AT_KEY, NOTES_FIRST_OPEN_HINT_KEY, NOTES_LABELS_COLLAPSED_KEY } from './infrastructure/storage.js';
|
||||
import * as dates from './domain/recurrence.js';
|
||||
import uiModule from '/static/js/ui.js?v=20260916largetoolscroll1';
|
||||
import { spawnConfetti } from '/static/js/shared/ui/confetti.js';
|
||||
import * as Modals from '/static/js/modalManager.js';
|
||||
import { attachColorPicker } from '/static/js/colorPicker.js?v=20260910eyedropper1';
|
||||
import { makeWindowDraggable } from '/static/js/windowDrag.js';
|
||||
import { snapModalToZone } from '/static/js/tileManager.js?v=20260910responsivebounds1';
|
||||
import { applyEdgeDock, clearDockSide } from '/static/js/modalSnap.js';
|
||||
import { topToolWindowZ, topPortalZ } from '/static/js/toolWindowZOrder.js';
|
||||
import { bindMenuDismiss, dismissOrRemove } from '/static/js/escMenuStack.js';
|
||||
import { bindTourHintDismiss } from '/static/js/tourHintDismiss.js';
|
||||
|
||||
const api = createNotesApi({ origin: window.location.origin, request: (...args) => fetch(...args) });
|
||||
const persistence = createNotesPersistence({ storage: typeof localStorage === 'undefined' ? undefined : localStorage });
|
||||
const { _loadPendingHighlights, _loadGlowedReminders, _saveGlowedReminders, _loadActiveHighlights, _saveActiveHighlights, _savePendingHighlights, _loadFiredReminders, _saveFiredReminders, _draftKey, _loadDraft, _clearDraft } = persistence;
|
||||
const clock = { now: () => Date.now() };
|
||||
const app = createNotesState({
|
||||
viewMode: (typeof localStorage !== 'undefined' && localStorage.getItem('odysseus-notes-view')) || 'list',
|
||||
labelsCollapsed: typeof localStorage !== 'undefined' && localStorage.getItem(NOTES_LABELS_COLLAPSED_KEY) === '1',
|
||||
firedDotDismissedAt: (() => { try { const v = parseInt(persistence.getItem(REMINDER_DISMISSED_AT_KEY) || '0', 10); return Number.isFinite(v) && v > 0 ? v : 0; } catch { return 0; } })(),
|
||||
});
|
||||
const state = app.state;
|
||||
const lifecycle = createNotesLifecycle();
|
||||
const scheduler = { setTimeout: (...args) => setTimeout(...args), clearTimeout: id => clearTimeout(id), setInterval: (...args) => setInterval(...args), clearInterval: id => clearInterval(id) };
|
||||
const notifications = createNotesNotifications({ browser: window, notify: window.Notification, openPanel: () => openPanel(), toast: title => uiModule?.showToast?.(title) });
|
||||
const reminders = createNotesReminders({
|
||||
app,
|
||||
api,
|
||||
persistence,
|
||||
notifications,
|
||||
clock,
|
||||
scheduler,
|
||||
fetchNotes: () => _fetchNotes(),
|
||||
isNoteFullyDone: note => _isNoteFullyDone(note),
|
||||
hasItems: note => _hasItems(note),
|
||||
dismissedKey: REMINDER_DISMISSED_AT_KEY,
|
||||
effects: { badge: () => _updateRailBadge(), highlight: id => {
|
||||
_setReminderCardGlow(id, true);
|
||||
const card = document.querySelector(`.note-card[data-note-id="${id}"]`);
|
||||
if (card) { card.classList.add('note-card-reminder-fired'); setTimeout(() => card.classList.remove('note-card-reminder-fired'), 3000); }
|
||||
else _queuePendingHighlight(id);
|
||||
} }
|
||||
});
|
||||
const workflows = createNotesWorkflows({
|
||||
app,
|
||||
api,
|
||||
effects: {
|
||||
render: () => _renderNotes(),
|
||||
showError: (...args) => uiModule.showError(...args),
|
||||
archived: undo => uiModule.showToast('Archived', { duration: 6000, action: 'Undo', actionIcon: _NOTE_UNDO_ICON, onAction: undo, actionHint: 'Ctrl+Z' }),
|
||||
celebrateArchive: (note, card) => { if (_hasItems(note) && !(note.items || []).some(i => !i.done)) { const r = card.getBoundingClientRect(); spawnConfetti(r.left + r.width / 2, r.top + r.height / 2, 80); } },
|
||||
}
|
||||
});
|
||||
const _NOTE_UNDO_ICON = '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:middle;"><polyline points="9 14 4 9 9 4"/><path d="M4 9h11a5 5 0 0 1 5 5v0a5 5 0 0 1-5 5H9"/></svg>';
|
||||
function _pushUndo(entry) { return workflows._pushUndo(entry); }
|
||||
function _popAndRunUndo() { return workflows._popAndRunUndo(); }
|
||||
function _undoArchive(note, prevIdx) { return workflows._undoArchive(note, prevIdx); }
|
||||
function _archiveNoteById(id, options) { return workflows._archiveNoteById(id, options); }
|
||||
function _fetchNotes() { return workflows._fetchNotes(); }
|
||||
|
||||
function _deleteNoteApi(id) { return workflows._deleteNoteApi(id); }
|
||||
function _patchNote(id, patch) { return workflows._patchNote(id, patch); }
|
||||
function _uid() { return Math.random().toString(36).slice(2, 10); }
|
||||
function _formatDueDate(dateStr) { return dates._formatDueDate(dateStr, clock); }
|
||||
function _isDueOverdue(dateStr) { return dates._isDueOverdue(dateStr, clock); }
|
||||
|
||||
function _laterTodayDate() { return dates._laterTodayDate(clock); }
|
||||
function _tomorrowDate() { return dates._tomorrowDate(clock); }
|
||||
function _nextWeekDate() { return dates._nextWeekDate(clock); }
|
||||
function _formatReminderTag(dateStr) { return dates._formatReminderTag(dateStr, clock); }
|
||||
function _snapToRepeat(currentDate, normRepeat) { return dates._snapToRepeat(currentDate, normRepeat, clock); }
|
||||
function _ensureNotificationPermission() { return notifications.ensurePermission(); }
|
||||
|
||||
function _startReminderLoop() { return reminders._startReminderLoop(); }
|
||||
|
||||
function _countFiredReminders() { return reminders._countFiredReminders(); }
|
||||
|
||||
function _hasActiveReminder(...args) { return noteRules._hasActiveReminder(...args, clock); }
|
||||
const _isNoteFullyDone = noteRules._isNoteFullyDone;
|
||||
const _hasItems = noteRules._hasItems;
|
||||
function _isPastReminder(...args) { return noteRules._isPastReminder(...args, clock); }
|
||||
function _esc(...args) { return text._esc(...args); }
|
||||
|
||||
function _safeImgSrc(...args) { return text._safeImgSrc(...args); }
|
||||
function _linkify(...args) { return text._linkify(...args); }
|
||||
function _isBgImage(...args) { return colors._isBgImage(...args); }
|
||||
|
||||
function _dotBg(...args) { return colors._dotBg(...args); }
|
||||
function _dotIsActive(...args) { return colors._dotIsActive(...args); }
|
||||
function _customColorStyle(...args) { return colors._customColorStyle(...args); }
|
||||
function _pickCustomBgImage(...args) { return colors._pickCustomBgImage(...args); }
|
||||
function _wireFormColors(...args) { return colors._wireFormColors(...args); }
|
||||
|
||||
function openPanel(...args) { return panel.openPanel(...args); }
|
||||
|
||||
function _smoothScrollToNoteCard(...args) { return panel._smoothScrollToNoteCard(...args); }
|
||||
function _clearViewedReminderGlows(...args) { return reminderDisplay._clearViewedReminderGlows(...args); }
|
||||
function _setReminderCardGlow(...args) { return reminderDisplay._setReminderCardGlow(...args); }
|
||||
function _queuePendingHighlight(...args) { return reminderDisplay._queuePendingHighlight(...args); }
|
||||
function _flushPendingHighlights(...args) { return reminderDisplay._flushPendingHighlights(...args); }
|
||||
function _updateRailBadge(...args) { return reminderDisplay._updateRailBadge(...args); }
|
||||
function _enterSelectMode(...args) { return selection._enterSelectMode(...args); }
|
||||
function _exitSelectMode(...args) { return selection._exitSelectMode(...args); }
|
||||
function _updateBulkBar(...args) { return selection._updateBulkBar(...args); }
|
||||
|
||||
function _renderLabelsInto(...args) { return filters._renderLabelsInto(...args); }
|
||||
function _renderLoadingSkeleton(...args) { return cardRendering._renderLoadingSkeleton(...args); }
|
||||
function _renderNotes(...args) { return cardRendering._renderNotes(...args); }
|
||||
function _captureCardPositions(...args) { return layout._captureCardPositions(...args); }
|
||||
function _animateReflow(...args) { return layout._animateReflow(...args); }
|
||||
function _applyMasonry(...args) { return layout._applyMasonry(...args); }
|
||||
function _renderQuickAdd(...args) { return quickAdd._renderQuickAdd(...args); }
|
||||
|
||||
function _editNote(...args) { return quickAdd._editNote(...args); }
|
||||
function _bindCardEvents(...args) { return cardInteractions._bindCardEvents(...args); }
|
||||
function _wireCardChecklist(...args) { return cardChecklist._wireCardChecklist(...args); }
|
||||
function _wireTodayView(...args) { return cardChecklist._wireTodayView(...args); }
|
||||
function _wireCardReorder(...args) { return cardReorder._wireCardReorder(...args); }
|
||||
|
||||
function _wireDraftAutosave(...args) { return draftEditor._wireDraftAutosave(...args); }
|
||||
function _commitOpenInPlaceEditor(...args) { return draftEditor._commitOpenInPlaceEditor(...args); }
|
||||
function _applyDraftToNote(...args) { return draftEditor._applyDraftToNote(...args); }
|
||||
function _buildForm(...args) { return editor._buildForm(...args); }
|
||||
function _wireReminderPicker(...args) { return reminderPicker._wireReminderPicker(...args); }
|
||||
function _buildGoalHtml(...args) { return checklist._buildGoalHtml(...args); }
|
||||
function _wireGoalForm(...args) { return checklist._wireGoalForm(...args); }
|
||||
function _buildChecklistHtml(...args) { return checklist._buildChecklistHtml(...args); }
|
||||
function _wireRow(...args) { return checklist._wireRow(...args); }
|
||||
function _wireChecklist(...args) { return checklist._wireChecklist(...args); }
|
||||
function _collectItems(...args) { return checklist._collectItems(...args); }
|
||||
function _buildDrawHtml(...args) { return drawing._buildDrawHtml(...args); }
|
||||
function _wireCanvas(...args) { return drawing._wireCanvas(...args); }
|
||||
function _uploadCanvasAsPng(...args) { return drawing._uploadCanvasAsPng(...args); }
|
||||
function _openNoteCornerMenu(...args) { return clipboard._openNoteCornerMenu(...args); }
|
||||
function _copyNote(...args) { return clipboard._copyNote(...args); }
|
||||
function _isNotesMobileMode(...args) { return mobileEditor._isNotesMobileMode(...args); }
|
||||
function _openMobileFullscreenEdit(...args) { return mobileEditor._openMobileFullscreenEdit(...args); }
|
||||
function _closeMobileFullscreenEdit(...args) { return mobileEditor._closeMobileFullscreenEdit(...args); }
|
||||
|
||||
function _bindLongPressDrag(...args) { return mobileReorder._bindLongPressDrag(...args); }
|
||||
|
||||
function _wireChecklistTouchReorder(...args) { return checklistReorder._wireChecklistTouchReorder(...args); }
|
||||
|
||||
function _sortedVisibleNotes(...args) { return queries._sortedVisibleNotes(...args); }
|
||||
function _userVisibleNotes(...args) { return queries._userVisibleNotes(...args); }
|
||||
function _agentSolveNote(...args) { return agentActions._agentSolveNote(...args); }
|
||||
|
||||
function _clearPastReminders(...args) { return deletion._clearPastReminders(...args); }
|
||||
const text = createText({
|
||||
uiModule
|
||||
});
|
||||
const colors = createColors({
|
||||
api
|
||||
});
|
||||
const { COLORS, COLOR_HEX } = colors;
|
||||
const windowLayout = createWindowLayout({
|
||||
makeWindowDraggable,
|
||||
snapModalToZone,
|
||||
clearDockSide,
|
||||
applyEdgeDock,
|
||||
topToolWindowZ
|
||||
});
|
||||
const toolbar = createToolbar({
|
||||
app,
|
||||
state,
|
||||
persistence,
|
||||
_renderNotes,
|
||||
_fetchNotes,
|
||||
_applyMasonry
|
||||
});
|
||||
const panel = createPanel({
|
||||
wireToolbar: toolbar.wireToolbar,
|
||||
wireSelectionActions: () => selection.wireSelectionActions(),
|
||||
_wireNotesWindow: windowLayout._wireNotesWindow,
|
||||
_restoreNotesSidebarDock: windowLayout._restoreNotesSidebarDock,
|
||||
_bringNotesToFront: windowLayout._bringNotesToFront,
|
||||
disposeUI: () => { layout.dispose(); mobileReorder.dispose(); checklistReorder.dispose(); lifecycle.dispose(); },
|
||||
lifecycle,
|
||||
Modals,
|
||||
NOTES_FIRST_OPEN_HINT_KEY,
|
||||
REMINDER_DISMISSED_AT_KEY,
|
||||
_clearViewedReminderGlows,
|
||||
_closeMobileFullscreenEdit,
|
||||
_commitOpenInPlaceEditor,
|
||||
_copyNote,
|
||||
_enterSelectMode,
|
||||
_exitSelectMode,
|
||||
_fetchNotes,
|
||||
_flushPendingHighlights,
|
||||
_isNotesMobileMode,
|
||||
_popAndRunUndo,
|
||||
_renderLoadingSkeleton,
|
||||
_renderNotes,
|
||||
_startReminderLoop,
|
||||
app,
|
||||
bindTourHintDismiss,
|
||||
dismissOrRemove,
|
||||
persistence,
|
||||
state,
|
||||
workflows
|
||||
});
|
||||
const reminderDisplay = createReminderDisplay({
|
||||
_countFiredReminders,
|
||||
_hasActiveReminder,
|
||||
_loadActiveHighlights,
|
||||
_loadGlowedReminders,
|
||||
_loadPendingHighlights,
|
||||
_saveActiveHighlights,
|
||||
_saveGlowedReminders,
|
||||
_savePendingHighlights,
|
||||
_smoothScrollToNoteCard,
|
||||
state
|
||||
});
|
||||
const selectionOperations = createSelectionOperations({
|
||||
app,
|
||||
api,
|
||||
fetchNotes: _fetchNotes,
|
||||
exitSelection: _exitSelectMode,
|
||||
sendContext: detail => window.dispatchEvent(new CustomEvent('odysseus:notes-context-selected', { detail })),
|
||||
effects: { render: _renderNotes, styledConfirm: uiModule.styledConfirm, showToast: (...args) => uiModule.showToast(...args) }
|
||||
});
|
||||
const selection = createSelection({
|
||||
operations: selectionOperations,
|
||||
_renderNotes,
|
||||
app,
|
||||
state
|
||||
});
|
||||
const filters = createFilters({
|
||||
NOTES_LABELS_COLLAPSED_KEY,
|
||||
_clearPastReminders,
|
||||
_esc,
|
||||
_isPastReminder,
|
||||
_renderNotes,
|
||||
_userVisibleNotes,
|
||||
app,
|
||||
persistence,
|
||||
state
|
||||
});
|
||||
const cardRendering = createCardRendering({
|
||||
COLORS,
|
||||
COLOR_HEX,
|
||||
_animateReflow,
|
||||
_applyMasonry,
|
||||
_bindCardEvents,
|
||||
_captureCardPositions,
|
||||
_customColorStyle,
|
||||
_dotBg,
|
||||
_dotIsActive,
|
||||
_esc,
|
||||
_formatDueDate,
|
||||
_formatReminderTag,
|
||||
_hasActiveReminder,
|
||||
_isBgImage,
|
||||
_isDueOverdue,
|
||||
_isNotesMobileMode,
|
||||
_linkify,
|
||||
_loadActiveHighlights,
|
||||
_renderLabelsInto,
|
||||
_renderQuickAdd,
|
||||
_safeImgSrc,
|
||||
_sortedVisibleNotes,
|
||||
_updateRailBadge,
|
||||
_wireTodayView,
|
||||
state,
|
||||
uiModule
|
||||
});
|
||||
const layout = createLayout({
|
||||
isOpen: () => state.open
|
||||
});
|
||||
const quickAdd = createQuickAdd({
|
||||
_applyDraftToNote,
|
||||
_applyMasonry,
|
||||
_buildForm,
|
||||
app,
|
||||
openPanel,
|
||||
state,
|
||||
uiModule
|
||||
});
|
||||
const cardOperations = createCardOperations({
|
||||
app,
|
||||
api,
|
||||
pushUndo: _pushUndo,
|
||||
undoArchive: _undoArchive,
|
||||
effects: { render: _renderNotes, showError: (...args) => uiModule.showError(...args), showToast: (...args) => uiModule.showToast(...args), archived: undo => uiModule.showToast('Archived', { duration: 6000, action: 'Undo', actionIcon: _NOTE_UNDO_ICON, onAction: undo, actionHint: 'Ctrl+Z' }) }
|
||||
});
|
||||
const checklistOperations = createChecklistOperations({
|
||||
app,
|
||||
api,
|
||||
uid: _uid,
|
||||
effects: { render: _renderNotes, showError: (...args) => uiModule.showError(...args) }
|
||||
});
|
||||
const cardInteractions = createCardInteractions({
|
||||
cardOperations,
|
||||
COLORS,
|
||||
_archiveNoteById,
|
||||
_bindLongPressDrag,
|
||||
_customColorStyle,
|
||||
_dotBg,
|
||||
_dotIsActive,
|
||||
_editNote,
|
||||
_isBgImage,
|
||||
_isNotesMobileMode,
|
||||
_openMobileFullscreenEdit,
|
||||
_openNoteCornerMenu,
|
||||
_pickCustomBgImage,
|
||||
_renderNotes,
|
||||
_setReminderCardGlow,
|
||||
_smoothScrollToNoteCard,
|
||||
_updateBulkBar,
|
||||
_wireCardChecklist,
|
||||
_wireCardReorder,
|
||||
app,
|
||||
spawnConfetti,
|
||||
state,
|
||||
uiModule
|
||||
});
|
||||
const cardChecklist = createCardChecklist({
|
||||
checklistOperations,
|
||||
_editNote,
|
||||
_renderNotes,
|
||||
app,
|
||||
spawnConfetti,
|
||||
state
|
||||
});
|
||||
const cardReorder = createCardReorder({
|
||||
persistOrder: cardOperations.persistOrder,
|
||||
lifecycle,
|
||||
_isNotesMobileMode,
|
||||
state
|
||||
});
|
||||
const draftEditor = createDraftEditor({
|
||||
bindDraft: (...args) => drafts.bindDraft(...args),
|
||||
_collectItems,
|
||||
_loadDraft
|
||||
});
|
||||
const editor = createEditor({
|
||||
deleteFromEditor: id => deletion.deleteFromEditor(id),
|
||||
submitNote: (...args) => submission.submitNote(...args),
|
||||
COLORS,
|
||||
_applyMasonry,
|
||||
_archiveNoteById,
|
||||
_buildChecklistHtml,
|
||||
_buildDrawHtml,
|
||||
_buildGoalHtml,
|
||||
_collectItems,
|
||||
_customColorStyle,
|
||||
_dotBg,
|
||||
_dotIsActive,
|
||||
_esc,
|
||||
_isBgImage,
|
||||
_renderNotes,
|
||||
_safeImgSrc,
|
||||
_uid,
|
||||
_uploadCanvasAsPng,
|
||||
_wireCanvas,
|
||||
_wireChecklist,
|
||||
_wireDraftAutosave,
|
||||
_wireFormColors,
|
||||
_wireGoalForm,
|
||||
_wireReminderPicker,
|
||||
api,
|
||||
app,
|
||||
state,
|
||||
uiModule
|
||||
});
|
||||
const reminderPicker = createReminderPicker({
|
||||
lifecycle,
|
||||
_ensureNotificationPermission,
|
||||
_esc,
|
||||
_formatReminderTag,
|
||||
_laterTodayDate,
|
||||
_nextWeekDate,
|
||||
_snapToRepeat,
|
||||
_tomorrowDate,
|
||||
bindMenuDismiss,
|
||||
dismissOrRemove
|
||||
});
|
||||
const checklist = createChecklist({
|
||||
_esc,
|
||||
_uid,
|
||||
spawnConfetti
|
||||
});
|
||||
const drawing = createDrawing({
|
||||
lifecycle,
|
||||
_safeImgSrc,
|
||||
api,
|
||||
attachColorPicker
|
||||
});
|
||||
const clipboard = createClipboard({
|
||||
_agentSolveNote,
|
||||
bindMenuDismiss,
|
||||
dismissOrRemove,
|
||||
state,
|
||||
topPortalZ,
|
||||
uiModule
|
||||
});
|
||||
const mobileEditor = createMobileEditor({
|
||||
_applyDraftToNote,
|
||||
_buildForm,
|
||||
_fetchNotes,
|
||||
_linkify,
|
||||
_renderNotes,
|
||||
_uid,
|
||||
_wireChecklistTouchReorder,
|
||||
_wireRow,
|
||||
app,
|
||||
state,
|
||||
uiModule
|
||||
});
|
||||
const mobileReorder = createMobileReorder({
|
||||
commitMobileOrder: cardOperations.commitMobileOrder,
|
||||
lifecycle,
|
||||
_applyMasonry,
|
||||
_enterSelectMode,
|
||||
app
|
||||
});
|
||||
const checklistReorder = createChecklistReorder({
|
||||
lifecycle
|
||||
});
|
||||
const queries = createQueries({
|
||||
_hasActiveReminder,
|
||||
state
|
||||
});
|
||||
const agentActions = createAgentActions({
|
||||
_patchNote,
|
||||
_renderNotes,
|
||||
api,
|
||||
app,
|
||||
createFormData: () => new FormData(),
|
||||
state,
|
||||
streamComplete: sid => { try { window.sessionModule?.markStreamComplete?.(sid); } catch {} },
|
||||
uiModule
|
||||
});
|
||||
const deletion = createDeletion({
|
||||
app,
|
||||
_deleteNoteApi,
|
||||
_fetchNotes,
|
||||
_isPastReminder,
|
||||
_renderNotes,
|
||||
effects: { styledConfirm: uiModule.styledConfirm, confirm: message => confirm(message), showToast: (...args) => uiModule.showToast(...args), showError: (...args) => uiModule.showError(...args) },
|
||||
state
|
||||
});
|
||||
const notesModule = { openPanel: panel.openPanel, closePanel: panel.closePanel, togglePanel: panel.togglePanel, isPanelOpen: panel.isPanelOpen, openNote: panel.openNote, newNote: quickAdd.newNote, openNotes: panel.openPanel, closeNotes: panel.closePanel, isNotesOpen: panel.isPanelOpen, refreshDueBadge: reminders.refreshDueBadge };
|
||||
const publicOpenPanel = panel.openPanel, publicClosePanel = panel.closePanel, publicTogglePanel = panel.togglePanel, publicIsPanelOpen = panel.isPanelOpen, publicOpenNote = panel.openNote, publicNewNote = quickAdd.newNote, publicRefreshDueBadge = reminders.refreshDueBadge, publicDismissFiredReminderDot = reminders.dismissFiredReminderDot;
|
||||
export { publicOpenPanel as openPanel, publicClosePanel as closePanel, publicTogglePanel as togglePanel, publicIsPanelOpen as isPanelOpen, publicOpenNote as openNote, publicNewNote as newNote, publicRefreshDueBadge as refreshDueBadge, publicDismissFiredReminderDot as dismissFiredReminderDot, publicOpenPanel as openNotes, publicClosePanel as closeNotes, publicIsPanelOpen as isNotesOpen };
|
||||
export function startNotesBackground() { reminders.start(); }
|
||||
export default notesModule;
|
||||
const submission = createNotesSubmission({
|
||||
app,
|
||||
api,
|
||||
persistence,
|
||||
clock,
|
||||
uid: _uid,
|
||||
fetchNotes: _fetchNotes,
|
||||
effects: { render: _renderNotes, showError: (...args) => uiModule.showError(...args), clearGlow: id => _setReminderCardGlow(id, false) }
|
||||
});
|
||||
const drafts = createNotesDrafts({
|
||||
app,
|
||||
api,
|
||||
persistence,
|
||||
scheduler,
|
||||
effects: { showError: (...args) => uiModule.showError(...args) }
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
/** Notes HTTP port. Response interpretation stays with the owning workflow. */
|
||||
export function createNotesApi({ origin, request }) {
|
||||
const json = (method, body) => ({ method, credentials: 'same-origin', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
|
||||
async function saveNote(note) {
|
||||
const response = await request(note.id ? `${origin}/api/notes/${note.id}` : `${origin}/api/notes`, json(note.id ? 'PUT' : 'POST', note));
|
||||
if (!response.ok) throw new Error('Failed to save note');
|
||||
return await response.json();
|
||||
}
|
||||
async function patchNote(id, patch) {
|
||||
const response = await request(`${origin}/api/notes/${id}`, json('PUT', patch));
|
||||
if (!response.ok) throw new Error('Failed to update note');
|
||||
return await response.json();
|
||||
}
|
||||
async function deleteNote(id) {
|
||||
const response = await request(`${origin}/api/notes/${id}`, { method: 'DELETE', credentials: 'same-origin' });
|
||||
if (!response.ok) throw new Error('HTTP ' + response.status);
|
||||
}
|
||||
return {
|
||||
saveNote, patchNote, deleteNote,
|
||||
listNotes: archived => request(`${origin}/api/notes${archived ? '?archived=true' : ''}`, { credentials: 'same-origin' }),
|
||||
reorder: ids => request(`${origin}/api/notes/reorder`, json('POST', { ids })),
|
||||
upload: body => request(`${origin}/api/upload`, { method: 'POST', body, credentials: 'same-origin' }),
|
||||
uploadUrl: id => `${origin}/api/upload/${id}`,
|
||||
fireReminder: body => request('/api/notes/fire-reminder', json('POST', body)),
|
||||
defaultChat: () => request(`${origin}/api/default-chat`, { credentials: 'same-origin' }),
|
||||
createSession: body => request(`${origin}/api/session`, { method: 'POST', body, credentials: 'same-origin' }),
|
||||
startChat: body => request(`${origin}/api/chat_stream`, { method: 'POST', body, credentials: 'same-origin' }),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
/** Browser notification permission/display port, independent of Notes rendering. */
|
||||
export function createNotesNotifications({ browser, notify, openPanel, toast }) {
|
||||
async function ensurePermission() {
|
||||
if (!('Notification' in browser)) return false;
|
||||
if (notify.permission === 'granted') return true;
|
||||
if (notify.permission === 'denied') return false;
|
||||
try { return await notify.requestPermission() === 'granted'; }
|
||||
catch { return false; }
|
||||
}
|
||||
function show(title, body, noteId) {
|
||||
if ('Notification' in browser && notify.permission === 'granted') {
|
||||
try {
|
||||
const notification = new notify(title, { body, tag: 'note-' + noteId, icon: '/static/favicon.ico' });
|
||||
notification.onclick = () => { browser.focus(); openPanel(); notification.close(); };
|
||||
} catch {}
|
||||
}
|
||||
toast(title);
|
||||
}
|
||||
return { ensurePermission, show };
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
/** Browser persistence and unchanged Notes key/serialization contracts. */
|
||||
export const REMINDER_FIRED_KEY = 'odysseus-notes-reminder-fired';
|
||||
export const REMINDER_GLOWED_KEY = 'odysseus-notes-reminder-glowed';
|
||||
export const REMINDER_PENDING_HIGHLIGHT_KEY = 'odysseus-notes-reminder-pending-highlight';
|
||||
export const REMINDER_ACTIVE_HIGHLIGHT_KEY = 'odysseus-notes-reminder-active-highlight';
|
||||
export const REMINDER_DISMISSED_AT_KEY = 'odysseus-notes-reminder-dismissed-at';
|
||||
export const NOTES_FIRST_OPEN_HINT_KEY = 'odysseus-notes-first-open-hint-v1';
|
||||
export const NOTES_LABELS_COLLAPSED_KEY = 'odysseus-notes-labels-collapsed';
|
||||
export const _DRAFT_PREFIX = 'odysseus-note-draft-';
|
||||
|
||||
export function createNotesPersistence({ storage: localStorage }) {
|
||||
function _loadPendingHighlights() {
|
||||
try { return new Set(JSON.parse(localStorage.getItem(REMINDER_PENDING_HIGHLIGHT_KEY) || '[]')); }
|
||||
catch { return new Set(); }
|
||||
}
|
||||
|
||||
function _loadGlowedReminders() {
|
||||
try { return new Set(JSON.parse(localStorage.getItem(REMINDER_GLOWED_KEY) || '[]')); }
|
||||
catch { return new Set(); }
|
||||
}
|
||||
|
||||
function _saveGlowedReminders(set) {
|
||||
try { localStorage.setItem(REMINDER_GLOWED_KEY, JSON.stringify([...set])); } catch {}
|
||||
}
|
||||
|
||||
function _loadActiveHighlights() {
|
||||
try { return new Set(JSON.parse(localStorage.getItem(REMINDER_ACTIVE_HIGHLIGHT_KEY) || '[]')); }
|
||||
catch { return new Set(); }
|
||||
}
|
||||
|
||||
function _saveActiveHighlights(set) {
|
||||
try { localStorage.setItem(REMINDER_ACTIVE_HIGHLIGHT_KEY, JSON.stringify([...set])); } catch {}
|
||||
}
|
||||
|
||||
function _savePendingHighlights(set) {
|
||||
try { localStorage.setItem(REMINDER_PENDING_HIGHLIGHT_KEY, JSON.stringify([...set])); }
|
||||
catch {}
|
||||
}
|
||||
|
||||
function _loadFiredReminders() {
|
||||
try { return new Set(JSON.parse(localStorage.getItem(REMINDER_FIRED_KEY) || '[]')); }
|
||||
catch { return new Set(); }
|
||||
}
|
||||
|
||||
function _saveFiredReminders(set) {
|
||||
try { localStorage.setItem(REMINDER_FIRED_KEY, JSON.stringify([...set])); }
|
||||
catch {}
|
||||
}
|
||||
|
||||
function _draftKey(id) { return _DRAFT_PREFIX + (id || '__new__'); }
|
||||
|
||||
function _loadDraft(id) {
|
||||
try { return JSON.parse(localStorage.getItem(_draftKey(id)) || 'null'); } catch { return null; }
|
||||
}
|
||||
|
||||
function _clearDraft(id) { try { localStorage.removeItem(_draftKey(id)); } catch {} }
|
||||
|
||||
return { _loadPendingHighlights, _loadGlowedReminders, _saveGlowedReminders, _loadActiveHighlights, _saveActiveHighlights, _savePendingHighlights, _loadFiredReminders, _saveFiredReminders, _draftKey, _loadDraft, _clearDraft,
|
||||
getItem: key => localStorage.getItem(key),
|
||||
setItem: (key, value) => localStorage.setItem(key, value),
|
||||
removeItem: key => localStorage.removeItem(key),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
/** Card checklist editing and Today-step interactions. */
|
||||
export function createCardChecklist({
|
||||
checklistOperations,
|
||||
_editNote,
|
||||
_renderNotes,
|
||||
app,
|
||||
spawnConfetti,
|
||||
state
|
||||
}) {
|
||||
function _wireCardChecklist(body) {
|
||||
// Remove a single checklist item (hover X)
|
||||
body.querySelectorAll('.note-checkbox-rm').forEach(btn => {
|
||||
btn.addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
if (state.selectMode) return;
|
||||
const noteId = btn.dataset.noteId;
|
||||
const idx = parseInt(btn.dataset.idx);
|
||||
checklistOperations.removeItem(noteId, idx);
|
||||
});
|
||||
});
|
||||
|
||||
function _startChecklistItemEdit(noteId, idx, span) {
|
||||
if (span.isContentEditable) return;
|
||||
const note = state.notes.find(n => n.id === noteId);
|
||||
if (!note || !Array.isArray(note.items) || !note.items[idx]) return;
|
||||
|
||||
span.textContent = note.items[idx].text || '';
|
||||
span.contentEditable = "true";
|
||||
span.spellcheck = false;
|
||||
span.focus();
|
||||
|
||||
const selection = window.getSelection();
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(span);
|
||||
selection.removeAllRanges();
|
||||
selection.addRange(range);
|
||||
|
||||
const save = () => {
|
||||
if (!span.isContentEditable) return;
|
||||
span.contentEditable = "false";
|
||||
const newText = span.textContent.trim();
|
||||
checklistOperations.editItem(note, idx, newText);
|
||||
};
|
||||
|
||||
const onKeydown = (e) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
save();
|
||||
} else if (e.key === 'Escape') {
|
||||
e.preventDefault();
|
||||
span.contentEditable = "false";
|
||||
_renderNotes();
|
||||
}
|
||||
};
|
||||
|
||||
span.addEventListener('blur', save, { once: true });
|
||||
span.addEventListener('keydown', onKeydown);
|
||||
}
|
||||
|
||||
// Edit a single checklist item (hover Edit button)
|
||||
body.querySelectorAll('.note-checkbox-edit').forEach(btn => {
|
||||
btn.addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
if (state.selectMode) return;
|
||||
const noteId = btn.dataset.noteId;
|
||||
const idx = parseInt(btn.dataset.idx);
|
||||
const span = btn.parentElement.querySelector('.note-check-text');
|
||||
if (span) _startChecklistItemEdit(noteId, idx, span);
|
||||
});
|
||||
});
|
||||
|
||||
// Prevent clicks from toggling the row while actively editing inline
|
||||
body.querySelectorAll('.note-check-text').forEach(span => {
|
||||
span.addEventListener('click', (e) => {
|
||||
if (span.isContentEditable) {
|
||||
e.stopPropagation();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Quick-add new checklist item (hover input at bottom of todo cards)
|
||||
body.querySelectorAll('.note-cl-quickadd-input').forEach(input => {
|
||||
input.addEventListener('click', (e) => e.stopPropagation());
|
||||
input.addEventListener('keydown', async (e) => {
|
||||
e.stopPropagation();
|
||||
if (e.key !== 'Enter') return;
|
||||
e.preventDefault();
|
||||
const text = input.value.trim();
|
||||
if (!text) return;
|
||||
const noteId = input.dataset.noteId;
|
||||
const persist = checklistOperations.addItem(noteId, text, () => { input.value = ''; });
|
||||
if (!persist) return;
|
||||
// Refocus the input on the same card
|
||||
setTimeout(() => {
|
||||
const next = document.querySelector(`.note-cl-quickadd-input[data-note-id="${noteId}"]`);
|
||||
if (next) next.focus();
|
||||
}, 0);
|
||||
persist();
|
||||
});
|
||||
});
|
||||
|
||||
// Checkboxes (dot toggle, optimistic) : disabled in select mode
|
||||
body.querySelectorAll('.note-checkbox').forEach(el => {
|
||||
el.addEventListener('click', (e) => {
|
||||
if (state.selectMode) return; // let card-level handler take over
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
const noteId = el.dataset.noteId;
|
||||
const idx = parseInt(el.dataset.idx);
|
||||
checklistOperations.toggleItem(noteId, idx, done => el.classList.toggle('done', done), () => {
|
||||
const card = el.closest('.note-card');
|
||||
if (card) { const r = card.getBoundingClientRect(); spawnConfetti(r.left + r.width / 2, r.top + r.height / 2, 60); }
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
}
|
||||
|
||||
function _wireTodayView(body) {
|
||||
body.querySelectorAll('.notes-today-row .note-check-dot').forEach(dot => {
|
||||
dot.addEventListener('click', async (e) => {
|
||||
e.stopPropagation();
|
||||
const id = dot.dataset.noteId;
|
||||
const idx = parseInt(dot.dataset.idx);
|
||||
const row = dot.closest('.notes-today-row');
|
||||
await checklistOperations.toggleTodayStep(id, idx, () => row?.classList.add('done'), () => {
|
||||
const r = (row || dot).getBoundingClientRect();
|
||||
spawnConfetti(r.left + r.width / 2, r.top + r.height / 2, 60);
|
||||
});
|
||||
});
|
||||
});
|
||||
body.querySelectorAll('.notes-today-title').forEach(el => {
|
||||
el.addEventListener('click', () => {
|
||||
const id = el.dataset.noteId;
|
||||
if (!id) return;
|
||||
// Drop the Today filter first so the regular card list is rendered;
|
||||
// _editNote needs to find a .note-card in the DOM to replace with
|
||||
// the editor form.
|
||||
app.setActiveFilter(null);
|
||||
_renderNotes();
|
||||
_editNote(id);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
return { _wireCardChecklist, _wireTodayView };
|
||||
}
|
||||
@@ -0,0 +1,337 @@
|
||||
/** Card taps, pin/color controls, menus and archive animation. */
|
||||
export function createCardInteractions({
|
||||
cardOperations,
|
||||
COLORS,
|
||||
_archiveNoteById,
|
||||
_bindLongPressDrag,
|
||||
_customColorStyle,
|
||||
_dotBg,
|
||||
_dotIsActive,
|
||||
_editNote,
|
||||
_isBgImage,
|
||||
_isNotesMobileMode,
|
||||
_openMobileFullscreenEdit,
|
||||
_openNoteCornerMenu,
|
||||
_pickCustomBgImage,
|
||||
_renderNotes,
|
||||
_setReminderCardGlow,
|
||||
_smoothScrollToNoteCard,
|
||||
_updateBulkBar,
|
||||
_wireCardChecklist,
|
||||
_wireCardReorder,
|
||||
app,
|
||||
spawnConfetti,
|
||||
state,
|
||||
uiModule
|
||||
}) {
|
||||
function _bindCardEvents(body) {
|
||||
// Skip completed leading rows so the first unfinished checklist item is
|
||||
// visible when a note preview has its own scroll area.
|
||||
requestAnimationFrame(() => {
|
||||
body.querySelectorAll('.note-checklist-preview').forEach(preview => {
|
||||
const firstPending = preview.querySelector('.note-checkbox:not(.done)');
|
||||
if (firstPending) preview.scrollTop = Math.max(0, firstPending.offsetTop - 4);
|
||||
});
|
||||
});
|
||||
const tapToEditOrSelect = (cardEl) => {
|
||||
const id = cardEl.dataset.noteId;
|
||||
// A long-press enters select mode and re-renders the card. Ignore the
|
||||
// synthetic click that mobile browsers emit when that same touch ends.
|
||||
if (state.suppressNextNoteTapId === id) {
|
||||
app.setSuppressNextNoteTapId(null);
|
||||
return;
|
||||
}
|
||||
if (state.selectMode) {
|
||||
const cb = cardEl.querySelector('.note-card-cb');
|
||||
if (cb) {
|
||||
cb.checked = !cb.checked;
|
||||
cb.dispatchEvent(new Event('change'));
|
||||
}
|
||||
} else if (_isNotesMobileMode()) {
|
||||
// Mobile: open the per-note fullscreen edit overlay instead of the
|
||||
// in-place form. Tiles on mobile are read-only previews.
|
||||
_openMobileFullscreenEdit(id, cardEl);
|
||||
} else {
|
||||
_editNote(id);
|
||||
}
|
||||
};
|
||||
// Mobile: long-press anywhere on a note card → enter Select mode and
|
||||
// select that card. Cancelled by movement (so it doesn't interfere with
|
||||
// vertical scrolling) or by lifting the finger before the timer fires.
|
||||
if (_isNotesMobileMode()) {
|
||||
body.querySelectorAll('.note-card').forEach(card => _bindLongPressDrag(card));
|
||||
}
|
||||
body.querySelectorAll('.note-card.note-card-reminder-fired-sticky').forEach(card => {
|
||||
card.addEventListener('click', () => _setReminderCardGlow(card.dataset.noteId, false), true);
|
||||
});
|
||||
// Click title : edit, or toggle select in select mode
|
||||
body.querySelectorAll('.note-card-title[data-action="edit"]').forEach(el => {
|
||||
el.addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
_smoothScrollToNoteCard(el.closest('.note-card'));
|
||||
tapToEditOrSelect(el.closest('.note-card'));
|
||||
});
|
||||
});
|
||||
// Click content : edit, or toggle select in select mode
|
||||
body.querySelectorAll('.note-content-preview').forEach(el => {
|
||||
el.addEventListener('click', (e) => { e.stopPropagation(); tapToEditOrSelect(el.closest('.note-card')); });
|
||||
});
|
||||
// A saved drawing is the note's primary content. Open its editor directly
|
||||
// when the preview is clicked, matching title/content preview behavior.
|
||||
body.querySelectorAll('.note-card-drawing .note-card-image').forEach(el => {
|
||||
el.addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
tapToEditOrSelect(el.closest('.note-card'));
|
||||
});
|
||||
});
|
||||
// Click empty area of checklist preview (not on checkbox/X) : edit
|
||||
body.querySelectorAll('.note-checklist-preview').forEach(el => {
|
||||
el.addEventListener('wheel', (e) => {
|
||||
const atTop = el.scrollTop <= 0;
|
||||
const atBottom = el.scrollTop + el.clientHeight >= el.scrollHeight - 1;
|
||||
if ((e.deltaY < 0 && atTop) || (e.deltaY > 0 && atBottom)) {
|
||||
const pane = el.closest('.notes-pane-body');
|
||||
if (pane) {
|
||||
pane.scrollTop += e.deltaY;
|
||||
e.preventDefault();
|
||||
}
|
||||
}
|
||||
}, { passive: false });
|
||||
el.addEventListener('click', (e) => {
|
||||
if (e.target.closest('.note-checkbox, .note-checkbox-rm, .note-cl-quickadd, input')) return;
|
||||
e.stopPropagation();
|
||||
tapToEditOrSelect(el.closest('.note-card'));
|
||||
});
|
||||
});
|
||||
// Clicking todo item text now toggles its checkbox : let the click bubble
|
||||
// up to the parent .note-checkbox row handler. To open the editor, the
|
||||
// user clicks the pencil corner.
|
||||
// (No-op block kept as a marker : removing the listener entirely means
|
||||
// clicks naturally bubble to the row toggle below.)
|
||||
// In select mode, clicking anywhere on the card toggles selection
|
||||
if (state.selectMode) {
|
||||
body.querySelectorAll('.note-card').forEach(card => {
|
||||
card.addEventListener('click', (e) => {
|
||||
if (e.target.closest('.note-card-cb')) return; // checkbox handles itself
|
||||
e.stopPropagation();
|
||||
tapToEditOrSelect(card);
|
||||
});
|
||||
});
|
||||
}
|
||||
// Mobile, non-select: tapping anywhere on the card body (not on an
|
||||
// interactive child : buttons, pin, checkbox, color dot, reminder pill,
|
||||
// agent tag, links) opens the fullscreen editor. Previously only the
|
||||
// title / content preview triggered edit, so padding + empty gutters were
|
||||
// dead zones that felt broken on mobile.
|
||||
if (_isNotesMobileMode() && !state.selectMode) {
|
||||
const _INTERACTIVE = 'button, a, input, label, .note-card-color-dot, .note-checkbox, .note-checkbox-rm, .note-cl-quickadd, .note-agent-tag, .note-card-pin, .note-card-corner-trash, .note-card-corner-menu, .note-card-corner-unarchive, .note-card-edit-corner, .note-card-reminder, .note-card-cb';
|
||||
body.querySelectorAll('.note-card').forEach(card => {
|
||||
card.addEventListener('click', (e) => {
|
||||
if (e.target.closest(_INTERACTIVE)) return;
|
||||
e.stopPropagation();
|
||||
tapToEditOrSelect(card);
|
||||
});
|
||||
});
|
||||
}
|
||||
// Multi-select checkbox (only in select mode)
|
||||
body.querySelectorAll('.note-card-cb').forEach(cb => {
|
||||
cb.addEventListener('click', (e) => e.stopPropagation());
|
||||
cb.addEventListener('change', () => {
|
||||
const id = cb.dataset.noteId;
|
||||
if (cb.checked) app.selectId(id);
|
||||
else app.deselectId(id);
|
||||
cb.closest('.note-card').classList.toggle('note-card-selected', cb.checked);
|
||||
_updateBulkBar();
|
||||
});
|
||||
});
|
||||
// Pin toggle (optimistic)
|
||||
body.querySelectorAll('.note-card-pin').forEach(btn => {
|
||||
btn.addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
const id = btn.dataset.noteId;
|
||||
cardOperations.togglePin(id);
|
||||
});
|
||||
});
|
||||
// Color picker
|
||||
const _applyCardColor = async (card, id, newColor) => {
|
||||
const isBg = _isBgImage(newColor);
|
||||
COLORS.forEach(c => { if (c.value && c.value !== 'custom') card.classList.remove('note-color-' + c.value); });
|
||||
if (newColor && !isBg) card.classList.add('note-color-' + newColor);
|
||||
if (isBg) card.setAttribute('style', _customColorStyle(newColor));
|
||||
else card.removeAttribute('style');
|
||||
card.querySelectorAll('.note-card-color-dot').forEach(d => {
|
||||
d.classList.toggle('active', _dotIsActive(d.dataset.color, newColor));
|
||||
d.style.background = _dotBg(d.dataset.color, newColor);
|
||||
});
|
||||
await cardOperations.updateColor(id, newColor);
|
||||
};
|
||||
body.querySelectorAll('.note-card-color-dot').forEach(dot => {
|
||||
dot.addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
const card = dot.closest('.note-card');
|
||||
const id = card.dataset.noteId;
|
||||
if (dot.dataset.color === 'custom') {
|
||||
_pickCustomBgImage().then(url => { if (url) _applyCardColor(card, id, 'bg:' + url); });
|
||||
return;
|
||||
}
|
||||
_applyCardColor(card, id, dot.dataset.color);
|
||||
});
|
||||
});
|
||||
// Plain pencil corner → open editor. The unarchive corner shares the
|
||||
// .note-card-edit-corner class for styling, so :not() keeps the edit
|
||||
// handler off it.
|
||||
body.querySelectorAll('.note-card-edit-corner:not(.note-card-unarchive-corner)').forEach(btn => {
|
||||
btn.addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
const id = btn.dataset.noteId;
|
||||
if (id) _editNote(id);
|
||||
});
|
||||
});
|
||||
// Copy corner : bottom-right, just left of the Done check. Shared with
|
||||
// the Ctrl/Cmd+C shortcut wired further down so both code paths run the
|
||||
// same serializer + feedback flash.
|
||||
// ⋯ corner menu : Copy + Agent (solve-this-todo).
|
||||
body.querySelectorAll('.note-card-corner-menu').forEach(btn => {
|
||||
btn.addEventListener('click', (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
_openNoteCornerMenu(btn);
|
||||
});
|
||||
});
|
||||
body.querySelectorAll('.note-card-label-chip').forEach(chip => {
|
||||
chip.addEventListener('click', (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
const label = chip.dataset.noteLabelFilter;
|
||||
if (!label) return;
|
||||
if (state.activeLabel === label && state.activeFilter === null) {
|
||||
app.setActiveLabel(null);
|
||||
} else {
|
||||
app.setActiveFilter(null);
|
||||
app.setActiveLabel(label);
|
||||
}
|
||||
_renderNotes();
|
||||
});
|
||||
});
|
||||
// Done (✓) at bottom-right : only visible on hover for active notes.
|
||||
body.querySelectorAll('.note-card-done').forEach(btn => {
|
||||
btn.addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
const id = btn.dataset.noteId;
|
||||
const card = btn.closest('.note-card');
|
||||
const idx = state.notes.findIndex(n => n.id === id);
|
||||
if (idx < 0) return;
|
||||
// Celebrate completion : same confetti shower the bulk-archive uses.
|
||||
if (card) {
|
||||
const r = card.getBoundingClientRect();
|
||||
spawnConfetti(r.left + r.width / 2, r.top + r.height / 2, 80);
|
||||
}
|
||||
const finish = cardOperations.stageArchive(id);
|
||||
if (!finish) return;
|
||||
if (card) {
|
||||
card.classList.add('note-card-sliding-out');
|
||||
let done = false;
|
||||
const once = () => { if (done) return; done = true; finish(); };
|
||||
card.addEventListener('transitionend', once, { once: true });
|
||||
setTimeout(once, 400);
|
||||
} else {
|
||||
finish();
|
||||
}
|
||||
});
|
||||
});
|
||||
// Unarchive corner : only visible in archive view.
|
||||
body.querySelectorAll('.note-card-corner-unarchive').forEach(btn => {
|
||||
btn.addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
const id = btn.dataset.noteId;
|
||||
cardOperations.unarchive(id);
|
||||
});
|
||||
});
|
||||
// Trash corner : archive view only. Permanent delete, no confirmation.
|
||||
body.querySelectorAll('.note-card-corner-trash').forEach(btn => {
|
||||
btn.addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
const id = btn.dataset.noteId;
|
||||
cardOperations.deleteOptimistically(id, true);
|
||||
});
|
||||
});
|
||||
|
||||
body.querySelectorAll('.note-card-archive').forEach(btn => {
|
||||
btn.addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
const id = btn.dataset.noteId;
|
||||
if (!id) return;
|
||||
const card = btn.closest('.note-card');
|
||||
let done = false;
|
||||
const finishRemove = () => {
|
||||
if (done) return;
|
||||
done = true;
|
||||
_archiveNoteById(id, { card, celebrate: true });
|
||||
};
|
||||
if (card) {
|
||||
card.classList.add('note-card-sliding-out');
|
||||
card.addEventListener('transitionend', finishRemove, { once: true });
|
||||
setTimeout(finishRemove, 400);
|
||||
} else {
|
||||
finishRemove();
|
||||
}
|
||||
});
|
||||
});
|
||||
// Unarchive (optimistic) : only present in archive view
|
||||
body.querySelectorAll('.note-card-unarchive').forEach(btn => {
|
||||
btn.addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
const id = btn.dataset.noteId;
|
||||
cardOperations.unarchive(id);
|
||||
});
|
||||
});
|
||||
// Delete (optimistic)
|
||||
body.querySelectorAll('.note-card-delete, .note-card-x').forEach(btn => {
|
||||
btn.addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
const id = btn.dataset.noteId;
|
||||
cardOperations.deleteOptimistically(id);
|
||||
});
|
||||
});
|
||||
// Copy entire checklist (title + items, markdown-style)
|
||||
body.querySelectorAll('.note-card-copy').forEach(btn => {
|
||||
btn.addEventListener('click', async (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
e.stopImmediatePropagation();
|
||||
const id = btn.dataset.noteId;
|
||||
const note = state.notes.find(n => n.id === id);
|
||||
if (!note) return;
|
||||
const lines = [];
|
||||
if (note.title) lines.push(note.title);
|
||||
if (note.content) lines.push(note.content);
|
||||
if (lines.length) lines.push('');
|
||||
for (const it of (note.items || [])) {
|
||||
if (!it || !(it.text || '').trim()) continue;
|
||||
lines.push(`- [${it.done ? 'x' : ' '}] ${(it.text || '').trim()}`);
|
||||
}
|
||||
const text = lines.join('\n').trim();
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
uiModule.showToast?.(`Copied ${(note.items || []).filter(i => (i?.text || '').trim()).length} items`);
|
||||
} catch {
|
||||
// Fallback for browsers blocking the async API
|
||||
const ta = document.createElement('textarea');
|
||||
ta.value = text;
|
||||
ta.style.position = 'fixed'; ta.style.left = '-9999px';
|
||||
document.body.appendChild(ta);
|
||||
ta.select();
|
||||
try { document.execCommand('copy'); uiModule.showToast?.('Copied'); }
|
||||
catch { uiModule.showError?.('Copy failed'); }
|
||||
ta.remove();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
_wireCardChecklist(body);
|
||||
_wireCardReorder(body);
|
||||
|
||||
}
|
||||
|
||||
return { _bindCardEvents };
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
/** Render note cards from application queries and read-only state. */
|
||||
import { _nextGoalStep, _goalProgress, _hasItems, _standardVisualVariant, _visibleNoteTags } from '../domain/noteRules.js';
|
||||
import { _hasTimeComponent, _formatRepeatLabel } from '../domain/recurrence.js';
|
||||
export function createCardRendering({
|
||||
COLORS,
|
||||
COLOR_HEX,
|
||||
_animateReflow,
|
||||
_applyMasonry,
|
||||
_bindCardEvents,
|
||||
_captureCardPositions,
|
||||
_customColorStyle,
|
||||
_dotBg,
|
||||
_dotIsActive,
|
||||
_esc,
|
||||
_formatDueDate,
|
||||
_formatReminderTag,
|
||||
_hasActiveReminder,
|
||||
_isBgImage,
|
||||
_isDueOverdue,
|
||||
_isNotesMobileMode,
|
||||
_linkify,
|
||||
_loadActiveHighlights,
|
||||
_renderLabelsInto,
|
||||
_renderQuickAdd,
|
||||
_safeImgSrc,
|
||||
_sortedVisibleNotes,
|
||||
_updateRailBadge,
|
||||
_wireTodayView,
|
||||
state,
|
||||
uiModule
|
||||
}) {
|
||||
function _renderLoadingSkeleton() {
|
||||
const body = document.querySelector('#notes-pane .notes-pane-body');
|
||||
if (!body) return;
|
||||
body.innerHTML = '';
|
||||
_renderLabelsInto(body);
|
||||
_renderQuickAdd(body);
|
||||
const skel = document.createElement('div');
|
||||
skel.className = 'notes-skeleton';
|
||||
skel.innerHTML = `
|
||||
<div class="notes-skeleton-card"></div>
|
||||
<div class="notes-skeleton-card"></div>
|
||||
<div class="notes-skeleton-card short"></div>
|
||||
<div class="notes-skeleton-card"></div>
|
||||
`;
|
||||
body.appendChild(skel);
|
||||
}
|
||||
|
||||
function _renderNotes() {
|
||||
_updateRailBadge();
|
||||
const body = document.querySelector('#notes-pane .notes-pane-body');
|
||||
if (!body) return;
|
||||
const prevPositions = _captureCardPositions();
|
||||
const activeReminderHighlights = _loadActiveHighlights();
|
||||
|
||||
const sorted = _sortedVisibleNotes();
|
||||
|
||||
let html = '';
|
||||
// Today view: render a compact card listing the next-unchecked step from
|
||||
// each active goal. Tapping a step toggles it done (same idx-based wiring
|
||||
// as regular checkboxes). Tapping the title opens the goal note for full
|
||||
// editing.
|
||||
if (state.activeFilter === 'today') {
|
||||
body.innerHTML = '';
|
||||
_renderLabelsInto(body);
|
||||
_renderQuickAdd(body);
|
||||
if (sorted.length === 0) {
|
||||
body.insertAdjacentHTML('beforeend', `<div class="notes-empty">All caught up — no pending goal steps right now.</div>`);
|
||||
} else {
|
||||
let todayHtml = `<div class="notes-today-wrap">
|
||||
<div class="notes-today-header">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>
|
||||
<span>Today · one step per goal</span>
|
||||
</div>
|
||||
<div class="notes-today-list">`;
|
||||
for (const note of sorted) {
|
||||
const next = _nextGoalStep(note);
|
||||
if (!next) continue;
|
||||
const progress = _goalProgress(note).trim();
|
||||
todayHtml += `<div class="notes-today-row" data-note-id="${note.id}">
|
||||
<span class="note-check-dot" data-note-id="${note.id}" data-idx="${next.idx}" title="Mark step done"></span>
|
||||
<div class="notes-today-text">
|
||||
<div class="notes-today-title" data-action="edit" data-note-id="${note.id}">${_esc(note.title || '(untitled goal)')}</div>
|
||||
<div class="notes-today-step">${_linkify(next.item.text || '')}</div>
|
||||
</div>
|
||||
<span class="notes-today-progress">${_esc(progress)}</span>
|
||||
</div>`;
|
||||
}
|
||||
todayHtml += `</div></div>`;
|
||||
body.insertAdjacentHTML('beforeend', todayHtml);
|
||||
}
|
||||
_wireTodayView(body);
|
||||
return;
|
||||
}
|
||||
for (const note of sorted) {
|
||||
if (state.editingId === note.id) continue; // skip : form is shown instead
|
||||
const borderColor = COLOR_HEX[note.color || ''] || 'var(--border)';
|
||||
const dueFmt = _formatDueDate(note.due_date);
|
||||
const overdue = _isDueOverdue(note.due_date);
|
||||
|
||||
let contentHtml = '';
|
||||
if (_hasItems(note) && Array.isArray(note.items)) {
|
||||
// Goal notes can carry a free-form description above the step list :
|
||||
// todos rarely do, but the same render works for both.
|
||||
if (note.note_type === 'goal' && (note.content || '').trim()) {
|
||||
const fullText = note.content || '';
|
||||
const preview = fullText.length > 300 ? fullText.slice(0, 300) + '…' : fullText;
|
||||
contentHtml += `<div class="note-goal-desc">${_esc(preview)}</div>`;
|
||||
}
|
||||
contentHtml += '<div class="note-checklist-preview">';
|
||||
// Show ALL items : the preview container is scrollable (CSS caps
|
||||
// its max-height + overflow-y:auto), so there's no need to truncate.
|
||||
for (let i = 0; i < note.items.length; i++) {
|
||||
const item = note.items[i];
|
||||
const doneClass = item.done ? ' done' : '';
|
||||
const indent = Math.min(item.indent || 0, 3);
|
||||
contentHtml += `<div class="note-checkbox${doneClass}" data-note-id="${note.id}" data-idx="${i}" style="padding-left:${indent * 16}px">
|
||||
<span class="note-check-dot" title="Mark done"></span>
|
||||
<span class="note-check-text">${_linkify(item.text)}</span>
|
||||
<button class="note-checkbox-edit" data-note-id="${note.id}" data-idx="${i}" title="Edit item">
|
||||
<svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
|
||||
</button>
|
||||
<button class="note-checkbox-rm" data-note-id="${note.id}" data-idx="${i}" title="Delete item">
|
||||
<svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
|
||||
</button>
|
||||
</div>`;
|
||||
}
|
||||
contentHtml += '</div>';
|
||||
} else {
|
||||
const fullText = note.content || '';
|
||||
const preview = fullText.length > 600 ? fullText.slice(0, 600) + '…' : fullText;
|
||||
// _linkify already calls _esc internally, so URLs become clickable
|
||||
// anchors (used by e.g. the "remind me to reply" email deep-link).
|
||||
contentHtml = preview ? `<div class="note-content-preview">${_linkify(preview)}</div>` : '';
|
||||
}
|
||||
|
||||
const isBg = _isBgImage(note.color);
|
||||
const cc = (note.color && !isBg) ? ' note-color-' + note.color : '';
|
||||
const cardStyle = isBg ? ` style="${_customColorStyle(note.color)}"` : '';
|
||||
const isStandard = !note.note_type || note.note_type === 'note';
|
||||
const visualClass = isStandard && !note.color ? ` note-standard note-standard-v${_standardVisualVariant(note)}` : '';
|
||||
const sel = state.selectedIds.has(note.id) ? ' note-card-selected' : '';
|
||||
const reminderTagHtml = note.due_date && _hasTimeComponent(note.due_date)
|
||||
? `<div class="note-card-reminder${overdue ? ' overdue' : ''}">
|
||||
<svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 0 1-3.46 0"/></svg>
|
||||
<span>${_esc(_formatReminderTag(note.due_date))}${note.repeat && note.repeat !== 'none' ? ' · ' + _esc(_formatRepeatLabel(note.repeat, new Date(note.due_date))) : ''}</span>
|
||||
</div>`
|
||||
: '';
|
||||
const noteTags = _visibleNoteTags(note);
|
||||
const dueBadge = dueFmt && !_hasTimeComponent(note.due_date) ? `<span class="note-due-inline${overdue ? ' note-due-overdue' : ''}">${dueFmt}</span>` : '';
|
||||
const colorDots = COLORS.map(c => `<span class="note-card-color-dot${_dotIsActive(c.value, note.color) ? ' active' : ''}" data-color="${c.value}" style="background:${_dotBg(c.value, note.color)}" title="${c.name || 'default'}"></span>`).join('');
|
||||
const goalClass = note.note_type === 'goal' ? ' note-card-goal' : '';
|
||||
const reminderGlowClass = activeReminderHighlights.has(note.id) && _hasActiveReminder(note) ? ' note-card-reminder-fired-sticky' : '';
|
||||
const goalPill = note.note_type === 'goal'
|
||||
? `<span class="note-goal-pill" title="AI-broken-down goal">
|
||||
<svg width="10" height="10" viewBox="0 0 24 24" fill="currentColor"><path d="M12 0L14.59 8.41L23 12L14.59 15.59L12 24L9.41 15.59L1 12L9.41 8.41Z"/></svg>
|
||||
Goal${_goalProgress(note)}
|
||||
</span>`
|
||||
: '';
|
||||
const drawingClass = note.note_type === 'draw' ? ' note-card-drawing' : '';
|
||||
html += `<div class="note-card${note.pinned ? ' note-card-pinned' : ''}${cc}${visualClass}${sel}${goalClass}${drawingClass}${reminderGlowClass}${state.selectMode ? ' note-card-selectmode' : ''}" draggable="${(state.selectMode || _isNotesMobileMode()) ? 'false' : 'true'}" data-note-id="${note.id}"${cardStyle}>
|
||||
${state.selectMode ? `<input type="checkbox" class="memory-select-cb note-card-cb" data-note-id="${note.id}" ${state.selectedIds.has(note.id) ? 'checked' : ''} />` : ''}
|
||||
${goalPill}
|
||||
<button class="note-card-pin${note.pinned ? ' active' : ''}" data-note-id="${note.id}" title="${note.pinned ? 'Unpin' : 'Pin'}">
|
||||
<svg width="16" height="16" viewBox="0 0 24 28" fill="${note.pinned ? 'currentColor' : 'none'}" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"${note.pinned ? ' style="color:var(--accent,var(--red));"' : ''}><g transform="rotate(${note.pinned ? 0 : 45} 12 14)" style="transition:transform 0.2s ease;"><line x1="12" y1="17" x2="12" y2="27"/><path d="M5 17h14v-1.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V6h1a2 2 0 0 0 0-4H8a2 2 0 0 0 0 4h1v4.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V17z"/></g></svg>
|
||||
</button>
|
||||
${state.showingArchived
|
||||
? `<button class="note-card-corner-trash" data-note-id="${note.id}" title="Delete forever" aria-label="Delete forever">
|
||||
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/><line x1="10" y1="11" x2="10" y2="17"/><line x1="14" y1="11" x2="14" y2="17"/></svg>
|
||||
</button>
|
||||
<button class="note-card-corner-unarchive" data-note-id="${note.id}" title="Unarchive" aria-label="Unarchive note">
|
||||
<svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 14l-5-5 5-5"/><path d="M4 9h11a5 5 0 0 1 5 5v0a5 5 0 0 1-5 5H9"/></svg>
|
||||
</button>`
|
||||
: `<button class="note-card-done" data-note-id="${note.id}" title="Mark done" aria-label="Mark done">
|
||||
<svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
|
||||
</button>
|
||||
${_hasItems(note) ? `<button class="note-card-copy note-card-copy-corner" data-note-id="${note.id}" title="Copy all items" aria-label="Copy all items">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
|
||||
</button>` : ''}`}
|
||||
<div class="note-card-header">
|
||||
<div class="note-card-title${note.title ? '' : ' empty'}" data-action="edit">${_esc(note.title || '')}</div>
|
||||
${dueBadge}
|
||||
</div>
|
||||
${_safeImgSrc(note.image_url) ? `<img class="note-card-image" src="${_esc(_safeImgSrc(note.image_url))}" alt="" draggable="false" />` : ''}
|
||||
${contentHtml}
|
||||
${_hasItems(note) ? `<div class="note-cl-quickadd"><input type="text" class="note-cl-quickadd-input" placeholder="+ Add item" data-note-id="${note.id}" /></div>` : ''}
|
||||
${reminderTagHtml}
|
||||
${noteTags.length ? `<div class="note-card-label">${noteTags.map(t => `<button type="button" class="note-card-label-chip" data-note-label-filter="${_esc(t)}" title="Filter #${_esc(t)}">#${_esc(t)}</button>`).join(' ')}</div>` : ''}
|
||||
<div class="note-card-actions">
|
||||
<div class="note-card-colors">${colorDots}</div>
|
||||
<span style="flex:1"></span>
|
||||
${state.showingArchived ? `
|
||||
<button class="note-card-action note-card-delete" data-note-id="${note.id}" title="Delete permanently">
|
||||
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/><line x1="10" y1="11" x2="10" y2="17"/><line x1="14" y1="11" x2="14" y2="17"/></svg>
|
||||
</button>
|
||||
<button class="note-card-action note-card-unarchive" data-note-id="${note.id}" title="Unarchive">
|
||||
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 12a9 9 0 1 0 3-6.7"/><polyline points="3 4 3 10 9 10"/></svg>
|
||||
</button>` : `
|
||||
${_hasItems(note) ? `
|
||||
<button class="note-card-action note-card-copy" data-note-id="${note.id}" title="Copy all items">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
|
||||
</button>` : ''}
|
||||
<button class="note-card-action note-card-archive" data-note-id="${note.id}" title="Save (archive)">
|
||||
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></svg>
|
||||
</button>
|
||||
<button class="note-card-action note-card-delete" data-note-id="${note.id}" title="Delete">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
|
||||
</button>
|
||||
<button class="note-card-action note-card-corner-menu" data-note-id="${note.id}" title="More" aria-label="More actions">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><circle cx="5" cy="12" r="1.7"/><circle cx="12" cy="12" r="1.7"/><circle cx="19" cy="12" r="1.7"/></svg>
|
||||
</button>`}
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
// Always render quick-add at top (collapsed unless user is typing)
|
||||
const existingForm = body.querySelector('.note-form');
|
||||
if (existingForm && state.editingId === '__new__') {
|
||||
// Keep the expanded form, replace cards after it
|
||||
const next = [...body.children].filter(c => c !== existingForm);
|
||||
next.forEach(c => c.remove());
|
||||
if (sorted.length === 0) {
|
||||
body.insertAdjacentHTML('beforeend', '<div class="notes-empty-msg">No notes <span style="vertical-align:-3px;margin-left:4px;">' + uiModule.emptyStateIcon('smiley') + '</span></div>');
|
||||
} else {
|
||||
existingForm.insertAdjacentHTML('afterend', html);
|
||||
}
|
||||
} else {
|
||||
body.innerHTML = '';
|
||||
_renderLabelsInto(body);
|
||||
_renderQuickAdd(body);
|
||||
if (sorted.length === 0) {
|
||||
body.insertAdjacentHTML('beforeend', '<div class="notes-empty-msg">No notes yet <span style="vertical-align:-3px;margin-left:4px;">' + uiModule.emptyStateIcon('smiley') + '</span></div>');
|
||||
} else {
|
||||
body.insertAdjacentHTML('beforeend', html);
|
||||
}
|
||||
}
|
||||
|
||||
_bindCardEvents(body);
|
||||
_animateReflow(prevPositions);
|
||||
_applyMasonry(body);
|
||||
}
|
||||
|
||||
return { _renderLoadingSkeleton, _renderNotes };
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
/** Desktop and large-touch-device card reorder gestures. */
|
||||
export function createCardReorder({
|
||||
lifecycle,
|
||||
_isNotesMobileMode,
|
||||
persistOrder,
|
||||
state
|
||||
}) {
|
||||
function _wireCardReorder(body) {
|
||||
lifecycle.release(body);
|
||||
// Drag-reorder notes on pointer/mouse devices. Mobile uses the custom
|
||||
// placeholder sorter below `_bindLongPressDrag`; native HTML5 dragging is
|
||||
// unreliable on touch browsers and can compete with the long-press flow.
|
||||
if (!_isNotesMobileMode()) {
|
||||
body.querySelectorAll('.note-card').forEach(card => {
|
||||
card.addEventListener('dragstart', (e) => {
|
||||
if (e.target.closest('.note-checkbox, .note-card-x, .note-card-select, .note-card-pin, .note-card-action, .note-card-color-dot, .note-card-title, .note-card-edit, .note-card-edit-corner, .note-card-done, .note-card-corner-menu, .note-agent-tag, .note-card-label-chip')) {
|
||||
e.preventDefault();
|
||||
return;
|
||||
}
|
||||
card.classList.add('dragging');
|
||||
body.classList.add('drag-active');
|
||||
e.dataTransfer.effectAllowed = 'move';
|
||||
try { e.dataTransfer.setData('text/plain', card.dataset.noteId); } catch {}
|
||||
});
|
||||
card.addEventListener('dragend', async () => {
|
||||
card.classList.remove('dragging');
|
||||
body.classList.remove('drag-active');
|
||||
body.querySelectorAll('.drop-before, .drop-after').forEach(el => el.classList.remove('drop-before', 'drop-after'));
|
||||
const ids = [...body.querySelectorAll('.note-card')].map(c => c.dataset.noteId);
|
||||
try { await persistOrder(ids); }
|
||||
catch {}
|
||||
});
|
||||
});
|
||||
}
|
||||
// Track which card we last swapped with so a single hover-over triggers
|
||||
// one swap, not a jitter as the pointer keeps moving inside the same card.
|
||||
let _lastSwapId = null;
|
||||
function _maybeSwap(dragging, clientX, clientY) {
|
||||
const target = document.elementFromPoint(clientX, clientY)?.closest('.note-card');
|
||||
if (!target || target === dragging || !body.contains(target)) return;
|
||||
const id = target.dataset.noteId;
|
||||
if (id === _lastSwapId) return;
|
||||
// FLIP across ALL siblings. In list view only `target` moves visually, but
|
||||
// in grid view (2-col) and when the pinned-section grid-column-start rule
|
||||
// shifts, several cards reflow at once. Capture every card's pre-swap rect,
|
||||
// do the DOM swap, then animate any that actually moved. The dragging card
|
||||
// is excluded : it's already finger-tracked via translate3d.
|
||||
const cards = [...body.querySelectorAll('.note-card')].filter(c => c !== dragging);
|
||||
const prevRects = new Map(cards.map(c => [c, c.getBoundingClientRect()]));
|
||||
const draggingNext = dragging.nextSibling === target ? dragging : dragging.nextSibling;
|
||||
body.insertBefore(dragging, target);
|
||||
body.insertBefore(target, draggingNext);
|
||||
for (const c of cards) {
|
||||
const prev = prevRects.get(c);
|
||||
const next = c.getBoundingClientRect();
|
||||
const dx = prev.left - next.left;
|
||||
const dy = prev.top - next.top;
|
||||
if (Math.abs(dx) < 0.5 && Math.abs(dy) < 0.5) continue;
|
||||
c.style.transition = 'none';
|
||||
c.style.transform = `translate(${dx}px, ${dy}px)`;
|
||||
requestAnimationFrame(() => {
|
||||
c.style.transition = 'transform 0.22s cubic-bezier(0.34, 1.2, 0.64, 1)';
|
||||
c.style.transform = '';
|
||||
c.addEventListener('transitionend', () => { c.style.transition = ''; }, { once: true });
|
||||
});
|
||||
}
|
||||
_lastSwapId = id;
|
||||
}
|
||||
lifecycle.listen(body, body, 'dragover', (e) => {
|
||||
e.preventDefault();
|
||||
const dragging = body.querySelector('.note-card.dragging');
|
||||
if (!dragging) return;
|
||||
_maybeSwap(dragging, e.clientX, e.clientY);
|
||||
});
|
||||
lifecycle.listen(body, body, 'dragend', () => { _lastSwapId = null; });
|
||||
|
||||
// Legacy touch drag for larger touch devices only. Phone-sized Notes uses
|
||||
// the placeholder sorter wired by `_bindLongPressDrag`; running both flows
|
||||
// makes one press start two independent drag sessions.
|
||||
if (!_isNotesMobileMode() && 'ontouchstart' in window) {
|
||||
let dragCard = null;
|
||||
let isDragging = false;
|
||||
let longPressTimer = null;
|
||||
let startX = 0, startY = 0;
|
||||
const LONG_PRESS_MS = 350;
|
||||
const MOVE_THRESHOLD_PX = 8;
|
||||
const _selectorSkip = '.note-checkbox, .note-card-x, .note-card-select, .note-card-pin, .note-card-action, .note-card-color-dot, .note-card-title, .note-card-edit, .note-card-edit-corner, .note-card-done, .note-card-corner-menu, .note-agent-tag, .note-card-label-chip, input, textarea, button, a';
|
||||
|
||||
// Anchor for the finger-follow transform. Recomputed after every swap so
|
||||
// the card stays under the finger across reorderings.
|
||||
let anchorX = 0, anchorY = 0;
|
||||
const _follow = (clientX, clientY) => {
|
||||
if (!dragCard) return;
|
||||
const dx = clientX - anchorX;
|
||||
const dy = clientY - anchorY;
|
||||
// Compose with the CSS .dragging transform (scale + rotate).
|
||||
dragCard.style.transform = `translate3d(${dx}px, ${dy}px, 0) scale(1.03) rotate(-0.6deg)`;
|
||||
};
|
||||
const _reanchor = (clientX, clientY) => {
|
||||
if (!dragCard) return;
|
||||
// Clear any prior translate so the card resettles in its natural slot,
|
||||
// then anchor at the finger's current position. Subsequent _follow calls
|
||||
// translate by (finger - anchor), keeping the finger at the same relative
|
||||
// spot on the card it had when we re-anchored.
|
||||
dragCard.style.transform = '';
|
||||
anchorX = clientX;
|
||||
anchorY = clientY;
|
||||
};
|
||||
|
||||
const _endDrag = (committed) => {
|
||||
clearTimeout(longPressTimer);
|
||||
longPressTimer = null;
|
||||
if (dragCard) {
|
||||
dragCard.classList.remove('dragging');
|
||||
dragCard.style.transform = '';
|
||||
}
|
||||
body.classList.remove('drag-active');
|
||||
_lastSwapId = null;
|
||||
if (isDragging) {
|
||||
document.documentElement.style.touchAction = '';
|
||||
if (committed) {
|
||||
const ids = [...body.querySelectorAll('.note-card')].map(c => c.dataset.noteId);
|
||||
persistOrder(ids).catch(() => {});
|
||||
}
|
||||
}
|
||||
dragCard = null;
|
||||
isDragging = false;
|
||||
};
|
||||
lifecycle.onDispose(body, () => _endDrag(false));
|
||||
|
||||
lifecycle.listen(body, body, 'touchstart', (e) => {
|
||||
if (state.selectMode) return;
|
||||
const card = e.target.closest('.note-card');
|
||||
if (!card) return;
|
||||
if (e.target.closest(_selectorSkip)) return;
|
||||
const t = e.touches[0];
|
||||
startX = t.clientX; startY = t.clientY;
|
||||
dragCard = card;
|
||||
longPressTimer = setTimeout(() => {
|
||||
if (!dragCard) return;
|
||||
isDragging = true;
|
||||
dragCard.classList.add('dragging');
|
||||
body.classList.add('drag-active');
|
||||
document.documentElement.style.touchAction = 'none';
|
||||
_reanchor(startX, startY);
|
||||
try { if (navigator.vibrate) navigator.vibrate(15); } catch {}
|
||||
}, LONG_PRESS_MS);
|
||||
}, { passive: true });
|
||||
|
||||
lifecycle.listen(body, body, 'touchmove', (e) => {
|
||||
if (!dragCard) return;
|
||||
const t = e.touches[0];
|
||||
if (!isDragging) {
|
||||
// Movement before long-press fires = user is scrolling; cancel pickup.
|
||||
if (Math.abs(t.clientX - startX) > MOVE_THRESHOLD_PX || Math.abs(t.clientY - startY) > MOVE_THRESHOLD_PX) {
|
||||
clearTimeout(longPressTimer);
|
||||
longPressTimer = null;
|
||||
dragCard = null;
|
||||
}
|
||||
return;
|
||||
}
|
||||
e.preventDefault();
|
||||
// Live-follow the finger first, then check for a swap. After a swap the
|
||||
// card's natural slot moves, so we re-anchor and re-apply the offset.
|
||||
_follow(t.clientX, t.clientY);
|
||||
const before = dragCard.parentNode && [...dragCard.parentNode.children].indexOf(dragCard);
|
||||
_maybeSwap(dragCard, t.clientX, t.clientY);
|
||||
const after = dragCard.parentNode && [...dragCard.parentNode.children].indexOf(dragCard);
|
||||
if (before !== after) {
|
||||
_reanchor(t.clientX, t.clientY);
|
||||
_follow(t.clientX, t.clientY);
|
||||
}
|
||||
}, { passive: false });
|
||||
|
||||
lifecycle.listen(body, body, 'touchend', () => _endDrag(true));
|
||||
lifecycle.listen(body, body, 'touchcancel', () => _endDrag(false));
|
||||
}
|
||||
}
|
||||
|
||||
return { _wireCardReorder };
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
/** Checklist rows, goal forms, keyboard input and item collection. */
|
||||
export function createChecklist({
|
||||
_esc,
|
||||
_uid,
|
||||
spawnConfetti
|
||||
}) {
|
||||
function _buildGoalHtml(note, items) {
|
||||
const desc = (note?.content || '').toString();
|
||||
return `
|
||||
<div class="note-form-goal">
|
||||
<textarea class="note-form-goal-desc" placeholder="Description (optional)" rows="3">${_esc(desc)}</textarea>
|
||||
${_buildChecklistHtml(items)}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
function _wireGoalForm(form, container) {
|
||||
if (!container) return;
|
||||
// _wireHashtag is a closure inside _buildForm : out of scope here. Inline
|
||||
// the same behavior (type "#foo " in the description → tag added to the
|
||||
// form's label input) so editing a goal note doesn't ReferenceError.
|
||||
const desc = container.querySelector('.note-form-goal-desc');
|
||||
const labelInput = form?.querySelector('.note-form-label');
|
||||
if (desc && labelInput) {
|
||||
const tagRe = /(^|\s)#([A-Za-z0-9][\w-]*)\s$/;
|
||||
desc.addEventListener('input', () => {
|
||||
const m = tagRe.exec(desc.value);
|
||||
if (!m) return;
|
||||
const tag = m[2];
|
||||
// Same dedup-after-stripping fix as the plain note hashtag handler.
|
||||
const existing = labelInput.value.trim().split(/\s+/).filter(Boolean);
|
||||
const stripped = existing.map(t => t.replace(/^#+/, ''));
|
||||
if (!stripped.includes(tag)) {
|
||||
existing.push('#' + tag);
|
||||
labelInput.value = existing.join(' ');
|
||||
labelInput.classList.add('flash-once');
|
||||
setTimeout(() => labelInput.classList.remove('flash-once'), 600);
|
||||
}
|
||||
const cut = desc.value.length - m[0].length + m[1].length;
|
||||
desc.value = desc.value.slice(0, cut);
|
||||
});
|
||||
}
|
||||
// Always wire the checklist. The previous gate on a `note-form-goal-fresh`
|
||||
// class was dead code : nothing ever set that class, so the editor never
|
||||
// hooked up add/drag/Tab.
|
||||
_wireChecklist(container);
|
||||
}
|
||||
|
||||
function _buildChecklistHtml(items) {
|
||||
let html = '<div class="note-checklist-inputs">';
|
||||
for (const item of items) {
|
||||
const indent = Math.min(item.indent || 0, 3);
|
||||
html += `<div class="note-cl-row${item.done ? ' done' : ''}" draggable="true" data-item-id="${item.id || _uid()}" data-indent="${indent}" style="padding-left:${indent * 16}px">
|
||||
<span class="note-cl-grip" title="Drag to reorder">⋮⋮</span>
|
||||
<span class="note-cl-dot"></span>
|
||||
<input type="text" class="note-cl-text" value="${_esc(item.text)}" placeholder="Item..." />
|
||||
<button type="button" class="note-cl-rm">×</button>
|
||||
</div>`;
|
||||
}
|
||||
// `type="button"` matters on mobile : without it some browsers treat
|
||||
// bare <button> as form-submit and the click handler never fires inside
|
||||
// certain containers. Also bumped tap target so fingers don't miss.
|
||||
html += `<button type="button" class="note-cl-add">+ Add</button></div>`;
|
||||
return html;
|
||||
}
|
||||
|
||||
function _wireRow(row, container) {
|
||||
row.querySelector('.note-cl-rm')?.addEventListener('click', () => row.remove());
|
||||
row.querySelector('.note-cl-dot')?.addEventListener('click', () => {
|
||||
const wasDone = row.classList.contains('done');
|
||||
row.classList.toggle('done');
|
||||
// The custom dot has no native input/change event. Notify the form so
|
||||
// mobile edit mode switches its action from Archive back to Update.
|
||||
container.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
const becameDone = !wasDone; // we just flipped it
|
||||
const dot = row.querySelector('.note-cl-dot');
|
||||
const dRect = (dot || row).getBoundingClientRect();
|
||||
// Small confetti burst on each fresh check so the user gets a
|
||||
// "well done" beat per item, not just the grand-finale on all-done.
|
||||
if (becameDone) {
|
||||
spawnConfetti(dRect.left + dRect.width / 2, dRect.top + dRect.height / 2, 16);
|
||||
}
|
||||
// Bigger burst when the whole list is now done.
|
||||
const rows = [...container.querySelectorAll('.note-cl-row')];
|
||||
const hasText = rows.some(r => (r.querySelector('.note-cl-text')?.value || '').trim().length > 0);
|
||||
if (hasText && rows.every(r => r.classList.contains('done') || !(r.querySelector('.note-cl-text')?.value || '').trim())) {
|
||||
spawnConfetti(dRect.left + dRect.width / 2, dRect.top + dRect.height / 2, 60);
|
||||
}
|
||||
});
|
||||
const txt = row.querySelector('.note-cl-text');
|
||||
txt?.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Enter') { e.preventDefault(); container.querySelector('.note-cl-add')?.click(); }
|
||||
else if (e.key === 'Tab') {
|
||||
e.preventDefault();
|
||||
const cur = parseInt(row.dataset.indent || '0');
|
||||
const next = e.shiftKey ? Math.max(0, cur - 1) : Math.min(3, cur + 1);
|
||||
row.dataset.indent = String(next);
|
||||
row.style.paddingLeft = (next * 16) + 'px';
|
||||
} else if (e.key === 'Backspace' && txt.value === '') {
|
||||
e.preventDefault();
|
||||
const prev = row.previousElementSibling;
|
||||
row.remove();
|
||||
if (prev && prev.classList.contains('note-cl-row')) prev.querySelector('.note-cl-text')?.focus();
|
||||
}
|
||||
});
|
||||
// Drag handlers
|
||||
row.addEventListener('dragstart', (e) => {
|
||||
row.classList.add('dragging');
|
||||
e.dataTransfer.effectAllowed = 'move';
|
||||
try { e.dataTransfer.setData('text/plain', row.dataset.itemId); } catch {}
|
||||
});
|
||||
row.addEventListener('dragend', () => {
|
||||
row.classList.remove('dragging');
|
||||
container.querySelectorAll('.drop-before, .drop-after').forEach(el => el.classList.remove('drop-before', 'drop-after'));
|
||||
});
|
||||
}
|
||||
|
||||
function _wireChecklist(container) {
|
||||
if (!container) return;
|
||||
// Delegate the + Add click off the container so re-renders + mobile
|
||||
// touch quirks don't leave the button dead. The previous direct
|
||||
// `addEventListener` on the button silently broke on mobile when
|
||||
// _wireChecklist ran more than once (or before the button was in DOM).
|
||||
if (!container._addDelegated) {
|
||||
container._addDelegated = true;
|
||||
container.addEventListener('click', (ev) => {
|
||||
const addBtn = ev.target.closest('.note-cl-add');
|
||||
if (!addBtn || !container.contains(addBtn)) return;
|
||||
ev.preventDefault();
|
||||
ev.stopPropagation();
|
||||
const inputs = container.querySelector('.note-checklist-inputs');
|
||||
if (!inputs) return;
|
||||
const row = document.createElement('div');
|
||||
row.className = 'note-cl-row';
|
||||
row.draggable = true;
|
||||
row.dataset.itemId = _uid();
|
||||
row.dataset.indent = '0';
|
||||
row.innerHTML = `<span class="note-cl-grip" title="Drag">⋮⋮</span><span class="note-cl-dot"></span><input type="text" class="note-cl-text" placeholder="Item..." /><button type="button" class="note-cl-rm">×</button>`;
|
||||
inputs.insertBefore(row, addBtn);
|
||||
row.querySelector('.note-cl-text').focus();
|
||||
_wireRow(row, container);
|
||||
});
|
||||
}
|
||||
container.querySelectorAll('.note-cl-row').forEach(row => _wireRow(row, container));
|
||||
|
||||
// Drag-over handler on the inputs container
|
||||
const inputs = container.querySelector('.note-checklist-inputs');
|
||||
if (inputs) {
|
||||
inputs.addEventListener('dragover', (e) => {
|
||||
e.preventDefault();
|
||||
const dragging = inputs.querySelector('.note-cl-row.dragging');
|
||||
if (!dragging) return;
|
||||
inputs.querySelectorAll('.drop-before, .drop-after').forEach(el => el.classList.remove('drop-before', 'drop-after'));
|
||||
const rows = [...inputs.querySelectorAll('.note-cl-row:not(.dragging)')];
|
||||
const after = rows.find(r => {
|
||||
const box = r.getBoundingClientRect();
|
||||
return e.clientY < box.top + box.height / 2;
|
||||
});
|
||||
if (after) {
|
||||
after.classList.add('drop-before');
|
||||
inputs.insertBefore(dragging, after);
|
||||
} else if (rows.length) {
|
||||
rows[rows.length - 1].classList.add('drop-after');
|
||||
inputs.insertBefore(dragging, container.querySelector('.note-cl-add'));
|
||||
}
|
||||
});
|
||||
inputs.addEventListener('dragleave', (e) => {
|
||||
if (!inputs.contains(e.relatedTarget)) {
|
||||
inputs.querySelectorAll('.drop-before, .drop-after').forEach(el => el.classList.remove('drop-before', 'drop-after'));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function _collectItems(form) {
|
||||
const items = [];
|
||||
form.querySelectorAll('.note-cl-row').forEach(row => {
|
||||
const text = row.querySelector('.note-cl-text')?.value?.trim();
|
||||
if (text) items.push({
|
||||
id: row.dataset.itemId || _uid(),
|
||||
text,
|
||||
done: row.classList.contains('done'),
|
||||
indent: parseInt(row.dataset.indent || '0'),
|
||||
});
|
||||
});
|
||||
return items;
|
||||
}
|
||||
|
||||
return { _buildGoalHtml, _wireGoalForm, _buildChecklistHtml, _wireRow, _wireChecklist, _collectItems };
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
/** Mobile checklist grip dragging and document listener ownership. */
|
||||
export function createChecklistReorder({
|
||||
lifecycle
|
||||
}) {
|
||||
let _clDrag = null;
|
||||
|
||||
let _clDocBound = false;
|
||||
let _clOwner = null;
|
||||
|
||||
function _wireChecklistTouchReorder(form) {
|
||||
const container = form.querySelector('.note-checklist-inputs');
|
||||
if (!container) return;
|
||||
container.querySelectorAll('.note-cl-grip').forEach(grip => {
|
||||
if (grip.dataset.touchBound === '1') return;
|
||||
grip.dataset.touchBound = '1';
|
||||
grip.addEventListener('touchstart', (e) => {
|
||||
if (e.touches.length !== 1) return;
|
||||
e.preventDefault();
|
||||
const row = grip.closest('.note-cl-row');
|
||||
if (!row) return;
|
||||
_beginChecklistGrab(row, container, e.touches[0]);
|
||||
}, { passive: false });
|
||||
});
|
||||
if (!_clDocBound || _clOwner !== form) {
|
||||
if (_clOwner) lifecycle.release(_clOwner);
|
||||
_clOwner = form;
|
||||
lifecycle.listen(form, document, 'touchmove', _onClTouchMove, { passive: false });
|
||||
lifecycle.listen(form, document, 'touchend', _onClTouchEnd, { passive: true });
|
||||
lifecycle.listen(form, document, 'touchcancel', _onClTouchEnd, { passive: true });
|
||||
_clDocBound = true;
|
||||
}
|
||||
}
|
||||
|
||||
function _beginChecklistGrab(row, container, touch) {
|
||||
if (_clDrag) return;
|
||||
const rect = row.getBoundingClientRect();
|
||||
const placeholder = document.createElement('div');
|
||||
placeholder.className = 'note-cl-row-placeholder';
|
||||
placeholder.style.height = rect.height + 'px';
|
||||
container.insertBefore(placeholder, row);
|
||||
|
||||
row.classList.add('note-cl-row-dragging');
|
||||
row.style.position = 'fixed';
|
||||
row.style.left = rect.left + 'px';
|
||||
row.style.top = rect.top + 'px';
|
||||
row.style.width = rect.width + 'px';
|
||||
row.style.zIndex = '10002';
|
||||
row.style.pointerEvents = 'none';
|
||||
|
||||
_clDrag = {
|
||||
row, placeholder, container,
|
||||
grabOffsetX: touch.clientX - rect.left,
|
||||
grabOffsetY: touch.clientY - rect.top,
|
||||
};
|
||||
try { navigator.vibrate?.(8); } catch {}
|
||||
}
|
||||
|
||||
function _onClTouchMove(e) {
|
||||
if (!_clDrag) return;
|
||||
if (e.touches.length !== 1) return;
|
||||
e.preventDefault();
|
||||
const t = e.touches[0];
|
||||
const { row, placeholder, container } = _clDrag;
|
||||
row.style.left = (t.clientX - _clDrag.grabOffsetX) + 'px';
|
||||
row.style.top = (t.clientY - _clDrag.grabOffsetY) + 'px';
|
||||
|
||||
const under = document.elementFromPoint(t.clientX, t.clientY);
|
||||
const target = under && under.closest
|
||||
? under.closest('.note-cl-row:not(.note-cl-row-dragging)')
|
||||
: null;
|
||||
if (!target || target === row) return;
|
||||
if (target.parentNode !== container) return;
|
||||
|
||||
const tRect = target.getBoundingClientRect();
|
||||
const targetMidY = tRect.top + tRect.height / 2;
|
||||
if (t.clientY < targetMidY) {
|
||||
if (placeholder.nextElementSibling !== target) {
|
||||
container.insertBefore(placeholder, target);
|
||||
}
|
||||
} else {
|
||||
if (target.nextElementSibling !== placeholder) {
|
||||
container.insertBefore(placeholder, target.nextElementSibling);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function _onClTouchEnd() {
|
||||
if (!_clDrag) return;
|
||||
const { row, placeholder } = _clDrag;
|
||||
_clDrag = null;
|
||||
const phRect = placeholder.getBoundingClientRect();
|
||||
row.style.transition = 'left 0.18s ease, top 0.18s ease';
|
||||
row.style.left = phRect.left + 'px';
|
||||
row.style.top = phRect.top + 'px';
|
||||
setTimeout(() => {
|
||||
placeholder.parentNode.insertBefore(row, placeholder);
|
||||
placeholder.remove();
|
||||
row.classList.remove('note-cl-row-dragging');
|
||||
row.style.cssText = '';
|
||||
// Order is persisted as part of the form's normal save (rows are
|
||||
// re-serialized in DOM order via _collectItems).
|
||||
}, 200);
|
||||
}
|
||||
|
||||
function dispose() {
|
||||
if (_clDrag) _onClTouchEnd();
|
||||
_clDocBound = false;
|
||||
_clOwner = null;
|
||||
}
|
||||
return { dispose, _wireChecklistTouchReorder, _beginChecklistGrab, _onClTouchMove, _onClTouchEnd };
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
/** Note clipboard feedback and the Copy/Agent corner menu. */
|
||||
import { _serializeNoteForCopy } from '../domain/noteRules.js';
|
||||
export function createClipboard({
|
||||
_agentSolveNote,
|
||||
bindMenuDismiss,
|
||||
dismissOrRemove,
|
||||
state,
|
||||
topPortalZ,
|
||||
uiModule
|
||||
}) {
|
||||
function _openNoteCornerMenu(btn) {
|
||||
document.querySelectorAll('.note-corner-menu-dropdown').forEach(dismissOrRemove);
|
||||
const id = btn.dataset.noteId;
|
||||
const note = state.notes.find(n => n.id === id);
|
||||
if (!note) return;
|
||||
const menu = document.createElement('div');
|
||||
menu.className = 'note-corner-menu-dropdown';
|
||||
menu.innerHTML = `
|
||||
<button type="button" class="ncm-item" data-act="copy">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
|
||||
<span>Copy</span>
|
||||
</button>
|
||||
<button type="button" class="ncm-item" data-act="agent">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 8V4H8"/><rect x="4" y="8" width="16" height="12" rx="2"/><path d="M2 14h2M20 14h2M15 13v2M9 13v2"/></svg>
|
||||
<span>${note.agent_session_id ? 'Re-run agent' : 'Agent: solve this'}</span>
|
||||
</button>`;
|
||||
document.body.appendChild(menu);
|
||||
const r = btn.getBoundingClientRect();
|
||||
// Right-align to the ⋯ button, clamped to the viewport.
|
||||
const mw = 168;
|
||||
let left = Math.min(r.right - mw, window.innerWidth - mw - 8);
|
||||
left = Math.max(8, left);
|
||||
// Drop down by default; flip up if there isn't room below (the button
|
||||
// sits at the card's bottom edge now).
|
||||
const mh = menu.offsetHeight || 96;
|
||||
const below = window.innerHeight - r.bottom;
|
||||
const top = (below < mh + 8 && r.top > mh + 8) ? (r.top - mh - 4) : (r.bottom + 4);
|
||||
menu.style.cssText += `position:fixed;z-index:${topPortalZ()};top:${Math.round(top)}px;left:${Math.round(left)}px;`;
|
||||
const close = bindMenuDismiss(menu, () => { menu.remove(); });
|
||||
menu.querySelector('[data-act="copy"]').addEventListener('click', () => { close(); _copyNote(id, btn); });
|
||||
menu.querySelector('[data-act="agent"]').addEventListener('click', () => { close(); _agentSolveNote(id); });
|
||||
}
|
||||
|
||||
async function _copyNote(noteId, btnEl) {
|
||||
const note = state.notes.find(n => n.id === noteId);
|
||||
if (!note) return false;
|
||||
const text = _serializeNoteForCopy(note);
|
||||
if (!text) return false;
|
||||
let ok = false;
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
ok = true;
|
||||
} catch {
|
||||
const ta = document.createElement('textarea');
|
||||
ta.value = text;
|
||||
ta.style.position = 'fixed'; ta.style.left = '-9999px';
|
||||
document.body.appendChild(ta);
|
||||
ta.select();
|
||||
try { ok = document.execCommand('copy'); } catch { ok = false; }
|
||||
ta.remove();
|
||||
}
|
||||
if (ok) {
|
||||
if (btnEl && !btnEl._copyFlashing) {
|
||||
const original = btnEl.innerHTML;
|
||||
btnEl._copyFlashing = true;
|
||||
btnEl.innerHTML = '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>';
|
||||
btnEl.classList.add('copied');
|
||||
setTimeout(() => {
|
||||
btnEl.innerHTML = original;
|
||||
btnEl.classList.remove('copied');
|
||||
btnEl._copyFlashing = false;
|
||||
}, 1200);
|
||||
}
|
||||
uiModule.showToast?.('Copied');
|
||||
} else {
|
||||
uiModule.showError?.('Copy failed');
|
||||
}
|
||||
return ok;
|
||||
}
|
||||
|
||||
return { _openNoteCornerMenu, _copyNote };
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
/** Note colors, custom background selection and form color controls. */
|
||||
export function createColors({
|
||||
api
|
||||
}) {
|
||||
const COLORS = [
|
||||
{ name: 'none', value: '' },
|
||||
{ name: 'red', value: 'red' },
|
||||
{ name: 'orange', value: 'orange' },
|
||||
{ name: 'yellow', value: 'yellow' },
|
||||
{ name: 'green', value: 'green' },
|
||||
{ name: 'blue', value: 'blue' },
|
||||
{ name: 'purple', value: 'purple' },
|
||||
{ name: 'custom', value: 'custom' }, // sentinel : clicking opens native color picker
|
||||
];
|
||||
|
||||
const COLOR_HEX = {
|
||||
'': 'var(--border)',
|
||||
// Pale/pastel palette : matches the calendar event color picker.
|
||||
red: '#f0b5ba',
|
||||
orange: '#e8ccb2',
|
||||
yellow: '#f2dfbd',
|
||||
green: '#cce0bc',
|
||||
blue: '#b0d7f7',
|
||||
purple: '#e2bcee',
|
||||
};
|
||||
|
||||
const _CUSTOM_GRADIENT = 'conic-gradient(from 0deg, #e06c75, #d19a66, #e5c07b, #98c379, #61afef, #c678dd, #e06c75)';
|
||||
|
||||
function _isBgImage(c) { return typeof c === 'string' && c.startsWith('bg:'); }
|
||||
|
||||
function _bgImageUrl(c) { return _isBgImage(c) ? c.slice(3) : ''; }
|
||||
|
||||
function _dotBg(value, noteColor) {
|
||||
if (value === 'custom') {
|
||||
const url = _bgImageUrl(noteColor);
|
||||
return url ? `center/cover no-repeat url('${url}')` : _CUSTOM_GRADIENT;
|
||||
}
|
||||
return COLOR_HEX[value];
|
||||
}
|
||||
|
||||
function _dotIsActive(value, noteColor) {
|
||||
if (value === 'custom') return _isBgImage(noteColor);
|
||||
return value === (noteColor || '');
|
||||
}
|
||||
|
||||
function _customColorStyle(c) {
|
||||
if (!_isBgImage(c)) return '';
|
||||
const url = _bgImageUrl(c);
|
||||
return `background-image: linear-gradient(color-mix(in srgb, var(--panel) 60%, transparent), color-mix(in srgb, var(--panel) 60%, transparent)), url('${url}'); background-size: cover; background-position: center; border-color: color-mix(in srgb, var(--fg) 25%, var(--border));`;
|
||||
}
|
||||
|
||||
function _pickCustomBgImage() {
|
||||
return new Promise(resolve => {
|
||||
const input = document.createElement('input');
|
||||
input.type = 'file';
|
||||
input.accept = 'image/*';
|
||||
input.style.cssText = 'position:fixed; left:-9999px; top:-9999px;';
|
||||
document.body.appendChild(input);
|
||||
let done = false;
|
||||
const finish = (v) => { if (done) return; done = true; input.remove(); resolve(v); };
|
||||
input.addEventListener('change', async () => {
|
||||
const file = input.files?.[0];
|
||||
if (!file) return finish(null);
|
||||
const fd = new FormData();
|
||||
fd.append('files', file);
|
||||
try {
|
||||
const res = await api.upload(fd);
|
||||
const data = await res.json();
|
||||
const fileId = data.files?.[0]?.id;
|
||||
if (!fileId) throw new Error('Upload failed');
|
||||
finish(api.uploadUrl(fileId));
|
||||
} catch { finish(null); }
|
||||
});
|
||||
// Best-effort cleanup if user dismisses the dialog.
|
||||
setTimeout(() => { if (!done && !input.files?.length) finish(null); }, 30000);
|
||||
input.click();
|
||||
});
|
||||
}
|
||||
|
||||
function _wireFormColors(form, setColor) {
|
||||
// Color dots : apply to entire form immediately
|
||||
const _applyFormColor = (newColor) => {
|
||||
const currentColor = newColor || '';
|
||||
setColor(currentColor);
|
||||
form.dataset.noteColor = currentColor;
|
||||
const isBg = _isBgImage(currentColor);
|
||||
COLORS.forEach(c => { if (c.value && c.value !== 'custom') form.classList.remove('note-color-' + c.value); });
|
||||
if (currentColor && !isBg) form.classList.add('note-color-' + currentColor);
|
||||
if (isBg) form.setAttribute('style', _customColorStyle(currentColor));
|
||||
else form.removeAttribute('style');
|
||||
form.querySelectorAll('.note-color-dot').forEach(d => {
|
||||
d.classList.toggle('active', _dotIsActive(d.dataset.color, currentColor));
|
||||
d.style.background = _dotBg(d.dataset.color, currentColor);
|
||||
});
|
||||
form.dispatchEvent(new Event('change', { bubbles: true }));
|
||||
};
|
||||
form.querySelectorAll('.note-color-dot').forEach(dot => {
|
||||
dot.addEventListener('click', () => {
|
||||
if (dot.dataset.color === 'custom') {
|
||||
_pickCustomBgImage().then(url => { if (url) _applyFormColor('bg:' + url); });
|
||||
return;
|
||||
}
|
||||
_applyFormColor(dot.dataset.color);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
}
|
||||
|
||||
return { COLORS, COLOR_HEX, _isBgImage, _bgImageUrl, _dotBg, _dotIsActive, _customColorStyle, _pickCustomBgImage, _wireFormColors };
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
/** Collect editor drafts, restore them and wire the autosave workflow. */
|
||||
export function createDraftEditor({
|
||||
bindDraft,
|
||||
_collectItems,
|
||||
_loadDraft
|
||||
}) {
|
||||
function _collectFormDraft(form) {
|
||||
if (!form) return null;
|
||||
const type = form.querySelector('.note-form-type-pill.active')?.dataset.type || form.dataset.noteType || 'note';
|
||||
const d = {
|
||||
_ts: Date.now(),
|
||||
note_type: type,
|
||||
color: form.dataset.noteColor || '',
|
||||
title: form.querySelector('.note-form-title')?.value || '',
|
||||
label: form.querySelector('.note-form-label')?.value || '',
|
||||
due_date: form.querySelector('.note-form-due')?.value || null,
|
||||
repeat: form.querySelector('.note-form-repeat')?.value || 'none',
|
||||
};
|
||||
if (type === 'note') d.content = form.querySelector('.note-form-content')?.value || '';
|
||||
else if (type === 'goal') { d.content = form.querySelector('.note-form-goal-desc')?.value || ''; d.items = _collectItems(form); }
|
||||
else d.items = _collectItems(form);
|
||||
return d;
|
||||
}
|
||||
|
||||
function _isDraftEmpty(d) {
|
||||
if (!d) return true;
|
||||
if ((d.title || '').trim()) return false;
|
||||
if ((d.content || '').trim()) return false;
|
||||
if (Array.isArray(d.items) && d.items.some(it => (it.text || '').trim())) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
function _wireDraftAutosave(form, id) {
|
||||
const view = {
|
||||
get failed() { return form._autosaveFailed; },
|
||||
set failed(value) { form._autosaveFailed = value; },
|
||||
};
|
||||
const draft = bindDraft({ collect: () => _collectFormDraft(form), id, view });
|
||||
form._flushDraft = draft.flush;
|
||||
form._stopDraftAutosave = draft.stop;
|
||||
form.addEventListener('input', draft.schedule);
|
||||
form.addEventListener('change', draft.schedule);
|
||||
form.addEventListener('click', event => {
|
||||
if (event.target.closest('.note-cl-dot, .note-cl-rm')) draft.schedule();
|
||||
});
|
||||
}
|
||||
|
||||
function _commitOpenInPlaceEditor() {
|
||||
const form = document.querySelector('#notes-pane .note-form');
|
||||
if (!form) return;
|
||||
const d = _collectFormDraft(form);
|
||||
if (_isDraftEmpty(d)) { form.querySelector('.note-form-cancel')?.click(); return; }
|
||||
form.querySelector('.note-form-save')?.click();
|
||||
}
|
||||
|
||||
function _applyDraftToNote(note, id) {
|
||||
const d = _loadDraft(id);
|
||||
if (!d) return { note, restored: false };
|
||||
const merged = { ...(note || {}) };
|
||||
['note_type', 'color', 'title', 'label', 'due_date', 'repeat', 'content', 'items'].forEach(k => {
|
||||
if (d[k] !== undefined) merged[k] = d[k];
|
||||
});
|
||||
return { note: merged, restored: true };
|
||||
}
|
||||
|
||||
return { _collectFormDraft, _isDraftEmpty, _wireDraftAutosave, _commitOpenInPlaceEditor, _applyDraftToNote };
|
||||
}
|
||||
@@ -0,0 +1,442 @@
|
||||
/** Canvas drawing tools, local drawing undo and PNG uploads. */
|
||||
export function createDrawing({
|
||||
lifecycle,
|
||||
_safeImgSrc,
|
||||
api,
|
||||
attachColorPicker
|
||||
}) {
|
||||
function _buildDrawHtml() {
|
||||
return `
|
||||
<div class="note-form-draw-wrap">
|
||||
<canvas class="note-form-canvas" width="600" height="320"></canvas>
|
||||
<div class="note-form-draw-toolbar">
|
||||
<input type="color" class="note-form-draw-color" title="Stroke color" value="#222222" />
|
||||
<label class="note-form-draw-tool note-form-draw-size-wrap" title="Stroke size">
|
||||
<input type="range" class="note-form-draw-size" min="1" max="24" value="3" />
|
||||
</label>
|
||||
<div class="note-form-draw-be" role="group">
|
||||
<button type="button" class="note-form-draw-be-btn note-form-draw-brush active" data-mode="pen" title="Brush">
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9.06 11.9l8.07-8.06a2.85 2.85 0 1 1 4.03 4.03l-8.06 8.08"/><path d="M7.07 14.94c-1.66 0-3 1.35-3 3.02 0 1.33-2.5 1.52-2 2.02 1.08 1.1 2.49 2.02 4 2.02 2.2 0 4-1.8 4-4.04 0-1.67-1.34-3.02-3-3.02z"/></svg>
|
||||
</button>
|
||||
<button type="button" class="note-form-draw-be-btn note-form-draw-eraser" data-mode="eraser" title="Eraser">
|
||||
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21"/><path d="M22 21H7"/><path d="m5 11 9 9"/></svg>
|
||||
</button>
|
||||
</div>
|
||||
<button type="button" class="note-form-draw-undo" title="Undo" aria-label="Undo">
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 14 4 9 9 4"></polyline><path d="M4 9h11a5 5 0 0 1 5 5v0a5 5 0 0 1-5 5H9"></path></svg>
|
||||
</button>
|
||||
<button type="button" class="note-form-draw-text" title="Add text — click to cycle size" aria-label="Add text">T<span class="note-form-draw-text-badge"></span></button>
|
||||
<button type="button" class="note-form-draw-line" title="Line — click to cycle size">
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="4" y1="20" x2="20" y2="4"/></svg>
|
||||
<span class="note-form-draw-shape-badge"></span>
|
||||
</button>
|
||||
<button type="button" class="note-form-draw-circle" title="Circle — click to cycle size">
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="9"/></svg>
|
||||
<span class="note-form-draw-shape-badge"></span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
function _wireCanvas(container, initialImageUrl) {
|
||||
const canvas = container.querySelector('.note-form-canvas');
|
||||
if (!canvas) return;
|
||||
const resolveThemeColor = (expression, fallback) => {
|
||||
const probe = document.createElement('span');
|
||||
probe.style.color = expression;
|
||||
probe.style.position = 'fixed';
|
||||
probe.style.visibility = 'hidden';
|
||||
document.body.appendChild(probe);
|
||||
const resolved = getComputedStyle(probe).color || fallback;
|
||||
probe.remove();
|
||||
return resolved;
|
||||
};
|
||||
const colorToHex = (color, fallback) => {
|
||||
try {
|
||||
const probe = document.createElement('canvas');
|
||||
probe.width = probe.height = 1;
|
||||
const probeCtx = probe.getContext('2d');
|
||||
probeCtx.fillStyle = color;
|
||||
probeCtx.fillRect(0, 0, 1, 1);
|
||||
const [r, g, b] = probeCtx.getImageData(0, 0, 1, 1).data;
|
||||
return `#${[r, g, b].map(v => v.toString(16).padStart(2, '0')).join('')}`;
|
||||
} catch { return fallback; }
|
||||
};
|
||||
const surfaceColor = resolveThemeColor('var(--panel, var(--bg))', '#282c34');
|
||||
const surfaceColorHex = colorToHex(surfaceColor, '#282c34');
|
||||
const highlightColor = colorToHex(
|
||||
resolveThemeColor('var(--accent, var(--red))', '#e06c75'),
|
||||
'#e06c75',
|
||||
);
|
||||
const colorInput = container.querySelector('.note-form-draw-color');
|
||||
if (colorInput) colorInput.value = highlightColor;
|
||||
// Bump the backing-store resolution for retina displays so strokes stay
|
||||
// crisp. Set only style.width : leaving style.height to auto so the canvas
|
||||
// scales uniformly via its intrinsic aspect ratio. If both CSS dimensions
|
||||
// are pinned, max-width:100% shrinks the width only, leaving rasterized
|
||||
// glyphs visibly stretched relative to their on-screen input.
|
||||
const dpr = Math.min(window.devicePixelRatio || 1, 2);
|
||||
const cssW = canvas.width;
|
||||
const cssH = canvas.height;
|
||||
// Fill the container up to the logical width (don't pin a hard 600px,
|
||||
// which on a narrow phone forces the card wider than the viewport and
|
||||
// pushes the drawing outside the note). _pos() scales pointer coords by
|
||||
// the actual displayed width, so accuracy is preserved at any size.
|
||||
canvas.style.width = '100%';
|
||||
canvas.style.maxWidth = cssW + 'px';
|
||||
canvas.style.height = 'auto';
|
||||
canvas.style.aspectRatio = cssW + ' / ' + cssH;
|
||||
canvas.width = cssW * dpr;
|
||||
canvas.height = cssH * dpr;
|
||||
const ctx = canvas.getContext('2d');
|
||||
ctx.scale(dpr, dpr);
|
||||
ctx.fillStyle = surfaceColor;
|
||||
ctx.fillRect(0, 0, cssW, cssH);
|
||||
ctx.lineCap = 'round';
|
||||
ctx.lineJoin = 'round';
|
||||
|
||||
// Load prior drawing as starting point so consecutive edits compose.
|
||||
const safeInitialImageUrl = _safeImgSrc(initialImageUrl);
|
||||
if (safeInitialImageUrl) {
|
||||
const img = new Image();
|
||||
img.crossOrigin = 'anonymous';
|
||||
img.onload = () => { try { ctx.drawImage(img, 0, 0, cssW, cssH); } catch {} };
|
||||
img.src = safeInitialImageUrl;
|
||||
// Float an X over the canvas so the user can blank it out and go back to
|
||||
// a clean draw surface. Removes itself once clicked.
|
||||
const wrap = container.querySelector('.note-form-draw-wrap');
|
||||
if (wrap && !wrap.querySelector('.note-form-draw-bg-rm')) {
|
||||
const rm = document.createElement('button');
|
||||
rm.type = 'button';
|
||||
rm.className = 'note-form-draw-bg-rm';
|
||||
rm.title = 'Clear photo (regular draw)';
|
||||
rm.innerHTML = '×';
|
||||
rm.addEventListener('click', (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
ctx.fillStyle = surfaceColor;
|
||||
ctx.fillRect(0, 0, cssW, cssH);
|
||||
rm.remove();
|
||||
});
|
||||
wrap.appendChild(rm);
|
||||
}
|
||||
}
|
||||
|
||||
// Swap the native browser color dialog for the in-house HSV picker
|
||||
// (same one used by Themes + the gallery editor). Existing `input` event
|
||||
// listeners + .value reads keep working : see colorPicker.js.
|
||||
if (colorInput) attachColorPicker(colorInput);
|
||||
const sizeInput = container.querySelector('.note-form-draw-size');
|
||||
const beSeg = container.querySelector('.note-form-draw-be');
|
||||
const brushBtn = container.querySelector('.note-form-draw-brush');
|
||||
const eraserBtn = container.querySelector('.note-form-draw-eraser');
|
||||
const textBtn = container.querySelector('.note-form-draw-text');
|
||||
const lineBtn = container.querySelector('.note-form-draw-line');
|
||||
const circleBtn = container.querySelector('.note-form-draw-circle');
|
||||
const undoBtn = container.querySelector('.note-form-draw-undo');
|
||||
// Single source of truth for what clicks/drags do. Other booleans are
|
||||
// derived from this so we never end up with conflicting "eraser AND text"
|
||||
// states (the bug that made T appear broken after using the eraser).
|
||||
// Modes: 'pen' | 'eraser' | 'text-s' | 'text-m' | 'text-l' | 'line' | 'circle'
|
||||
let mode = 'pen';
|
||||
let drawing = false;
|
||||
let last = null;
|
||||
// The text tool has three preset sizes (CSS px font-size).
|
||||
const TEXT_SIZES = { 's': 16, 'm': 26, 'l': 40 };
|
||||
// Line / circle stroke widths in logical pixels : three crisp options.
|
||||
const SHAPE_WIDTHS = { 's': 2, 'm': 5, 'l': 10 };
|
||||
// Snapshot taken at the start of a shape drag so the preview can repaint
|
||||
// cleanly on each move without accumulating intermediate strokes.
|
||||
let _shapeSnapshot = null;
|
||||
|
||||
// Per-canvas undo stack. We snapshot the bitmap (as ImageData) BEFORE each
|
||||
// operation : stroke, text commit, or future operations : and pop+restore
|
||||
// on Undo. Cap to 30 to keep memory bounded.
|
||||
const _undoStack = [];
|
||||
const UNDO_LIMIT = 30;
|
||||
const _syncUndoButton = () => {
|
||||
const available = _undoStack.length > 0;
|
||||
undoBtn?.classList.toggle('has-undo', available);
|
||||
undoBtn?.toggleAttribute('disabled', !available);
|
||||
undoBtn?.setAttribute('aria-disabled', available ? 'false' : 'true');
|
||||
};
|
||||
const _markCanvasDirty = () => container.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
const _snapshot = () => {
|
||||
try {
|
||||
const w = canvas.width, h = canvas.height;
|
||||
_undoStack.push(ctx.getImageData(0, 0, w, h));
|
||||
if (_undoStack.length > UNDO_LIMIT) _undoStack.shift();
|
||||
_syncUndoButton();
|
||||
} catch {}
|
||||
};
|
||||
const _undo = () => {
|
||||
const prev = _undoStack.pop();
|
||||
if (!prev) { _syncUndoButton(); return; }
|
||||
// Restore against the raw backing store: temporarily reset the active
|
||||
// ctx scale, paint the snapshot 1:1, then reapply our standard transform.
|
||||
ctx.save();
|
||||
ctx.setTransform(1, 0, 0, 1, 0, 0);
|
||||
ctx.putImageData(prev, 0, 0);
|
||||
ctx.restore();
|
||||
_markCanvasDirty();
|
||||
_syncUndoButton();
|
||||
};
|
||||
|
||||
const _pos = (e) => {
|
||||
// CSS can shrink the canvas (max-width:100%) without changing its logical
|
||||
// size, so compute the displayed-to-logical scale per axis. Pointer coords
|
||||
// are in CSS pixels; the dpr-scaled ctx expects logical (cssW × cssH).
|
||||
const r = canvas.getBoundingClientRect();
|
||||
const sx = cssW / r.width;
|
||||
const sy = cssH / r.height;
|
||||
const t = e.touches ? e.touches[0] : e;
|
||||
return { x: (t.clientX - r.left) * sx, y: (t.clientY - r.top) * sy };
|
||||
};
|
||||
const _begin = (e) => {
|
||||
if (mode.startsWith('text-')) {
|
||||
// Stop the event so the browser doesn't synthesize a follow-up click
|
||||
// that would blur the input we're about to create.
|
||||
e.preventDefault?.();
|
||||
e.stopPropagation?.();
|
||||
_openTextInput(e);
|
||||
return;
|
||||
}
|
||||
_snapshot();
|
||||
last = _pos(e);
|
||||
drawing = true;
|
||||
if (mode.startsWith('line-') || mode.startsWith('circle-')) {
|
||||
// Capture the backing pixels so the preview can replay each move from
|
||||
// the same starting state (otherwise live shapes accumulate).
|
||||
try { _shapeSnapshot = ctx.getImageData(0, 0, canvas.width, canvas.height); } catch {}
|
||||
return;
|
||||
}
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(last.x, last.y);
|
||||
};
|
||||
|
||||
// Drop an HTML input at the click position so the user can type, then
|
||||
// rasterize the text onto the canvas at blur/Enter. Mirrors how PDF form
|
||||
// annotations work in our doc editor.
|
||||
let _activeTextInput = null;
|
||||
const _openTextInput = (e) => {
|
||||
// Commit any prior pending input before starting a new one : otherwise
|
||||
// the first click leaves an orphaned input the user thinks "didn't work".
|
||||
if (_activeTextInput) { try { _activeTextInput.blur(); } catch {} }
|
||||
const r = canvas.getBoundingClientRect();
|
||||
const t = e.touches ? e.touches[0] : e;
|
||||
// Position is anchored to the wrap, not the canvas; since the canvas is
|
||||
// the first child of the wrap and the wrap has no padding, they share an
|
||||
// origin, so we offset from the canvas rect directly.
|
||||
const px = t.clientX - r.left;
|
||||
const py = t.clientY - r.top;
|
||||
const logical = _pos(e);
|
||||
// Size is decided by which T variant is active (S/M/L), not the stroke
|
||||
// slider : those are independent dials.
|
||||
const sizeKey = mode.startsWith('text-') ? mode.slice(-1) : 'm';
|
||||
const sizeCss = TEXT_SIZES[sizeKey] || TEXT_SIZES.m;
|
||||
const wrap = container.querySelector('.note-form-draw-wrap');
|
||||
if (!wrap) return;
|
||||
if (getComputedStyle(wrap).position === 'static') wrap.style.position = 'relative';
|
||||
const input = document.createElement('input');
|
||||
input.type = 'text';
|
||||
input.className = 'note-form-draw-textinput';
|
||||
input.placeholder = 'type then Enter';
|
||||
const color = colorInput?.value || '#222';
|
||||
const maxW = Math.max(120, Math.floor(r.width - px - 4));
|
||||
input.style.cssText = [
|
||||
'position:absolute',
|
||||
`left:${px}px`,
|
||||
`top:${Math.max(0, py - sizeCss * 0.7)}px`,
|
||||
`font:${sizeCss}px Arial, sans-serif`,
|
||||
`color:${color}`,
|
||||
'background:#ffffff',
|
||||
'border:2px solid var(--accent)',
|
||||
'border-radius:4px',
|
||||
'outline:none',
|
||||
'padding:2px 6px',
|
||||
'min-width:120px',
|
||||
`max-width:${maxW}px`,
|
||||
'z-index:1000',
|
||||
'box-shadow:0 2px 8px rgba(0,0,0,0.25)',
|
||||
'pointer-events:auto',
|
||||
].join(';');
|
||||
wrap.appendChild(input);
|
||||
_activeTextInput = input;
|
||||
// Focus synchronously so the call still counts as inside the user gesture
|
||||
// on iOS / Android, then re-focus on the next frame in case a competing
|
||||
// synthetic event (touch → click) moved focus away.
|
||||
input.focus();
|
||||
requestAnimationFrame(() => { if (document.activeElement !== input) input.focus(); });
|
||||
let committed = false;
|
||||
const commit = () => {
|
||||
if (committed) return;
|
||||
committed = true;
|
||||
const text = input.value;
|
||||
if (_activeTextInput === input) _activeTextInput = null;
|
||||
input.remove();
|
||||
if (!text) return;
|
||||
// Snapshot BEFORE rasterizing so Undo removes the text in one step.
|
||||
_snapshot();
|
||||
ctx.save();
|
||||
ctx.globalCompositeOperation = 'source-over';
|
||||
ctx.fillStyle = color;
|
||||
// Canvas now scales uniformly (style.height: auto), so a single ratio
|
||||
// suffices for picking the logical font size that matches what the
|
||||
// user just saw in the HTML input.
|
||||
const sx = cssW / r.width;
|
||||
const logicalSize = sizeCss * sx;
|
||||
ctx.font = `${logicalSize}px sans-serif`;
|
||||
ctx.textBaseline = 'top';
|
||||
ctx.fillText(text, logical.x, logical.y - logicalSize * 0.7);
|
||||
ctx.restore();
|
||||
_markCanvasDirty();
|
||||
};
|
||||
input.addEventListener('blur', commit);
|
||||
input.addEventListener('keydown', (ev) => {
|
||||
if (ev.key === 'Enter') { ev.preventDefault(); input.blur(); }
|
||||
else if (ev.key === 'Escape') { input.value = ''; input.blur(); }
|
||||
});
|
||||
};
|
||||
const _move = (e) => {
|
||||
if (!drawing) return;
|
||||
e.preventDefault?.();
|
||||
const p = _pos(e);
|
||||
if (mode.startsWith('line-') || mode.startsWith('circle-')) {
|
||||
// Restore the pre-shape bitmap, then redraw the preview shape from
|
||||
// anchor → current pointer.
|
||||
if (_shapeSnapshot) {
|
||||
ctx.save();
|
||||
ctx.setTransform(1, 0, 0, 1, 0, 0);
|
||||
ctx.putImageData(_shapeSnapshot, 0, 0);
|
||||
ctx.restore();
|
||||
}
|
||||
ctx.globalCompositeOperation = 'source-over';
|
||||
ctx.strokeStyle = colorInput?.value || '#222';
|
||||
const sizeKey = mode.slice(-1);
|
||||
ctx.lineWidth = SHAPE_WIDTHS[sizeKey] || SHAPE_WIDTHS.m;
|
||||
ctx.beginPath();
|
||||
if (mode.startsWith('line-')) {
|
||||
ctx.moveTo(last.x, last.y);
|
||||
ctx.lineTo(p.x, p.y);
|
||||
} else {
|
||||
const dx = p.x - last.x;
|
||||
const dy = p.y - last.y;
|
||||
const radius = Math.hypot(dx, dy);
|
||||
ctx.arc(last.x, last.y, radius, 0, Math.PI * 2);
|
||||
}
|
||||
ctx.stroke();
|
||||
return;
|
||||
}
|
||||
const erasing = mode === 'eraser';
|
||||
ctx.globalCompositeOperation = 'source-over';
|
||||
ctx.strokeStyle = erasing ? surfaceColor : (colorInput?.value || highlightColor);
|
||||
ctx.lineWidth = Number(sizeInput?.value || 3) * (erasing ? 2.5 : 1);
|
||||
ctx.lineTo(p.x, p.y);
|
||||
ctx.stroke();
|
||||
last = p;
|
||||
};
|
||||
const _end = () => {
|
||||
if (drawing) _markCanvasDirty();
|
||||
drawing = false; last = null; _shapeSnapshot = null;
|
||||
};
|
||||
|
||||
canvas.addEventListener('mousedown', _begin);
|
||||
canvas.addEventListener('mousemove', _move);
|
||||
lifecycle.listen(canvas, window, 'mouseup', _end);
|
||||
// Non-passive so text mode can preventDefault : otherwise the synthetic
|
||||
// mousedown/click that follows a touch can blur the freshly-created text
|
||||
// input on iOS Safari, making T look like a no-op.
|
||||
canvas.addEventListener('touchstart', (e) => { if (mode.startsWith('text-')) e.preventDefault(); _begin(e); }, { passive: false });
|
||||
canvas.addEventListener('touchmove', _move, { passive: false });
|
||||
canvas.addEventListener('touchend', _end);
|
||||
canvas.addEventListener('touchcancel', _end);
|
||||
|
||||
// Single mode setter : keeps the toolbar, swatch, and cursor in sync, and
|
||||
// makes sure exiting the eraser restores the user's chosen color whether
|
||||
// they exit by clicking another tool or by toggling eraser off.
|
||||
let _preEraseColor = null;
|
||||
const _setMode = (next) => {
|
||||
const wasEraser = mode === 'eraser';
|
||||
mode = next;
|
||||
const isEraser = next === 'eraser';
|
||||
const isPen = next === 'pen';
|
||||
const isText = next.startsWith('text-');
|
||||
// Swatch: theme surface while erasing, restored when leaving that mode.
|
||||
if (isEraser && !wasEraser && colorInput) {
|
||||
_preEraseColor = colorInput.value;
|
||||
colorInput.value = surfaceColorHex;
|
||||
} else if (!isEraser && wasEraser && colorInput && _preEraseColor) {
|
||||
colorInput.value = _preEraseColor;
|
||||
_preEraseColor = null;
|
||||
}
|
||||
// Brush/Eraser segmented pill : slides to the active side. When a non-
|
||||
// pen/eraser tool (T / line / circle) is active, neither half is
|
||||
// highlighted, but the pill still indicates which side the user was on
|
||||
// last so they can return with one click.
|
||||
const isLine = next.startsWith('line-');
|
||||
const isCircle = next.startsWith('circle-');
|
||||
beSeg?.classList.toggle('is-eraser', isEraser);
|
||||
brushBtn?.classList.toggle('active', isPen);
|
||||
eraserBtn?.classList.toggle('active', isEraser);
|
||||
textBtn?.classList.toggle('active', isText);
|
||||
lineBtn?.classList.toggle('active', isLine);
|
||||
circleBtn?.classList.toggle('active', isCircle);
|
||||
// Per-button size badges (S/M/L), driven off the mode suffix.
|
||||
const tBadge = textBtn?.querySelector('.note-form-draw-text-badge');
|
||||
if (tBadge) tBadge.textContent = isText ? next.slice(-1).toUpperCase() : '';
|
||||
const lBadge = lineBtn?.querySelector('.note-form-draw-shape-badge');
|
||||
if (lBadge) lBadge.textContent = isLine ? next.slice(-1).toUpperCase() : '';
|
||||
const cBadge = circleBtn?.querySelector('.note-form-draw-shape-badge');
|
||||
if (cBadge) cBadge.textContent = isCircle ? next.slice(-1).toUpperCase() : '';
|
||||
// Reflect the chosen size in the icon itself : thicker line/circle stroke
|
||||
// for M+L, larger T glyph for M+L. CSS rules read `.size-s/.size-m/.size-l`.
|
||||
const _sz = next.slice(-1);
|
||||
[textBtn, lineBtn, circleBtn].forEach(b => b?.classList.remove('size-s', 'size-m', 'size-l'));
|
||||
if (isText && /[sml]/.test(_sz)) textBtn?.classList.add('size-' + _sz);
|
||||
if (isLine && /[sml]/.test(_sz)) lineBtn?.classList.add('size-' + _sz);
|
||||
if (isCircle && /[sml]/.test(_sz)) circleBtn?.classList.add('size-' + _sz);
|
||||
canvas.style.cursor = isText ? 'text' : 'crosshair';
|
||||
};
|
||||
brushBtn?.addEventListener('click', () => _setMode('pen'));
|
||||
eraserBtn?.addEventListener('click', () => _setMode('eraser'));
|
||||
// T / Line / Circle: each cycles its own three sizes, then back to pen.
|
||||
const _cycle = (prefix) => {
|
||||
const seq = ['s', 'm', 'l'];
|
||||
if (!mode.startsWith(prefix)) return prefix + 's';
|
||||
const cur = mode.slice(-1);
|
||||
const next = seq[seq.indexOf(cur) + 1];
|
||||
return next ? prefix + next : 'pen';
|
||||
};
|
||||
textBtn?.addEventListener('click', () => _setMode(_cycle('text-')));
|
||||
lineBtn?.addEventListener('click', () => _setMode(_cycle('line-')));
|
||||
circleBtn?.addEventListener('click', () => _setMode(_cycle('circle-')));
|
||||
undoBtn?.addEventListener('click', () => _undo());
|
||||
_syncUndoButton();
|
||||
|
||||
// Stash so the save handler can read it later without re-resolving DOM.
|
||||
canvas._cssW = cssW;
|
||||
canvas._cssH = cssH;
|
||||
return canvas;
|
||||
}
|
||||
|
||||
async function _uploadCanvasAsPng(canvas, galleryId = null) {
|
||||
if (!canvas) return null;
|
||||
const blob = await new Promise(r => canvas.toBlob(r, 'image/png'));
|
||||
if (!blob) return null;
|
||||
const fd = new FormData();
|
||||
fd.append('files', blob, 'drawing.png');
|
||||
if (galleryId) fd.append('gallery_id', galleryId);
|
||||
try {
|
||||
const res = await api.upload(fd);
|
||||
const data = await res.json();
|
||||
const id = data.files?.[0]?.id;
|
||||
return id ? {
|
||||
url: api.uploadUrl(id),
|
||||
galleryId: data.files?.[0]?.gallery_id || null,
|
||||
} : null;
|
||||
} catch { return null; }
|
||||
}
|
||||
|
||||
return { _buildDrawHtml, _wireCanvas, _uploadCanvasAsPng };
|
||||
}
|
||||
@@ -0,0 +1,518 @@
|
||||
/** Build and wire note, checklist, goal and drawing editor forms. */
|
||||
export function createEditor({
|
||||
deleteFromEditor,
|
||||
submitNote,
|
||||
COLORS,
|
||||
_applyMasonry,
|
||||
_archiveNoteById,
|
||||
_buildChecklistHtml,
|
||||
_buildDrawHtml,
|
||||
_buildGoalHtml,
|
||||
_collectItems,
|
||||
_customColorStyle,
|
||||
_dotBg,
|
||||
_dotIsActive,
|
||||
_esc,
|
||||
_isBgImage,
|
||||
_renderNotes,
|
||||
_safeImgSrc,
|
||||
_uid,
|
||||
_uploadCanvasAsPng,
|
||||
_wireCanvas,
|
||||
_wireChecklist,
|
||||
_wireDraftAutosave,
|
||||
_wireFormColors,
|
||||
_wireGoalForm,
|
||||
_wireReminderPicker,
|
||||
api,
|
||||
app,
|
||||
state,
|
||||
uiModule
|
||||
}) {
|
||||
function _buildForm(note = null) {
|
||||
const isEdit = note && note.id;
|
||||
const type = note?.note_type === 'checklist' ? 'todo' : (note?.note_type || 'note');
|
||||
const color = note?.color || '';
|
||||
const items = note?.items || [{ id: _uid(), text: '', done: false }];
|
||||
|
||||
const form = document.createElement('div');
|
||||
form.className = 'note-form';
|
||||
form.dataset.noteType = type;
|
||||
form.dataset.noteColor = color || '';
|
||||
if (color && !_isBgImage(color)) form.classList.add('note-color-' + color);
|
||||
if (_isBgImage(color)) form.setAttribute('style', _customColorStyle(color));
|
||||
let currentImageUrl = _safeImgSrc(note?.image_url || '');
|
||||
form.innerHTML = `
|
||||
<div class="note-form-header">
|
||||
<input type="text" class="note-form-title" placeholder="Title" value="${_esc(note?.title || '')}" />
|
||||
<button type="button" class="note-form-icon-btn note-form-remind-btn${note?.due_date ? ' has-date' : ''}" title="Remind me">
|
||||
<svg width="31" height="31" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 0 1-3.46 0"/></svg>
|
||||
</button>
|
||||
<input type="hidden" class="note-form-due" value="${note?.due_date || ''}" />
|
||||
<input type="hidden" class="note-form-repeat" value="${note?.repeat || 'none'}" />
|
||||
</div>
|
||||
${currentImageUrl && type !== 'draw' ? `<div class="note-form-image-wrap"><img class="note-form-image" src="${_esc(currentImageUrl)}" draggable="false" /><button class="note-form-image-rm" title="Remove">×</button></div>` : ''}
|
||||
<div class="note-form-body">
|
||||
${type === 'note'
|
||||
? `<textarea class="note-form-content" placeholder="Take a note..." rows="4">${_esc(note?.content || '')}</textarea>`
|
||||
: type === 'draw'
|
||||
? _buildDrawHtml()
|
||||
: type === 'goal'
|
||||
? _buildGoalHtml(note, items)
|
||||
: _buildChecklistHtml(items)}
|
||||
</div>
|
||||
<div class="note-form-reminder-tags"></div>
|
||||
<div class="note-form-meta">
|
||||
<div class="note-form-type-seg${type === 'todo' ? ' is-todo' : type === 'draw' ? ' is-draw' : ''}" role="group">
|
||||
<button type="button" class="note-form-type-pill${type === 'note' ? ' active' : ''}" data-type="note">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="4" y1="6" x2="20" y2="6"/><line x1="4" y1="12" x2="20" y2="12"/><line x1="4" y1="18" x2="14" y2="18"/></svg>
|
||||
<span>Note</span>
|
||||
</button>
|
||||
<button type="button" class="note-form-type-pill${type === 'todo' ? ' active' : ''}" data-type="todo">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 11 12 14 22 4"/><path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"/></svg>
|
||||
<span>Todo</span>
|
||||
</button>
|
||||
<button type="button" class="note-form-type-pill${type === 'draw' ? ' active' : ''}" data-type="draw">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 19l7-7 3 3-7 7-3-3z"/><path d="M18 13l-1.5-7.5L2 2l3.5 14.5L13 18l5-5z"/><path d="M2 2l7.586 7.586"/><circle cx="11" cy="11" r="2"/></svg>
|
||||
<span>Draw</span>
|
||||
</button>
|
||||
</div>
|
||||
<button class="note-form-photo-btn" title="Attach photo">
|
||||
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>
|
||||
</button>
|
||||
<input type="file" class="note-form-photo-input" accept="image/*" capture="environment" style="display:none" />
|
||||
<div class="note-color-picker">
|
||||
${COLORS.map(c => `<span class="note-color-dot${_dotIsActive(c.value, color) ? ' active' : ''}" data-color="${c.value}" style="background:${_dotBg(c.value, color)}" title="${c.name || 'default'}"></span>`).join('')}
|
||||
</div>
|
||||
<input type="text" class="note-form-label" value="${_esc(note?.label || '')}" placeholder="#tag1 #tag2" title="Tag(s) — space-separated" />
|
||||
<div class="note-form-actions-group">
|
||||
${isEdit ? `
|
||||
<button type="button" class="note-form-text-btn note-form-archive-btn note-form-collapsible" title="Archive">
|
||||
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="3" width="20" height="5" rx="1"/><path d="M4 8v11a2 2 0 002 2h12a2 2 0 002-2V8"/><path d="M10 12h4"/></svg><span class="nft-label">Archive</span>
|
||||
</button>
|
||||
<button type="button" class="note-form-text-btn note-form-delete-btn note-form-collapsible danger" title="Delete">
|
||||
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/><line x1="10" y1="11" x2="10" y2="17"/><line x1="14" y1="11" x2="14" y2="17"/></svg><span class="nft-label">Delete</span>
|
||||
</button>
|
||||
` : ''}
|
||||
<span class="note-form-actions-spacer"></span>
|
||||
<button class="note-form-cancel note-form-text-btn note-form-collapsible" title="Close (keep changes)">
|
||||
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"><line x1="6" y1="6" x2="18" y2="18"/><line x1="18" y1="6" x2="6" y2="18"/></svg><span class="nft-label">Close</span>
|
||||
</button>
|
||||
<button class="note-form-save note-form-text-btn" title="${isEdit ? 'Update' : 'Save'}">
|
||||
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg><span class="nft-label">${isEdit ? 'Update' : 'Save'}</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
let currentType = type;
|
||||
let currentColor = color;
|
||||
// Stash original-form values so round-trips (Note→Todo→Note) restore the
|
||||
// user's hand-formatted text instead of a join of generated items. Same the
|
||||
// other way: if you started in todo, switch to note, switch back, items
|
||||
// come back unchanged.
|
||||
let _stashedNoteText = (type === 'note') ? (note?.content || '') : null;
|
||||
let _stashedTodoItems = (type === 'todo' && Array.isArray(note?.items)) ? note.items.slice() : null;
|
||||
// Goal mode kept its own pair of stashes (description + steps) so a
|
||||
// Todo→Goal→Todo round-trip wouldn't lose either side. The Goal pill in
|
||||
// the type picker was later removed, so the only entry point now is
|
||||
// *editing* an existing goal-typed note : but the switch handler still
|
||||
// accepts Goal→Todo/Note transitions (downgrading legacy goals), so
|
||||
// these stashes still earn their keep.
|
||||
let _stashedGoalDesc = (type === 'goal') ? (note?.content || '') : null;
|
||||
let _stashedGoalItems = (type === 'goal' && Array.isArray(note?.items)) ? note.items.slice() : null;
|
||||
|
||||
// Drawing also stashes the saved image URL so it survives Note↔Draw flips.
|
||||
let _stashedDrawUrl = (type === 'draw') ? (_safeImgSrc(note?.image_url) || null) : null;
|
||||
const _refreshFormLayout = () => {
|
||||
const body = form.closest('.notes-pane-body');
|
||||
if (!body) return;
|
||||
_applyMasonry(body);
|
||||
requestAnimationFrame(() => {
|
||||
_applyMasonry(body);
|
||||
requestAnimationFrame(() => _applyMasonry(body));
|
||||
});
|
||||
};
|
||||
|
||||
// Type segmented control : Note | Todo | Draw
|
||||
form.querySelectorAll('.note-form-type-pill').forEach(pill => {
|
||||
pill.addEventListener('click', () => {
|
||||
const newType = pill.dataset.type;
|
||||
if (newType === currentType) return;
|
||||
const bodyEl = form.querySelector('.note-form-body');
|
||||
// Stash whatever the user has in the current mode before swapping it
|
||||
// out, so a subsequent flip back restores their work.
|
||||
if (currentType === 'note') {
|
||||
_stashedNoteText = form.querySelector('.note-form-content')?.value || '';
|
||||
} else if (currentType === 'todo') {
|
||||
_stashedTodoItems = _collectItems(form);
|
||||
} else if (currentType === 'goal') {
|
||||
_stashedGoalDesc = form.querySelector('.note-form-goal-desc')?.value || '';
|
||||
_stashedGoalItems = _collectItems(form);
|
||||
} else if (currentType === 'draw') {
|
||||
const c = form.querySelector('.note-form-canvas');
|
||||
if (c) { try { _stashedDrawUrl = c.toDataURL('image/png'); } catch {} }
|
||||
}
|
||||
// Render the new mode's body and re-wire its inputs.
|
||||
if (newType === 'todo') {
|
||||
let nextItems;
|
||||
if (_stashedTodoItems && _stashedTodoItems.length) {
|
||||
nextItems = _stashedTodoItems;
|
||||
} else if (_stashedGoalItems && _stashedGoalItems.length) {
|
||||
// Going Goal→Todo keeps the AI-generated steps as a plain checklist.
|
||||
nextItems = _stashedGoalItems;
|
||||
} else if (_stashedNoteText) {
|
||||
const lines = _stashedNoteText.split('\n').map(s => s.trim()).filter(Boolean);
|
||||
nextItems = lines.length ? lines.map(t => ({ id: _uid(), text: t, done: false })) : [{ id: _uid(), text: '', done: false }];
|
||||
} else {
|
||||
nextItems = [{ id: _uid(), text: '', done: false }];
|
||||
}
|
||||
bodyEl.innerHTML = _buildChecklistHtml(nextItems);
|
||||
_wireChecklist(bodyEl);
|
||||
} else if (newType === 'draw') {
|
||||
bodyEl.innerHTML = _buildDrawHtml();
|
||||
// If the user just attached a photo (via the photo button) and then
|
||||
// toggled to Draw, paint that photo onto the canvas so they can draw
|
||||
// on top of it. _stashedDrawUrl wins if they were drawing earlier in
|
||||
// the same edit session.
|
||||
_wireCanvas(bodyEl, _stashedDrawUrl || currentImageUrl || _safeImgSrc(note?.image_url) || null);
|
||||
} else {
|
||||
const text = (_stashedNoteText !== null && _stashedNoteText !== undefined && _stashedNoteText !== '')
|
||||
? _stashedNoteText
|
||||
: (_stashedGoalDesc && _stashedGoalDesc)
|
||||
|| (_stashedTodoItems || _stashedGoalItems || []).map(i => i.text).join('\n');
|
||||
bodyEl.innerHTML = `<textarea class="note-form-content" placeholder="Take a note..." rows="4">${_esc(text)}</textarea>`;
|
||||
_wireHashtag(bodyEl.querySelector('.note-form-content'));
|
||||
}
|
||||
const focusEl = newType === 'note'
|
||||
? bodyEl.querySelector('.note-form-content')
|
||||
: newType === 'todo'
|
||||
? bodyEl.querySelector('.note-cl-text')
|
||||
: null;
|
||||
if (focusEl) {
|
||||
requestAnimationFrame(() => {
|
||||
focusEl.focus({ preventScroll: true });
|
||||
try {
|
||||
const end = focusEl.value.length;
|
||||
focusEl.setSelectionRange(end, end);
|
||||
} catch {}
|
||||
});
|
||||
}
|
||||
currentType = newType;
|
||||
const seg = form.querySelector('.note-form-type-seg');
|
||||
seg?.classList.toggle('is-todo', newType === 'todo');
|
||||
seg?.classList.toggle('is-draw', newType === 'draw');
|
||||
form.querySelectorAll('.note-form-type-pill').forEach(p => p.classList.toggle('active', p.dataset.type === newType));
|
||||
// The standalone image preview (form-image-wrap) and the canvas would
|
||||
// otherwise both show the same image_url when editing a drawn note.
|
||||
// Hide it in draw mode, restore it when leaving draw mode.
|
||||
const imgWrap = form.querySelector('.note-form-image-wrap');
|
||||
if (imgWrap) imgWrap.style.display = (newType === 'draw') ? 'none' : '';
|
||||
// The background-color dots set the note card's bg : they make no sense
|
||||
// for a drawn note (the canvas image IS the card content), so hide them.
|
||||
const bgPicker = form.querySelector('.note-color-picker');
|
||||
if (bgPicker) bgPicker.style.display = (newType === 'draw') ? 'none' : '';
|
||||
if (form.closest('.notes-pane.notes-view-grid') && window.matchMedia('(max-width: 768px)').matches) {
|
||||
form.style.gridColumn = '1 / -1';
|
||||
form.style.gridRowEnd = newType === 'draw' ? 'span 152' : 'span 64';
|
||||
}
|
||||
_refreshFormLayout();
|
||||
});
|
||||
});
|
||||
|
||||
// Slide a finger across the Note/Todo/Draw control to switch modes (mobile).
|
||||
// On touchmove we find the pill under the finger and click it : reusing the
|
||||
// pill click handler above, so the body re-renders + content stashing all
|
||||
// work. Only fires when crossing into a *different* pill.
|
||||
const _typeSeg = form.querySelector('.note-form-type-seg');
|
||||
if (_typeSeg) {
|
||||
let _sliding = false;
|
||||
const _activateAt = (x, y) => {
|
||||
const pill = document.elementFromPoint(x, y)?.closest?.('.note-form-type-pill');
|
||||
if (pill && !pill.classList.contains('active')) pill.click();
|
||||
};
|
||||
_typeSeg.addEventListener('touchstart', () => { _sliding = true; }, { passive: true });
|
||||
_typeSeg.addEventListener('touchmove', (e) => {
|
||||
if (_sliding && e.touches[0]) _activateAt(e.touches[0].clientX, e.touches[0].clientY);
|
||||
}, { passive: true });
|
||||
_typeSeg.addEventListener('touchend', () => { _sliding = false; });
|
||||
_typeSeg.addEventListener('touchcancel', () => { _sliding = false; });
|
||||
}
|
||||
|
||||
_wireFormColors(form, value => { currentColor = value; });
|
||||
|
||||
if (currentType === 'todo') _wireChecklist(form.querySelector('.note-form-body'));
|
||||
if (currentType === 'goal') _wireGoalForm(form, form.querySelector('.note-form-body'));
|
||||
if (currentType === 'draw') {
|
||||
_wireCanvas(form.querySelector('.note-form-body'), _safeImgSrc(note?.image_url) || null);
|
||||
// Same hides we apply on type-switch : keep them consistent on initial open.
|
||||
const _ip = form.querySelector('.note-form-image-wrap'); if (_ip) _ip.style.display = 'none';
|
||||
const _cp = form.querySelector('.note-color-picker'); if (_cp) _cp.style.display = 'none';
|
||||
}
|
||||
|
||||
// Auto-grow the plain-note textarea so editing longer notes is
|
||||
// comfortable : it expands with the content (up to a cap) instead of
|
||||
// staying a cramped 4-row box. The user can still drag-resize too.
|
||||
const _contentTa = form.querySelector('.note-form-content');
|
||||
if (_contentTa) {
|
||||
const _grow = () => {
|
||||
_contentTa.style.height = 'auto';
|
||||
// Inline form: cap at ~50vh so a huge note doesn't push the action
|
||||
// buttons off-screen. Fullscreen mobile overlay: the body scrolls and
|
||||
// there are no inline buttons crowding, so allow nearly the full height
|
||||
// : capping at 50vh there clipped longer notes ("part disappears").
|
||||
const inFullscreen = !!_contentTa.closest('.note-fullscreen-overlay');
|
||||
const max = Math.round(window.innerHeight * (inFullscreen ? 0.9 : 0.5));
|
||||
_contentTa.style.height = Math.min(_contentTa.scrollHeight, max) + 'px';
|
||||
};
|
||||
_contentTa.addEventListener('input', _grow);
|
||||
// Grow on open so existing content is fully visible. Run again after the
|
||||
// fullscreen overlay's open animation settles : measuring mid-animation
|
||||
// (the overlay starts scaled/transitioning) can under-size the box.
|
||||
setTimeout(_grow, 0);
|
||||
setTimeout(_grow, 360);
|
||||
}
|
||||
|
||||
_wireReminderPicker(form);
|
||||
|
||||
// Photo upload
|
||||
const photoBtn = form.querySelector('.note-form-photo-btn');
|
||||
const photoInput = form.querySelector('.note-form-photo-input');
|
||||
if (photoBtn && photoInput) {
|
||||
photoBtn.addEventListener('click', () => photoInput.click());
|
||||
photoInput.addEventListener('change', async () => {
|
||||
const file = photoInput.files?.[0];
|
||||
if (!file) return;
|
||||
const fd = new FormData();
|
||||
fd.append('files', file);
|
||||
try {
|
||||
const res = await api.upload(fd);
|
||||
const data = await res.json();
|
||||
const fileId = data.files?.[0]?.id;
|
||||
if (!fileId) throw new Error('Upload failed');
|
||||
currentImageUrl = api.uploadUrl(fileId);
|
||||
// Only ever keep the latest attached photo : drop any existing wrap
|
||||
// before inserting a fresh one. Picking a second photo replaces the
|
||||
// first instead of stacking.
|
||||
form.querySelector('.note-form-image-wrap')?.remove();
|
||||
const wrap = document.createElement('div');
|
||||
wrap.className = 'note-form-image-wrap';
|
||||
wrap.innerHTML = `<img class="note-form-image" draggable="false" /><button class="note-form-image-rm" title="Remove">×</button>`;
|
||||
// Insert AFTER the whole header (a flex-row), not after the
|
||||
// title input itself : otherwise the image lands as a sibling
|
||||
// of the title inside the header and flex puts them side-by-side.
|
||||
form.querySelector('.note-form-header').after(wrap);
|
||||
wrap.querySelector('.note-form-image-rm').addEventListener('click', () => { wrap.remove(); currentImageUrl = ''; });
|
||||
wrap.querySelector('img').src = currentImageUrl;
|
||||
} catch (err) { uiModule.showError('Image upload failed'); }
|
||||
photoInput.value = '';
|
||||
});
|
||||
}
|
||||
// Existing image remove
|
||||
form.querySelector('.note-form-image-rm')?.addEventListener('click', () => {
|
||||
form.querySelector('.note-form-image-wrap')?.remove();
|
||||
currentImageUrl = '';
|
||||
});
|
||||
|
||||
// Title Enter -> focus body (textarea or first checklist item)
|
||||
form.querySelector('.note-form-title').addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Enter' && !e.shiftKey && !e.ctrlKey && !e.metaKey) {
|
||||
e.preventDefault();
|
||||
const ta = form.querySelector('.note-form-content');
|
||||
if (ta) { ta.focus(); return; }
|
||||
const firstItem = form.querySelector('.note-cl-text');
|
||||
if (firstItem) firstItem.focus();
|
||||
}
|
||||
});
|
||||
|
||||
// Hashtag → label: typing "#foo " in title/content appends "foo" to the
|
||||
// space-separated tag list. Repeats are deduplicated, so #foo #foo only
|
||||
// keeps one. Tags already present in the label field are left alone.
|
||||
const labelInput = form.querySelector('.note-form-label');
|
||||
const _hashtagRe = /(^|\s)#([A-Za-z0-9][\w-]*)\s$/;
|
||||
function _wireHashtag(el) {
|
||||
if (!el || !labelInput) return;
|
||||
el.addEventListener('input', () => {
|
||||
const m = _hashtagRe.exec(el.value);
|
||||
if (!m) return;
|
||||
const tag = m[2];
|
||||
// Dedup against the stripped form : labelInput may already hold `#tag`
|
||||
// (after Enter normalised), so includes(tag) on the raw split would
|
||||
// miss the duplicate and append a bare `tag` next to `#tag`.
|
||||
const existing = labelInput.value.trim().split(/\s+/).filter(Boolean);
|
||||
const stripped = existing.map(t => t.replace(/^#+/, ''));
|
||||
if (!stripped.includes(tag)) {
|
||||
existing.push('#' + tag);
|
||||
labelInput.value = existing.join(' ');
|
||||
labelInput.classList.add('flash-once');
|
||||
setTimeout(() => labelInput.classList.remove('flash-once'), 600);
|
||||
}
|
||||
const cut = el.value.length - m[0].length + m[1].length;
|
||||
el.value = el.value.slice(0, cut);
|
||||
});
|
||||
}
|
||||
_wireHashtag(form.querySelector('.note-form-title'));
|
||||
_wireHashtag(form.querySelector('.note-form-content'));
|
||||
// Pressing Enter in the tag field commits the current word as its own tag
|
||||
// and parks the cursor after a trailing space, so the next word becomes a
|
||||
// separate tag rather than overwriting the previous one.
|
||||
labelInput?.addEventListener('keydown', (e) => {
|
||||
if (e.key !== 'Enter' || e.shiftKey || e.ctrlKey || e.metaKey) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
// Strip any leading #s the user typed, dedupe, then re-prepend exactly
|
||||
// one #. So typing "foo" or "#foo" both end up as "#foo " in the input;
|
||||
// the save handler keeps stripping #s before storing so DB stays clean.
|
||||
const tags = [...new Set(labelInput.value.split(/\s+/).map(t => t.replace(/^#+/, '').trim()).filter(Boolean))];
|
||||
if (!tags.length) return;
|
||||
labelInput.value = tags.map(t => '#' + t).join(' ') + ' ';
|
||||
labelInput.setSelectionRange(labelInput.value.length, labelInput.value.length);
|
||||
labelInput.classList.add('flash-once');
|
||||
setTimeout(() => labelInput.classList.remove('flash-once'), 600);
|
||||
});
|
||||
|
||||
// Shift+Enter (or Cmd/Ctrl+Enter) anywhere in the form -> save
|
||||
// Escape -> cancel edit
|
||||
form.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Enter' && (e.shiftKey || e.ctrlKey || e.metaKey)) {
|
||||
e.preventDefault();
|
||||
form.querySelector('.note-form-save')?.click();
|
||||
} else if (e.key === 'Escape') {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
form.querySelector('.note-form-cancel')?.click();
|
||||
}
|
||||
});
|
||||
|
||||
// Save. Prevent the button from stealing focus on press: on mobile, the
|
||||
// first tap would otherwise just blur the focused textarea/input (closing
|
||||
// the keyboard and shifting layout), so the tap never reached the button and
|
||||
// you had to tap "Done" twice. mousedown preventDefault keeps focus put while
|
||||
// still letting the click fire.
|
||||
const _saveBtnEl0 = form.querySelector('.note-form-save');
|
||||
_saveBtnEl0.addEventListener('mousedown', (e) => e.preventDefault());
|
||||
_saveBtnEl0.addEventListener('click', async () => {
|
||||
// Guard against spam-clicks: the drawing save AWAITS a canvas upload before
|
||||
// the optimistic re-render removes the form, so without this a slow upload
|
||||
// let repeated clicks create duplicate notes.
|
||||
const _saveBtn = form.querySelector('.note-form-save');
|
||||
if (_saveBtn._saving) return;
|
||||
// Mobile: when an existing note is opened and closed without edits, the
|
||||
// Update (✓) button morphs into Archive (set up below). Route the click
|
||||
// directly through the archive flow. Using a DOM .click() proxy here was
|
||||
// fragile on mobile because the real archive button can move from the
|
||||
// footer to the fullscreen header.
|
||||
if (_saveBtn.classList.contains('archive-mode')) {
|
||||
_archiveNoteById(note?.id);
|
||||
return;
|
||||
}
|
||||
_saveBtn._saving = true; _saveBtn.disabled = true; _saveBtn.style.opacity = '0.5';
|
||||
try {
|
||||
form._flushDraft?.();
|
||||
await form._stopDraftAutosave?.();
|
||||
form._flushDraft?.();
|
||||
const title = form.querySelector('.note-form-title').value.trim();
|
||||
// Normalize tag input: split on whitespace, strip leading #s, dedupe,
|
||||
// re-join with single spaces. Empty → null.
|
||||
const _rawLabel = form.querySelector('.note-form-label')?.value || '';
|
||||
const _tags = [...new Set(_rawLabel.split(/\s+/).map(t => t.replace(/^#+/, '').trim()).filter(Boolean))];
|
||||
if (form.querySelector('.note-form-due').value && !_tags.includes('reminder')) _tags.push('reminder');
|
||||
const labelVal = _tags.length ? _tags.join(' ') : null;
|
||||
const payload = {
|
||||
title,
|
||||
note_type: currentType,
|
||||
color: currentColor,
|
||||
label: labelVal,
|
||||
due_date: form.querySelector('.note-form-due').value || null,
|
||||
repeat: form.querySelector('.note-form-repeat')?.value || 'none',
|
||||
image_url: currentImageUrl || null,
|
||||
};
|
||||
if (currentType === 'note') {
|
||||
payload.content = form.querySelector('.note-form-content')?.value || '';
|
||||
} else if (currentType === 'draw') {
|
||||
// Upload the canvas PNG before saving so image_url points to a
|
||||
// persistent file. We block the save until upload completes : drawings
|
||||
// can't be re-rendered later without the URL.
|
||||
const canvas = form.querySelector('.note-form-canvas');
|
||||
const upload = await _uploadCanvasAsPng(canvas, note?.gallery_id || null);
|
||||
if (!upload?.url) { uiModule.showError('Failed to save drawing'); return; }
|
||||
payload.image_url = upload.url;
|
||||
if (upload.galleryId) payload.gallery_id = upload.galleryId;
|
||||
} else if (currentType === 'goal') {
|
||||
// Legacy: existing goal-type notes still edit through this branch.
|
||||
// No AI involvement : save as a normal note with description + items.
|
||||
payload.content = form.querySelector('.note-form-goal-desc')?.value || '';
|
||||
payload.items = _collectItems(form);
|
||||
} else {
|
||||
payload.items = _collectItems(form);
|
||||
}
|
||||
if (isEdit) payload.id = note.id;
|
||||
submitNote(payload, note, isEdit);
|
||||
} finally {
|
||||
// Re-enable on early returns / errors. On success the form is removed by
|
||||
// the optimistic re-render, so re-enabling the detached button is a no-op.
|
||||
_saveBtn._saving = false; _saveBtn.disabled = false; _saveBtn.style.opacity = '';
|
||||
}
|
||||
});
|
||||
|
||||
// Mobile-only: when editing an existing note, the Update (✓) button starts in
|
||||
// archive-mode (visually + behaviorally) and flips to Update on the first
|
||||
// edit. Lets the user tap a note to skim, then tap ✓ to archive without ever
|
||||
// touching a separate Archive button.
|
||||
if (isEdit && window.innerWidth <= 768) {
|
||||
const _saveLabelEl = _saveBtnEl0.querySelector('.nft-label');
|
||||
const _isFinishedTodo = () => {
|
||||
if (currentType !== 'todo') return false;
|
||||
const rows = [...form.querySelectorAll('.note-cl-row')];
|
||||
const withText = rows.filter(row => (row.querySelector('.note-cl-text')?.value || '').trim());
|
||||
return withText.length > 0 && withText.every(row => row.classList.contains('done'));
|
||||
};
|
||||
const _enterArchive = () => {
|
||||
_saveBtnEl0.classList.add('archive-mode');
|
||||
const label = _isFinishedTodo() ? 'Finish' : 'Archive';
|
||||
if (_saveLabelEl) _saveLabelEl.textContent = label;
|
||||
_saveBtnEl0.title = label;
|
||||
};
|
||||
const _enterUpdate = () => {
|
||||
if (!_saveBtnEl0.classList.contains('archive-mode')) return;
|
||||
_saveBtnEl0.classList.remove('archive-mode');
|
||||
if (_saveLabelEl) _saveLabelEl.textContent = 'Update';
|
||||
_saveBtnEl0.title = 'Update';
|
||||
};
|
||||
_enterArchive();
|
||||
form.addEventListener('input', _enterUpdate, true);
|
||||
form.addEventListener('change', _enterUpdate, true);
|
||||
// Checklist dots use a custom control and dispatch their update before
|
||||
// this click bubbles. Re-evaluate afterward so a fully completed todo
|
||||
// offers Finish (which archives/removes it from the active list).
|
||||
form.addEventListener('click', (event) => {
|
||||
if (!event.target.closest('.note-cl-dot')) return;
|
||||
setTimeout(() => {
|
||||
if (_isFinishedTodo()) _enterArchive();
|
||||
else _enterUpdate();
|
||||
}, 0);
|
||||
}, true);
|
||||
}
|
||||
|
||||
// Cancel
|
||||
form.querySelector('.note-form-cancel').addEventListener('click', () => { form._flushDraft?.(); app.setEditingId(null); _renderNotes(); });
|
||||
|
||||
// Archive / Delete : edit-mode-only buttons, mirror the (now-hidden) card actions.
|
||||
form.querySelector('.note-form-archive-btn')?.addEventListener('click', () => {
|
||||
if (!isEdit) return;
|
||||
_archiveNoteById(note.id);
|
||||
});
|
||||
form.querySelector('.note-form-delete-btn')?.addEventListener('click', () => {
|
||||
if (!isEdit) return;
|
||||
return deleteFromEditor(note.id);
|
||||
});
|
||||
|
||||
// Autosave a draft to persistence on every change so unsaved edits
|
||||
// survive connection loss / reload / accidental close.
|
||||
_wireDraftAutosave(form, isEdit ? note.id : '__new__');
|
||||
|
||||
return form;
|
||||
}
|
||||
|
||||
return { _buildForm };
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
/** Label chips, reminder/goal filters and collapsed tag-strip rendering. */
|
||||
import { _visibleNoteTags, _nextGoalStep } from '../domain/noteRules.js';
|
||||
import { _hasTimeComponent } from '../domain/recurrence.js';
|
||||
export function createFilters({
|
||||
NOTES_LABELS_COLLAPSED_KEY,
|
||||
_clearPastReminders,
|
||||
_esc,
|
||||
_isPastReminder,
|
||||
_renderNotes,
|
||||
_userVisibleNotes,
|
||||
app,
|
||||
persistence,
|
||||
state
|
||||
}) {
|
||||
function _renderLabels(root = document) {
|
||||
const bar = root.querySelector?.('.notes-labels-bar') || document.querySelector('.notes-labels-bar');
|
||||
if (!bar) return;
|
||||
if (state.labelsCollapsed) {
|
||||
bar.innerHTML = '';
|
||||
bar.style.display = 'none';
|
||||
return;
|
||||
}
|
||||
const visibleNotes = _userVisibleNotes();
|
||||
const labels = new Set();
|
||||
for (const n of visibleNotes) for (const t of _visibleNoteTags(n)) labels.add(t);
|
||||
const sortedLabels = [...labels].sort();
|
||||
// Count active reminders (not archived, has datetime due_date)
|
||||
const reminderCount = visibleNotes.filter(n => !n.archived && n.due_date && _hasTimeComponent(n.due_date)).length;
|
||||
const pastReminderCount = visibleNotes.filter(n => !n.archived && _isPastReminder(n)).length;
|
||||
const defaultCount = visibleNotes.filter(n => !n.archived && _visibleNoteTags(n).length === 0).length;
|
||||
// Active goals = non-archived goal notes. Today view lists pending steps
|
||||
// from each, so we surface the count next to the chip.
|
||||
const goalCount = visibleNotes.filter(n => n.note_type === 'goal' && !n.archived).length;
|
||||
const todayCount = visibleNotes.filter(n => n.note_type === 'goal' && !n.archived && _nextGoalStep(n)).length;
|
||||
const hasUsefulFilters = sortedLabels.length > 0 || reminderCount > 0 || goalCount > 0;
|
||||
const hasActiveFilter = state.activeLabel !== null || state.activeFilter !== null;
|
||||
if (!hasUsefulFilters && !hasActiveFilter) {
|
||||
bar.innerHTML = '';
|
||||
bar.style.display = 'none';
|
||||
return;
|
||||
}
|
||||
bar.style.display = '';
|
||||
const allActive = state.activeLabel === null && state.activeFilter === null;
|
||||
let html = `<button class="notes-label-chip${allActive ? ' active' : ''}" data-action="all">All</button>`;
|
||||
html += `<button class="notes-label-chip${state.activeFilter === 'default' ? ' active' : ''}" data-action="default" title="Show notes without tags">Default <span class="notes-label-chip-count">${defaultCount}</span></button>`;
|
||||
if (todayCount > 0) {
|
||||
const isOn = state.activeFilter === 'today';
|
||||
const icon = '<svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-1px;margin-right:2px"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>';
|
||||
html += `<button class="notes-label-chip notes-label-chip-today${isOn ? ' active' : ''}" data-action="today" title="Next step from every goal">${icon}Today <span class="notes-label-chip-count">${todayCount}</span></button>`;
|
||||
}
|
||||
if (goalCount > 0) {
|
||||
const isOn = state.activeFilter === 'goals';
|
||||
const icon = '<svg width="10" height="10" viewBox="0 0 24 24" fill="currentColor" style="vertical-align:-1px;margin-right:2px"><path d="M12 0L14.59 8.41L23 12L14.59 15.59L12 24L9.41 15.59L1 12L9.41 8.41Z"/></svg>';
|
||||
html += `<button class="notes-label-chip notes-label-chip-goals${isOn ? ' active' : ''}" data-action="goals" title="Show only goals">${icon}Goals <span class="notes-label-chip-count">${goalCount}</span></button>`;
|
||||
}
|
||||
const isReminderOn = state.activeFilter === 'reminders';
|
||||
const isReminderOff = state.activeFilter === 'no-reminders';
|
||||
const reminderCls = `notes-label-chip notes-label-chip-reminders${isReminderOn ? ' active' : ''}${isReminderOff ? ' active negated' : ''}`;
|
||||
const reminderIcon = isReminderOff
|
||||
// bell-off icon
|
||||
? '<svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-1px;margin-right:2px"><path d="M13.73 21a2 2 0 0 1-3.46 0"/><path d="M18.63 13A17.89 17.89 0 0 1 18 8"/><path d="M6.26 6.26A5.86 5.86 0 0 0 6 8c0 7-3 9-3 9h14"/><path d="M18 8a6 6 0 0 0-9.33-5"/><line x1="1" y1="1" x2="23" y2="23"/></svg>'
|
||||
: '<svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-1px;margin-right:2px"><path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 0 1-3.46 0"/></svg>';
|
||||
html += `<button class="${reminderCls}" data-action="reminders" title="${isReminderOn ? 'Showing only reminders — click to show all' : isReminderOff ? 'Hiding reminders — click to show only reminders' : 'Click to filter reminders'}">${reminderIcon}Reminders <span class="notes-label-chip-count">${reminderCount}</span></button>`;
|
||||
const showingReminders = state.activeFilter === 'reminders';
|
||||
if (showingReminders && pastReminderCount > 0) {
|
||||
html += `<button class="notes-label-chip notes-label-clear-past" data-action="clear-past-reminders" title="Delete reminders whose time has passed"><svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>Clear past <span class="notes-label-chip-count">${pastReminderCount}</span></button>`;
|
||||
}
|
||||
for (const lbl of sortedLabels) {
|
||||
html += `<button class="notes-label-chip${state.activeLabel === lbl ? ' active' : ''}" data-label="${_esc(lbl)}">#${_esc(lbl)}</button>`;
|
||||
}
|
||||
bar.innerHTML = html;
|
||||
bar.querySelectorAll('.notes-label-chip').forEach(chip => {
|
||||
chip.addEventListener('click', () => {
|
||||
if (chip.dataset.action === 'all') {
|
||||
app.setActiveLabel(null);
|
||||
app.setActiveFilter(null);
|
||||
} else if (chip.dataset.action === 'today') {
|
||||
app.setActiveLabel(null);
|
||||
app.setActiveFilter((state.activeFilter === 'today') ? null : 'today');
|
||||
} else if (chip.dataset.action === 'goals') {
|
||||
app.setActiveLabel(null);
|
||||
app.setActiveFilter((state.activeFilter === 'goals') ? null : 'goals');
|
||||
} else if (chip.dataset.action === 'default') {
|
||||
app.setActiveLabel(null);
|
||||
app.setActiveFilter((state.activeFilter === 'default') ? null : 'default');
|
||||
} else if (chip.dataset.action === 'reminders') {
|
||||
app.setActiveLabel(null);
|
||||
// Cycle: null → reminders → null → no-reminders → null → reminders → ...
|
||||
if (state.activeFilter === null) {
|
||||
app.setActiveFilter(state.reminderChipNext);
|
||||
app.setReminderChipNext((state.reminderChipNext === 'reminders') ? 'no-reminders' : 'reminders');
|
||||
} else {
|
||||
app.setActiveFilter(null);
|
||||
}
|
||||
} else if (chip.dataset.action === 'clear-past-reminders') {
|
||||
_clearPastReminders();
|
||||
return;
|
||||
} else {
|
||||
app.setActiveFilter(null);
|
||||
app.setActiveLabel(chip.dataset.label || null);
|
||||
}
|
||||
_renderNotes();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function _renderLabelsInto(_body) {
|
||||
if (!_body) return;
|
||||
const pane = _body.closest('.notes-pane');
|
||||
const toggleHost = pane?.querySelector('.notes-search-bar') || _body;
|
||||
let toggle = toggleHost.querySelector(':scope > .notes-label-toggle');
|
||||
if (!toggle) {
|
||||
toggle = document.createElement('button');
|
||||
toggle.type = 'button';
|
||||
toggle.className = 'notes-label-toggle cal-filter-toggle';
|
||||
toggle.addEventListener('click', () => {
|
||||
app.setLabelsCollapsed(!state.labelsCollapsed);
|
||||
try { persistence.setItem(NOTES_LABELS_COLLAPSED_KEY, state.labelsCollapsed ? '1' : '0'); } catch {}
|
||||
_renderNotes();
|
||||
});
|
||||
const selectButton = toggleHost.querySelector('#notes-select-btn');
|
||||
toggleHost.insertBefore(toggle, selectButton || null);
|
||||
}
|
||||
toggle.textContent = state.labelsCollapsed ? '+ Tags' : '− Tags';
|
||||
toggle.title = state.labelsCollapsed ? 'Show tags' : 'Hide tags';
|
||||
toggle.setAttribute('aria-expanded', state.labelsCollapsed ? 'false' : 'true');
|
||||
|
||||
// The shared chip scroller wraps this row once it is mounted.
|
||||
let bar = _body.querySelector('.notes-labels-bar');
|
||||
if (!bar) {
|
||||
bar = document.createElement('div');
|
||||
bar.className = 'notes-labels-bar';
|
||||
_body.appendChild(bar);
|
||||
}
|
||||
_renderLabels(_body);
|
||||
}
|
||||
|
||||
return { _renderLabels, _renderLabelsInto };
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
/** Card reflow animation and the owned masonry resize observer. */
|
||||
export function createLayout({ isOpen = () => true } = {}) {
|
||||
function _captureCardPositions() {
|
||||
const body = document.querySelector('#notes-pane .notes-pane-body');
|
||||
if (!body) return null;
|
||||
const positions = new Map();
|
||||
body.querySelectorAll('.note-card').forEach(card => {
|
||||
const id = card.dataset.noteId;
|
||||
if (id) positions.set(id, card.getBoundingClientRect());
|
||||
});
|
||||
return positions;
|
||||
}
|
||||
|
||||
function _animateReflow(prevPositions) {
|
||||
if (!prevPositions || !prevPositions.size) return;
|
||||
const body = document.querySelector('#notes-pane .notes-pane-body');
|
||||
if (!body || !body.isConnected) return;
|
||||
body.querySelectorAll('.note-card').forEach(card => {
|
||||
const id = card.dataset.noteId;
|
||||
const prev = prevPositions.get(id);
|
||||
if (!prev) return;
|
||||
const next = card.getBoundingClientRect();
|
||||
const dx = prev.left - next.left;
|
||||
const dy = prev.top - next.top;
|
||||
if (Math.abs(dx) < 1 && Math.abs(dy) < 1) return;
|
||||
// Invert: jump back to old position
|
||||
card.style.transition = 'none';
|
||||
card.style.transform = `translate(${dx}px, ${dy}px)`;
|
||||
// Play: animate to 0
|
||||
requestAnimationFrame(() => {
|
||||
card.style.transition = 'transform 0.25s cubic-bezier(0.34, 1.2, 0.64, 1)';
|
||||
card.style.transform = '';
|
||||
card.addEventListener('transitionend', () => {
|
||||
card.style.transition = '';
|
||||
}, { once: true });
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function _applyMasonry(body) {
|
||||
if (!body || !body.isConnected) return;
|
||||
const pane = body.closest('.notes-pane');
|
||||
const isGrid = pane?.classList.contains('notes-view-grid');
|
||||
const isMobileGrid = isGrid && window.matchMedia('(max-width: 768px)').matches;
|
||||
// Tear down any prior observer (defensive : _renderNotes wipes body.innerHTML).
|
||||
if (_masonryObserver) { try { _masonryObserver.disconnect(); } catch {} _masonryObserver = null; }
|
||||
// A save that resolves after close re-renders the leaving pane; don't
|
||||
// re-create the observer that panel teardown already disposed.
|
||||
if (!isOpen()) return;
|
||||
if (!isGrid) {
|
||||
// Clear any leftover inline spans so list view lays out normally.
|
||||
body.querySelectorAll('.note-card, .notes-label-toggle, .notes-labels-bar, .notes-quick-add, .note-form, .doclib-chip-scroll-frame:has(> .notes-labels-bar)').forEach(c => { c.style.gridRowEnd = ''; });
|
||||
return;
|
||||
}
|
||||
const ROW_PX = 4;
|
||||
const spanForHeight = (h) => Math.max(1, Math.ceil(h / ROW_PX));
|
||||
const recomputeFullRows = () => {
|
||||
const quickAdd = body.querySelector('.notes-quick-add');
|
||||
const labelsToggle = body.querySelector('.notes-label-toggle');
|
||||
const labelsBar = body.querySelector('.notes-labels-bar');
|
||||
const labelsLayout = labelsBar?.parentElement?.classList.contains('doclib-chip-scroll-frame')
|
||||
? labelsBar.parentElement
|
||||
: labelsBar;
|
||||
if (labelsToggle && getComputedStyle(labelsToggle).display !== 'none') {
|
||||
labelsToggle.style.gridRowEnd = `span ${Math.max(1, spanForHeight(labelsToggle.scrollHeight))}`;
|
||||
}
|
||||
if (labelsLayout && getComputedStyle(labelsLayout).display !== 'none') {
|
||||
const shave = isMobileGrid ? 4 : 0;
|
||||
labelsLayout.style.gridRowEnd = `span ${Math.max(1, spanForHeight(labelsLayout.scrollHeight) - shave)}`;
|
||||
}
|
||||
if (quickAdd) {
|
||||
const shave = isMobileGrid ? 4 : 0;
|
||||
quickAdd.style.gridRowEnd = `span ${Math.max(1, spanForHeight(quickAdd.scrollHeight + 10) - shave)}`;
|
||||
}
|
||||
body.querySelectorAll('.note-form').forEach(form => {
|
||||
form.style.gridColumn = '1 / -1';
|
||||
const isDrawForm = !!form.querySelector('.note-form-type-seg.is-draw');
|
||||
const minSpan = isMobileGrid ? (isDrawForm ? 104 : 64) : 1;
|
||||
const renderedHeight = form.getBoundingClientRect?.().height || 0;
|
||||
const drawReserve = isDrawForm && isMobileGrid ? 12 : 12;
|
||||
const measuredHeight = Math.max(form.scrollHeight, renderedHeight) + drawReserve;
|
||||
form.style.gridRowEnd = `span ${Math.max(minSpan, spanForHeight(measuredHeight))}`;
|
||||
});
|
||||
};
|
||||
const recompute = (card) => {
|
||||
// scrollHeight returns the natural content height : card.getBoundingClientRect()
|
||||
// would return the grid cell height (collapsed to 4px until the span is set,
|
||||
// which is the value we're trying to compute).
|
||||
const h = card.scrollHeight + (isMobileGrid ? 6 : 8);
|
||||
if (h <= 0) return;
|
||||
card.style.gridRowEnd = `span ${spanForHeight(h)}`;
|
||||
};
|
||||
recomputeFullRows();
|
||||
body.querySelectorAll('.note-card').forEach(recompute);
|
||||
// Watch masonry participants : content can grow (image load, todo edits,
|
||||
// quick-add/form expansion), and stale spans are what cause visual merging.
|
||||
if ('ResizeObserver' in window) {
|
||||
_masonryObserver = new ResizeObserver(entries => {
|
||||
let fullRowsChanged = false;
|
||||
for (const e of entries) {
|
||||
if (e.target.classList.contains('note-card')) recompute(e.target);
|
||||
else fullRowsChanged = true;
|
||||
}
|
||||
if (fullRowsChanged) recomputeFullRows();
|
||||
});
|
||||
body.querySelectorAll('.note-card').forEach(c => _masonryObserver.observe(c));
|
||||
body.querySelectorAll('.notes-label-toggle, .notes-quick-add, .note-form').forEach(c => _masonryObserver.observe(c));
|
||||
const labelsBar = body.querySelector('.notes-labels-bar');
|
||||
const labelsLayout = labelsBar?.parentElement?.classList.contains('doclib-chip-scroll-frame')
|
||||
? labelsBar.parentElement
|
||||
: labelsBar;
|
||||
if (labelsLayout) _masonryObserver.observe(labelsLayout);
|
||||
}
|
||||
}
|
||||
|
||||
let _masonryObserver = null;
|
||||
|
||||
function dispose() {
|
||||
_masonryObserver?.disconnect();
|
||||
_masonryObserver = null;
|
||||
}
|
||||
return { dispose, _captureCardPositions, _animateReflow, _applyMasonry };
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
/** Notes-owned document/window listeners. Detached editor/menu owners release their resources. */
|
||||
export function createNotesLifecycle() {
|
||||
const owners = new Map();
|
||||
let observer = null;
|
||||
function release(owner) {
|
||||
const entry = owners.get(owner);
|
||||
if (!entry) return;
|
||||
owners.delete(owner);
|
||||
for (const remove of entry.removers) remove();
|
||||
if (!owners.size) { observer?.disconnect(); observer = null; }
|
||||
}
|
||||
function onDispose(owner, remove) {
|
||||
if (!owner) throw new Error('Notes listener needs a lifecycle owner');
|
||||
let entry = owners.get(owner);
|
||||
if (!entry) {
|
||||
entry = { connected: owner.isConnected, removers: [] };
|
||||
owners.set(owner, entry);
|
||||
}
|
||||
entry.removers.push(remove);
|
||||
if (!observer) {
|
||||
observer = new MutationObserver(() => {
|
||||
for (const [node, scope] of owners) {
|
||||
if (node.isConnected) scope.connected = true;
|
||||
else if (scope.connected) release(node);
|
||||
}
|
||||
});
|
||||
observer.observe(document.body, { childList: true, subtree: true });
|
||||
}
|
||||
}
|
||||
function listen(owner, target, event, listener, options) {
|
||||
onDispose(owner, () => target.removeEventListener(event, listener, options));
|
||||
target.addEventListener(event, listener, options);
|
||||
}
|
||||
function dispose() { for (const owner of [...owners.keys()]) release(owner); }
|
||||
return { listen, onDispose, release, dispose };
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
/** Mobile fullscreen editing, link reader mode and return to the panel. */
|
||||
export function createMobileEditor({
|
||||
_applyDraftToNote,
|
||||
_buildForm,
|
||||
_fetchNotes,
|
||||
_linkify,
|
||||
_renderNotes,
|
||||
_uid,
|
||||
_wireChecklistTouchReorder,
|
||||
_wireRow,
|
||||
app,
|
||||
state,
|
||||
uiModule
|
||||
}) {
|
||||
function _isNotesMobileMode() {
|
||||
return ('ontouchstart' in window) && window.innerWidth <= 768;
|
||||
}
|
||||
|
||||
let _mobileFsOverlay = null;
|
||||
|
||||
let _mobileFsNoteId = null;
|
||||
|
||||
function _openMobileFullscreenEdit(id, fromCard) {
|
||||
const note = state.notes.find(n => n.id === id);
|
||||
if (!note) return;
|
||||
// Tear down any previous overlay (defensive).
|
||||
_closeMobileFullscreenEdit({ save: false });
|
||||
_mobileFsNoteId = id;
|
||||
app.setEditingId(id);
|
||||
|
||||
const overlay = document.createElement('div');
|
||||
overlay.className = 'note-fullscreen-overlay';
|
||||
overlay.innerHTML = `
|
||||
<div class="note-fullscreen-header">
|
||||
<button type="button" class="note-fullscreen-back" title="Back">
|
||||
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"></polyline></svg>
|
||||
</button>
|
||||
<div class="note-fullscreen-actions"></div>
|
||||
</div>
|
||||
<div class="note-fullscreen-body"></div>
|
||||
`;
|
||||
const body = overlay.querySelector('.note-fullscreen-body');
|
||||
// Reuse the same edit form the in-place flow builds. Save buttons,
|
||||
// checklist toggles, etc. all work as-is. Restore any unsaved draft.
|
||||
const { note: _n, restored } = _applyDraftToNote(note, id);
|
||||
const form = _buildForm(_n);
|
||||
body.appendChild(form);
|
||||
if (restored) uiModule.showToast('Restored unsaved changes');
|
||||
document.body.appendChild(overlay);
|
||||
_mobileFsOverlay = overlay;
|
||||
|
||||
// Animate up from the tapped tile's position so the transition reads
|
||||
// as a zoom rather than a hard cut.
|
||||
if (fromCard) {
|
||||
const r = fromCard.getBoundingClientRect();
|
||||
const vw = window.innerWidth, vh = window.innerHeight;
|
||||
overlay.style.transformOrigin =
|
||||
`${((r.left + r.width / 2) / vw) * 100}% ${((r.top + r.height / 2) / vh) * 100}%`;
|
||||
}
|
||||
overlay.classList.add('opening');
|
||||
requestAnimationFrame(() => overlay.classList.add('open'));
|
||||
|
||||
// Wire the back button : saves whatever the form has and closes.
|
||||
// mousedown preventDefault so it doesn't blur the input on first tap (which
|
||||
// would eat the tap and require a second one).
|
||||
const _backBtn = overlay.querySelector('.note-fullscreen-back');
|
||||
_backBtn.addEventListener('mousedown', (e) => e.preventDefault());
|
||||
_backBtn.addEventListener('click', () => {
|
||||
_closeMobileFullscreenEdit({ save: true });
|
||||
});
|
||||
|
||||
// The form's built-in Cancel only resets the in-place edit state; in
|
||||
// the overlay context it does nothing visible. Replace its handler so
|
||||
// Cancel actually dismisses the overlay without saving.
|
||||
const cancelBtn = form.querySelector('.note-form-cancel');
|
||||
if (cancelBtn) {
|
||||
const fresh = cancelBtn.cloneNode(true);
|
||||
cancelBtn.parentNode.replaceChild(fresh, cancelBtn);
|
||||
fresh.addEventListener('mousedown', (e) => e.preventDefault());
|
||||
fresh.addEventListener('click', (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
_closeMobileFullscreenEdit({ save: false });
|
||||
});
|
||||
}
|
||||
// The built-in Save handler does the API call + refresh, but doesn't
|
||||
// dismiss our overlay. Augment it (do NOT replace : the original is
|
||||
// async and we'd lose the API call) to schedule a close once the
|
||||
// save+render has had time to complete.
|
||||
const saveBtn = form.querySelector('.note-form-save');
|
||||
if (saveBtn) {
|
||||
saveBtn.addEventListener('click', () => {
|
||||
setTimeout(() => _closeMobileFullscreenEdit({ save: false }), 350);
|
||||
});
|
||||
}
|
||||
// Make the checklist row drag handle (⋮⋮) actually work on touch.
|
||||
// The form's default uses HTML5 native draggable which never fires
|
||||
// on iOS/Android. Wire touch-based reorder for any row inside the
|
||||
// overlay's checklist.
|
||||
_wireChecklistTouchReorder(form);
|
||||
|
||||
// For each todo row whose text contains a URL, swap the bare <input>
|
||||
// for a linkified <span> so URLs are tappable. Tapping anywhere that
|
||||
// ISN'T a link flips back to the input for editing.
|
||||
form.querySelectorAll('.note-cl-row').forEach(_addRowReadMode);
|
||||
|
||||
// Move only Delete from the form's footer actions row into the header.
|
||||
// Archive intentionally stays out of the header: the footer Update button
|
||||
// already morphs into the mobile Archive action for an untouched note.
|
||||
const headerActions = overlay.querySelector('.note-fullscreen-actions');
|
||||
const archiveBtn = form.querySelector('.note-form-archive-btn');
|
||||
const deleteBtn = form.querySelector('.note-form-delete-btn');
|
||||
if (headerActions && deleteBtn) {
|
||||
deleteBtn.classList.remove('note-form-collapsible');
|
||||
headerActions.appendChild(deleteBtn);
|
||||
}
|
||||
// The built-in archive/delete handlers re-render the notes grid but
|
||||
// leave THIS overlay sitting in front of it : looks like nothing
|
||||
// happened. Add follow-up listeners that close the overlay so the
|
||||
// user sees the action take effect.
|
||||
if (archiveBtn) {
|
||||
archiveBtn.addEventListener('click', () => {
|
||||
setTimeout(() => _closeMobileFullscreenEdit({ save: false }), 200);
|
||||
});
|
||||
}
|
||||
if (deleteBtn) {
|
||||
deleteBtn.addEventListener('click', () => {
|
||||
// Delete shows a styled confirm : give it room to resolve before
|
||||
// we try to dismiss the overlay.
|
||||
setTimeout(() => _closeMobileFullscreenEdit({ save: false }), 500);
|
||||
});
|
||||
}
|
||||
|
||||
// Tuck the tags input into the bottom actions row (Cancel / Update),
|
||||
// pinned to the LEFT. Frees the meta row of an extra wrapping line
|
||||
// and groups all the "exit" controls together.
|
||||
const actionsGroup = form.querySelector('.note-form-actions-group');
|
||||
const tagsInput = form.querySelector('.note-form-label');
|
||||
if (actionsGroup && tagsInput) {
|
||||
actionsGroup.insertBefore(tagsInput, actionsGroup.firstChild);
|
||||
}
|
||||
|
||||
// For checklist-type notes, move the photo (attach image) button into
|
||||
// the same row as the + Add button (right side) : keeps the meta row
|
||||
// tidy and puts the camera within thumb-reach of the active edit.
|
||||
const addBtn = form.querySelector('.note-cl-add');
|
||||
const photoBtn = form.querySelector('.note-form-photo-btn');
|
||||
if (addBtn && photoBtn) {
|
||||
const addRow = document.createElement('div');
|
||||
addRow.className = 'note-cl-add-row';
|
||||
addBtn.parentNode.insertBefore(addRow, addBtn);
|
||||
addRow.appendChild(addBtn);
|
||||
addRow.appendChild(photoBtn);
|
||||
// Tapping anywhere on the row (the empty gap, the dashed border,
|
||||
// the "+ Add" label) triggers add. The photo button keeps its own
|
||||
// click target so attach-image isn't ambushed.
|
||||
addRow.addEventListener('click', (e) => {
|
||||
if (e.target.closest('.note-form-photo-btn')) return;
|
||||
if (e.target === addBtn || addBtn.contains(e.target)) return;
|
||||
addBtn.click();
|
||||
});
|
||||
// The form's delegated "+ Add" handler does
|
||||
// inputs.insertBefore(newRow, addBtn)
|
||||
// : but addBtn is no longer a direct child of `.note-checklist-inputs`
|
||||
// now that we wrapped it. Bind a fresh handler that does the same
|
||||
// thing but inserts before the WRAPPING row, and stop propagation
|
||||
// so the broken delegate never runs.
|
||||
addBtn.addEventListener('click', (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
const inputs = form.querySelector('.note-checklist-inputs');
|
||||
if (!inputs) return;
|
||||
const newRow = document.createElement('div');
|
||||
newRow.className = 'note-cl-row';
|
||||
newRow.draggable = true;
|
||||
newRow.dataset.itemId = _uid();
|
||||
newRow.dataset.indent = '0';
|
||||
newRow.innerHTML = '<span class="note-cl-grip" title="Drag">⋮⋮</span><span class="note-cl-dot"></span><input type="text" class="note-cl-text" placeholder="Item..." /><button type="button" class="note-cl-rm">×</button>';
|
||||
inputs.insertBefore(newRow, addRow);
|
||||
_wireRow(newRow, inputs);
|
||||
// Touch reorder on the freshly-added row's grip.
|
||||
_wireChecklistTouchReorder(form);
|
||||
newRow.querySelector('.note-cl-text')?.focus();
|
||||
}, { capture: true });
|
||||
}
|
||||
|
||||
// Read-mode overlay for plain notes: render the content as a div with
|
||||
// clickable hyperlinks, layered above the textarea. Tapping anywhere
|
||||
// in the overlay that ISN'T a link hides the overlay and focuses the
|
||||
// textarea so the user can start editing. Tapping a link opens it.
|
||||
const ta = form.querySelector('.note-form-content');
|
||||
if (ta && (note.content || '').trim()) {
|
||||
const reader = document.createElement('div');
|
||||
reader.className = 'note-form-content-reader';
|
||||
reader.innerHTML = _linkify(note.content || '');
|
||||
ta.style.display = 'none';
|
||||
ta.insertAdjacentElement('beforebegin', reader);
|
||||
reader.addEventListener('click', (e) => {
|
||||
if (e.target.closest('a')) return; // let links open normally
|
||||
reader.remove();
|
||||
ta.style.display = '';
|
||||
// Let the browser place the cursor naturally : forcing
|
||||
// setSelectionRange right after focus() raced with the underlying
|
||||
// tap event and produced inconsistent cursor positions on mobile.
|
||||
ta.focus({ preventScroll: true });
|
||||
});
|
||||
}
|
||||
|
||||
// Opening an EXISTING note → read mode, no keyboard pop. Only a
|
||||
// brand-new note (created via the + button) should auto-focus an
|
||||
// input field. The user can tap the content to switch to edit.
|
||||
// (New-note creation flows through _createNote, not this function.)
|
||||
}
|
||||
|
||||
function _closeMobileFullscreenEdit(opts = {}) {
|
||||
if (!_mobileFsOverlay) return;
|
||||
const overlay = _mobileFsOverlay;
|
||||
overlay.querySelector('.note-form')?._flushDraft?.();
|
||||
_mobileFsOverlay = null;
|
||||
// If the form has a Save button, click it on close so edits aren't lost
|
||||
// when the user uses the back arrow instead of an explicit Save.
|
||||
if (opts.save) {
|
||||
const saveBtn = overlay.querySelector('.note-form-save, [data-action="save"]');
|
||||
if (saveBtn) try { saveBtn.click(); } catch {}
|
||||
}
|
||||
overlay.classList.remove('open');
|
||||
overlay.classList.add('closing');
|
||||
setTimeout(() => {
|
||||
if (overlay.parentNode) overlay.parentNode.removeChild(overlay);
|
||||
_mobileFsNoteId = null;
|
||||
app.setEditingId(null);
|
||||
// Refresh the grid so any save the user made is reflected.
|
||||
if (opts.save !== false) { _fetchNotes().then(_renderNotes).catch(() => {}); }
|
||||
}, 220);
|
||||
}
|
||||
|
||||
function _addRowReadMode(row) {
|
||||
const txt = row.querySelector('.note-cl-text');
|
||||
if (!txt) return;
|
||||
const val = txt.value || '';
|
||||
if (!/(https?:\/\/|www\.)/i.test(val)) return;
|
||||
if (row.querySelector('.note-cl-text-reader')) return; // already wired
|
||||
const span = document.createElement('span');
|
||||
span.className = 'note-cl-text-reader';
|
||||
span.innerHTML = _linkify(val);
|
||||
txt.style.display = 'none';
|
||||
txt.insertAdjacentElement('beforebegin', span);
|
||||
span.addEventListener('click', (e) => {
|
||||
if (e.target.closest('a')) return; // let the link open
|
||||
span.remove();
|
||||
txt.style.display = '';
|
||||
txt.focus({ preventScroll: true });
|
||||
});
|
||||
}
|
||||
|
||||
return { _isNotesMobileMode, _openMobileFullscreenEdit, _closeMobileFullscreenEdit, _addRowReadMode };
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
/** Mobile card long press, placeholder drag and reorder persistence. */
|
||||
export function createMobileReorder({
|
||||
lifecycle,
|
||||
_applyMasonry,
|
||||
_enterSelectMode,
|
||||
commitMobileOrder,
|
||||
app,
|
||||
}) {
|
||||
function _bindLongPressDrag(card) {
|
||||
let pressTimer = null;
|
||||
let startX = 0, startY = 0;
|
||||
let armed = false;
|
||||
const CANCEL_PX = 8;
|
||||
const HOLD_MS = 450;
|
||||
|
||||
card.addEventListener('touchstart', (e) => {
|
||||
// Don't fight scroll on touchpoints over real interactive children
|
||||
// (in mobile-mode they're CSS-hidden anyway, but be defensive).
|
||||
if (e.target.closest('button, input, a, .note-form')) return;
|
||||
if (e.touches.length !== 1) return;
|
||||
armed = true;
|
||||
startX = e.touches[0].clientX;
|
||||
startY = e.touches[0].clientY;
|
||||
pressTimer = setTimeout(() => {
|
||||
if (!armed) return;
|
||||
try { navigator.vibrate?.(15); } catch {}
|
||||
app.setSuppressNextNoteTapId(card.dataset.noteId);
|
||||
_enterSelectMode(card.dataset.noteId);
|
||||
}, HOLD_MS);
|
||||
}, { passive: true });
|
||||
card.addEventListener('touchmove', (e) => {
|
||||
if (!armed) return;
|
||||
const t = e.touches[0];
|
||||
if (Math.abs(t.clientX - startX) > CANCEL_PX || Math.abs(t.clientY - startY) > CANCEL_PX) {
|
||||
armed = false;
|
||||
if (pressTimer) { clearTimeout(pressTimer); pressTimer = null; }
|
||||
}
|
||||
}, { passive: true });
|
||||
const cancel = () => {
|
||||
armed = false;
|
||||
if (pressTimer) { clearTimeout(pressTimer); pressTimer = null; }
|
||||
};
|
||||
lifecycle.onDispose(card, cancel);
|
||||
card.addEventListener('touchend', cancel, { passive: true });
|
||||
card.addEventListener('touchcancel', cancel, { passive: true });
|
||||
}
|
||||
|
||||
let _dragState = null;
|
||||
|
||||
let _docDragHandlersBound = false;
|
||||
|
||||
function _enterDragMode(initialCard, initialTouch) {
|
||||
document.body.classList.add('notes-drag-mode');
|
||||
document.querySelectorAll('.note-card').forEach(_setupDragForCard);
|
||||
if (!_docDragHandlersBound) {
|
||||
lifecycle.listen(document.getElementById('notes-pane'), document, 'touchmove', _onDocTouchMove, { passive: false });
|
||||
lifecycle.listen(document.getElementById('notes-pane'), document, 'touchend', _onDocTouchEnd, { passive: true });
|
||||
lifecycle.listen(document.getElementById('notes-pane'), document, 'touchcancel', _onDocTouchEnd, { passive: true });
|
||||
_docDragHandlersBound = true;
|
||||
}
|
||||
// Auto-grab the card the user long-pressed : they're already holding
|
||||
// their finger on it, so begin the drag straight away. Releasing
|
||||
// (touchend) commits the reorder AND exits drag mode in one motion.
|
||||
if (initialCard && initialTouch) {
|
||||
_beginGrab(initialCard, initialTouch);
|
||||
}
|
||||
}
|
||||
|
||||
function _exitDragMode() {
|
||||
document.body.classList.remove('notes-drag-mode');
|
||||
if (_dragState) {
|
||||
// Defensive: if exit fires while a drag is in flight, snap the card back.
|
||||
_onDocTouchEnd();
|
||||
}
|
||||
// Leave _docDragHandlersBound true so re-entering drag mode reuses them.
|
||||
}
|
||||
|
||||
function _setupDragForCard(card) {
|
||||
if (card.dataset.dragBound === '1') return;
|
||||
card.dataset.dragBound = '1';
|
||||
card.addEventListener('touchstart', (e) => {
|
||||
if (!document.body.classList.contains('notes-drag-mode')) return;
|
||||
if (e.touches.length !== 1) return;
|
||||
if (_dragState) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
_beginGrab(card, e.touches[0]);
|
||||
}, { passive: false });
|
||||
}
|
||||
|
||||
function _beginGrab(card, touch) {
|
||||
const rect = card.getBoundingClientRect();
|
||||
const prevStyle = card.getAttribute('style') || '';
|
||||
// Placeholder fills the card's old slot so the grid layout doesn't reflow.
|
||||
const placeholder = document.createElement('div');
|
||||
placeholder.className = 'note-card-placeholder';
|
||||
placeholder.style.width = rect.width + 'px';
|
||||
placeholder.style.height = rect.height + 'px';
|
||||
placeholder.style.margin = getComputedStyle(card).margin;
|
||||
if (card.style.gridRowEnd) placeholder.style.gridRowEnd = card.style.gridRowEnd;
|
||||
const grid = card.parentNode;
|
||||
grid.insertBefore(placeholder, card);
|
||||
|
||||
// Detach the card visually : fixed-position, anchored to the finger.
|
||||
card.classList.add('note-card-dragging');
|
||||
card.style.position = 'fixed';
|
||||
card.style.left = rect.left + 'px';
|
||||
card.style.top = rect.top + 'px';
|
||||
card.style.width = rect.width + 'px';
|
||||
card.style.height = rect.height + 'px';
|
||||
card.style.margin = '0';
|
||||
card.style.zIndex = '10001';
|
||||
// pointer-events:none so elementFromPoint sees the card BENEATH the finger
|
||||
card.style.pointerEvents = 'none';
|
||||
|
||||
_dragState = {
|
||||
card, placeholder, grid, prevStyle,
|
||||
grabOffsetX: touch.clientX - rect.left,
|
||||
grabOffsetY: touch.clientY - rect.top,
|
||||
};
|
||||
try { navigator.vibrate?.(8); } catch {}
|
||||
}
|
||||
|
||||
function _onDocTouchMove(e) {
|
||||
if (!_dragState) return;
|
||||
if (e.touches.length !== 1) return;
|
||||
e.preventDefault();
|
||||
const touch = e.touches[0];
|
||||
const { card, placeholder, grid } = _dragState;
|
||||
card.style.left = (touch.clientX - _dragState.grabOffsetX) + 'px';
|
||||
const quickAdd = grid.querySelector('.notes-quick-add');
|
||||
const minTop = quickAdd ? quickAdd.getBoundingClientRect().bottom + 4 : grid.getBoundingClientRect().top;
|
||||
const maxTop = Math.max(minTop, window.innerHeight - card.getBoundingClientRect().height - 8);
|
||||
const nextTop = Math.max(minTop, Math.min(maxTop, touch.clientY - _dragState.grabOffsetY));
|
||||
card.style.top = nextTop + 'px';
|
||||
|
||||
const hitY = Math.max(minTop + 1, Math.min(window.innerHeight - 1, touch.clientY));
|
||||
const under = document.elementFromPoint(touch.clientX, hitY);
|
||||
const target = under && under.closest
|
||||
? under.closest('.note-card:not(.note-card-dragging)')
|
||||
: null;
|
||||
if (!target || target === card) return;
|
||||
if (target.parentNode !== grid) return;
|
||||
|
||||
// Move the PLACEHOLDER (not the card) above or below the target depending
|
||||
// on which half of the target the finger is in. This is the hysteresis
|
||||
// that stops the oscillation : once the placeholder moves past a card,
|
||||
// the cursor has to cross THAT card's midpoint in the other direction
|
||||
// to swap back.
|
||||
const tRect = target.getBoundingClientRect();
|
||||
const targetMidY = tRect.top + tRect.height / 2;
|
||||
if (touch.clientY < targetMidY) {
|
||||
if (placeholder.nextElementSibling !== target) {
|
||||
grid.insertBefore(placeholder, target);
|
||||
}
|
||||
} else {
|
||||
if (target.nextElementSibling !== placeholder) {
|
||||
grid.insertBefore(placeholder, target.nextElementSibling);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function _onDocTouchEnd() {
|
||||
if (!_dragState) return;
|
||||
const { card, placeholder, grid, prevStyle } = _dragState;
|
||||
_dragState = null;
|
||||
// Animate the card from its current fixed position to where the
|
||||
// placeholder sits, then re-parent and clear inline styles. Drag
|
||||
// mode auto-exits once the snap finishes : release = done.
|
||||
const phRect = placeholder.getBoundingClientRect();
|
||||
card.style.transition = 'left 0.2s ease, top 0.2s ease';
|
||||
card.style.left = phRect.left + 'px';
|
||||
card.style.top = phRect.top + 'px';
|
||||
setTimeout(() => {
|
||||
placeholder.parentNode.insertBefore(card, placeholder);
|
||||
placeholder.remove();
|
||||
card.classList.remove('note-card-dragging');
|
||||
// Restore the card's pre-drag inline styles. Mobile masonry stores
|
||||
// grid-row-end inline, and custom backgrounds use inline style too; wiping
|
||||
// cssText made dropped cards collapse into neighboring notes in grid view.
|
||||
if (prevStyle) card.setAttribute('style', prevStyle);
|
||||
else card.removeAttribute('style');
|
||||
_applyMasonry(grid);
|
||||
_commitNoteReorder();
|
||||
// One drag, one exit : release ends the rearrange session entirely.
|
||||
if (document.body.classList.contains('notes-drag-mode')) {
|
||||
document.body.classList.remove('notes-drag-mode');
|
||||
}
|
||||
}, 210);
|
||||
}
|
||||
|
||||
async function _commitNoteReorder() {
|
||||
const grid = document.querySelector('#notes-pane .notes-pane-body');
|
||||
if (!grid) return;
|
||||
const ids = Array.from(grid.querySelectorAll('.note-card')).map(c => c.dataset.noteId).filter(Boolean);
|
||||
if (!ids.length) return;
|
||||
await commitMobileOrder(ids);
|
||||
}
|
||||
|
||||
function dispose() {
|
||||
if (_dragState) {
|
||||
const { card, placeholder, prevStyle } = _dragState;
|
||||
_dragState = null;
|
||||
placeholder.parentNode?.insertBefore(card, placeholder);
|
||||
placeholder.remove();
|
||||
card.classList.remove('note-card-dragging');
|
||||
if (prevStyle) card.setAttribute('style', prevStyle);
|
||||
else card.removeAttribute('style');
|
||||
}
|
||||
document.body.classList.remove('notes-drag-mode');
|
||||
_docDragHandlersBound = false;
|
||||
}
|
||||
return { dispose, _bindLongPressDrag, _enterDragMode, _exitDragMode, _setupDragForCard, _beginGrab, _onDocTouchMove, _onDocTouchEnd, _commitNoteReorder };
|
||||
}
|
||||
@@ -0,0 +1,506 @@
|
||||
/** Panel mounting, keyboard handlers, minimization and note navigation. */
|
||||
export function createPanel({
|
||||
wireToolbar,
|
||||
wireSelectionActions,
|
||||
_wireNotesWindow,
|
||||
_restoreNotesSidebarDock,
|
||||
_bringNotesToFront,
|
||||
disposeUI,
|
||||
lifecycle,
|
||||
Modals,
|
||||
NOTES_FIRST_OPEN_HINT_KEY,
|
||||
REMINDER_DISMISSED_AT_KEY,
|
||||
_clearViewedReminderGlows,
|
||||
_closeMobileFullscreenEdit,
|
||||
_commitOpenInPlaceEditor,
|
||||
_copyNote,
|
||||
_enterSelectMode,
|
||||
_exitSelectMode,
|
||||
_fetchNotes,
|
||||
_flushPendingHighlights,
|
||||
_isNotesMobileMode,
|
||||
_popAndRunUndo,
|
||||
_renderLoadingSkeleton,
|
||||
_renderNotes,
|
||||
_startReminderLoop,
|
||||
app,
|
||||
bindTourHintDismiss,
|
||||
dismissOrRemove,
|
||||
persistence,
|
||||
state,
|
||||
workflows
|
||||
}) {
|
||||
function _forceCloseNotesPanel() {
|
||||
app.setOpen(false);
|
||||
app.setEditingId(null);
|
||||
try { _commitOpenInPlaceEditor(); } catch {}
|
||||
try { _closeMobileFullscreenEdit({ save: true }); } catch {}
|
||||
try { _clearViewedReminderGlows(); } catch {}
|
||||
if (_notesKeydownHandler) {
|
||||
document.removeEventListener('keydown', _notesKeydownHandler);
|
||||
_notesKeydownHandler = null;
|
||||
}
|
||||
if (_notesSelectEscHandler) {
|
||||
document.removeEventListener('keydown', _notesSelectEscHandler, true);
|
||||
_notesSelectEscHandler = null;
|
||||
}
|
||||
disposeOwnedPortals();
|
||||
disposeUI();
|
||||
document.body.classList.remove('notes-view', 'notes-mobile-mode', 'notes-drag-mode');
|
||||
document.getElementById('tool-notes-btn')?.classList.remove('active');
|
||||
try { Modals.unregister('notes-panel'); } catch {}
|
||||
try { document.getElementById('notes-pane')?.remove(); } catch {}
|
||||
try { document.getElementById('notes-pane-backdrop')?.remove(); } catch {}
|
||||
try { window._restoreSidebarIfRouteCollapsed?.(); } catch {}
|
||||
}
|
||||
|
||||
function _showNotesFirstOpenHint(pane) {
|
||||
if (!pane || typeof persistence === 'undefined') return;
|
||||
try {
|
||||
if (persistence.getItem(NOTES_FIRST_OPEN_HINT_KEY)) return;
|
||||
persistence.setItem(NOTES_FIRST_OPEN_HINT_KEY, '1');
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
|
||||
dismissOrRemove(document.getElementById('notes-first-open-hint'));
|
||||
const hint = document.createElement('div');
|
||||
hint.id = 'notes-first-open-hint';
|
||||
hint.className = 'tour-hint';
|
||||
hint.innerHTML = `
|
||||
<div class="tour-hint-text"><b>Notes</b> is your basic todo list, and also where reminders are managed.</div>
|
||||
<button type="button" class="tour-hint-dismiss">OK</button>
|
||||
`;
|
||||
document.body.appendChild(hint);
|
||||
|
||||
const place = () => {
|
||||
const r = pane.getBoundingClientRect();
|
||||
const hw = hint.offsetWidth || 260;
|
||||
hint.style.top = Math.max(12, r.top + 58) + 'px';
|
||||
hint.style.left = Math.min(window.innerWidth - hw - 12, Math.max(12, r.left + 18)) + 'px';
|
||||
};
|
||||
requestAnimationFrame(() => {
|
||||
place();
|
||||
hint.classList.add('tour-hint-in');
|
||||
});
|
||||
lifecycle.listen(hint, window, 'resize', place);
|
||||
bindTourHintDismiss(hint, {
|
||||
timeout: 6500,
|
||||
fade: 180,
|
||||
onDismiss: () => window.removeEventListener('resize', place),
|
||||
});
|
||||
}
|
||||
|
||||
function _ensureNotesChipRegistered() {
|
||||
if (Modals.isRegistered('notes-panel')) return;
|
||||
Modals.register('notes-panel', {
|
||||
railBtnId: 'rail-notes',
|
||||
sidebarBtnId: 'tool-notes-btn',
|
||||
restoreFn: () => { openPanel(); },
|
||||
closeFn: () => { _forceCloseNotesPanel(); },
|
||||
});
|
||||
}
|
||||
|
||||
function openPanel() {
|
||||
if (state.open) {
|
||||
_bringNotesToFront();
|
||||
return;
|
||||
}
|
||||
// Notes and the document editor occupy the same primary workspace. Preserve
|
||||
// an open document as a dock chip instead of allowing the two panes to stack
|
||||
// into a broken layout (or closing the user's document outright).
|
||||
try {
|
||||
if (window.documentModule?.isPanelOpen?.()) {
|
||||
window.documentModule.closePanel('down');
|
||||
}
|
||||
} catch (_) {}
|
||||
app.setOpen(true);
|
||||
app.setEditingId(null);
|
||||
app.setSearchQuery('');
|
||||
_clearViewedReminderGlows();
|
||||
app.setFiredDotDismissedAt(Date.now());
|
||||
try { persistence.setItem(REMINDER_DISMISSED_AT_KEY, String(state.firedDotDismissedAt)); } catch {}
|
||||
|
||||
const container = document.getElementById('chat-container');
|
||||
if (!container) return;
|
||||
|
||||
document.body.classList.add('notes-view');
|
||||
|
||||
// On mobile the notes panel takes the whole screen : auto-close the
|
||||
// sidebar so the panel isn't cropped underneath it.
|
||||
if (window.innerWidth <= 768) {
|
||||
const sb = document.getElementById('sidebar');
|
||||
if (sb) sb.classList.add('hidden');
|
||||
document.body.classList.add('sidebar-collapsed');
|
||||
}
|
||||
// Mobile mode: tiles become read-only previews (no inline checkbox /
|
||||
// edit / archive / etc.), tap opens a fullscreen edit overlay,
|
||||
// long-press enters drag-to-reorder mode. See _bindCardEvents +
|
||||
// .notes-mobile-mode CSS rules.
|
||||
if (_isNotesMobileMode()) document.body.classList.add('notes-mobile-mode');
|
||||
|
||||
// Toggle button state
|
||||
const btn = document.getElementById('tool-notes-btn');
|
||||
if (btn) btn.classList.add('active');
|
||||
|
||||
// Create panel
|
||||
const pane = document.createElement('div');
|
||||
pane.id = 'notes-pane';
|
||||
pane.className = 'notes-pane';
|
||||
pane.innerHTML = `
|
||||
<div class="notes-mobile-grabber" id="notes-mobile-grabber" aria-hidden="true"></div>
|
||||
<div class="notes-pane-header">
|
||||
<h4 class="notes-pane-title"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-2.5px;margin-right:6px"><path d="M5 3h10l4 4v14H5z"/><path d="M15 3v5h5"/><path d="M8 17.5 15.5 10l2.5 2.5L10.5 20H8z"/></svg>Notes</h4>
|
||||
<span style="flex:1"></span>
|
||||
<button id="notes-archive-toggle" class="doc-action-icon-btn notes-header-text-btn" title="View archive" style="opacity:0.8;gap:5px;">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="3" width="20" height="5" rx="1"/><path d="M4 8v11a2 2 0 002 2h12a2 2 0 002-2V8"/><path d="M10 12h4"/></svg>
|
||||
<span class="notes-header-btn-label">Archive</span>
|
||||
</button>
|
||||
<button id="notes-view-toggle" class="doc-action-icon-btn notes-header-text-btn" title="Toggle view" style="opacity:0.8;gap:5px;">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/></svg>
|
||||
<span class="notes-header-btn-label">Toggle</span>
|
||||
</button>
|
||||
<button id="notes-minimize-btn" class="modal-minimize-btn" title="Minimize" aria-label="Minimize notes" style="position:relative;left:2px;"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3.4" stroke-linecap="round" aria-hidden="true"><line x1="6" y1="18" x2="18" y2="18"/></svg></button>
|
||||
</div>
|
||||
<div class="notes-search-bar">
|
||||
<input type="text" id="notes-search" class="memory-search-input" placeholder="Search notes…" autocomplete="off" />
|
||||
<button id="notes-select-btn" class="notes-select-trigger" type="button">Select</button>
|
||||
</div>
|
||||
<div id="notes-bulk-bar" class="memory-bulk-bar hidden">
|
||||
<label class="memory-bulk-check-all"><input type="checkbox" id="notes-select-all" /> All</label>
|
||||
<span id="notes-selected-count">0 Selected</span>
|
||||
<span style="flex:1"></span>
|
||||
<button id="notes-send-agent" class="memory-toolbar-btn" disabled><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-2px;margin-right:5px;opacity:0.6"><path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"></path></svg>Send to Agent</button>
|
||||
<button id="notes-bulk-archive" class="memory-toolbar-btn" disabled>
|
||||
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-2px;margin-right:4px;"><rect x="2" y="3" width="20" height="5" rx="1"/><path d="M4 8v11a2 2 0 002 2h12a2 2 0 002-2V8"/><path d="M10 12h4"/></svg>Archive
|
||||
</button>
|
||||
<button id="notes-bulk-delete" class="memory-toolbar-btn danger" disabled>
|
||||
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-2px;margin-right:4px;"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/><line x1="10" y1="11" x2="10" y2="17"/><line x1="14" y1="11" x2="14" y2="17"/></svg>Delete
|
||||
</button>
|
||||
<button id="notes-bulk-cancel" class="memory-toolbar-btn active" title="Cancel selection" aria-label="Cancel selection">
|
||||
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
|
||||
</button>
|
||||
</div>
|
||||
<div class="notes-pane-body"></div>
|
||||
`;
|
||||
|
||||
// On mobile open as a full-screen bottom sheet (slide up), not the desktop
|
||||
// side panel. Set inline so it wins over the base .notes-pane rule regardless
|
||||
// of cascade specifics (the CSS @media override wasn't reliably applying,
|
||||
// which left it as a side panel squeezing the chat).
|
||||
if (window.innerWidth <= 768) {
|
||||
pane.style.position = 'fixed';
|
||||
pane.style.inset = '0';
|
||||
pane.style.width = '100%';
|
||||
pane.style.maxWidth = '100%';
|
||||
pane.style.zIndex = '170';
|
||||
pane.style.borderRadius = '14px 14px 0 0';
|
||||
pane.style.animation = 'sheet-enter 0.25s cubic-bezier(0.2, 0.8, 0.2, 1) both';
|
||||
pane.style.transformOrigin = 'bottom center';
|
||||
}
|
||||
|
||||
// Mount on body so Notes can behave like the other draggable windows. On
|
||||
// desktop it is immediately docked to the right by _restoreNotesSidebarDock.
|
||||
const backdrop = document.createElement('div');
|
||||
backdrop.className = 'notes-pane-backdrop';
|
||||
backdrop.id = 'notes-pane-backdrop';
|
||||
backdrop.addEventListener('click', (ev) => {
|
||||
if (ev.target === backdrop) closePanel('down');
|
||||
});
|
||||
backdrop.appendChild(pane);
|
||||
document.body.appendChild(backdrop);
|
||||
_wireNotesWindow(pane);
|
||||
_restoreNotesSidebarDock(pane);
|
||||
_bringNotesToFront(pane);
|
||||
|
||||
// Events
|
||||
// (Close chevron removed : swipe down on mobile, tool-rail toggle on desktop.)
|
||||
|
||||
// Mobile: swipe the grab handle / header down to dismiss (minimise to chip).
|
||||
// Mirrors the document sheet gesture : finger-following, velocity-based
|
||||
// dismiss, rubber-band on up-drag, spring snap-back.
|
||||
_wireNotesSwipeDismiss(pane.querySelector('.notes-mobile-grabber'), pane);
|
||||
_wireNotesSwipeDismiss(pane.querySelector('.notes-pane-header'), pane);
|
||||
|
||||
pane.addEventListener('pointerdown', () => _bringNotesToFront(pane), true);
|
||||
pane.addEventListener('focusin', () => _bringNotesToFront(pane), true);
|
||||
|
||||
const minBtn = document.getElementById('notes-minimize-btn');
|
||||
if (minBtn) minBtn.addEventListener('click', (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
closePanel('down');
|
||||
});
|
||||
wireToolbar(pane);
|
||||
// Select mode
|
||||
document.getElementById('notes-select-btn').addEventListener('click', () => {
|
||||
if (state.selectMode) _exitSelectMode(); else _enterSelectMode();
|
||||
});
|
||||
// Esc cancels select mode. Notes uses a toggle "Select" button rather
|
||||
// than a *-bulk-cancel button, so the global Esc-cancel handler in
|
||||
// keyboard-shortcuts.js can't reach it : handle it here. Capture phase
|
||||
// + stopPropagation so Esc cancels select instead of closing the panel.
|
||||
if (_notesSelectEscHandler) {
|
||||
document.removeEventListener('keydown', _notesSelectEscHandler, true);
|
||||
}
|
||||
_notesSelectEscHandler = (e) => {
|
||||
if (e.key === 'Escape' && state.selectMode) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
_exitSelectMode();
|
||||
}
|
||||
};
|
||||
document.addEventListener('keydown', _notesSelectEscHandler, true);
|
||||
wireSelectionActions();
|
||||
// Escape: exit select mode first (if active), otherwise close the panel.
|
||||
// Skip when the user is editing a form field : those have their own
|
||||
// ESC-to-cancel handlers and we don't want to nuke the whole panel
|
||||
// mid-edit.
|
||||
// Idempotent: remove any previous handler from a prior openPanel so
|
||||
// re-opening doesn't stack multiple handlers.
|
||||
if (_notesKeydownHandler) {
|
||||
document.removeEventListener('keydown', _notesKeydownHandler);
|
||||
_notesKeydownHandler = null;
|
||||
}
|
||||
_notesKeydownHandler = (e) => {
|
||||
if (!state.open) return;
|
||||
const t = e.target;
|
||||
const inField = t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable);
|
||||
// Ctrl/Cmd+Z anywhere in the panel : undo the last note action. Skip when
|
||||
// typing in a field so the browser's normal text-undo still works.
|
||||
if ((e.ctrlKey || e.metaKey) && (e.key === 'z' || e.key === 'Z') && !e.shiftKey) {
|
||||
if (inField) return;
|
||||
if (workflows.undoCount() === 0) return;
|
||||
e.preventDefault();
|
||||
_popAndRunUndo();
|
||||
return;
|
||||
}
|
||||
// Ctrl/Cmd+C while hovering a note card → copy that note. Skip when the
|
||||
// user is editing or has an active text selection (let the browser handle
|
||||
// a real text copy in that case).
|
||||
if ((e.ctrlKey || e.metaKey) && (e.key === 'c' || e.key === 'C') && !e.shiftKey && !e.altKey) {
|
||||
if (inField) return;
|
||||
const sel = window.getSelection?.();
|
||||
if (sel && sel.toString && sel.toString().length > 0) return;
|
||||
const hovered = document.querySelector('.note-card:hover');
|
||||
if (!hovered) return;
|
||||
const id = hovered.dataset.noteId;
|
||||
if (!id) return;
|
||||
e.preventDefault();
|
||||
// Flash the ⋯ menu button (copy now lives in that menu).
|
||||
const btn = hovered.querySelector('.note-card-corner-menu');
|
||||
_copyNote(id, btn);
|
||||
return;
|
||||
}
|
||||
if (e.key !== 'Escape') return;
|
||||
if (inField) return;
|
||||
if (state.selectMode) { _exitSelectMode(); return; }
|
||||
if (state.showingArchived) {
|
||||
// Mirror the archive toggle button: flip back to active notes.
|
||||
document.getElementById('notes-archive-toggle')?.click();
|
||||
return;
|
||||
}
|
||||
_forceCloseNotesPanel();
|
||||
};
|
||||
document.addEventListener('keydown', _notesKeydownHandler);
|
||||
|
||||
// Load : show skeleton immediately, then fetch
|
||||
_renderLoadingSkeleton();
|
||||
// Defer the highlight flush to the next frame so it runs *after* the cards
|
||||
// are committed to the DOM (and any FLIP animations have settled), giving
|
||||
// the querySelector lookups inside something to find.
|
||||
_fetchNotes().then(() => {
|
||||
if (!pane.isConnected || !state.open) { _startReminderLoop(); return; }
|
||||
_renderNotes();
|
||||
requestAnimationFrame(() => _flushPendingHighlights());
|
||||
_startReminderLoop();
|
||||
_showNotesFirstOpenHint(pane);
|
||||
});
|
||||
}
|
||||
|
||||
function closePanel(direction) {
|
||||
if (!state.open) return;
|
||||
app.setOpen(false);
|
||||
app.setEditingId(null);
|
||||
_clearViewedReminderGlows();
|
||||
const _minimize = direction === 'down';
|
||||
if (_minimize) {
|
||||
_ensureNotesChipRegistered();
|
||||
} else if (Modals.isRegistered('notes-panel')) {
|
||||
Modals.unregister('notes-panel');
|
||||
}
|
||||
|
||||
// Drop panel-owned keydown listeners. The reminder interval is page-owned.
|
||||
if (_notesKeydownHandler) {
|
||||
document.removeEventListener('keydown', _notesKeydownHandler);
|
||||
_notesKeydownHandler = null;
|
||||
}
|
||||
if (_notesSelectEscHandler) {
|
||||
document.removeEventListener('keydown', _notesSelectEscHandler, true);
|
||||
_notesSelectEscHandler = null;
|
||||
}
|
||||
|
||||
disposeOwnedPortals();
|
||||
disposeUI();
|
||||
document.body.classList.remove('notes-view');
|
||||
document.body.classList.remove('notes-mobile-mode');
|
||||
document.body.classList.remove('notes-drag-mode');
|
||||
// Closing the panel should PRESERVE in-progress edits, not drop them.
|
||||
// Commit any open in-place editor, and close the mobile fullscreen
|
||||
// overlay with save=true so the note is persisted.
|
||||
try { _commitOpenInPlaceEditor(); } catch {}
|
||||
_closeMobileFullscreenEdit({ save: true });
|
||||
// /notes route may have collapsed the wide sidebar to a rail; restore.
|
||||
try { window._restoreSidebarIfRouteCollapsed?.(); } catch (_) {}
|
||||
|
||||
const btn = document.getElementById('tool-notes-btn');
|
||||
if (btn) btn.classList.remove('active');
|
||||
|
||||
const pane = document.getElementById('notes-pane');
|
||||
const backdrop = document.getElementById('notes-pane-backdrop');
|
||||
if (pane) {
|
||||
// Scale-out + fade. Match the enter animation duration so close feels
|
||||
// like the same gesture played backwards.
|
||||
pane.classList.add('notes-pane-leaving');
|
||||
const _cleanup = () => {
|
||||
try { pane.remove(); } catch {}
|
||||
try { backdrop?.remove(); } catch {}
|
||||
};
|
||||
pane.addEventListener('animationend', _cleanup, { once: true });
|
||||
// Belt-and-braces: if animation is skipped (reduced motion / detached
|
||||
// tab) the listener won't fire; remove after the expected duration.
|
||||
setTimeout(_cleanup, 220);
|
||||
} else if (backdrop) {
|
||||
backdrop.remove();
|
||||
}
|
||||
// Show the dock chip for a swipe-down minimize (tap it to reopen).
|
||||
if (_minimize) { try { Modals.minimize('notes-panel'); } catch {} }
|
||||
}
|
||||
|
||||
function togglePanel() {
|
||||
if (state.open) closePanel();
|
||||
else openPanel();
|
||||
}
|
||||
|
||||
function isPanelOpen() { return state.open; }
|
||||
|
||||
async function openNote(noteId) {
|
||||
const wasOpen = !!(isPanelOpen && isPanelOpen());
|
||||
app.setShowingArchived(false);
|
||||
app.setActiveLabel(null);
|
||||
app.setActiveFilter(null);
|
||||
app.setSearchQuery('');
|
||||
if (!wasOpen) {
|
||||
openPanel();
|
||||
} else {
|
||||
_bringNotesToFront();
|
||||
const searchEl = document.getElementById('notes-search');
|
||||
if (searchEl) searchEl.value = '';
|
||||
const pane = document.getElementById('notes-pane');
|
||||
if (pane) pane.classList.remove('notes-pane-archive');
|
||||
const archiveBtn = document.getElementById('notes-archive-toggle');
|
||||
if (archiveBtn) archiveBtn.classList.remove('active');
|
||||
await _fetchNotes();
|
||||
_renderNotes();
|
||||
}
|
||||
// openPanel() kicks off _fetchNotes() asynchronously, so the cards for
|
||||
// newly-created notes may not be in the DOM yet. Poll until the card exists.
|
||||
if (!noteId) return;
|
||||
let tries = 0;
|
||||
const findAndFlash = () => {
|
||||
const card = document.querySelector(`.note-card[data-note-id="${noteId}"]`)
|
||||
|| document.querySelector(`.note-card[data-note-id^="${noteId.slice(0, 8)}"]`);
|
||||
if (card) {
|
||||
_smoothScrollToNoteCard(card);
|
||||
card.classList.add('note-card-flash');
|
||||
setTimeout(() => card.classList.remove('note-card-flash'), 1600);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
const tryNext = () => {
|
||||
if (findAndFlash()) return;
|
||||
if (++tries < 20) setTimeout(tryNext, 200);
|
||||
};
|
||||
setTimeout(tryNext, 120);
|
||||
}
|
||||
|
||||
let _notesKeydownHandler = null;
|
||||
|
||||
let _notesSelectEscHandler = null;
|
||||
|
||||
function _wireNotesSwipeDismiss(el, pane) {
|
||||
if (!el || !pane) return;
|
||||
const DISMISS_THRESHOLD = 50, VELOCITY_THRESHOLD = 0.3, RUBBER = 0.35;
|
||||
let startY = 0, startX = 0, lastY = 0, lastT = 0, velocity = 0;
|
||||
let dragging = false, cancelled = false;
|
||||
|
||||
el.addEventListener('touchstart', (e) => {
|
||||
if (window.innerWidth > 768 || e.touches.length !== 1) return;
|
||||
if (e.target.closest('button, input, select, label, textarea')) return;
|
||||
const t = e.touches[0];
|
||||
startY = t.clientY; startX = t.clientX; lastY = startY; lastT = e.timeStamp;
|
||||
velocity = 0; dragging = false; cancelled = false;
|
||||
}, { passive: true });
|
||||
|
||||
el.addEventListener('touchmove', (e) => {
|
||||
if (cancelled || window.innerWidth > 768) return;
|
||||
const t = e.touches[0];
|
||||
const dx = Math.abs(t.clientX - startX);
|
||||
const dy = t.clientY - startY;
|
||||
if (!dragging) {
|
||||
if (dx > 40 && dx > Math.abs(dy) * 2) { cancelled = true; return; }
|
||||
if (Math.abs(dy) > 8) {
|
||||
dragging = true;
|
||||
pane.style.animation = 'none';
|
||||
pane.style.transition = 'none';
|
||||
pane.style.willChange = 'transform';
|
||||
} else return;
|
||||
}
|
||||
const dt = e.timeStamp - lastT;
|
||||
if (dt > 0) velocity = velocity * 0.6 + ((t.clientY - lastY) / dt) * 0.4;
|
||||
lastY = t.clientY; lastT = e.timeStamp;
|
||||
e.preventDefault();
|
||||
pane.style.transform = dy > 0 ? `translateY(${dy}px)` : `translateY(${dy * RUBBER}px)`;
|
||||
}, { passive: false });
|
||||
|
||||
const endSwipe = () => {
|
||||
if (!dragging) return;
|
||||
dragging = false;
|
||||
pane.style.willChange = '';
|
||||
const dy = lastY - startY;
|
||||
if (dy > DISMISS_THRESHOLD || (dy > 20 && velocity > VELOCITY_THRESHOLD)) {
|
||||
// Slide fully off-screen, then minimise. Keep it translated down (don't
|
||||
// reset) so it doesn't flash back before closePanel removes it.
|
||||
pane.style.transition = 'transform 0.2s cubic-bezier(0.2, 0, 0.4, 1)';
|
||||
pane.style.transform = 'translateY(100%)';
|
||||
setTimeout(() => closePanel('down'), 200);
|
||||
} else {
|
||||
pane.style.transition = 'transform 0.25s cubic-bezier(0.2, 0.9, 0.3, 1.05)';
|
||||
pane.style.transform = '';
|
||||
setTimeout(() => { pane.style.transition = ''; }, 260);
|
||||
}
|
||||
};
|
||||
el.addEventListener('touchend', endSwipe, { passive: true });
|
||||
el.addEventListener('touchcancel', endSwipe, { passive: true });
|
||||
}
|
||||
|
||||
function _smoothScrollToNoteCard(card) {
|
||||
if (!card) return;
|
||||
const scroller = card.closest('.notes-pane-body');
|
||||
if (!scroller) {
|
||||
try { card.scrollIntoView({ block: 'center', behavior: 'smooth' }); } catch (_) {}
|
||||
return;
|
||||
}
|
||||
const scrollerRect = scroller.getBoundingClientRect();
|
||||
const cardRect = card.getBoundingClientRect();
|
||||
const delta = (cardRect.top - scrollerRect.top) - (scroller.clientHeight - cardRect.height) / 2;
|
||||
scroller.scrollTo({ top: Math.max(0, scroller.scrollTop + delta), behavior: 'smooth' });
|
||||
}
|
||||
|
||||
function disposeOwnedPortals() {
|
||||
document.querySelectorAll('.note-reminder-menu, .note-corner-menu-dropdown, #notes-first-open-hint').forEach(dismissOrRemove);
|
||||
}
|
||||
|
||||
return { _forceCloseNotesPanel, openPanel, closePanel, togglePanel, isPanelOpen, openNote, _smoothScrollToNoteCard };
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
/** Quick-add expansion, draft restoration and opening inline editors. */
|
||||
export function createQuickAdd({
|
||||
_applyDraftToNote,
|
||||
_applyMasonry,
|
||||
_buildForm,
|
||||
app,
|
||||
openPanel,
|
||||
state,
|
||||
uiModule
|
||||
}) {
|
||||
function _renderQuickAdd(body) {
|
||||
const wrap = document.createElement('div');
|
||||
wrap.className = 'notes-quick-add';
|
||||
// 2-pill Note/Todo toggle mirrors the full form's type-seg (minus Draw :
|
||||
// drawing happens in the expanded form). The pill that's active steers
|
||||
// both the placeholder and the type the form opens in.
|
||||
wrap.innerHTML = `
|
||||
<div class="notes-quick-type-seg is-todo" role="group" aria-label="New item type">
|
||||
<button type="button" class="notes-quick-type-pill" data-type="note" aria-label="Note" aria-pressed="false" title="Note">
|
||||
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><line x1="4" y1="6" x2="20" y2="6"/><line x1="4" y1="12" x2="20" y2="12"/><line x1="4" y1="18" x2="14" y2="18"/></svg>
|
||||
</button>
|
||||
<button type="button" class="notes-quick-type-pill active" data-type="todo" aria-label="To-do" aria-pressed="true" title="To-do">
|
||||
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="9 11 12 14 22 4"/><path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"/></svg>
|
||||
</button>
|
||||
</div>
|
||||
<input type="text" class="notes-quick-input" placeholder="Add a to-do…" />
|
||||
<button class="notes-quick-icon" data-action="photo" title="Attach photo">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>
|
||||
</button>
|
||||
`;
|
||||
body.appendChild(wrap);
|
||||
|
||||
const input = wrap.querySelector('.notes-quick-input');
|
||||
const seg = wrap.querySelector('.notes-quick-type-seg');
|
||||
let currentType = 'todo';
|
||||
const setType = (t) => {
|
||||
if (t !== 'note' && t !== 'todo') return;
|
||||
currentType = t;
|
||||
seg.classList.toggle('is-todo', t === 'todo');
|
||||
seg.classList.toggle('is-note', t === 'note');
|
||||
seg.querySelectorAll('.notes-quick-type-pill').forEach(p => {
|
||||
const on = p.dataset.type === t;
|
||||
p.classList.toggle('active', on);
|
||||
p.setAttribute('aria-pressed', on ? 'true' : 'false');
|
||||
});
|
||||
input.placeholder = t === 'note' ? 'Add a note…' : 'Add a to-do…';
|
||||
};
|
||||
seg.querySelectorAll('.notes-quick-type-pill').forEach(p => {
|
||||
p.addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
setType(p.dataset.type);
|
||||
});
|
||||
});
|
||||
// Click input or type → expand to full form
|
||||
const expandToForm = (initialType = 'note', initialText = '') => {
|
||||
app.setEditingId('__new__');
|
||||
const form = _buildForm({ note_type: initialType });
|
||||
form.classList.add('note-form-new');
|
||||
if (initialText) {
|
||||
const titleEl = form.querySelector('.note-form-title');
|
||||
if (titleEl) titleEl.value = initialText;
|
||||
}
|
||||
const mobileGrid = body.closest('.notes-pane')?.classList.contains('notes-view-grid')
|
||||
&& window.matchMedia('(max-width: 768px)').matches;
|
||||
if (mobileGrid) {
|
||||
form.style.gridColumn = '1 / -1';
|
||||
form.style.gridRowEnd = 'span 64';
|
||||
}
|
||||
wrap.replaceWith(form);
|
||||
_applyMasonry(body);
|
||||
requestAnimationFrame(() => _applyMasonry(body));
|
||||
const titleEl = form.querySelector('.note-form-title');
|
||||
if (titleEl) {
|
||||
titleEl.focus();
|
||||
// Move caret to end
|
||||
titleEl.setSelectionRange(titleEl.value.length, titleEl.value.length);
|
||||
}
|
||||
};
|
||||
// Expand only on real intent: a click directly on the input, or actual
|
||||
// typing. Focus alone : including focus stolen from a missed nearby
|
||||
// click : no longer creates an empty form.
|
||||
input.addEventListener('click', () => expandToForm(currentType, input.value));
|
||||
input.addEventListener('input', () => expandToForm(currentType, input.value));
|
||||
wrap.querySelector('[data-action="photo"]').addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
expandToForm(currentType);
|
||||
// Trigger photo input on the new form
|
||||
setTimeout(() => document.querySelector('.note-form-photo-btn')?.click(), 50);
|
||||
});
|
||||
}
|
||||
|
||||
function _createNote(type = 'todo') {
|
||||
const body = document.querySelector('#notes-pane .notes-pane-body');
|
||||
if (!body || state.editingId === '__new__') return;
|
||||
app.setEditingId('__new__');
|
||||
// Restore an unsaved new-note draft if one survived a prior close/loss.
|
||||
const { note: _n, restored } = _applyDraftToNote({ note_type: type }, '__new__');
|
||||
const form = _buildForm(_n);
|
||||
form.classList.add('note-form-new');
|
||||
body.prepend(form);
|
||||
const initialField = type === 'note'
|
||||
? form.querySelector('.note-form-content')
|
||||
: form.querySelector('.note-cl-text, .note-form-title');
|
||||
initialField?.focus();
|
||||
if (restored) uiModule.showToast('Restored unsaved note');
|
||||
}
|
||||
|
||||
function newNote() {
|
||||
if (!state.open) openPanel();
|
||||
requestAnimationFrame(() => _createNote('note'));
|
||||
}
|
||||
|
||||
function _editNote(id) {
|
||||
const note = state.notes.find(n => n.id === id);
|
||||
if (!note) return;
|
||||
app.setEditingId(id);
|
||||
const card = document.querySelector(`.note-card[data-note-id="${id}"]`);
|
||||
if (!card) return;
|
||||
// Restore an unsaved draft (from a prior connection loss / close) over
|
||||
// the saved note so the user picks up where they left off.
|
||||
const { note: _n, restored } = _applyDraftToNote(note, id);
|
||||
const form = _buildForm(_n);
|
||||
card.replaceWith(form);
|
||||
if (restored) uiModule.showToast('Restored unsaved changes');
|
||||
// Pinned notes live in the first masonry column : the edit form has
|
||||
// column-span:all, which can leave the form rendered above the fold or
|
||||
// visually buried under neighboring pinned cards. Bring it into view
|
||||
// (and onto a higher stacking context) so editing a pinned note always
|
||||
// pops to the top.
|
||||
form.style.position = 'relative';
|
||||
form.style.zIndex = '5';
|
||||
// Grid view: the form keeps the CSS default `grid-row-end: span 16` (64px)
|
||||
// after replaceWith, which is much shorter than the actual form. Recompute
|
||||
// masonry so the form gets the correct row span and cards below stop
|
||||
// overlapping it. ResizeObserver inside _applyMasonry keeps it in sync as
|
||||
// the user types / adds checklist items.
|
||||
const _body = form.closest('.notes-pane-body');
|
||||
if (_body) {
|
||||
_applyMasonry(_body);
|
||||
requestAnimationFrame(() => _applyMasonry(_body));
|
||||
}
|
||||
requestAnimationFrame(() => {
|
||||
try { form.scrollIntoView({ block: 'center', behavior: 'smooth' }); }
|
||||
catch { form.scrollIntoView(); }
|
||||
});
|
||||
// Pick the most useful field to focus. On phones especially, the user
|
||||
// taps Edit to type : landing in the title when there's already a title
|
||||
// (and likely a body to extend) loses momentum. Prefer the body textarea
|
||||
// for plain notes, the first checklist item for todos, fall back to title.
|
||||
const _focusBest = () => {
|
||||
if (note.note_type === 'note' || !note.note_type) {
|
||||
const ta = form.querySelector('.note-form-content');
|
||||
if (ta) { ta.focus(); try { ta.setSelectionRange(ta.value.length, ta.value.length); } catch {} return; }
|
||||
}
|
||||
if (note.note_type === 'todo' || note.note_type === 'goal' || note.note_type === 'checklist') {
|
||||
// Last non-empty checklist row, or the first row if all empty.
|
||||
const rows = form.querySelectorAll('.note-cl-row .note-cl-text');
|
||||
let target = null;
|
||||
for (const inp of rows) { if ((inp.value || '').trim()) target = inp; }
|
||||
target = target || rows[0];
|
||||
if (target) { target.focus(); try { target.setSelectionRange(target.value.length, target.value.length); } catch {} return; }
|
||||
}
|
||||
const titleEl = form.querySelector('.note-form-title');
|
||||
if (titleEl) titleEl.focus();
|
||||
};
|
||||
_focusBest();
|
||||
}
|
||||
|
||||
return { _renderQuickAdd, _createNote, newNote, _editNote };
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
/** Reminder badges, sticky card highlights and entry scrolling. */
|
||||
import { _isNoteFullyDone } from '../domain/noteRules.js';
|
||||
import { _hasTimeComponent } from '../domain/recurrence.js';
|
||||
export function createReminderDisplay({
|
||||
_countFiredReminders,
|
||||
_hasActiveReminder,
|
||||
_loadActiveHighlights,
|
||||
_loadGlowedReminders,
|
||||
_loadPendingHighlights,
|
||||
_saveActiveHighlights,
|
||||
_saveGlowedReminders,
|
||||
_savePendingHighlights,
|
||||
_smoothScrollToNoteCard,
|
||||
state
|
||||
}) {
|
||||
function _clearViewedReminderGlows() {
|
||||
const active = _loadActiveHighlights();
|
||||
if (!active.size) return;
|
||||
_saveActiveHighlights(new Set());
|
||||
document.querySelectorAll('.note-card-reminder-fired-sticky').forEach(card => {
|
||||
card.classList.remove('note-card-reminder-fired-sticky');
|
||||
});
|
||||
}
|
||||
|
||||
function _setReminderCardGlow(noteId, on = true) {
|
||||
if (!noteId) return;
|
||||
const active = _loadActiveHighlights();
|
||||
if (on) active.add(noteId);
|
||||
else active.delete(noteId);
|
||||
_saveActiveHighlights(active);
|
||||
document.querySelectorAll(`.note-card[data-note-id="${noteId}"]`).forEach(card => {
|
||||
card.classList.toggle('note-card-reminder-fired-sticky', on);
|
||||
});
|
||||
}
|
||||
|
||||
function _queuePendingHighlight(noteId) {
|
||||
const set = _loadPendingHighlights();
|
||||
set.add(noteId);
|
||||
_savePendingHighlights(set);
|
||||
}
|
||||
|
||||
function _flushPendingHighlights() {
|
||||
// Fresh firings (queued by the background loop while the panel was closed)
|
||||
// glow unconditionally : a notification just told the user something
|
||||
// happened, so we always point at the note even if it was glowed before.
|
||||
const queued = _loadPendingHighlights();
|
||||
const glowed = _loadGlowedReminders();
|
||||
const toGlow = new Set(queued);
|
||||
// For notes that are merely overdue at open time (no fresh firing event),
|
||||
// only glow the ones we haven't already shown : otherwise reopening the
|
||||
// panel keeps lighting up old reminders forever.
|
||||
for (const n of state.notes) {
|
||||
if (!_hasActiveReminder(n) || !_hasTimeComponent(n.due_date)) continue;
|
||||
if (queued.has(n.id) || !glowed.has(n.id)) toGlow.add(n.id);
|
||||
}
|
||||
// Always consume the queue.
|
||||
_savePendingHighlights(new Set());
|
||||
if (!toGlow.size) return;
|
||||
let firstCard = null;
|
||||
for (const id of toGlow) {
|
||||
const card = document.querySelector(`.note-card[data-note-id="${id}"]`);
|
||||
if (!card) continue;
|
||||
_setReminderCardGlow(id, true);
|
||||
if (!firstCard) firstCard = card;
|
||||
glowed.add(id);
|
||||
}
|
||||
_saveGlowedReminders(glowed);
|
||||
// Bring the first one into view so it can't get buried below the fold.
|
||||
if (firstCard) {
|
||||
requestAnimationFrame(() => {
|
||||
_smoothScrollToNoteCard(firstCard);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function _updateRailBadge() {
|
||||
const fired = _countFiredReminders();
|
||||
// Rail (mini sidebar) : only show the count when reminders have ACTUALLY
|
||||
// fired since the last dismissal (i.e. you haven't opened notes yet).
|
||||
// Showing every overdue note forever made the badge feel permanent.
|
||||
const railBtn = document.getElementById('rail-notes');
|
||||
if (railBtn) {
|
||||
let badge = railBtn.querySelector('.rail-notes-badge');
|
||||
if (fired > 0) {
|
||||
if (!badge) {
|
||||
badge = document.createElement('span');
|
||||
badge.className = 'rail-notes-badge';
|
||||
railBtn.appendChild(badge);
|
||||
}
|
||||
badge.textContent = fired > 99 ? '99+' : String(fired);
|
||||
badge.classList.add('fired');
|
||||
} else if (badge) {
|
||||
badge.remove();
|
||||
}
|
||||
}
|
||||
// Main sidebar button
|
||||
const sidebarBtn = document.getElementById('tool-notes-btn');
|
||||
if (sidebarBtn) {
|
||||
let dot = sidebarBtn.querySelector('.tool-notes-dot');
|
||||
if (fired > 0) {
|
||||
if (!dot) {
|
||||
dot = document.createElement('span');
|
||||
dot.className = 'tool-notes-dot';
|
||||
const newNoteBtn = sidebarBtn.querySelector('#notes-new-note-btn');
|
||||
sidebarBtn.insertBefore(dot, newNoteBtn || null);
|
||||
}
|
||||
} else if (dot) {
|
||||
dot.remove();
|
||||
}
|
||||
}
|
||||
// Individual note cards : pulse ones with fired reminders
|
||||
document.querySelectorAll('.note-card').forEach(card => {
|
||||
const id = card.dataset.noteId;
|
||||
const note = state.notes.find(n => n.id === id);
|
||||
if (!note || note.archived || _isNoteFullyDone(note)) {
|
||||
card.classList.remove('note-card-reminder-due');
|
||||
return;
|
||||
}
|
||||
if (note.due_date && _hasTimeComponent(note.due_date)) {
|
||||
const t = new Date(note.due_date).getTime();
|
||||
card.classList.toggle('note-card-reminder-due', !isNaN(t) && t <= Date.now());
|
||||
} else {
|
||||
card.classList.remove('note-card-reminder-due');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return { _clearViewedReminderGlows, _setReminderCardGlow, _queuePendingHighlight, _flushPendingHighlights, _updateRailBadge };
|
||||
}
|
||||
@@ -0,0 +1,335 @@
|
||||
/** Reminder date presets and recurrence picker interactions. */
|
||||
import { _formatRepeatLabel, _toLocalDatetimeStr, _normalizeRepeat, _DAYS, _ORDINALS } from '../domain/recurrence.js';
|
||||
export function createReminderPicker({
|
||||
lifecycle,
|
||||
_ensureNotificationPermission,
|
||||
_esc,
|
||||
_formatReminderTag,
|
||||
_laterTodayDate,
|
||||
_nextWeekDate,
|
||||
_snapToRepeat,
|
||||
_tomorrowDate,
|
||||
bindMenuDismiss,
|
||||
dismissOrRemove
|
||||
}) {
|
||||
function _wireReminderPicker(form) {
|
||||
// Reminder bell : opens dropdown menu
|
||||
const remindBtn = form.querySelector('.note-form-remind-btn');
|
||||
const dueInput = form.querySelector('.note-form-due');
|
||||
const repeatInput = form.querySelector('.note-form-repeat');
|
||||
const tagsEl = form.querySelector('.note-form-reminder-tags');
|
||||
|
||||
function _renderReminderTag() {
|
||||
if (!tagsEl) return;
|
||||
const v = dueInput.value;
|
||||
const rep = repeatInput.value || 'none';
|
||||
if (!v) { tagsEl.innerHTML = ''; return; }
|
||||
const label = _formatReminderTag(v);
|
||||
const repLabel = rep !== 'none' ? ` · ${_formatRepeatLabel(rep, new Date(v))}` : '';
|
||||
tagsEl.innerHTML = `<button class="note-reminder-tag" type="button" title="Edit reminder">
|
||||
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 0 1-3.46 0"/></svg>
|
||||
<span>${_esc(label)}${_esc(repLabel)}</span>
|
||||
<span class="note-reminder-tag-x" title="Remove">×</span>
|
||||
</button>`;
|
||||
tagsEl.querySelector('.note-reminder-tag').addEventListener('click', (e) => {
|
||||
if (e.target.classList.contains('note-reminder-tag-x')) {
|
||||
dueInput.value = '';
|
||||
repeatInput.value = 'none';
|
||||
_renderReminderTag();
|
||||
return;
|
||||
}
|
||||
_openReminderMenu(remindBtn || tagsEl, true);
|
||||
});
|
||||
}
|
||||
|
||||
function _openReminderMenu(anchor, isEdit = false) {
|
||||
// Close any existing menu
|
||||
document.querySelectorAll('.note-reminder-menu').forEach(m => m.remove());
|
||||
const menu = document.createElement('div');
|
||||
menu.className = 'note-reminder-menu';
|
||||
document.body.appendChild(menu);
|
||||
|
||||
const presetItems = [
|
||||
{ label: 'Later today', sub: _laterTodayDate().toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' }), action: () => _setReminder(_toLocalDatetimeStr(_laterTodayDate())) },
|
||||
{ label: 'Tomorrow', sub: _tomorrowDate().toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' }), action: () => _setReminder(_toLocalDatetimeStr(_tomorrowDate())) },
|
||||
{ label: 'Next week', sub: _nextWeekDate().toLocaleDateString([], { weekday: 'short' }) + ' ' + _nextWeekDate().toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' }), action: () => _setReminder(_toLocalDatetimeStr(_nextWeekDate())) },
|
||||
{ label: 'Select date and time', sub: '', action: () => _pickCustomDate() },
|
||||
];
|
||||
|
||||
// Sub-page state for the repeat picker. null = top page.
|
||||
// 'weekly' | 'monthly' | 'monthly_nth'
|
||||
let subMode = null;
|
||||
// Temporary state for monthly_nth so user can click N then weekday (or vice versa)
|
||||
// before committing.
|
||||
let nthDraft = { n: 0, w: -1 };
|
||||
|
||||
const DAY_SHORT = ['S', 'M', 'T', 'W', 'T', 'F', 'S'];
|
||||
|
||||
function getNorm() {
|
||||
if (!dueInput.value) return 'none';
|
||||
return _normalizeRepeat(repeatInput.value || 'none', new Date(dueInput.value));
|
||||
}
|
||||
|
||||
function commit(val) {
|
||||
repeatInput.value = val;
|
||||
_renderReminderTag();
|
||||
menu.remove();
|
||||
}
|
||||
|
||||
// Like commit, but first snaps dueInput.value forward to the next matching
|
||||
// slot for the chosen recurrence. Use for weekly/monthly variants where the
|
||||
// current due date may not match the chosen pattern (e.g. user picks
|
||||
// "weekly on Mondays" while the date is a Wednesday).
|
||||
function snapAndCommit(val) {
|
||||
if (dueInput.value) {
|
||||
const cur = new Date(dueInput.value);
|
||||
const norm = _normalizeRepeat(val, cur);
|
||||
const snapped = _snapToRepeat(cur, norm);
|
||||
if (snapped) {
|
||||
dueInput.value = _toLocalDatetimeStr(snapped);
|
||||
if (remindBtn) remindBtn.classList.add('has-date');
|
||||
}
|
||||
}
|
||||
commit(val);
|
||||
}
|
||||
|
||||
function reposition() {
|
||||
const rect = anchor.getBoundingClientRect();
|
||||
const vw = window.innerWidth;
|
||||
const vh = window.innerHeight;
|
||||
const mw = menu.offsetWidth || 220;
|
||||
const mh = menu.offsetHeight || 280;
|
||||
let top = rect.bottom + 4;
|
||||
let left = rect.left;
|
||||
if (top + mh > vh - 8) top = Math.max(8, rect.top - mh - 4);
|
||||
if (left + mw > vw - 8) left = Math.max(8, vw - mw - 8);
|
||||
if (left < 8) left = 8;
|
||||
menu.style.top = top + 'px';
|
||||
menu.style.left = left + 'px';
|
||||
}
|
||||
|
||||
function render() {
|
||||
let html = '';
|
||||
|
||||
if (subMode === null) {
|
||||
html += '<div class="note-reminder-menu-title">Remind me later</div>';
|
||||
for (let i = 0; i < presetItems.length; i++) {
|
||||
const it = presetItems[i];
|
||||
html += `<button class="note-reminder-menu-item" data-action="preset" data-i="${i}"><span>${it.label}</span><span class="note-reminder-menu-sub">${it.sub}</span></button>`;
|
||||
}
|
||||
if (isEdit && dueInput.value) {
|
||||
const norm = getNorm();
|
||||
html += '<div class="note-reminder-menu-divider"></div>';
|
||||
html += '<div class="note-reminder-menu-title">Repeat</div>';
|
||||
// None
|
||||
html += `<button class="note-reminder-menu-item${norm === 'none' ? ' active' : ''}" data-action="set" data-val="none"><span>Doesn't repeat</span>${norm === 'none' ? '<span class="note-reminder-menu-check">✓</span>' : ''}</button>`;
|
||||
// Daily
|
||||
html += `<button class="note-reminder-menu-item${norm === 'daily' ? ' active' : ''}" data-action="set" data-val="daily"><span>Daily</span>${norm === 'daily' ? '<span class="note-reminder-menu-check">✓</span>' : ''}</button>`;
|
||||
// Weekly →
|
||||
{
|
||||
const isW = norm.startsWith('weekly:');
|
||||
const wd = isW ? parseInt(norm.split(':')[1], 10) : null;
|
||||
const sub = isW && !isNaN(wd) ? `<span class="note-reminder-menu-sub">${_DAYS[wd]}</span>` : '';
|
||||
html += `<button class="note-reminder-menu-item${isW ? ' active' : ''}" data-action="sub" data-sub="weekly"><span>Weekly</span>${sub}<span class="note-reminder-menu-arrow">›</span></button>`;
|
||||
}
|
||||
// Monthly →
|
||||
{
|
||||
const isM = norm.startsWith('monthly:');
|
||||
const sub = isM ? `<span class="note-reminder-menu-sub">${_monthlyShortDescriptor(norm)}</span>` : '';
|
||||
html += `<button class="note-reminder-menu-item${isM ? ' active' : ''}" data-action="sub" data-sub="monthly"><span>Monthly</span>${sub}<span class="note-reminder-menu-arrow">›</span></button>`;
|
||||
}
|
||||
// Yearly
|
||||
html += `<button class="note-reminder-menu-item${norm === 'yearly' ? ' active' : ''}" data-action="set" data-val="yearly"><span>Yearly</span>${norm === 'yearly' ? '<span class="note-reminder-menu-check">✓</span>' : ''}</button>`;
|
||||
}
|
||||
} else if (subMode === 'weekly') {
|
||||
const norm = getNorm();
|
||||
const curWd = norm.startsWith('weekly:') ? parseInt(norm.split(':')[1], 10) : -1;
|
||||
html += `<button class="note-reminder-menu-back" data-action="back"><span class="note-reminder-menu-arrow-back">‹</span> Repeat</button>`;
|
||||
html += '<div class="note-reminder-menu-title">Weekly on…</div>';
|
||||
html += '<div class="note-reminder-weekday-row">';
|
||||
for (let i = 0; i < 7; i++) {
|
||||
html += `<button class="note-reminder-day-chip${curWd === i ? ' active' : ''}" data-action="weekly-pick" data-wd="${i}" title="${_DAYS[i]}">${DAY_SHORT[i]}</button>`;
|
||||
}
|
||||
html += '</div>';
|
||||
} else if (subMode === 'monthly') {
|
||||
const norm = getNorm();
|
||||
const dueDate = new Date(dueInput.value);
|
||||
const dayN = dueDate.getDate();
|
||||
html += `<button class="note-reminder-menu-back" data-action="back"><span class="note-reminder-menu-arrow-back">‹</span> Repeat</button>`;
|
||||
html += '<div class="note-reminder-menu-title">Monthly on…</div>';
|
||||
// Day N : uses the chosen date's day. Always offered.
|
||||
const dayVal = `monthly:day:${dayN}`;
|
||||
html += `<button class="note-reminder-menu-item${norm === dayVal ? ' active' : ''}" data-action="set" data-val="${dayVal}"><span>Day ${dayN} every month</span>${norm === dayVal ? '<span class="note-reminder-menu-check">✓</span>' : ''}</button>`;
|
||||
// Nth weekday →
|
||||
{
|
||||
const isNth = norm.startsWith('monthly:nth:');
|
||||
const sub = isNth ? `<span class="note-reminder-menu-sub">${_monthlyShortDescriptor(norm)}</span>` : '';
|
||||
html += `<button class="note-reminder-menu-item${isNth ? ' active' : ''}" data-action="sub" data-sub="monthly_nth"><span>Nth weekday</span>${sub}<span class="note-reminder-menu-arrow">›</span></button>`;
|
||||
}
|
||||
} else if (subMode === 'monthly_nth') {
|
||||
// Pick ordinal (1..4) and weekday (0..6); commit when both chosen.
|
||||
html += `<button class="note-reminder-menu-back" data-action="back-monthly"><span class="note-reminder-menu-arrow-back">‹</span> Monthly</button>`;
|
||||
html += '<div class="note-reminder-menu-title">Nth weekday of month</div>';
|
||||
html += '<div class="note-reminder-menu-sublabel">Which one</div>';
|
||||
html += '<div class="note-reminder-weekday-row">';
|
||||
for (let i = 1; i <= 4; i++) {
|
||||
html += `<button class="note-reminder-day-chip wide${nthDraft.n === i ? ' active' : ''}" data-action="nth-n" data-n="${i}">${_ORDINALS[i - 1]}</button>`;
|
||||
}
|
||||
html += '</div>';
|
||||
html += '<div class="note-reminder-menu-sublabel">Weekday</div>';
|
||||
html += '<div class="note-reminder-weekday-row">';
|
||||
for (let i = 0; i < 7; i++) {
|
||||
html += `<button class="note-reminder-day-chip${nthDraft.w === i ? ' active' : ''}" data-action="nth-w" data-wd="${i}" title="${_DAYS[i]}">${DAY_SHORT[i]}</button>`;
|
||||
}
|
||||
html += '</div>';
|
||||
html += '<div class="note-reminder-menu-divider"></div>';
|
||||
const ready = nthDraft.n > 0 && nthDraft.w >= 0;
|
||||
const lbl = ready ? `Save: ${_ORDINALS[nthDraft.n - 1]} ${_DAYS[nthDraft.w]}` : 'Pick week and weekday';
|
||||
html += `<button class="note-reminder-menu-item note-reminder-menu-confirm${ready ? '' : ' disabled'}" data-action="nth-save" ${ready ? '' : 'disabled'}><span>${lbl}</span></button>`;
|
||||
}
|
||||
|
||||
menu.innerHTML = html;
|
||||
reposition();
|
||||
wire();
|
||||
}
|
||||
|
||||
function wire() {
|
||||
menu.querySelectorAll('[data-action]').forEach(el => {
|
||||
el.addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
const a = el.dataset.action;
|
||||
if (a === 'preset') {
|
||||
const it = presetItems[parseInt(el.dataset.i, 10)];
|
||||
it.action();
|
||||
menu.remove();
|
||||
} else if (a === 'set') {
|
||||
snapAndCommit(el.dataset.val);
|
||||
} else if (a === 'sub') {
|
||||
subMode = el.dataset.sub;
|
||||
// Seed nth draft from saved value only on first entry : preserve
|
||||
// in-progress picks across back-trips (Nth → back → Nth again).
|
||||
if (subMode === 'monthly_nth' && nthDraft.n === 0 && nthDraft.w === -1) {
|
||||
const norm = getNorm();
|
||||
const m = norm.match(/^monthly:nth:(\d):(\d)$/);
|
||||
if (m) nthDraft = { n: parseInt(m[1], 10), w: parseInt(m[2], 10) };
|
||||
}
|
||||
render();
|
||||
} else if (a === 'back') {
|
||||
subMode = null;
|
||||
render();
|
||||
} else if (a === 'back-monthly') {
|
||||
subMode = 'monthly';
|
||||
render();
|
||||
} else if (a === 'weekly-pick') {
|
||||
snapAndCommit(`weekly:${el.dataset.wd}`);
|
||||
} else if (a === 'nth-n') {
|
||||
nthDraft.n = parseInt(el.dataset.n, 10);
|
||||
render();
|
||||
} else if (a === 'nth-w') {
|
||||
nthDraft.w = parseInt(el.dataset.wd, 10);
|
||||
render();
|
||||
} else if (a === 'nth-save') {
|
||||
if (nthDraft.n > 0 && nthDraft.w >= 0) {
|
||||
snapAndCommit(`monthly:nth:${nthDraft.n}:${nthDraft.w}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
render();
|
||||
// Click outside to close (single global handler attached after first paint)
|
||||
setTimeout(() => {
|
||||
const close = (e) => {
|
||||
if (!menu.isConnected) { document.removeEventListener('click', close); return; }
|
||||
if (!menu.contains(e.target)) { menu.remove(); document.removeEventListener('click', close); }
|
||||
};
|
||||
if (menu.isConnected) lifecycle.listen(menu, document, 'click', close);
|
||||
}, 0);
|
||||
}
|
||||
|
||||
function _monthlyShortDescriptor(norm) {
|
||||
const parts = norm.split(':');
|
||||
if (parts[1] === 'day') return `Day ${parts[2]}`;
|
||||
if (parts[1] === 'nth') {
|
||||
const n = parseInt(parts[2], 10);
|
||||
const wd = parseInt(parts[3], 10);
|
||||
return `${_ORDINALS[n - 1] || `${n}th`} ${_DAYS[wd].slice(0, 3)}`;
|
||||
}
|
||||
if (parts[1] === 'last') {
|
||||
const wd = parseInt(parts[2], 10);
|
||||
return `Last ${_DAYS[wd].slice(0, 3)}`;
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
function _setReminder(datetimeLocalStr) {
|
||||
dueInput.value = datetimeLocalStr;
|
||||
if (remindBtn) {
|
||||
remindBtn.classList.add('has-date');
|
||||
// Jingle the bell. CSS handles the animation; remove + reflow + re-add
|
||||
// so it replays every time the user sets/changes a reminder.
|
||||
const _bell = remindBtn.querySelector('svg');
|
||||
if (_bell) {
|
||||
_bell.classList.remove('jingling');
|
||||
void _bell.offsetWidth;
|
||||
_bell.classList.add('jingling');
|
||||
setTimeout(() => _bell.classList.remove('jingling'), 700);
|
||||
}
|
||||
}
|
||||
_renderReminderTag();
|
||||
_ensureNotificationPermission();
|
||||
}
|
||||
|
||||
function _pickCustomDate() {
|
||||
// Replace the dropdown menu with a small inline picker
|
||||
document.querySelectorAll('.note-reminder-menu').forEach(dismissOrRemove);
|
||||
const menu = document.createElement('div');
|
||||
menu.className = 'note-reminder-menu';
|
||||
const initial = dueInput.value || _toLocalDatetimeStr(_tomorrowDate());
|
||||
menu.innerHTML = `
|
||||
<div class="note-reminder-menu-title">Pick date and time</div>
|
||||
<div class="note-reminder-menu-picker">
|
||||
<input type="datetime-local" class="note-reminder-date-input" />
|
||||
</div>
|
||||
<div class="note-reminder-menu-divider"></div>
|
||||
<button class="note-reminder-menu-item note-reminder-menu-confirm">
|
||||
<span>Save</span>
|
||||
</button>
|
||||
`;
|
||||
document.body.appendChild(menu);
|
||||
// Position next to the bell button
|
||||
const anchor = remindBtn || form.querySelector('.note-form-reminder-tags');
|
||||
const rect = anchor.getBoundingClientRect();
|
||||
const vw = window.innerWidth;
|
||||
const vh = window.innerHeight;
|
||||
const mw = menu.offsetWidth || 240;
|
||||
const mh = menu.offsetHeight || 200;
|
||||
let top = rect.bottom + 4;
|
||||
let left = rect.left;
|
||||
if (top + mh > vh - 8) top = Math.max(8, rect.top - mh - 4);
|
||||
if (left + mw > vw - 8) left = Math.max(8, vw - mw - 8);
|
||||
if (left < 8) left = 8;
|
||||
menu.style.top = top + 'px';
|
||||
menu.style.left = left + 'px';
|
||||
const dInput = menu.querySelector('.note-reminder-date-input');
|
||||
dInput.value = initial;
|
||||
dInput.focus();
|
||||
if (typeof dInput.showPicker === 'function') {
|
||||
try { dInput.showPicker(); } catch {}
|
||||
}
|
||||
const close = bindMenuDismiss(menu, () => { menu.remove(); });
|
||||
menu.querySelector('.note-reminder-menu-confirm').addEventListener('click', () => {
|
||||
if (dInput.value) _setReminder(dInput.value);
|
||||
close();
|
||||
});
|
||||
}
|
||||
|
||||
if (remindBtn) remindBtn.addEventListener('click', (e) => { e.stopPropagation(); _openReminderMenu(remindBtn, !!dueInput.value); });
|
||||
_renderReminderTag();
|
||||
|
||||
|
||||
}
|
||||
|
||||
return { _wireReminderPicker };
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
/** Selection controls and view feedback for accepted attachments. */
|
||||
export function createSelection({
|
||||
operations,
|
||||
_renderNotes,
|
||||
app,
|
||||
state
|
||||
}) {
|
||||
function _enterSelectMode(initialId = null) {
|
||||
app.setSelectMode(true);
|
||||
app.clearSelection();
|
||||
if (initialId) app.selectId(initialId);
|
||||
const bar = document.getElementById('notes-bulk-bar');
|
||||
const btn = document.getElementById('notes-select-btn');
|
||||
if (bar) bar.classList.remove('hidden');
|
||||
if (btn) { btn.classList.add('active'); btn.textContent = 'Cancel'; }
|
||||
_renderNotes();
|
||||
_updateBulkBar();
|
||||
}
|
||||
|
||||
function _exitSelectMode() {
|
||||
app.setSelectMode(false);
|
||||
app.clearSelection();
|
||||
const bar = document.getElementById('notes-bulk-bar');
|
||||
const btn = document.getElementById('notes-select-btn');
|
||||
const all = document.getElementById('notes-select-all');
|
||||
if (bar) bar.classList.add('hidden');
|
||||
if (btn) { btn.classList.remove('active'); btn.textContent = 'Select'; }
|
||||
if (all) all.checked = false;
|
||||
_renderNotes();
|
||||
}
|
||||
|
||||
function _updateBulkBar() {
|
||||
const count = state.selectedIds.size;
|
||||
const countEl = document.getElementById('notes-selected-count');
|
||||
const sendAgentBtn = document.getElementById('notes-send-agent');
|
||||
const archiveBtn = document.getElementById('notes-bulk-archive');
|
||||
const deleteBtn = document.getElementById('notes-bulk-delete');
|
||||
const allEl = document.getElementById('notes-select-all');
|
||||
if (countEl) countEl.textContent = `${count} Selected`;
|
||||
if (sendAgentBtn) sendAgentBtn.disabled = count === 0;
|
||||
if (archiveBtn) archiveBtn.disabled = count === 0;
|
||||
if (deleteBtn) deleteBtn.disabled = count === 0;
|
||||
if (allEl) allEl.checked = state.notes.length > 0 && state.notes.every(n => state.selectedIds.has(n.id));
|
||||
// Toggle select-mode class so todo dots don't react to hover
|
||||
const pane = document.getElementById('notes-pane');
|
||||
if (pane) pane.classList.toggle('notes-select-mode', count > 0);
|
||||
}
|
||||
|
||||
function wireSelectionActions() {
|
||||
document.getElementById('notes-select-all').addEventListener('change', e => {
|
||||
if (e.target.checked) state.notes.forEach(n => app.selectId(n.id));
|
||||
else app.clearSelection();
|
||||
_renderNotes(); _updateBulkBar();
|
||||
});
|
||||
document.getElementById('notes-send-agent').addEventListener('click', operations.attachSelected);
|
||||
document.getElementById('notes-bulk-archive').addEventListener('click', operations.archiveSelected);
|
||||
document.getElementById('notes-bulk-delete').addEventListener('click', operations.deleteSelected);
|
||||
document.getElementById('notes-bulk-cancel').addEventListener('click', _exitSelectMode);
|
||||
}
|
||||
return { wireSelectionActions, _enterSelectMode, _exitSelectMode, _updateBulkBar };
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/** Escaping, safe image sources and link rendering. */
|
||||
export function createText({
|
||||
uiModule
|
||||
}) {
|
||||
function _esc(s) { return uiModule.esc ? uiModule.esc(s || '') : (s || '').replace(/</g, '<').replace(/>/g, '>'); }
|
||||
|
||||
function _attrEsc(s) {
|
||||
return String(s || '')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/`/g, '`');
|
||||
}
|
||||
|
||||
function _safeImgSrc(s) {
|
||||
const v = (s || '').trim();
|
||||
if (!v) return '';
|
||||
if (v.startsWith('/') || v.startsWith('./') || v.startsWith('../')) return v;
|
||||
if (/^https?:\/\//i.test(v) || /^data:image\/(?:png|jpe?g|gif|webp);base64,/i.test(v)) return v;
|
||||
return '';
|
||||
}
|
||||
|
||||
function _linkify(s) {
|
||||
const escaped = _esc(s);
|
||||
const urlRe = /\b((?:https?:\/\/|www\.)[^\s<>"']+[^\s<>"'.,;:!?\]])/g;
|
||||
return escaped.replace(urlRe, (m) => {
|
||||
let url = m;
|
||||
// Trim a trailing ')' that doesn't have a matching '(' inside the URL
|
||||
if (url.endsWith(')') && (url.match(/\(/g) || []).length < (url.match(/\)/g) || []).length) {
|
||||
url = url.slice(0, -1);
|
||||
}
|
||||
const href = url.startsWith('www.') ? `https://${url}` : url;
|
||||
return `<a href="${_attrEsc(href)}" class="note-link" target="_blank" rel="noopener noreferrer" onclick="event.stopPropagation()">${url}</a>` + (url !== m ? m.slice(url.length) : '');
|
||||
});
|
||||
}
|
||||
|
||||
return { _esc, _attrEsc, _safeImgSrc, _linkify };
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
/** Panel search, archive and list/grid controls. */
|
||||
export function createToolbar({
|
||||
app,
|
||||
state,
|
||||
persistence,
|
||||
_renderNotes,
|
||||
_fetchNotes,
|
||||
_applyMasonry
|
||||
}) {
|
||||
function wireToolbar(pane) {
|
||||
// Search
|
||||
const searchEl = document.getElementById('notes-search');
|
||||
if (searchEl) {
|
||||
searchEl.addEventListener('input', () => {
|
||||
app.setSearchQuery(searchEl.value.trim().toLowerCase());
|
||||
_renderNotes();
|
||||
});
|
||||
}
|
||||
|
||||
// View toggle
|
||||
const archiveBtn = document.getElementById('notes-archive-toggle');
|
||||
if (archiveBtn) {
|
||||
const ARCHIVE_ICON = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="3" width="20" height="5" rx="1"/><path d="M4 8v11a2 2 0 002 2h12a2 2 0 002-2V8"/><path d="M10 12h4"/></svg><span class="notes-header-btn-label">Archive</span>';
|
||||
const CLOSE_ICON = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><line x1="6" y1="6" x2="18" y2="18"/><line x1="18" y1="6" x2="6" y2="18"/></svg><span class="notes-header-btn-label">Archive</span>';
|
||||
const syncArchiveBtn = () => {
|
||||
archiveBtn.classList.toggle('active', state.showingArchived);
|
||||
archiveBtn.title = state.showingArchived ? 'Exit archive' : 'View archive';
|
||||
archiveBtn.style.opacity = state.showingArchived ? '1' : '0.8';
|
||||
// Swap to an X while in archive view so it doubles as a close-back-
|
||||
// to-active-notes toggle.
|
||||
archiveBtn.innerHTML = state.showingArchived ? CLOSE_ICON : ARCHIVE_ICON;
|
||||
// Tint the whole pane so it's obvious you're not in the active list.
|
||||
pane.classList.toggle('notes-pane-archive', state.showingArchived);
|
||||
};
|
||||
syncArchiveBtn();
|
||||
archiveBtn.addEventListener('click', async () => {
|
||||
app.setShowingArchived(!state.showingArchived);
|
||||
app.clearSelection();
|
||||
syncArchiveBtn();
|
||||
// Brief fade so the body content swap doesn't snap : the bg-tint
|
||||
// change is already eased by CSS transitions on .notes-pane*.
|
||||
const _bodyEl = document.querySelector('#notes-pane .notes-pane-body');
|
||||
if (_bodyEl) {
|
||||
_bodyEl.style.transition = 'opacity 0.18s ease';
|
||||
_bodyEl.style.opacity = '0.25';
|
||||
}
|
||||
await _fetchNotes();
|
||||
_renderNotes();
|
||||
if (_bodyEl) {
|
||||
requestAnimationFrame(() => {
|
||||
_bodyEl.style.opacity = '';
|
||||
_bodyEl.addEventListener('transitionend', () => { _bodyEl.style.transition = ''; }, { once: true });
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
const viewBtn = document.getElementById('notes-view-toggle');
|
||||
if (viewBtn) {
|
||||
pane.classList.toggle('notes-view-grid', state.viewMode === 'grid');
|
||||
// Label shows what you'll switch TO : "Grid" while in list, "List" while in grid.
|
||||
const _setViewLabel = () => {
|
||||
const lbl = viewBtn.querySelector('.notes-header-btn-label');
|
||||
if (lbl) lbl.textContent = state.viewMode === 'grid' ? 'List' : 'Grid';
|
||||
};
|
||||
_setViewLabel();
|
||||
requestAnimationFrame(() => _applyMasonry(document.querySelector('#notes-pane .notes-pane-body')));
|
||||
viewBtn.addEventListener('click', () => {
|
||||
app.setViewMode(state.viewMode === 'grid' ? 'list' : 'grid');
|
||||
try { persistence.setItem('odysseus-notes-view', state.viewMode); } catch {}
|
||||
pane.classList.toggle('notes-view-grid', state.viewMode === 'grid');
|
||||
_setViewLabel();
|
||||
requestAnimationFrame(() => _applyMasonry(document.querySelector('#notes-pane .notes-pane-body')));
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
return { wireToolbar };
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
/** Shared-window integration: safe fullscreen bounds, docking and stacking. */
|
||||
export function createWindowLayout({
|
||||
makeWindowDraggable,
|
||||
snapModalToZone,
|
||||
clearDockSide,
|
||||
applyEdgeDock,
|
||||
topToolWindowZ
|
||||
}) {
|
||||
function _notesFullscreenSafeRect() {
|
||||
const vw = window.innerWidth || document.documentElement.clientWidth || 0;
|
||||
const vh = window.innerHeight || document.documentElement.clientHeight || 0;
|
||||
let left = 0;
|
||||
let right = vw;
|
||||
|
||||
const sidebar = document.getElementById('sidebar');
|
||||
const rail = document.getElementById('icon-rail');
|
||||
const hamburgerRight = document.body.classList.contains('hamburger-right')
|
||||
|| sidebar?.classList.contains('right-side')
|
||||
|| rail?.classList.contains('right-side');
|
||||
|
||||
const reserve = (el) => {
|
||||
if (!el || getComputedStyle(el).display === 'none') return;
|
||||
const rect = el.getBoundingClientRect();
|
||||
if (rect.width <= 0 || rect.height <= 0) return;
|
||||
if (hamburgerRight) right = Math.min(right, rect.left);
|
||||
else left = Math.max(left, rect.right);
|
||||
};
|
||||
|
||||
if (sidebar && !sidebar.classList.contains('hidden')) reserve(sidebar);
|
||||
reserve(rail);
|
||||
|
||||
// The fixed hamburger can remain visible even when the rail/sidebar is
|
||||
// collapsed. Reserve its strip too so fullscreen Notes does not sit beneath it.
|
||||
const hamburger = document.getElementById('hamburger-btn');
|
||||
if (hamburger && getComputedStyle(hamburger).display !== 'none') {
|
||||
const rect = hamburger.getBoundingClientRect();
|
||||
const pad = 8;
|
||||
if (hamburgerRight) right = Math.min(right, rect.left - pad);
|
||||
else left = Math.max(left, rect.right + pad);
|
||||
}
|
||||
|
||||
left = Math.max(0, Math.min(left, vw - 80));
|
||||
right = Math.max(left + 80, Math.min(right, vw));
|
||||
return { left, top: 0, width: right - left, height: vh };
|
||||
}
|
||||
|
||||
function _wireNotesWindow(pane) {
|
||||
if (!pane || pane.dataset.windowDragWired === '1') return;
|
||||
const header = pane.querySelector('.notes-pane-header');
|
||||
if (!header) return;
|
||||
pane.dataset.windowDragWired = '1';
|
||||
makeWindowDraggable(pane, {
|
||||
content: pane,
|
||||
header,
|
||||
fsClass: 'notes-window-fullscreen',
|
||||
skipSelector: 'button, input, select, textarea, label, .notes-mobile-grabber',
|
||||
enableDock: true,
|
||||
enableLeftDock: true,
|
||||
onEnterFullscreen: () => {
|
||||
pane.classList.add('notes-window-fullscreen');
|
||||
snapModalToZone(pane, {
|
||||
name: 'fullscreen',
|
||||
rect: _notesFullscreenSafeRect(),
|
||||
});
|
||||
},
|
||||
onExitFullscreen: () => {
|
||||
_restoreNotesSidebarDock(pane);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function _clearNotesSnapStyles(pane) {
|
||||
if (!pane) return;
|
||||
const hadLeft = pane.classList.contains('modal-left-docked');
|
||||
const hadRight = pane.classList.contains('modal-right-docked');
|
||||
pane.classList.remove('notes-window-fullscreen', 'modal-left-docked', 'modal-right-docked');
|
||||
if (hadLeft) clearDockSide('left', pane);
|
||||
if (hadRight) clearDockSide('right', pane);
|
||||
['position', 'left', 'top', 'right', 'bottom', 'width', 'max-width', 'height',
|
||||
'max-height', 'margin', 'transform', 'border-radius']
|
||||
.forEach((prop) => pane.style.removeProperty(prop));
|
||||
delete pane.dataset._tilePreSnap;
|
||||
delete pane.dataset._tileZone;
|
||||
delete pane._preDockSnapshot;
|
||||
delete pane._dockSide;
|
||||
delete pane._dockSuspended;
|
||||
}
|
||||
|
||||
function _restoreNotesSidebarDock(pane) {
|
||||
if (!pane || window.innerWidth <= 768) return;
|
||||
_clearNotesSnapStyles(pane);
|
||||
if (!pane.isConnected) return;
|
||||
applyEdgeDock(pane, 'right');
|
||||
}
|
||||
|
||||
function _topToolWindowZ(exclude = null) {
|
||||
return topToolWindowZ({ exclude });
|
||||
}
|
||||
|
||||
function _bringNotesToFront(pane = document.getElementById('notes-pane')) {
|
||||
if (!pane) return;
|
||||
const backdrop = document.getElementById('notes-pane-backdrop') || pane.parentElement;
|
||||
const z = _topToolWindowZ(backdrop) + 1;
|
||||
if (backdrop) backdrop.style.setProperty('z-index', String(z), 'important');
|
||||
try {
|
||||
window.dispatchEvent(new CustomEvent('odysseus:modal-opened', {
|
||||
detail: { id: 'notes-panel', modal: pane },
|
||||
}));
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
|
||||
return { _wireNotesWindow, _restoreNotesSidebarDock, _bringNotesToFront };
|
||||
}
|
||||
+4
-5469
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,28 @@
|
||||
/** Stateless celebration renderer shared by Notes and Compare. */
|
||||
export function spawnConfetti(cx, cy, count) {
|
||||
const colors = ['#ffd700', '#ff6b6b', '#5b8def', '#51cf66', '#ff922b', '#cc5de8', '#22b8cf', '#fff'];
|
||||
for (let i = 0; i < count; i++) {
|
||||
const el = document.createElement('div');
|
||||
el.className = 'confetti-piece';
|
||||
const color = colors[Math.floor(Math.random() * colors.length)];
|
||||
const size = 5 + Math.random() * 8;
|
||||
const isCircle = Math.random() > 0.5;
|
||||
el.style.width = size + 'px';
|
||||
el.style.height = (isCircle ? size : size * 0.6) + 'px';
|
||||
el.style.background = color;
|
||||
el.style.borderRadius = isCircle ? '50%' : '2px';
|
||||
el.style.left = cx + 'px';
|
||||
el.style.top = cy + 'px';
|
||||
const angle = Math.random() * Math.PI * 2;
|
||||
const speed = 60 + Math.random() * 160;
|
||||
const dx = Math.cos(angle) * speed;
|
||||
const dy = Math.sin(angle) * speed - 100;
|
||||
const duration = 1.0 + Math.random() * 1.0;
|
||||
el.animate([
|
||||
{ transform: 'translate(0, 0) rotate(0deg) scale(1)', opacity: 1 },
|
||||
{ transform: `translate(${dx}px, ${dy + 200}px) rotate(${400 + Math.random() * 400}deg) scale(0)`, opacity: 0 }
|
||||
], { duration: duration * 1000, easing: 'cubic-bezier(0.15, 0.6, 0.35, 1)', fill: 'forwards' });
|
||||
document.body.appendChild(el);
|
||||
setTimeout(() => el.remove(), duration * 1000 + 50);
|
||||
}
|
||||
}
|
||||
+52
-1
@@ -7,7 +7,7 @@
|
||||
// - Other static assets (images/fonts/libs): cache-first with bg refresh.
|
||||
// - API / non-GET: never cached.
|
||||
// Bump CACHE_NAME whenever the precache list or SW logic changes.
|
||||
const CACHE_NAME = 'odysseus-v658-publication-assets-restore';
|
||||
const CACHE_NAME = 'odysseus-v659-notes-reference';
|
||||
|
||||
// KaTeX resolves these from its own stylesheet, so caching the CSS without them
|
||||
// gives offline math fallback glyphs instead of proper typesetting.
|
||||
@@ -115,6 +115,57 @@ const PRECACHE = [
|
||||
// emailInbox.js has always imported this one; it was never precached.
|
||||
'/static/js/emailLibrary/replyRecipients.js',
|
||||
'/static/js/notes.js?v=20260911notesselectioncancel1',
|
||||
'/static/js/features/notes/domain/recurrence.js',
|
||||
// Exact legacy URLs still reached by the Notes graph.
|
||||
'/static/js/toolWindowZOrder.js',
|
||||
'/static/js/color/hex.js',
|
||||
'/static/js/windowDrag.js',
|
||||
'/static/js/modalSnap.js',
|
||||
'/static/js/windowResize.js',
|
||||
'/static/js/modalManager.js',
|
||||
'/static/js/escMenuStack.js',
|
||||
'/static/js/tourHintDismiss.js',
|
||||
'/static/js/shared/ui/confetti.js',
|
||||
'/static/js/features/notes/application/selection.js',
|
||||
'/static/js/features/notes/ui/toolbar.js',
|
||||
'/static/js/features/notes/ui/windowLayout.js',
|
||||
'/static/js/features/notes/application/cardOperations.js',
|
||||
'/static/js/features/notes/application/checklistOperations.js',
|
||||
'/static/js/features/notes/application/submission.js',
|
||||
'/static/js/features/notes/application/drafts.js',
|
||||
'/static/js/features/notes/ui/lifecycle.js',
|
||||
'/static/js/features/notes/ui/text.js',
|
||||
'/static/js/features/notes/ui/colors.js',
|
||||
'/static/js/features/notes/ui/panel.js',
|
||||
'/static/js/features/notes/ui/reminderDisplay.js',
|
||||
'/static/js/features/notes/ui/selection.js',
|
||||
'/static/js/features/notes/ui/filters.js',
|
||||
'/static/js/features/notes/ui/cardRendering.js',
|
||||
'/static/js/features/notes/ui/layout.js',
|
||||
'/static/js/features/notes/ui/quickAdd.js',
|
||||
'/static/js/features/notes/ui/cardInteractions.js',
|
||||
'/static/js/features/notes/ui/cardChecklist.js',
|
||||
'/static/js/features/notes/ui/cardReorder.js',
|
||||
'/static/js/features/notes/ui/draftEditor.js',
|
||||
'/static/js/features/notes/ui/editor.js',
|
||||
'/static/js/features/notes/ui/reminderPicker.js',
|
||||
'/static/js/features/notes/ui/checklist.js',
|
||||
'/static/js/features/notes/ui/drawing.js',
|
||||
'/static/js/features/notes/ui/clipboard.js',
|
||||
'/static/js/features/notes/ui/mobileEditor.js',
|
||||
'/static/js/features/notes/ui/mobileReorder.js',
|
||||
'/static/js/features/notes/ui/checklistReorder.js',
|
||||
'/static/js/features/notes/application/queries.js',
|
||||
'/static/js/features/notes/application/agentActions.js',
|
||||
'/static/js/features/notes/application/deletion.js',
|
||||
'/static/js/features/notes/domain/noteRules.js',
|
||||
'/static/js/features/notes/index.js',
|
||||
'/static/js/features/notes/application/reminders.js',
|
||||
'/static/js/features/notes/infrastructure/notifications.js',
|
||||
'/static/js/features/notes/application/state.js',
|
||||
'/static/js/features/notes/application/workflows.js',
|
||||
'/static/js/features/notes/infrastructure/http.js',
|
||||
'/static/js/features/notes/infrastructure/storage.js',
|
||||
'/static/js/tasks.js?v=20260914taskmodel1',
|
||||
'/static/js/calendar.js?v=20260914emailsource11',
|
||||
'/static/js/calendar/utils.js',
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user