From 5a73d7d3e56f853a965207ac709e8f5e84918959 Mon Sep 17 00:00:00 2001 From: johnnyjoygh Date: Sun, 28 Jun 2026 22:59:14 +0800 Subject: [PATCH] refactor: rebuild the editor on CodeMirror as decorated source MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Rebuild the memo editor as a single CodeMirror 6 "decorated source" editor. The document is the raw markdown, stored verbatim and styled in place (markers stay visible), so the editor never serializes a tree back to markdown — removing the round-trip fidelity bug class (inline images, setext headings, ordered-list indentation, HTML entities) that the old editor needed per-case patches for. - MemoEditor/Editor: CodeMirror 6 + lang-markdown (GFM). Tokens, heading lines, #tag/@mention, and the autocomplete popover are styled in plain CSS (Editor/editor.css) with theme tokens, not a CSS-in-JS theme. - Tab/Shift-Tab nest/outdent list items (marker-aware, ordered items renumbered so nesting is CommonMark-valid); Escape blurs; #tag autocomplete sourced from useTagCounts. - Focus-mode toolbar reimplemented as markdown-text ops; active state read from the Lezer tree via the backend-agnostic formatting/commands catalog. - Remove the old serialize-back-to-markdown editor (its Editor dir, PlainEditor, the editor-mode system) and its now-unused dependencies (marked, textarea-caret, and the rich-text editor packages). - Consolidate toolbar components under Toolbar/. Read-only MemoContent rendering is unchanged. --- web/package.json | 20 +- web/pnpm-lock.yaml | 739 +++++------------- .../components/MemoContent/markdown/List.tsx | 10 +- .../components/MemoEditor/Editor/Mention.ts | 124 --- .../MemoEditor/Editor/PreservedBlock.ts | 217 ----- web/src/components/MemoEditor/Editor/Tag.ts | 122 --- .../MemoEditor/Editor/TagSuggestion.ts | 42 - .../MemoEditor/Editor/controller.ts | 37 + .../components/MemoEditor/Editor/editor.css | 133 ++++ .../MemoEditor/Editor/extensions.ts | 108 +-- .../MemoEditor/Editor/formatting.ts | 138 ++++ .../MemoEditor/Editor/headingDecorations.ts | 27 + .../components/MemoEditor/Editor/index.tsx | 294 ++----- .../MemoEditor/Editor/listIndent.ts | 119 +++ .../MemoEditor/Editor/markdownCodec.ts | 70 -- .../MemoEditor/Editor/suggestionExtension.ts | 56 -- .../MemoEditor/Editor/suggestionMenu.tsx | 194 ----- .../MemoEditor/Editor/tagAutocomplete.ts | 25 + .../MemoEditor/Editor/tagMarkdown.ts | 113 --- .../Editor/tagMentionDecorations.ts | 34 + web/src/components/MemoEditor/Editor/theme.ts | 23 + .../MemoEditor/Editor/viewportDecorations.ts | 23 + .../MemoEditor/PlainEditor/index.tsx | 198 ----- web/src/components/MemoEditor/README.md | 89 +-- .../{components => Toolbar}/EditorToolbar.tsx | 4 +- .../FormattingToolbar.tsx | 12 +- .../MemoEditor/Toolbar/InsertMenu.tsx | 16 - .../components/MemoEditor/Toolbar/index.ts | 2 + .../components/AudioRecorderPanel.tsx | 2 +- .../MemoEditor/components/EditorContent.tsx | 87 +-- .../components/MemoEditor/components/index.ts | 2 - web/src/components/MemoEditor/editorMode.ts | 20 - .../commands.ts} | 55 +- .../MemoEditor/hooks/useEditorActiveState.ts | 2 +- .../MemoEditor/hooks/useLocation.ts | 2 +- .../MemoEditor/hooks/useMemoInit.ts | 17 +- web/src/components/MemoEditor/index.tsx | 25 +- .../components/MemoEditor/state/actions.ts | 6 - .../components/MemoEditor/state/reducer.ts | 9 - web/src/components/MemoEditor/state/types.ts | 16 +- .../MemoEditor/types/editorController.ts | 21 +- web/src/components/MemoEditor/types/index.ts | 3 +- .../types/{insert-menu.ts => insertMenu.ts} | 0 .../MemoMetadata/Location/LocationDialog.tsx | 2 +- web/src/index.css | 57 -- web/src/lib/markdownStyles.ts | 35 +- web/src/utils/mention-grammar.ts | 4 +- web/src/utils/tag-grammar.ts | 5 +- web/tests/editor-commands.test.ts | 65 -- web/tests/editor-controller.test.ts | 32 + web/tests/editor-controller.test.tsx | 249 ------ web/tests/editor-decorations.test.ts | 16 + web/tests/editor-formatting.test.ts | 56 ++ web/tests/editor-heading-decorations.test.ts | 19 + web/tests/editor-keys.test.ts | 86 ++ web/tests/editor-load-guard.test.tsx | 63 -- web/tests/editor-mention.test.ts | 96 --- web/tests/editor-mode-toggle.test.tsx | 126 --- web/tests/editor-mode.test.ts | 34 - web/tests/editor-preserved.test.ts | 85 -- web/tests/editor-tag-autocomplete.test.ts | 25 + web/tests/editor-tag.test.ts | 151 ---- web/tests/editor.test.tsx | 34 + .../markdown-corpus/preserved/block-html.md | 7 - .../markdown-corpus/preserved/inline-html.md | 1 - .../markdown-corpus/preserved/math-block.md | 7 - .../markdown-corpus/preserved/math-inline.md | 1 - .../markdown-corpus/preserved/table.md | 4 - .../markdown-corpus/supported/basic.md | 7 - .../supported/blockquote-mixed.md | 7 - .../markdown-corpus/supported/cjk-emoji.md | 9 - .../markdown-corpus/supported/code-blocks.md | 16 - .../markdown-corpus/supported/headings.md | 13 - .../markdown-corpus/supported/lists.md | 11 - .../markdown-corpus/supported/task-lists.md | 8 - web/tests/formatting-controller.test.tsx | 95 --- web/tests/formatting-toolbar.test.tsx | 4 +- web/tests/insert-menu-mode-toggle.test.tsx | 71 -- web/tests/markdown-roundtrip.test.ts | 51 -- web/tests/memo-editor-paste.test.tsx | 35 - web/tests/plain-editor-controller.test.tsx | 57 -- web/tests/setup.ts | 4 + web/tests/suggestion-extension.test.ts | 77 -- web/tests/suggestion-menu.test.tsx | 176 ----- 84 files changed, 1277 insertions(+), 3880 deletions(-) delete mode 100644 web/src/components/MemoEditor/Editor/Mention.ts delete mode 100644 web/src/components/MemoEditor/Editor/PreservedBlock.ts delete mode 100644 web/src/components/MemoEditor/Editor/Tag.ts delete mode 100644 web/src/components/MemoEditor/Editor/TagSuggestion.ts create mode 100644 web/src/components/MemoEditor/Editor/controller.ts create mode 100644 web/src/components/MemoEditor/Editor/editor.css create mode 100644 web/src/components/MemoEditor/Editor/formatting.ts create mode 100644 web/src/components/MemoEditor/Editor/headingDecorations.ts create mode 100644 web/src/components/MemoEditor/Editor/listIndent.ts delete mode 100644 web/src/components/MemoEditor/Editor/markdownCodec.ts delete mode 100644 web/src/components/MemoEditor/Editor/suggestionExtension.ts delete mode 100644 web/src/components/MemoEditor/Editor/suggestionMenu.tsx create mode 100644 web/src/components/MemoEditor/Editor/tagAutocomplete.ts delete mode 100644 web/src/components/MemoEditor/Editor/tagMarkdown.ts create mode 100644 web/src/components/MemoEditor/Editor/tagMentionDecorations.ts create mode 100644 web/src/components/MemoEditor/Editor/theme.ts create mode 100644 web/src/components/MemoEditor/Editor/viewportDecorations.ts delete mode 100644 web/src/components/MemoEditor/PlainEditor/index.tsx rename web/src/components/MemoEditor/{components => Toolbar}/EditorToolbar.tsx (95%) rename web/src/components/MemoEditor/{components => Toolbar}/FormattingToolbar.tsx (95%) delete mode 100644 web/src/components/MemoEditor/editorMode.ts rename web/src/components/MemoEditor/{Editor/editorCommands.ts => formatting/commands.ts} (61%) rename web/src/components/MemoEditor/types/{insert-menu.ts => insertMenu.ts} (100%) delete mode 100644 web/tests/editor-commands.test.ts create mode 100644 web/tests/editor-controller.test.ts delete mode 100644 web/tests/editor-controller.test.tsx create mode 100644 web/tests/editor-decorations.test.ts create mode 100644 web/tests/editor-formatting.test.ts create mode 100644 web/tests/editor-heading-decorations.test.ts create mode 100644 web/tests/editor-keys.test.ts delete mode 100644 web/tests/editor-load-guard.test.tsx delete mode 100644 web/tests/editor-mention.test.ts delete mode 100644 web/tests/editor-mode-toggle.test.tsx delete mode 100644 web/tests/editor-mode.test.ts delete mode 100644 web/tests/editor-preserved.test.ts create mode 100644 web/tests/editor-tag-autocomplete.test.ts delete mode 100644 web/tests/editor-tag.test.ts create mode 100644 web/tests/editor.test.tsx delete mode 100644 web/tests/fixtures/markdown-corpus/preserved/block-html.md delete mode 100644 web/tests/fixtures/markdown-corpus/preserved/inline-html.md delete mode 100644 web/tests/fixtures/markdown-corpus/preserved/math-block.md delete mode 100644 web/tests/fixtures/markdown-corpus/preserved/math-inline.md delete mode 100644 web/tests/fixtures/markdown-corpus/preserved/table.md delete mode 100644 web/tests/fixtures/markdown-corpus/supported/basic.md delete mode 100644 web/tests/fixtures/markdown-corpus/supported/blockquote-mixed.md delete mode 100644 web/tests/fixtures/markdown-corpus/supported/cjk-emoji.md delete mode 100644 web/tests/fixtures/markdown-corpus/supported/code-blocks.md delete mode 100644 web/tests/fixtures/markdown-corpus/supported/headings.md delete mode 100644 web/tests/fixtures/markdown-corpus/supported/lists.md delete mode 100644 web/tests/fixtures/markdown-corpus/supported/task-lists.md delete mode 100644 web/tests/formatting-controller.test.tsx delete mode 100644 web/tests/insert-menu-mode-toggle.test.tsx delete mode 100644 web/tests/markdown-roundtrip.test.ts delete mode 100644 web/tests/memo-editor-paste.test.tsx delete mode 100644 web/tests/plain-editor-controller.test.tsx delete mode 100644 web/tests/suggestion-extension.test.ts delete mode 100644 web/tests/suggestion-menu.test.tsx diff --git a/web/package.json b/web/package.json index 3f93372a..ca1f91ea 100644 --- a/web/package.json +++ b/web/package.json @@ -17,9 +17,17 @@ "test:coverage": "vitest run --coverage" }, "dependencies": { + "@codemirror/autocomplete": "^6.20.3", + "@codemirror/commands": "^6.10.4", + "@codemirror/lang-markdown": "^6.5.0", + "@codemirror/language": "^6.12.4", + "@codemirror/state": "^6.7.0", + "@codemirror/view": "^6.43.3", "@connectrpc/connect": "^2.1.1", "@connectrpc/connect-web": "^2.1.1", "@github/relative-time-element": "^5.0.0", + "@lezer/highlight": "^1.2.3", + "@lezer/markdown": "^1.6.4", "@radix-ui/react-checkbox": "^1.3.3", "@radix-ui/react-dialog": "^1.1.15", "@radix-ui/react-dropdown-menu": "^2.1.16", @@ -34,15 +42,6 @@ "@tailwindcss/vite": "^4.2.4", "@tanstack/react-query": "^5.100.9", "@tanstack/react-query-devtools": "^5.100.9", - "@tiptap/core": "3.26.0", - "@tiptap/extension-heading": "3.26.0", - "@tiptap/extension-list": "3.26.0", - "@tiptap/extensions": "3.26.0", - "@tiptap/markdown": "3.26.0", - "@tiptap/pm": "3.26.0", - "@tiptap/react": "3.26.0", - "@tiptap/starter-kit": "3.26.0", - "@tiptap/suggestion": "3.26.0", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "copy-to-clipboard": "^4.0.2", @@ -56,7 +55,6 @@ "leaflet.markercluster": "^1.5.3", "lodash-es": "^4.18.1", "lucide-react": "^1.14.0", - "marked": "^17.0.6", "mdast-util-from-markdown": "^2.0.3", "mdast-util-gfm": "^3.1.0", "mermaid": "^11.14.0", @@ -78,7 +76,6 @@ "remark-math": "^6.0.0", "tailwind-merge": "^3.5.0", "tailwindcss": "^4.2.4", - "textarea-caret": "^3.1.0", "unist-util-visit": "^5.1.0", "uuid": "^14.0.0" }, @@ -102,7 +99,6 @@ "@types/qs": "^6.15.1", "@types/react": "^19.2.14", "@types/react-dom": "^19.2.3", - "@types/textarea-caret": "^3.0.4", "@types/unist": "^3.0.3", "@vitejs/plugin-react": "^6.0.1", "babel-plugin-react-compiler": "1.0.0", diff --git a/web/pnpm-lock.yaml b/web/pnpm-lock.yaml index 9dff6740..52adf0da 100644 --- a/web/pnpm-lock.yaml +++ b/web/pnpm-lock.yaml @@ -8,6 +8,24 @@ importers: .: dependencies: + '@codemirror/autocomplete': + specifier: ^6.20.3 + version: 6.20.3 + '@codemirror/commands': + specifier: ^6.10.4 + version: 6.10.4 + '@codemirror/lang-markdown': + specifier: ^6.5.0 + version: 6.5.0 + '@codemirror/language': + specifier: ^6.12.4 + version: 6.12.4 + '@codemirror/state': + specifier: ^6.7.0 + version: 6.7.0 + '@codemirror/view': + specifier: ^6.43.3 + version: 6.43.3 '@connectrpc/connect': specifier: ^2.1.1 version: 2.1.1(@bufbuild/protobuf@2.12.0) @@ -17,6 +35,12 @@ importers: '@github/relative-time-element': specifier: ^5.0.0 version: 5.0.0 + '@lezer/highlight': + specifier: ^1.2.3 + version: 1.2.3 + '@lezer/markdown': + specifier: ^1.6.4 + version: 1.6.4 '@radix-ui/react-checkbox': specifier: ^1.3.3 version: 1.3.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.6(react@19.2.6))(react@19.2.6) @@ -59,33 +83,6 @@ importers: '@tanstack/react-query-devtools': specifier: ^5.100.9 version: 5.100.9(@tanstack/react-query@5.100.9(react@19.2.6))(react@19.2.6) - '@tiptap/core': - specifier: 3.26.0 - version: 3.26.0(@tiptap/pm@3.26.0) - '@tiptap/extension-heading': - specifier: 3.26.0 - version: 3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0)) - '@tiptap/extension-list': - specifier: 3.26.0 - version: 3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0) - '@tiptap/extensions': - specifier: 3.26.0 - version: 3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0) - '@tiptap/markdown': - specifier: 3.26.0 - version: 3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0) - '@tiptap/pm': - specifier: 3.26.0 - version: 3.26.0 - '@tiptap/react': - specifier: 3.26.0 - version: 3.26.0(@floating-ui/dom@1.7.6)(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0)(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.6(react@19.2.6))(react@19.2.6) - '@tiptap/starter-kit': - specifier: 3.26.0 - version: 3.26.0 - '@tiptap/suggestion': - specifier: 3.26.0 - version: 3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0) class-variance-authority: specifier: ^0.7.1 version: 0.7.1 @@ -125,9 +122,6 @@ importers: lucide-react: specifier: ^1.14.0 version: 1.14.0(react@19.2.6) - marked: - specifier: ^17.0.6 - version: 17.0.6 mdast-util-from-markdown: specifier: ^2.0.3 version: 2.0.3 @@ -191,9 +185,6 @@ importers: tailwindcss: specifier: ^4.2.4 version: 4.2.4 - textarea-caret: - specifier: ^3.1.0 - version: 3.1.0 unist-util-visit: specifier: ^5.1.0 version: 5.1.0 @@ -258,9 +249,6 @@ importers: '@types/react-dom': specifier: ^19.2.3 version: 19.2.3(@types/react@19.2.14) - '@types/textarea-caret': - specifier: ^3.0.4 - version: 3.0.4 '@types/unist': specifier: ^3.0.3 version: 3.0.3 @@ -486,6 +474,36 @@ packages: '@chevrotain/utils@12.0.0': resolution: {integrity: sha512-lB59uJoaGIfOOL9knQqQRfhl9g7x8/wqFkp13zTdkRu1huG9kg6IJs1O8hqj9rs6h7orGxHJUKb+mX3rPbWGhA==} + '@codemirror/autocomplete@6.20.3': + resolution: {integrity: sha512-tlosUqb+3BbxCxZdu4tKeRghPFC+QM7q4X5YhKV2eCmPG+1r2F3f4AaSz5sCrFqUtX4Jh20VFTKecl16MgiV9g==} + + '@codemirror/commands@6.10.4': + resolution: {integrity: sha512-Ryk9y9T0FFVF0cUGhAknveAyUOl/A1qReTFi+qPKtOh2Z9F4AUBz3XOrYD4ZEgZirdugVzHvd/2/Wcwy5OliTg==} + + '@codemirror/lang-css@6.3.1': + resolution: {integrity: sha512-kr5fwBGiGtmz6l0LSJIbno9QrifNMUusivHbnA1H6Dmqy4HZFte3UAICix1VuKo0lMPKQr2rqB+0BkKi/S3Ejg==} + + '@codemirror/lang-html@6.4.11': + resolution: {integrity: sha512-9NsXp7Nwp891pQchI7gPdTwBuSuT3K65NGTHWHNJ55HjYcHLllr0rbIZNdOzas9ztc1EUVBlHou85FFZS4BNnw==} + + '@codemirror/lang-javascript@6.2.5': + resolution: {integrity: sha512-zD4e5mS+50htS7F+TYjBPsiIFGanfVqg4HyUz6WNFikgOPf2BgKlx+TQedI1w6n/IqRBVBbBWmGFdLB/7uxO4A==} + + '@codemirror/lang-markdown@6.5.0': + resolution: {integrity: sha512-0K40bZ35jpHya6FriukbgaleaqzBLZfOh7HuzqbMxBXkbYMJDxfF39c23xOgxFezR+3G+tR2/Mup+Xk865OMvw==} + + '@codemirror/language@6.12.4': + resolution: {integrity: sha512-1q4PaT+o6PbgpkJt4Q8Fv5XJxTy4FUZ4MWETtyiDw3J0Pyr9E2vqcKL+k9wcvjNTIsauxvE7OfmWj3FRPHQ76A==} + + '@codemirror/lint@6.9.7': + resolution: {integrity: sha512-28/+iWLYxKxsvGYhSYL7zaCZqLz5+FFFDq9tVsvGv9kv8RY4fFAchJ5WX9M3YrrRlTIsECjsXPqeNgnSmNP2dg==} + + '@codemirror/state@6.7.0': + resolution: {integrity: sha512-Zbl9NyscLMZkfXPQnNAIIAFftidrA1UbcJEIMp24C0Bukc2I5T8wJS0wsXYsnDOqCFJUeJ1BITGNs5CqPDSmSg==} + + '@codemirror/view@6.43.3': + resolution: {integrity: sha512-MwEwCAr/o0agJefhC2+reBv5kfOQpMcDRUNQrRYZgWlhH8IwQcerMZrpqWyUFSyO0ebgN2cnh/w87F7G4BGSng==} + '@connectrpc/connect-web@2.1.1': resolution: {integrity: sha512-J8317Q2MaFRCT1jzVR1o06bZhDIBmU0UAzWx6xOIXzOq8+k71/+k7MUF7AwcBUX+34WIvbm5syRgC5HXQA8fOg==} peerDependencies: @@ -594,6 +612,30 @@ packages: '@jridgewell/trace-mapping@0.3.31': resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} + '@lezer/common@1.5.2': + resolution: {integrity: sha512-sxQE460fPZyU3sdc8lafxiPwJHBzZRy/udNFynGQky1SePYBdhkBl1kOagA9uT3pxR8K09bOrmTUqA9wb/PjSQ==} + + '@lezer/css@1.3.3': + resolution: {integrity: sha512-RzBo8r+/6QJeow7aPHIpGVIH59xTcJXp399820gZoMo9noQDRVpJLheIBUicYwKcsbOYoBRoLZlf2720dG/4Tg==} + + '@lezer/highlight@1.2.3': + resolution: {integrity: sha512-qXdH7UqTvGfdVBINrgKhDsVTJTxactNNxLk7+UMwZhU13lMHaOBlJe9Vqp907ya56Y3+ed2tlqzys7jDkTmW0g==} + + '@lezer/html@1.3.13': + resolution: {integrity: sha512-oI7n6NJml729m7pjm9lvLvmXbdoMoi2f+1pwSDJkl9d68zGr7a9Btz8NdHTGQZtW2DA25ybeuv/SyDb9D5tseg==} + + '@lezer/javascript@1.5.4': + resolution: {integrity: sha512-vvYx3MhWqeZtGPwDStM2dwgljd5smolYD2lR2UyFcHfxbBQebqx8yjmFmxtJ/E6nN6u1D9srOiVWm3Rb4tmcUA==} + + '@lezer/lr@1.4.10': + resolution: {integrity: sha512-rnCpTIBafOx4mRp43xOxDJbFipJm/c0cia/V5TiGlhmMa+wsSdoGmUN3w5Bqrks/09Q/D4tNAmWaT8p6NRi77A==} + + '@lezer/markdown@1.6.4': + resolution: {integrity: sha512-N0SxazMj4k65DBfaf1azqtMZd6u7MqluP84/NZnB/io8Td9aleFmAhz9hcbvSfsxT5tdYlJ5qgv5aMJGY4zEtA==} + + '@marijn/find-cluster-break@1.0.2': + resolution: {integrity: sha512-l0h88YhZFyKdXIFNfSWpyjStDjGHwZ/U7iobcK1cQQD8sejsONdQtTVU+1wVN1PBw40PiiHB1vA5S7VTfQiP9g==} + '@mermaid-js/parser@1.1.0': resolution: {integrity: sha512-gxK9ZX2+Fex5zu8LhRQoMeMPEHbc73UKZ0FQ54YrQtUxE1VVhMwzeNtKRPAu5aXks4FasbMe4xB4bWrmq6Jlxw==} @@ -1298,167 +1340,6 @@ packages: '@types/react-dom': optional: true - '@tiptap/core@3.26.0': - resolution: {integrity: sha512-7jTed/RirIVsp+lLdLvGzGqF3EBGpnGHGYKOwz6t28V2BIJLAFdUhfEVdWie7xPxQNWK0TP+fPlsqZS0vxfHBg==} - peerDependencies: - '@tiptap/pm': 3.26.0 - - '@tiptap/extension-blockquote@3.26.0': - resolution: {integrity: sha512-57accpka9affjiJRjP2LMNCDJDTMjTvO23RJCxtP43sp9cTIZ7YZnyDfRxCINTRBNK0X4o4w2+emOLyRwsk3CA==} - peerDependencies: - '@tiptap/core': 3.26.0 - - '@tiptap/extension-bold@3.26.0': - resolution: {integrity: sha512-j6CzTMofcGJ5iMoUgDRQpM0FkG00jBID3aKqs+UBbgtzLgtG/CI/91tMFv0XPC30LeFA895qYgvGZtHdejZhiQ==} - peerDependencies: - '@tiptap/core': 3.26.0 - - '@tiptap/extension-bubble-menu@3.26.0': - resolution: {integrity: sha512-H2E3Hp0lV79jQV8YGtdDJkXkUalXZeYzKCx+vCZlDpb2ChS7/rNT9YY7poRA1NlJLUO0DH1wbAnFhx9KZMUx5g==} - peerDependencies: - '@tiptap/core': 3.26.0 - '@tiptap/pm': 3.26.0 - - '@tiptap/extension-bullet-list@3.26.0': - resolution: {integrity: sha512-Jv7BX+kBB2wUIvO/NhuUjv+T3kAed2Tjr664fgQ2zKT6X69jKIkYuCCedrIHuOyaOQ+SBDuH9h51wYv/E97QgQ==} - peerDependencies: - '@tiptap/extension-list': 3.26.0 - - '@tiptap/extension-code-block@3.26.0': - resolution: {integrity: sha512-WPN9iZ3UjeDD2ckDzSs9tleibXv0cLj7j575NxuvjhwZTehYGNeYDSUTi+6DQUG6bKbhGg9Wcei5H0131vvJHg==} - peerDependencies: - '@tiptap/core': 3.26.0 - '@tiptap/pm': 3.26.0 - - '@tiptap/extension-code@3.26.0': - resolution: {integrity: sha512-VJYcV6rvjnENRTroOi9tDcHWW6G0pmCoRETwatlbgfDzuCmkTOwVwQjeJCXOVMMLNPzNiXZzibsRCUt+Azq/jw==} - peerDependencies: - '@tiptap/core': 3.26.0 - - '@tiptap/extension-document@3.26.0': - resolution: {integrity: sha512-Xhd6DCjaxCN4otQNvV6qra+XuoIjk6Vyjm87E5xn5Y/BMw7UGAG7LTkk3C2IEvxKrVZwJjalfxEqdHOgXQzVfw==} - peerDependencies: - '@tiptap/core': 3.26.0 - - '@tiptap/extension-dropcursor@3.26.0': - resolution: {integrity: sha512-rhAtp5J/YVDUCUIc5T7b0XY9dLeuI72JgOr53w0QQc0VA0uwbfTn7sx0LI9PDCE9uwmDH8H3snVRZRnAvlM8oA==} - peerDependencies: - '@tiptap/extensions': 3.26.0 - - '@tiptap/extension-floating-menu@3.26.0': - resolution: {integrity: sha512-reQ77NRYAOP7iPudsNbzLBuBTdL2aGxZzjccUFmE2lNdmwP23n9A/JhkuUhshVBs/6IozvahI+smG3Bnea0TCQ==} - peerDependencies: - '@floating-ui/dom': ^1.0.0 - '@tiptap/core': 3.26.0 - '@tiptap/pm': 3.26.0 - - '@tiptap/extension-gapcursor@3.26.0': - resolution: {integrity: sha512-SIe68SDwx2fozt/XKG0FhCwzz/yRN6Bvo4D5TqvfDg6NK3PQb1DS4GN9PilmJqbY+kXryuiWEEJOWi7HpO8SuQ==} - peerDependencies: - '@tiptap/extensions': 3.26.0 - - '@tiptap/extension-hard-break@3.26.0': - resolution: {integrity: sha512-baXvv/rtOTVd2Axjb7Zbb41Y9Qmy3U2fP7EHqLuhViqGxVX8LwQtP0PHUXEZkPokbBpRez10+dmOlvvsYFKAZQ==} - peerDependencies: - '@tiptap/core': 3.26.0 - - '@tiptap/extension-heading@3.26.0': - resolution: {integrity: sha512-qenEQEgzE5FjQay/H6iKOnwIt6DPO27cS+v0mGhXmrL1MjrNER4X0ZkATJbVd0WA6ffsAGaP44NKYDworGeidw==} - peerDependencies: - '@tiptap/core': 3.26.0 - - '@tiptap/extension-horizontal-rule@3.26.0': - resolution: {integrity: sha512-a+N/C4wkQV+/8x4ShdoiC2JdTW3Tw84C5cAloYLFMeaWmRa2me9ACSI+zo0SO9bbH9RJwsoRp7eaxBbk27eF1Q==} - peerDependencies: - '@tiptap/core': 3.26.0 - '@tiptap/pm': 3.26.0 - - '@tiptap/extension-italic@3.26.0': - resolution: {integrity: sha512-s8oFpH+0xmhvY19f452/2dExO3p1tjxh761g6cg4irwEUNUEAJKF2VLcjiaeOhNJ+pmnQYxb+VSkwkXvO+7vHQ==} - peerDependencies: - '@tiptap/core': 3.26.0 - - '@tiptap/extension-link@3.26.0': - resolution: {integrity: sha512-FA/d157aBxyvZFvsdc5eSu46tmHWXebAsqOQSvivOMyw+deBb00VlMsf+iD2J8+sekjbMYwx/hvbsu+xUoX43Q==} - peerDependencies: - '@tiptap/core': 3.26.0 - '@tiptap/pm': 3.26.0 - - '@tiptap/extension-list-item@3.26.0': - resolution: {integrity: sha512-MccGyj9HY4fkl04eIiFoTCkr8067Jku/VVdJNtRWW104Spx43C/7V2zpbxPvpcDhq3dW384fDxYXfpnb186xLg==} - peerDependencies: - '@tiptap/extension-list': 3.26.0 - - '@tiptap/extension-list-keymap@3.26.0': - resolution: {integrity: sha512-oBcj6qaNrRHQ+N0+pDuOVAQa4Nx9r8Cm5ANvyM2lTpoy60sOLOizuVvcvw1andVxbSrsZ1N/Sk+RZWyv1uoWyQ==} - peerDependencies: - '@tiptap/extension-list': 3.26.0 - - '@tiptap/extension-list@3.26.0': - resolution: {integrity: sha512-EM8woyHDNKLEQ+lWUEoDtA4KrwP6fei/mYX1NxseMzKHHo7LFecx7wk6sovAXZrUvdML/yFBihgiMiO5VIsfkg==} - peerDependencies: - '@tiptap/core': 3.26.0 - '@tiptap/pm': 3.26.0 - - '@tiptap/extension-ordered-list@3.26.0': - resolution: {integrity: sha512-ItLdFlcMsJz2vhbs1PcUfcN7nzVqGBOwPeCrrWxjrgscp+K3JoOGD+HhVVpBACOMwivUrlh8Ry5Ohvues2nOeA==} - peerDependencies: - '@tiptap/extension-list': 3.26.0 - - '@tiptap/extension-paragraph@3.26.0': - resolution: {integrity: sha512-h8fYLikg4qN39IghQ1y9g+zzUsgxBpDi5YS3IZbWoxWYYx1YqLL8nAvOiPr7Us14aQ0TjA2/xY7zqmyf29rX1A==} - peerDependencies: - '@tiptap/core': 3.26.0 - - '@tiptap/extension-strike@3.26.0': - resolution: {integrity: sha512-jUll3Pqhq7u1JKvO0B6USW/bmVmUsO6sRcxo/d5tXqLhS0tWAobOGoGU2IgwXnQDSjf+vF73RYD5tRGDLkRC9Q==} - peerDependencies: - '@tiptap/core': 3.26.0 - - '@tiptap/extension-text@3.26.0': - resolution: {integrity: sha512-yZXdevp3/8omGbb40Z52VfvID+tsRNhPQ1GNUToD56XSr2BjdJyAzAb9rWGgDKgVMUPLgJ26yT0O278RFqOKhA==} - peerDependencies: - '@tiptap/core': 3.26.0 - - '@tiptap/extension-underline@3.26.0': - resolution: {integrity: sha512-LlVkivH5cBwov/EMD8BL7ZRcU6YcadiSVIffLW1hyalw9YfhaFzoLxjtWhL7jiU/n2Kg+9dXSZxmV2hTeTwyrQ==} - peerDependencies: - '@tiptap/core': 3.26.0 - - '@tiptap/extensions@3.26.0': - resolution: {integrity: sha512-4wajuqnO2X0+LVvsBjW/xk3/tmdb16bNL939QhicAay4YYqXITeV2v3XJsryzmG4L5GkK1yLxvRGk4aLoxWrnA==} - peerDependencies: - '@tiptap/core': 3.26.0 - '@tiptap/pm': 3.26.0 - - '@tiptap/markdown@3.26.0': - resolution: {integrity: sha512-jg5xrwl1gTXUl5JA3+g8YYfhOzplM9CVecwKZeFtlYtPLyxLCmIDvqV/vULoGu57HwtY4819nNpMZwY6jBNtrw==} - peerDependencies: - '@tiptap/core': 3.26.0 - '@tiptap/pm': 3.26.0 - - '@tiptap/pm@3.26.0': - resolution: {integrity: sha512-q4RDeWwVrhOL0jJCGRgGxLSdjOYwzQ4h2InURZVhC66433ipcHd6f3bqSOhcXZ4r0sFmMNsuF7aZmUntjWLc7w==} - - '@tiptap/react@3.26.0': - resolution: {integrity: sha512-NLPAG6tk4/AsfOsUNsbGqdgIHuGsD4A/hlYriozuo+LCAAduuluhzsL/MEHZXtFT4GXUOlCdaEqNCOrMuz/zaw==} - peerDependencies: - '@tiptap/core': 3.26.0 - '@tiptap/pm': 3.26.0 - '@types/react': ^17.0.0 || ^18.0.0 || ^19.0.0 - '@types/react-dom': ^17.0.0 || ^18.0.0 || ^19.0.0 - react: ^17.0.0 || ^18.0.0 || ^19.0.0 - react-dom: ^17.0.0 || ^18.0.0 || ^19.0.0 - - '@tiptap/starter-kit@3.26.0': - resolution: {integrity: sha512-o34EtMfqtBaljdmeElZsRG/067oGx9Zcq+j2GWo71KlZe22ga/ALexeTf1c+ETsjCxSTKR6eyQ4RZvz/2JpYfg==} - - '@tiptap/suggestion@3.26.0': - resolution: {integrity: sha512-3jxBvjmfooQroR0eCw61kSgr+g90KFVD3dM5bANhpQbCpCYRydp/iXDQmpoPHjv8FpeU5JZgcnJ3R9vhjeIM2A==} - peerDependencies: - '@tiptap/core': 3.26.0 - '@tiptap/pm': 3.26.0 - '@tybys/wasm-util@0.10.2': resolution: {integrity: sha512-RoBvJ2X0wuKlWFIjrwffGw1IqZHKQqzIchKaadZZfnNpsAYp2mM0h36JtPCjNDAHGgYez/15uMBpfGwchhiMgg==} @@ -1623,9 +1504,6 @@ packages: '@types/react@19.2.14': resolution: {integrity: sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w==} - '@types/textarea-caret@3.0.4': - resolution: {integrity: sha512-epJGYB37/sNrTDbhfyRjHkXsQSAcO6zby0JBDS0QMt6HQ1f1W2E4YpSc7TQkNmWaWmYXv92zOIfN5PHA8CmThg==} - '@types/trusted-types@2.0.7': resolution: {integrity: sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==} @@ -1635,9 +1513,6 @@ packages: '@types/unist@3.0.3': resolution: {integrity: sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==} - '@types/use-sync-external-store@0.0.6': - resolution: {integrity: sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg==} - '@ungap/structured-clone@1.3.0': resolution: {integrity: sha512-WmoN8qaIAo7WTYWbAZuG8PYEhn5fkz7dZrqTBZ7dtt//lL2Gwms1IcnQ5yHqjDfX8Ft5j4YzDM23f87zBfDe9g==} @@ -1830,6 +1705,9 @@ packages: cose-base@2.2.0: resolution: {integrity: sha512-AzlgcsCbUMymkADOJtQm3wO9S3ltPfYOFD5033keQn9NJzIbtnZj+UdBJe7DYml/8TdbtHJW3j58SOnKhWY/5g==} + crelt@1.0.6: + resolution: {integrity: sha512-VQ2MBenTq1fWZUH9DJNGti7kKv6EeAuYr3cLwxUWhIu1baTaXh4Ib5W2CqHVqib4/MqbYGJqiL3Zb8GJZr3l4g==} + css-tree@3.2.1: resolution: {integrity: sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==} engines: {node: ^10 || ^12.20.0 || ^14.13.0 || >=15.0.0} @@ -2087,10 +1965,6 @@ packages: extend@3.0.2: resolution: {integrity: sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==} - fast-equals@5.4.0: - resolution: {integrity: sha512-jt2DW/aNFNwke7AUd+Z+e6pz39KO5rzdbbFCg2sGafS4mk13MI7Z8O5z9cADNn5lhGODIgLwug6TZO2ctf7kcw==} - engines: {node: '>=6.0.0'} - fdir@6.5.0: resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==} engines: {node: '>=12.0.0'} @@ -2368,9 +2242,6 @@ packages: resolution: {integrity: sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==} engines: {node: '>= 12.0.0'} - linkifyjs@4.3.3: - resolution: {integrity: sha512-P8aEP5U/D1/IlTY2OeYsErdwh9bGuLE30NcXtKEjgdHcahveQoQwM2yZNsioQHsWFz0P7KKudisbrzCgR0sDHg==} - lodash-es@4.18.1: resolution: {integrity: sha512-J8xewKD/Gk22OZbhpOVSwcs60zhd95ESDwezOFuA3/099925PdHJ7OFHNTGtajL3AlZkykD32HykiMo+BIBI8A==} @@ -2410,11 +2281,6 @@ packages: engines: {node: '>= 20'} hasBin: true - marked@17.0.6: - resolution: {integrity: sha512-gB0gkNafnonOw0obSTEGZTT86IuhILt2Wfx0mWH/1Au83kybTayroZ/V6nS25mN7u8ASy+5fMhgB3XPNrOZdmA==} - engines: {node: '>= 20'} - hasBin: true - mdast-util-find-and-replace@3.0.2: resolution: {integrity: sha512-Tmd1Vg/m3Xz43afeNxDIhWRtFZgM2VLyaf4vSTYwudTyeuTneoL3qtWMA5jeLyz/O1vDJmmV4QuScFCA2tBPwg==} @@ -2585,9 +2451,6 @@ packages: obug@2.1.1: resolution: {integrity: sha512-uTqF9MuPraAQ+IsnPf366RG4cP9RtUi7MLO1N3KEc+wb0a6yKpeL0lmk2IB1jY5KHPAlTc6T/JRdC/YqxHNwkQ==} - orderedmap@2.1.1: - resolution: {integrity: sha512-TvAWxi0nDe1j/rtMcWcIj94+Ffe6n7zhow33h40SKxmsmozs6dz/e+EajymfoFcHd7sxNn8yHM8839uixMOV6g==} - package-manager-detector@1.6.0: resolution: {integrity: sha512-61A5ThoTiDG/C8s8UMZwSorAGwMJ0ERVGj2OjoW5pAalsNOg15+iQiPzrLJ4jhZ1HJzmC2PIHT2oEiH3R5fzNA==} @@ -2636,45 +2499,6 @@ packages: property-information@7.1.0: resolution: {integrity: sha512-TwEZ+X+yCJmYfL7TPUOcvBZ4QfoT5YenQiJuX//0th53DE6w0xxLEtfK3iyryQFddXuvkIk51EEgrJQ0WJkOmQ==} - prosemirror-changeset@2.4.1: - resolution: {integrity: sha512-96WBLhOaYhJ+kPhLg3uW359Tz6I/MfcrQfL4EGv4SrcqKEMC1gmoGrXHecPE8eOwTVCJ4IwgfzM8fFad25wNfw==} - - prosemirror-commands@1.7.1: - resolution: {integrity: sha512-rT7qZnQtx5c0/y/KlYaGvtG411S97UaL6gdp6RIZ23DLHanMYLyfGBV5DtSnZdthQql7W+lEVbpSfwtO8T+L2w==} - - prosemirror-dropcursor@1.8.2: - resolution: {integrity: sha512-CCk6Gyx9+Tt2sbYk5NK0nB1ukHi2ryaRgadV/LvyNuO3ena1payM2z6Cg0vO1ebK8cxbzo41ku2DE5Axj1Zuiw==} - - prosemirror-gapcursor@1.4.1: - resolution: {integrity: sha512-pMdYaEnjNMSwl11yjEGtgTmLkR08m/Vl+Jj443167p9eB3HVQKhYCc4gmHVDsLPODfZfjr/MmirsdyZziXbQKw==} - - prosemirror-history@1.5.0: - resolution: {integrity: sha512-zlzTiH01eKA55UAf1MEjtssJeHnGxO0j4K4Dpx+gnmX9n+SHNlDqI2oO1Kv1iPN5B1dm5fsljCfqKF9nFL6HRg==} - - prosemirror-inputrules@1.5.1: - resolution: {integrity: sha512-7wj4uMjKaXWAQ1CDgxNzNtR9AlsuwzHfdFH1ygEHA2KHF2DOEaXl1CJfNPAKCg9qNEh4rum975QLaCiQPyY6Fw==} - - prosemirror-keymap@1.2.3: - resolution: {integrity: sha512-4HucRlpiLd1IPQQXNqeo81BGtkY8Ai5smHhKW9jjPKRc2wQIxksg7Hl1tTI2IfT2B/LgX6bfYvXxEpJl7aKYKw==} - - prosemirror-model@1.25.8: - resolution: {integrity: sha512-BswA4BLSFEiORV6Vjj/yZBXDbos1zTEnhyeSSgT8psGFhstQS7UJ8/WOLiDos9Byaee27+tml0/DuMNxYR84zg==} - - prosemirror-schema-list@1.5.1: - resolution: {integrity: sha512-927lFx/uwyQaGwJxLWCZRkjXG0p48KpMj6ueoYiu4JX05GGuGcgzAy62dfiV8eFZftgyBUvLx76RsMe20fJl+Q==} - - prosemirror-state@1.4.4: - resolution: {integrity: sha512-6jiYHH2CIGbCfnxdHbXZ12gySFY/fz/ulZE333G6bPqIZ4F+TXo9ifiR86nAHpWnfoNjOb3o5ESi7J8Uz1jXHw==} - - prosemirror-tables@1.8.5: - resolution: {integrity: sha512-V/0cDCsHKHe/tfWkeCmthNUcEp1IVO3p6vwN8XtwE9PZQLAZJigbw3QoraAdfJPir4NKJtNvOB8oYGKRl+t0Dw==} - - prosemirror-transform@1.12.0: - resolution: {integrity: sha512-GxboyN4AMIsoHNtz5uf2r2Ru551i5hWeCMD6E2Ib4Eogqoub0NflniaBPVQ4MrGE5yZ8JV9tUHg9qcZTTrcN4w==} - - prosemirror-view@1.41.9: - resolution: {integrity: sha512-clTunTX+eaLbr87L1V1QPheRlEQJyTlL3gXe9x3jQIk3rL0RVWxviDGz8tFaydwIVm+hKhYCyr+R/zBtWr9s6A==} - punycode@2.3.1: resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==} engines: {node: '>=6'} @@ -2831,9 +2655,6 @@ packages: engines: {node: ^20.19.0 || >=22.12.0} hasBin: true - rope-sequence@1.3.4: - resolution: {integrity: sha512-UT5EDe2cu2E/6O4igUr5PSFs23nvvukicWHx6GnOPlHAiiYbzNuCRQCuiUdHJQcqKalLKlrYJnjY0ySGsXNQXQ==} - roughjs@4.6.6: resolution: {integrity: sha512-ZUz/69+SYpFN/g/lUlo2FXcIjRkSu3nDarreVdGGndHEBJ6cXPdKguS8JGxwj5HA5xIbVKSmLgr5b3AWxtRfvQ==} @@ -2887,6 +2708,9 @@ packages: resolution: {integrity: sha512-laJTa3Jb+VQpaC6DseHhF7dXVqHTfJPCRDaEbid/drOhgitgYku/letMUqOXFoWV0zIIUbjpdH2t+tYj4bQMRQ==} engines: {node: '>=8'} + style-mod@4.1.3: + resolution: {integrity: sha512-i/n8VsZydrugj3Iuzll8+x/00GH2vnYsk1eomD8QiRrSAeW6ItbCQDtfXCeJHd0iwiNagqjQkvpvREEPtW3IoQ==} + style-to-js@1.1.21: resolution: {integrity: sha512-RjQetxJrrUJLQPHbLku6U/ocGtzyjbJMP9lCNK7Ag0CNh690nSH8woqWH9u16nMjYBAok+i7JO1NP2pOy8IsPQ==} @@ -2918,9 +2742,6 @@ packages: engines: {node: '>=10'} hasBin: true - textarea-caret@3.1.0: - resolution: {integrity: sha512-cXAvzO9pP5CGa6NKx0WYHl+8CHKZs8byMkt3PCJBCmq2a34YA9pO1NrQET5pzeqnBjBdToF5No4rrmkDUgQC2Q==} - tinybench@2.9.0: resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==} @@ -3416,6 +3237,86 @@ snapshots: '@chevrotain/utils@12.0.0': {} + '@codemirror/autocomplete@6.20.3': + dependencies: + '@codemirror/language': 6.12.4 + '@codemirror/state': 6.7.0 + '@codemirror/view': 6.43.3 + '@lezer/common': 1.5.2 + + '@codemirror/commands@6.10.4': + dependencies: + '@codemirror/language': 6.12.4 + '@codemirror/state': 6.7.0 + '@codemirror/view': 6.43.3 + '@lezer/common': 1.5.2 + + '@codemirror/lang-css@6.3.1': + dependencies: + '@codemirror/autocomplete': 6.20.3 + '@codemirror/language': 6.12.4 + '@codemirror/state': 6.7.0 + '@lezer/common': 1.5.2 + '@lezer/css': 1.3.3 + + '@codemirror/lang-html@6.4.11': + dependencies: + '@codemirror/autocomplete': 6.20.3 + '@codemirror/lang-css': 6.3.1 + '@codemirror/lang-javascript': 6.2.5 + '@codemirror/language': 6.12.4 + '@codemirror/state': 6.7.0 + '@codemirror/view': 6.43.3 + '@lezer/common': 1.5.2 + '@lezer/css': 1.3.3 + '@lezer/html': 1.3.13 + + '@codemirror/lang-javascript@6.2.5': + dependencies: + '@codemirror/autocomplete': 6.20.3 + '@codemirror/language': 6.12.4 + '@codemirror/lint': 6.9.7 + '@codemirror/state': 6.7.0 + '@codemirror/view': 6.43.3 + '@lezer/common': 1.5.2 + '@lezer/javascript': 1.5.4 + + '@codemirror/lang-markdown@6.5.0': + dependencies: + '@codemirror/autocomplete': 6.20.3 + '@codemirror/lang-html': 6.4.11 + '@codemirror/language': 6.12.4 + '@codemirror/state': 6.7.0 + '@codemirror/view': 6.43.3 + '@lezer/common': 1.5.2 + '@lezer/markdown': 1.6.4 + + '@codemirror/language@6.12.4': + dependencies: + '@codemirror/state': 6.7.0 + '@codemirror/view': 6.43.3 + '@lezer/common': 1.5.2 + '@lezer/highlight': 1.2.3 + '@lezer/lr': 1.4.10 + style-mod: 4.1.3 + + '@codemirror/lint@6.9.7': + dependencies: + '@codemirror/state': 6.7.0 + '@codemirror/view': 6.43.3 + crelt: 1.0.6 + + '@codemirror/state@6.7.0': + dependencies: + '@marijn/find-cluster-break': 1.0.2 + + '@codemirror/view@6.43.3': + dependencies: + '@codemirror/state': 6.7.0 + crelt: 1.0.6 + style-mod: 4.1.3 + w3c-keyname: 2.2.8 + '@connectrpc/connect-web@2.1.1(@bufbuild/protobuf@2.12.0)(@connectrpc/connect@2.1.1(@bufbuild/protobuf@2.12.0))': dependencies: '@bufbuild/protobuf': 2.12.0 @@ -3518,6 +3419,41 @@ snapshots: '@jridgewell/resolve-uri': 3.1.2 '@jridgewell/sourcemap-codec': 1.5.5 + '@lezer/common@1.5.2': {} + + '@lezer/css@1.3.3': + dependencies: + '@lezer/common': 1.5.2 + '@lezer/highlight': 1.2.3 + '@lezer/lr': 1.4.10 + + '@lezer/highlight@1.2.3': + dependencies: + '@lezer/common': 1.5.2 + + '@lezer/html@1.3.13': + dependencies: + '@lezer/common': 1.5.2 + '@lezer/highlight': 1.2.3 + '@lezer/lr': 1.4.10 + + '@lezer/javascript@1.5.4': + dependencies: + '@lezer/common': 1.5.2 + '@lezer/highlight': 1.2.3 + '@lezer/lr': 1.4.10 + + '@lezer/lr@1.4.10': + dependencies: + '@lezer/common': 1.5.2 + + '@lezer/markdown@1.6.4': + dependencies: + '@lezer/common': 1.5.2 + '@lezer/highlight': 1.2.3 + + '@marijn/find-cluster-break@1.0.2': {} + '@mermaid-js/parser@1.1.0': dependencies: langium: 4.2.2 @@ -4149,189 +4085,6 @@ snapshots: '@types/react': 19.2.14 '@types/react-dom': 19.2.3(@types/react@19.2.14) - '@tiptap/core@3.26.0(@tiptap/pm@3.26.0)': - dependencies: - '@tiptap/pm': 3.26.0 - - '@tiptap/extension-blockquote@3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))': - dependencies: - '@tiptap/core': 3.26.0(@tiptap/pm@3.26.0) - - '@tiptap/extension-bold@3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))': - dependencies: - '@tiptap/core': 3.26.0(@tiptap/pm@3.26.0) - - '@tiptap/extension-bubble-menu@3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0)': - dependencies: - '@floating-ui/dom': 1.7.6 - '@tiptap/core': 3.26.0(@tiptap/pm@3.26.0) - '@tiptap/pm': 3.26.0 - optional: true - - '@tiptap/extension-bullet-list@3.26.0(@tiptap/extension-list@3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0))': - dependencies: - '@tiptap/extension-list': 3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0) - - '@tiptap/extension-code-block@3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0)': - dependencies: - '@tiptap/core': 3.26.0(@tiptap/pm@3.26.0) - '@tiptap/pm': 3.26.0 - - '@tiptap/extension-code@3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))': - dependencies: - '@tiptap/core': 3.26.0(@tiptap/pm@3.26.0) - - '@tiptap/extension-document@3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))': - dependencies: - '@tiptap/core': 3.26.0(@tiptap/pm@3.26.0) - - '@tiptap/extension-dropcursor@3.26.0(@tiptap/extensions@3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0))': - dependencies: - '@tiptap/extensions': 3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0) - - '@tiptap/extension-floating-menu@3.26.0(@floating-ui/dom@1.7.6)(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0)': - dependencies: - '@floating-ui/dom': 1.7.6 - '@tiptap/core': 3.26.0(@tiptap/pm@3.26.0) - '@tiptap/pm': 3.26.0 - optional: true - - '@tiptap/extension-gapcursor@3.26.0(@tiptap/extensions@3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0))': - dependencies: - '@tiptap/extensions': 3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0) - - '@tiptap/extension-hard-break@3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))': - dependencies: - '@tiptap/core': 3.26.0(@tiptap/pm@3.26.0) - - '@tiptap/extension-heading@3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))': - dependencies: - '@tiptap/core': 3.26.0(@tiptap/pm@3.26.0) - - '@tiptap/extension-horizontal-rule@3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0)': - dependencies: - '@tiptap/core': 3.26.0(@tiptap/pm@3.26.0) - '@tiptap/pm': 3.26.0 - - '@tiptap/extension-italic@3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))': - dependencies: - '@tiptap/core': 3.26.0(@tiptap/pm@3.26.0) - - '@tiptap/extension-link@3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0)': - dependencies: - '@tiptap/core': 3.26.0(@tiptap/pm@3.26.0) - '@tiptap/pm': 3.26.0 - linkifyjs: 4.3.3 - - '@tiptap/extension-list-item@3.26.0(@tiptap/extension-list@3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0))': - dependencies: - '@tiptap/extension-list': 3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0) - - '@tiptap/extension-list-keymap@3.26.0(@tiptap/extension-list@3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0))': - dependencies: - '@tiptap/extension-list': 3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0) - - '@tiptap/extension-list@3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0)': - dependencies: - '@tiptap/core': 3.26.0(@tiptap/pm@3.26.0) - '@tiptap/pm': 3.26.0 - - '@tiptap/extension-ordered-list@3.26.0(@tiptap/extension-list@3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0))': - dependencies: - '@tiptap/extension-list': 3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0) - - '@tiptap/extension-paragraph@3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))': - dependencies: - '@tiptap/core': 3.26.0(@tiptap/pm@3.26.0) - - '@tiptap/extension-strike@3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))': - dependencies: - '@tiptap/core': 3.26.0(@tiptap/pm@3.26.0) - - '@tiptap/extension-text@3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))': - dependencies: - '@tiptap/core': 3.26.0(@tiptap/pm@3.26.0) - - '@tiptap/extension-underline@3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))': - dependencies: - '@tiptap/core': 3.26.0(@tiptap/pm@3.26.0) - - '@tiptap/extensions@3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0)': - dependencies: - '@tiptap/core': 3.26.0(@tiptap/pm@3.26.0) - '@tiptap/pm': 3.26.0 - - '@tiptap/markdown@3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0)': - dependencies: - '@tiptap/core': 3.26.0(@tiptap/pm@3.26.0) - '@tiptap/pm': 3.26.0 - marked: 17.0.6 - - '@tiptap/pm@3.26.0': - dependencies: - prosemirror-changeset: 2.4.1 - prosemirror-commands: 1.7.1 - prosemirror-dropcursor: 1.8.2 - prosemirror-gapcursor: 1.4.1 - prosemirror-history: 1.5.0 - prosemirror-inputrules: 1.5.1 - prosemirror-keymap: 1.2.3 - prosemirror-model: 1.25.8 - prosemirror-schema-list: 1.5.1 - prosemirror-state: 1.4.4 - prosemirror-tables: 1.8.5 - prosemirror-transform: 1.12.0 - prosemirror-view: 1.41.9 - - '@tiptap/react@3.26.0(@floating-ui/dom@1.7.6)(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0)(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.6(react@19.2.6))(react@19.2.6)': - dependencies: - '@tiptap/core': 3.26.0(@tiptap/pm@3.26.0) - '@tiptap/pm': 3.26.0 - '@types/react': 19.2.14 - '@types/react-dom': 19.2.3(@types/react@19.2.14) - '@types/use-sync-external-store': 0.0.6 - fast-equals: 5.4.0 - react: 19.2.6 - react-dom: 19.2.6(react@19.2.6) - use-sync-external-store: 1.6.0(react@19.2.6) - optionalDependencies: - '@tiptap/extension-bubble-menu': 3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0) - '@tiptap/extension-floating-menu': 3.26.0(@floating-ui/dom@1.7.6)(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0) - transitivePeerDependencies: - - '@floating-ui/dom' - - '@tiptap/starter-kit@3.26.0': - dependencies: - '@tiptap/core': 3.26.0(@tiptap/pm@3.26.0) - '@tiptap/extension-blockquote': 3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0)) - '@tiptap/extension-bold': 3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0)) - '@tiptap/extension-bullet-list': 3.26.0(@tiptap/extension-list@3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0)) - '@tiptap/extension-code': 3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0)) - '@tiptap/extension-code-block': 3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0) - '@tiptap/extension-document': 3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0)) - '@tiptap/extension-dropcursor': 3.26.0(@tiptap/extensions@3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0)) - '@tiptap/extension-gapcursor': 3.26.0(@tiptap/extensions@3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0)) - '@tiptap/extension-hard-break': 3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0)) - '@tiptap/extension-heading': 3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0)) - '@tiptap/extension-horizontal-rule': 3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0) - '@tiptap/extension-italic': 3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0)) - '@tiptap/extension-link': 3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0) - '@tiptap/extension-list': 3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0) - '@tiptap/extension-list-item': 3.26.0(@tiptap/extension-list@3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0)) - '@tiptap/extension-list-keymap': 3.26.0(@tiptap/extension-list@3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0)) - '@tiptap/extension-ordered-list': 3.26.0(@tiptap/extension-list@3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0)) - '@tiptap/extension-paragraph': 3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0)) - '@tiptap/extension-strike': 3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0)) - '@tiptap/extension-text': 3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0)) - '@tiptap/extension-underline': 3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0)) - '@tiptap/extensions': 3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0) - '@tiptap/pm': 3.26.0 - - '@tiptap/suggestion@3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0)': - dependencies: - '@tiptap/core': 3.26.0(@tiptap/pm@3.26.0) - '@tiptap/pm': 3.26.0 - '@tybys/wasm-util@0.10.2': dependencies: tslib: 2.8.1 @@ -4532,8 +4285,6 @@ snapshots: dependencies: csstype: 3.2.3 - '@types/textarea-caret@3.0.4': {} - '@types/trusted-types@2.0.7': optional: true @@ -4541,8 +4292,6 @@ snapshots: '@types/unist@3.0.3': {} - '@types/use-sync-external-store@0.0.6': {} - '@ungap/structured-clone@1.3.0': {} '@upsetjs/venn.js@2.0.0': @@ -4726,6 +4475,8 @@ snapshots: dependencies: layout-base: 2.0.1 + crelt@1.0.6: {} + css-tree@3.2.1: dependencies: mdn-data: 2.27.1 @@ -4989,8 +4740,6 @@ snapshots: extend@3.0.2: {} - fast-equals@5.4.0: {} - fdir@6.5.0(picomatch@4.0.4): optionalDependencies: picomatch: 4.0.4 @@ -5291,8 +5040,6 @@ snapshots: lightningcss-win32-arm64-msvc: 1.32.0 lightningcss-win32-x64-msvc: 1.32.0 - linkifyjs@4.3.3: {} - lodash-es@4.18.1: {} lodash.debounce@4.0.8: {} @@ -5321,8 +5068,6 @@ snapshots: marked@16.4.2: {} - marked@17.0.6: {} - mdast-util-find-and-replace@3.0.2: dependencies: '@types/mdast': 4.0.4 @@ -5739,8 +5484,6 @@ snapshots: obug@2.1.1: {} - orderedmap@2.1.1: {} - package-manager-detector@1.6.0: {} parse-entities@4.0.2: @@ -5798,80 +5541,6 @@ snapshots: property-information@7.1.0: {} - prosemirror-changeset@2.4.1: - dependencies: - prosemirror-transform: 1.12.0 - - prosemirror-commands@1.7.1: - dependencies: - prosemirror-model: 1.25.8 - prosemirror-state: 1.4.4 - prosemirror-transform: 1.12.0 - - prosemirror-dropcursor@1.8.2: - dependencies: - prosemirror-state: 1.4.4 - prosemirror-transform: 1.12.0 - prosemirror-view: 1.41.9 - - prosemirror-gapcursor@1.4.1: - dependencies: - prosemirror-keymap: 1.2.3 - prosemirror-model: 1.25.8 - prosemirror-state: 1.4.4 - prosemirror-view: 1.41.9 - - prosemirror-history@1.5.0: - dependencies: - prosemirror-state: 1.4.4 - prosemirror-transform: 1.12.0 - prosemirror-view: 1.41.9 - rope-sequence: 1.3.4 - - prosemirror-inputrules@1.5.1: - dependencies: - prosemirror-state: 1.4.4 - prosemirror-transform: 1.12.0 - - prosemirror-keymap@1.2.3: - dependencies: - prosemirror-state: 1.4.4 - w3c-keyname: 2.2.8 - - prosemirror-model@1.25.8: - dependencies: - orderedmap: 2.1.1 - - prosemirror-schema-list@1.5.1: - dependencies: - prosemirror-model: 1.25.8 - prosemirror-state: 1.4.4 - prosemirror-transform: 1.12.0 - - prosemirror-state@1.4.4: - dependencies: - prosemirror-model: 1.25.8 - prosemirror-transform: 1.12.0 - prosemirror-view: 1.41.9 - - prosemirror-tables@1.8.5: - dependencies: - prosemirror-keymap: 1.2.3 - prosemirror-model: 1.25.8 - prosemirror-state: 1.4.4 - prosemirror-transform: 1.12.0 - prosemirror-view: 1.41.9 - - prosemirror-transform@1.12.0: - dependencies: - prosemirror-model: 1.25.8 - - prosemirror-view@1.41.9: - dependencies: - prosemirror-model: 1.25.8 - prosemirror-state: 1.4.4 - prosemirror-transform: 1.12.0 - punycode@2.3.1: {} react-dom@19.2.6(react@19.2.6): @@ -6083,8 +5752,6 @@ snapshots: '@rolldown/binding-win32-arm64-msvc': 1.0.0-rc.18 '@rolldown/binding-win32-x64-msvc': 1.0.0-rc.18 - rope-sequence@1.3.4: {} - roughjs@4.6.6: dependencies: hachure-fill: 0.5.2 @@ -6132,6 +5799,8 @@ snapshots: dependencies: min-indent: 1.0.1 + style-mod@4.1.3: {} + style-to-js@1.1.21: dependencies: style-to-object: 1.0.14 @@ -6159,8 +5828,6 @@ snapshots: commander: 2.20.3 source-map-support: 0.5.21 - textarea-caret@3.1.0: {} - tinybench@2.9.0: {} tinyexec@1.1.1: {} diff --git a/web/src/components/MemoContent/markdown/List.tsx b/web/src/components/MemoContent/markdown/List.tsx index 790c17e7..6daa0db1 100644 --- a/web/src/components/MemoContent/markdown/List.tsx +++ b/web/src/components/MemoContent/markdown/List.tsx @@ -99,16 +99,10 @@ export const ListItem = ({ children, className, node: _node, ...domProps }: List const { checkbox, content } = splitTaskListItemChildren(children); return ( -
  • [data-slot=checkbox]]:mt-1", - className, - )} - {...domProps} - > +
  • {checkbox} -
    {content}
    +
    {content}
  • ); diff --git a/web/src/components/MemoEditor/Editor/Mention.ts b/web/src/components/MemoEditor/Editor/Mention.ts deleted file mode 100644 index a8f0dc3c..00000000 --- a/web/src/components/MemoEditor/Editor/Mention.ts +++ /dev/null @@ -1,124 +0,0 @@ -import type { MarkdownToken } from "@tiptap/core"; -import { InputRule, Mark, mergeAttributes } from "@tiptap/core"; -import { mentionStyles } from "@/lib/markdownStyles"; -import { isMentionChar, MENTION_RUN } from "@/utils/mention-grammar"; - -// Default mention accent, shared with the read-only view (MemoContent/Mention.tsx). -// Computed once — renderHTML runs on every view update. -const MENTION_CLASS = mentionStyles.base; - -// Built from the shared MENTION_RUN (@/utils/mention-grammar) so the editor's -// input rule and tokenizer can't drift from the read-only renderer's lexer -// (web/src/utils/remark-plugins/remark-mention.ts). The `(? element.getAttribute("data-mention") ?? "", - renderHTML: (attributes) => ({ "data-mention": attributes.username }), - }, - }; - }, - - parseHTML() { - return [{ tag: "span[data-mention]" }]; - }, - - renderHTML({ HTMLAttributes }) { - return [ - "span", - mergeAttributes(HTMLAttributes, { - class: MENTION_CLASS, - }), - 0, - ]; - }, - - addInputRules() { - return [ - new InputRule({ - find: MENTION_INPUT_RULE, - handler: ({ state, range, match }) => { - // Mark only from the `@`; the trailing space stays outside the mark - // and is re-inserted explicitly (the handler's steps suppress the - // typed space), mirroring the Tag input rule. - const start = range.from + match[0].indexOf("@"); - state.tr - .addMark(start, range.to, this.type.create({ username: match[1] })) - .insertText(" ", range.to) - .removeStoredMark(this.type); - }, - }), - ]; - }, - - markdownTokenizer: { - name: "memoMention", - level: "inline", - // Point marked only at an `@` that could *begin* a mention — one at a - // boundary (string start, or a non-mention char before it). An `@` glued to - // a preceding word/username char belongs to an email (`support@example.com`) - // or the tail of `@a@b`; surfacing its index here would make marked split - // the text at the `@` and rob its GFM autolinker of the contiguous email, - // suppressing the mailto link. Skipping such `@`s leaves emails to autolink. - start: (src: string) => { - for (let i = src.indexOf("@"); i !== -1; i = src.indexOf("@", i + 1)) { - if (i === 0 || !isMentionChar(src[i - 1])) { - return i; - } - } - return -1; - }, - tokenize: (src: string, tokens: MarkdownToken[]) => { - const match = MENTION_TOKEN_RULE.exec(src); - if (!match) { - return undefined; - } - // A mention only starts at a boundary. The previous token's last source - // character is exactly the character before this `@`; if it is a mention - // character the `@` is glued to a word or username (`support@example`, - // the second `@` in `@a@b`) and must stay literal — mirroring the - // read-only renderer's isMentionBoundary check (remark-mention.ts). - const prevChar = (tokens[tokens.length - 1]?.raw ?? "").slice(-1); - if (prevChar && isMentionChar(prevChar)) { - return undefined; - } - return { type: "memoMention", raw: match[0], username: match[1] }; - }, - }, - markdownTokenName: "memoMention", - parseMarkdown: (token, helpers) => { - const t = token as MarkdownToken & { username?: string }; - return helpers.createTextNode(t.raw ?? "", [{ type: "mention", attrs: { username: t.username ?? "" } }]); - }, - // No delimiters: the literal `@username` text carries the syntax. - renderMarkdown: (node, helpers) => (node.content ? helpers.renderChildren(node.content) : ""), -}); diff --git a/web/src/components/MemoEditor/Editor/PreservedBlock.ts b/web/src/components/MemoEditor/Editor/PreservedBlock.ts deleted file mode 100644 index c177b9d7..00000000 --- a/web/src/components/MemoEditor/Editor/PreservedBlock.ts +++ /dev/null @@ -1,217 +0,0 @@ -import type { MarkdownParseHelpers, MarkdownToken } from "@tiptap/core"; -import { Extension, Mark, mergeAttributes, Node } from "@tiptap/core"; -import type { Tokens } from "marked"; -import { marked } from "marked"; - -/** - * Fidelity workhorse for syntax the WYSIWYG editor does not model (tables, - * math, raw HTML). Constructs are captured at parse time with their raw - * markdown source, shown as editable literal mono text, and re-emitted - * byte-for-byte on serialize. `code: true` keeps the serializer from - * escaping/entity-encoding the inner text. - */ -export const PreservedBlock = Node.create({ - name: "preservedBlock", - group: "block", - content: "text*", - marks: "", - code: true, - defining: true, - - parseHTML() { - return [{ tag: "pre[data-preserved-block]", preserveWhitespace: "full" }]; - }, - - renderHTML({ HTMLAttributes }) { - return [ - "pre", - mergeAttributes(HTMLAttributes, { - "data-preserved-block": "", - class: "font-mono text-sm opacity-80 whitespace-pre-wrap my-0", - }), - 0, - ]; - }, - - // The literal source is the node's text; Document joins blocks with \n\n. - renderMarkdown: (node, helpers) => (node.content ? helpers.renderChildren(node.content) : ""), -}); - -/** Inline counterpart: a `code: true` mark that emits its text verbatim. */ -export const PreservedInline = Mark.create({ - name: "preservedInline", - code: true, - - parseHTML() { - return [{ tag: "span[data-preserved-inline]" }]; - }, - - renderHTML({ HTMLAttributes }) { - return ["span", mergeAttributes(HTMLAttributes, { "data-preserved-inline": "", class: "font-mono opacity-80" }), 0]; - }, - - // No delimiters: the preserved text already contains its own syntax. - renderMarkdown: (node, helpers) => (node.content ? helpers.renderChildren(node.content) : ""), -}); - -// Note: `MarkdownParseResult` in @tiptap/core 3.26.0 does not admit `null`; -// the manager treats an empty array as "handler declined" (it requires -// `normalized.length > 0` before accepting a result), so `[]` is the -// type-safe way to fall through to the next handler / fallback. -function preservedBlockFromToken(token: MarkdownToken, helpers: MarkdownParseHelpers) { - const source = (token.raw ?? "").replace(/\n+$/, ""); - if (!source) { - return []; - } - return helpers.createNode("preservedBlock", {}, [helpers.createTextNode(source)]); -} - -/** Inline counterpart: the token's raw source as preservedInline-marked text. */ -function preservedInlineFromToken(token: MarkdownToken, helpers: MarkdownParseHelpers) { - return helpers.createTextNode(token.raw ?? "", [{ type: "preservedInline" }]); -} - -/** Routes marked's `table` tokens into preservedBlock instead of dropping them. */ -export const PreservedTableBridge = Extension.create({ - name: "preservedTableBridge", - markdownTokenName: "table", - parseMarkdown: preservedBlockFromToken, -}); - -/** - * Routes block-level raw HTML into preservedBlock. Inline HTML never reaches - * the handler registry (the markdown manager intercepts it and would convert - * recognized tags like into marks), so inline tags are captured earlier - * by the custom tokenizer in PreservedHtmlInlineBridge below. - */ -export const PreservedHtmlBlockBridge = Extension.create({ - name: "preservedHtmlBlockBridge", - markdownTokenName: "html", - parseMarkdown: (token, helpers) => { - if (!token.block) { - return []; - } - return preservedBlockFromToken(token, helpers); - }, -}); - -function tokenizePreservedHtmlInline(src: string): Tokens.Generic | undefined { - // One HTML comment, or one opening/closing/self-closing HTML tag. For - // tags, the first character after `<` (or `` — this never - // matches autolinks such as or - // (`:`/`@` break the match). Attribute values are matched quote-aware so - // `>` inside a quoted value (e.g. data-x="1 > 0") does not end the tag. - // The alternatives are disjoint: the catch-all class [^<>"'] excludes both - // quote characters so it cannot overlap with the quoted branches, which - // eliminates catastrophic backtracking on unterminated tags with many quotes. - const match = /^(?:|<\/?[a-zA-Z][a-zA-Z0-9-]*(?:\s(?:"[^"]*"|'[^']*'|[^<>"'])*)?\/?>)/.exec(src); - if (!match) { - return undefined; - } - return { type: "preservedHtmlInline", raw: match[0], text: match[0] }; -} - -function tokenizePreservedMathBlock(src: string): Tokens.Generic | undefined { - // Anchored to line geometry: opens at line start (guaranteed by marked - // handing us `src` from the current block position) and closes with `$$` - // at end-of-line. Trailing newlines are NOT consumed into `raw` (the - // `(?=\n|$)` lookahead): marked tolerates this for block tokens — its - // "space" tokenizer absorbs the leftover `\n` and the following block - // tokenizes normally (verified by the round-trip tests). Either way, - // "$$\nx\n$$\nnext" serializes as "$$\nx\n$$\n\nnext": the \n\n comes - // from the Document serializer joining sibling blocks, and - // preservedBlockFromToken strips trailing \n from raw regardless — so - // we keep raw minimal rather than swallow separators we don't re-emit. - const match = /^\$\$[\s\S]+?\$\$(?=\n|$)/.exec(src); - if (!match) { - return undefined; - } - return { type: "preservedMathBlock", raw: match[0], text: match[0] }; -} - -function tokenizePreservedMathInline(src: string): Tokens.Generic | undefined { - const match = /^\$[^$\n]+\$/.exec(src); - if (!match) { - return undefined; - } - return { type: "preservedMathInline", raw: match[0], text: match[0] }; -} - -/** - * The three preserved-syntax tokenizers are registered DIRECTLY on the global - * marked singleton, module-scope and idempotent — the Tag.ts pattern (see the - * rationale there). Routing them through each Extension's `markdownTokenizer` - * would make every `new Editor()` re-register them on the shared `marked` - * instance forever (the accumulation hazard documented in markdownCodec.ts). - * The Extensions below keep `markdownTokenName` + `parseMarkdown`, which is - * all the manager needs to route the tokens. - */ -let preservedTokenizersRegistered = false; -function registerPreservedTokenizers() { - if (preservedTokenizersRegistered) { - return; - } - preservedTokenizersRegistered = true; - marked.use({ - extensions: [ - { - name: "preservedHtmlInline", - level: "inline", - start: (src: string) => src.indexOf("<"), - tokenizer: tokenizePreservedHtmlInline, - }, - { - name: "preservedMathBlock", - level: "block", - // Marked truncates the preceding paragraph at whatever index `start` - // returns, even if `tokenizer` then declines — so only report `$$` that - // sits at the start of a line, never a mid-line `$$` (e.g. "costs $$"). - // Marked invokes block `start` callbacks exclusively from its paragraph - // interrupt check, on `src.slice(1)` — index 0 of the string we receive - // is always mid-line, so a `^`-anchored branch would false-positive - // (e.g. "$$$$" → "$\n$\n$$"). Only a `$$` right after `\n` is line-start. - start: (src: string) => { - const match = /\n\$\$/.exec(src); - return match ? match.index + 1 : -1; - }, - tokenizer: tokenizePreservedMathBlock, - }, - { - name: "preservedMathInline", - level: "inline", - start: (src: string) => src.indexOf("$"), - tokenizer: tokenizePreservedMathInline, - }, - ], - }); -} -registerPreservedTokenizers(); - -export const PreservedHtmlInlineBridge = Extension.create({ - name: "preservedHtmlInlineBridge", - markdownTokenName: "preservedHtmlInline", - parseMarkdown: preservedInlineFromToken, -}); - -export const PreservedMathBlockBridge = Extension.create({ - name: "preservedMathBlockBridge", - markdownTokenName: "preservedMathBlock", - parseMarkdown: preservedBlockFromToken, -}); - -export const PreservedMathInlineBridge = Extension.create({ - name: "preservedMathInlineBridge", - markdownTokenName: "preservedMathInline", - parseMarkdown: preservedInlineFromToken, -}); - -export const preservedExtensions = [ - PreservedBlock, - PreservedInline, - PreservedTableBridge, - PreservedHtmlBlockBridge, - PreservedHtmlInlineBridge, - PreservedMathBlockBridge, - PreservedMathInlineBridge, -]; diff --git a/web/src/components/MemoEditor/Editor/Tag.ts b/web/src/components/MemoEditor/Editor/Tag.ts deleted file mode 100644 index 478cabc9..00000000 --- a/web/src/components/MemoEditor/Editor/Tag.ts +++ /dev/null @@ -1,122 +0,0 @@ -import type { MarkdownToken } from "@tiptap/core"; -import { InputRule, Mark, mergeAttributes } from "@tiptap/core"; -import { tagStyles } from "@/lib/markdownStyles"; -import { TAG_RUN } from "@/utils/tag-grammar"; - -// Default tag pill, shared with the read-only view (MemoContent/Tag.tsx). -// Computed once — renderHTML runs on every view update. -const TAG_CLASS = `${tagStyles.base} ${tagStyles.defaultColor}`; - -// Built from the shared TAG_RUN (@/utils/tag-grammar) so the editor's input -// rule and tokenizer can't drift from the serialize-escape or the read-only -// renderer's lexer (web/src/utils/remark-plugins/remark-tag.ts). The capped-run -// lookahead in TAG_RUN also makes an over-long run decline to match — no -// separate length check needed. -const TAG_INPUT_RULE = new RegExp(`(?:^|\\s)#(${TAG_RUN})\\s$`, "u"); -const TAG_TOKEN_RULE = new RegExp(`^#(${TAG_RUN})`, "u"); - -/** - * Mark for memos `#tags`: styled in the editor, serialized back to `#tag` - * verbatim. Modeled as a `code: true` text mark (the PreservedInline pattern, - * see PreservedBlock.ts) rather than an inline atom node: text marks compose - * through the serializer's mark open/close machinery, so a tag inside - * `**bold**` or a heading round-trips byte-identically, and `code: true` - * keeps the literal text (`#a_b`) unescaped. Inline atoms cannot do either — - * `applyMarkToContent` only attaches enclosing marks to text nodes, so an - * atom inside bold silently drops the bold delimiters. - * - * Parsed live while typing (the input rule) and from markdown (the - * `markdownTokenizer` below — the canonical @tiptap/markdown extension point, - * https://tiptap.dev/docs/editor/markdown/advanced-usage/custom-tokenizer). - * - * Two consequences of going through the manager (vs. registering on `marked` - * directly) are handled in tagMarkdown.ts: - * - The tokenizer can't see whether it sits inside a link label — the manager - * forwards only `{ inlineTokens, blockTokens }`, not the lexer's `inLink` - * state — so tag-in-link skipping is a tree pass there, mirroring how the - * read-only renderer (remark-tag) skips link nodes. - * - The manager re-registers this tokenizer onto the global `marked` on every - * Editor construction (the accumulation noted in markdownCodec.ts). The - * impact is sub-millisecond for memo-sized content and the test codec is a - * singleton; accepted as the cost of the canonical API. - */ -export const Tag = Mark.create({ - name: "tag", - // Typing immediately after a tag must not extend it. - inclusive: false, - // Serializer emits the inner text verbatim, without escaping. - code: true, - - addAttributes() { - return { - // The tag name without `#`, for downstream consumers (e.g. suggestion - // insertion). Stored as `tag` but rendered/parsed as `data-tag`. - tag: { - default: "", - parseHTML: (element) => element.getAttribute("data-tag") ?? "", - renderHTML: (attributes) => ({ "data-tag": attributes.tag }), - }, - }; - }, - - parseHTML() { - return [{ tag: "span[data-tag]" }]; - }, - - renderHTML({ HTMLAttributes }) { - return [ - "span", - mergeAttributes(HTMLAttributes, { - class: TAG_CLASS, - }), - 0, - ]; - }, - - addInputRules() { - return [ - new InputRule({ - find: TAG_INPUT_RULE, - handler: ({ state, range, match }) => { - // The match may include a leading separator — only mark from the - // `#`. The trailing space stays outside the mark; because the - // handler produces steps the typed space is suppressed, so it is - // re-inserted explicitly after the marked range. - const start = range.from + match[0].indexOf("#"); - state.tr - .addMark(start, range.to, this.type.create({ tag: match[1] })) - .insertText(" ", range.to) - .removeStoredMark(this.type); - }, - }), - ]; - }, - - markdownTokenizer: { - name: "memoTag", - level: "inline", - start: (src: string) => src.indexOf("#"), - tokenize: (src: string) => { - const match = TAG_TOKEN_RULE.exec(src); - if (!match) { - return undefined; - } - // `#a#b`: decline when the run is directly followed by another `#`, so the - // FIRST run stays plain text "#a" + tag "b" (`##x` likewise → text "#" + - // tag "x"). The serialize-escape then escapes the tag-shaped literal "#a", - // so `#a#b` round-trips as `\#a#b` — doc-equivalent and stable thereafter. - // (An over-long run already declines: TAG_RUN's lookahead fails to match.) - if (src.slice(match[0].length).startsWith("#")) { - return undefined; - } - return { type: "memoTag", raw: match[0], tag: match[1] }; - }, - }, - markdownTokenName: "memoTag", - parseMarkdown: (token, helpers) => { - const t = token as MarkdownToken & { tag?: string }; - return helpers.createTextNode(t.raw ?? "", [{ type: "tag", attrs: { tag: t.tag ?? "" } }]); - }, - // No delimiters: the literal `#tag` text carries the syntax. - renderMarkdown: (node, helpers) => (node.content ? helpers.renderChildren(node.content) : ""), -}); diff --git a/web/src/components/MemoEditor/Editor/TagSuggestion.ts b/web/src/components/MemoEditor/Editor/TagSuggestion.ts deleted file mode 100644 index 94f72357..00000000 --- a/web/src/components/MemoEditor/Editor/TagSuggestion.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { createElement } from "react"; -import { createSuggestionExtension } from "./suggestionExtension"; - -export interface TagSuggestionOptions { - /** Getter (not a snapshot) so the popup always sees freshly fetched tags. */ - getTags: () => string[]; -} - -const MAX_SUGGESTIONS = 20; - -/** `#` popup backed by the user's existing tags; inserts tag-marked text + a space. */ -export function createTagSuggestion({ getTags }: TagSuggestionOptions) { - return createSuggestionExtension({ - name: "tagSuggestion", - char: "#", - allowSpaces: false, - items: (query) => { - // Require at least one char after `#` so a bare `#` (or `# ` heading) - // doesn't pop the tag menu and conflict with markdown headings. - if (query.length === 0) { - return []; - } - const q = query.toLowerCase(); - return getTags() - .filter((tag) => tag.toLowerCase().includes(q)) - .slice(0, MAX_SUGGESTIONS); - }, - command: ({ editor, range, props: tag }) => { - editor - .chain() - .focus() - .insertContentAt(range, [ - { type: "text", text: `#${tag}`, marks: [{ type: "tag", attrs: { tag } }] }, - { type: "text", text: " " }, - ]) - .run(); - }, - renderItem: (tag) => - createElement("span", { className: "truncate" }, createElement("span", { className: "text-muted-foreground mr-1" }, "#"), tag), - getItemKey: (tag) => tag, - }); -} diff --git a/web/src/components/MemoEditor/Editor/controller.ts b/web/src/components/MemoEditor/Editor/controller.ts new file mode 100644 index 00000000..759477ce --- /dev/null +++ b/web/src/components/MemoEditor/Editor/controller.ts @@ -0,0 +1,37 @@ +import { EditorSelection, type EditorState } from "@codemirror/state"; +import { EditorView } from "@codemirror/view"; +import type { EditorController, FormattingController } from "../types/editorController"; + +const isEmptyDoc = (state: EditorState) => state.doc.toString().trim() === ""; + +/** Block padding for insertMarkdown: ensure the inserted text is its own block. */ +function blockPad(before: string, after: string): { prefix: string; suffix: string } { + const prefix = before.length === 0 || before.endsWith("\n\n") ? "" : before.endsWith("\n") ? "\n" : "\n\n"; + const suffix = after.length === 0 || after.startsWith("\n\n") ? "" : after.startsWith("\n") ? "\n" : "\n\n"; + return { prefix, suffix }; +} + +export function createController(view: EditorView, formatting: FormattingController): EditorController { + return { + focus: () => view.focus(), + hasFocus: () => view.hasFocus, + isEmpty: () => isEmptyDoc(view.state), + getMarkdown: () => view.state.doc.toString(), + setMarkdown: (markdown) => { + view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: markdown } }); + }, + insertMarkdown: (markdown) => { + if (!markdown) return; + const { from, to } = view.state.selection.main; + const doc = view.state.doc.toString(); + const { prefix, suffix } = blockPad(doc.slice(0, from), doc.slice(to)); + const insert = prefix + markdown + suffix; + const caret = from + insert.length; + view.dispatch({ changes: { from, to, insert }, selection: { anchor: caret }, scrollIntoView: true }); + view.focus(); + }, + scrollToCursor: () => view.dispatch({ effects: EditorView.scrollIntoView(view.state.selection.main.head) }), + selectAll: () => view.dispatch({ selection: EditorSelection.range(0, view.state.doc.length) }), + formatting, + }; +} diff --git a/web/src/components/MemoEditor/Editor/editor.css b/web/src/components/MemoEditor/Editor/editor.css new file mode 100644 index 00000000..52f1ab89 --- /dev/null +++ b/web/src/components/MemoEditor/Editor/editor.css @@ -0,0 +1,133 @@ +/* + * Styling for the CodeMirror source editor, in plain CSS with the app's theme + * variables — the same model Obsidian / GitHub use for an app-integrated CM6 + * editor (class-based tokens + CSS, not a CSS-in-JS theme). Co-located with the + * component and scoped to its wrapper so nothing leaks to other CM instances. + * + * Token classes (.cm-md-*) come from the tagHighlighter in theme.ts; heading + * line classes (.cm-md-h*) from headingDecorations.ts; #tag/@mention + * (.cm-memo-*) from tagMentionDecorations.ts; the rest are CodeMirror's own. + */ +.memo-editor-content { + & .cm-editor { + background: transparent; + font-size: 1rem; + } + & .cm-editor.cm-focused { + outline: none; + } + & .cm-content { + font-family: inherit; + padding: 0; + caret-color: var(--foreground); + } + & .cm-line { + padding: 0; + } + & .cm-scroller { + font-family: inherit; + line-height: 1.5; + } + & .cm-placeholder { + color: var(--muted-foreground); + opacity: 0.7; + } + + /* drawSelection() caret + selection (no base color theme is loaded). */ + & .cm-cursor, + & .cm-dropCursor { + border-left-color: var(--foreground); + } + & .cm-selectionBackground, + & .cm-focused .cm-selectionBackground { + background: var(--accent); + } + + /* Markdown tokens. Markers (#, *, fences, bullets) stay visible but muted + (.cm-md-mark); styled text leads. */ + & .cm-md-strong { + font-weight: 700; + } + & .cm-md-emphasis { + font-style: italic; + } + & .cm-md-strike { + text-decoration: line-through; + } + & .cm-md-code { + font-family: var(--font-mono, monospace); + color: var(--foreground); + } + & .cm-md-link { + color: var(--primary); + text-decoration: underline; + } + & .cm-md-url { + color: var(--muted-foreground); + } + & .cm-md-quote { + color: var(--muted-foreground); + font-style: italic; + } + & .cm-md-mark { + color: var(--muted-foreground); + } + + /* Heading lines (require a space after the hashes; headingDecorations.ts). */ + & .cm-md-h1 { + font-size: 1.5em; + font-weight: 600; + line-height: 1.3; + } + & .cm-md-h2 { + font-size: 1.3em; + font-weight: 600; + } + & .cm-md-h3 { + font-size: 1.15em; + font-weight: 600; + } + & .cm-md-h4, + & .cm-md-h5, + & .cm-md-h6 { + font-weight: 600; + } + + /* #tag / @mention decorations. */ + & .cm-memo-tag, + & .cm-memo-mention { + color: var(--primary); + } + + /* Tag autocomplete popover — app surface, not CodeMirror defaults. */ + & .cm-tooltip.cm-tooltip-autocomplete { + background: var(--popover); + color: var(--popover-foreground); + border: 1px solid var(--border); + border-radius: 0.5rem; + box-shadow: var(--shadow-md); + overflow: hidden; + font-family: inherit; + font-size: 0.9rem; + } + & .cm-tooltip-autocomplete > ul { + font-family: inherit; + color: var(--popover-foreground); + } + & .cm-tooltip-autocomplete > ul > li { + padding: 0.25rem 0.5rem; + color: var(--popover-foreground); + } + & .cm-tooltip-autocomplete > ul > li[aria-selected] { + background: var(--accent); + color: var(--accent-foreground); + } + & .cm-completionIcon { + display: none; + } + & .cm-completionMatchedText { + text-decoration: none; + font-weight: 600; + color: inherit; + } +} diff --git a/web/src/components/MemoEditor/Editor/extensions.ts b/web/src/components/MemoEditor/Editor/extensions.ts index d24f40e7..395b7663 100644 --- a/web/src/components/MemoEditor/Editor/extensions.ts +++ b/web/src/components/MemoEditor/Editor/extensions.ts @@ -1,55 +1,67 @@ -import { type AnyExtension, mergeAttributes } from "@tiptap/core"; -import { Heading } from "@tiptap/extension-heading"; -import { TaskItem, TaskList } from "@tiptap/extension-list"; -import StarterKit from "@tiptap/starter-kit"; -import { type HeadingLevel, headingClass, markdownStyles } from "@/lib/markdownStyles"; -import { Mention } from "./Mention"; -import { preservedExtensions } from "./PreservedBlock"; -import { Tag } from "./Tag"; -import { TagAwareMarkdown } from "./tagMarkdown"; +import { defaultKeymap, history, historyKeymap, indentWithTab } from "@codemirror/commands"; +import { markdown } from "@codemirror/lang-markdown"; +import { indentUnit } from "@codemirror/language"; +import { EditorState, type Extension } from "@codemirror/state"; +import { placeholder as cmPlaceholder, drawSelection, dropCursor, EditorView, type KeyBinding, keymap } from "@codemirror/view"; +import { GFM } from "@lezer/markdown"; +import { headingDecorations } from "./headingDecorations"; +import { liftListItem, sinkListItem } from "./listIndent"; +import { tagAutocomplete } from "./tagAutocomplete"; +import { tagMentionDecorations } from "./tagMentionDecorations"; +import { memoEditorTheme } from "./theme"; -/** - * StarterKit's Heading is bundled and cannot vary classes by level via static - * HTMLAttributes, so we disable it (heading: false) and render headings here. - * renderHTML only affects the editable DOM — heading markdown serialization is - * unchanged — so the round-trip codec is unaffected. - */ -const StyledHeading = Heading.extend({ - renderHTML({ node, HTMLAttributes }) { - const { levels } = this.options; - const level = (levels.includes(node.attrs.level) ? node.attrs.level : levels[0]) as HeadingLevel; - return [`h${level}`, mergeAttributes(this.options.HTMLAttributes, HTMLAttributes, { class: headingClass(level) }), 0]; +// Key bindings layered below the autocomplete keymap so the completion popup's +// own Tab/Escape win while it is open. On a list item, Tab/Shift-Tab nest / +// outdent it (marker-aware, CommonMark-valid); elsewhere they fall through to +// indentWithTab's plain indent. Escape blurs the editor so keyboard users keep +// an escape hatch out of the otherwise Tab-trapping editor. +const editorKeys: KeyBinding[] = [ + { + key: "Escape", + run: (view) => { + view.contentDOM.blur(); + return true; + }, }, -}); + { key: "Tab", run: sinkListItem }, + { key: "Shift-Tab", run: liftListItem }, +]; -/** - * The canonical schema-relevant extension set, shared by the live editor and - * the headless markdown codec so that parse/serialize behavior is identical - * in both. UI-only extensions (Placeholder, suggestion popups) are added by - * the editor component on top of this list and must never affect the schema. - */ -export function buildExtensions(): AnyExtension[] { +export interface EditorExtensionsOptions { + placeholder: string; + onChange: (markdown: string) => void; + onUpdate: () => void; + getTags: () => string[]; +} + +export function buildEditorExtensions({ placeholder, onChange, onUpdate, getTags }: EditorExtensionsOptions): Extension[] { return [ - StarterKit.configure({ - heading: false, - link: { openOnClick: false, HTMLAttributes: { class: markdownStyles.link } }, - // Markdown has no underline syntax; keeping the extension would let - // Ctrl+U create marks that cannot serialize. Out of the schema entirely. - underline: false, - paragraph: { HTMLAttributes: { class: markdownStyles.paragraph } }, - blockquote: { HTMLAttributes: { class: markdownStyles.blockquote } }, - bulletList: { HTMLAttributes: { class: markdownStyles.bulletList } }, - orderedList: { HTMLAttributes: { class: markdownStyles.orderedList } }, - listItem: { HTMLAttributes: { class: markdownStyles.listItem } }, - code: { HTMLAttributes: { class: markdownStyles.inlineCode } }, - horizontalRule: { HTMLAttributes: { class: markdownStyles.horizontalRule } }, + // Core editing behavior. Without these the editor relies on raw + // contenteditable: typing works but there is no visible caret on focus + // (drawSelection), no undo/redo (history), and Enter/selection/word-motion + // keys are unwired (defaultKeymap). They are NOT part of CodeMirror's + // minimal core — basicSetup bundles them, and we assemble them here. + history(), + drawSelection(), + dropCursor(), + EditorState.allowMultipleSelections.of(true), + // Indent with spaces (markdown), matching the 2-space bullet nesting. + indentUnit.of(" "), + markdown({ extensions: [GFM] }), + ...memoEditorTheme, + EditorView.lineWrapping, + cmPlaceholder(placeholder), + tagMentionDecorations, + headingDecorations, + // tagAutocomplete must precede the editing keymap so the completion popup's + // Enter/Tab/arrow bindings win while it is open. + tagAutocomplete(getTags), + keymap.of([...editorKeys, indentWithTab, ...defaultKeymap, ...historyKeymap]), + EditorView.updateListener.of((u) => { + if (u.docChanged) onChange(u.state.doc.toString()); + // Toolbar active-state depends only on the doc and selection; skip the + // getActiveFormats tree walk on focus/viewport/measure-only updates. + if (u.docChanged || u.selectionSet) onUpdate(); }), - StyledHeading.configure({ levels: [1, 2, 3, 4, 5, 6] }), - TaskList, - TaskItem.configure({ nested: true }), - TagAwareMarkdown, - ...preservedExtensions, - Tag, - Mention, ]; } diff --git a/web/src/components/MemoEditor/Editor/formatting.ts b/web/src/components/MemoEditor/Editor/formatting.ts new file mode 100644 index 00000000..c9f1a530 --- /dev/null +++ b/web/src/components/MemoEditor/Editor/formatting.ts @@ -0,0 +1,138 @@ +import { syntaxTree } from "@codemirror/language"; +import type { EditorView } from "@codemirror/view"; +import { + type ActiveFormatState, + type EditorCommandContext, + type EditorCommandId, + EMPTY_ACTIVE_FORMATS, + type ToolbarHeadingLevel, +} from "../formatting/commands"; +import type { FormattingController } from "../types/editorController"; + +const MARK: Partial> = { bold: "**", italic: "*", code: "`" }; +const LINE_PREFIX: Partial> = { bulletList: "- ", orderedList: "1. ", taskList: "- [ ] " }; + +// Enclosing syntax-tree node and the delimiter child node for each inline mark. +// Delimiter names verified empirically against the Lezer markdown parser: +// StrongEmphasis/Emphasis use `EmphasisMark`, InlineCode uses `CodeMark`. +const MARK_NODES: Partial> = { + bold: { wrapper: "StrongEmphasis", delimiter: "EmphasisMark" }, + italic: { wrapper: "Emphasis", delimiter: "EmphasisMark" }, + code: { wrapper: "InlineCode", delimiter: "CodeMark" }, +}; + +function wrapSelection(view: EditorView, token: string) { + const { from, to } = view.state.selection.main; + const sel = view.state.sliceDoc(from, to); + view.dispatch({ + changes: { from, to, insert: `${token}${sel}${token}` }, + selection: { anchor: from + token.length, head: from + token.length + sel.length }, + }); +} + +/** + * Toggle an inline mark (bold/italic/code). When the selection head already sits + * inside the corresponding mark, strip the surrounding delimiter nodes instead of + * nesting a new pair. Deleting the actual delimiter child ranges handles the + * differing delimiter lengths (`**` vs `*` vs `` ` ``) automatically. + */ +function toggleMark(view: EditorView, command: EditorCommandId, token: string) { + const nodes = MARK_NODES[command]; + if (nodes) { + const head = view.state.selection.main.head; + const tree = syntaxTree(view.state); + for (let n: ReturnType | null = tree.resolve(head, -1); n; n = n.parent) { + if (n.name !== nodes.wrapper) continue; + // Collect the opening and closing delimiter child node ranges. + const marks: { from: number; to: number }[] = []; + for (let child = n.firstChild; child; child = child.nextSibling) { + if (child.name === nodes.delimiter) marks.push({ from: child.from, to: child.to }); + } + if (marks.length >= 2) { + const opening = marks[0]; + const closing = marks[marks.length - 1]; + // Delete the later range first so the earlier offsets stay valid. + view.dispatch({ + changes: [ + { from: closing.from, to: closing.to, insert: "" }, + { from: opening.from, to: opening.to, insert: "" }, + ], + }); + return; + } + } + } + wrapSelection(view, token); +} + +function toggleLinePrefix(view: EditorView, prefix: string) { + const line = view.state.doc.lineAt(view.state.selection.main.head); + const has = line.text.startsWith(prefix); + view.dispatch({ + changes: has ? { from: line.from, to: line.from + prefix.length, insert: "" } : { from: line.from, insert: prefix }, + }); +} + +function setHeading(view: EditorView, level: number) { + const line = view.state.doc.lineAt(view.state.selection.main.head); + const stripped = line.text.replace(/^#{1,6}\s+/, ""); + const insert = level === 0 ? stripped : `${"#".repeat(level)} ${stripped}`; + view.dispatch({ changes: { from: line.from, to: line.to, insert } }); +} + +export function createFormattingController(view: EditorView, listeners: Set<() => void>): FormattingController { + return { + run(command: EditorCommandId, ctx?: EditorCommandContext) { + const mark = MARK[command]; + if (mark) return toggleMark(view, command, mark); + const prefix = LINE_PREFIX[command]; + if (prefix) return toggleLinePrefix(view, prefix); + if (command === "heading1") return setHeading(view, 1); + if (command === "heading2") return setHeading(view, 2); + if (command === "heading3") return setHeading(view, 3); + if (command === "paragraph") return setHeading(view, 0); + if (command === "link") { + const { from, to } = view.state.selection.main; + const sel = view.state.sliceDoc(from, to); + view.dispatch({ changes: { from, to, insert: `[${sel}](${ctx?.url ?? ""})` } }); + } + }, + getActiveFormats(): ActiveFormatState { + const pos = view.state.selection.main.head; + const tree = syntaxTree(view.state); + const active: ActiveFormatState = { ...EMPTY_ACTIVE_FORMATS }; + for (let n: ReturnType | null = tree.resolve(pos, -1); n; n = n.parent) { + const name = n.name; + if (name === "StrongEmphasis") active.bold = true; + else if (name === "Emphasis") active.italic = true; + else if (name === "InlineCode") active.code = true; + else if (name === "Link") active.link = true; + else if (name === "BulletList") active.bulletList = true; + else if (name === "OrderedList") active.orderedList = true; + else { + const h = /^ATXHeading([1-6])$/.exec(name); + if (h) { + const lvl = Number(h[1]); + if (lvl <= 3) active.headingLevel = lvl as ToolbarHeadingLevel; + } + } + } + const line = view.state.doc.lineAt(pos).text; + if (/^\s*- \[[ xX]\] /.test(line)) { + active.taskList = true; + active.bulletList = false; + } + return active; + }, + getSelectedText() { + const { from, to } = view.state.selection.main; + return view.state.sliceDoc(from, to); + }, + subscribe(listener: () => void) { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; + }, + }; +} diff --git a/web/src/components/MemoEditor/Editor/headingDecorations.ts b/web/src/components/MemoEditor/Editor/headingDecorations.ts new file mode 100644 index 00000000..177436e3 --- /dev/null +++ b/web/src/components/MemoEditor/Editor/headingDecorations.ts @@ -0,0 +1,27 @@ +import { RangeSetBuilder } from "@codemirror/state"; +import { Decoration, type DecorationSet, EditorView } from "@codemirror/view"; +import { viewportDecorations } from "./viewportDecorations"; + +// A heading is a line that starts with 1-6 hashes followed by a space or tab. +// A bare "#" or a "#tag" (no space) is intentionally NOT a heading. +const HEADING_RE = /^(#{1,6})[ \t]/; + +const lineDecorations = [1, 2, 3, 4, 5, 6].map((level) => Decoration.line({ class: `cm-md-h${level}` })); + +function build(view: EditorView): DecorationSet { + const builder = new RangeSetBuilder(); + for (const { from, to } of view.visibleRanges) { + const startLine = view.state.doc.lineAt(from).number; + const endLine = view.state.doc.lineAt(to).number; + for (let n = startLine; n <= endLine; n++) { + const line = view.state.doc.line(n); + const m = HEADING_RE.exec(line.text); + if (m) { + builder.add(line.from, line.from, lineDecorations[m[1].length - 1]); + } + } + } + return builder.finish(); +} + +export const headingDecorations = viewportDecorations(build); diff --git a/web/src/components/MemoEditor/Editor/index.tsx b/web/src/components/MemoEditor/Editor/index.tsx index 71049493..4b13562a 100644 --- a/web/src/components/MemoEditor/Editor/index.tsx +++ b/web/src/components/MemoEditor/Editor/index.tsx @@ -1,261 +1,85 @@ -import { Extension } from "@tiptap/core"; -import { Placeholder } from "@tiptap/extensions"; -import { AllSelection, Plugin, PluginKey, Selection } from "@tiptap/pm/state"; -import type { EditorProps as ProseMirrorEditorProps } from "@tiptap/pm/view"; -import { EditorContent as RichTextContent, useEditor } from "@tiptap/react"; -import { forwardRef, useEffect, useImperativeHandle, useMemo, useRef } from "react"; -import { matchPath } from "react-router-dom"; +import { EditorState } from "@codemirror/state"; +import { EditorView } from "@codemirror/view"; +import { forwardRef, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef } from "react"; import { useTagCounts } from "@/hooks/useUserQueries"; import { cn } from "@/lib/utils"; -import { ROUTES as Routes } from "@/router/routes"; import { EDITOR_HEIGHT } from "../constants"; import type { EditorController } from "../types/editorController"; -import { EDITOR_COMMANDS_BY_ID, EMPTY_ACTIVE_FORMATS, getActiveFormats } from "./editorCommands"; -import { buildExtensions } from "./extensions"; -import { createTagSuggestion } from "./TagSuggestion"; +import { createController } from "./controller"; +import "./editor.css"; +import { buildEditorExtensions } from "./extensions"; +import { createFormattingController } from "./formatting"; -// Mod-Enter is the app-wide "save memo" shortcut (useKeyboard). StarterKit's -// HardBreak extension also binds Mod-Enter to insert a hard break, which would -// mutate the document right before save fires. This extension swallows the -// shortcut (returning true stops further keymap handlers) while preserving -// DOM event bubbling — preventDefault does NOT stopPropagation, so the window- -// level save listener in useKeyboard still receives and handles the keystroke. -// Priority 1000 > HardBreak's default 100, so this handler runs first. -// Shift-Enter still inserts a hard break as expected. -const SaveShortcutPassthrough = Extension.create({ - name: "saveShortcutPassthrough", - priority: 1000, - addKeyboardShortcuts() { - return { - "Mod-Enter": () => true, - }; - }, -}); - -// Ctrl+A makes ProseMirror's whole-document AllSelection. Deleting it -// (Backspace / Delete / Cut) empties the document, but AllSelection.map() -// always returns another AllSelection — so the editor is left holding a -// non-empty selection spanning the now-empty paragraph, which the view paints -// as a "selected" empty block (the reported artifact). After any doc-changing -// edit that leaves an AllSelection behind, collapse it to a caret at the start, -// the same way deleting an ordinary text selection collapses to a cursor. -// The `instanceof AllSelection` guard re-evaluates against the post-collapse -// state, so the appended selection-only transaction is not re-processed. -const CollapseAllSelectionAfterDelete = Extension.create({ - name: "collapseAllSelectionAfterDelete", - addProseMirrorPlugins() { - return [ - new Plugin({ - key: new PluginKey("collapseAllSelectionAfterDelete"), - appendTransaction: (transactions, _oldState, newState) => { - if (!transactions.some((tr) => tr.docChanged) || !(newState.selection instanceof AllSelection)) { - return null; - } - return newState.tr.setSelection(Selection.atStart(newState.doc)); - }, - }), - ]; - }, -}); - -export interface EditorProps { - className?: string; +interface EditorProps { + className: string; initialContent: string; placeholder: string; - isFocusMode?: boolean; onContentChange: (content: string) => void; onPaste: (event: React.ClipboardEvent) => void; + isFocusMode?: boolean; } -/** - * The Document serializer joins/terminates blocks with `\n\n`, so e.g. a task - * list serializes with a trailing blank line. Outer whitespace is meaningless - * at the document level (the round-trip corpus compares modulo outer trim), - * so every markdown string leaving this component is trimmed. - */ -function serializeMarkdown(editor: { getMarkdown: () => string } | null): string { - return (editor?.getMarkdown() ?? "").trim(); -} +const Editor = forwardRef(function Editor(props: EditorProps, ref: React.ForwardedRef) { + const { className, initialContent, placeholder, onContentChange, onPaste, isFocusMode } = props; + const hostRef = useRef(null); + const viewRef = useRef(null); + const controllerRef = useRef(null); + const onChangeRef = useRef(onContentChange); + onChangeRef.current = onContentChange; + const listenersRef = useRef(new Set<() => void>()); + const { data: tagData } = useTagCounts(); + const tags = useMemo(() => Object.keys(tagData ?? {}), [tagData]); + const tagsRef = useRef(tags); + tagsRef.current = tags; -/** - * WYSIWYG memo editor built on ProseMirror. Markdown is the only format - * crossing its boundary: in via setContent(contentType: "markdown"), out via - * serializeMarkdown() on every update. IME, list continuation, input rules, - * and auto-grow are native ProseMirror/contenteditable behavior. - */ -const Editor = forwardRef(function Editor(props, ref) { - const { className, initialContent, placeholder, isFocusMode, onContentChange, onPaste } = props; - - // Last markdown emitted through onContentChange, so the sync effect can - // recognize the parent echoing our own value back without re-serializing. - const lastEmittedRef = useRef(null); - // Stable across editor re-creation so the toolbar can subscribe once. The - // effect below binds the live editor's transaction/selection events to it. - const activeListenersRef = useRef(new Set<() => void>()); - // Read through refs so the memoized extension/editorProps closures below - // always see the latest props (Placeholder decorations recompute per - // transaction; handlePaste resolves per event). - const placeholderRef = useRef(placeholder); - placeholderRef.current = placeholder; - const onPasteRef = useRef(onPaste); - onPasteRef.current = onPaste; - - // On the explore page suggestions include all users' tags; otherwise the - // current user's. - const isExplorePage = useMemo(() => Boolean(matchPath(Routes.EXPLORE, window.location.pathname)), []); - const { data: tagCount = {} } = useTagCounts(!isExplorePage); - const sortedTags = useMemo( - () => - Object.entries(tagCount) - .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])) - .map(([tag]) => tag), - [tagCount], - ); - const tagsRef = useRef([]); - tagsRef.current = sortedTags; - - // Stable option identities so useEditor's compareOptions stays equal across - // renders and the editor skips a needless setOptions/view.setProps pass per - // keystroke. All dynamic values reach the closures through refs above. - // `content` is only consumed at editor creation — later external changes - // flow through the sync effect — so the mount-time value is frozen too. - const mountContentRef = useRef(initialContent); - const extensions = useMemo( - () => [ - ...buildExtensions(), - Placeholder.configure({ placeholder: () => placeholderRef.current }), - createTagSuggestion({ getTags: () => tagsRef.current }), - SaveShortcutPassthrough, - CollapseAllSelectionAfterDelete, - ], - [], - ); - const editorProps = useMemo( - () => ({ - attributes: { - class: "memo-wysiwyg outline-none w-full text-base break-words min-h-6", - }, - handlePaste: (_view, event) => { - const hasFiles = Array.from(event.clipboardData?.items ?? []).some((item) => item.kind === "file"); - if (hasFiles) { - onPasteRef.current(event as unknown as React.ClipboardEvent); - return true; - } - // Text paste (incl. URL-over-selection → link) is handled natively. - return false; - }, - }), - [], - ); - - const editor = useEditor({ - extensions, - content: mountContentRef.current, - contentType: "markdown", - editorProps, - onUpdate: ({ editor: currentEditor }) => { - const markdown = serializeMarkdown(currentEditor); - lastEmittedRef.current = markdown; - onContentChange(markdown); - }, - }); - - // Sync external content changes (e.g. reset after save, draft restore) - // without clobbering the document the user is typing into: only apply when - // the markdown actually differs. - useEffect(() => { - if (!editor) { - return; - } - // Parent echo of our own emission — nothing to sync (O(1) fast path). - // Comparing against the live document instead would race: a keystroke - // landing between the emission and this passive effect would make the - // echo look like an external change and clobber the keystroke/cursor. - if (initialContent === lastEmittedRef.current) { - return; - } - // Never clobber an in-progress IME composition. - if (editor.view.composing) { - return; - } - if (serializeMarkdown(editor) !== initialContent.trim()) { - editor.commands.setContent(initialContent, { contentType: "markdown", emitUpdate: false }); - // A subsequent identical echo of this value is also a no-op. - lastEmittedRef.current = initialContent; - } - }, [initialContent, editor]); - - // Fan editor transactions out to toolbar subscribers so active-state - // highlighting tracks the cursor live. Every change — including a pure - // selection move — is a transaction, so this single event covers both. - useEffect(() => { - if (!editor) { - return; - } - const notify = () => activeListenersRef.current.forEach((listener) => listener()); - editor.on("transaction", notify); + // useLayoutEffect (not useEffect) so the EditorView — and its placeholder — + // mount before the browser paints. With useEffect the first painted frame + // shows an empty host, then the placeholder pops in (a load flicker). + useLayoutEffect(() => { + if (!hostRef.current) return; + const view = new EditorView({ + state: EditorState.create({ + doc: initialContent, + extensions: buildEditorExtensions({ + placeholder, + onChange: (md) => onChangeRef.current(md), + onUpdate: () => listenersRef.current.forEach((l) => l()), + getTags: () => tagsRef.current, + }), + }), + parent: hostRef.current, + }); + viewRef.current = view; + controllerRef.current = createController(view, createFormattingController(view, listenersRef.current)); return () => { - editor.off("transaction", notify); + view.destroy(); + viewRef.current = null; + controllerRef.current = null; }; - }, [editor]); + // Mount once; external sync handled below. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); - useImperativeHandle( - ref, - (): EditorController => ({ - focus: () => editor?.commands.focus(), - hasFocus: () => editor?.isFocused ?? false, - // Contract: whitespace-only counts as empty. The editor's structural - // `editor.isEmpty` would call a paragraph of spaces non-empty. - isEmpty: () => serializeMarkdown(editor) === "", - getMarkdown: () => serializeMarkdown(editor), - setMarkdown: (markdown) => editor?.commands.setContent(markdown, { contentType: "markdown" }), - insertMarkdown: (markdown) => editor?.chain().focus().insertContent(markdown, { contentType: "markdown" }).run(), - scrollToCursor: () => editor?.commands.scrollIntoView(), - selectAll: () => editor?.commands.selectAll(), - // WYSIWYG supports rich formatting; the whole surface is driven by the - // shared command catalog (editorCommands.ts), so adding a verb there - // flows here — and to the toolbar and active-state — with no edit here. - formatting: { - run: (command, ctx) => { - if (editor) { - EDITOR_COMMANDS_BY_ID[command]?.run(editor, ctx); - } - }, - getActiveFormats: () => (editor ? getActiveFormats(editor) : EMPTY_ACTIVE_FORMATS), - getSelectedText: () => { - if (!editor) { - return ""; - } - const { from, to } = editor.state.selection; - return editor.state.doc.textBetween(from, to, " "); - }, - subscribe: (listener) => { - activeListenersRef.current.add(listener); - return () => { - activeListenersRef.current.delete(listener); - }; - }, - }, - }), - [editor], - ); + useEffect(() => { + const view = viewRef.current; + if (!view) return; + if (view.state.doc.toString() === initialContent) return; + view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: initialContent } }); + }, [initialContent]); + + // The controller is created in the mount layout effect above, which runs + // before this (also layout-phase) handle, so controllerRef.current is set. + useImperativeHandle(ref, () => controllerRef.current as EditorController, []); return (
    { - // In focus mode the wrapper extends below the content; a click on the - // empty area should land the caret at the end instead of doing nothing. - if (event.target === event.currentTarget) { - editor?.commands.focus("end"); - } - }} > - +
    ); }); diff --git a/web/src/components/MemoEditor/Editor/listIndent.ts b/web/src/components/MemoEditor/Editor/listIndent.ts new file mode 100644 index 00000000..21df239a --- /dev/null +++ b/web/src/components/MemoEditor/Editor/listIndent.ts @@ -0,0 +1,119 @@ +import type { Text } from "@codemirror/state"; +import type { EditorView } from "@codemirror/view"; + +// A list item line: leading whitespace + bullet (-, *, +) or ordered marker +// (1. / 1)) + at least one space. +const LIST_ITEM = /^(\s*)(?:[-*+]|\d+[.)])\s/; +const ORDERED_ITEM = /^(\s*)(\d+)([.)])(\s+)(.*)$/; +// The full marker prefix (indent + marker + trailing spaces); its length is the +// column where the item's content — and therefore a nested child — begins. +const LIST_PREFIX = /^\s*(?:[-*+]|\d+[.)])\s+/; + +const leadingWhitespace = (text: string): number => text.length - text.trimStart().length; + +function selectedLineNumbers(view: EditorView): number[] { + const { doc, selection } = view.state; + const nums = new Set(); + for (const range of selection.ranges) { + for (let n = doc.lineAt(range.from).number; n <= doc.lineAt(range.to).number; n++) { + nums.add(n); + } + } + return [...nums]; +} + +/** Preceding lines, nearest first, stopping at the first blank line (list end). */ +function* previousListLines(doc: Text, from: number): Generator<{ text: string; indent: number }> { + for (let p = from - 1; p >= 1; p--) { + const { text } = doc.line(p); + if (text.trim() === "") return; + yield { text, indent: leadingWhitespace(text) }; + } +} + +/** + * The number an ordered item should take at `indent`: one more than the nearest + * preceding sibling ordered item at the same indent, else 1 (first child of a + * new sublist). CommonMark only nests an ordered sublist whose first item is + * `1.`, so renumbering — not just re-indenting — is what makes a nested ordered + * list actually render as nested. + */ +function nextOrderedNumber(doc: Text, lineNumber: number, indent: number): number { + for (const prev of previousListLines(doc, lineNumber)) { + if (prev.indent < indent) break; // reached the parent + if (prev.indent === indent) { + const ordered = ORDERED_ITEM.exec(prev.text); + return ordered ? Number.parseInt(ordered[2], 10) + 1 : 1; + } + // deeper line — part of a sibling's subtree; keep scanning up + } + return 1; +} + +/** Rewrite a list line to a new indent, renumbering it if it is an ordered item. */ +function reindented(doc: Text, lineNumber: number, text: string, indent: number): string { + const ordered = ORDERED_ITEM.exec(text); + if (ordered) { + const [, , , delimiter, spaces, content] = ordered; + return `${" ".repeat(indent)}${nextOrderedNumber(doc, lineNumber, indent)}${delimiter}${spaces}${content}`; + } + return " ".repeat(indent) + text.slice(leadingWhitespace(text)); +} + +/** + * Tab on a list item: nest it under the preceding item by aligning its indent to + * that item's content column (past the marker) and renumbering ordered items so + * the nested list is CommonMark-valid. Returns false when not on a list item so + * the caller's default Tab (plain indent) applies. + */ +export function sinkListItem(view: EditorView): boolean { + const { doc } = view.state; + const changes: { from: number; to: number; insert: string }[] = []; + for (const n of selectedLineNumbers(view)) { + const line = doc.line(n); + const match = LIST_ITEM.exec(line.text); + if (!match) return false; + const indent = match[1].length; + let target = indent + 2; // fallback when there is no item to nest under + for (const prev of previousListLines(doc, n)) { + if (prev.indent > indent) continue; // deeper subtree — skip past it + const prevPrefix = LIST_PREFIX.exec(prev.text); + if (prevPrefix) target = prevPrefix[0].length; + break; + } + if (target > indent) { + changes.push({ from: line.from, to: line.to, insert: reindented(doc, n, line.text, target) }); + } + } + if (changes.length === 0) return false; + view.dispatch({ changes, userEvent: "input.indent" }); + return true; +} + +/** + * Shift-Tab on a list item: outdent it to its parent's indent (or the margin), + * renumbering ordered items for the new level. Returns false when not on an + * indented list item so the default outdent applies. + */ +export function liftListItem(view: EditorView): boolean { + const { doc } = view.state; + const changes: { from: number; to: number; insert: string }[] = []; + for (const n of selectedLineNumbers(view)) { + const line = doc.line(n); + const match = LIST_ITEM.exec(line.text); + if (!match) return false; + const indent = match[1].length; + if (indent === 0) return false; + let target = 0; + for (const prev of previousListLines(doc, n)) { + if (prev.indent < indent) { + target = LIST_ITEM.test(prev.text) ? prev.indent : 0; + break; + } + } + changes.push({ from: line.from, to: line.to, insert: reindented(doc, n, line.text, target) }); + } + if (changes.length === 0) return false; + view.dispatch({ changes, userEvent: "delete.dedent" }); + return true; +} diff --git a/web/src/components/MemoEditor/Editor/markdownCodec.ts b/web/src/components/MemoEditor/Editor/markdownCodec.ts deleted file mode 100644 index 27086f6d..00000000 --- a/web/src/components/MemoEditor/Editor/markdownCodec.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { Editor, type JSONContent } from "@tiptap/core"; -import { buildExtensions } from "./extensions"; - -/** - * Headless markdown ⇄ ProseMirror document helpers built on the exact same - * extension list as the live editor. Used by the round-trip corpus tests and - * the memo-open load guard. - * - * WHY A SINGLETON: - * `@tiptap/markdown`'s MarkdownManager registers each extension's - * `markdownTokenizer` onto the global `marked` singleton via `marked.use(...)` - * inside every `new Editor(...)` construction, and `editor.destroy()` never - * unregisters those tokenizers. `@tiptap/extension-list` ships 2 block - * tokenizers, so every per-call editor construction leaks 2 registrations onto - * the global marked instance. The resulting accumulation causes parse time to - * degrade measurably (observed: ~0.7 s → 14.5 s over ~120 calls). The - * preserved-syntax bridges (PreservedBlock.ts) add more custom tokenizers per - * Editor construction — each live editor mount registers them globally too — - * so the codec singleton keeps the tests/load-guard pinned at one registration. - * - * WHY NOT `Markdown.configure({ marked: new Marked() })`: - * Upstream `MarkdownManager.createLexer()` calls - * `new this.markedInstance.Lexer()` without passing the options object that - * carries the instance-registered tokenizer extensions, so any tokenizers - * registered on the private Marked instance are silently ignored. Task-list - * syntax breaks: `- [ ] open` round-trips to `- open`. - * - * The singleton is created lazily on first use and reused forever. - */ -let _singletonEditor: Editor | null = null; - -function getSingletonEditor(): Editor { - if (!_singletonEditor) { - _singletonEditor = new Editor({ - extensions: buildExtensions(), - content: "", - contentType: "markdown", - }); - } - return _singletonEditor; -} - -function getMarkdownManager() { - const editor = getSingletonEditor(); - if (!editor.markdown) { - throw new Error("markdownCodec: editor.markdown is not available — ensure @tiptap/markdown is in the extension list"); - } - return editor.markdown; -} - -export function parseMarkdown(markdown: string): JSONContent { - return getMarkdownManager().parse(markdown); -} - -export function roundTripMarkdown(markdown: string): string { - const manager = getMarkdownManager(); - return manager.serialize(manager.parse(markdown)); -} - -/** True when a serialize cycle would not change the document's meaning. */ -export function isLosslessRoundTrip(markdown: string): boolean { - try { - const manager = getMarkdownManager(); - const once = manager.parse(markdown); - const twice = manager.parse(manager.serialize(once)); - return JSON.stringify(once) === JSON.stringify(twice); - } catch { - return false; - } -} diff --git a/web/src/components/MemoEditor/Editor/suggestionExtension.ts b/web/src/components/MemoEditor/Editor/suggestionExtension.ts deleted file mode 100644 index fec95d7a..00000000 --- a/web/src/components/MemoEditor/Editor/suggestionExtension.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { Extension } from "@tiptap/core"; -import { PluginKey } from "@tiptap/pm/state"; -import Suggestion, { type SuggestionOptions } from "@tiptap/suggestion"; -import type { ReactNode } from "react"; -import { createSuggestionRenderer } from "./suggestionMenu"; - -/** - * Everything a single `@tiptap/suggestion` trigger needs, minus the boilerplate - * (the Extension wrapper, the PluginKey, and the React popup renderer). Each - * trigger — `#` tags today, `/` commands or `@` mentions tomorrow — is now a - * small config object instead of a hand-wired extension. - */ -export interface SuggestionExtensionConfig { - /** Unique extension + plugin-key name, e.g. "tagSuggestion". */ - name: string; - /** The character that opens the popup, e.g. "#" or "/". */ - char: string; - /** Whether a space inside the query keeps the popup open. Defaults to false. */ - allowSpaces?: boolean; - /** Resolve the items to show for the current query (already stripped of `char`). */ - items: (query: string) => T[]; - /** Apply the chosen item to the document. */ - command: SuggestionOptions["command"]; - /** Render a single item row. */ - renderItem: (item: T, isSelected: boolean) => ReactNode; - /** Stable React key for an item. */ - getItemKey: (item: T) => string; -} - -/** - * Build a Tiptap extension that shows the shared suggestion popup when `char` - * is typed. Mirrors the original hand-written TagSuggestion exactly; it just - * factors out the parts every trigger repeats so adding another is ~10 lines. - */ -export function createSuggestionExtension(config: SuggestionExtensionConfig): Extension { - return Extension.create({ - name: config.name, - - addProseMirrorPlugins() { - return [ - Suggestion({ - editor: this.editor, - pluginKey: new PluginKey(config.name), - char: config.char, - allowSpaces: config.allowSpaces ?? false, - items: ({ query }) => config.items(query), - command: config.command, - render: createSuggestionRenderer({ - renderItem: config.renderItem, - getItemKey: config.getItemKey, - }), - }), - ]; - }, - }); -} diff --git a/web/src/components/MemoEditor/Editor/suggestionMenu.tsx b/web/src/components/MemoEditor/Editor/suggestionMenu.tsx deleted file mode 100644 index 3cf955f0..00000000 --- a/web/src/components/MemoEditor/Editor/suggestionMenu.tsx +++ /dev/null @@ -1,194 +0,0 @@ -import { ReactRenderer } from "@tiptap/react"; -import type { SuggestionKeyDownProps, SuggestionOptions, SuggestionProps } from "@tiptap/suggestion"; -import { - type ForwardRefExoticComponent, - forwardRef, - type PropsWithoutRef, - type ReactElement, - type ReactNode, - type RefAttributes, - useEffect, - useImperativeHandle, - useRef, - useState, -} from "react"; -import { cn } from "@/lib/utils"; - -export interface SuggestionMenuHandle { - onKeyDown: (props: SuggestionKeyDownProps) => boolean; -} - -interface SuggestionMenuProps { - items: T[]; - command: (item: T) => void; - renderItem: (item: T, isSelected: boolean) => ReactNode; - getItemKey: (item: T) => string; -} - -// Floating popup chrome shared by every suggestion trigger (tags today, more later). -const MENU_STYLES = { - container: - "z-50 p-1 max-w-48 max-h-60 rounded border bg-popover text-popover-foreground shadow-lg font-mono flex flex-col overflow-y-auto overflow-x-hidden", - item: "rounded p-1 px-2 w-full text-sm cursor-pointer transition-colors select-none hover:bg-accent hover:text-accent-foreground", -}; - -function SuggestionMenuInner( - { items, command, renderItem, getItemKey }: SuggestionMenuProps, - ref: React.ForwardedRef, -) { - const [selectedIndex, setSelectedIndex] = useState(0); - // Keep a ref so the imperative onKeyDown handler always reads the latest - // selected index even between React batched renders (e.g. Arrow then Enter - // in the same synchronous tick in tests). - const selectedIndexRef = useRef(selectedIndex); - selectedIndexRef.current = selectedIndex; - - // Ref assigned to the currently-highlighted item so we can scroll it into - // view when arrow navigation moves the highlight off-screen. - const selectedItemRef = useRef(null); - - useEffect(() => { - setSelectedIndex(0); - selectedIndexRef.current = 0; - }, [items]); - - // Scroll the highlighted item into view whenever it changes. - useEffect(() => { - selectedItemRef.current?.scrollIntoView?.({ block: "nearest" }); - }, [selectedIndex]); - - useImperativeHandle( - ref, - () => ({ - onKeyDown: ({ event }) => { - if (items.length === 0) { - return false; - } - if (event.key === "ArrowDown") { - const next = (selectedIndexRef.current + 1) % items.length; - selectedIndexRef.current = next; - setSelectedIndex(next); - return true; - } - if (event.key === "ArrowUp") { - const prev = (selectedIndexRef.current - 1 + items.length) % items.length; - selectedIndexRef.current = prev; - setSelectedIndex(prev); - return true; - } - if (event.key === "Enter" || event.key === "Tab") { - command(items[selectedIndexRef.current]); - return true; - } - return false; - }, - }), - [items, command], - ); - - if (items.length === 0) { - return null; - } - - return ( -
    - {items.map((item, index) => ( -
    { - event.preventDefault(); - command(item); - }} - className={cn(MENU_STYLES.item, index === selectedIndex && "bg-accent text-accent-foreground")} - > - {renderItem(item, index === selectedIndex)} -
    - ))} -
    - ); -} - -export const SuggestionMenu = forwardRef(SuggestionMenuInner) as ( - props: SuggestionMenuProps & { ref?: React.ForwardedRef }, -) => ReactElement | null; - -/** - * Builds the Suggestion-plugin `render` lifecycle: mounts SuggestionMenu in a - * floating container positioned at the trigger's caret rect. No tippy — - * a plain absolutely-positioned element on document.body. - */ -export function createSuggestionRenderer(menu: { - renderItem: (item: T, isSelected: boolean) => ReactNode; - getItemKey: (item: T) => string; -}): SuggestionOptions["render"] { - return () => { - let renderer: ReactRenderer | null = null; - let container: HTMLDivElement | null = null; - // Unsubscribes the editor blur listener; null once run (idempotent destroy). - let removeBlurListener: (() => void) | null = null; - - const reposition = (props: SuggestionProps) => { - const rect = props.clientRect?.(); - if (!rect || !container) { - return; - } - container.style.left = `${rect.left + window.scrollX}px`; - container.style.top = `${rect.bottom + window.scrollY + 4}px`; - }; - - const destroy = () => { - removeBlurListener?.(); - removeBlurListener = null; - renderer?.destroy(); - container?.remove(); - renderer = null; - container = null; - }; - - const menuProps = (props: SuggestionProps) => ({ - items: props.items, - command: props.command, - renderItem: menu.renderItem, - getItemKey: menu.getItemKey, - }); - - return { - onStart: (props) => { - // SuggestionMenu is a generic forwardRef component; the ReactRenderer - // constructor expects a concrete ComponentType. We cast via - // top-level type imports for readability (runtime shape is correct). - type MenuProps = ReturnType; - renderer = new ReactRenderer( - SuggestionMenu as unknown as ForwardRefExoticComponent & RefAttributes>, - { - props: menuProps(props), - editor: props.editor, - }, - ); - container = document.createElement("div"); - container.style.position = "absolute"; - container.style.zIndex = "50"; - container.appendChild(renderer.element); - document.body.appendChild(container); - reposition(props); - // Hide the popup when the editor loses focus so it doesn't linger. - const handleBlur = () => destroy(); - props.editor.on("blur", handleBlur); - removeBlurListener = () => props.editor.off("blur", handleBlur); - }, - onUpdate: (props) => { - renderer?.updateProps(menuProps(props)); - reposition(props); - }, - onKeyDown: (props) => { - if (props.event.key === "Escape") { - destroy(); - return true; - } - return renderer?.ref?.onKeyDown(props) ?? false; - }, - onExit: destroy, - }; - }; -} diff --git a/web/src/components/MemoEditor/Editor/tagAutocomplete.ts b/web/src/components/MemoEditor/Editor/tagAutocomplete.ts new file mode 100644 index 00000000..91770f43 --- /dev/null +++ b/web/src/components/MemoEditor/Editor/tagAutocomplete.ts @@ -0,0 +1,25 @@ +import { autocompletion, type CompletionContext, type CompletionResult } from "@codemirror/autocomplete"; +import type { Extension } from "@codemirror/state"; +import { TAG_CHAR_CLASS } from "@/utils/tag-grammar"; + +const TAG_BEFORE = new RegExp(`#(${TAG_CHAR_CLASS}*)$`, "u"); + +export function makeTagCompletionSource(getTags: () => string[]) { + return (ctx: CompletionContext): CompletionResult | null => { + const before = ctx.matchBefore(TAG_BEFORE); + if (!before || (before.from === before.to && !ctx.explicit)) return null; + const typed = before.text.slice(1).toLowerCase(); + // Require at least one character after `#` unless completion was explicitly + // invoked, so a bare `#` doesn't pop the menu while typing. + if (typed.length < 1 && !ctx.explicit) return null; + const options = getTags() + .filter((tag) => tag.toLowerCase().startsWith(typed)) + .map((tag) => ({ label: tag, type: "keyword" })); + if (options.length === 0) return null; + return { from: before.from + 1, options }; + }; +} + +export function tagAutocomplete(getTags: () => string[]): Extension { + return autocompletion({ override: [makeTagCompletionSource(getTags)] }); +} diff --git a/web/src/components/MemoEditor/Editor/tagMarkdown.ts b/web/src/components/MemoEditor/Editor/tagMarkdown.ts deleted file mode 100644 index eedfe463..00000000 --- a/web/src/components/MemoEditor/Editor/tagMarkdown.ts +++ /dev/null @@ -1,113 +0,0 @@ -import type { JSONContent } from "@tiptap/core"; -import { Markdown } from "@tiptap/markdown"; -import type { Schema } from "@tiptap/pm/model"; -import { TAG_RUN } from "@/utils/tag-grammar"; - -// A `#` begins a memo tag when a capped TAG_RUN follows it — the same grammar -// the editor tokenizer (Tag.ts) matches, so escape and parse can't disagree. -// The lookahead matches only the `#`, leaving the run itself untouched. -const TAG_HASH = new RegExp(`#(?=${TAG_RUN})`, "gu"); - -/** - * Backslash-escape a `#` that would otherwise re-parse into a `#tag`. - * - * memos layers hashtag syntax on top of CommonMark, so — exactly as - * prosemirror-markdown escapes inline syntax characters like `*` and `_` — - * plain text that looks like a tag must be escaped on serialize, or it silently - * becomes a tag on the next parse. - */ -export function escapeTagHashes(text: string): string { - return text.replace(TAG_HASH, "\\#"); -} - -type JsonMark = string | { type?: string }; -type JsonNode = { type?: string; marks?: JsonMark[] }; -type PatchableManager = { - encodeTextForMarkdown?: (text: string, node: JsonNode, parentNode?: JsonNode) => string; - parse?: (markdown: string) => JSONContent; -}; - -const markName = (mark: JsonMark): string => (typeof mark === "string" ? mark : (mark.type ?? "")); -const hasMark = (node: JsonNode, name: string): boolean => (node.marks ?? []).some((mark) => markName(mark) === name); - -/** - * A `#tag` only forms in plain inline prose. The tokenizer declines inside - * links, and `code: true` marks/nodes (the Tag mark itself, inline code, - * preserved spans/blocks, code blocks) serialize verbatim — so escaping a `#` - * in any of those contexts would be wrong (and would corrupt the byte-identical - * round-trips those constructs rely on). - */ -function escapesTagsHere(schema: Schema, node: JsonNode, parentNode?: JsonNode): boolean { - for (const mark of node.marks ?? []) { - const name = markName(mark); - if (name === "link") { - return false; - } - if (schema.marks[name]?.spec.code) { - return false; - } - } - const parentType = parentNode?.type; - if (parentType && schema.nodes[parentType]?.spec.code) { - return false; - } - return true; -} - -/** - * Strip the `tag` mark from any text that also carries a `link` mark. - * - * The `markdownTokenizer` in Tag.ts cannot tell it is inside a link label — the - * manager forwards only `{ inlineTokens, blockTokens }`, never the lexer's - * `inLink` state — so `[see #x](url)` parses with `#x` tagged. We undo that as a - * tree pass, the same way the read-only renderer (remark-tag) skips link nodes, - * keeping the editor and renderer in agreement: a `#` in a link label is link - * text, never a tag pill. - */ -function stripTagInsideLinks(node: JSONContent): JSONContent { - if (Array.isArray(node.marks) && hasMark(node, "link")) { - node.marks = node.marks.filter((mark) => markName(mark) !== "tag"); - } - node.content?.forEach(stripTagInsideLinks); - return node; -} - -/** - * The `markdownTokenizer` in Tag.ts handles `#tag` the canonical - * @tiptap/markdown way, but two memos-specific concerns sit above the tokenizer - * and have no public hook, so we compose them onto the manager here: - * - * - serialize: escape a tag-shaped `#` in plain prose ({@link escapeTagHashes}) - * so a literal `#NAS` can't silently re-parse into a tag; - * - parse: skip tags inside link labels ({@link stripTagInsideLinks}). - * - * Escapes stay a purely lexical concern — the document model carries no - * "escaped tag" node or mark. A literal `#NAS` is just text: parsing strips a - * leading `\` (marked's built-in escape) and serializing adds it back, the same - * way TipTap handles every other escapable character. - */ -export const TagAwareMarkdown = Markdown.extend({ - onBeforeCreate(props) { - this.parent?.(props); - const { editor } = this; - const manager = editor.markdown as unknown as PatchableManager | undefined; - if (!manager) { - return; - } - - const encode = manager.encodeTextForMarkdown; - if (typeof encode === "function") { - const bound = encode.bind(manager); - manager.encodeTextForMarkdown = (text, node, parentNode) => { - const encoded = bound(text, node, parentNode); - return escapesTagsHere(editor.schema, node, parentNode) ? escapeTagHashes(encoded) : encoded; - }; - } - - const parse = manager.parse; - if (typeof parse === "function") { - const bound = parse.bind(manager); - manager.parse = (markdown) => stripTagInsideLinks(bound(markdown)); - } - }, -}); diff --git a/web/src/components/MemoEditor/Editor/tagMentionDecorations.ts b/web/src/components/MemoEditor/Editor/tagMentionDecorations.ts new file mode 100644 index 00000000..dc318ddb --- /dev/null +++ b/web/src/components/MemoEditor/Editor/tagMentionDecorations.ts @@ -0,0 +1,34 @@ +import { RangeSetBuilder } from "@codemirror/state"; +import { Decoration, type DecorationSet, EditorView } from "@codemirror/view"; +import { MENTION_RUN } from "@/utils/mention-grammar"; +import { TAG_RUN } from "@/utils/tag-grammar"; +import { viewportDecorations } from "./viewportDecorations"; + +const TAG_RE = new RegExp(`(^|[^\\p{L}\\p{N}])#(${TAG_RUN})`, "gu"); +const MENTION_RE = new RegExp(`(^|[^A-Za-z0-9])@(${MENTION_RUN})`, "gu"); +const tagMark = Decoration.mark({ class: "cm-memo-tag" }); +const mentionMark = Decoration.mark({ class: "cm-memo-mention" }); + +function build(view: EditorView): DecorationSet { + const ranges: { from: number; to: number; deco: Decoration }[] = []; + for (const { from, to } of view.visibleRanges) { + const text = view.state.doc.sliceString(from, to); + for (const [re, deco] of [ + [TAG_RE, tagMark], + [MENTION_RE, mentionMark], + ] as const) { + re.lastIndex = 0; + let m: RegExpExecArray | null; + while ((m = re.exec(text)) !== null) { + const start = from + m.index + m[1].length; // skip the boundary char + ranges.push({ from: start, to: start + 1 + m[2].length, deco }); + } + } + } + ranges.sort((a, b) => a.from - b.from || a.to - b.to); + const builder = new RangeSetBuilder(); + for (const r of ranges) builder.add(r.from, r.to, r.deco); + return builder.finish(); +} + +export const tagMentionDecorations = viewportDecorations(build); diff --git a/web/src/components/MemoEditor/Editor/theme.ts b/web/src/components/MemoEditor/Editor/theme.ts new file mode 100644 index 00000000..18589659 --- /dev/null +++ b/web/src/components/MemoEditor/Editor/theme.ts @@ -0,0 +1,23 @@ +import { syntaxHighlighting } from "@codemirror/language"; +import { tags as t, tagHighlighter } from "@lezer/highlight"; + +/** + * Map markdown syntax tokens to stable class names. ALL visual styling lives in + * plain CSS (the `.memo-editor-content` block in `src/index.css`) so the editor + * is themed like the rest of the app — Tailwind/theme tokens in a stylesheet — + * rather than a CodeMirror CSS-in-JS theme object. Headings (`.cm-md-h*`) and + * `#tag`/`@mention` (`.cm-memo-*`) classes come from the decoration plugins; + * the rest of the `.cm-*` chrome is CodeMirror's own and is styled in that CSS. + */ +const markdownHighlighter = tagHighlighter([ + { tag: t.strong, class: "cm-md-strong" }, + { tag: t.emphasis, class: "cm-md-emphasis" }, + { tag: t.strikethrough, class: "cm-md-strike" }, + { tag: t.monospace, class: "cm-md-code" }, + { tag: t.link, class: "cm-md-link" }, + { tag: t.url, class: "cm-md-url" }, + { tag: t.quote, class: "cm-md-quote" }, + { tag: [t.processingInstruction, t.meta, t.contentSeparator], class: "cm-md-mark" }, +]); + +export const memoEditorTheme = [syntaxHighlighting(markdownHighlighter)]; diff --git a/web/src/components/MemoEditor/Editor/viewportDecorations.ts b/web/src/components/MemoEditor/Editor/viewportDecorations.ts new file mode 100644 index 00000000..78ec7f29 --- /dev/null +++ b/web/src/components/MemoEditor/Editor/viewportDecorations.ts @@ -0,0 +1,23 @@ +import { type DecorationSet, EditorView, ViewPlugin, type ViewUpdate } from "@codemirror/view"; + +/** + * A ViewPlugin that maintains viewport-scoped decorations, rebuilding when the + * document or viewport changes. Shared by the tag/mention and heading + * decoration plugins, which differ only in their `build` function. + */ +export function viewportDecorations(build: (view: EditorView) => DecorationSet) { + return ViewPlugin.fromClass( + class { + decorations: DecorationSet; + constructor(view: EditorView) { + this.decorations = build(view); + } + update(u: ViewUpdate) { + if (u.docChanged || u.viewportChanged) { + this.decorations = build(u.view); + } + } + }, + { decorations: (v) => v.decorations }, + ); +} diff --git a/web/src/components/MemoEditor/PlainEditor/index.tsx b/web/src/components/MemoEditor/PlainEditor/index.tsx deleted file mode 100644 index 86ec3a1e..00000000 --- a/web/src/components/MemoEditor/PlainEditor/index.tsx +++ /dev/null @@ -1,198 +0,0 @@ -import { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef } from "react"; -import getCaretCoordinates from "textarea-caret"; -import { cn } from "@/lib/utils"; -import { EDITOR_HEIGHT } from "../constants"; -import type { EditorController } from "../types/editorController"; - -interface PlainEditorProps { - className: string; - initialContent: string; - placeholder: string; - onContentChange: (content: string) => void; - onPaste: (event: React.ClipboardEvent) => void; - isFocusMode?: boolean; -} - -// Low-level string-surgery handle over the textarea. Internal to this file — -// outside callers only ever see the EditorController exposed via the ref. -interface TextareaActions { - getEditor: () => HTMLTextAreaElement | null; - focus: () => void; - scrollToCursor: () => void; - insertText: (text: string, prefix?: string, suffix?: string) => void; - setContent: (text: string) => void; - getContent: () => string; - getCursorPosition: () => number; - setCursorPosition: (startPos: number, endPos?: number) => void; -} - -const PlainEditor = forwardRef(function PlainEditor(props: PlainEditorProps, ref: React.ForwardedRef) { - const { className, initialContent, placeholder, onPaste, onContentChange: handleContentChangeCallback, isFocusMode } = props; - const editorRef = useRef(null); - - const updateEditorHeight = useCallback(() => { - if (editorRef.current) { - editorRef.current.style.height = "auto"; - editorRef.current.style.height = `${editorRef.current.scrollHeight ?? 0}px`; - } - }, []); - - const updateContent = useCallback(() => { - if (editorRef.current) { - handleContentChangeCallback(editorRef.current.value); - updateEditorHeight(); - } - }, [handleContentChangeCallback, updateEditorHeight]); - - const scrollToCaret = useCallback((options: { force?: boolean } = {}) => { - const editor = editorRef.current; - if (!editor) return; - - const { force = false } = options; - const caret = getCaretCoordinates(editor, editor.selectionEnd); - - if (force) { - editor.scrollTop = Math.max(0, caret.top - editor.clientHeight / 2); - return; - } - - const lineHeight = parseFloat(getComputedStyle(editor).lineHeight) || 24; - const viewportBottom = editor.scrollTop + editor.clientHeight; - // Scroll if cursor is near or beyond bottom edge (within 2 lines) - if (caret.top + lineHeight * 2 > viewportBottom) { - editor.scrollTop = Math.max(0, caret.top - editor.clientHeight / 2); - } - }, []); - - useEffect(() => { - if (editorRef.current && initialContent) { - editorRef.current.value = initialContent; - handleContentChangeCallback(initialContent); - updateEditorHeight(); - } - // Only run once on mount to set initial content - // eslint-disable-next-line react-hooks/exhaustive-deps - }, []); - - // Update editor when content is externally changed (e.g., reset after save) - useEffect(() => { - if (editorRef.current && editorRef.current.value !== initialContent) { - editorRef.current.value = initialContent; - updateEditorHeight(); - } - }, [initialContent, updateEditorHeight]); - - const actions: TextareaActions = useMemo( - () => ({ - getEditor: () => editorRef.current, - focus: () => editorRef.current?.focus(), - scrollToCursor: () => { - scrollToCaret({ force: true }); - }, - insertText: (content = "", prefix = "", suffix = "") => { - const editor = editorRef.current; - if (!editor) return; - - const cursorPos = editor.selectionStart; - const endPos = editor.selectionEnd; - const prev = editor.value; - const actual = content || prev.slice(cursorPos, endPos); - editor.value = prev.slice(0, cursorPos) + prefix + actual + suffix + prev.slice(endPos); - - editor.focus(); - editor.setSelectionRange(cursorPos + prefix.length + actual.length, cursorPos + prefix.length + actual.length); - updateContent(); - }, - setContent: (text: string) => { - const editor = editorRef.current; - if (editor) { - editor.value = text; - updateContent(); - } - }, - getContent: () => editorRef.current?.value ?? "", - getCursorPosition: () => editorRef.current?.selectionStart ?? 0, - setCursorPosition: (startPos: number, endPos?: number) => { - const editor = editorRef.current; - if (!editor) return; - // setSelectionRange requires valid arguments; default to startPos if endPos is undefined - const endPosition = endPos !== undefined && !Number.isNaN(endPos) ? endPos : startPos; - editor.setSelectionRange(startPos, endPosition); - }, - }), - [updateContent, scrollToCaret], - ); - - // The raw textarea is an honest fallback: it realizes only the core - // EditorController surface (markdown in/out, focus, selection) on top of - // textarea string ops. It exposes no `formatting` capability — the focus-mode - // toolbar is WYSIWYG-only — so rich formatting is never faked here. - useImperativeHandle( - ref, - (): EditorController => ({ - focus: () => actions.focus(), - hasFocus: () => { - const element = actions.getEditor(); - return Boolean(element) && document.activeElement === element; - }, - isEmpty: () => actions.getContent().trim() === "", - getMarkdown: () => actions.getContent(), - setMarkdown: (markdown) => actions.setContent(markdown), - insertMarkdown: (markdown) => { - if (!markdown) return; - const content = actions.getContent(); - const cursor = actions.getCursorPosition(); - const before = content.slice(0, cursor); - const after = content.slice(cursor); - const prefix = before.length === 0 || before.endsWith("\n\n") ? "" : before.endsWith("\n") ? "\n" : "\n\n"; - const suffix = after.length === 0 || after.startsWith("\n\n") ? "" : after.startsWith("\n") ? "\n" : "\n\n"; - actions.insertText(markdown, prefix, suffix); - }, - scrollToCursor: () => actions.scrollToCursor(), - selectAll: () => actions.setCursorPosition(0, actions.getContent().length), - }), - [actions], - ); - - const handleEditorInput = useCallback(() => { - if (editorRef.current) { - handleContentChangeCallback(editorRef.current.value); - updateEditorHeight(); - - // Auto-scroll to keep cursor visible when typing - // See: https://github.com/usememos/memos/issues/5469 - scrollToCaret(); - } - }, [handleContentChangeCallback, updateEditorHeight, scrollToCaret]); - - // Recalculate editor height when focus mode changes - useEffect(() => { - updateEditorHeight(); - }, [isFocusMode, updateEditorHeight]); - - return ( -
    - -
    - ); -}); - -export default PlainEditor; diff --git a/web/src/components/MemoEditor/README.md b/web/src/components/MemoEditor/README.md index afbd46a5..64fce3ae 100644 --- a/web/src/components/MemoEditor/README.md +++ b/web/src/components/MemoEditor/README.md @@ -2,7 +2,7 @@ ## Overview -MemoEditor uses a three-layer architecture for better separation of concerns and testability. It ships two editor implementations — a WYSIWYG rich-text editor (Tiptap/ProseMirror, the default) and a plain-text textarea — behind a single `EditorController` contract, so all layers above the editor boundary are mode-agnostic. +MemoEditor is a three-layer component. At its core is a single editor — `Editor/`, a CodeMirror 6 "decorated source" editor. It stores the memo as **raw markdown, verbatim** (no parse/serialize round-trip) and styles that source in place with CodeMirror decorations: the markers (`#`, `*`, `` ` ``, list bullets, fences) stay visible but de-emphasized while the styled text leads. There is one editor and one storage format; everything above the editor boundary talks markdown through the `EditorController` contract. ## Architecture @@ -15,8 +15,8 @@ MemoEditor uses a three-layer architecture for better separation of concerns and ┌─────────────────▼───────────────────────┐ │ State Layer (Reducer + Context) │ │ - state/, useEditorContext() │ -│ - state.content ← markdown (source │ -│ of truth for both editor modes) │ +│ - state.content ← markdown (the │ +│ single source of truth) │ └─────────────────┬───────────────────────┘ │ ┌─────────────────▼───────────────────────┐ @@ -32,29 +32,25 @@ MemoEditor/ ├── state/ # State management (reducer, actions, context) ├── services/ # Business logic (pure functions) ├── components/ # UI components -│ ├── EditorContent.tsx # Hosts the active editor; exposes mode-routing controller -│ ├── EditorToolbar.tsx # Toolbar including the mode toggle button +│ ├── EditorContent.tsx # Hosts Editor; forwards its EditorController ref +│ ├── EditorToolbar.tsx # Toolbar │ └── ... ├── hooks/ # React hooks (utilities) -│ ├── useMemoInit.ts # Initializes editor content; load guard for WYSIWYG -│ └── ... -├── PlainEditor/ # Plain textarea (raw mode) implementation -│ └── index.tsx # Bare textarea implementing EditorController directly -├── Editor/ # Tiptap WYSIWYG implementation (default) -│ ├── index.tsx # Editor component; implements EditorController -│ ├── extensions.ts # Canonical schema-relevant extension set (shared with codec) -│ ├── markdownCodec.ts # Headless parse/serialize helpers (singleton editor) -│ ├── PreservedBlock.ts # Byte-for-byte preservation of tables, math, raw HTML -│ ├── Tag.ts # Memos #tag mark (markdownTokenizer + input rule) -│ ├── tagMarkdown.ts # Tag-aware Markdown: # escape on serialize, link-skip on parse -│ ├── TagSuggestion.ts # # popup for WYSIWYG mode -│ └── suggestionMenu.tsx # Shared suggestion popup renderer (used by TagSuggestion) +├── Editor/ # The CodeMirror 6 decorated-source editor +│ ├── index.tsx # React wrapper: mounts the EditorView, owns the +│ │ # controller refs, syncs initialContent in/out +│ ├── extensions.ts # buildEditorExtensions(): assembles the CM extension set +│ ├── theme.ts # Syntax-highlight style + editor theme (CSS-var colors) +│ ├── tagMentionDecorations.ts# ViewPlugin that decorates #tag / @mention spans +│ ├── tagAutocomplete.ts # CM autocompletion source for #tag +│ ├── formatting.ts # FormattingController impl (toggle marks, headings, lists) +│ └── controller.ts # EditorController impl over an EditorView +├── formatting/ +│ └── commands.ts # Backend-agnostic catalog of formatting verbs ├── Toolbar/ # Toolbar sub-components (InsertMenu, VisibilitySelector) -├── editorMode.ts # EditorMode type + localStorage persistence helpers ├── constants.ts └── types/ - ├── editorController.ts # EditorController interface (the cross-mode contract) - └── ... + └── editorController.ts # EditorController / FormattingController interfaces ``` ## Key Concepts @@ -63,48 +59,32 @@ MemoEditor/ Uses `useReducer` + Context for predictable state transitions. All state changes go through action creators. -`state.content` holds the document as a **markdown string** and is the single source of truth for both editor modes. Each editor serializes its current content into the reducer on every change via `onContentChange`; neither editor reads content back from the other. +`state.content` holds the document as a **markdown string** and is the single source of truth. Because the editor stores markdown verbatim, `state.content` is exactly the editor's document — there is no encoding or normalization step. -### Dual-mode editor +### The editor contract -`types/editorController.ts` defines the `EditorController` interface — `focus`, `getMarkdown`, `setMarkdown`, `insertMarkdown`, formatting toggles, etc. — that callers outside an editor implementation must use exclusively. +`types/editorController.ts` defines `EditorController` — `focus`, `getMarkdown`, `setMarkdown`, `insertMarkdown`, `selectAll`, `scrollToCursor`, plus an optional `formatting` capability. Callers outside the editor implementation use this interface exclusively and never reach into CodeMirror internals. -- **WYSIWYG mode** (`Editor/`): Tiptap/ProseMirror rich-text editor. The default mode. Implements `EditorController` directly via `useImperativeHandle` in `Editor/index.tsx`. -- **Raw mode** (`PlainEditor/`): a bare textarea with no in-editor assistance (no suggestion popups, list continuation, or keyboard markdown shortcuts) — just auto-grow and cursor-visibility scrolling. It implements `EditorController` directly (markdown is just the textarea value), so the toolbar's formatting toggles still work. +`Editor/controller.ts` implements `EditorController` over a CodeMirror `EditorView`: `getMarkdown` is just `view.state.doc.toString()`, `setMarkdown` replaces the whole document, and `insertMarkdown` block-pads the insertion so it lands as its own block. -`components/EditorContent.tsx` hosts whichever implementation `state.ui.editorMode` selects and exposes a single mode-routing `EditorController` facade to the rest of the component tree via `forwardRef`. +`FormattingController` (same file in `types/`) is the rich-formatting surface the focus-mode `FormattingToolbar` drives: `run(commandId, ctx?)`, `getActiveFormats()`, `getSelectedText()`, and `subscribe(listener)`. `Editor/formatting.ts` implements it by editing the markdown source directly — toggling inline marks (`**`/`*`/`` ` ``), line prefixes (`- `, `1. `, `- [ ] `), and ATX heading prefixes (`#`…) — and by reading active state from the Lezer syntax tree at the caret. -### Mode toggle +### Formatting command catalog -The toolbar button in `EditorToolbar.tsx` dispatches `SET_EDITOR_MODE` and calls `setPreferredEditorMode` (from `editorMode.ts`) to persist the preference per device in `localStorage["memos-editor-mode"]`. WYSIWYG is the default when no preference is stored. +`formatting/commands.ts` is the single, editor-agnostic catalog of formatting verbs (`EDITOR_COMMANDS`, `EditorCommandId`, `ActiveFormatState`, `isCommandActive`). It is metadata only — labels (i18n keys), icons, and grouping — with no dependency on any concrete editor. The toolbar and the active-state highlighting derive everything from this catalog; `Editor/formatting.ts` supplies how each verb is applied to the live CodeMirror document. To add a verb, add one entry here (and its field on `ActiveFormatState`). -Mode switching is a markdown handoff: because both editors write into `state.content` on every keystroke, the incoming editor simply initializes from it — no content is ever pushed between editors directly. +### Editor extensions -### Markdown fidelity layer (Editor) +`Editor/extensions.ts` exports `buildEditorExtensions()`, which composes the CodeMirror extension set: `@codemirror/lang-markdown` (with GFM), line wrapping, a placeholder, the editor theme, the `#tag`/`@mention` decoration plugin, the `#tag` autocomplete, and an update listener that pushes document changes back to the reducer via `onChange`. -`Editor/extensions.ts` exports `buildExtensions()`, the canonical schema-relevant extension set. It is shared by the live editor and the headless `markdownCodec.ts` (parse/serialize/round-trip helpers over a singleton Tiptap instance) so parse and serialize behavior is identical in both contexts. +`Editor/theme.ts` defines the decorated-source look: a `HighlightStyle` over the Lezer markdown highlight tags (headings, strong, emphasis, code, links, quotes, markers) and an `EditorView.theme`. Colors come from CSS custom properties so light/dark themes just work. This is the editor's own styling — the read-only memo view styles itself separately via `@/lib/markdownStyles`. -`PreservedBlock.ts` handles syntax the WYSIWYG editor does not model richly: tables, `$$math$$`, and raw HTML are captured at parse time with their raw markdown source, shown as editable monospace literal text, and re-emitted byte-for-byte on serialize. +### Tags and mentions -`Tag.ts` models memos `#tags` as a `code: true` text mark, letting tags round-trip byte-identically even inside bold or heading spans. Its `#tag` lexing is a `markdownTokenizer` (the canonical `@tiptap/markdown` extension point); `tagMarkdown.ts` adds the two things that tokenizer can't do — on serialize it backslash-escapes a literal `#` that would otherwise re-parse into a tag (escapes are lexical, so there is no "escaped tag" node), and on parse it strips the tag mark from text inside link labels. The `#tag` grammar itself lives once in `utils/tag-grammar.ts` (`TAG_RUN`), shared by the tokenizer, the serialize-escape, and the read-only `remark-tag` renderer so they can't drift. +`#tag` autocomplete and `#tag`/`@mention` decoration both reuse the shared grammar so the editor can't drift from the rest of the app: -### Why the markdown manager is worked around in several places - -`@tiptap/markdown` (3.26.0) exposes no public, per-instance hook for custom tokenizers or for text escaping, and it registers each extension's tokenizer onto the **global** `marked` singleton on every `new Editor()` — registrations it never removes. That one limitation is the reason for three otherwise-surprising choices, each documented in detail at its call site: - -- **`markdownCodec.ts` keeps a single editor instance** — re-creating editors would leak tokenizer registrations onto global `marked` and measurably degrade parse time. -- **`PreservedBlock.ts` registers its tokenizers on `marked` once at module scope** (idempotent) instead of via the per-extension `markdownTokenizer`, to avoid that per-construction accumulation. -- **`tagMarkdown.ts` composes onto the manager in `onBeforeCreate`** (escape, link-skip) because the relevant manager methods are `private` with no public seam. - -`Tag.ts` deliberately uses the canonical `markdownTokenizer` API and accepts the per-construction re-registration as its cost; `PreservedBlock.ts` refuses it for its seven tokenizers. The asymmetry is intentional — collapse both onto one path if upstream ever ships a public per-instance tokenizer hook. - -### Suggestions - -The `#` tag suggestion popup is a **WYSIWYG-only** feature: `Editor/TagSuggestion.ts`, using the shared `Editor/suggestionMenu.tsx` renderer. Raw mode is a plain textarea with no suggestions. (Formatting actions that a `/` command menu would once have offered — lists, code, link — are now available from the focus-mode `FormattingToolbar` header.) - -### Load guard - -`hooks/useMemoInit.ts` runs a round-trip check on every existing memo when the editor opens. If the preferred mode is WYSIWYG and `isLosslessRoundTrip` (from `markdownCodec.ts`) returns false for the memo's content, the editor falls back to raw mode for that session only (preference is not changed) and shows a toast. This is a safety net; the corpus tests are designed to make it never fire in practice. +- `Editor/tagMentionDecorations.ts` is a `ViewPlugin` that scans the visible ranges and adds `cm-memo-tag` / `cm-memo-mention` marks, matching against `TAG_RUN` (`@/utils/tag-grammar`) and `MENTION_RUN` (`@/utils/mention-grammar`). +- `Editor/tagAutocomplete.ts` is a CodeMirror autocompletion source for `#tag`, matching the in-progress token with `TAG_CHAR_CLASS` (`@/utils/tag-grammar`) and offering known tags (from `useTagCounts`). ### Services @@ -114,13 +94,6 @@ Pure TypeScript functions containing business logic. No React hooks, easy to tes Thin presentation components that dispatch actions and render UI. -## Markdown fidelity contract - -The round-trip corpus tests in `web/tests/markdown-roundtrip.test.ts`, backed by fixtures under `web/tests/fixtures/markdown-corpus/`, enforce two guarantees: - -- **Supported syntax** (`supported/`): a parse → serialize → parse cycle produces an identical document tree (semantic equality; marker style may normalize). -- **Preserved syntax** (`preserved/`): tables, math, and raw HTML round-trip byte-for-byte. - ## Usage ```typescript diff --git a/web/src/components/MemoEditor/components/EditorToolbar.tsx b/web/src/components/MemoEditor/Toolbar/EditorToolbar.tsx similarity index 95% rename from web/src/components/MemoEditor/components/EditorToolbar.tsx rename to web/src/components/MemoEditor/Toolbar/EditorToolbar.tsx index 866a009e..a216df93 100644 --- a/web/src/components/MemoEditor/components/EditorToolbar.tsx +++ b/web/src/components/MemoEditor/Toolbar/EditorToolbar.tsx @@ -4,9 +4,9 @@ import type { Location, Visibility } from "@/types/proto/api/v1/memo_service_pb" import { useTranslate } from "@/utils/i18n"; import { validationService } from "../services"; import { useEditorContext, useEditorSelector } from "../state"; -import InsertMenu from "../Toolbar/InsertMenu"; -import VisibilitySelector from "../Toolbar/VisibilitySelector"; import type { EditorToolbarProps } from "../types"; +import InsertMenu from "./InsertMenu"; +import VisibilitySelector from "./VisibilitySelector"; export const EditorToolbar: FC = ({ onSave, onCancel, memoName, onAudioRecorderClick }) => { const t = useTranslate(); diff --git a/web/src/components/MemoEditor/components/FormattingToolbar.tsx b/web/src/components/MemoEditor/Toolbar/FormattingToolbar.tsx similarity index 95% rename from web/src/components/MemoEditor/components/FormattingToolbar.tsx rename to web/src/components/MemoEditor/Toolbar/FormattingToolbar.tsx index 4a0a49bf..185a059e 100644 --- a/web/src/components/MemoEditor/components/FormattingToolbar.tsx +++ b/web/src/components/MemoEditor/Toolbar/FormattingToolbar.tsx @@ -10,15 +10,9 @@ import { } from "@/components/ui/dropdown-menu"; import { cn } from "@/lib/utils"; import { useTranslate } from "@/utils/i18n"; -import { - EDITOR_COMMANDS, - EDITOR_COMMANDS_BY_ID, - type EditorCommand, - type EditorCommandId, - isCommandActive, -} from "../Editor/editorCommands"; +import { EDITOR_COMMANDS, EDITOR_COMMANDS_BY_ID, type EditorCommand, type EditorCommandId, isCommandActive } from "../formatting/commands"; import { isCompactWidth, useEditorActiveState, useElementWidth } from "../hooks"; -import type { EditorController } from "../types/editorController"; +import type { EditorController } from "../types"; interface FormattingToolbarProps { controllerRef: RefObject; @@ -42,7 +36,7 @@ interface ToolbarButton { /** * Focus-mode header: a rich-text formatting toolbar driven entirely through the * editor controller's formatting capability. Every button is derived from the - * shared command catalog (Editor/editorCommands.ts), so adding a verb there + * shared command catalog (formatting/commands.ts), so adding a verb there * surfaces it here automatically. Responsive: below COMPACT_TOOLBAR_WIDTH the * list and link controls fold into a "more" menu while marks stay inline. */ diff --git a/web/src/components/MemoEditor/Toolbar/InsertMenu.tsx b/web/src/components/MemoEditor/Toolbar/InsertMenu.tsx index 79ac72e0..e6a9be6d 100644 --- a/web/src/components/MemoEditor/Toolbar/InsertMenu.tsx +++ b/web/src/components/MemoEditor/Toolbar/InsertMenu.tsx @@ -18,7 +18,6 @@ import { useReverseGeocoding } from "@/components/map/useReverseGeocoding"; import { Button } from "@/components/ui/button"; import { DropdownMenu, - DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, @@ -31,7 +30,6 @@ import { import { useDebouncedEffect } from "@/hooks"; import type { MemoRelation } from "@/types/proto/api/v1/memo_service_pb"; import { useTranslate } from "@/utils/i18n"; -import { setPreferredEditorMode } from "../editorMode"; import { useFileUpload, useLinkMemo, useLocation } from "../hooks"; import { useEditorContext, useEditorSelector } from "../state"; import type { InsertMenuProps } from "../types"; @@ -41,7 +39,6 @@ const InsertMenu = (props: InsertMenuProps) => { const t = useTranslate(); const { actions, dispatch } = useEditorContext(); const relations = useEditorSelector((s) => s.metadata.relations); - const editorMode = useEditorSelector((s) => s.ui.editorMode); const { location: initialLocation, onLocationChange, onToggleFocusMode, isUploading: isUploadingProp } = props; const [linkDialogOpen, setLinkDialogOpen] = useState(false); @@ -136,15 +133,6 @@ const InsertMenu = (props: InsertMenuProps) => { setMoreSubmenuOpen(false); }, [onToggleFocusMode]); - const handleEditorModeChange = useCallback( - (checked: boolean) => { - const next = checked ? "wysiwyg" : "raw"; - dispatch(actions.setEditorMode(next)); - setPreferredEditorMode(next); - }, - [actions, dispatch], - ); - const handleMediaUploadClick = useCallback(() => { handleUploadClick("image/*,video/*"); }, [handleUploadClick]); @@ -224,10 +212,6 @@ const InsertMenu = (props: InsertMenuProps) => { {t("editor.focus-mode")} - {/* Editor display mode: checked = rich text (WYSIWYG), unchecked = raw Markdown */} - - {t("editor.wysiwyg-editor")} - diff --git a/web/src/components/MemoEditor/Toolbar/index.ts b/web/src/components/MemoEditor/Toolbar/index.ts index 35034fc8..676ca402 100644 --- a/web/src/components/MemoEditor/Toolbar/index.ts +++ b/web/src/components/MemoEditor/Toolbar/index.ts @@ -1,3 +1,5 @@ // Toolbar components for MemoEditor +export { EditorToolbar } from "./EditorToolbar"; +export { FormattingToolbar } from "./FormattingToolbar"; export { default as InsertMenu } from "./InsertMenu"; export { default as VisibilitySelector } from "./VisibilitySelector"; diff --git a/web/src/components/MemoEditor/components/AudioRecorderPanel.tsx b/web/src/components/MemoEditor/components/AudioRecorderPanel.tsx index f153f670..014210ab 100644 --- a/web/src/components/MemoEditor/components/AudioRecorderPanel.tsx +++ b/web/src/components/MemoEditor/components/AudioRecorderPanel.tsx @@ -6,7 +6,7 @@ import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip import { cn } from "@/lib/utils"; import { useTranslate } from "@/utils/i18n"; import { useAudioWaveform } from "../hooks/useAudioWaveform"; -import type { AudioRecorderPanelProps } from "../types/components"; +import type { AudioRecorderPanelProps } from "../types"; import { VoiceWaveform } from "./VoiceWaveform"; export const AudioRecorderPanel: FC = ({ diff --git a/web/src/components/MemoEditor/components/EditorContent.tsx b/web/src/components/MemoEditor/components/EditorContent.tsx index 38990c70..4ea7d975 100644 --- a/web/src/components/MemoEditor/components/EditorContent.tsx +++ b/web/src/components/MemoEditor/components/EditorContent.tsx @@ -1,66 +1,27 @@ -import { forwardRef, useCallback, useEffect, useImperativeHandle, useRef } from "react"; +import { forwardRef } from "react"; import Editor from "../Editor"; import { useBlobUrls, useDragAndDrop } from "../hooks"; -import PlainEditor from "../PlainEditor"; import { useEditorContext, useEditorSelector } from "../state"; import type { EditorContentProps } from "../types"; import type { LocalFile } from "../types/attachment"; import type { EditorController } from "../types/editorController"; +// Imported eagerly (not React.lazy): the editor is the always-present compose +// box on the home route, which is already code-split — so deferring the +// CodeMirror bundle separately bought nothing and made the editor paint empty +// for a beat before its placeholder appeared (a visible flicker on load). + /** - * Hosts one of the two editor implementations behind the EditorController - * contract, selected by state.ui.editorMode. Mode switching is a markdown - * handoff: both editors serialize into state.content on every change, so the - * incoming editor simply initializes from it. + * Hosts the CodeMirror Editor behind the EditorController contract. The + * editor serializes into state.content on every change and exposes its + * formatting capability for the focus-mode toolbar. */ export const EditorContent = forwardRef(({ placeholder }, ref) => { const { actions, dispatch } = useEditorContext(); const { createBlobUrl } = useBlobUrls(); const content = useEditorSelector((s) => s.content); - const mode = useEditorSelector((s) => s.ui.editorMode); const isFocusMode = useEditorSelector((s) => s.ui.isFocusMode); - // Both editors implement EditorController; the host holds one ref each and - // routes the parent's single ref to whichever mode is active. - const wysiwygRef = useRef(null); - const plainRef = useRef(null); - - const modeRef = useRef(mode); - modeRef.current = mode; - const getActive = useCallback((): EditorController | null => (modeRef.current === "wysiwyg" ? wysiwygRef.current : plainRef.current), []); - - // Mid-edit mode switches should land the user back in the editor, not on - // the toolbar button. Skipped on first mount (useMemoInit owns autofocus). - const previousModeRef = useRef(mode); - useEffect(() => { - if (previousModeRef.current === mode) { - return; - } - previousModeRef.current = mode; - getActive()?.focus(); - }, [mode, getActive]); - - useImperativeHandle( - ref, - (): EditorController => ({ - focus: () => getActive()?.focus(), - hasFocus: () => getActive()?.hasFocus() ?? false, - isEmpty: () => getActive()?.isEmpty() ?? true, - getMarkdown: () => getActive()?.getMarkdown() ?? "", - setMarkdown: (markdown) => getActive()?.setMarkdown(markdown), - insertMarkdown: (markdown) => getActive()?.insertMarkdown(markdown), - scrollToCursor: () => getActive()?.scrollToCursor(), - selectAll: () => getActive()?.selectAll(), - // Formatting is whatever the active editor exposes: the WYSIWYG editor - // provides it, the raw textarea leaves it undefined. No more faking a - // per-verb inert surface — the toolbar simply isn't shown in raw mode. - get formatting() { - return getActive()?.formatting; - }, - }), - [getActive], - ); - const { dragHandlers } = useDragAndDrop((files: FileList) => { const localFiles: LocalFile[] = Array.from(files).map((file) => ({ file, @@ -102,27 +63,15 @@ export const EditorContent = forwardRef(({ return (
    - {mode === "wysiwyg" ? ( - - ) : ( - - )} +
    ); }); diff --git a/web/src/components/MemoEditor/components/index.ts b/web/src/components/MemoEditor/components/index.ts index 4510bcd5..c7445720 100644 --- a/web/src/components/MemoEditor/components/index.ts +++ b/web/src/components/MemoEditor/components/index.ts @@ -3,7 +3,5 @@ export * from "./AudioRecorderPanel"; export * from "./EditorContent"; export * from "./EditorMetadata"; -export * from "./EditorToolbar"; export { FocusModeExitButton, FocusModeOverlay } from "./FocusModeOverlay"; -export { FormattingToolbar } from "./FormattingToolbar"; export { TimestampPopover } from "./TimestampPopover"; diff --git a/web/src/components/MemoEditor/editorMode.ts b/web/src/components/MemoEditor/editorMode.ts deleted file mode 100644 index 6359253a..00000000 --- a/web/src/components/MemoEditor/editorMode.ts +++ /dev/null @@ -1,20 +0,0 @@ -export type EditorMode = "wysiwyg" | "raw"; - -const STORAGE_KEY = "memos-editor-mode"; - -/** Per-device editor mode preference. WYSIWYG is the default for everyone. */ -export function getPreferredEditorMode(): EditorMode { - try { - return localStorage.getItem(STORAGE_KEY) === "raw" ? "raw" : "wysiwyg"; - } catch { - return "wysiwyg"; - } -} - -export function setPreferredEditorMode(mode: EditorMode): void { - try { - localStorage.setItem(STORAGE_KEY, mode); - } catch { - // localStorage unavailable (e.g. blocked storage) — preference won't persist. - } -} diff --git a/web/src/components/MemoEditor/Editor/editorCommands.ts b/web/src/components/MemoEditor/formatting/commands.ts similarity index 61% rename from web/src/components/MemoEditor/Editor/editorCommands.ts rename to web/src/components/MemoEditor/formatting/commands.ts index 39d3941e..a3be993c 100644 --- a/web/src/components/MemoEditor/Editor/editorCommands.ts +++ b/web/src/components/MemoEditor/formatting/commands.ts @@ -1,13 +1,13 @@ -import type { Editor } from "@tiptap/core"; import { BoldIcon, CodeIcon, ItalicIcon, LinkIcon, ListIcon, ListOrderedIcon, ListTodoIcon, type LucideIcon } from "lucide-react"; import type { Translations } from "@/utils/i18n"; /** - * The single source of truth for the editor's formatting verbs. Every surface - * that needs them — the focus-mode toolbar, the active-state hook, and any - * future `/` slash menu — derives from this catalog instead of re-declaring the - * verb, its icon, and its command in its own file. Commands act directly on the - * live Tiptap editor (the only place that holds it). + * Backend-agnostic catalog of the editor's formatting verbs — metadata only, no + * dependency on the concrete editor. Every surface that needs the verbs — the + * focus-mode toolbar, the active-state hook, and any future `/` slash menu — + * derives its labels, icons, and grouping from this catalog instead of + * re-declaring them. How a verb is applied to the live editor is supplied + * separately (Editor/formatting.ts). * * To add a formatting verb, add one entry here (and, if it's a new mark/list, * its field on ActiveFormatState); the toolbar and active-state pick it up. @@ -66,8 +66,6 @@ export interface EditorCommand { /** Button icon. Omitted for headings/paragraph, which render as label-only dropdown items. */ icon?: LucideIcon; group: EditorCommandGroup; - /** Apply to the live editor. The `link` command reads `ctx.url`. */ - run: (editor: Editor, ctx?: EditorCommandContext) => void; } export const EDITOR_COMMANDS: EditorCommand[] = [ @@ -76,83 +74,62 @@ export const EDITOR_COMMANDS: EditorCommand[] = [ labelKey: "editor.format.bold", icon: BoldIcon, group: "mark", - run: (editor) => editor.chain().focus().toggleBold().run(), }, { id: "italic", labelKey: "editor.format.italic", icon: ItalicIcon, group: "mark", - run: (editor) => editor.chain().focus().toggleItalic().run(), }, { id: "code", labelKey: "editor.format.code", icon: CodeIcon, group: "mark", - run: (editor) => editor.chain().focus().toggleCode().run(), }, { id: "bulletList", labelKey: "editor.format.bullet-list", icon: ListIcon, group: "list", - run: (editor) => editor.chain().focus().toggleBulletList().run(), }, { id: "orderedList", labelKey: "editor.format.ordered-list", icon: ListOrderedIcon, group: "list", - run: (editor) => editor.chain().focus().toggleOrderedList().run(), }, { id: "taskList", labelKey: "editor.format.task-list", icon: ListTodoIcon, group: "list", - run: (editor) => editor.chain().focus().toggleTaskList().run(), }, { id: "paragraph", labelKey: "editor.format.paragraph", group: "heading", - run: (editor) => editor.chain().focus().setParagraph().run(), }, { id: "heading1", labelKey: "editor.format.heading-1", group: "heading", - run: (editor) => editor.chain().focus().setHeading({ level: 1 }).run(), }, { id: "heading2", labelKey: "editor.format.heading-2", group: "heading", - run: (editor) => editor.chain().focus().setHeading({ level: 2 }).run(), }, { id: "heading3", labelKey: "editor.format.heading-3", group: "heading", - run: (editor) => editor.chain().focus().setHeading({ level: 3 }).run(), }, { id: "link", labelKey: "editor.format.link", icon: LinkIcon, group: "link", - run: (editor, ctx) => { - if (editor.isActive("link")) { - editor.chain().focus().unsetLink().run(); - return; - } - const href = ctx?.url?.trim(); - if (!href) { - return; - } - editor.chain().focus().extendMarkRange("link").setLink({ href }).run(); - }, }, ]; @@ -161,25 +138,9 @@ export const EDITOR_COMMANDS_BY_ID = Object.fromEntries(EDITOR_COMMANDS.map((com EditorCommand >; -const HEADING_LEVELS: ToolbarHeadingLevel[] = [1, 2, 3]; - -/** Derive the full active-format snapshot from the live editor in one pass. */ -export function getActiveFormats(editor: Editor): ActiveFormatState { - const headingLevel = HEADING_LEVELS.find((level) => editor.isActive("heading", { level })) ?? null; - return { - bold: editor.isActive("bold"), - italic: editor.isActive("italic"), - code: editor.isActive("code"), - bulletList: editor.isActive("bulletList"), - orderedList: editor.isActive("orderedList"), - taskList: editor.isActive("taskList"), - link: editor.isActive("link"), - headingLevel, - }; -} - /** Whether a given command is active for an active-format snapshot. Lets any - * surface (toolbar, slash menu) highlight commands without re-deriving state. */ + * surface (toolbar, slash menu) highlight commands by reading the backend- + * agnostic ActiveFormatState — no live-editor dependency. */ export function isCommandActive(active: ActiveFormatState, id: EditorCommandId): boolean { switch (id) { case "paragraph": diff --git a/web/src/components/MemoEditor/hooks/useEditorActiveState.ts b/web/src/components/MemoEditor/hooks/useEditorActiveState.ts index 24bc379a..da3e7e00 100644 --- a/web/src/components/MemoEditor/hooks/useEditorActiveState.ts +++ b/web/src/components/MemoEditor/hooks/useEditorActiveState.ts @@ -1,5 +1,5 @@ import { type RefObject, useEffect, useState } from "react"; -import { type ActiveFormatState, EMPTY_ACTIVE_FORMATS } from "../Editor/editorCommands"; +import { type ActiveFormatState, EMPTY_ACTIVE_FORMATS } from "../formatting/commands"; import type { EditorController } from "../types/editorController"; function sameActiveFormats(a: ActiveFormatState, b: ActiveFormatState): boolean { diff --git a/web/src/components/MemoEditor/hooks/useLocation.ts b/web/src/components/MemoEditor/hooks/useLocation.ts index e0a979a5..ffed6ada 100644 --- a/web/src/components/MemoEditor/hooks/useLocation.ts +++ b/web/src/components/MemoEditor/hooks/useLocation.ts @@ -2,7 +2,7 @@ import { create } from "@bufbuild/protobuf"; import { useCallback, useMemo, useRef, useState } from "react"; import type { MapPoint } from "@/components/map/types"; import { Location, LocationSchema } from "@/types/proto/api/v1/memo_service_pb"; -import { LocationState } from "../types/insert-menu"; +import { LocationState } from "../types/insertMenu"; export const useLocation = (initialLocation?: Location) => { const [locationInitialized, setLocationInitialized] = useState(false); diff --git a/web/src/components/MemoEditor/hooks/useMemoInit.ts b/web/src/components/MemoEditor/hooks/useMemoInit.ts index 544c0338..2aa59a29 100644 --- a/web/src/components/MemoEditor/hooks/useMemoInit.ts +++ b/web/src/components/MemoEditor/hooks/useMemoInit.ts @@ -1,9 +1,5 @@ import { useEffect, useRef, useState } from "react"; -import toast from "react-hot-toast"; import type { Memo, Visibility } from "@/types/proto/api/v1/memo_service_pb"; -import { useTranslate } from "@/utils/i18n"; -import { isLosslessRoundTrip } from "../Editor/markdownCodec"; -import { getPreferredEditorMode } from "../editorMode"; import { cacheService, memoService } from "../services"; import { useEditorContext } from "../state"; import type { EditorController } from "../types/editorController"; @@ -27,7 +23,6 @@ export const useMemoInit = ({ defaultVisibility, defaultCreateTime, }: UseMemoInitOptions) => { - const t = useTranslate(); const { actions, dispatch } = useEditorContext(); const initializedRef = useRef(false); const [isInitialized, setIsInitialized] = useState(false); @@ -41,16 +36,6 @@ export const useMemoInit = ({ const initialState = memoService.fromMemo(memo); cacheService.clear(key); dispatch(actions.initMemo(initialState)); - // Load guard (tripwire): if the WYSIWYG round trip would change this - // memo's meaning, edit it raw for this session. Preference untouched — - // and INIT_MEMO ignores ui state, so the mode must be dispatched here. - // No length cap: the check runs in a useEffect (post-paint). Add a cap - // if profiling ever identifies cost on very large memos. - if (getPreferredEditorMode() === "wysiwyg" && initialState.content && !isLosslessRoundTrip(initialState.content)) { - console.warn("memo content failed wysiwyg round-trip; falling back to raw editor", memo.name); - dispatch(actions.setEditorMode("raw")); - toast(t("editor.unsupported-syntax-raw-mode")); - } } else { const cachedContent = cacheService.load(key); if (cachedContent) { @@ -69,7 +54,7 @@ export const useMemoInit = ({ } setIsInitialized(true); - }, [memo, cacheKey, username, autoFocus, defaultVisibility, defaultCreateTime, actions, dispatch, editorRef, t]); + }, [memo, cacheKey, username, autoFocus, defaultVisibility, defaultCreateTime, actions, dispatch, editorRef]); return { isInitialized }; }; diff --git a/web/src/components/MemoEditor/index.tsx b/web/src/components/MemoEditor/index.tsx index 340984ab..bbf37785 100644 --- a/web/src/components/MemoEditor/index.tsx +++ b/web/src/components/MemoEditor/index.tsx @@ -12,20 +12,12 @@ import { cn } from "@/lib/utils"; import { InstanceSetting_Key } from "@/types/proto/api/v1/instance_service_pb"; import { useTranslate } from "@/utils/i18n"; import { convertVisibilityFromString } from "@/utils/memo"; -import { - AudioRecorderPanel, - EditorContent, - EditorMetadata, - EditorToolbar, - FocusModeExitButton, - FocusModeOverlay, - FormattingToolbar, - TimestampPopover, -} from "./components"; +import { AudioRecorderPanel, EditorContent, EditorMetadata, FocusModeOverlay, TimestampPopover } from "./components"; import { FOCUS_MODE_STYLES } from "./constants"; import { useAudioRecorder, useAutoSave, useFocusMode, useKeyboard, useMemoInit } from "./hooks"; import { errorService, memoService, transcriptionService, validationService } from "./services"; import { EditorProvider, useEditorContext, useEditorSelector } from "./state"; +import { EditorToolbar, FormattingToolbar } from "./Toolbar"; import type { MemoEditorProps } from "./types"; import type { LocalFile } from "./types/attachment"; import type { EditorController } from "./types/editorController"; @@ -56,7 +48,6 @@ const MemoEditorImpl: React.FC = ({ // typing (which changes content) does not re-render the editor shell and its // toolbar/metadata children. const isFocusMode = useEditorSelector((s) => s.ui.isFocusMode); - const editorMode = useEditorSelector((s) => s.ui.editorMode); const hasTimestamp = useEditorSelector((s) => Boolean(s.timestamps.createTime)); const { userGeneralSetting } = useAuth(); const { aiSetting, fetchSetting } = useInstance(); @@ -323,14 +314,10 @@ const MemoEditorImpl: React.FC = ({ className, )} > - {/* Focus-mode header. WYSIWYG gets the formatting toolbar (exit lives in - it); raw mode falls back to the floating exit button. */} - {isFocusMode && - (editorMode === "wysiwyg" ? ( - - ) : ( - - ))} + {/* Focus-mode header: the formatting toolbar (exit lives in it). */} + {isFocusMode && ( + + )} {(memoName || (!memo && hasTimestamp)) && (
    diff --git a/web/src/components/MemoEditor/state/actions.ts b/web/src/components/MemoEditor/state/actions.ts index cddbf742..8c80fcac 100644 --- a/web/src/components/MemoEditor/state/actions.ts +++ b/web/src/components/MemoEditor/state/actions.ts @@ -1,4 +1,3 @@ -import type { EditorMode } from "../editorMode"; import type { LocalFile } from "../types/attachment"; import type { EditorAction, EditorState, LoadingKey } from "./types"; @@ -52,11 +51,6 @@ export const editorActions = { payload: value, }), - setEditorMode: (mode: EditorMode): EditorAction => ({ - type: "SET_EDITOR_MODE", - payload: mode, - }), - reset: (): EditorAction => ({ type: "RESET", }), diff --git a/web/src/components/MemoEditor/state/reducer.ts b/web/src/components/MemoEditor/state/reducer.ts index 6aff7ceb..31ea0ce8 100644 --- a/web/src/components/MemoEditor/state/reducer.ts +++ b/web/src/components/MemoEditor/state/reducer.ts @@ -80,15 +80,6 @@ export function editorReducer(state: EditorState, action: EditorAction): EditorS recorderBusy: action.payload, }; - case "SET_EDITOR_MODE": - return { - ...state, - ui: { - ...state.ui, - editorMode: action.payload, - }, - }; - case "RESET": return createInitialState(); diff --git a/web/src/components/MemoEditor/state/types.ts b/web/src/components/MemoEditor/state/types.ts index 2a586936..9bd9735a 100644 --- a/web/src/components/MemoEditor/state/types.ts +++ b/web/src/components/MemoEditor/state/types.ts @@ -1,7 +1,6 @@ import type { Attachment } from "@/types/proto/api/v1/attachment_service_pb"; import type { Location, MemoRelation } from "@/types/proto/api/v1/memo_service_pb"; import { Visibility } from "@/types/proto/api/v1/memo_service_pb"; -import { type EditorMode, getPreferredEditorMode } from "../editorMode"; import type { LocalFile } from "../types/attachment"; export type LoadingKey = "saving" | "uploading" | "loading"; @@ -21,7 +20,6 @@ export interface EditorState { uploading: boolean; loading: boolean; }; - editorMode: EditorMode; }; timestamps: { createTime?: Date; @@ -44,12 +42,9 @@ export type EditorAction = | { type: "SET_LOADING"; payload: { key: LoadingKey; value: boolean } } | { type: "SET_TIMESTAMPS"; payload: Partial } | { type: "SET_RECORDER_BUSY"; payload: boolean } - | { type: "SET_EDITOR_MODE"; payload: EditorMode } | { type: "RESET" }; -// Module-private template for createInitialState — not exported because its -// hardcoded editorMode ignores the persisted preference; always go through -// createInitialState() for a real initial state. +// Module-private template for createInitialState. const defaultState: EditorState = { content: "", metadata: { @@ -65,7 +60,6 @@ const defaultState: EditorState = { uploading: false, loading: false, }, - editorMode: "wysiwyg", }, timestamps: { createTime: undefined, @@ -75,14 +69,10 @@ const defaultState: EditorState = { recorderBusy: false, }; -/** - * Fresh initial state for a mounting editor. Reads the persisted mode - * preference at call time (not module load) so newly opened editors honor a - * toggle made earlier in the session. - */ +/** Fresh initial state for a mounting editor. */ export function createInitialState(): EditorState { return { ...defaultState, - ui: { ...defaultState.ui, editorMode: getPreferredEditorMode() }, + ui: { ...defaultState.ui }, }; } diff --git a/web/src/components/MemoEditor/types/editorController.ts b/web/src/components/MemoEditor/types/editorController.ts index 1deb2866..2ac012a7 100644 --- a/web/src/components/MemoEditor/types/editorController.ts +++ b/web/src/components/MemoEditor/types/editorController.ts @@ -1,9 +1,9 @@ -import type { ActiveFormatState, EditorCommandContext, EditorCommandId } from "../Editor/editorCommands"; +import type { ActiveFormatState, EditorCommandContext, EditorCommandId } from "../formatting/commands"; /** - * The contract both memo editors (raw textarea and WYSIWYG) implement. - * Everything outside an editor implementation talks markdown through this - * interface and never reaches for an editor's internal DOM/ProseMirror APIs. + * The contract the memo editor (Editor) implements. Everything outside the + * editor implementation talks markdown through this interface and never reaches + * for the editor's internal CodeMirror/DOM APIs. */ export interface EditorController { focus(): void; @@ -20,19 +20,18 @@ export interface EditorController { /** Select the entire document (used by tests and select-all flows). */ selectAll(): void; /** - * Rich-formatting capability. Present only on editors that support it — the - * WYSIWYG editor sets it; the raw textarea leaves it undefined. The - * focus-mode FormattingToolbar (its only consumer) is shown solely in WYSIWYG - * mode, so it can rely on this being present. + * Rich-formatting capability driving the focus-mode FormattingToolbar. + * Editor always sets it; the field is optional so the contract stays + * decoupled from any one editor implementation. */ formatting?: FormattingController; } /** * Rich-formatting surface, backed by the editor command catalog - * (Editor/editorCommands.ts). `getActiveFormats` is the sanctioned, typed place - * editor state crosses the boundary — ProseMirror node/mark names never leak - * out as stringly-typed `isActive(name)` calls. + * (formatting/commands.ts). `getActiveFormats` is the sanctioned, typed place + * editor state crosses the boundary — the editor's internal node/mark names + * never leak out as stringly-typed `isActive(name)` calls. */ export interface FormattingController { /** Run a catalog command (e.g. "bold", "heading2", "link"). */ diff --git a/web/src/components/MemoEditor/types/index.ts b/web/src/components/MemoEditor/types/index.ts index 394eae75..299a934f 100644 --- a/web/src/components/MemoEditor/types/index.ts +++ b/web/src/components/MemoEditor/types/index.ts @@ -1,6 +1,7 @@ // MemoEditor type exports export type { + AudioRecorderPanelProps, EditorContentProps, EditorMetadataProps, EditorToolbarProps, @@ -11,4 +12,4 @@ export type { VisibilitySelectorProps, } from "./components"; export type { EditorController } from "./editorController"; -export type { LocationState } from "./insert-menu"; +export type { LocationState } from "./insertMenu"; diff --git a/web/src/components/MemoEditor/types/insert-menu.ts b/web/src/components/MemoEditor/types/insertMenu.ts similarity index 100% rename from web/src/components/MemoEditor/types/insert-menu.ts rename to web/src/components/MemoEditor/types/insertMenu.ts diff --git a/web/src/components/MemoMetadata/Location/LocationDialog.tsx b/web/src/components/MemoMetadata/Location/LocationDialog.tsx index a47b5642..d3b918a0 100644 --- a/web/src/components/MemoMetadata/Location/LocationDialog.tsx +++ b/web/src/components/MemoMetadata/Location/LocationDialog.tsx @@ -1,4 +1,4 @@ -import type { LocationState } from "@/components/MemoEditor/types/insert-menu"; +import type { LocationState } from "@/components/MemoEditor/types/insertMenu"; import { LazyLocationPicker } from "@/components/map/LazyLocationPicker"; import type { MapPoint } from "@/components/map/types"; import { Button } from "@/components/ui/button"; diff --git a/web/src/index.css b/web/src/index.css index 5ad8f1eb..532aba00 100644 --- a/web/src/index.css +++ b/web/src/index.css @@ -31,60 +31,3 @@ @apply bg-background text-foreground; } } - -/* Tiptap WYSIWYG memo editor */ -.memo-wysiwyg p.is-editor-empty:first-child::before { - content: attr(data-placeholder); - float: left; - height: 0; - opacity: 0.7; - pointer-events: none; -} - -/* Block styles (e.g. a paragraph's mb-2) add a trailing bottom margin that the - raw textarea editor — whose box has no trailing space — does not have, so the - WYSIWYG editor renders ~8px taller. Most visible when empty: a lone empty - paragraph sits a line-plus-margin tall against the textarea's single line. - Dropping the final block's bottom margin keeps both editor modes the same - height. Scoped with `>` to the top-level block only (nested last children, - e.g. the last list item, keep their spacing). */ -.memo-wysiwyg > :last-child { - margin-bottom: 0; -} - -/* Editor-only element styles: task lists and code blocks have no shared markup - with the read-only memo view (MemoContent renders those via TaskListItem.tsx - and CodeBlock.tsx), so unlike the elements in markdownStyles.ts they stay - local to the editor here rather than in the shared style token. */ -.memo-wysiwyg ul[data-type="taskList"] { - list-style: none; - padding-left: 0; -} - -.memo-wysiwyg ul[data-type="taskList"] li { - display: flex; - gap: 0.5rem; -} - -.memo-wysiwyg ul[data-type="taskList"] li > label { - flex: 0 0 auto; - user-select: none; -} - -.memo-wysiwyg ul[data-type="taskList"] li > div { - flex: 1 1 auto; -} - -.memo-wysiwyg pre { - background: var(--muted); - border-radius: 0.375rem; - padding: 0.5rem 0.75rem; - font-family: var(--font-mono, monospace); - font-size: 0.875rem; - white-space: pre-wrap; -} - -.memo-wysiwyg pre code { - background: transparent; - padding: 0; -} diff --git a/web/src/lib/markdownStyles.ts b/web/src/lib/markdownStyles.ts index c7cb686b..3edef3b2 100644 --- a/web/src/lib/markdownStyles.ts +++ b/web/src/lib/markdownStyles.ts @@ -18,8 +18,7 @@ const headingBaseClasses = "mt-3 mb-2 leading-tight"; /** * Complete heading class per level, precomputed once at module load (base + * per-level). headingClass is a hot path — MemoContent renders it per heading - * and the editor's renderHTML runs it on essentially every keystroke — so the - * cn() merge happens here, not per call. + * on every content render — so the cn() merge happens here, not per call. */ const headingClasses: Record = { 1: cn(headingBaseClasses, headingLevelClasses[1]), @@ -32,10 +31,10 @@ const headingClasses: Record = { /** * Single source of truth for the styling of common markdown elements rendered - * by BOTH the read-only memo view (MemoContent) and the WYSIWYG editor - * (MemoEditor). Each value is a complete, standalone Tailwind class string so it - * can be dropped onto a DOM element as-is (the editor sets these via Tiptap - * `HTMLAttributes`; MemoContent merges them with `cn`). + * by the read-only memo view (MemoContent). Each value is a complete, standalone + * Tailwind class string so it can be dropped onto a DOM element as-is (MemoContent + * merges them with `cn`). The editor does not use these — it styles its raw + * markdown source via CodeMirror decorations in `MemoEditor/Editor/theme.ts`. * * These are static string literals so Tailwind's JIT scanner detects them. */ @@ -45,6 +44,10 @@ export const markdownStyles = { bulletList: "my-0 mb-2 list-outside pl-6 list-disc", orderedList: "my-0 mb-2 list-outside pl-6 list-decimal", listItem: "mt-0.5 leading-6", + // Shared by the read-only task item (MemoContent/markdown/List.tsx) and the + // editor so the checkbox + text grid stays identical in both. + taskListItem: "mt-0.5 min-w-0 leading-6 list-none grid grid-cols-[auto_minmax(0,1fr)] items-start gap-x-2 [&>[data-slot=checkbox]]:mt-1", + taskItemContent: "min-w-0 [overflow-wrap:anywhere] [&>*:last-child]:mb-0", inlineCode: "font-mono text-sm bg-muted px-1 py-0.5 rounded-md", link: "text-primary underline decoration-primary/50 underline-offset-2 transition-colors hover:decoration-primary", horizontalRule: "my-2 h-0 border-0 border-b border-border", @@ -54,12 +57,10 @@ export const markdownStyles = { export const headingClass = (level: HeadingLevel): string => headingClasses[level]; /** - * Tag pill styling, shared by the read-only memo view (MemoContent/Tag.tsx) and - * the editor's tag mark (MemoEditor/Editor/Tag.ts) so a `#tag` looks identical - * while typing and after saving. Split into two tokens so the viewer can swap - * `defaultColor` for an inline custom color, and so the editor — which is never - * custom-colored and is not a filter button — takes the shape + default color - * without the viewer's click/hover affordances. + * Tag pill styling for the read-only memo view (MemoContent/Tag.tsx). Split into + * two tokens so the viewer can swap `defaultColor` for an inline custom color. + * (The editor does not use these; it colors `#tag` source via the + * `cm-memo-tag` decoration in Editor/theme.ts.) */ export const tagStyles = { /** Shape, padding, and typography — always applied. */ @@ -69,11 +70,11 @@ export const tagStyles = { } as const; /** - * `@mention` styling, shared by the read-only memo view (MemoContent/Mention.tsx) - * and the editor's mention mark (MemoEditor/Editor/Mention.ts) so a mention looks - * identical while typing and after saving. Unlike a tag this is not a pill — it - * is the same primary-colored accent the resolved read-only mention uses in its - * resting state (the read-only view adds `hover:underline` for its link). + * `@mention` styling for the read-only memo view (MemoContent/Mention.tsx). + * Unlike a tag this is not a pill — it is a primary-colored accent (the read-only + * view adds `hover:underline` for its link). (The editor does not use these; it + * colors `@mention` source via the `cm-memo-mention` decoration in + * Editor/theme.ts.) */ export const mentionStyles = { base: "text-primary underline-offset-2", diff --git a/web/src/utils/mention-grammar.ts b/web/src/utils/mention-grammar.ts index de87284d..63024992 100644 --- a/web/src/utils/mention-grammar.ts +++ b/web/src/utils/mention-grammar.ts @@ -1,7 +1,7 @@ /** * The single source of truth for memos' `@mention` lexing grammar, shared by the - * editor tokenizer (components/MemoEditor/Editor/Mention.ts) and the read-only - * renderer (utils/remark-plugins/remark-mention.ts) so they can't drift. + * editor and the read-only renderer (utils/remark-plugins/remark-mention.ts) so + * they can't drift. * * A mention character is an ASCII letter, digit, or hyphen. A username is capped * at MAX_MENTION_LENGTH characters and must contain at least one letter or digit diff --git a/web/src/utils/tag-grammar.ts b/web/src/utils/tag-grammar.ts index de394b8e..491de772 100644 --- a/web/src/utils/tag-grammar.ts +++ b/web/src/utils/tag-grammar.ts @@ -1,8 +1,7 @@ /** * The single source of truth for memos' `#tag` lexing grammar, shared by the - * editor tokenizer + serialize-escape (components/MemoEditor/Editor/Tag.ts and - * tagMarkdown.ts) and the read-only renderer (utils/remark-plugins/remark-tag.ts) - * so they can't drift. + * editor and the read-only renderer (utils/remark-plugins/remark-tag.ts) so they + * can't drift. * * A tag character is any Unicode letter, mark, number, or symbol, plus * `_ - / &`. The mark class (`\p{M}`) keeps combining marks — Indic vowel diff --git a/web/tests/editor-commands.test.ts b/web/tests/editor-commands.test.ts deleted file mode 100644 index d1a8b777..00000000 --- a/web/tests/editor-commands.test.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { Editor } from "@tiptap/core"; -import { describe, expect, it } from "vitest"; -import { EDITOR_COMMANDS, EDITOR_COMMANDS_BY_ID, getActiveFormats } from "@/components/MemoEditor/Editor/editorCommands"; -import { buildExtensions } from "@/components/MemoEditor/Editor/extensions"; - -function makeEditor(content = "") { - return new Editor({ extensions: buildExtensions(), content, contentType: "markdown" }); -} - -describe("editor command catalog", () => { - it("exposes every command keyed by id", () => { - for (const command of EDITOR_COMMANDS) { - expect(EDITOR_COMMANDS_BY_ID[command.id]).toBe(command); - } - }); - - it("bold command toggles the bold mark, reflected by getActiveFormats", () => { - const editor = makeEditor("hello"); - try { - editor.commands.selectAll(); - expect(getActiveFormats(editor).bold).toBe(false); - EDITOR_COMMANDS_BY_ID.bold.run(editor); - expect(getActiveFormats(editor).bold).toBe(true); - } finally { - editor.destroy(); - } - }); - - it("heading2 command sets the level, reported by getActiveFormats.headingLevel", () => { - const editor = makeEditor("title"); - try { - expect(getActiveFormats(editor).headingLevel).toBeNull(); - EDITOR_COMMANDS_BY_ID.heading2.run(editor); - expect(getActiveFormats(editor).headingLevel).toBe(2); - EDITOR_COMMANDS_BY_ID.paragraph.run(editor); - expect(getActiveFormats(editor).headingLevel).toBeNull(); - } finally { - editor.destroy(); - } - }); - - it("taskList command toggles a task list", () => { - const editor = makeEditor("buy milk"); - try { - EDITOR_COMMANDS_BY_ID.taskList.run(editor); - expect(getActiveFormats(editor).taskList).toBe(true); - } finally { - editor.destroy(); - } - }); - - it("link command applies a link from ctx.url and clears it when already active", () => { - const editor = makeEditor("memos"); - try { - editor.commands.selectAll(); - EDITOR_COMMANDS_BY_ID.link.run(editor, { url: "https://usememos.com" }); - expect(getActiveFormats(editor).link).toBe(true); - editor.commands.selectAll(); - EDITOR_COMMANDS_BY_ID.link.run(editor); // active → unset (ignores missing url) - expect(getActiveFormats(editor).link).toBe(false); - } finally { - editor.destroy(); - } - }); -}); diff --git a/web/tests/editor-controller.test.ts b/web/tests/editor-controller.test.ts new file mode 100644 index 00000000..e159137f --- /dev/null +++ b/web/tests/editor-controller.test.ts @@ -0,0 +1,32 @@ +import { EditorState } from "@codemirror/state"; +import { EditorView } from "@codemirror/view"; +import { describe, expect, it } from "vitest"; +import { createController } from "@/components/MemoEditor/Editor/controller"; + +function view(doc = "") { + return new EditorView({ state: EditorState.create({ doc }) }); +} + +describe("source editor controller", () => { + it("round-trips markdown verbatim, including previously-lossy inputs", () => { + const v = view(); + const c = createController(v, {} as never); + for (const md of ["![a](x.png)", "Title\n===", "1. a\n 1. b\n 1. c", "a b"]) { + c.setMarkdown(md); + expect(c.getMarkdown()).toBe(md); + } + }); + + it("reports emptiness on whitespace", () => { + const c = createController(view(" \n "), {} as never); + expect(c.isEmpty()).toBe(true); + }); + + it("inserts markdown as its own block", () => { + const v = view("alpha"); + const c = createController(v, {} as never); + v.dispatch({ selection: { anchor: 5 } }); + c.insertMarkdown("beta"); + expect(c.getMarkdown()).toBe("alpha\n\nbeta"); + }); +}); diff --git a/web/tests/editor-controller.test.tsx b/web/tests/editor-controller.test.tsx deleted file mode 100644 index bbe1ca61..00000000 --- a/web/tests/editor-controller.test.tsx +++ /dev/null @@ -1,249 +0,0 @@ -import { act, fireEvent, render } from "@testing-library/react"; -import type { Editor as EditorInstance } from "@tiptap/core"; -import { AllSelection } from "@tiptap/pm/state"; -import { createRef } from "react"; -import { describe, expect, it, vi } from "vitest"; -import Editor from "@/components/MemoEditor/Editor"; -import type { EditorController } from "@/components/MemoEditor/types/editorController"; - -vi.mock("@/hooks/useUserQueries", async (importOriginal) => ({ - ...(await importOriginal()), - useTagCounts: () => ({ data: {} }), -})); - -function setup(initialContent = "") { - const ref = createRef(); - const onContentChange = vi.fn(); - const { container } = render( - , - ); - // The editor instance is exposed on the ProseMirror DOM node; tests use it - // only where the EditorController surface cannot produce the state. - const editor = (container.querySelector(".ProseMirror") as HTMLElement & { editor?: EditorInstance }).editor as EditorInstance; - return { ref, onContentChange, editor }; -} - -// Like setup(), but exposes a rerender(content) that re-renders the SAME -// component instance with a new initialContent — the external-sync path. -function setupRerenderable(initialContent = "") { - const ref = createRef(); - const onContentChange = vi.fn(); - const renderEditor = (content: string) => ( - - ); - const { rerender: rtlRerender } = render(renderEditor(initialContent)); - const rerender = (content: string) => act(() => rtlRerender(renderEditor(content))); - return { ref, onContentChange, rerender }; -} - -describe("Editor EditorController", () => { - it("loads markdown and serializes it back", () => { - const { ref } = setup("# Title\n\nSome **bold** text."); - expect(ref.current?.getMarkdown()).toBe("# Title\n\nSome **bold** text."); - }); - - it("reports emptiness", () => { - const { ref } = setup(""); - expect(ref.current?.isEmpty()).toBe(true); - }); - - it("treats whitespace-only content as empty", () => { - // Markdown parsing can never produce a whitespace-only text node, so type - // the spaces through a raw ProseMirror transaction the way a user would. - const { ref, editor } = setup(""); - act(() => { - editor.view.dispatch(editor.state.tr.insertText(" ", 1)); - }); - expect(editor.isEmpty).toBe(false); // structurally non-empty... - expect(ref.current?.isEmpty()).toBe(true); // ...but empty per the contract - }); - - it("setMarkdown replaces the document", () => { - const { ref } = setup("old"); - act(() => ref.current?.setMarkdown("- [ ] task")); - expect(ref.current?.getMarkdown()).toBe("- [ ] task"); - }); - - it("insertMarkdown adds content and notifies onContentChange", () => { - const { ref, onContentChange } = setup(""); - act(() => ref.current?.insertMarkdown("hello")); - expect(ref.current?.getMarkdown()).toContain("hello"); - expect(onContentChange).toHaveBeenCalledWith(expect.stringContaining("hello")); - }); - - it("formatting.run('bold') bolds the selected text", () => { - const { ref } = setup("bold me"); - act(() => ref.current?.selectAll()); - act(() => ref.current?.formatting?.run("bold")); - expect(ref.current?.getMarkdown()).toBe("**bold me**"); - }); - - it("formatting.run('taskList') converts the current block", () => { - const { ref } = setup("buy milk"); - act(() => ref.current?.formatting?.run("taskList")); - expect(ref.current?.getMarkdown()).toBe("- [ ] buy milk"); - }); -}); - -describe("tag suggestion insertion", () => { - it("tag suggestion command inserts tag-marked text plus an unmarked space", () => { - const { ref, editor } = setup(""); - act(() => { - editor - .chain() - .focus() - .insertContentAt({ from: 1, to: 1 }, [ - { type: "text", text: "#alpha", marks: [{ type: "tag", attrs: { tag: "alpha" } }] }, - { type: "text", text: " " }, - ]) - .run(); - }); - expect(ref.current?.getMarkdown()).toBe("#alpha"); - const para = editor.getJSON().content?.[0]; - expect(para?.content?.[0]).toMatchObject({ text: "#alpha", marks: [{ type: "tag" }] }); - expect(para?.content?.[1]?.marks ?? []).toHaveLength(0); - }); -}); - -describe("tag escaping", () => { - // Drives the ProseMirror input-rules plugin the way real typing does: - // someProp("handleTextInput", …) is exactly what the view calls on keystroke. - function typeText(editor: EditorInstance, text: string) { - const { from } = editor.state.selection; - editor.view.someProp("handleTextInput", (handler) => handler(editor.view, from, from, text)); - } - - it("undoing the tag autoformat leaves a durable literal #tag, not a pill", () => { - const { ref, editor } = setup(""); - act(() => { - editor.view.dispatch(editor.state.tr.insertText("#NAS", 1)); - }); - act(() => typeText(editor, " ")); // tag input rule fires → pill - act(() => { - editor.commands.undoInputRule(); // the standard "I didn't want that" gesture - }); - - // Back to plain text — and the serializer escapes it so it can't re-tag. - expect(ref.current?.getMarkdown()?.trim()).toBe("\\#NAS"); - const para = editor.getJSON().content?.[0]; - expect(para?.content?.some((n) => (n.marks ?? []).some((m) => m.type === "tag"))).toBeFalsy(); - }); - - it("a plain #tag still becomes a tag", () => { - const { ref, editor } = setup(""); - act(() => { - editor.view.dispatch(editor.state.tr.insertText("#work", 1)); - }); - act(() => typeText(editor, " ")); - - expect(ref.current?.getMarkdown()?.trim()).toBe("#work"); - const para = editor.getJSON().content?.[0]; - expect(para?.content?.[0]).toMatchObject({ text: "#work", marks: [{ type: "tag" }] }); - }); -}); - -describe("external content sync", () => { - it("a trim-equal echo of the editor's own output does not reset the document", () => { - const { ref, rerender } = setupRerenderable("hello"); - // simulate parent echoing back the serialized value - rerender("hello"); - expect(ref.current?.getMarkdown()).toBe("hello"); - }); - - it("a genuinely external change replaces the document without emitting onContentChange", () => { - const { ref, onContentChange, rerender } = setupRerenderable("old"); - rerender("# new"); - expect(ref.current?.getMarkdown()).toBe("# new"); - expect(onContentChange).not.toHaveBeenCalled(); - }); - - it("reset-to-empty clears the editor", () => { - const { ref, rerender } = setupRerenderable("something"); - rerender(""); - expect(ref.current?.isEmpty()).toBe(true); - }); -}); - -describe("keyboard shortcuts", () => { - it("Mod-Enter does not insert a hard break (reserved for app-level save)", () => { - // ProseMirror attaches its keydown listener directly on the contenteditable - // (.ProseMirror) element. fireEvent.keyDown dispatches a real DOM event - // that triggers PM's handler → keymap plugin resolution → our - // SaveShortcutPassthrough extension (priority 1000) returns true before - // HardBreak's handler runs, so no document mutation occurs. - // - // Non-vacuousness proof: the parallel Shift-Enter test below uses the same - // dispatch path and DOES mutate the document, confirming that fireEvent.keyDown - // reaches ProseMirror's keymap in jsdom. - const { ref, editor } = setup("hello"); - const proseMirrorEl = document.querySelector(".ProseMirror") as HTMLElement; - const docBefore = editor.state.doc.toString(); - act(() => { - fireEvent.keyDown(proseMirrorEl, { key: "Enter", ctrlKey: true }); - }); - expect(editor.state.doc.toString()).toBe(docBefore); - expect(ref.current?.getMarkdown()).toBe("hello"); - }); - - it("Shift-Enter still inserts a hard break (proves fireEvent.keyDown reaches PM keymap)", () => { - // Positive control: the same keydown dispatch path DOES mutate the document - // when it reaches HardBreak's handler (Shift-Enter is not intercepted by - // SaveShortcutPassthrough, which only swallows Mod-Enter). - // This confirms the Mod-Enter test above is not vacuous. - const { ref, editor } = setup("hello"); - // Select all first so the cursor is in a known position and PM's - // setHardBreak command can execute (requires a text selection). - act(() => { - editor.commands.selectAll(); - }); - const proseMirrorEl = document.querySelector(".ProseMirror") as HTMLElement; - const docBefore = editor.state.doc.toString(); - act(() => { - fireEvent.keyDown(proseMirrorEl, { key: "Enter", shiftKey: true }); - }); - // A hardBreak node must have been inserted — the document changed. - expect(editor.state.doc.toString()).not.toBe(docBefore); - expect(editor.state.doc.toString()).toContain("hardBreak"); - // The serialized markdown now contains a hard break (two trailing spaces + newline). - expect(ref.current?.getMarkdown()).not.toBe("hello"); - }); -}); - -describe("select-all then delete", () => { - it("collapses to a caret instead of leaving a highlighted empty block", () => { - // Repro of the reported bug: Ctrl+A makes an AllSelection, Backspace empties - // the document. AllSelection.map() always returns another AllSelection, so - // without intervention the selection is left as a non-empty whole-document - // AllSelection over the empty paragraph — which the view paints as a - // "selected" empty block (the screenshot artifact). - const { ref, editor } = setup("hello world"); - const proseMirrorEl = document.querySelector(".ProseMirror") as HTMLElement; - act(() => { - editor.commands.selectAll(); - }); - expect(editor.state.selection).toBeInstanceOf(AllSelection); - act(() => { - fireEvent.keyDown(proseMirrorEl, { key: "Backspace" }); - }); - expect(ref.current?.isEmpty()).toBe(true); - // The fix: the leftover selection must be a collapsed caret, never a - // lingering non-empty AllSelection. - expect(editor.state.selection.empty).toBe(true); - expect(editor.state.selection).not.toBeInstanceOf(AllSelection); - }); - - it("deleting an all-selection via the deleteSelection command also collapses (covers Cut)", () => { - // Cut (Cmd-X) and programmatic deletes go through deleteSelection rather - // than the Backspace keymap, but hit the same AllSelection.map() trap. - const { ref, editor } = setup("# Title\n\nsome **bold** text"); - act(() => { - editor.commands.selectAll(); - }); - act(() => { - editor.commands.deleteSelection(); - }); - expect(ref.current?.isEmpty()).toBe(true); - expect(editor.state.selection.empty).toBe(true); - expect(editor.state.selection).not.toBeInstanceOf(AllSelection); - }); -}); diff --git a/web/tests/editor-decorations.test.ts b/web/tests/editor-decorations.test.ts new file mode 100644 index 00000000..2fea535d --- /dev/null +++ b/web/tests/editor-decorations.test.ts @@ -0,0 +1,16 @@ +import { EditorState } from "@codemirror/state"; +import { EditorView } from "@codemirror/view"; +import { describe, expect, it } from "vitest"; +import { tagMentionDecorations } from "@/components/MemoEditor/Editor/tagMentionDecorations"; + +function countClass(doc: string, cls: string): number { + const view = new EditorView({ state: EditorState.create({ doc, extensions: [tagMentionDecorations] }), parent: document.body }); + const n = view.dom.querySelectorAll(`.${cls}`).length; + view.destroy(); + return n; +} + +describe("tag/mention decorations", () => { + it("decorates #tags", () => expect(countClass("a #todo and #work/sub b", "cm-memo-tag")).toBe(2)); + it("decorates @mentions", () => expect(countClass("hi @alice", "cm-memo-mention")).toBe(1)); +}); diff --git a/web/tests/editor-formatting.test.ts b/web/tests/editor-formatting.test.ts new file mode 100644 index 00000000..9970b7b2 --- /dev/null +++ b/web/tests/editor-formatting.test.ts @@ -0,0 +1,56 @@ +import { markdown } from "@codemirror/lang-markdown"; +import { EditorSelection, EditorState } from "@codemirror/state"; +import { EditorView } from "@codemirror/view"; +import { describe, expect, it } from "vitest"; +import { createFormattingController } from "@/components/MemoEditor/Editor/formatting"; + +function setup(doc: string, from: number, to: number) { + const view = new EditorView({ + state: EditorState.create({ doc, extensions: [markdown()], selection: EditorSelection.range(from, to) }), + }); + return { view, f: createFormattingController(view, new Set()) }; +} + +describe("formatting controller", () => { + it("wraps selection in bold and reports active", () => { + const { view, f } = setup("hello world", 0, 5); + f.run("bold"); + expect(view.state.doc.toString()).toBe("**hello** world"); + view.dispatch({ selection: { anchor: 3 } }); + expect(f.getActiveFormats().bold).toBe(true); + }); + + it("prefixes a heading and reports its level", () => { + const { view, f } = setup("Title", 0, 0); + f.run("heading1"); + expect(view.state.doc.toString()).toBe("# Title"); + view.dispatch({ selection: { anchor: 3 } }); + expect(f.getActiveFormats().headingLevel).toBe(1); + }); + + it("toggles a bullet list line", () => { + const { view, f } = setup("item", 0, 0); + f.run("bulletList"); + expect(view.state.doc.toString()).toBe("- item"); + f.run("bulletList"); + expect(view.state.doc.toString()).toBe("item"); + }); + + it("unbolds when already bold", () => { + const { view, f } = setup("**hello** world", 4, 4); // cursor inside bold + f.run("bold"); + expect(view.state.doc.toString()).toBe("hello world"); + }); + + it("unwraps italic when already italic", () => { + const { view, f } = setup("*hi* there", 2, 2); + f.run("italic"); + expect(view.state.doc.toString()).toBe("hi there"); + }); + + it("unwraps inline code when already code", () => { + const { view, f } = setup("`code` here", 3, 3); + f.run("code"); + expect(view.state.doc.toString()).toBe("code here"); + }); +}); diff --git a/web/tests/editor-heading-decorations.test.ts b/web/tests/editor-heading-decorations.test.ts new file mode 100644 index 00000000..da23cefb --- /dev/null +++ b/web/tests/editor-heading-decorations.test.ts @@ -0,0 +1,19 @@ +import { markdown } from "@codemirror/lang-markdown"; +import { EditorState } from "@codemirror/state"; +import { EditorView } from "@codemirror/view"; +import { describe, expect, it } from "vitest"; +import { headingDecorations } from "@/components/MemoEditor/Editor/headingDecorations"; + +function hasClass(doc: string, cls: string): boolean { + const view = new EditorView({ state: EditorState.create({ doc, extensions: [markdown(), headingDecorations] }), parent: document.body }); + const found = view.dom.querySelector(`.${cls}`) !== null; + view.destroy(); + return found; +} + +describe("heading line decorations require a space", () => { + it("styles '# Title' as h1", () => expect(hasClass("# Title", "cm-md-h1")).toBe(true)); + it("styles '### x' as h3", () => expect(hasClass("### x", "cm-md-h3")).toBe(true)); + it("does NOT style a bare '#'", () => expect(hasClass("#", "cm-md-h1")).toBe(false)); + it("does NOT style '#tag' (no space)", () => expect(hasClass("#tag", "cm-md-h1")).toBe(false)); +}); diff --git a/web/tests/editor-keys.test.ts b/web/tests/editor-keys.test.ts new file mode 100644 index 00000000..73c817eb --- /dev/null +++ b/web/tests/editor-keys.test.ts @@ -0,0 +1,86 @@ +import { EditorState } from "@codemirror/state"; +import { EditorView } from "@codemirror/view"; +import React from "react"; +import { renderToStaticMarkup } from "react-dom/server"; +import { describe, expect, it } from "vitest"; +import { MemoMarkdownRenderer } from "@/components/MemoContent/MemoMarkdownRenderer"; +import { buildEditorExtensions } from "@/components/MemoEditor/Editor/extensions"; + +function makeView(doc: string) { + return new EditorView({ + state: EditorState.create({ + doc, + extensions: buildEditorExtensions({ placeholder: "", onChange: () => {}, onUpdate: () => {}, getTags: () => [] }), + }), + parent: document.body, + }); +} + +function press(view: EditorView, key: string, opts: KeyboardEventInit = {}) { + view.contentDOM.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true, ...opts })); +} + +/** Place the cursor on the given 1-based line, then press Tab/Shift-Tab. */ +function tabOnLine(view: EditorView, lineNumber: number, shiftKey = false) { + const line = view.state.doc.line(lineNumber); + view.dispatch({ selection: { anchor: line.to } }); + press(view, "Tab", { shiftKey }); +} + +describe("editor key bindings", () => { + it("Tab indents a non-list line by two spaces", () => { + const view = makeView("hello"); + view.dispatch({ selection: { anchor: 0 } }); + press(view, "Tab"); + expect(view.state.doc.toString()).toBe(" hello"); + view.destroy(); + }); + + it("Escape blurs the editor (keyboard escape hatch)", () => { + const view = makeView("x"); + view.focus(); + expect(view.hasFocus).toBe(true); + press(view, "Escape"); + expect(view.hasFocus).toBe(false); + view.destroy(); + }); + + it("Tab nests an ordered item: marker-aligned indent + renumbered to 1", () => { + const view = makeView("1. a\n2. b"); + tabOnLine(view, 2); + // 3-space indent (past "1. ") AND renumbered 2 -> 1 so CommonMark nests it. + expect(view.state.doc.toString()).toBe("1. a\n 1. b"); + view.destroy(); + }); + + it("Tab nests a bullet item to two spaces", () => { + const view = makeView("- a\n- b"); + tabOnLine(view, 2); + expect(view.state.doc.toString()).toBe("- a\n - b"); + view.destroy(); + }); + + it("Shift-Tab outdents a nested list item back to its parent level", () => { + const view = makeView("1. a\n 2. b"); + tabOnLine(view, 2, true); + expect(view.state.doc.toString()).toBe("1. a\n2. b"); + view.destroy(); + }); + + it("Tab-nested ordered lists render nested in the display (no flat siblings)", () => { + const view = makeView("1. a\n2. b\n3. c"); + tabOnLine(view, 2); // nest b under a + tabOnLine(view, 3); // nest c under a ... + tabOnLine(view, 3); // ... then under b + const md = view.state.doc.toString(); + view.destroy(); + // Each nested level renumbers to 1, which is what CommonMark requires to + // nest an ordered sublist (a 2./3. start can't interrupt the parent line). + expect(md).toBe("1. a\n 1. b\n 1. c"); + // remark-gfm (the display) now reads this as three nested ordered lists. + const html = renderToStaticMarkup( + React.createElement(MemoMarkdownRenderer, { content: md, resolvedMentionUsernames: new Set() }), + ); + expect((html.match(/
      vi.fn()); -vi.mock("react-hot-toast", () => ({ - default: Object.assign(toastMock, { error: vi.fn(), success: vi.fn() }), - toast: Object.assign(toastMock, { error: vi.fn(), success: vi.fn() }), -})); - -const isLosslessMock = vi.hoisted(() => vi.fn()); -vi.mock("@/components/MemoEditor/Editor/markdownCodec", () => ({ - isLosslessRoundTrip: isLosslessMock, -})); - -vi.mock("@/utils/i18n", () => ({ useTranslate: () => (key: string) => key })); - -function Harness({ content }: { content: string }) { - const memo = create(MemoSchema, { name: "memos/1", content }); - useMemoInit({ editorRef: { current: null }, memo, username: "users/test" }); - const editorMode = useEditorSelector((s) => s.ui.editorMode); - return {editorMode}; -} - -function renderGuard(content: string) { - render( - - - , - ); -} - -describe("memo-open load guard", () => { - it("switches the session to raw mode when the round trip would lose content", () => { - localStorage.clear(); - isLosslessMock.mockReturnValue(false); - renderGuard("some exotic content"); - expect(screen.getByTestId("mode").textContent).toBe("raw"); - expect(toastMock).toHaveBeenCalled(); - expect(isLosslessMock).toHaveBeenCalledWith("some exotic content"); - // Session-only: the persisted preference is untouched. - expect(localStorage.getItem("memos-editor-mode")).toBeNull(); - }); - - it("stays in wysiwyg when the round trip is lossless", () => { - localStorage.clear(); - isLosslessMock.mockReturnValue(true); - renderGuard("plain content"); - expect(screen.getByTestId("mode").textContent).toBe("wysiwyg"); - }); - - it("skips the round-trip check when the user already prefers raw mode", () => { - localStorage.clear(); - localStorage.setItem("memos-editor-mode", "raw"); - isLosslessMock.mockReturnValue(false); - renderGuard("exotic content"); - expect(isLosslessMock).not.toHaveBeenCalled(); - expect(toastMock).not.toHaveBeenCalled(); - }); -}); diff --git a/web/tests/editor-mention.test.ts b/web/tests/editor-mention.test.ts deleted file mode 100644 index ab9f5e66..00000000 --- a/web/tests/editor-mention.test.ts +++ /dev/null @@ -1,96 +0,0 @@ -import type { JSONContent } from "@tiptap/core"; -import { describe, expect, it } from "vitest"; -import { parseMarkdown, roundTripMarkdown } from "@/components/MemoEditor/Editor/markdownCodec"; - -function firstParagraphChildren(markdown: string) { - return parseMarkdown(markdown).content?.[0]?.content ?? []; -} - -function hasMentionMark(node: JSONContent) { - return (node.marks ?? []).some((m) => m.type === "mention"); -} - -describe("Mention mark", () => { - it("parses @username into mention-marked text", () => { - const mentioned = firstParagraphChildren("hey @alice there").find(hasMentionMark); - expect(mentioned).toMatchObject({ type: "text", text: "@alice", marks: [{ type: "mention", attrs: { username: "alice" } }] }); - }); - - it("serializes mention-marked text back to @username verbatim", () => { - expect(roundTripMarkdown("ping @bob now").trim()).toBe("ping @bob now"); - }); - - it("preserves username case in the editor model (no lowercasing)", () => { - const mentioned = firstParagraphChildren("@Alice").find(hasMentionMark); - expect(mentioned).toMatchObject({ text: "@Alice", marks: [{ type: "mention", attrs: { username: "Alice" } }] }); - expect(roundTripMarkdown("@Alice").trim()).toBe("@Alice"); - }); - - it("supports hyphenated usernames", () => { - const username = firstParagraphChildren("@jane-doe ok") - .find(hasMentionMark) - ?.marks?.find((m) => m.type === "mention")?.attrs?.username; - expect(username).toBe("jane-doe"); - expect(roundTripMarkdown("@jane-doe ok").trim()).toBe("@jane-doe ok"); - }); - - it("autolinks a bare email to mailto and never treats it as a mention", () => { - // The `@` in an email must not become a mention, and the email itself must - // still autolink to a mailto: link (GFM, same as the read-only view) — for - // a standalone email and one mid-sentence alike. The mention tokenizer must - // stay out of the email's way rather than splitting the text at its `@`. - for (const input of ["support@example.com", "mail support@example.com please"]) { - expect(firstParagraphChildren(input).some(hasMentionMark)).toBe(false); - expect(roundTripMarkdown(input)).toContain("[support@example.com](mailto:support@example.com)"); - } - }); - - it("stops at a mention-char boundary: @a@b is mention `a` then literal `@b`", () => { - const mentioned = firstParagraphChildren("@a@b").filter(hasMentionMark); - expect(mentioned).toHaveLength(1); - expect(mentioned[0]).toMatchObject({ text: "@a", marks: [{ type: "mention", attrs: { username: "a" } }] }); - expect(roundTripMarkdown("@a@b").trim()).toBe("@a@b"); - }); - - it("carries both bold and mention marks on **@bob** and round-trips", () => { - const input = "**hi @bob**"; - expect(roundTripMarkdown(input).trim()).toBe(input); - const markTypes = (firstParagraphChildren(input).find((n) => n.text === "@bob")?.marks ?? []).map((m) => m.type); - expect(markTypes).toContain("bold"); - expect(markTypes).toContain("mention"); - }); - - it("keeps a mention inside a link label and round-trips byte-identically", () => { - const input = "[ping @bob](https://example.com)"; - expect(roundTripMarkdown(input).trim()).toBe(input); - }); - - it("does not create a mention from an all-hyphen run", () => { - const children = firstParagraphChildren("@--- nope"); - expect(children.some(hasMentionMark)).toBe(false); - expect(roundTripMarkdown("@--- nope").trim()).toBe("@--- nope"); - }); - - it("caps the username at 32 chars, leaving the overflow as plain text", () => { - const input = `@${"a".repeat(40)}`; - const username = firstParagraphChildren(input) - .find(hasMentionMark) - ?.marks?.find((m) => m.type === "mention")?.attrs?.username; - expect(username).toBe("a".repeat(32)); - expect(roundTripMarkdown(input).trim()).toBe(input); - }); - - it("marks the mentions, autolinks the email, in a mixed line", () => { - // Mentions stay mentions (editor preserves case, unlike backend extraction - // which lowercases), the email autolinks to mailto, and the two never - // collide. Based on the backend's canonical case (markdown_test.go). - const input = "Hi @Alice and @bob. Email support@example.com today."; - const usernames = firstParagraphChildren(input) - .filter(hasMentionMark) - .map((n) => n.marks?.find((m) => m.type === "mention")?.attrs?.username); - expect(usernames).toEqual(["Alice", "bob"]); - - const out = roundTripMarkdown(input).trim(); - expect(out).toBe("Hi @Alice and @bob. Email [support@example.com](mailto:support@example.com) today."); - }); -}); diff --git a/web/tests/editor-mode-toggle.test.tsx b/web/tests/editor-mode-toggle.test.tsx deleted file mode 100644 index d29d011a..00000000 --- a/web/tests/editor-mode-toggle.test.tsx +++ /dev/null @@ -1,126 +0,0 @@ -import { act, fireEvent, render, screen } from "@testing-library/react"; -import { describe, expect, it, vi } from "vitest"; -import { EditorContent } from "@/components/MemoEditor/components/EditorContent"; -import { EditorProvider, useEditorContext, useEditorSelector } from "@/components/MemoEditor/state"; - -vi.mock("@/hooks/useUserQueries", () => ({ - useTagCounts: () => ({ data: {} }), -})); - -// useTranslate returns the key string in tests (no i18next backend initialised). -vi.mock("@/utils/i18n", () => ({ useTranslate: () => (key: string) => key })); - -function ModeProbe() { - const { actions, dispatch } = useEditorContext(); - const editorMode = useEditorSelector((s) => s.ui.editorMode); - return ( - <> - - - - ); -} - -function renderDualEditor() { - render( - - - - , - ); -} - -describe("editor mode switching", () => { - it("mounts the WYSIWYG editor by default", () => { - localStorage.clear(); - renderDualEditor(); - expect(document.querySelector(".memo-wysiwyg")).not.toBeNull(); - expect(screen.queryByPlaceholderText("memo")).toBeNull(); - }); - - it("mounts the textarea when the persisted preference is raw", () => { - localStorage.setItem("memos-editor-mode", "raw"); - renderDualEditor(); - expect(screen.getByPlaceholderText("memo")).toBeInTheDocument(); - expect(document.querySelector(".memo-wysiwyg")).toBeNull(); - }); - - it("hands content across when toggling raw → wysiwyg", () => { - localStorage.setItem("memos-editor-mode", "raw"); - renderDualEditor(); - const textarea = screen.getByPlaceholderText("memo") as HTMLTextAreaElement; - fireEvent.input(textarea, { target: { value: "hello **world**" } }); - - fireEvent.click(screen.getByTestId("probe-toggle")); - - const wysiwyg = document.querySelector(".memo-wysiwyg"); - expect(wysiwyg).not.toBeNull(); - expect(wysiwyg?.textContent).toContain("hello world"); - expect(wysiwyg?.querySelector("strong")?.textContent).toBe("world"); - }); - - it("hands content across when toggling wysiwyg → raw", () => { - localStorage.clear(); - renderDualEditor(); - // Seed content through the reducer exactly as the wysiwyg editor would. - act(() => { - fireEvent.click(screen.getByTestId("probe-set-content")); - }); - act(() => { - fireEvent.click(screen.getByTestId("probe-toggle")); - }); - const textarea = screen.getByPlaceholderText("memo") as HTMLTextAreaElement; - expect(textarea.value).toBe("from **wysiwyg**"); - }); - - it("double toggle round-trips content byte-identically", () => { - localStorage.setItem("memos-editor-mode", "raw"); - renderDualEditor(); - const textarea = screen.getByPlaceholderText("memo") as HTMLTextAreaElement; - fireEvent.input(textarea, { target: { value: "- [ ] task one\n\nsome **bold** text" } }); - act(() => { - fireEvent.click(screen.getByTestId("probe-toggle")); // raw → wysiwyg - }); - act(() => { - fireEvent.click(screen.getByTestId("probe-toggle")); // wysiwyg → raw - }); - const textareaAfter = screen.getByPlaceholderText("memo") as HTMLTextAreaElement; - expect(textareaAfter.value).toBe("- [ ] task one\n\nsome **bold** text"); - }); - - it("focuses the incoming editor after a toggle", () => { - localStorage.setItem("memos-editor-mode", "raw"); - // The WYSIWYG editor's focus command schedules the actual DOM focus via - // requestAnimationFrame. Mock rAF to fire synchronously so we can assert - // that HTMLElement.prototype.focus() was called within the act() boundary. - const pendingRafs: FrameRequestCallback[] = []; - const rafSpy = vi.spyOn(globalThis, "requestAnimationFrame").mockImplementation((cb) => { - pendingRafs.push(cb); - return pendingRafs.length; - }); - const focusSpy = vi.spyOn(HTMLElement.prototype, "focus"); - renderDualEditor(); - focusSpy.mockClear(); - pendingRafs.length = 0; // clear any rAF calls from initial render - - act(() => { - fireEvent.click(screen.getByTestId("probe-toggle")); // raw → wysiwyg - }); - // Flush pending animation frames (captures the editor's deferred view.focus()). - act(() => { - pendingRafs.splice(0).forEach((cb) => cb(0)); - }); - - expect(focusSpy).toHaveBeenCalled(); - focusSpy.mockRestore(); - rafSpy.mockRestore(); - }); -}); diff --git a/web/tests/editor-mode.test.ts b/web/tests/editor-mode.test.ts deleted file mode 100644 index b934db17..00000000 --- a/web/tests/editor-mode.test.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { beforeEach, describe, expect, it } from "vitest"; -import { getPreferredEditorMode, setPreferredEditorMode } from "@/components/MemoEditor/editorMode"; -import { editorReducer } from "@/components/MemoEditor/state/reducer"; -import { createInitialState } from "@/components/MemoEditor/state/types"; - -describe("editor mode preference", () => { - beforeEach(() => localStorage.clear()); - - it("defaults to wysiwyg", () => { - expect(getPreferredEditorMode()).toBe("wysiwyg"); - }); - - it("persists raw mode", () => { - setPreferredEditorMode("raw"); - expect(getPreferredEditorMode()).toBe("raw"); - expect(localStorage.getItem("memos-editor-mode")).toBe("raw"); - }); - - it("ignores garbage values", () => { - localStorage.setItem("memos-editor-mode", "weird"); - expect(getPreferredEditorMode()).toBe("wysiwyg"); - }); -}); - -describe("editor mode in reducer", () => { - beforeEach(() => localStorage.clear()); - - it("RESET re-reads the persisted preference", () => { - setPreferredEditorMode("raw"); - const state = editorReducer(createInitialState(), { type: "SET_EDITOR_MODE", payload: "wysiwyg" }); - const reset = editorReducer(state, { type: "RESET" }); - expect(reset.ui.editorMode).toBe("raw"); - }); -}); diff --git a/web/tests/editor-preserved.test.ts b/web/tests/editor-preserved.test.ts deleted file mode 100644 index 118b33c3..00000000 --- a/web/tests/editor-preserved.test.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { parseMarkdown, roundTripMarkdown } from "@/components/MemoEditor/Editor/markdownCodec"; - -function blockTypes(markdown: string): string[] { - return (parseMarkdown(markdown).content ?? []).map((node) => node.type ?? ""); -} - -describe("PreservedBlock", () => { - it("captures a table as a single preservedBlock node", () => { - const md = "| a | b |\n| --- | --- |\n| 1 | 2 |"; - expect(blockTypes(md)).toEqual(["preservedBlock"]); - }); - - it("captures block math as preservedBlock", () => { - const md = "$$\nx^2\n$$"; - expect(blockTypes(md)).toEqual(["preservedBlock"]); - }); - - it("captures block HTML as preservedBlock", () => { - const md = "
      \nhello\n
      "; - expect(blockTypes(md)).toEqual(["preservedBlock"]); - }); -}); - -describe("PreservedInline", () => { - it("keeps inline math verbatim — underscores must not get escaped", () => { - expect(roundTripMarkdown("index $x_1$ here").trim()).toBe("index $x_1$ here"); - }); - - it("keeps inline HTML tags literal instead of converting them to marks", () => { - expect(roundTripMarkdown("an emphasis tag").trim()).toBe("an emphasis tag"); - }); - - it("does not swallow autolinks", () => { - const doc = parseMarkdown("see now"); - const para = doc.content?.[0]; - const hasLinkMark = (para?.content ?? []).some((n) => (n.marks ?? []).some((m) => m.type === "link")); - expect(hasLinkMark).toBe(true); - }); -}); - -describe("preserved-syntax edge cases", () => { - it.each([ - "I paid $$ for this", - "tip: 20%, cost: $$, worth it", - "that costs $$$ these days", - "$$$$", - "$a$$b$", - ])("mid-line $$ does not split paragraphs: %s", (s) => { - expect(roundTripMarkdown(s).trim()).toBe(s); - }); - - it("block math followed directly by text normalizes once to blank-line separation, then is stable", () => { - // Byte-identity is impossible here regardless of how the tokenizer treats - // the trailing newline: the math block and the following paragraph are - // sibling block nodes, and the Document serializer joins siblings with - // \n\n. The single \n separator is normalized to a blank line exactly - // once; after that the output is a fixed point. - const out = roundTripMarkdown("$$\nx\n$$\nnext line"); - expect(out.trim()).toBe("$$\nx\n$$\n\nnext line"); // known one-time normalization - expect(roundTripMarkdown(out)).toBe(out); // stable afterward - }); - - it("preserves inline HTML comments", () => { - expect(roundTripMarkdown("text more").trim()).toBe("text more"); - }); - - it("preserves block HTML comments", () => { - expect(roundTripMarkdown("").trim()).toBe(""); - }); - - it("handles > inside quoted attributes", () => { - expect(roundTripMarkdown('a hm b').trim()).toBe('a hm b'); - }); - - it("does not catastrophically backtrack on unterminated tags full of quotes", () => { - const hostile = `a tags); + const state = EditorState.create({ doc }); + return source(new CompletionContext(state, pos, false)); +} + +describe("tag autocomplete", () => { + it("offers known tags after #", () => { + const result = complete("hello #to", 9, ["todo", "today", "work"]); + expect(result?.options.map((o) => o.label)).toEqual(["todo", "today"]); + }); + + it("returns null on a bare # with nothing typed", () => { + expect(complete("hello #", 7, ["todo"])).toBeNull(); + }); + + it("returns null when not in a tag", () => { + expect(complete("hello world", 11, ["todo"])).toBeNull(); + }); +}); diff --git a/web/tests/editor-tag.test.ts b/web/tests/editor-tag.test.ts deleted file mode 100644 index b5921a41..00000000 --- a/web/tests/editor-tag.test.ts +++ /dev/null @@ -1,151 +0,0 @@ -import type { JSONContent } from "@tiptap/core"; -import { describe, expect, it } from "vitest"; -import { parseMarkdown, roundTripMarkdown } from "@/components/MemoEditor/Editor/markdownCodec"; - -function firstParagraphChildren(markdown: string) { - return parseMarkdown(markdown).content?.[0]?.content ?? []; -} - -function collectTextNodes(node: JSONContent): JSONContent[] { - const out: JSONContent[] = []; - if (node.type === "text") { - out.push(node); - } - for (const child of node.content ?? []) { - out.push(...collectTextNodes(child)); - } - return out; -} - -function hasTagMark(node: JSONContent) { - return (node.marks ?? []).some((m) => m.type === "tag"); -} - -describe("Tag mark", () => { - it("parses #tag into tag-marked text", () => { - const children = firstParagraphChildren("#hello world"); - expect(children[0]).toMatchObject({ type: "text", text: "#hello", marks: [{ type: "tag", attrs: { tag: "hello" } }] }); - expect(children[1]).toMatchObject({ type: "text", text: " world" }); - }); - - it("serializes tag-marked text back to #tag verbatim", () => { - expect(roundTripMarkdown("a #b-tag c").trim()).toBe("a #b-tag c"); - }); - - it("supports unicode and nested-path tags", () => { - expect(firstParagraphChildren("#日本語 and #work/project-1")[0]).toMatchObject({ - type: "text", - text: "#日本語", - marks: [{ type: "tag", attrs: { tag: "日本語" } }], - }); - const children = firstParagraphChildren("see #work/project-1 now"); - const tagged = children.find((n) => hasTagMark(n)); - expect(tagged?.marks?.find((m) => m.type === "tag")?.attrs?.tag).toBe("work/project-1"); - }); - - it("includes combining marks in a tag run", () => { - // Malayalam കവിത carries a spacing combining vowel sign (U+0D3F, \p{M}); - // the tag must cover the whole word, not stop at the first mark. - expect(firstParagraphChildren("#കവിത")[0]).toMatchObject({ - type: "text", - text: "#കവിത", - marks: [{ type: "tag", attrs: { tag: "കവിത" } }], - }); - }); - - it("does not turn headings into tags", () => { - expect(parseMarkdown("# heading").content?.[0]?.type).toBe("heading"); - }); - - it("does not match a bare # followed by space", () => { - const children = firstParagraphChildren("a # b"); - expect(children.every((n) => n.type === "text" && !hasTagMark(n))).toBe(true); - }); - - it("skips tags inside link labels and round-trips byte-identically", () => { - const input = "[see #x](https://example.com)"; - expect(roundTripMarkdown(input).trim()).toBe(input); - }); - - it("keeps #notes inside the link label while tagging #real outside", () => { - const input = "see [release #notes](https://e.com) and #real"; - expect(roundTripMarkdown(input).trim()).toBe(input); - - const children = firstParagraphChildren(input); - const linked = children.filter((n) => (n.marks ?? []).some((m) => m.type === "link")); - expect(linked.map((n) => n.text).join("")).toBe("release #notes"); - expect(linked.some((n) => hasTagMark(n))).toBe(false); - - const tagged = children.filter((n) => hasTagMark(n)); - expect(tagged).toHaveLength(1); - expect(tagged[0]).toMatchObject({ text: "#real", marks: [{ type: "tag", attrs: { tag: "real" } }] }); - }); - - it("composes with bold and round-trips byte-identically", () => { - const input = "**bold #tag bold**"; - expect(roundTripMarkdown(input).trim()).toBe(input); - }); - - it("carries both bold and tag marks on **#urgent**", () => { - const input = "**#urgent**"; - expect(roundTripMarkdown(input).trim()).toBe(input); - - const children = firstParagraphChildren(input); - const node = children.find((n) => n.text === "#urgent"); - const markTypes = (node?.marks ?? []).map((m) => m.type); - expect(markTypes).toContain("bold"); - expect(markTypes).toContain("tag"); - }); - - it("does not escape underscores inside tags (code mark emits verbatim)", () => { - expect(roundTripMarkdown("#a_b").trim()).toBe("#a_b"); - }); - - it("respects punctuation boundaries", () => { - const input = "#tag, then #two."; - expect(roundTripMarkdown(input).trim()).toBe(input); - }); - - it("round-trips ##x unchanged and normalizes #a#b to \\#a#b (conservative # escaping)", () => { - // "##x" → text "#" + tag "x"; the lone "#" is not tag-shaped, so untouched. - expect(roundTripMarkdown("##x").trim()).toBe("##x"); - // "#a#b" → text "#a" + tag "b"; the plain "#a" is tag-shaped, so the - // serializer escapes it to keep it literal. Doc-equivalent, stable after. - expect(roundTripMarkdown("#a#b").trim()).toBe("\\#a#b"); - expect(roundTripMarkdown("\\#a#b").trim()).toBe("\\#a#b"); - }); - - it("treats a run longer than 100 tag characters as plain text", () => { - const input = `#${"x".repeat(101)}`; - expect(roundTripMarkdown(input).trim()).toBe(input); - const textNodes = collectTextNodes(parseMarkdown(input)); - expect(textNodes.length).toBeGreaterThan(0); - expect(textNodes.some((n) => hasTagMark(n))).toBe(false); - }); - - it("keeps a backslash-escaped \\#tag literal and durable across round-trips", () => { - const input = "\\#NAS is my server"; - - // Escapes are lexical: `\#NAS` parses to ordinary text — no tag mark, no - // bespoke "escaped tag" node — the `\` is simply consumed. - const children = firstParagraphChildren(input); - expect(children.some(hasTagMark)).toBe(false); - expect(children.map((n) => n.text ?? "").join("")).toBe("#NAS is my server"); - - // The serializer re-escapes the tag-shaped `#`, so it never degrades into a - // tag... - const once = roundTripMarkdown(input).trim(); - expect(once).toBe("\\#NAS is my server"); - // ...and stays stable on every subsequent cycle. - expect(roundTripMarkdown(once).trim()).toBe(once); - }); - - it("escapes only the literal tag while still tagging a real one beside it", () => { - const input = "\\#NAS and #real"; - expect(roundTripMarkdown(input).trim()).toBe("\\#NAS and #real"); - - const tagged = firstParagraphChildren(input).filter(hasTagMark); - expect(tagged).toHaveLength(1); - expect(tagged[0]).toMatchObject({ text: "#real", marks: [{ type: "tag", attrs: { tag: "real" } }] }); - }); -}); diff --git a/web/tests/editor.test.tsx b/web/tests/editor.test.tsx new file mode 100644 index 00000000..ba456919 --- /dev/null +++ b/web/tests/editor.test.tsx @@ -0,0 +1,34 @@ +import { render } from "@testing-library/react"; +import { createRef } from "react"; +import { describe, expect, it, vi } from "vitest"; +import Editor from "@/components/MemoEditor/Editor"; +import type { EditorController } from "@/components/MemoEditor/types/editorController"; + +vi.mock("@/hooks/useUserQueries", () => ({ + useTagCounts: () => ({ data: {} }), +})); + +describe("Editor", () => { + it("loads markdown and serializes it back verbatim", () => { + const ref = createRef(); + render( + , + ); + expect(ref.current?.getMarkdown()).toBe("# Title\n\n- a\n 1. b"); + }); + + it("emits changes through onContentChange", () => { + const ref = createRef(); + const onChange = vi.fn(); + render(); + ref.current?.setMarkdown("hello"); + expect(onChange).toHaveBeenCalledWith("hello"); + }); +}); diff --git a/web/tests/fixtures/markdown-corpus/preserved/block-html.md b/web/tests/fixtures/markdown-corpus/preserved/block-html.md deleted file mode 100644 index cce1cf10..00000000 --- a/web/tests/fixtures/markdown-corpus/preserved/block-html.md +++ /dev/null @@ -1,7 +0,0 @@ -Paragraph before. - -
      -

      Raw HTML block content

      -
      - -Paragraph after. diff --git a/web/tests/fixtures/markdown-corpus/preserved/inline-html.md b/web/tests/fixtures/markdown-corpus/preserved/inline-html.md deleted file mode 100644 index 18a229a4..00000000 --- a/web/tests/fixtures/markdown-corpus/preserved/inline-html.md +++ /dev/null @@ -1 +0,0 @@ -Use emphasis and a line
      break and spans here. diff --git a/web/tests/fixtures/markdown-corpus/preserved/math-block.md b/web/tests/fixtures/markdown-corpus/preserved/math-block.md deleted file mode 100644 index b258e560..00000000 --- a/web/tests/fixtures/markdown-corpus/preserved/math-block.md +++ /dev/null @@ -1,7 +0,0 @@ -Before the math. - -$$ -E = mc^2 \cdot \frac{1}{\sqrt{1 - v^2/c^2}} -$$ - -After the math. diff --git a/web/tests/fixtures/markdown-corpus/preserved/math-inline.md b/web/tests/fixtures/markdown-corpus/preserved/math-inline.md deleted file mode 100644 index c279931f..00000000 --- a/web/tests/fixtures/markdown-corpus/preserved/math-inline.md +++ /dev/null @@ -1 +0,0 @@ -Energy is $E=mc^2$ and the index is $x_1$ in this sentence. diff --git a/web/tests/fixtures/markdown-corpus/preserved/table.md b/web/tests/fixtures/markdown-corpus/preserved/table.md deleted file mode 100644 index 62fdd572..00000000 --- a/web/tests/fixtures/markdown-corpus/preserved/table.md +++ /dev/null @@ -1,4 +0,0 @@ -| Name | Role | -| --- | --- | -| Ada | Engineer | -| Grace | Admiral | diff --git a/web/tests/fixtures/markdown-corpus/supported/basic.md b/web/tests/fixtures/markdown-corpus/supported/basic.md deleted file mode 100644 index e7faea1d..00000000 --- a/web/tests/fixtures/markdown-corpus/supported/basic.md +++ /dev/null @@ -1,7 +0,0 @@ -# Hello memos - -Some **bold**, *italic*, ~~struck~~, and `inline code` text. - -> A blockquote with **bold** inside. - -A [link](https://example.com/docs) in a sentence. diff --git a/web/tests/fixtures/markdown-corpus/supported/blockquote-mixed.md b/web/tests/fixtures/markdown-corpus/supported/blockquote-mixed.md deleted file mode 100644 index bf063247..00000000 --- a/web/tests/fixtures/markdown-corpus/supported/blockquote-mixed.md +++ /dev/null @@ -1,7 +0,0 @@ -> Outer quote line one. -> Still the same quote. - -Paragraph after. - -> - a list in a quote -> - second item diff --git a/web/tests/fixtures/markdown-corpus/supported/cjk-emoji.md b/web/tests/fixtures/markdown-corpus/supported/cjk-emoji.md deleted file mode 100644 index 1ebf4cd6..00000000 --- a/web/tests/fixtures/markdown-corpus/supported/cjk-emoji.md +++ /dev/null @@ -1,9 +0,0 @@ -# 日本語の見出し - -これは**太字**と*斜体*のテストです。改行も確認します。 - -- 中文列表项 -- 한국어 항목 -- emoji 🎉 in a list 🚀 - -> 引用文です 😀 diff --git a/web/tests/fixtures/markdown-corpus/supported/code-blocks.md b/web/tests/fixtures/markdown-corpus/supported/code-blocks.md deleted file mode 100644 index 421195e4..00000000 --- a/web/tests/fixtures/markdown-corpus/supported/code-blocks.md +++ /dev/null @@ -1,16 +0,0 @@ -Some text first. - -```go -func main() { - fmt.Println("hello *not italic* #not-a-tag") -} -``` - -```mermaid -graph TD; - A-->B; -``` - -``` -no language fence -``` diff --git a/web/tests/fixtures/markdown-corpus/supported/headings.md b/web/tests/fixtures/markdown-corpus/supported/headings.md deleted file mode 100644 index 911de0ee..00000000 --- a/web/tests/fixtures/markdown-corpus/supported/headings.md +++ /dev/null @@ -1,13 +0,0 @@ -# H1 - -## H2 - -### H3 - -#### H4 - -##### H5 - -###### H6 - -Body under headings. diff --git a/web/tests/fixtures/markdown-corpus/supported/lists.md b/web/tests/fixtures/markdown-corpus/supported/lists.md deleted file mode 100644 index 9a9bc0fb..00000000 --- a/web/tests/fixtures/markdown-corpus/supported/lists.md +++ /dev/null @@ -1,11 +0,0 @@ -- alpha -- beta - - nested one - - nested two -- gamma - -1. first -2. second - 1. second-a - 2. second-b -3. third diff --git a/web/tests/fixtures/markdown-corpus/supported/task-lists.md b/web/tests/fixtures/markdown-corpus/supported/task-lists.md deleted file mode 100644 index ddcd5780..00000000 --- a/web/tests/fixtures/markdown-corpus/supported/task-lists.md +++ /dev/null @@ -1,8 +0,0 @@ -- [ ] open task -- [x] done task -- [ ] task with **bold** text - -Regular paragraph between. - -- [ ] another list - - [x] nested done diff --git a/web/tests/formatting-controller.test.tsx b/web/tests/formatting-controller.test.tsx deleted file mode 100644 index cdf71c88..00000000 --- a/web/tests/formatting-controller.test.tsx +++ /dev/null @@ -1,95 +0,0 @@ -import { act, render } from "@testing-library/react"; -import { createRef } from "react"; -import { describe, expect, it, vi } from "vitest"; -import Editor from "@/components/MemoEditor/Editor"; -import type { EditorController } from "@/components/MemoEditor/types/editorController"; - -vi.mock("@/hooks/useUserQueries", async (importOriginal) => ({ - ...(await importOriginal()), - useTagCounts: () => ({ data: {} }), -})); - -function setup(initialContent = "") { - const ref = createRef(); - render(); - return ref; -} - -describe("WYSIWYG formatting capability", () => { - it("the WYSIWYG editor exposes a formatting capability", () => { - const ref = setup("x"); - expect(ref.current?.formatting).toBeDefined(); - }); - - it("run('code') wraps the selection in inline code", () => { - const ref = setup("code me"); - act(() => ref.current?.selectAll()); - act(() => ref.current?.formatting?.run("code")); - expect(ref.current?.getMarkdown()).toBe("`code me`"); - }); - - it("run('bulletList') converts the current block", () => { - const ref = setup("item"); - act(() => ref.current?.formatting?.run("bulletList")); - expect(ref.current?.getMarkdown()).toBe("- item"); - }); - - it("run('orderedList') converts the current block", () => { - const ref = setup("item"); - act(() => ref.current?.formatting?.run("orderedList")); - expect(ref.current?.getMarkdown()).toBe("1. item"); - }); - - it("run('heading2') makes the block a heading and getActiveFormats reflects the level", () => { - const ref = setup("title"); - act(() => ref.current?.formatting?.run("heading2")); - expect(ref.current?.getMarkdown()).toBe("## title"); - expect(ref.current?.formatting?.getActiveFormats().headingLevel).toBe(2); - }); - - it("run('paragraph') reverts a heading", () => { - const ref = setup("# title"); - act(() => ref.current?.formatting?.run("paragraph")); - expect(ref.current?.getMarkdown()).toBe("title"); - }); - - it("getActiveFormats().bold tracks the bold mark", () => { - const ref = setup("x"); - expect(ref.current?.formatting?.getActiveFormats().bold).toBe(false); - act(() => ref.current?.selectAll()); - act(() => ref.current?.formatting?.run("bold")); - expect(ref.current?.formatting?.getActiveFormats().bold).toBe(true); - }); - - it("run('link') applies a link over the selection, and removes it when active", () => { - const ref = setup("memos"); - act(() => ref.current?.selectAll()); - act(() => ref.current?.formatting?.run("link", { url: "https://usememos.com" })); - expect(ref.current?.getMarkdown()).toBe("[memos](https://usememos.com)"); - act(() => ref.current?.selectAll()); - act(() => ref.current?.formatting?.run("link")); - expect(ref.current?.getMarkdown()).toBe("memos"); - }); - - it("getSelectedText returns the current selection text", () => { - const ref = setup("hello world"); - act(() => ref.current?.selectAll()); - expect(ref.current?.formatting?.getSelectedText()).toBe("hello world"); - }); - - it("subscribe fires on transactions and unsubscribe stops it", () => { - const ref = setup("x"); - const listener = vi.fn(); - let unsubscribe = () => {}; - act(() => { - unsubscribe = ref.current!.formatting!.subscribe(listener); - }); - act(() => ref.current?.selectAll()); - act(() => ref.current?.formatting?.run("bold")); - const callsWhileSubscribed = listener.mock.calls.length; - expect(callsWhileSubscribed).toBeGreaterThan(0); - act(() => unsubscribe()); - act(() => ref.current?.formatting?.run("italic")); - expect(listener.mock.calls.length).toBe(callsWhileSubscribed); - }); -}); diff --git a/web/tests/formatting-toolbar.test.tsx b/web/tests/formatting-toolbar.test.tsx index f1e5a920..006f8cd4 100644 --- a/web/tests/formatting-toolbar.test.tsx +++ b/web/tests/formatting-toolbar.test.tsx @@ -1,8 +1,8 @@ import { fireEvent, render, screen } from "@testing-library/react"; import { createRef } from "react"; import { beforeAll, describe, expect, it, vi } from "vitest"; -import { FormattingToolbar } from "@/components/MemoEditor/components/FormattingToolbar"; -import { type ActiveFormatState, EMPTY_ACTIVE_FORMATS } from "@/components/MemoEditor/Editor/editorCommands"; +import { type ActiveFormatState, EMPTY_ACTIVE_FORMATS } from "@/components/MemoEditor/formatting/commands"; +import { FormattingToolbar } from "@/components/MemoEditor/Toolbar/FormattingToolbar"; import type { EditorController } from "@/components/MemoEditor/types/editorController"; // Match the repo convention: t echoes the i18n key (no i18next backend in tests), diff --git a/web/tests/insert-menu-mode-toggle.test.tsx b/web/tests/insert-menu-mode-toggle.test.tsx deleted file mode 100644 index 92f265ce..00000000 --- a/web/tests/insert-menu-mode-toggle.test.tsx +++ /dev/null @@ -1,71 +0,0 @@ -import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; -import { fireEvent, render, screen } from "@testing-library/react"; -import { beforeAll, describe, expect, it, vi } from "vitest"; -import { EditorProvider, useEditorSelector } from "@/components/MemoEditor/state"; -import InsertMenu from "@/components/MemoEditor/Toolbar/InsertMenu"; - -// useTranslate returns the i18n key directly (no i18next backend in tests). -vi.mock("@/utils/i18n", () => ({ useTranslate: () => (key: string) => key })); -// The link/location dialogs drag in maps + heavy deps; they're closed here. -vi.mock("@/components/MemoMetadata", () => ({ LinkMemoDialog: () => null, LocationDialog: () => null })); -// useLinkMemo → useCurrentUser → useAuth would need an AuthProvider; stub the user. -vi.mock("@/hooks/useCurrentUser", () => ({ default: () => ({ name: "users/test" }) })); - -// Radix DropdownMenu reaches for layout/pointer APIs jsdom doesn't implement. -beforeAll(() => { - Element.prototype.scrollIntoView = vi.fn(); - Element.prototype.hasPointerCapture = vi.fn(() => false); - Element.prototype.setPointerCapture = vi.fn(); - Element.prototype.releasePointerCapture = vi.fn(); -}); - -function ModeProbe() { - const editorMode = useEditorSelector((s) => s.ui.editorMode); - return {editorMode}; -} - -function renderInsertMenu() { - const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); - render( - - - {}} /> - - - , - ); -} - -// Opens the "+" dropdown, then its "More" submenu, and returns the -// "WYSIWYG Editor" checkbox item. -function openWysiwygCheckbox() { - // Open the dropdown (keyboard open is the most reliable path in jsdom). - fireEvent.keyDown(screen.getByRole("button"), { key: "Enter" }); - // Open the "More" submenu (controlled open state toggles on trigger click). - fireEvent.click(screen.getByText("common.more")); - return screen.getByText("editor.wysiwyg-editor"); -} - -describe("InsertMenu editor-mode toggle", () => { - it("unchecking the WYSIWYG item switches to raw and persists the preference", () => { - localStorage.clear(); - renderInsertMenu(); - expect(screen.getByTestId("mode").textContent).toBe("wysiwyg"); - - fireEvent.click(openWysiwygCheckbox()); - - expect(screen.getByTestId("mode").textContent).toBe("raw"); - expect(localStorage.getItem("memos-editor-mode")).toBe("raw"); - }); - - it("checking the WYSIWYG item switches back to rich text from raw mode", () => { - localStorage.setItem("memos-editor-mode", "raw"); - renderInsertMenu(); - expect(screen.getByTestId("mode").textContent).toBe("raw"); - - fireEvent.click(openWysiwygCheckbox()); - - expect(screen.getByTestId("mode").textContent).toBe("wysiwyg"); - expect(localStorage.getItem("memos-editor-mode")).toBe("wysiwyg"); - }); -}); diff --git a/web/tests/markdown-roundtrip.test.ts b/web/tests/markdown-roundtrip.test.ts deleted file mode 100644 index 918b1974..00000000 --- a/web/tests/markdown-roundtrip.test.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { readdirSync, readFileSync } from "node:fs"; -import { join } from "node:path"; -import { describe, expect, it } from "vitest"; -import { parseMarkdown, roundTripMarkdown } from "@/components/MemoEditor/Editor/markdownCodec"; - -const CORPUS_DIR = join(__dirname, "fixtures", "markdown-corpus"); - -function fixtures(group: string): Array<[name: string, source: string]> { - const dir = join(CORPUS_DIR, group); - return readdirSync(dir) - .filter((f) => f.endsWith(".md")) - .sort() - .map((f) => [f, readFileSync(join(dir, f), "utf8")]); -} - -// Fidelity contract part 1: supported constructs round-trip semantically. -// "Semantic" = the parsed document tree is identical before and after a -// serialize cycle; marker style (e.g. `*` vs `-` bullets) may normalize. -describe("markdown round-trip corpus: supported syntax (semantic equality)", () => { - for (const [name, source] of fixtures("supported")) { - it(`${name}: parse → serialize → parse is identity`, () => { - const serialized = roundTripMarkdown(source); - expect(parseMarkdown(serialized)).toEqual(parseMarkdown(source)); - }); - - it(`${name}: serialization is idempotent`, () => { - const once = roundTripMarkdown(source); - expect(roundTripMarkdown(once)).toBe(once); - }); - } -}); - -// Fidelity contract part 2: unmodeled constructs round-trip byte-for-byte. -// Fixtures in preserved/ contain only preserved constructs + inert prose, -// so the entire file must survive a round trip unchanged (modulo outer trim). -// One known whitespace normalization: a block construct separated from the -// next block by a single \n gains a blank line (\n\n) on the first round trip -// — the Document serializer joins sibling blocks with \n\n. It is a one-time -// normalization; the idempotence tests below pin the output as stable. -describe("markdown round-trip corpus: preserved syntax (byte equality)", () => { - for (const [name, source] of fixtures("preserved")) { - it(`${name}: round-trips byte-for-byte`, () => { - expect(roundTripMarkdown(source).trim()).toBe(source.trim()); - }); - - it(`${name}: serialization is idempotent`, () => { - const once = roundTripMarkdown(source); - expect(roundTripMarkdown(once)).toBe(once); - }); - } -}); diff --git a/web/tests/memo-editor-paste.test.tsx b/web/tests/memo-editor-paste.test.tsx deleted file mode 100644 index c959e90a..00000000 --- a/web/tests/memo-editor-paste.test.tsx +++ /dev/null @@ -1,35 +0,0 @@ -import { fireEvent, render, screen } from "@testing-library/react"; -import { describe, expect, it, vi } from "vitest"; -import PlainEditor from "@/components/MemoEditor/PlainEditor"; - -function pastePlainText(textarea: HTMLTextAreaElement, text: string) { - fireEvent.paste(textarea, { - clipboardData: { - getData: (type: string) => (type === "text/plain" || type === "text" ? text : ""), - }, - }); -} - -function renderEditor(initialContent: string) { - const onPaste = vi.fn(); - render(); - - return { - onPaste, - textarea: screen.getByPlaceholderText("memo") as HTMLTextAreaElement, - }; -} - -describe("plain editor paste handling", () => { - // The plain textarea does no in-editor paste transformation (no URL → link - // wrapping); it forwards every paste to onPaste so the host can handle files. - it("forwards pasted text to onPaste without altering the value", () => { - const { onPaste, textarea } = renderEditor("read the docs"); - textarea.setSelectionRange(9, 13); - - pastePlainText(textarea, "https://example.com"); - - expect(textarea).toHaveValue("read the docs"); - expect(onPaste).toHaveBeenCalledOnce(); - }); -}); diff --git a/web/tests/plain-editor-controller.test.tsx b/web/tests/plain-editor-controller.test.tsx deleted file mode 100644 index dd9e1006..00000000 --- a/web/tests/plain-editor-controller.test.tsx +++ /dev/null @@ -1,57 +0,0 @@ -import { render, screen } from "@testing-library/react"; -import { createRef } from "react"; -import { describe, expect, it, vi } from "vitest"; -import PlainEditor from "@/components/MemoEditor/PlainEditor"; -import type { EditorController } from "@/components/MemoEditor/types/editorController"; - -function setup(initialContent = "") { - const ref = createRef(); - render( - , - ); - const controller = ref.current as EditorController; - const textarea = screen.getByPlaceholderText("memo") as HTMLTextAreaElement; - return { controller, textarea }; -} - -describe("PlainEditor EditorController", () => { - it("getMarkdown/setMarkdown mirror the textarea value", () => { - const { controller, textarea } = setup("hello"); - expect(controller.getMarkdown()).toBe("hello"); - controller.setMarkdown("changed"); - expect(textarea.value).toBe("changed"); - }); - - it("isEmpty treats whitespace-only content as empty", () => { - const { controller } = setup(" \n "); - expect(controller.isEmpty()).toBe(true); - }); - - it("insertMarkdown separates blocks with blank lines", () => { - const { controller, textarea } = setup("first line"); - textarea.setSelectionRange(10, 10); - controller.insertMarkdown("transcribed"); - expect(textarea.value).toBe("first line\n\ntranscribed"); - }); - - // The raw textarea is an honest fallback with no rich-formatting capability - // (controller.formatting is undefined); the focus-mode toolbar is WYSIWYG-only. - it("exposes no formatting capability", () => { - const { controller } = setup("x"); - expect(controller.formatting).toBeUndefined(); - }); - - it("insertMarkdown with an empty string is a no-op", () => { - const { controller, textarea } = setup("unchanged"); - textarea.setSelectionRange(0, 9); - controller.insertMarkdown(""); - expect(textarea.value).toBe("unchanged"); - }); - - it("hasFocus reflects the active element", () => { - const { controller, textarea } = setup("x"); - expect(controller.hasFocus()).toBe(false); - textarea.focus(); - expect(controller.hasFocus()).toBe(true); - }); -}); diff --git a/web/tests/setup.ts b/web/tests/setup.ts index ffda4f48..79e46d4c 100644 --- a/web/tests/setup.ts +++ b/web/tests/setup.ts @@ -19,6 +19,10 @@ if (typeof document !== "undefined") { Range.prototype.getBoundingClientRect = () => ({ x: 0, y: 0, top: 0, left: 0, bottom: 0, right: 0, width: 0, height: 0, toJSON: () => ({}) }) as DOMRect; } + // CodeMirror probes additional layout APIs jsdom doesn't implement while measuring. + if (typeof Element !== "undefined" && !Element.prototype.getClientRects) { + Element.prototype.getClientRects = () => [] as unknown as DOMRectList; + } } // jsdom runs with an opaque origin (no URL set), so its built-in localStorage diff --git a/web/tests/suggestion-extension.test.ts b/web/tests/suggestion-extension.test.ts deleted file mode 100644 index 5939be92..00000000 --- a/web/tests/suggestion-extension.test.ts +++ /dev/null @@ -1,77 +0,0 @@ -import { Editor } from "@tiptap/core"; -import { describe, expect, it } from "vitest"; -import { buildExtensions } from "@/components/MemoEditor/Editor/extensions"; -import { createSuggestionExtension } from "@/components/MemoEditor/Editor/suggestionExtension"; - -describe("createSuggestionExtension", () => { - it("creates a Tiptap extension with the configured name", () => { - const ext = createSuggestionExtension({ - name: "fooSuggestion", - char: "@", - items: () => [], - command: () => {}, - renderItem: (item) => item, - getItemKey: (item) => item, - }); - expect(ext.name).toBe("fooSuggestion"); - }); - - it("contributes its suggestion plugin to the editor", () => { - const base = new Editor({ extensions: buildExtensions(), content: "", contentType: "markdown" }); - const baseline = base.state.plugins.length; - base.destroy(); - - const withSuggestion = new Editor({ - extensions: [ - ...buildExtensions(), - createSuggestionExtension({ - name: "pluginProbe", - char: "@", - items: () => [], - command: () => {}, - renderItem: (item) => item, - getItemKey: (item) => item, - }), - ], - content: "", - contentType: "markdown", - }); - try { - expect(withSuggestion.state.plugins.length).toBeGreaterThan(baseline); - } finally { - withSuggestion.destroy(); - } - }); - - it("lets multiple triggers coexist in one editor without plugin-key collision", () => { - const tagLike = createSuggestionExtension({ - name: "tagLike", - char: "#", - items: () => ["alpha"], - command: () => {}, - renderItem: (item) => item, - getItemKey: (item) => item, - }); - const slashLike = createSuggestionExtension({ - name: "slashLike", - char: "/", - items: () => ["heading"], - command: () => {}, - renderItem: (item) => item, - getItemKey: (item) => item, - }); - - const editor = new Editor({ - extensions: [...buildExtensions(), tagLike, slashLike], - content: "", - contentType: "markdown", - }); - try { - const names = editor.extensionManager.extensions.map((e) => e.name); - expect(names).toContain("tagLike"); - expect(names).toContain("slashLike"); - } finally { - editor.destroy(); - } - }); -}); diff --git a/web/tests/suggestion-menu.test.tsx b/web/tests/suggestion-menu.test.tsx deleted file mode 100644 index d28e3b84..00000000 --- a/web/tests/suggestion-menu.test.tsx +++ /dev/null @@ -1,176 +0,0 @@ -import { act, fireEvent, render, screen } from "@testing-library/react"; -import { createRef } from "react"; -import { createRoot } from "react-dom/client"; -import { describe, expect, it, vi } from "vitest"; -import { createSuggestionRenderer, SuggestionMenu, type SuggestionMenuHandle } from "@/components/MemoEditor/Editor/suggestionMenu"; - -function setup(items = ["alpha", "beta", "gamma"]) { - const command = vi.fn(); - const ref = createRef(); - render( - item} - renderItem={(item: string) => #{item}} - />, - ); - return { command, ref }; -} - -const keyDown = (key: string) => ({ event: new KeyboardEvent("keydown", { key }) }) as never; - -describe("SuggestionMenu", () => { - it("renders all items", () => { - setup(); - expect(screen.getByText("#alpha")).toBeInTheDocument(); - expect(screen.getByText("#gamma")).toBeInTheDocument(); - }); - - it("navigates with arrows and selects with Enter", () => { - const { command, ref } = setup(); - expect(ref.current?.onKeyDown(keyDown("ArrowDown"))).toBe(true); - expect(ref.current?.onKeyDown(keyDown("Enter"))).toBe(true); - expect(command).toHaveBeenCalledWith("beta"); - }); - - it("selects on mouse down", () => { - const { command } = setup(); - fireEvent.mouseDown(screen.getByText("#gamma")); - expect(command).toHaveBeenCalledWith("gamma"); - }); - - it("renders nothing for an empty list and lets keys pass through", () => { - const { ref } = setup([]); - expect(document.querySelector("[data-suggestion-menu]")).toBeNull(); - expect(ref.current?.onKeyDown(keyDown("Enter"))).toBe(false); - }); - - it("scrolls the selected item into view on arrow navigation", async () => { - const { ref } = setup(["a", "b", "c"]); - // Assign scrollIntoView spy on HTMLElement.prototype so it survives re-renders. - const spy = vi.fn(); - const original = HTMLElement.prototype.scrollIntoView; - HTMLElement.prototype.scrollIntoView = spy; - try { - await act(async () => { - ref.current?.onKeyDown(keyDown("ArrowDown")); - }); - expect(spy).toHaveBeenCalled(); - } finally { - HTMLElement.prototype.scrollIntoView = original; - } - }); -}); - -describe("createSuggestionRenderer blur handling", () => { - /** - * Build a minimal fake editor that satisfies the ReactRenderer constructor: - * - isEditorContentInitialized=true causes ReactRenderer to call flushSync, - * so the component renders synchronously. - * - contentComponent.setRenderer renders the React element into renderer.element - * via createPortal, making [data-suggestion-menu] visible in the DOM. - */ - function makeFakeEditor() { - const handlers: Record void>> = {}; - const fakeEditor = { - isEditorContentInitialized: true, - contentComponent: { - setRenderer: vi.fn((_id: string, renderer: { reactElement: React.ReactNode; element: HTMLElement }) => { - // Mimic the real portal: render the element directly into renderer.element - // via React so it shows up in the DOM when appended to document.body. - const root = createRoot(renderer.element); - act(() => { - root.render(renderer.reactElement as React.ReactElement); - }); - }), - removeRenderer: vi.fn(), - }, - on: vi.fn((event: string, handler: () => void) => { - (handlers[event] ??= []).push(handler); - }), - off: vi.fn(), - handlers, - }; - return fakeEditor; - } - - it("destroys the popup container and unsubscribes on editor blur", () => { - const fakeEditor = makeFakeEditor(); - - const renderFn = createSuggestionRenderer({ - renderItem: (item: string) => {item}, - getItemKey: (item: string) => item, - }); - - const lifecycle = renderFn!(); - - act(() => { - lifecycle!.onStart!({ - clientRect: () => null, - editor: fakeEditor as never, - items: ["x"], - command: vi.fn(), - query: "", - text: "", - decorationNode: null, - } as never); - }); - - // The outer container div must be attached to document.body. - const container = document.body.lastElementChild as HTMLElement; - expect(container).not.toBeNull(); - expect(container?.style.position).toBe("absolute"); - expect(container?.isConnected).toBe(true); - - expect(fakeEditor.on).toHaveBeenCalledWith("blur", expect.any(Function)); - - // Simulate the editor emitting "blur". - const blurHandler = fakeEditor.handlers["blur"]?.[0]; - expect(blurHandler).toBeDefined(); - act(() => { - blurHandler?.(); - }); - - // Container must be detached from the document. - expect(container.isConnected).toBe(false); - // off must have been called to avoid leaking the listener. - expect(fakeEditor.off).toHaveBeenCalledWith("blur", expect.any(Function)); - }); - - it("is idempotent — calling destroy twice does not throw", () => { - const fakeEditor = { - isEditorContentInitialized: false, - on: vi.fn(), - off: vi.fn(), - }; - - const renderFn = createSuggestionRenderer({ - renderItem: (item: string) => {item}, - getItemKey: (item: string) => item, - }); - - const lifecycle = renderFn!(); - - act(() => { - lifecycle!.onStart!({ - clientRect: () => null, - editor: fakeEditor as never, - items: ["x"], - command: vi.fn(), - query: "", - text: "", - decorationNode: null, - } as never); - }); - - act(() => { - lifecycle!.onExit!({} as never); - // Second call (e.g. from Escape after onExit) must not throw. - lifecycle!.onExit!({} as never); - }); - - expect(fakeEditor.off).toHaveBeenCalledTimes(1); - }); -});