feat(web): markdown WYSIWYG editor with raw-mode toggle (#6030)
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
parent
8080bd10e1
commit
797f1ff15d
54 changed files with 6005 additions and 68 deletions
2621
docs/superpowers/plans/2026-06-11-markdown-wysiwyg-editor.md
Normal file
2621
docs/superpowers/plans/2026-06-11-markdown-wysiwyg-editor.md
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -0,0 +1,168 @@
|
||||||
|
# Markdown WYSIWYG Editor — Design
|
||||||
|
|
||||||
|
**Date:** 2026-06-11
|
||||||
|
**Status:** Approved pending user review
|
||||||
|
|
||||||
|
## Goal
|
||||||
|
|
||||||
|
Replace the plain `<textarea>` memo editor with a modern WYSIWYG editor that renders
|
||||||
|
markdown syntax live as the user types (Linear / Claude.ai composer style) while keeping
|
||||||
|
markdown — not HTML — as the only storage and API format. A toggle lets users drop back
|
||||||
|
to the raw textarea editor at any time.
|
||||||
|
|
||||||
|
## Background
|
||||||
|
|
||||||
|
The current editor (`web/src/components/MemoEditor/Editor/index.tsx`) is a textarea with
|
||||||
|
hand-rolled features layered on top: tag suggestions (`#`), slash commands (`/`),
|
||||||
|
Ctrl+B/I markdown shortcuts, list auto-continuation, URL-paste-to-link, IME composition
|
||||||
|
plumbing, auto-grow height, and a toolbar that inserts raw markdown strings through an
|
||||||
|
imperative, character-offset-based `EditorRefActions` API.
|
||||||
|
|
||||||
|
Live markdown editing is among the most-requested memos features
|
||||||
|
(usememos/memos#2216, #3495, #766, #4259).
|
||||||
|
|
||||||
|
### Prior art (researched 2026-06)
|
||||||
|
|
||||||
|
- **Linear** builds its editor directly on **ProseMirror** (+ y-prosemirror for collab).
|
||||||
|
- **ChatGPT's composer** is raw **ProseMirror**.
|
||||||
|
- **Claude.ai's composer** is **Tiptap** (headless framework on ProseMirror).
|
||||||
|
|
||||||
|
All three references are ProseMirror-family WYSIWYG editors with markdown input rules.
|
||||||
|
|
||||||
|
### Library options considered
|
||||||
|
|
||||||
|
| Option | Verdict |
|
||||||
|
|---|---|
|
||||||
|
| **Tiptap v3 + `@tiptap/markdown`** | **Chosen.** Claude.ai's stack. Best ecosystem; StarterKit covers the core set with input rules; Suggestion utility replaces hand-rolled tag/slash popups; official bidirectional markdown (early release — gated by a spike). First-class React bindings; best-in-class IME handling via ProseMirror. ~100 KB gzipped. |
|
||||||
|
| Milkdown | Markdown-first ProseMirror + remark; strongest fidelity by design, but thin UX building blocks, small community, low bus factor. |
|
||||||
|
| Raw ProseMirror + prosemirror-markdown | Linear's literal approach; maximum control, most engineering effort for the least product difference. |
|
||||||
|
| Lexical | Non-ProseMirror engine; markdown is a conversion target, historically weaker IME. |
|
||||||
|
| CodeMirror 6 live-preview (Obsidian style) | Perfect byte fidelity but a different UX than the named references; largely DIY. |
|
||||||
|
|
||||||
|
## Decisions (user-confirmed)
|
||||||
|
|
||||||
|
1. **Raw mode stays**: a per-editor toggle switches between WYSIWYG and the current
|
||||||
|
textarea editor. (Revised from an earlier "full replacement" decision.)
|
||||||
|
2. **Fidelity contract**: lossless for supported syntax — semantic round-trip for
|
||||||
|
everything the editor models; style normalization (e.g. `*` → `-` bullets) is
|
||||||
|
acceptable. Unknown/exotic syntax is preserved verbatim, never dropped.
|
||||||
|
3. **v1 scope — Linear-style core set** rendered live: bold/italic/strike/inline-code,
|
||||||
|
headings, ordered/unordered/task lists, links, blockquotes, code blocks, and memos
|
||||||
|
`#tags`. Tables, `$…$`/`$$…$$` math, and inline HTML remain literal text in the
|
||||||
|
editor (they still render richly in the memo view after save). Mermaid lives in
|
||||||
|
` ```mermaid ` fences, so it is just a code block while editing.
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
### Editor abstraction
|
||||||
|
|
||||||
|
`EditorContent` hosts one of two implementations behind a shared **`EditorController`**
|
||||||
|
interface:
|
||||||
|
|
||||||
|
- `focus()`, `getMarkdown()`, `setMarkdown()`, `insertMarkdown()`, `isEmpty()`
|
||||||
|
- Formatting **intents**: `toggleBold()`, `toggleItalic()`, `toggleTaskList()`, etc.
|
||||||
|
|
||||||
|
The **Tiptap editor** implements intents as ProseMirror commands. The **textarea editor**
|
||||||
|
implements them exactly as today (wrap selection in `**`). The toolbar dispatches intents
|
||||||
|
and never knows which editor is mounted. The textarea's existing string-surgery API
|
||||||
|
(`EditorRefActions`) becomes internal to the textarea implementation rather than the
|
||||||
|
public contract.
|
||||||
|
|
||||||
|
### Mode toggle
|
||||||
|
|
||||||
|
- A small icon button in the editor toolbar switches modes mid-edit.
|
||||||
|
- Switching is a markdown string handoff: WYSIWYG → raw serializes (the same path as
|
||||||
|
save, so no new fidelity risk); raw → WYSIWYG parses.
|
||||||
|
- The preference persists in localStorage (per device). No backend/proto changes; can
|
||||||
|
graduate to a server-side user setting later.
|
||||||
|
|
||||||
|
### Tiptap editor composition
|
||||||
|
|
||||||
|
Built on `@tiptap/react` `useEditor`. Extensions:
|
||||||
|
|
||||||
|
- **StarterKit** (configured): headings, bold/italic/strike/code, lists, blockquote,
|
||||||
|
code block — all with live input rules (`**bold**` converts as you type).
|
||||||
|
- **TaskList / TaskItem**, **Link** (includes URL-paste-over-selection → link),
|
||||||
|
**Placeholder** (i18n'd), **`@tiptap/markdown`**.
|
||||||
|
- **`Tag`** (custom): inline node for `#tag`, rendered as a styled token, serialized
|
||||||
|
back to `#tag` verbatim. `#` triggers a Suggestion-plugin popup backed by the
|
||||||
|
existing tag store.
|
||||||
|
- **`SlashCommand`** (custom): Suggestion-plugin popup on `/`, replacing
|
||||||
|
`SlashCommands.tsx` in WYSIWYG mode.
|
||||||
|
- **`PreservedBlock`** (custom): the fidelity workhorse — unmodeled constructs
|
||||||
|
(tables, math, inline HTML, unrecognized syntax) are captured at parse time into
|
||||||
|
nodes carrying their raw source, displayed as literal text (subtle mono styling),
|
||||||
|
and re-emitted byte-for-byte on serialize.
|
||||||
|
|
||||||
|
Hand-rolled textarea features that become native or config in WYSIWYG mode:
|
||||||
|
Ctrl+B/I keymaps (StarterKit), list auto-continuation (ProseMirror lists),
|
||||||
|
auto-grow height (contenteditable), IME composition (ProseMirror — better CJK
|
||||||
|
behavior than the textarea plumbing).
|
||||||
|
|
||||||
|
### Data flow
|
||||||
|
|
||||||
|
Unchanged at the boundaries. Memo markdown → `setMarkdown()` on load. On update,
|
||||||
|
serialized markdown (debounced) flows into the existing state reducer as
|
||||||
|
`state.content`, so auto-save, the localStorage draft cache (still a plain markdown
|
||||||
|
string), tag extraction, and the save path are untouched. The backend only ever sees
|
||||||
|
markdown. File paste/drag wires Tiptap `handlePaste`/`handleDrop` into the existing
|
||||||
|
`uploadService`.
|
||||||
|
|
||||||
|
## Fidelity contract
|
||||||
|
|
||||||
|
1. **Supported constructs** round-trip semantically; list-marker style may normalize;
|
||||||
|
content never changes meaning.
|
||||||
|
2. **Unmodeled constructs** round-trip byte-for-byte via `PreservedBlock`.
|
||||||
|
3. **A round-trip corpus test enforces this permanently** (see Testing). It is written
|
||||||
|
first, as a spike, and is the go/no-go gate on `@tiptap/markdown` (early release).
|
||||||
|
If the gate fails and custom Marked tokenizers cannot fix it, the fallback is
|
||||||
|
swapping only the parse/serialize layer to remark (already a memos dependency)
|
||||||
|
while keeping the Tiptap editor — editor and serialization are deliberately
|
||||||
|
decoupled for this reason.
|
||||||
|
|
||||||
|
## Error handling
|
||||||
|
|
||||||
|
- **Load guard (tripwire):** on opening an existing memo, parse → re-serialize →
|
||||||
|
compare semantically. If the round-trip would lose content, log it and show a
|
||||||
|
notice — "this memo contains syntax the editor can't safely edit" — with a
|
||||||
|
one-click switch to raw mode for that memo. Expected never to fire.
|
||||||
|
- **Draft safety:** the localStorage draft cache stays a markdown string on the same
|
||||||
|
debounce as today; drafts are interchangeable between both editor modes.
|
||||||
|
- **Save path:** reuses already-serialized `state.content`; save never triggers a
|
||||||
|
fresh parse, so it gains no new failure mode.
|
||||||
|
|
||||||
|
## Testing
|
||||||
|
|
||||||
|
- **Round-trip corpus test (the spike, written first):** fixture markdown files
|
||||||
|
(GFM, tables, math, mermaid, inline HTML, nested lists, CJK, emoji) → parse →
|
||||||
|
serialize → assert semantic equality for supported syntax, byte equality for
|
||||||
|
preserved blocks. Runs in the existing vitest/jsdom setup.
|
||||||
|
- **Extension unit tests:** `Tag` (parse/serialize/suggestion trigger),
|
||||||
|
`PreservedBlock` (verbatim round-trip), link-paste.
|
||||||
|
- **Component tests** (@testing-library): toolbar intents produce expected markdown
|
||||||
|
in both modes; slash/tag popups open and insert correctly; mode toggle hands
|
||||||
|
content across without loss.
|
||||||
|
- **Manual QA:** CJK IME composition, mobile Safari/Chrome soft keyboards, focus
|
||||||
|
mode, paste-image upload.
|
||||||
|
|
||||||
|
## Rollout
|
||||||
|
|
||||||
|
Feature branch, PR series:
|
||||||
|
|
||||||
|
1. **Spike:** corpus test + `@tiptap/markdown` verdict (throwaway if the gate fails).
|
||||||
|
2. **Core editor:** Tiptap behind `EditorController`, StarterKit set, markdown in/out,
|
||||||
|
wired into the state layer.
|
||||||
|
3. **Memos features:** `Tag` + suggestions, `SlashCommand`, `PreservedBlock`,
|
||||||
|
file paste/drop, toolbar intent conversion.
|
||||||
|
4. **Toggle + refactor:** mode toggle UI and persistence; textarea editor refactored
|
||||||
|
to implement `EditorController` (nothing deleted — it powers raw mode).
|
||||||
|
|
||||||
|
Dependency cost: ~100 KB gzipped (`@tiptap/core`, `@tiptap/react`, extensions,
|
||||||
|
`@tiptap/markdown` + MarkedJS). WYSIWYG is the default mode for all users.
|
||||||
|
|
||||||
|
## Out of scope (v1)
|
||||||
|
|
||||||
|
- Interactive table editing, live KaTeX/mermaid rendering while editing.
|
||||||
|
- Collaborative editing (Yjs).
|
||||||
|
- Server-side persistence of the mode preference.
|
||||||
|
- Mobile apps (web/PWA only — native apps are separate codebases).
|
||||||
|
|
@ -36,6 +36,14 @@
|
||||||
"@tailwindcss/vite": "^4.2.4",
|
"@tailwindcss/vite": "^4.2.4",
|
||||||
"@tanstack/react-query": "^5.100.9",
|
"@tanstack/react-query": "^5.100.9",
|
||||||
"@tanstack/react-query-devtools": "^5.100.9",
|
"@tanstack/react-query-devtools": "^5.100.9",
|
||||||
|
"@tiptap/core": "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",
|
"class-variance-authority": "^0.7.1",
|
||||||
"clsx": "^2.1.1",
|
"clsx": "^2.1.1",
|
||||||
"copy-to-clipboard": "^4.0.2",
|
"copy-to-clipboard": "^4.0.2",
|
||||||
|
|
@ -49,6 +57,7 @@
|
||||||
"leaflet.markercluster": "^1.5.3",
|
"leaflet.markercluster": "^1.5.3",
|
||||||
"lodash-es": "^4.18.1",
|
"lodash-es": "^4.18.1",
|
||||||
"lucide-react": "^1.14.0",
|
"lucide-react": "^1.14.0",
|
||||||
|
"marked": "^17.0.6",
|
||||||
"mdast-util-from-markdown": "^2.0.3",
|
"mdast-util-from-markdown": "^2.0.3",
|
||||||
"mdast-util-gfm": "^3.1.0",
|
"mdast-util-gfm": "^3.1.0",
|
||||||
"mermaid": "^11.14.0",
|
"mermaid": "^11.14.0",
|
||||||
|
|
|
||||||
|
|
@ -65,6 +65,30 @@ importers:
|
||||||
'@tanstack/react-query-devtools':
|
'@tanstack/react-query-devtools':
|
||||||
specifier: ^5.100.9
|
specifier: ^5.100.9
|
||||||
version: 5.100.9(@tanstack/react-query@5.100.9(react@19.2.6))(react@19.2.6)
|
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-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:
|
class-variance-authority:
|
||||||
specifier: ^0.7.1
|
specifier: ^0.7.1
|
||||||
version: 0.7.1
|
version: 0.7.1
|
||||||
|
|
@ -104,6 +128,9 @@ importers:
|
||||||
lucide-react:
|
lucide-react:
|
||||||
specifier: ^1.14.0
|
specifier: ^1.14.0
|
||||||
version: 1.14.0(react@19.2.6)
|
version: 1.14.0(react@19.2.6)
|
||||||
|
marked:
|
||||||
|
specifier: ^17.0.6
|
||||||
|
version: 17.0.6
|
||||||
mdast-util-from-markdown:
|
mdast-util-from-markdown:
|
||||||
specifier: ^2.0.3
|
specifier: ^2.0.3
|
||||||
version: 2.0.3
|
version: 2.0.3
|
||||||
|
|
@ -1328,6 +1355,167 @@ packages:
|
||||||
'@types/react-dom':
|
'@types/react-dom':
|
||||||
optional: true
|
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':
|
'@tybys/wasm-util@0.10.2':
|
||||||
resolution: {integrity: sha512-RoBvJ2X0wuKlWFIjrwffGw1IqZHKQqzIchKaadZZfnNpsAYp2mM0h36JtPCjNDAHGgYez/15uMBpfGwchhiMgg==}
|
resolution: {integrity: sha512-RoBvJ2X0wuKlWFIjrwffGw1IqZHKQqzIchKaadZZfnNpsAYp2mM0h36JtPCjNDAHGgYez/15uMBpfGwchhiMgg==}
|
||||||
|
|
||||||
|
|
@ -1507,6 +1695,9 @@ packages:
|
||||||
'@types/unist@3.0.3':
|
'@types/unist@3.0.3':
|
||||||
resolution: {integrity: sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==}
|
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':
|
'@ungap/structured-clone@1.3.0':
|
||||||
resolution: {integrity: sha512-WmoN8qaIAo7WTYWbAZuG8PYEhn5fkz7dZrqTBZ7dtt//lL2Gwms1IcnQ5yHqjDfX8Ft5j4YzDM23f87zBfDe9g==}
|
resolution: {integrity: sha512-WmoN8qaIAo7WTYWbAZuG8PYEhn5fkz7dZrqTBZ7dtt//lL2Gwms1IcnQ5yHqjDfX8Ft5j4YzDM23f87zBfDe9g==}
|
||||||
|
|
||||||
|
|
@ -1978,6 +2169,10 @@ packages:
|
||||||
extend@3.0.2:
|
extend@3.0.2:
|
||||||
resolution: {integrity: sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==}
|
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:
|
fdir@6.5.0:
|
||||||
resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==}
|
resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==}
|
||||||
engines: {node: '>=12.0.0'}
|
engines: {node: '>=12.0.0'}
|
||||||
|
|
@ -2274,6 +2469,9 @@ packages:
|
||||||
lines-and-columns@1.2.4:
|
lines-and-columns@1.2.4:
|
||||||
resolution: {integrity: sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==}
|
resolution: {integrity: sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==}
|
||||||
|
|
||||||
|
linkifyjs@4.3.3:
|
||||||
|
resolution: {integrity: sha512-P8aEP5U/D1/IlTY2OeYsErdwh9bGuLE30NcXtKEjgdHcahveQoQwM2yZNsioQHsWFz0P7KKudisbrzCgR0sDHg==}
|
||||||
|
|
||||||
lodash-es@4.18.1:
|
lodash-es@4.18.1:
|
||||||
resolution: {integrity: sha512-J8xewKD/Gk22OZbhpOVSwcs60zhd95ESDwezOFuA3/099925PdHJ7OFHNTGtajL3AlZkykD32HykiMo+BIBI8A==}
|
resolution: {integrity: sha512-J8xewKD/Gk22OZbhpOVSwcs60zhd95ESDwezOFuA3/099925PdHJ7OFHNTGtajL3AlZkykD32HykiMo+BIBI8A==}
|
||||||
|
|
||||||
|
|
@ -2313,6 +2511,11 @@ packages:
|
||||||
engines: {node: '>= 20'}
|
engines: {node: '>= 20'}
|
||||||
hasBin: true
|
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:
|
mdast-util-find-and-replace@3.0.2:
|
||||||
resolution: {integrity: sha512-Tmd1Vg/m3Xz43afeNxDIhWRtFZgM2VLyaf4vSTYwudTyeuTneoL3qtWMA5jeLyz/O1vDJmmV4QuScFCA2tBPwg==}
|
resolution: {integrity: sha512-Tmd1Vg/m3Xz43afeNxDIhWRtFZgM2VLyaf4vSTYwudTyeuTneoL3qtWMA5jeLyz/O1vDJmmV4QuScFCA2tBPwg==}
|
||||||
|
|
||||||
|
|
@ -2483,6 +2686,9 @@ packages:
|
||||||
obug@2.1.1:
|
obug@2.1.1:
|
||||||
resolution: {integrity: sha512-uTqF9MuPraAQ+IsnPf366RG4cP9RtUi7MLO1N3KEc+wb0a6yKpeL0lmk2IB1jY5KHPAlTc6T/JRdC/YqxHNwkQ==}
|
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:
|
package-manager-detector@1.6.0:
|
||||||
resolution: {integrity: sha512-61A5ThoTiDG/C8s8UMZwSorAGwMJ0ERVGj2OjoW5pAalsNOg15+iQiPzrLJ4jhZ1HJzmC2PIHT2oEiH3R5fzNA==}
|
resolution: {integrity: sha512-61A5ThoTiDG/C8s8UMZwSorAGwMJ0ERVGj2OjoW5pAalsNOg15+iQiPzrLJ4jhZ1HJzmC2PIHT2oEiH3R5fzNA==}
|
||||||
|
|
||||||
|
|
@ -2543,6 +2749,45 @@ packages:
|
||||||
property-information@7.1.0:
|
property-information@7.1.0:
|
||||||
resolution: {integrity: sha512-TwEZ+X+yCJmYfL7TPUOcvBZ4QfoT5YenQiJuX//0th53DE6w0xxLEtfK3iyryQFddXuvkIk51EEgrJQ0WJkOmQ==}
|
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:
|
punycode@2.3.1:
|
||||||
resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==}
|
resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==}
|
||||||
engines: {node: '>=6'}
|
engines: {node: '>=6'}
|
||||||
|
|
@ -2706,6 +2951,9 @@ packages:
|
||||||
engines: {node: ^20.19.0 || >=22.12.0}
|
engines: {node: ^20.19.0 || >=22.12.0}
|
||||||
hasBin: true
|
hasBin: true
|
||||||
|
|
||||||
|
rope-sequence@1.3.4:
|
||||||
|
resolution: {integrity: sha512-UT5EDe2cu2E/6O4igUr5PSFs23nvvukicWHx6GnOPlHAiiYbzNuCRQCuiUdHJQcqKalLKlrYJnjY0ySGsXNQXQ==}
|
||||||
|
|
||||||
roughjs@4.6.6:
|
roughjs@4.6.6:
|
||||||
resolution: {integrity: sha512-ZUz/69+SYpFN/g/lUlo2FXcIjRkSu3nDarreVdGGndHEBJ6cXPdKguS8JGxwj5HA5xIbVKSmLgr5b3AWxtRfvQ==}
|
resolution: {integrity: sha512-ZUz/69+SYpFN/g/lUlo2FXcIjRkSu3nDarreVdGGndHEBJ6cXPdKguS8JGxwj5HA5xIbVKSmLgr5b3AWxtRfvQ==}
|
||||||
|
|
||||||
|
|
@ -3041,6 +3289,9 @@ packages:
|
||||||
vscode-uri@3.1.0:
|
vscode-uri@3.1.0:
|
||||||
resolution: {integrity: sha512-/BpdSx+yCQGnCvecbyXdxHDkuk55/G3xwnC0GqY4gmQ3j+A+g8kzzgB4Nk/SINjqn6+waqw3EgbVF2QKExkRxQ==}
|
resolution: {integrity: sha512-/BpdSx+yCQGnCvecbyXdxHDkuk55/G3xwnC0GqY4gmQ3j+A+g8kzzgB4Nk/SINjqn6+waqw3EgbVF2QKExkRxQ==}
|
||||||
|
|
||||||
|
w3c-keyname@2.2.8:
|
||||||
|
resolution: {integrity: sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==}
|
||||||
|
|
||||||
w3c-xmlserializer@5.0.0:
|
w3c-xmlserializer@5.0.0:
|
||||||
resolution: {integrity: sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==}
|
resolution: {integrity: sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==}
|
||||||
engines: {node: '>=18'}
|
engines: {node: '>=18'}
|
||||||
|
|
@ -4112,6 +4363,189 @@ snapshots:
|
||||||
'@types/react': 19.2.14
|
'@types/react': 19.2.14
|
||||||
'@types/react-dom': 19.2.3(@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':
|
'@tybys/wasm-util@0.10.2':
|
||||||
dependencies:
|
dependencies:
|
||||||
tslib: 2.8.1
|
tslib: 2.8.1
|
||||||
|
|
@ -4323,6 +4757,8 @@ snapshots:
|
||||||
|
|
||||||
'@types/unist@3.0.3': {}
|
'@types/unist@3.0.3': {}
|
||||||
|
|
||||||
|
'@types/use-sync-external-store@0.0.6': {}
|
||||||
|
|
||||||
'@ungap/structured-clone@1.3.0': {}
|
'@ungap/structured-clone@1.3.0': {}
|
||||||
|
|
||||||
'@upsetjs/venn.js@2.0.0':
|
'@upsetjs/venn.js@2.0.0':
|
||||||
|
|
@ -4793,6 +5229,8 @@ snapshots:
|
||||||
|
|
||||||
extend@3.0.2: {}
|
extend@3.0.2: {}
|
||||||
|
|
||||||
|
fast-equals@5.4.0: {}
|
||||||
|
|
||||||
fdir@6.5.0(picomatch@4.0.4):
|
fdir@6.5.0(picomatch@4.0.4):
|
||||||
optionalDependencies:
|
optionalDependencies:
|
||||||
picomatch: 4.0.4
|
picomatch: 4.0.4
|
||||||
|
|
@ -5110,6 +5548,8 @@ snapshots:
|
||||||
|
|
||||||
lines-and-columns@1.2.4: {}
|
lines-and-columns@1.2.4: {}
|
||||||
|
|
||||||
|
linkifyjs@4.3.3: {}
|
||||||
|
|
||||||
lodash-es@4.18.1: {}
|
lodash-es@4.18.1: {}
|
||||||
|
|
||||||
lodash.debounce@4.0.8: {}
|
lodash.debounce@4.0.8: {}
|
||||||
|
|
@ -5138,6 +5578,8 @@ snapshots:
|
||||||
|
|
||||||
marked@16.4.2: {}
|
marked@16.4.2: {}
|
||||||
|
|
||||||
|
marked@17.0.6: {}
|
||||||
|
|
||||||
mdast-util-find-and-replace@3.0.2:
|
mdast-util-find-and-replace@3.0.2:
|
||||||
dependencies:
|
dependencies:
|
||||||
'@types/mdast': 4.0.4
|
'@types/mdast': 4.0.4
|
||||||
|
|
@ -5554,6 +5996,8 @@ snapshots:
|
||||||
|
|
||||||
obug@2.1.1: {}
|
obug@2.1.1: {}
|
||||||
|
|
||||||
|
orderedmap@2.1.1: {}
|
||||||
|
|
||||||
package-manager-detector@1.6.0: {}
|
package-manager-detector@1.6.0: {}
|
||||||
|
|
||||||
parent-module@1.0.1:
|
parent-module@1.0.1:
|
||||||
|
|
@ -5624,6 +6068,80 @@ snapshots:
|
||||||
|
|
||||||
property-information@7.1.0: {}
|
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: {}
|
punycode@2.3.1: {}
|
||||||
|
|
||||||
react-dom@19.2.6(react@19.2.6):
|
react-dom@19.2.6(react@19.2.6):
|
||||||
|
|
@ -5839,6 +6357,8 @@ snapshots:
|
||||||
'@rolldown/binding-win32-arm64-msvc': 1.0.0-rc.18
|
'@rolldown/binding-win32-arm64-msvc': 1.0.0-rc.18
|
||||||
'@rolldown/binding-win32-x64-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:
|
roughjs@4.6.6:
|
||||||
dependencies:
|
dependencies:
|
||||||
hachure-fill: 0.5.2
|
hachure-fill: 0.5.2
|
||||||
|
|
@ -6109,6 +6629,8 @@ snapshots:
|
||||||
|
|
||||||
vscode-uri@3.1.0: {}
|
vscode-uri@3.1.0: {}
|
||||||
|
|
||||||
|
w3c-keyname@2.2.8: {}
|
||||||
|
|
||||||
w3c-xmlserializer@5.0.0:
|
w3c-xmlserializer@5.0.0:
|
||||||
dependencies:
|
dependencies:
|
||||||
xml-name-validator: 5.0.0
|
xml-name-validator: 5.0.0
|
||||||
|
|
|
||||||
63
web/src/components/MemoEditor/Editor/controllerAdapter.ts
Normal file
63
web/src/components/MemoEditor/Editor/controllerAdapter.ts
Normal file
|
|
@ -0,0 +1,63 @@
|
||||||
|
import type { EditorController } from "../types/editorController";
|
||||||
|
import type { EditorRefActions } from "./index";
|
||||||
|
import { toggleTextStyle } from "./shortcuts";
|
||||||
|
|
||||||
|
const TASK_PREFIX = "- [ ] ";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adapts the textarea editor's imperative string-surgery API to the shared
|
||||||
|
* EditorController contract. Takes a getter because the underlying ref is
|
||||||
|
* populated after mount and may swap when the editor remounts.
|
||||||
|
*/
|
||||||
|
export function createTextareaController(getActions: () => EditorRefActions | null): EditorController {
|
||||||
|
return {
|
||||||
|
focus: () => getActions()?.focus(),
|
||||||
|
hasFocus: () => {
|
||||||
|
const element = getActions()?.getEditor();
|
||||||
|
return Boolean(element) && document.activeElement === element;
|
||||||
|
},
|
||||||
|
isEmpty: () => (getActions()?.getContent() ?? "").trim() === "",
|
||||||
|
getMarkdown: () => getActions()?.getContent() ?? "",
|
||||||
|
setMarkdown: (markdown) => getActions()?.setContent(markdown),
|
||||||
|
insertMarkdown: (markdown) => {
|
||||||
|
const actions = getActions();
|
||||||
|
if (!actions) return;
|
||||||
|
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: () => getActions()?.scrollToCursor(),
|
||||||
|
selectAll: () => {
|
||||||
|
const actions = getActions();
|
||||||
|
if (!actions) return;
|
||||||
|
actions.setCursorPosition(0, actions.getContent().length);
|
||||||
|
},
|
||||||
|
toggleBold: () => {
|
||||||
|
const actions = getActions();
|
||||||
|
if (actions) toggleTextStyle(actions, "**");
|
||||||
|
},
|
||||||
|
toggleItalic: () => {
|
||||||
|
const actions = getActions();
|
||||||
|
if (actions) toggleTextStyle(actions, "*");
|
||||||
|
},
|
||||||
|
toggleTaskList: () => {
|
||||||
|
const actions = getActions();
|
||||||
|
if (!actions) return;
|
||||||
|
const lineNumber = actions.getCursorLineNumber();
|
||||||
|
const line = actions.getLine(lineNumber);
|
||||||
|
const taskMatch = line.match(/^(\s*)- \[[ xX]\] /);
|
||||||
|
if (taskMatch) {
|
||||||
|
actions.setLine(lineNumber, taskMatch[1] + line.slice(taskMatch[0].length));
|
||||||
|
} else {
|
||||||
|
const indentMatch = line.match(/^(\s*)/);
|
||||||
|
const indent = indentMatch?.[1] ?? "";
|
||||||
|
actions.setLine(lineNumber, `${indent}${TASK_PREFIX}${line.slice(indent.length)}`);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
@ -40,7 +40,7 @@ export function insertHyperlink(editor: EditorRefActions, url?: string): void {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function toggleTextStyle(editor: EditorRefActions, delimiter: string): void {
|
export function toggleTextStyle(editor: EditorRefActions, delimiter: string): void {
|
||||||
const cursorPosition = editor.getCursorPosition();
|
const cursorPosition = editor.getCursorPosition();
|
||||||
const selectedContent = editor.getSelectedContent();
|
const selectedContent = editor.getSelectedContent();
|
||||||
const isStyled = isTextStyled(selectedContent, delimiter);
|
const isStyled = isTextStyled(selectedContent, delimiter);
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@
|
||||||
|
|
||||||
## Overview
|
## Overview
|
||||||
|
|
||||||
MemoEditor uses a three-layer architecture for better separation of concerns and testability.
|
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.
|
||||||
|
|
||||||
## Architecture
|
## Architecture
|
||||||
|
|
||||||
|
|
@ -11,10 +11,12 @@ MemoEditor uses a three-layer architecture for better separation of concerns and
|
||||||
│ Presentation Layer (Components) │
|
│ Presentation Layer (Components) │
|
||||||
│ - EditorToolbar, EditorContent, etc. │
|
│ - EditorToolbar, EditorContent, etc. │
|
||||||
└─────────────────┬───────────────────────┘
|
└─────────────────┬───────────────────────┘
|
||||||
│
|
│ EditorController
|
||||||
┌─────────────────▼───────────────────────┐
|
┌─────────────────▼───────────────────────┐
|
||||||
│ State Layer (Reducer + Context) │
|
│ State Layer (Reducer + Context) │
|
||||||
│ - state/, useEditorContext() │
|
│ - state/, useEditorContext() │
|
||||||
|
│ - state.content ← markdown (source │
|
||||||
|
│ of truth for both editor modes) │
|
||||||
└─────────────────┬───────────────────────┘
|
└─────────────────┬───────────────────────┘
|
||||||
│
|
│
|
||||||
┌─────────────────▼───────────────────────┐
|
┌─────────────────▼───────────────────────┐
|
||||||
|
|
@ -28,13 +30,34 @@ MemoEditor uses a three-layer architecture for better separation of concerns and
|
||||||
```
|
```
|
||||||
MemoEditor/
|
MemoEditor/
|
||||||
├── state/ # State management (reducer, actions, context)
|
├── state/ # State management (reducer, actions, context)
|
||||||
├── services/ # Business logic (pure functions)
|
├── services/ # Business logic (pure functions)
|
||||||
├── components/ # UI components
|
├── components/ # UI components
|
||||||
├── hooks/ # React hooks (utilities)
|
│ ├── EditorContent.tsx # Hosts the active editor; exposes mode-routing controller
|
||||||
├── Editor/ # Core editor component
|
│ ├── EditorToolbar.tsx # Toolbar including the mode toggle button
|
||||||
├── Toolbar/ # Toolbar components
|
│ └── ...
|
||||||
|
├── hooks/ # React hooks (utilities)
|
||||||
|
│ ├── useMemoInit.ts # Initializes editor content; load guard for WYSIWYG
|
||||||
|
│ └── ...
|
||||||
|
├── Editor/ # Textarea (raw mode) implementation
|
||||||
|
│ ├── controllerAdapter.ts # Adapts EditorRefActions → EditorController
|
||||||
|
│ ├── TagSuggestions.tsx # # popup for raw mode
|
||||||
|
│ ├── SlashCommands.tsx # / popup for raw mode
|
||||||
|
│ └── ...
|
||||||
|
├── TiptapEditor/ # Tiptap WYSIWYG implementation
|
||||||
|
│ ├── 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
|
||||||
|
│ ├── TagSuggestion.ts # # popup for WYSIWYG mode
|
||||||
|
│ ├── SlashCommand.ts # / popup for WYSIWYG mode
|
||||||
|
│ └── suggestionMenu.tsx # Shared suggestion popup renderer (used by both above)
|
||||||
|
├── Toolbar/ # Toolbar sub-components (InsertMenu, VisibilitySelector)
|
||||||
|
├── editorMode.ts # EditorMode type + localStorage persistence helpers
|
||||||
├── constants.ts
|
├── constants.ts
|
||||||
└── types/
|
└── types/
|
||||||
|
├── editorController.ts # EditorController interface (the cross-mode contract)
|
||||||
|
└── ...
|
||||||
```
|
```
|
||||||
|
|
||||||
## Key Concepts
|
## Key Concepts
|
||||||
|
|
@ -43,6 +66,42 @@ MemoEditor/
|
||||||
|
|
||||||
Uses `useReducer` + Context for predictable state transitions. All state changes go through action creators.
|
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.
|
||||||
|
|
||||||
|
### Dual-mode editor
|
||||||
|
|
||||||
|
`types/editorController.ts` defines the `EditorController` interface — `focus`, `getMarkdown`, `setMarkdown`, `insertMarkdown`, formatting toggles, etc. — that callers outside an editor implementation must use exclusively.
|
||||||
|
|
||||||
|
- **WYSIWYG mode** (`TiptapEditor/`): Tiptap/ProseMirror rich-text editor. The default mode. Implements `EditorController` directly via `useImperativeHandle` in `TiptapEditor/index.tsx`.
|
||||||
|
- **Raw mode** (`Editor/`): plain textarea. `Editor/controllerAdapter.ts` adapts the textarea's imperative string-surgery API (`EditorRefActions`) to the same `EditorController` contract.
|
||||||
|
|
||||||
|
`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`.
|
||||||
|
|
||||||
|
### Mode toggle
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
### Markdown fidelity layer (TiptapEditor)
|
||||||
|
|
||||||
|
`TiptapEditor/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.
|
||||||
|
|
||||||
|
`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.
|
||||||
|
|
||||||
|
`Tag.ts` models memos `#tags` as a `code: true` text mark, letting tags round-trip byte-identically even inside bold or heading spans.
|
||||||
|
|
||||||
|
### Suggestions
|
||||||
|
|
||||||
|
Both modes provide `#` tag and `/` slash-command suggestion popups, but they are implemented separately:
|
||||||
|
|
||||||
|
- WYSIWYG mode: `TiptapEditor/TagSuggestion.ts` and `TiptapEditor/SlashCommand.ts`, both using the shared `TiptapEditor/suggestionMenu.tsx` renderer.
|
||||||
|
- Raw mode: `Editor/TagSuggestions.tsx` and `Editor/SlashCommands.tsx`.
|
||||||
|
|
||||||
|
### 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.
|
||||||
|
|
||||||
### Services
|
### Services
|
||||||
|
|
||||||
Pure TypeScript functions containing business logic. No React hooks, easy to test.
|
Pure TypeScript functions containing business logic. No React hooks, easy to test.
|
||||||
|
|
@ -51,6 +110,13 @@ Pure TypeScript functions containing business logic. No React hooks, easy to tes
|
||||||
|
|
||||||
Thin presentation components that dispatch actions and render UI.
|
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
|
## Usage
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
|
|
@ -65,7 +131,7 @@ import MemoEditor from "@/components/MemoEditor";
|
||||||
|
|
||||||
## Testing
|
## Testing
|
||||||
|
|
||||||
Services are pure functions - easy to unit test without React.
|
Services are pure functions — easy to unit test without React.
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
const state = mockEditorState();
|
const state = mockEditorState();
|
||||||
|
|
|
||||||
217
web/src/components/MemoEditor/TiptapEditor/PreservedBlock.ts
Normal file
217
web/src/components/MemoEditor/TiptapEditor/PreservedBlock.ts
Normal file
|
|
@ -0,0 +1,217 @@
|
||||||
|
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 <em> 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 `</`) must be a letter and the
|
||||||
|
// tag name only [a-zA-Z0-9-], followed by attributes/`>` — this never
|
||||||
|
// matches autolinks such as <https://example.com> or <mail@example.com>
|
||||||
|
// (`:`/`@` 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 = /^(?:<!--[\s\S]*?-->|<\/?[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,
|
||||||
|
];
|
||||||
91
web/src/components/MemoEditor/TiptapEditor/SlashCommand.ts
Normal file
91
web/src/components/MemoEditor/TiptapEditor/SlashCommand.ts
Normal file
|
|
@ -0,0 +1,91 @@
|
||||||
|
import { type Editor, Extension, type Range } from "@tiptap/core";
|
||||||
|
import { PluginKey } from "@tiptap/pm/state";
|
||||||
|
import Suggestion from "@tiptap/suggestion";
|
||||||
|
import { createElement } from "react";
|
||||||
|
import { createSuggestionRenderer } from "./suggestionMenu";
|
||||||
|
|
||||||
|
export interface SlashCommandItem {
|
||||||
|
name: string;
|
||||||
|
apply: (editor: Editor, range: Range) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
// WYSIWYG counterparts of the raw editor's commands (Editor/commands.ts):
|
||||||
|
// the same four entries, realized as editor commands instead of raw strings.
|
||||||
|
export const slashCommandItems: SlashCommandItem[] = [
|
||||||
|
{
|
||||||
|
name: "todo",
|
||||||
|
apply: (editor, range) => editor.chain().focus().deleteRange(range).toggleTaskList().run(),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "code",
|
||||||
|
apply: (editor, range) => editor.chain().focus().deleteRange(range).toggleCodeBlock().run(),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "link",
|
||||||
|
// After deleteRange + insertContent the marked text node "text" occupies
|
||||||
|
// positions range.from..range.from+4. Select it so the user can overtype
|
||||||
|
// the display text immediately — matching the textarea editor's cursorOffset=1.
|
||||||
|
apply: (editor, range) =>
|
||||||
|
editor
|
||||||
|
.chain()
|
||||||
|
.focus()
|
||||||
|
.deleteRange(range)
|
||||||
|
.insertContent("[text](url)", { contentType: "markdown" })
|
||||||
|
.setTextSelection({ from: range.from, to: range.from + 4 })
|
||||||
|
.run(),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "table",
|
||||||
|
// After insert the preservedBlock text starts at range.from. "| Header …"
|
||||||
|
// has "| " (2 chars) before the first cell label, so range.from+2 lands on
|
||||||
|
// the "H" of "Header" — matching the textarea editor's first-header-cell
|
||||||
|
// cursor placement.
|
||||||
|
apply: (editor, range) =>
|
||||||
|
editor
|
||||||
|
.chain()
|
||||||
|
.focus()
|
||||||
|
.deleteRange(range)
|
||||||
|
.insertContent("| Header | Header |\n| ------ | ------ |\n| Cell | Cell |", { contentType: "markdown" })
|
||||||
|
.setTextSelection(range.from + 2)
|
||||||
|
.run(),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the subset of slash commands whose name starts with `query`
|
||||||
|
* (case-insensitive). Returns the full list when `query` is empty.
|
||||||
|
*/
|
||||||
|
export function filterSlashCommands(query: string): SlashCommandItem[] {
|
||||||
|
const q = query.toLowerCase();
|
||||||
|
return q ? slashCommandItems.filter((item) => item.name.startsWith(q)) : slashCommandItems;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `/` command popup; replaces the raw editor's SlashCommands in WYSIWYG mode. */
|
||||||
|
export const SlashCommand = Extension.create({
|
||||||
|
name: "slashCommand",
|
||||||
|
|
||||||
|
addProseMirrorPlugins() {
|
||||||
|
return [
|
||||||
|
Suggestion<SlashCommandItem>({
|
||||||
|
editor: this.editor,
|
||||||
|
pluginKey: new PluginKey("slashCommand"),
|
||||||
|
char: "/",
|
||||||
|
allowSpaces: false,
|
||||||
|
items: ({ query }) => filterSlashCommands(query),
|
||||||
|
command: ({ editor, range, props: item }) => {
|
||||||
|
item.apply(editor, range);
|
||||||
|
},
|
||||||
|
render: createSuggestionRenderer<SlashCommandItem>({
|
||||||
|
getItemKey: (item) => item.name,
|
||||||
|
renderItem: (item) =>
|
||||||
|
createElement(
|
||||||
|
"span",
|
||||||
|
{ className: "tracking-wide" },
|
||||||
|
createElement("span", { className: "text-muted-foreground" }, "/"),
|
||||||
|
item.name,
|
||||||
|
),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
];
|
||||||
|
},
|
||||||
|
});
|
||||||
158
web/src/components/MemoEditor/TiptapEditor/Tag.ts
Normal file
158
web/src/components/MemoEditor/TiptapEditor/Tag.ts
Normal file
|
|
@ -0,0 +1,158 @@
|
||||||
|
import type { MarkdownToken } from "@tiptap/core";
|
||||||
|
import { InputRule, Mark, mergeAttributes } from "@tiptap/core";
|
||||||
|
import type { TokenizerThis, Tokens } from "marked";
|
||||||
|
import { marked } from "marked";
|
||||||
|
|
||||||
|
// Mirrors the renderer's tag lexer (web/src/utils/remark-plugins/remark-tag.ts):
|
||||||
|
// letters, numbers, symbols, plus _ - / &, max 100 chars. Keep the two in sync.
|
||||||
|
const TAG_CHAR = "[\\p{L}\\p{N}\\p{S}_\\-/&]";
|
||||||
|
const TAG_INPUT_RULE = new RegExp(`(?:^|\\s)#(${TAG_CHAR}{1,100})\\s$`, "u");
|
||||||
|
const TAG_TOKEN_RULE = new RegExp(`^#(${TAG_CHAR}{1,100})`, "u");
|
||||||
|
// Tests the REMAINDER of the source (not a single code unit) so astral-plane
|
||||||
|
// tag characters (emoji et al.) are seen whole, not as lone surrogates.
|
||||||
|
const TAG_CHAR_AHEAD = new RegExp(`^${TAG_CHAR}`, "u");
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tag tokenizer, registered DIRECTLY on the global marked singleton instead of
|
||||||
|
* through `markdownTokenizer`. Two reasons:
|
||||||
|
*
|
||||||
|
* 1. `@tiptap/markdown`'s MarkdownManager wraps `markdownTokenizer.tokenize`
|
||||||
|
* in `tokenizer(src, tokens) { ... tokenize(src, tokens, helper) }` — the
|
||||||
|
* wrapper receives marked's TokenizerThis (with `lexer.state.inLink`) but
|
||||||
|
* does NOT forward it, so a manager-registered tokenizer can never know it
|
||||||
|
* is inside a link label. Registered natively, marked invokes us with
|
||||||
|
* `this.lexer` bound and we can decline inside `[label](url)` the same way
|
||||||
|
* remark-tag skips link nodes.
|
||||||
|
* 2. The manager defaults to the global `marked` export (`markedInstance =
|
||||||
|
* options?.marked ?? marked`) and `web` resolves the exact same marked
|
||||||
|
* module instance as `@tiptap/markdown` does, so this registration is
|
||||||
|
* visible to every lexer the manager creates. Module scope + idempotent:
|
||||||
|
* registered exactly once per page load (the manager's own per-Editor
|
||||||
|
* `marked.use` calls are the accumulation hazard documented in
|
||||||
|
* markdownCodec.ts; this adds a single registration, ever).
|
||||||
|
*
|
||||||
|
* The Tag mark below still declares `markdownTokenName: "memoTag"` +
|
||||||
|
* `parseMarkdown`, which is all the manager needs to route the token.
|
||||||
|
*/
|
||||||
|
function tokenizeTag(this: TokenizerThis, src: string): Tokens.Generic | undefined {
|
||||||
|
// remark-tag skips link nodes entirely; marked sets `state.inLink` while
|
||||||
|
// tokenizing link/reflink labels, so declining here keeps `[see #x](url)`
|
||||||
|
// a plain link label instead of tearing the tag out of it.
|
||||||
|
if (this.lexer?.state?.inLink) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
const match = TAG_TOKEN_RULE.exec(src);
|
||||||
|
if (!match) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
const rest = src.slice(match[0].length);
|
||||||
|
// `#a#b`: decline when the run is directly followed by another `#`, so the
|
||||||
|
// FIRST run stays plain text. NOT full remark parity — remark-tag treats
|
||||||
|
// `#a#b` as two tags and `##x` as all-text, while here `#a#b` becomes text
|
||||||
|
// "#a" + tag "b" and `##x` becomes text "#" + tag "x". The divergence is
|
||||||
|
// visual-only in the editor: both shapes serialize back byte-identically
|
||||||
|
// (the surrounding text nodes re-emit their literal characters).
|
||||||
|
if (rest.startsWith("#")) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
// Runs longer than 100 tag characters are not tags at all in remark-tag
|
||||||
|
// (the whole run stays plain text) — decline instead of splitting the run
|
||||||
|
// into a 100-char tag plus leftover text.
|
||||||
|
if (TAG_CHAR_AHEAD.test(rest)) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
return { type: "memoTag", raw: match[0], text: match[0], tag: match[1] };
|
||||||
|
}
|
||||||
|
|
||||||
|
let tagTokenizerRegistered = false;
|
||||||
|
function registerTagTokenizer() {
|
||||||
|
if (tagTokenizerRegistered) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
tagTokenizerRegistered = true;
|
||||||
|
marked.use({
|
||||||
|
extensions: [
|
||||||
|
{
|
||||||
|
name: "memoTag",
|
||||||
|
level: "inline",
|
||||||
|
start: (src: string) => src.indexOf("#"),
|
||||||
|
tokenizer: tokenizeTag,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
registerTagTokenizer();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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 (input rule) and from markdown (the native marked
|
||||||
|
* tokenizer above).
|
||||||
|
*/
|
||||||
|
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: "inline-block rounded bg-accent text-accent-foreground px-1",
|
||||||
|
}),
|
||||||
|
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);
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
];
|
||||||
|
},
|
||||||
|
|
||||||
|
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) : ""),
|
||||||
|
});
|
||||||
53
web/src/components/MemoEditor/TiptapEditor/TagSuggestion.ts
Normal file
53
web/src/components/MemoEditor/TiptapEditor/TagSuggestion.ts
Normal file
|
|
@ -0,0 +1,53 @@
|
||||||
|
import { Extension } from "@tiptap/core";
|
||||||
|
import { PluginKey } from "@tiptap/pm/state";
|
||||||
|
import Suggestion from "@tiptap/suggestion";
|
||||||
|
import { createElement } from "react";
|
||||||
|
import { createSuggestionRenderer } from "./suggestionMenu";
|
||||||
|
|
||||||
|
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 const TagSuggestion = Extension.create<TagSuggestionOptions>({
|
||||||
|
name: "tagSuggestion",
|
||||||
|
|
||||||
|
addOptions() {
|
||||||
|
return { getTags: () => [] };
|
||||||
|
},
|
||||||
|
|
||||||
|
addProseMirrorPlugins() {
|
||||||
|
return [
|
||||||
|
Suggestion<string>({
|
||||||
|
editor: this.editor,
|
||||||
|
pluginKey: new PluginKey("tagSuggestion"),
|
||||||
|
char: "#",
|
||||||
|
allowSpaces: false,
|
||||||
|
items: ({ query }) => {
|
||||||
|
const tags = this.options.getTags();
|
||||||
|
const q = query.toLowerCase();
|
||||||
|
const filtered = q ? tags.filter((tag) => tag.toLowerCase().includes(q)) : tags;
|
||||||
|
return filtered.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();
|
||||||
|
},
|
||||||
|
render: createSuggestionRenderer<string>({
|
||||||
|
getItemKey: (tag) => tag,
|
||||||
|
renderItem: (tag) =>
|
||||||
|
createElement("span", { className: "truncate" }, createElement("span", { className: "text-muted-foreground mr-1" }, "#"), tag),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
];
|
||||||
|
},
|
||||||
|
});
|
||||||
29
web/src/components/MemoEditor/TiptapEditor/extensions.ts
Normal file
29
web/src/components/MemoEditor/TiptapEditor/extensions.ts
Normal file
|
|
@ -0,0 +1,29 @@
|
||||||
|
import type { AnyExtension } from "@tiptap/core";
|
||||||
|
import { TaskItem, TaskList } from "@tiptap/extension-list";
|
||||||
|
import { Markdown } from "@tiptap/markdown";
|
||||||
|
import StarterKit from "@tiptap/starter-kit";
|
||||||
|
import { preservedExtensions } from "./PreservedBlock";
|
||||||
|
import { Tag } from "./Tag";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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[] {
|
||||||
|
return [
|
||||||
|
StarterKit.configure({
|
||||||
|
heading: { levels: [1, 2, 3, 4, 5, 6] },
|
||||||
|
link: { openOnClick: false },
|
||||||
|
// Markdown has no underline syntax; keeping the extension would let
|
||||||
|
// Ctrl+U create marks that cannot serialize. Out of the schema entirely.
|
||||||
|
underline: false,
|
||||||
|
}),
|
||||||
|
TaskList,
|
||||||
|
TaskItem.configure({ nested: true }),
|
||||||
|
Markdown,
|
||||||
|
...preservedExtensions,
|
||||||
|
Tag,
|
||||||
|
];
|
||||||
|
}
|
||||||
198
web/src/components/MemoEditor/TiptapEditor/index.tsx
Normal file
198
web/src/components/MemoEditor/TiptapEditor/index.tsx
Normal file
|
|
@ -0,0 +1,198 @@
|
||||||
|
import { Extension } from "@tiptap/core";
|
||||||
|
import { Placeholder } from "@tiptap/extensions";
|
||||||
|
import type { EditorProps as ProseMirrorEditorProps } from "@tiptap/pm/view";
|
||||||
|
import { EditorContent as TiptapEditorContent, useEditor } from "@tiptap/react";
|
||||||
|
import { forwardRef, useEffect, useImperativeHandle, useMemo, useRef } from "react";
|
||||||
|
import { matchPath } from "react-router-dom";
|
||||||
|
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 { buildExtensions } from "./extensions";
|
||||||
|
import { SlashCommand } from "./SlashCommand";
|
||||||
|
import { TagSuggestion } from "./TagSuggestion";
|
||||||
|
|
||||||
|
// 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,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export interface TiptapEditorProps {
|
||||||
|
className?: string;
|
||||||
|
initialContent: string;
|
||||||
|
placeholder: string;
|
||||||
|
isFocusMode?: boolean;
|
||||||
|
onContentChange: (content: string) => void;
|
||||||
|
onPaste: (event: React.ClipboardEvent) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* WYSIWYG memo editor on Tiptap/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 TiptapEditor = forwardRef<EditorController, TiptapEditorProps>(function TiptapEditor(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<string | null>(null);
|
||||||
|
// 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. Same sourcing as the raw editor's TagSuggestions.
|
||||||
|
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<string[]>([]);
|
||||||
|
tagsRef.current = sortedTags;
|
||||||
|
|
||||||
|
// Stable option identities so useEditor's compareOptions stays equal across
|
||||||
|
// renders and Tiptap 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 }),
|
||||||
|
TagSuggestion.configure({ getTags: () => tagsRef.current }),
|
||||||
|
SlashCommand,
|
||||||
|
SaveShortcutPassthrough,
|
||||||
|
],
|
||||||
|
[],
|
||||||
|
);
|
||||||
|
const editorProps = useMemo<ProseMirrorEditorProps>(
|
||||||
|
() => ({
|
||||||
|
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]);
|
||||||
|
|
||||||
|
useImperativeHandle(
|
||||||
|
ref,
|
||||||
|
(): EditorController => ({
|
||||||
|
focus: () => editor?.commands.focus(),
|
||||||
|
hasFocus: () => editor?.isFocused ?? false,
|
||||||
|
// Contract: whitespace-only counts as empty. Tiptap'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(),
|
||||||
|
toggleBold: () => editor?.chain().focus().toggleBold().run(),
|
||||||
|
toggleItalic: () => editor?.chain().focus().toggleItalic().run(),
|
||||||
|
toggleTaskList: () => editor?.chain().focus().toggleTaskList().run(),
|
||||||
|
}),
|
||||||
|
[editor],
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"flex flex-col justify-start items-start relative w-full bg-inherit overflow-y-auto overflow-x-hidden",
|
||||||
|
isFocusMode ? "flex-1" : `h-auto ${EDITOR_HEIGHT.normal}`,
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
onClick={(event) => {
|
||||||
|
// 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");
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<TiptapEditorContent editor={editor} className="w-full" />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
export default TiptapEditor;
|
||||||
70
web/src/components/MemoEditor/TiptapEditor/markdownCodec.ts
Normal file
70
web/src/components/MemoEditor/TiptapEditor/markdownCodec.ts
Normal file
|
|
@ -0,0 +1,70 @@
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
194
web/src/components/MemoEditor/TiptapEditor/suggestionMenu.tsx
Normal file
194
web/src/components/MemoEditor/TiptapEditor/suggestionMenu.tsx
Normal file
|
|
@ -0,0 +1,194 @@
|
||||||
|
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<T> {
|
||||||
|
items: T[];
|
||||||
|
command: (item: T) => void;
|
||||||
|
renderItem: (item: T, isSelected: boolean) => ReactNode;
|
||||||
|
getItemKey: (item: T) => string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Visual parity with the textarea editor's popup (Editor/SuggestionsPopup.tsx).
|
||||||
|
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<T>(
|
||||||
|
{ items, command, renderItem, getItemKey }: SuggestionMenuProps<T>,
|
||||||
|
ref: React.ForwardedRef<SuggestionMenuHandle>,
|
||||||
|
) {
|
||||||
|
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<HTMLDivElement>(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 (
|
||||||
|
<div data-suggestion-menu className={MENU_STYLES.container}>
|
||||||
|
{items.map((item, index) => (
|
||||||
|
<div
|
||||||
|
key={getItemKey(item)}
|
||||||
|
ref={index === selectedIndex ? selectedItemRef : undefined}
|
||||||
|
onMouseDown={(event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
command(item);
|
||||||
|
}}
|
||||||
|
className={cn(MENU_STYLES.item, index === selectedIndex && "bg-accent text-accent-foreground")}
|
||||||
|
>
|
||||||
|
{renderItem(item, index === selectedIndex)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export const SuggestionMenu = forwardRef(SuggestionMenuInner) as <T>(
|
||||||
|
props: SuggestionMenuProps<T> & { ref?: React.ForwardedRef<SuggestionMenuHandle> },
|
||||||
|
) => 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<T>(menu: {
|
||||||
|
renderItem: (item: T, isSelected: boolean) => ReactNode;
|
||||||
|
getItemKey: (item: T) => string;
|
||||||
|
}): SuggestionOptions<T>["render"] {
|
||||||
|
return () => {
|
||||||
|
let renderer: ReactRenderer<SuggestionMenuHandle> | 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<T>) => {
|
||||||
|
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<T>) => ({
|
||||||
|
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<R, P>. We cast via
|
||||||
|
// top-level type imports for readability (runtime shape is correct).
|
||||||
|
type MenuProps = ReturnType<typeof menuProps>;
|
||||||
|
renderer = new ReactRenderer<SuggestionMenuHandle, MenuProps>(
|
||||||
|
SuggestionMenu as unknown as ForwardRefExoticComponent<PropsWithoutRef<MenuProps> & RefAttributes<SuggestionMenuHandle>>,
|
||||||
|
{
|
||||||
|
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,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
import { uniqBy } from "lodash-es";
|
import { uniqBy } from "lodash-es";
|
||||||
import {
|
import {
|
||||||
|
CodeXmlIcon,
|
||||||
FileIcon,
|
FileIcon,
|
||||||
ImageIcon,
|
ImageIcon,
|
||||||
LinkIcon,
|
LinkIcon,
|
||||||
|
|
@ -10,6 +11,7 @@ import {
|
||||||
MicIcon,
|
MicIcon,
|
||||||
MoreHorizontalIcon,
|
MoreHorizontalIcon,
|
||||||
PlusIcon,
|
PlusIcon,
|
||||||
|
TypeIcon,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||||
import { LinkMemoDialog, LocationDialog } from "@/components/MemoMetadata";
|
import { LinkMemoDialog, LocationDialog } from "@/components/MemoMetadata";
|
||||||
|
|
@ -30,6 +32,7 @@ import {
|
||||||
import { useDebouncedEffect } from "@/hooks";
|
import { useDebouncedEffect } from "@/hooks";
|
||||||
import type { MemoRelation } from "@/types/proto/api/v1/memo_service_pb";
|
import type { MemoRelation } from "@/types/proto/api/v1/memo_service_pb";
|
||||||
import { useTranslate } from "@/utils/i18n";
|
import { useTranslate } from "@/utils/i18n";
|
||||||
|
import { setPreferredEditorMode } from "../editorMode";
|
||||||
import { useFileUpload, useLinkMemo, useLocation } from "../hooks";
|
import { useFileUpload, useLinkMemo, useLocation } from "../hooks";
|
||||||
import { useEditorContext } from "../state";
|
import { useEditorContext } from "../state";
|
||||||
import type { InsertMenuProps } from "../types";
|
import type { InsertMenuProps } from "../types";
|
||||||
|
|
@ -132,6 +135,12 @@ const InsertMenu = (props: InsertMenuProps) => {
|
||||||
setMoreSubmenuOpen(false);
|
setMoreSubmenuOpen(false);
|
||||||
}, [onToggleFocusMode]);
|
}, [onToggleFocusMode]);
|
||||||
|
|
||||||
|
const handleToggleEditorMode = useCallback(() => {
|
||||||
|
const next = state.ui.editorMode === "wysiwyg" ? "raw" : "wysiwyg";
|
||||||
|
dispatch(actions.setEditorMode(next));
|
||||||
|
setPreferredEditorMode(next);
|
||||||
|
}, [state.ui.editorMode, actions, dispatch]);
|
||||||
|
|
||||||
const handleMediaUploadClick = useCallback(() => {
|
const handleMediaUploadClick = useCallback(() => {
|
||||||
handleUploadClick("image/*,video/*");
|
handleUploadClick("image/*,video/*");
|
||||||
}, [handleUploadClick]);
|
}, [handleUploadClick]);
|
||||||
|
|
@ -200,6 +209,11 @@ const InsertMenu = (props: InsertMenuProps) => {
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
))}
|
))}
|
||||||
<DropdownMenuSeparator />
|
<DropdownMenuSeparator />
|
||||||
|
{/* Editor display mode: raw Markdown ↔ rich text (WYSIWYG) */}
|
||||||
|
<DropdownMenuItem onClick={handleToggleEditorMode}>
|
||||||
|
{state.ui.editorMode === "wysiwyg" ? <CodeXmlIcon className="w-4 h-4" /> : <TypeIcon className="w-4 h-4" />}
|
||||||
|
{state.ui.editorMode === "wysiwyg" ? t("editor.switch-to-raw") : t("editor.switch-to-wysiwyg")}
|
||||||
|
</DropdownMenuItem>
|
||||||
{/* View submenu with Focus Mode */}
|
{/* View submenu with Focus Mode */}
|
||||||
<DropdownMenuSub open={moreSubmenuOpen} onOpenChange={setMoreSubmenuOpen}>
|
<DropdownMenuSub open={moreSubmenuOpen} onOpenChange={setMoreSubmenuOpen}>
|
||||||
<DropdownMenuSubTrigger onPointerEnter={handleTriggerEnter} onPointerLeave={handleTriggerLeave}>
|
<DropdownMenuSubTrigger onPointerEnter={handleTriggerEnter} onPointerLeave={handleTriggerLeave}>
|
||||||
|
|
|
||||||
|
|
@ -1,13 +1,63 @@
|
||||||
import { forwardRef } from "react";
|
import { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef } from "react";
|
||||||
import Editor, { type EditorRefActions } from "../Editor";
|
import Editor, { type EditorRefActions } from "../Editor";
|
||||||
|
import { createTextareaController } from "../Editor/controllerAdapter";
|
||||||
import { useBlobUrls, useDragAndDrop } from "../hooks";
|
import { useBlobUrls, useDragAndDrop } from "../hooks";
|
||||||
import { useEditorContext } from "../state";
|
import { useEditorContext } from "../state";
|
||||||
|
import TiptapEditor from "../TiptapEditor";
|
||||||
import type { EditorContentProps } from "../types";
|
import type { EditorContentProps } from "../types";
|
||||||
import type { LocalFile } from "../types/attachment";
|
import type { LocalFile } from "../types/attachment";
|
||||||
|
import type { EditorController } from "../types/editorController";
|
||||||
|
|
||||||
export const EditorContent = forwardRef<EditorRefActions, EditorContentProps>(({ placeholder }, ref) => {
|
/**
|
||||||
|
* 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.
|
||||||
|
*/
|
||||||
|
export const EditorContent = forwardRef<EditorController, EditorContentProps>(({ placeholder }, ref) => {
|
||||||
const { state, actions, dispatch } = useEditorContext();
|
const { state, actions, dispatch } = useEditorContext();
|
||||||
const { createBlobUrl } = useBlobUrls();
|
const { createBlobUrl } = useBlobUrls();
|
||||||
|
const mode = state.ui.editorMode;
|
||||||
|
|
||||||
|
const textareaActionsRef = useRef<EditorRefActions>(null);
|
||||||
|
const tiptapControllerRef = useRef<EditorController>(null);
|
||||||
|
const textareaController = useMemo(() => createTextareaController(() => textareaActionsRef.current), []);
|
||||||
|
|
||||||
|
const modeRef = useRef(mode);
|
||||||
|
modeRef.current = mode;
|
||||||
|
const getActive = useCallback(
|
||||||
|
(): EditorController | null => (modeRef.current === "wysiwyg" ? tiptapControllerRef.current : textareaController),
|
||||||
|
[textareaController],
|
||||||
|
);
|
||||||
|
|
||||||
|
// 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(),
|
||||||
|
toggleBold: () => getActive()?.toggleBold(),
|
||||||
|
toggleItalic: () => getActive()?.toggleItalic(),
|
||||||
|
toggleTaskList: () => getActive()?.toggleTaskList(),
|
||||||
|
}),
|
||||||
|
[getActive],
|
||||||
|
);
|
||||||
|
|
||||||
const { dragHandlers } = useDragAndDrop((files: FileList) => {
|
const { dragHandlers } = useDragAndDrop((files: FileList) => {
|
||||||
const localFiles: LocalFile[] = Array.from(files).map((file) => ({
|
const localFiles: LocalFile[] = Array.from(files).map((file) => ({
|
||||||
|
|
@ -58,18 +108,33 @@ export const EditorContent = forwardRef<EditorRefActions, EditorContentProps>(({
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="w-full flex flex-col flex-1" {...dragHandlers}>
|
<div className="w-full flex flex-col flex-1" {...dragHandlers}>
|
||||||
<Editor
|
{mode === "wysiwyg" ? (
|
||||||
ref={ref}
|
// No composition wiring: ProseMirror handles IME natively, and
|
||||||
className="memo-editor-content"
|
// state.ui.isComposing is only read by the raw editor below — feeding
|
||||||
initialContent={state.content}
|
// it from here could only strand the flag across a mode switch.
|
||||||
placeholder={placeholder || ""}
|
<TiptapEditor
|
||||||
isFocusMode={state.ui.isFocusMode}
|
ref={tiptapControllerRef}
|
||||||
isInIME={state.ui.isComposing}
|
className="memo-editor-content"
|
||||||
onContentChange={handleContentChange}
|
initialContent={state.content}
|
||||||
onPaste={handlePaste}
|
placeholder={placeholder || ""}
|
||||||
onCompositionStart={handleCompositionStart}
|
isFocusMode={state.ui.isFocusMode}
|
||||||
onCompositionEnd={handleCompositionEnd}
|
onContentChange={handleContentChange}
|
||||||
/>
|
onPaste={handlePaste}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<Editor
|
||||||
|
ref={textareaActionsRef}
|
||||||
|
className="memo-editor-content"
|
||||||
|
initialContent={state.content}
|
||||||
|
placeholder={placeholder || ""}
|
||||||
|
isFocusMode={state.ui.isFocusMode}
|
||||||
|
isInIME={state.ui.isComposing}
|
||||||
|
onContentChange={handleContentChange}
|
||||||
|
onPaste={handlePaste}
|
||||||
|
onCompositionStart={handleCompositionStart}
|
||||||
|
onCompositionEnd={handleCompositionEnd}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
|
||||||
20
web/src/components/MemoEditor/editorMode.ts
Normal file
20
web/src/components/MemoEditor/editorMode.ts
Normal file
|
|
@ -0,0 +1,20 @@
|
||||||
|
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.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
import { useEffect, useRef } from "react";
|
import { useEffect, useRef } from "react";
|
||||||
import type { EditorRefActions } from "../Editor";
|
import type { EditorController } from "../types/editorController";
|
||||||
|
|
||||||
export const useKeyboard = (editorRef: React.RefObject<EditorRefActions | null>, onSave: () => void) => {
|
export const useKeyboard = (editorRef: React.RefObject<EditorController | null>, onSave: () => void) => {
|
||||||
const onSaveRef = useRef(onSave);
|
const onSaveRef = useRef(onSave);
|
||||||
onSaveRef.current = onSave;
|
onSaveRef.current = onSave;
|
||||||
|
|
||||||
|
|
@ -11,14 +11,7 @@ export const useKeyboard = (editorRef: React.RefObject<EditorRefActions | null>,
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const editor = editorRef.current?.getEditor();
|
if (!editorRef.current?.hasFocus()) {
|
||||||
if (!editor) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const activeElement = document.activeElement;
|
|
||||||
const target = event.target;
|
|
||||||
if (activeElement !== editor && target !== editor) {
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,11 +1,15 @@
|
||||||
import { useEffect, useRef, useState } from "react";
|
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 type { Memo, Visibility } from "@/types/proto/api/v1/memo_service_pb";
|
||||||
import type { EditorRefActions } from "../Editor";
|
import { useTranslate } from "@/utils/i18n";
|
||||||
|
import { getPreferredEditorMode } from "../editorMode";
|
||||||
import { cacheService, memoService } from "../services";
|
import { cacheService, memoService } from "../services";
|
||||||
import { useEditorContext } from "../state";
|
import { useEditorContext } from "../state";
|
||||||
|
import { isLosslessRoundTrip } from "../TiptapEditor/markdownCodec";
|
||||||
|
import type { EditorController } from "../types/editorController";
|
||||||
|
|
||||||
interface UseMemoInitOptions {
|
interface UseMemoInitOptions {
|
||||||
editorRef: React.RefObject<EditorRefActions | null>;
|
editorRef: React.RefObject<EditorController | null>;
|
||||||
memo?: Memo;
|
memo?: Memo;
|
||||||
cacheKey?: string;
|
cacheKey?: string;
|
||||||
username: string;
|
username: string;
|
||||||
|
|
@ -23,6 +27,7 @@ export const useMemoInit = ({
|
||||||
defaultVisibility,
|
defaultVisibility,
|
||||||
defaultCreateTime,
|
defaultCreateTime,
|
||||||
}: UseMemoInitOptions) => {
|
}: UseMemoInitOptions) => {
|
||||||
|
const t = useTranslate();
|
||||||
const { actions, dispatch } = useEditorContext();
|
const { actions, dispatch } = useEditorContext();
|
||||||
const initializedRef = useRef(false);
|
const initializedRef = useRef(false);
|
||||||
const [isInitialized, setIsInitialized] = useState(false);
|
const [isInitialized, setIsInitialized] = useState(false);
|
||||||
|
|
@ -36,6 +41,16 @@ export const useMemoInit = ({
|
||||||
const initialState = memoService.fromMemo(memo);
|
const initialState = memoService.fromMemo(memo);
|
||||||
cacheService.clear(key);
|
cacheService.clear(key);
|
||||||
dispatch(actions.initMemo(initialState));
|
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 {
|
} else {
|
||||||
const cachedContent = cacheService.load(key);
|
const cachedContent = cacheService.load(key);
|
||||||
if (cachedContent) {
|
if (cachedContent) {
|
||||||
|
|
@ -54,7 +69,7 @@ export const useMemoInit = ({
|
||||||
}
|
}
|
||||||
|
|
||||||
setIsInitialized(true);
|
setIsInitialized(true);
|
||||||
}, [memo, cacheKey, username, autoFocus, defaultVisibility, defaultCreateTime, actions, dispatch, editorRef]);
|
}, [memo, cacheKey, username, autoFocus, defaultVisibility, defaultCreateTime, actions, dispatch, editorRef, t]);
|
||||||
|
|
||||||
return { isInitialized };
|
return { isInitialized };
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -21,12 +21,12 @@ import {
|
||||||
TimestampPopover,
|
TimestampPopover,
|
||||||
} from "./components";
|
} from "./components";
|
||||||
import { FOCUS_MODE_STYLES } from "./constants";
|
import { FOCUS_MODE_STYLES } from "./constants";
|
||||||
import type { EditorRefActions } from "./Editor";
|
|
||||||
import { useAudioRecorder, useAutoSave, useFocusMode, useKeyboard, useMemoInit } from "./hooks";
|
import { useAudioRecorder, useAutoSave, useFocusMode, useKeyboard, useMemoInit } from "./hooks";
|
||||||
import { errorService, memoService, transcriptionService, validationService } from "./services";
|
import { errorService, memoService, transcriptionService, validationService } from "./services";
|
||||||
import { EditorProvider, useEditorContext } from "./state";
|
import { EditorProvider, useEditorContext } from "./state";
|
||||||
import type { MemoEditorProps } from "./types";
|
import type { MemoEditorProps } from "./types";
|
||||||
import type { LocalFile } from "./types/attachment";
|
import type { LocalFile } from "./types/attachment";
|
||||||
|
import type { EditorController } from "./types/editorController";
|
||||||
|
|
||||||
const MemoEditor = (props: MemoEditorProps) => (
|
const MemoEditor = (props: MemoEditorProps) => (
|
||||||
<EditorProvider>
|
<EditorProvider>
|
||||||
|
|
@ -48,7 +48,7 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({
|
||||||
const t = useTranslate();
|
const t = useTranslate();
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
const currentUser = useCurrentUser();
|
const currentUser = useCurrentUser();
|
||||||
const editorRef = useRef<EditorRefActions>(null);
|
const editorRef = useRef<EditorController>(null);
|
||||||
const { state, actions, dispatch } = useEditorContext();
|
const { state, actions, dispatch } = useEditorContext();
|
||||||
const { userGeneralSetting } = useAuth();
|
const { userGeneralSetting } = useAuth();
|
||||||
const { aiSetting, fetchSetting } = useInstance();
|
const { aiSetting, fetchSetting } = useInstance();
|
||||||
|
|
@ -112,15 +112,7 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({
|
||||||
if (!editor) {
|
if (!editor) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
editor.insertMarkdown(text);
|
||||||
const content = editor.getContent();
|
|
||||||
const cursor = editor.getCursorPosition();
|
|
||||||
const beforeCursor = content.slice(0, cursor);
|
|
||||||
const afterCursor = content.slice(cursor);
|
|
||||||
const prefix = beforeCursor.length === 0 || beforeCursor.endsWith("\n\n") ? "" : beforeCursor.endsWith("\n") ? "\n" : "\n\n";
|
|
||||||
const suffix = afterCursor.length === 0 || afterCursor.startsWith("\n\n") ? "" : afterCursor.startsWith("\n") ? "\n" : "\n\n";
|
|
||||||
|
|
||||||
editor.insertText(text, prefix, suffix);
|
|
||||||
editor.scrollToCursor();
|
editor.scrollToCursor();
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -122,8 +122,12 @@ export const memoService = {
|
||||||
return { memoName: memo.name, hasChanges: true };
|
return { memoName: memo.name, hasChanges: true };
|
||||||
},
|
},
|
||||||
|
|
||||||
/** Build editor state from an already-loaded Memo entity (no network request). */
|
/**
|
||||||
fromMemo(memo: Memo): EditorState {
|
* Build the INIT_MEMO payload from an already-loaded Memo entity (no network
|
||||||
|
* request). Returns only the fields the reducer's INIT_MEMO case consumes —
|
||||||
|
* UI state (mode, loading flags, …) is owned by the reducer, not by memos.
|
||||||
|
*/
|
||||||
|
fromMemo(memo: Memo): Pick<EditorState, "content" | "metadata" | "timestamps"> {
|
||||||
return {
|
return {
|
||||||
content: memo.content,
|
content: memo.content,
|
||||||
metadata: {
|
metadata: {
|
||||||
|
|
@ -132,23 +136,10 @@ export const memoService = {
|
||||||
relations: memo.relations,
|
relations: memo.relations,
|
||||||
location: memo.location,
|
location: memo.location,
|
||||||
},
|
},
|
||||||
ui: {
|
|
||||||
isFocusMode: false,
|
|
||||||
isLoading: { saving: false, uploading: false, loading: false },
|
|
||||||
isComposing: false,
|
|
||||||
},
|
|
||||||
timestamps: {
|
timestamps: {
|
||||||
createTime: memo.createTime ? timestampDate(memo.createTime) : undefined,
|
createTime: memo.createTime ? timestampDate(memo.createTime) : undefined,
|
||||||
updateTime: memo.updateTime ? timestampDate(memo.updateTime) : undefined,
|
updateTime: memo.updateTime ? timestampDate(memo.updateTime) : undefined,
|
||||||
},
|
},
|
||||||
localFiles: [],
|
|
||||||
audioRecorder: {
|
|
||||||
isSupported: true,
|
|
||||||
permission: "unknown",
|
|
||||||
status: "idle",
|
|
||||||
elapsedSeconds: 0,
|
|
||||||
error: undefined,
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
import type { Attachment } from "@/types/proto/api/v1/attachment_service_pb";
|
import type { Attachment } from "@/types/proto/api/v1/attachment_service_pb";
|
||||||
import type { MemoRelation } from "@/types/proto/api/v1/memo_service_pb";
|
import type { MemoRelation } from "@/types/proto/api/v1/memo_service_pb";
|
||||||
|
import type { EditorMode } from "../editorMode";
|
||||||
import type { LocalFile } from "../types/attachment";
|
import type { LocalFile } from "../types/attachment";
|
||||||
import type { AudioRecorderPermission, AudioRecorderStatus, EditorAction, EditorState, LoadingKey } from "./types";
|
import type { AudioRecorderPermission, AudioRecorderStatus, EditorAction, EditorState, LoadingKey } from "./types";
|
||||||
|
|
||||||
|
|
@ -102,6 +103,11 @@ export const editorActions = {
|
||||||
payload: value,
|
payload: value,
|
||||||
}),
|
}),
|
||||||
|
|
||||||
|
setEditorMode: (mode: EditorMode): EditorAction => ({
|
||||||
|
type: "SET_EDITOR_MODE",
|
||||||
|
payload: mode,
|
||||||
|
}),
|
||||||
|
|
||||||
reset: (): EditorAction => ({
|
reset: (): EditorAction => ({
|
||||||
type: "RESET",
|
type: "RESET",
|
||||||
}),
|
}),
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@ import { createContext, type Dispatch, type FC, type PropsWithChildren, useConte
|
||||||
import { editorActions } from "./actions";
|
import { editorActions } from "./actions";
|
||||||
import { editorReducer } from "./reducer";
|
import { editorReducer } from "./reducer";
|
||||||
import type { EditorAction, EditorState } from "./types";
|
import type { EditorAction, EditorState } from "./types";
|
||||||
import { initialState } from "./types";
|
import { createInitialState } from "./types";
|
||||||
|
|
||||||
interface EditorContextValue {
|
interface EditorContextValue {
|
||||||
state: EditorState;
|
state: EditorState;
|
||||||
|
|
@ -25,7 +25,7 @@ interface EditorProviderProps extends PropsWithChildren {
|
||||||
}
|
}
|
||||||
|
|
||||||
export const EditorProvider: FC<EditorProviderProps> = ({ children, initialEditorState }) => {
|
export const EditorProvider: FC<EditorProviderProps> = ({ children, initialEditorState }) => {
|
||||||
const [state, dispatch] = useReducer(editorReducer, initialEditorState || initialState);
|
const [state, dispatch] = useReducer(editorReducer, initialEditorState, (provided) => provided ?? createInitialState());
|
||||||
|
|
||||||
const value = useMemo<EditorContextValue>(
|
const value = useMemo<EditorContextValue>(
|
||||||
() => ({
|
() => ({
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
import type { EditorAction, EditorState } from "./types";
|
import type { EditorAction, EditorState } from "./types";
|
||||||
import { initialState } from "./types";
|
import { createInitialState } from "./types";
|
||||||
|
|
||||||
export function editorReducer(state: EditorState, action: EditorAction): EditorState {
|
export function editorReducer(state: EditorState, action: EditorAction): EditorState {
|
||||||
switch (action.type) {
|
switch (action.type) {
|
||||||
|
|
@ -171,11 +171,21 @@ export function editorReducer(state: EditorState, action: EditorAction): EditorS
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
case "RESET":
|
case "SET_EDITOR_MODE":
|
||||||
return {
|
return {
|
||||||
...initialState,
|
...state,
|
||||||
|
ui: {
|
||||||
|
...state.ui,
|
||||||
|
editorMode: action.payload,
|
||||||
|
// A composition can't survive an editor swap; a stuck flag would
|
||||||
|
// disable the textarea's IME-guarded features until the next IME cycle.
|
||||||
|
isComposing: false,
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
case "RESET":
|
||||||
|
return createInitialState();
|
||||||
|
|
||||||
default:
|
default:
|
||||||
return state;
|
return state;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
import type { Attachment } from "@/types/proto/api/v1/attachment_service_pb";
|
import type { Attachment } from "@/types/proto/api/v1/attachment_service_pb";
|
||||||
import type { Location, MemoRelation } from "@/types/proto/api/v1/memo_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 { Visibility } from "@/types/proto/api/v1/memo_service_pb";
|
||||||
|
import { type EditorMode, getPreferredEditorMode } from "../editorMode";
|
||||||
import type { LocalFile } from "../types/attachment";
|
import type { LocalFile } from "../types/attachment";
|
||||||
|
|
||||||
export type LoadingKey = "saving" | "uploading" | "loading";
|
export type LoadingKey = "saving" | "uploading" | "loading";
|
||||||
|
|
@ -23,6 +24,7 @@ export interface EditorState {
|
||||||
loading: boolean;
|
loading: boolean;
|
||||||
};
|
};
|
||||||
isComposing: boolean;
|
isComposing: boolean;
|
||||||
|
editorMode: EditorMode;
|
||||||
};
|
};
|
||||||
timestamps: {
|
timestamps: {
|
||||||
createTime?: Date;
|
createTime?: Date;
|
||||||
|
|
@ -59,9 +61,13 @@ export type EditorAction =
|
||||||
| { type: "SET_AUDIO_RECORDER_STATUS"; payload: AudioRecorderStatus }
|
| { type: "SET_AUDIO_RECORDER_STATUS"; payload: AudioRecorderStatus }
|
||||||
| { type: "SET_AUDIO_RECORDER_ELAPSED"; payload: number }
|
| { type: "SET_AUDIO_RECORDER_ELAPSED"; payload: number }
|
||||||
| { type: "SET_AUDIO_RECORDER_ERROR"; payload?: string }
|
| { type: "SET_AUDIO_RECORDER_ERROR"; payload?: string }
|
||||||
|
| { type: "SET_EDITOR_MODE"; payload: EditorMode }
|
||||||
| { type: "RESET" };
|
| { type: "RESET" };
|
||||||
|
|
||||||
export const initialState: EditorState = {
|
// Module-private template for createInitialState — not exported because its
|
||||||
|
// hardcoded editorMode ignores the persisted preference; always go through
|
||||||
|
// createInitialState() for a real initial state.
|
||||||
|
const defaultState: EditorState = {
|
||||||
content: "",
|
content: "",
|
||||||
metadata: {
|
metadata: {
|
||||||
visibility: Visibility.PRIVATE,
|
visibility: Visibility.PRIVATE,
|
||||||
|
|
@ -77,6 +83,7 @@ export const initialState: EditorState = {
|
||||||
loading: false,
|
loading: false,
|
||||||
},
|
},
|
||||||
isComposing: false,
|
isComposing: false,
|
||||||
|
editorMode: "wysiwyg",
|
||||||
},
|
},
|
||||||
timestamps: {
|
timestamps: {
|
||||||
createTime: undefined,
|
createTime: undefined,
|
||||||
|
|
@ -91,3 +98,15 @@ export const initialState: EditorState = {
|
||||||
error: undefined,
|
error: undefined,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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.
|
||||||
|
*/
|
||||||
|
export function createInitialState(): EditorState {
|
||||||
|
return {
|
||||||
|
...defaultState,
|
||||||
|
ui: { ...defaultState.ui, editorMode: getPreferredEditorMode() },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
|
||||||
24
web/src/components/MemoEditor/types/editorController.ts
Normal file
24
web/src/components/MemoEditor/types/editorController.ts
Normal file
|
|
@ -0,0 +1,24 @@
|
||||||
|
/**
|
||||||
|
* The contract both memo editors (raw textarea and Tiptap WYSIWYG) implement.
|
||||||
|
* Everything outside an editor implementation must talk markdown through this
|
||||||
|
* interface and never reach for editor-specific APIs like EditorRefActions.
|
||||||
|
*/
|
||||||
|
export interface EditorController {
|
||||||
|
focus(): void;
|
||||||
|
hasFocus(): boolean;
|
||||||
|
/** Whitespace-only content counts as empty. */
|
||||||
|
isEmpty(): boolean;
|
||||||
|
/** Current document as a markdown string (the only storage format). */
|
||||||
|
getMarkdown(): string;
|
||||||
|
/** Replace the whole document from a markdown string. */
|
||||||
|
setMarkdown(markdown: string): void;
|
||||||
|
/** Insert markdown at the cursor as its own block. */
|
||||||
|
insertMarkdown(markdown: string): void;
|
||||||
|
scrollToCursor(): void;
|
||||||
|
/** Select the entire document (used by tests and select-all flows). */
|
||||||
|
selectAll(): void;
|
||||||
|
// Formatting intents — each editor realizes them natively.
|
||||||
|
toggleBold(): void;
|
||||||
|
toggleItalic(): void;
|
||||||
|
toggleTaskList(): void;
|
||||||
|
}
|
||||||
|
|
@ -13,4 +13,5 @@ export type {
|
||||||
TagSuggestionsProps,
|
TagSuggestionsProps,
|
||||||
VisibilitySelectorProps,
|
VisibilitySelectorProps,
|
||||||
} from "./components";
|
} from "./components";
|
||||||
|
export type { EditorController } from "./editorController";
|
||||||
export type { LocationState } from "./insert-menu";
|
export type { LocationState } from "./insert-menu";
|
||||||
|
|
|
||||||
|
|
@ -31,3 +31,126 @@
|
||||||
@apply bg-background text-foreground;
|
@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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Tailwind's preflight resets h1–h6 to inherit; restore the same heading
|
||||||
|
scale the memo view uses (MemoContent/markdown/Heading.tsx) so live
|
||||||
|
conversion is visible while editing. */
|
||||||
|
.memo-wysiwyg h1,
|
||||||
|
.memo-wysiwyg h2,
|
||||||
|
.memo-wysiwyg h3,
|
||||||
|
.memo-wysiwyg h4,
|
||||||
|
.memo-wysiwyg h5,
|
||||||
|
.memo-wysiwyg h6 {
|
||||||
|
margin: 0.75rem 0 0.5rem;
|
||||||
|
line-height: 1.25;
|
||||||
|
}
|
||||||
|
|
||||||
|
.memo-wysiwyg h1:first-child,
|
||||||
|
.memo-wysiwyg h2:first-child,
|
||||||
|
.memo-wysiwyg h3:first-child {
|
||||||
|
margin-top: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.memo-wysiwyg h1 {
|
||||||
|
font-size: 1.875rem;
|
||||||
|
font-weight: 700;
|
||||||
|
border-bottom: 1px solid var(--border);
|
||||||
|
padding-bottom: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.memo-wysiwyg h2 {
|
||||||
|
font-size: 1.5rem;
|
||||||
|
font-weight: 600;
|
||||||
|
border-bottom: 1px solid var(--border);
|
||||||
|
padding-bottom: 0.375rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.memo-wysiwyg h3 {
|
||||||
|
font-size: 1.25rem;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.memo-wysiwyg h4 {
|
||||||
|
font-size: 1.125rem;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.memo-wysiwyg h5 {
|
||||||
|
font-size: 1rem;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.memo-wysiwyg h6 {
|
||||||
|
font-size: 1rem;
|
||||||
|
font-weight: 500;
|
||||||
|
color: var(--muted-foreground);
|
||||||
|
}
|
||||||
|
|
||||||
|
.memo-wysiwyg ul,
|
||||||
|
.memo-wysiwyg ol {
|
||||||
|
padding-left: 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.memo-wysiwyg ul {
|
||||||
|
list-style: disc;
|
||||||
|
}
|
||||||
|
|
||||||
|
.memo-wysiwyg ol {
|
||||||
|
list-style: decimal;
|
||||||
|
}
|
||||||
|
|
||||||
|
.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 blockquote {
|
||||||
|
border-left: 2px solid var(--border);
|
||||||
|
padding-left: 0.75rem;
|
||||||
|
opacity: 0.9;
|
||||||
|
}
|
||||||
|
|
||||||
|
.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 code {
|
||||||
|
background: var(--muted);
|
||||||
|
border-radius: 0.25rem;
|
||||||
|
padding: 0 0.25rem;
|
||||||
|
font-family: var(--font-mono, monospace);
|
||||||
|
font-size: 0.875em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.memo-wysiwyg pre code {
|
||||||
|
background: transparent;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -173,6 +173,9 @@
|
||||||
"save": "Save",
|
"save": "Save",
|
||||||
"saving": "Saving...",
|
"saving": "Saving...",
|
||||||
"slash-commands": "Type `/` for commands",
|
"slash-commands": "Type `/` for commands",
|
||||||
|
"switch-to-raw": "Edit raw Markdown",
|
||||||
|
"switch-to-wysiwyg": "Edit rich text",
|
||||||
|
"unsupported-syntax-raw-mode": "This memo contains syntax the rich-text editor can't safely edit, so it opened in raw Markdown mode.",
|
||||||
"audio-recorder": {
|
"audio-recorder": {
|
||||||
"attachment-label": "Audio recording",
|
"attachment-label": "Audio recording",
|
||||||
"attachment-label-with-time": "Audio recording {{time}}",
|
"attachment-label-with-time": "Audio recording {{time}}",
|
||||||
|
|
|
||||||
92
web/tests/editor-controller-adapter.test.tsx
Normal file
92
web/tests/editor-controller-adapter.test.tsx
Normal file
|
|
@ -0,0 +1,92 @@
|
||||||
|
import { render, screen } from "@testing-library/react";
|
||||||
|
import { createRef } from "react";
|
||||||
|
import { describe, expect, it, vi } from "vitest";
|
||||||
|
import Editor, { type EditorRefActions } from "@/components/MemoEditor/Editor";
|
||||||
|
import { createTextareaController } from "@/components/MemoEditor/Editor/controllerAdapter";
|
||||||
|
|
||||||
|
vi.mock("@/components/MemoEditor/Editor/TagSuggestions", () => ({ default: () => null }));
|
||||||
|
vi.mock("@/components/MemoEditor/Editor/SlashCommands", () => ({ default: () => null }));
|
||||||
|
|
||||||
|
function setup(initialContent = "") {
|
||||||
|
const ref = createRef<EditorRefActions>();
|
||||||
|
render(
|
||||||
|
<Editor
|
||||||
|
ref={ref}
|
||||||
|
className=""
|
||||||
|
initialContent={initialContent}
|
||||||
|
placeholder="memo"
|
||||||
|
onContentChange={vi.fn()}
|
||||||
|
onPaste={vi.fn()}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
const controller = createTextareaController(() => ref.current);
|
||||||
|
const textarea = screen.getByPlaceholderText("memo") as HTMLTextAreaElement;
|
||||||
|
return { controller, textarea };
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("textarea EditorController adapter", () => {
|
||||||
|
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");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("toggleBold wraps the selection in **", () => {
|
||||||
|
const { controller, textarea } = setup("read the docs");
|
||||||
|
textarea.setSelectionRange(9, 13);
|
||||||
|
controller.toggleBold();
|
||||||
|
expect(textarea.value).toBe("read the **docs**");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("toggleTaskList prefixes and unprefixes the current line", () => {
|
||||||
|
const { controller, textarea } = setup("buy milk");
|
||||||
|
textarea.setSelectionRange(4, 4);
|
||||||
|
controller.toggleTaskList();
|
||||||
|
expect(textarea.value).toBe("- [ ] buy milk");
|
||||||
|
controller.toggleTaskList();
|
||||||
|
expect(textarea.value).toBe("buy milk");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("toggleTaskList unprefixes a checked task line", () => {
|
||||||
|
const { controller, textarea } = setup("- [x] done thing");
|
||||||
|
textarea.setSelectionRange(8, 8);
|
||||||
|
controller.toggleTaskList();
|
||||||
|
expect(textarea.value).toBe("done thing");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("toggleTaskList preserves indentation", () => {
|
||||||
|
const { controller, textarea } = setup(" nested item");
|
||||||
|
textarea.setSelectionRange(4, 4);
|
||||||
|
controller.toggleTaskList();
|
||||||
|
expect(textarea.value).toBe(" - [ ] nested item");
|
||||||
|
controller.toggleTaskList();
|
||||||
|
expect(textarea.value).toBe(" nested item");
|
||||||
|
});
|
||||||
|
|
||||||
|
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);
|
||||||
|
});
|
||||||
|
});
|
||||||
63
web/tests/editor-load-guard.test.tsx
Normal file
63
web/tests/editor-load-guard.test.tsx
Normal file
|
|
@ -0,0 +1,63 @@
|
||||||
|
import { render, screen } from "@testing-library/react";
|
||||||
|
import { describe, expect, it, vi } from "vitest";
|
||||||
|
import { create } from "@bufbuild/protobuf";
|
||||||
|
import { useMemoInit } from "@/components/MemoEditor/hooks";
|
||||||
|
import { EditorProvider, useEditorContext } from "@/components/MemoEditor/state";
|
||||||
|
import { MemoSchema } from "@/types/proto/api/v1/memo_service_pb";
|
||||||
|
|
||||||
|
const toastMock = vi.hoisted(() => 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/TiptapEditor/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 { state } = useEditorContext();
|
||||||
|
return <span data-testid="mode">{state.ui.editorMode}</span>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderGuard(content: string) {
|
||||||
|
render(
|
||||||
|
<EditorProvider>
|
||||||
|
<Harness content={content} />
|
||||||
|
</EditorProvider>,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
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();
|
||||||
|
});
|
||||||
|
});
|
||||||
131
web/tests/editor-mode-toggle.test.tsx
Normal file
131
web/tests/editor-mode-toggle.test.tsx
Normal file
|
|
@ -0,0 +1,131 @@
|
||||||
|
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 } from "@/components/MemoEditor/state";
|
||||||
|
|
||||||
|
vi.mock("@/hooks/useUserQueries", () => ({
|
||||||
|
useTagCounts: () => ({ data: {} }),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("@/components/MemoEditor/Editor/TagSuggestions", () => ({ default: () => null }));
|
||||||
|
vi.mock("@/components/MemoEditor/Editor/SlashCommands", () => ({ default: () => null }));
|
||||||
|
// useTranslate returns the key string in tests (no i18next backend initialised).
|
||||||
|
vi.mock("@/utils/i18n", () => ({ useTranslate: () => (key: string) => key }));
|
||||||
|
|
||||||
|
function ModeProbe() {
|
||||||
|
const { state, actions, dispatch } = useEditorContext();
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
data-testid="probe-toggle"
|
||||||
|
onClick={() => dispatch(actions.setEditorMode(state.ui.editorMode === "wysiwyg" ? "raw" : "wysiwyg"))}
|
||||||
|
>
|
||||||
|
{state.ui.editorMode}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
data-testid="probe-set-content"
|
||||||
|
onClick={() => dispatch(actions.updateContent("from **wysiwyg**"))}
|
||||||
|
>
|
||||||
|
set content
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderDualEditor() {
|
||||||
|
render(
|
||||||
|
<EditorProvider>
|
||||||
|
<EditorContent placeholder="memo" />
|
||||||
|
<ModeProbe />
|
||||||
|
</EditorProvider>,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
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");
|
||||||
|
// Tiptap'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 Tiptap's deferred view.focus()).
|
||||||
|
act(() => {
|
||||||
|
pendingRafs.splice(0).forEach((cb) => cb(0));
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(focusSpy).toHaveBeenCalled();
|
||||||
|
focusSpy.mockRestore();
|
||||||
|
rafSpy.mockRestore();
|
||||||
|
});
|
||||||
|
});
|
||||||
41
web/tests/editor-mode.test.ts
Normal file
41
web/tests/editor-mode.test.ts
Normal file
|
|
@ -0,0 +1,41 @@
|
||||||
|
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");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("SET_EDITOR_MODE clears isComposing", () => {
|
||||||
|
const state = { ...createInitialState() };
|
||||||
|
state.ui = { ...state.ui, isComposing: true };
|
||||||
|
const next = editorReducer(state, { type: "SET_EDITOR_MODE", payload: "raw" });
|
||||||
|
expect(next.ui.isComposing).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
7
web/tests/fixtures/markdown-corpus/preserved/block-html.md
vendored
Normal file
7
web/tests/fixtures/markdown-corpus/preserved/block-html.md
vendored
Normal file
|
|
@ -0,0 +1,7 @@
|
||||||
|
Paragraph before.
|
||||||
|
|
||||||
|
<div class="custom">
|
||||||
|
<p>Raw HTML block content</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
Paragraph after.
|
||||||
1
web/tests/fixtures/markdown-corpus/preserved/inline-html.md
vendored
Normal file
1
web/tests/fixtures/markdown-corpus/preserved/inline-html.md
vendored
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
Use <em>emphasis</em> and a line<br>break and <span class="x">spans</span> here.
|
||||||
7
web/tests/fixtures/markdown-corpus/preserved/math-block.md
vendored
Normal file
7
web/tests/fixtures/markdown-corpus/preserved/math-block.md
vendored
Normal file
|
|
@ -0,0 +1,7 @@
|
||||||
|
Before the math.
|
||||||
|
|
||||||
|
$$
|
||||||
|
E = mc^2 \cdot \frac{1}{\sqrt{1 - v^2/c^2}}
|
||||||
|
$$
|
||||||
|
|
||||||
|
After the math.
|
||||||
1
web/tests/fixtures/markdown-corpus/preserved/math-inline.md
vendored
Normal file
1
web/tests/fixtures/markdown-corpus/preserved/math-inline.md
vendored
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
Energy is $E=mc^2$ and the index is $x_1$ in this sentence.
|
||||||
4
web/tests/fixtures/markdown-corpus/preserved/table.md
vendored
Normal file
4
web/tests/fixtures/markdown-corpus/preserved/table.md
vendored
Normal file
|
|
@ -0,0 +1,4 @@
|
||||||
|
| Name | Role |
|
||||||
|
| --- | --- |
|
||||||
|
| Ada | Engineer |
|
||||||
|
| Grace | Admiral |
|
||||||
7
web/tests/fixtures/markdown-corpus/supported/basic.md
vendored
Normal file
7
web/tests/fixtures/markdown-corpus/supported/basic.md
vendored
Normal file
|
|
@ -0,0 +1,7 @@
|
||||||
|
# Hello memos
|
||||||
|
|
||||||
|
Some **bold**, *italic*, ~~struck~~, and `inline code` text.
|
||||||
|
|
||||||
|
> A blockquote with **bold** inside.
|
||||||
|
|
||||||
|
A [link](https://example.com/docs) in a sentence.
|
||||||
7
web/tests/fixtures/markdown-corpus/supported/blockquote-mixed.md
vendored
Normal file
7
web/tests/fixtures/markdown-corpus/supported/blockquote-mixed.md
vendored
Normal file
|
|
@ -0,0 +1,7 @@
|
||||||
|
> Outer quote line one.
|
||||||
|
> Still the same quote.
|
||||||
|
|
||||||
|
Paragraph after.
|
||||||
|
|
||||||
|
> - a list in a quote
|
||||||
|
> - second item
|
||||||
9
web/tests/fixtures/markdown-corpus/supported/cjk-emoji.md
vendored
Normal file
9
web/tests/fixtures/markdown-corpus/supported/cjk-emoji.md
vendored
Normal file
|
|
@ -0,0 +1,9 @@
|
||||||
|
# 日本語の見出し
|
||||||
|
|
||||||
|
これは**太字**と*斜体*のテストです。改行も確認します。
|
||||||
|
|
||||||
|
- 中文列表项
|
||||||
|
- 한국어 항목
|
||||||
|
- emoji 🎉 in a list 🚀
|
||||||
|
|
||||||
|
> 引用文です 😀
|
||||||
16
web/tests/fixtures/markdown-corpus/supported/code-blocks.md
vendored
Normal file
16
web/tests/fixtures/markdown-corpus/supported/code-blocks.md
vendored
Normal file
|
|
@ -0,0 +1,16 @@
|
||||||
|
Some text first.
|
||||||
|
|
||||||
|
```go
|
||||||
|
func main() {
|
||||||
|
fmt.Println("hello *not italic* #not-a-tag")
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
graph TD;
|
||||||
|
A-->B;
|
||||||
|
```
|
||||||
|
|
||||||
|
```
|
||||||
|
no language fence
|
||||||
|
```
|
||||||
13
web/tests/fixtures/markdown-corpus/supported/headings.md
vendored
Normal file
13
web/tests/fixtures/markdown-corpus/supported/headings.md
vendored
Normal file
|
|
@ -0,0 +1,13 @@
|
||||||
|
# H1
|
||||||
|
|
||||||
|
## H2
|
||||||
|
|
||||||
|
### H3
|
||||||
|
|
||||||
|
#### H4
|
||||||
|
|
||||||
|
##### H5
|
||||||
|
|
||||||
|
###### H6
|
||||||
|
|
||||||
|
Body under headings.
|
||||||
11
web/tests/fixtures/markdown-corpus/supported/lists.md
vendored
Normal file
11
web/tests/fixtures/markdown-corpus/supported/lists.md
vendored
Normal file
|
|
@ -0,0 +1,11 @@
|
||||||
|
- alpha
|
||||||
|
- beta
|
||||||
|
- nested one
|
||||||
|
- nested two
|
||||||
|
- gamma
|
||||||
|
|
||||||
|
1. first
|
||||||
|
2. second
|
||||||
|
1. second-a
|
||||||
|
2. second-b
|
||||||
|
3. third
|
||||||
8
web/tests/fixtures/markdown-corpus/supported/task-lists.md
vendored
Normal file
8
web/tests/fixtures/markdown-corpus/supported/task-lists.md
vendored
Normal file
|
|
@ -0,0 +1,8 @@
|
||||||
|
- [ ] open task
|
||||||
|
- [x] done task
|
||||||
|
- [ ] task with **bold** text
|
||||||
|
|
||||||
|
Regular paragraph between.
|
||||||
|
|
||||||
|
- [ ] another list
|
||||||
|
- [x] nested done
|
||||||
66
web/tests/insert-menu-mode-toggle.test.tsx
Normal file
66
web/tests/insert-menu-mode-toggle.test.tsx
Normal file
|
|
@ -0,0 +1,66 @@
|
||||||
|
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||||
|
import { fireEvent, render, screen } from "@testing-library/react";
|
||||||
|
import { beforeAll, describe, expect, it, vi } from "vitest";
|
||||||
|
import InsertMenu from "@/components/MemoEditor/Toolbar/InsertMenu";
|
||||||
|
import { EditorProvider, useEditorContext } from "@/components/MemoEditor/state";
|
||||||
|
|
||||||
|
// 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 { state } = useEditorContext();
|
||||||
|
return <span data-testid="mode">{state.ui.editorMode}</span>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderInsertMenu() {
|
||||||
|
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||||
|
render(
|
||||||
|
<QueryClientProvider client={client}>
|
||||||
|
<EditorProvider>
|
||||||
|
<InsertMenu onLocationChange={() => {}} />
|
||||||
|
<ModeProbe />
|
||||||
|
</EditorProvider>
|
||||||
|
</QueryClientProvider>,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("InsertMenu editor-mode toggle", () => {
|
||||||
|
it("switches mode and persists the preference when the item is selected", () => {
|
||||||
|
localStorage.clear();
|
||||||
|
renderInsertMenu();
|
||||||
|
expect(screen.getByTestId("mode").textContent).toBe("wysiwyg");
|
||||||
|
|
||||||
|
// Open the dropdown (keyboard open is the most reliable path in jsdom).
|
||||||
|
fireEvent.keyDown(screen.getByRole("button"), { key: "Enter" });
|
||||||
|
|
||||||
|
// Default mode is wysiwyg, so the item offers to switch to raw.
|
||||||
|
fireEvent.click(screen.getByText("editor.switch-to-raw"));
|
||||||
|
|
||||||
|
expect(screen.getByTestId("mode").textContent).toBe("raw");
|
||||||
|
expect(localStorage.getItem("memos-editor-mode")).toBe("raw");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("offers to switch back to rich text when already in raw mode", () => {
|
||||||
|
localStorage.setItem("memos-editor-mode", "raw");
|
||||||
|
renderInsertMenu();
|
||||||
|
expect(screen.getByTestId("mode").textContent).toBe("raw");
|
||||||
|
|
||||||
|
fireEvent.keyDown(screen.getByRole("button"), { key: "Enter" });
|
||||||
|
fireEvent.click(screen.getByText("editor.switch-to-wysiwyg"));
|
||||||
|
|
||||||
|
expect(screen.getByTestId("mode").textContent).toBe("wysiwyg");
|
||||||
|
expect(localStorage.getItem("memos-editor-mode")).toBe("wysiwyg");
|
||||||
|
});
|
||||||
|
});
|
||||||
51
web/tests/markdown-roundtrip.test.ts
Normal file
51
web/tests/markdown-roundtrip.test.ts
Normal file
|
|
@ -0,0 +1,51 @@
|
||||||
|
import { readdirSync, readFileSync } from "node:fs";
|
||||||
|
import { join } from "node:path";
|
||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { parseMarkdown, roundTripMarkdown } from "@/components/MemoEditor/TiptapEditor/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);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
@ -9,6 +9,43 @@ afterEach(() => {
|
||||||
cleanup();
|
cleanup();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ProseMirror probes layout APIs jsdom doesn't implement.
|
||||||
|
if (typeof document !== "undefined") {
|
||||||
|
if (!document.elementFromPoint) {
|
||||||
|
document.elementFromPoint = () => null;
|
||||||
|
}
|
||||||
|
if (typeof Range !== "undefined" && !Range.prototype.getClientRects) {
|
||||||
|
Range.prototype.getClientRects = () => [] as unknown as DOMRectList;
|
||||||
|
Range.prototype.getBoundingClientRect = () =>
|
||||||
|
({ x: 0, y: 0, top: 0, left: 0, bottom: 0, right: 0, width: 0, height: 0, toJSON: () => ({}) }) as DOMRect;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// jsdom runs with an opaque origin (no URL set), so its built-in localStorage
|
||||||
|
// implementation throws SecurityError on every access. Install a Map-backed shim
|
||||||
|
// so any test that touches localStorage directly can call getItem/setItem/removeItem/clear
|
||||||
|
// without additional per-file setup. Tests that need special behavior (hooks.test.tsx,
|
||||||
|
// memo-editor-cache.test.ts) override this via Object.defineProperty / vi.stubGlobal.
|
||||||
|
if (typeof globalThis.localStorage === "undefined" || typeof globalThis.localStorage.clear !== "function") {
|
||||||
|
let _store = new Map<string, string>();
|
||||||
|
const localStorageShim: Storage = {
|
||||||
|
get length() {
|
||||||
|
return _store.size;
|
||||||
|
},
|
||||||
|
getItem: (key: string) => _store.get(key) ?? null,
|
||||||
|
setItem: (key: string, value: string) => _store.set(key, value),
|
||||||
|
removeItem: (key: string) => _store.delete(key),
|
||||||
|
clear: () => {
|
||||||
|
_store = new Map<string, string>();
|
||||||
|
},
|
||||||
|
key: (index: number) => Array.from(_store.keys())[index] ?? null,
|
||||||
|
};
|
||||||
|
Object.defineProperty(globalThis, "localStorage", {
|
||||||
|
configurable: true,
|
||||||
|
value: localStorageShim,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
// Defensive shim: `@/auth-state` constructs a BroadcastChannel at module load
|
// Defensive shim: `@/auth-state` constructs a BroadcastChannel at module load
|
||||||
// to coordinate token refreshes across tabs. jsdom historically has not shipped
|
// to coordinate token refreshes across tabs. jsdom historically has not shipped
|
||||||
// BroadcastChannel, so any future test that transitively imports auth-state
|
// BroadcastChannel, so any future test that transitively imports auth-state
|
||||||
|
|
|
||||||
176
web/tests/suggestion-menu.test.tsx
Normal file
176
web/tests/suggestion-menu.test.tsx
Normal file
|
|
@ -0,0 +1,176 @@
|
||||||
|
import { act, fireEvent, render, screen } from "@testing-library/react";
|
||||||
|
import { createRef } from "react";
|
||||||
|
import { describe, expect, it, vi } from "vitest";
|
||||||
|
import { SuggestionMenu, createSuggestionRenderer, type SuggestionMenuHandle } from "@/components/MemoEditor/TiptapEditor/suggestionMenu";
|
||||||
|
|
||||||
|
function setup(items = ["alpha", "beta", "gamma"]) {
|
||||||
|
const command = vi.fn();
|
||||||
|
const ref = createRef<SuggestionMenuHandle>();
|
||||||
|
render(
|
||||||
|
<SuggestionMenu
|
||||||
|
ref={ref}
|
||||||
|
items={items}
|
||||||
|
command={command}
|
||||||
|
getItemKey={(item: string) => item}
|
||||||
|
renderItem={(item: string) => <span>#{item}</span>}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
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<string, Array<() => 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 { createRoot } = require("react-dom/client") as typeof import("react-dom/client");
|
||||||
|
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<string>({
|
||||||
|
renderItem: (item: string) => <span>{item}</span>,
|
||||||
|
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<string>({
|
||||||
|
renderItem: (item: string) => <span>{item}</span>,
|
||||||
|
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);
|
||||||
|
});
|
||||||
|
});
|
||||||
172
web/tests/tiptap-editor-controller.test.tsx
Normal file
172
web/tests/tiptap-editor-controller.test.tsx
Normal file
|
|
@ -0,0 +1,172 @@
|
||||||
|
import type { Editor } from "@tiptap/core";
|
||||||
|
import { act, fireEvent, render } from "@testing-library/react";
|
||||||
|
import { createRef } from "react";
|
||||||
|
import { describe, expect, it, vi } from "vitest";
|
||||||
|
import TiptapEditor from "@/components/MemoEditor/TiptapEditor";
|
||||||
|
import type { EditorController } from "@/components/MemoEditor/types/editorController";
|
||||||
|
|
||||||
|
vi.mock("@/hooks/useUserQueries", async (importOriginal) => ({
|
||||||
|
...(await importOriginal<object>()),
|
||||||
|
useTagCounts: () => ({ data: {} }),
|
||||||
|
}));
|
||||||
|
|
||||||
|
function setup(initialContent = "") {
|
||||||
|
const ref = createRef<EditorController>();
|
||||||
|
const onContentChange = vi.fn();
|
||||||
|
const { container } = render(
|
||||||
|
<TiptapEditor ref={ref} initialContent={initialContent} placeholder="memo" onContentChange={onContentChange} onPaste={vi.fn()} />,
|
||||||
|
);
|
||||||
|
// Tiptap exposes the editor instance 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?: Editor }).editor as Editor;
|
||||||
|
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<EditorController>();
|
||||||
|
const onContentChange = vi.fn();
|
||||||
|
const renderEditor = (content: string) => (
|
||||||
|
<TiptapEditor ref={ref} initialContent={content} placeholder="memo" onContentChange={onContentChange} onPaste={vi.fn()} />
|
||||||
|
);
|
||||||
|
const { rerender: rtlRerender } = render(renderEditor(initialContent));
|
||||||
|
const rerender = (content: string) => act(() => rtlRerender(renderEditor(content)));
|
||||||
|
return { ref, onContentChange, rerender };
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("TiptapEditor 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("toggleBold bolds the selected text", () => {
|
||||||
|
const { ref } = setup("bold me");
|
||||||
|
act(() => ref.current?.selectAll());
|
||||||
|
act(() => ref.current?.toggleBold());
|
||||||
|
expect(ref.current?.getMarkdown()).toBe("**bold me**");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("toggleTaskList converts the current block", () => {
|
||||||
|
const { ref } = setup("buy milk");
|
||||||
|
act(() => ref.current?.toggleTaskList());
|
||||||
|
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("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");
|
||||||
|
});
|
||||||
|
});
|
||||||
85
web/tests/tiptap-preserved.test.ts
Normal file
85
web/tests/tiptap-preserved.test.ts
Normal file
|
|
@ -0,0 +1,85 @@
|
||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { parseMarkdown, roundTripMarkdown } from "@/components/MemoEditor/TiptapEditor/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 = "<div>\nhello\n</div>";
|
||||||
|
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 <em>emphasis</em> tag").trim()).toBe("an <em>emphasis</em> tag");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not swallow autolinks", () => {
|
||||||
|
const doc = parseMarkdown("see <https://example.com> 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 <!-- hi --> more").trim()).toBe("text <!-- hi --> more");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("preserves block HTML comments", () => {
|
||||||
|
expect(roundTripMarkdown("<!-- standalone -->").trim()).toBe("<!-- standalone -->");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("handles > inside quoted attributes", () => {
|
||||||
|
expect(roundTripMarkdown('a <span data-x="1 > 0">hm</span> b').trim()).toBe('a <span data-x="1 > 0">hm</span> b');
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not catastrophically backtrack on unterminated tags full of quotes", () => {
|
||||||
|
const hostile = `a <span ${'"x'.repeat(60)} b`;
|
||||||
|
const startedAt = performance.now();
|
||||||
|
const out = roundTripMarkdown(hostile);
|
||||||
|
expect(performance.now() - startedAt).toBeLessThan(1000);
|
||||||
|
// Stray unmatched quotes may be entity-encoded by upstream; keep the timing
|
||||||
|
// assertion strict and only verify the stable trailing content is present.
|
||||||
|
expect(out).toContain("b");
|
||||||
|
});
|
||||||
|
});
|
||||||
80
web/tests/tiptap-slash-commands.test.ts
Normal file
80
web/tests/tiptap-slash-commands.test.ts
Normal file
|
|
@ -0,0 +1,80 @@
|
||||||
|
import { Editor } from "@tiptap/core";
|
||||||
|
import { afterEach, describe, expect, it } from "vitest";
|
||||||
|
import { buildExtensions } from "@/components/MemoEditor/TiptapEditor/extensions";
|
||||||
|
import { filterSlashCommands, slashCommandItems } from "@/components/MemoEditor/TiptapEditor/SlashCommand";
|
||||||
|
|
||||||
|
let editor: Editor;
|
||||||
|
|
||||||
|
function applyCommand(name: string, content = "") {
|
||||||
|
editor = new Editor({ extensions: buildExtensions(), content, contentType: "markdown" });
|
||||||
|
const item = slashCommandItems.find((candidate) => candidate.name === name);
|
||||||
|
if (!item) throw new Error(`unknown slash command: ${name}`);
|
||||||
|
// Simulate a trigger at the end of an empty paragraph (the only case this
|
||||||
|
// range math is correct for). After inserting "/" into an empty paragraph,
|
||||||
|
// the doc is doc(paragraph(text"/")), with the slash at positions 1..2
|
||||||
|
// (doc.content.size = 3). We replicate that range so deleteRange removes the
|
||||||
|
// trigger character exactly as the real Suggestion plugin would.
|
||||||
|
editor.commands.insertContent("/");
|
||||||
|
const end = editor.state.doc.content.size;
|
||||||
|
item.apply(editor, { from: end - 2, to: end - 1 });
|
||||||
|
return editor.getMarkdown();
|
||||||
|
}
|
||||||
|
|
||||||
|
afterEach(() => editor?.destroy());
|
||||||
|
|
||||||
|
describe("WYSIWYG slash commands", () => {
|
||||||
|
it("todo converts the block into a task list", () => {
|
||||||
|
expect(applyCommand("todo").trimEnd()).toBe("- [ ]");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("code converts the block into a code block", () => {
|
||||||
|
expect(applyCommand("code")).toContain("```");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("link inserts a markdown link", () => {
|
||||||
|
expect(applyCommand("link")).toContain("[text](url)");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("link places cursor selecting the display text", () => {
|
||||||
|
// After deleteRange(from:1, to:2) + insertContent the marked text node
|
||||||
|
// "text" occupies positions 1..5 (range.from=1, text length=4).
|
||||||
|
// The command chains .setTextSelection({ from: 1, to: 5 }) so the user
|
||||||
|
// can immediately overtype the placeholder label.
|
||||||
|
applyCommand("link");
|
||||||
|
const sel = editor.state.selection;
|
||||||
|
expect(sel.from).toBe(1);
|
||||||
|
expect(sel.to).toBe(5);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("table inserts a preserved markdown table", () => {
|
||||||
|
const markdown = applyCommand("table");
|
||||||
|
expect(markdown).toContain("| Header | Header |");
|
||||||
|
expect(markdown).toContain("| ------ | ------ |");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("table places cursor at the first header cell", () => {
|
||||||
|
// The preservedBlock text starts at range.from (pos 1). "| Header …" has
|
||||||
|
// "| " (2 chars) before the first label, so the command chains
|
||||||
|
// .setTextSelection(range.from + 2) = position 3, landing on the "H".
|
||||||
|
applyCommand("table");
|
||||||
|
const sel = editor.state.selection;
|
||||||
|
expect(sel.from).toBe(3);
|
||||||
|
expect(sel.to).toBe(3);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("filterSlashCommands", () => {
|
||||||
|
it("returns all items for an empty query", () => {
|
||||||
|
expect(filterSlashCommands("").map((i) => i.name)).toEqual(["todo", "code", "link", "table"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("filters items by case-insensitive prefix", () => {
|
||||||
|
expect(filterSlashCommands("t").map((i) => i.name)).toEqual(["todo", "table"]);
|
||||||
|
expect(filterSlashCommands("T").map((i) => i.name)).toEqual(["todo", "table"]);
|
||||||
|
expect(filterSlashCommands("c").map((i) => i.name)).toEqual(["code"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns an empty array for a non-matching query", () => {
|
||||||
|
expect(filterSlashCommands("x")).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
117
web/tests/tiptap-tag.test.ts
Normal file
117
web/tests/tiptap-tag.test.ts
Normal file
|
|
@ -0,0 +1,117 @@
|
||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import type { JSONContent } from "@tiptap/core";
|
||||||
|
import { parseMarkdown, roundTripMarkdown } from "@/components/MemoEditor/TiptapEditor/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("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 and #a#b byte-identically (visual divergence documented in Tag.ts)", () => {
|
||||||
|
expect(roundTripMarkdown("##x").trim()).toBe("##x");
|
||||||
|
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("documents known gap: backslash-escaped \\# degrades after one cycle (upstream escape dropping)", () => {
|
||||||
|
const out = roundTripMarkdown("\\#escaped");
|
||||||
|
expect(out.trim()).toBe("#escaped"); // upstream drops the escape (pre-existing); re-parse then sees a tag
|
||||||
|
expect(roundTripMarkdown(out)).toBe(out); // at least stable from then on
|
||||||
|
});
|
||||||
|
});
|
||||||
Loading…
Reference in a new issue