Memos is an open-source, self-hosted note-taking app that brings your everyday thoughts together in a personal timeline. Your data stays yours, and you choose what to keep private or share.
Go dockerfossgomarkdownmemomicroblognote-takingnotesopen-sourceown-your-datareactself-hostedsqlitetimeline
feat(web): markdown WYSIWYG editor with raw-mode toggle (#6030)
boojack797f1ff15dcb
diff --git a/docs/superpowers/plans/2026-06-11-markdown-wysiwyg-editor.md b/docs/superpowers/plans/2026-06-11-markdown-wysiwyg-editor.mdnew file mode 100644index 000000000..c4d044a10--- /dev/null+++ b/docs/superpowers/plans/2026-06-11-markdown-wysiwyg-editor.md@@ -0,0 +1,2621 @@+# Markdown WYSIWYG Editor Implementation Plan++> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.++**Goal:** Replace the plain `<textarea>` memo editor with a Tiptap-based WYSIWYG editor that renders markdown live while keeping markdown as the only storage format, with a per-device toggle back to the raw textarea editor.++**Architecture:** Both editors sit behind a shared `EditorController` interface hosted by `EditorContent`. The Tiptap editor uses the official `@tiptap/markdown` extension (Tiptap 3.26) for bidirectional markdown; custom `Tag`, `PreservedBlock`/`PreservedInline`, `TagSuggestion`, and `SlashCommand` extensions cover memos-specific features and fidelity. Unmodeled syntax (tables, math, raw HTML) is preserved byte-for-byte. A round-trip corpus test is written first as the go/no-go spike gate.++**Tech Stack:** React 19, Tiptap 3.26 (`@tiptap/core`, `@tiptap/react`, `@tiptap/starter-kit`, `@tiptap/extension-list`, `@tiptap/extensions`, `@tiptap/suggestion`, `@tiptap/markdown` + marked 17), vitest + jsdom + @testing-library/react, Tailwind 4.++---++## Context for the implementer (read first)++- All web code lives in `web/`. Run commands from `/Users/steven/Projects/usememos/memos/web` unless stated otherwise. Package manager is **pnpm**.+- Tests live in `web/tests/*.test.{ts,tsx}` (NOT colocated with src), run by `pnpm test` (vitest, jsdom, setup file `web/tests/setup.ts`). Path alias `@/` → `web/src/`.+- Lint/typecheck: `pnpm lint` (runs `tsc --noEmit` + biome). Auto-fix style: `pnpm lint:fix`.+- The current textarea editor is `web/src/components/MemoEditor/Editor/index.tsx`, exposing an imperative `EditorRefActions` API. It stays — it powers raw mode. **Do not delete it or its sub-features** (`TagSuggestions.tsx`, `SlashCommands.tsx`, `useSuggestions.ts`, `useListCompletion.ts`, `shortcuts.ts`, `commands.ts`).+- Editor state flows through a reducer context (`web/src/components/MemoEditor/state/`). `state.content` is the markdown string; auto-save drafts (`useAutoSave`), validation, and save (`memoService.save`) all read it. The backend only ever sees markdown.+- Verified API facts (Tiptap 3.26.0, inspected from published sources — do not re-derive):+ - `@tiptap/markdown` exports `Markdown` (an Extension). It adds `editor.getMarkdown(): string`, `editor.markdown.parse(md): JSONContent`, and a `contentType: "markdown"` option to `new Editor()`, `setContent`, `insertContent`, `insertContentAt`.+ - Extensions declare markdown behavior via top-level config fields (typed in `@tiptap/core`): `markdownTokenName` (marked token type to handle), `parseMarkdown: (token, helpers) => JSONContent | JSONContent[] | null`, `renderMarkdown: (node, helpers, context) => string`, and `markdownTokenizer: { name, level: "inline" | "block", start, tokenize }` (a marked tokenizer extension; **custom tokenizers run before marked's built-ins**).+ - `parseMarkdown` helpers include `createNode(type, attrs?, content?)`, `createTextNode(text, marks?)`, `parseInline(tokens)`, `parseChildren(tokens)`.+ - The `Document` extension joins top-level blocks with `\n\n`; block renderers return their content **without** trailing separators (e.g. CodeBlock returns ` ```lang\n…\n``` `).+ - Nodes/marks with `code: true` skip the serializer's markdown escaping and HTML-entity encoding for their inner text — this is what makes verbatim preservation work.+ - Inline `html` tokens are handled internally by the markdown manager **before** the handler registry (recognized tags like `<em>` get converted to marks — a fidelity violation for us), so inline HTML preservation must use a custom inline *tokenizer* that captures tags before marked's built-in html tokenizer. Block-level `html` tokens DO consult the registry first, so a plain `parseMarkdown` handler works for them.+ - StarterKit v3 already includes: Bold, Italic, Strike, Code, CodeBlock, Heading, BulletList/OrderedList/ListItem/ListKeymap, Blockquote, Link (with `linkOnPaste: true` default — URL-paste-over-selection → link), Underline, HardBreak, HorizontalRule, Dropcursor, Gapcursor, UndoRedo, TrailingNode. All ship with markdown input rules and parse/render specs.+ - `TaskList`/`TaskItem` are exported from `@tiptap/extension-list`. `Placeholder` is exported from `@tiptap/extensions`. `Suggestion` is the default and a named export of `@tiptap/suggestion`.+- **Deliberate deviation from the spec:** the spec says serialized markdown flows to the reducer "debounced". We serialize on every `update` event instead — serialization is cheap at memo scale, and synchronous `state.content` keeps the save path, draft cache, and mode-toggle handoff race-free. Revisit only if profiling shows cost.+- Conventional commits, matching repo style: `feat(web): …`, `fix(web): …`, `test(web): …`.++## File structure++New files:++| File | Responsibility |+|---|---|+| `web/src/components/MemoEditor/types/editorController.ts` | The shared `EditorController` interface |+| `web/src/components/MemoEditor/Editor/controllerAdapter.ts` | Adapts textarea `EditorRefActions` → `EditorController` |+| `web/src/components/MemoEditor/TiptapEditor/extensions.ts` | Canonical schema extension list (`buildExtensions()`) |+| `web/src/components/MemoEditor/TiptapEditor/markdownCodec.ts` | Headless parse/serialize/round-trip helpers (tests + load guard) |+| `web/src/components/MemoEditor/TiptapEditor/PreservedBlock.ts` | Fidelity workhorse: preserved block node, preserved inline mark, parse bridges for table/html/math |+| `web/src/components/MemoEditor/TiptapEditor/Tag.ts` | Inline `#tag` atom node with tokenizer + input rule |+| `web/src/components/MemoEditor/TiptapEditor/suggestionMenu.tsx` | Shared popup component + Suggestion-plugin renderer factory |+| `web/src/components/MemoEditor/TiptapEditor/TagSuggestion.ts` | `#` suggestion popup extension |+| `web/src/components/MemoEditor/TiptapEditor/SlashCommand.ts` | `/` command popup extension |+| `web/src/components/MemoEditor/TiptapEditor/index.tsx` | The Tiptap editor React component (implements `EditorController`) |+| `web/src/components/MemoEditor/editorMode.ts` | localStorage mode preference helpers |+| `web/tests/fixtures/markdown-corpus/supported/*.md` | Round-trip fixtures: semantic equality group |+| `web/tests/fixtures/markdown-corpus/preserved/*.md` | Round-trip fixtures: byte equality group |++Modified files: `web/src/components/MemoEditor/Editor/shortcuts.ts` (export `toggleTextStyle`), `state/types.ts` + `state/actions.ts` + `state/reducer.ts` + `state/context.tsx` (editor mode), `components/EditorContent.tsx` (dual host), `components/EditorToolbar.tsx` (toggle button), `hooks/useKeyboard.ts` + `hooks/useMemoInit.ts` + `index.tsx` (switch to `EditorController`), `web/src/locales/en.json` (new strings), `web/src/index.css` (task-list/placeholder styles), `web/package.json`.++---++### Task 1: Branch + dependencies++**Files:**+- Modify: `web/package.json` (via pnpm)++- [ ] **Step 1: Create the feature branch** (skip if already on an isolated worktree created for this plan)++```bash+cd /Users/steven/Projects/usememos/memos+git checkout -b feat/wysiwyg-editor+```++- [ ] **Step 2: Install Tiptap packages**++```bash+cd /Users/steven/Projects/usememos/memos/web+pnpm add @tiptap/[email protected] @tiptap/[email protected] @tiptap/[email protected] @tiptap/[email protected] @tiptap/[email protected] @tiptap/[email protected] @tiptap/[email protected] @tiptap/[email protected] marked@^17.0.1+```++Expected: pnpm resolves and writes to `package.json`/`pnpm-lock.yaml` without peer-dependency errors (`@tiptap/pm` is the peer of `@tiptap/markdown`).++- [ ] **Step 3: Verify the toolchain still passes**++```bash+pnpm lint && pnpm test+```++Expected: PASS (no source changes yet).++- [ ] **Step 4: Commit**++```bash+git add package.json pnpm-lock.yaml+git commit -m "feat(web): add tiptap 3.26 dependencies for wysiwyg editor"+```++---++### Task 2: Spike — markdown codec + round-trip corpus test (GO/NO-GO gate)++This is the spike from the spec's fidelity contract. It must be done first. If, after honest effort at configuration/custom tokenizers, the **supported-syntax** corpus cannot pass, **STOP and report**: the fallback decision (swap only the parse/serialize layer to remark, keeping the Tiptap editor) is a human decision, not something to improvise mid-plan.++**Files:**+- Create: `web/src/components/MemoEditor/TiptapEditor/extensions.ts`+- Create: `web/src/components/MemoEditor/TiptapEditor/markdownCodec.ts`+- Create: `web/tests/fixtures/markdown-corpus/supported/` (7 fixture files below)+- Test: `web/tests/markdown-roundtrip.test.ts`++- [ ] **Step 1: Create the corpus fixtures**++`web/tests/fixtures/markdown-corpus/supported/basic.md`:++````markdown+# Hello memos++Some **bold**, *italic*, ~~struck~~, and `inline code` text.++> A blockquote with **bold** inside.++A [link](https://example.com/docs) in a sentence.+````++`web/tests/fixtures/markdown-corpus/supported/headings.md`:++````markdown+# H1++## H2++### H3++#### H4++##### H5++###### H6++Body under headings.+````++`web/tests/fixtures/markdown-corpus/supported/lists.md`:++````markdown+- alpha+- beta+ - nested one+ - nested two+- gamma++1. first+2. second+ 1. second-a+ 2. second-b+3. third+````++`web/tests/fixtures/markdown-corpus/supported/task-lists.md`:++````markdown+- [ ] open task+- [x] done task+- [ ] task with **bold** text++Regular paragraph between.++- [ ] another list+ - [x] nested done+````++`web/tests/fixtures/markdown-corpus/supported/code-blocks.md`:++`````markdown+Some text first.++```go+func main() {+ fmt.Println("hello *not italic* #not-a-tag")+}+```++```mermaid+graph TD;+ A-->B;+```++```+no language fence+```+`````++`web/tests/fixtures/markdown-corpus/supported/cjk-emoji.md`:++````markdown+# 日本語の見出し++これは**太字**と*斜体*のテストです。改行も確認します。++- 中文列表项+- 한국어 항목+- emoji 🎉 in a list 🚀++> 引用文です 😀+````++`web/tests/fixtures/markdown-corpus/supported/blockquote-mixed.md`:++````markdown+> Outer quote line one.+> Still the same quote.++Paragraph after.++> - a list in a quote+> - second item+````++- [ ] **Step 2: Write the failing round-trip test**++`web/tests/markdown-roundtrip.test.ts`:++```ts+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);+ });+ }+});+```++- [ ] **Step 3: Run it to verify it fails for the right reason**++```bash+pnpm test -- markdown-roundtrip+```++Expected: FAIL with "Failed to resolve import …/markdownCodec" (module doesn't exist yet).++- [ ] **Step 4: Implement the extension list and the codec**++`web/src/components/MemoEditor/TiptapEditor/extensions.ts`:++```ts+import type { AnyExtension } from "@tiptap/core";+import { TaskItem, TaskList } from "@tiptap/extension-list";+import { Markdown } from "@tiptap/markdown";+import StarterKit from "@tiptap/starter-kit";++/**+ * 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,+ ];+}+```++`web/src/components/MemoEditor/TiptapEditor/markdownCodec.ts`:++```ts+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.+ */+function withEditor<T>(markdown: string, fn: (editor: Editor) => T): T {+ const editor = new Editor({+ extensions: buildExtensions(),+ content: markdown,+ contentType: "markdown",+ });+ try {+ return fn(editor);+ } finally {+ editor.destroy();+ }+}++export function parseMarkdown(markdown: string): JSONContent {+ return withEditor(markdown, (editor) => editor.getJSON());+}++export function roundTripMarkdown(markdown: string): string {+ return withEditor(markdown, (editor) => editor.getMarkdown());+}++/** True when a serialize cycle would not change the document's meaning. */+export function isLosslessRoundTrip(markdown: string): boolean {+ try {+ const once = parseMarkdown(markdown);+ const twice = parseMarkdown(roundTripMarkdown(markdown));+ return JSON.stringify(once) === JSON.stringify(twice);+ } catch {+ return false;+ }+}+```++- [ ] **Step 5: Run the corpus test — this is the gate**++```bash+pnpm test -- markdown-roundtrip+```++Expected: PASS (14 tests: 7 fixtures × 2 assertions).++Troubleshooting, in order:+1. `new Editor()` throws about a missing element in jsdom → pass `element: document.createElement("div")` in `withEditor`.+2. A specific fixture fails semantic equality → diff the two JSON trees (`console.log(JSON.stringify(parseMarkdown(src), null, 2))`), then fix via StarterKit configuration or (only if config can't) a small custom `parseMarkdown`/`renderMarkdown` override on the offending extension via `.extend()` in `extensions.ts`. Document each override with a comment naming the fixture that needs it.+3. Idempotence fails but semantic equality passes → acceptable only if the second pass output equals the third (stable after one normalization); in that case change the idempotence assertion to compare pass 2 vs pass 3 and leave a comment explaining the one-time normalization. Otherwise treat as a real bug.+4. **If supported-syntax failures cannot be fixed at all → STOP. Report NO-GO** with the failing fixtures and diffs. Do not proceed to Task 3.++- [ ] **Step 6: Commit**++```bash+cd /Users/steven/Projects/usememos/memos+git add web/src/components/MemoEditor/TiptapEditor web/tests+git commit -m "test(web): add markdown round-trip corpus spike for tiptap codec"+```++---++### Task 3: PreservedBlock / PreservedInline — byte-for-byte fidelity for unmodeled syntax++Tables, `$…$`/`$$…$$` math, and raw HTML are out of the v1 editing scope but must survive an edit session byte-for-byte. Block constructs become an editable literal-text block node (`preservedBlock`, mono styling, `code: true` so nothing inside is escaped); inline constructs become plain text carrying a `preservedInline` mark (`code: true` likewise). Marked "bridge" extensions route the relevant tokens into them at parse time.++**Files:**+- Create: `web/src/components/MemoEditor/TiptapEditor/PreservedBlock.ts`+- Modify: `web/src/components/MemoEditor/TiptapEditor/extensions.ts`+- Create: `web/tests/fixtures/markdown-corpus/preserved/` (5 fixtures)+- Test: `web/tests/tiptap-preserved.test.ts`, extend `web/tests/markdown-roundtrip.test.ts`++- [ ] **Step 1: Create the preserved-corpus fixtures**++IMPORTANT authoring constraint: these files are asserted **byte-equal** (trimmed) after a round trip, so they must contain *only* preserved constructs plus plain prose that no serializer pass would rewrite — no `*`, `_`, `` ` ``, `[`, `]`, `~`, `\` characters outside the preserved spans, no list markers, no headings.++`web/tests/fixtures/markdown-corpus/preserved/table.md`:++````markdown+| Name | Role |+| --- | --- |+| Ada | Engineer |+| Grace | Admiral |+````++`web/tests/fixtures/markdown-corpus/preserved/math-block.md`:++````markdown+Before the math.++$$+E = mc^2 \cdot \frac{1}{\sqrt{1 - v^2/c^2}}+$$++After the math.+````++`web/tests/fixtures/markdown-corpus/preserved/math-inline.md`:++````markdown+Energy is $E=mc^2$ and the index is $x_1$ in this sentence.+````++`web/tests/fixtures/markdown-corpus/preserved/inline-html.md`:++````markdown+Use <em>emphasis</em> and a line<br>break and <span class="x">spans</span> here.+````++`web/tests/fixtures/markdown-corpus/preserved/block-html.md`:++````markdown+Paragraph before.++<div class="custom">+ <p>Raw HTML block content</p>+</div>++Paragraph after.+````++- [ ] **Step 2: Extend the corpus test with the byte-equality group**++Append to `web/tests/markdown-roundtrip.test.ts`:++```ts+// 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).+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);+ });+ }+});+```++- [ ] **Step 3: Write the unit test for the preservation nodes**++`web/tests/tiptap-preserved.test.ts`:++```ts+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);+ });+});+```++- [ ] **Step 4: Run both tests to verify they fail**++```bash+pnpm test -- tiptap-preserved markdown-roundtrip+```++Expected: the new preserved/byte-equality and unit tests FAIL (e.g. table parsed via fallback, `$x_1$` re-serialized as `$x\_1$`); the supported group still PASSES.++- [ ] **Step 5: Implement the preservation extensions**++`web/src/components/MemoEditor/TiptapEditor/PreservedBlock.ts`:++```ts+import { Extension, Mark, Node, mergeAttributes } from "@tiptap/core";+import type { MarkdownParseHelpers, MarkdownToken } from "@tiptap/core";++/**+ * 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) : ""),+});++function preservedBlockFromToken(token: MarkdownToken, helpers: MarkdownParseHelpers) {+ const source = (token.raw ?? "").replace(/\n+$/, "");+ if (!source) {+ return null;+ }+ return helpers.createNode("preservedBlock", {}, [helpers.createTextNode(source)]);+}++/** 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 null;+ }+ return preservedBlockFromToken(token, helpers);+ },+});++export const PreservedHtmlInlineBridge = Extension.create({+ name: "preservedHtmlInlineBridge",+ markdownTokenName: "preservedHtmlInline",+ markdownTokenizer: {+ name: "preservedHtmlInline",+ level: "inline",+ start: (src: string) => src.indexOf("<"),+ tokenize(src: string) {+ // One opening/closing/self-closing HTML tag. 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 <[email protected]> (`:`/`@` break the match).+ const match = /^<\/?[a-zA-Z][a-zA-Z0-9-]*(?:\s[^<>]*)?\/?>/.exec(src);+ if (!match) {+ return undefined;+ }+ return { type: "preservedHtmlInline", raw: match[0], text: match[0] };+ },+ },+ parseMarkdown: (token, helpers) => helpers.createTextNode(token.raw ?? "", [{ type: "preservedInline" }]),+});++export const PreservedMathBlockBridge = Extension.create({+ name: "preservedMathBlockBridge",+ markdownTokenName: "preservedMathBlock",+ markdownTokenizer: {+ name: "preservedMathBlock",+ level: "block",+ start: (src: string) => src.indexOf("$$"),+ tokenize(src: string) {+ const match = /^\$\$[\s\S]+?\$\$(?:\n+|$)/.exec(src);+ if (!match) {+ return undefined;+ }+ return { type: "preservedMathBlock", raw: match[0], text: match[0] };+ },+ },+ parseMarkdown: preservedBlockFromToken,+});++export const PreservedMathInlineBridge = Extension.create({+ name: "preservedMathInlineBridge",+ markdownTokenName: "preservedMathInline",+ markdownTokenizer: {+ name: "preservedMathInline",+ level: "inline",+ start: (src: string) => src.indexOf("$"),+ tokenize(src: string) {+ const match = /^\$[^$\n]+\$/.exec(src);+ if (!match) {+ return undefined;+ }+ return { type: "preservedMathInline", raw: match[0], text: match[0] };+ },+ },+ parseMarkdown: (token, helpers) => helpers.createTextNode(token.raw ?? "", [{ type: "preservedInline" }]),+});++export const preservedExtensions = [+ PreservedBlock,+ PreservedInline,+ PreservedTableBridge,+ PreservedHtmlBlockBridge,+ PreservedHtmlInlineBridge,+ PreservedMathBlockBridge,+ PreservedMathInlineBridge,+];+```++Register in `web/src/components/MemoEditor/TiptapEditor/extensions.ts` — add the import and spread the list into the returned array after `Markdown`:++```ts+import { preservedExtensions } from "./PreservedBlock";+// …inside buildExtensions() return array, after Markdown:+ ...preservedExtensions,+```++- [ ] **Step 6: Run the tests until green**++```bash+pnpm test -- tiptap-preserved markdown-roundtrip+```++Expected: PASS (all groups).++Troubleshooting:+- TS error on `markdownTokenName`/`parseMarkdown` config fields → confirm `@tiptap/core` is 3.26.0 (`pnpm why @tiptap/core`); these fields are typed in `ExtendableConfig` there.+- Inline HTML still converted to `<em>` marks → the custom tokenizer isn't winning; verify the `markdownTokenizer.name` matches `markdownTokenName` exactly and check token output with `editor.markdown.parse("…")` in a scratch test.+- `block-html.md` byte test fails on internal blank lines: marked may split an HTML block at blank lines into multiple tokens. If so, simplify the fixture's `<div>` to have no blank lines inside (the contract is per-construct preservation, not blank-line geometry inside raw HTML), and note it in the fixture.+- Tokenizer with `level: "block"` not firing mid-document → marked requires block tokenizers to match at line starts; the `start` index approach is handled by the markdown manager. Verify with a one-line scratch test before deeper debugging.++- [ ] **Step 7: Commit**++```bash+git add web/src/components/MemoEditor/TiptapEditor web/tests+git commit -m "feat(web): preserve unmodeled markdown syntax byte-for-byte in tiptap editor"+```++---++### Task 4: `Tag` extension — memos `#tags` as inline tokens++**Files:**+- Create: `web/src/components/MemoEditor/TiptapEditor/Tag.ts`+- Modify: `web/src/components/MemoEditor/TiptapEditor/extensions.ts`+- Test: `web/tests/tiptap-tag.test.ts`++- [ ] **Step 1: Write the failing test**++`web/tests/tiptap-tag.test.ts`:++```ts+import { describe, expect, it } from "vitest";+import { parseMarkdown, roundTripMarkdown } from "@/components/MemoEditor/TiptapEditor/markdownCodec";++function firstParagraphChildren(markdown: string) {+ return parseMarkdown(markdown).content?.[0]?.content ?? [];+}++describe("Tag node", () => {+ it("parses #tag into a tag node", () => {+ const children = firstParagraphChildren("#hello world");+ expect(children[0]).toMatchObject({ type: "tag", attrs: { tag: "hello" } });+ expect(children[1]).toMatchObject({ type: "text", text: " world" });+ });++ it("serializes a tag node 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: "tag",+ attrs: { tag: "日本語" },+ });+ const children = firstParagraphChildren("see #work/project-1 now");+ const tagNode = children.find((n) => n.type === "tag");+ expect(tagNode?.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")).toBe(true);+ });+});+```++- [ ] **Step 2: Run it to verify it fails**++```bash+pnpm test -- tiptap-tag+```++Expected: FAIL — `#hello` currently parses as plain text, no `tag` node.++- [ ] **Step 3: Implement the Tag node**++`web/src/components/MemoEditor/TiptapEditor/Tag.ts`:++```ts+import { InputRule, Node, mergeAttributes } from "@tiptap/core";+import type { MarkdownToken } from "@tiptap/core";++// 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");++/**+ * Inline atom for memos `#tags`: rendered as a styled token in the editor,+ * serialized back to `#tag` verbatim. Parsed live while typing (input rule)+ * and from markdown (custom marked tokenizer).+ */+export const Tag = Node.create({+ name: "tag",+ group: "inline",+ inline: true,+ atom: true,+ selectable: true,++ addAttributes() {+ return { tag: { default: "" } };+ },++ parseHTML() {+ return [+ {+ tag: "span[data-tag]",+ getAttrs: (element) => ({ tag: (element as HTMLElement).getAttribute("data-tag") ?? "" }),+ },+ ];+ },++ renderHTML({ node, HTMLAttributes }) {+ return [+ "span",+ mergeAttributes(HTMLAttributes, {+ "data-tag": node.attrs.tag,+ class: "inline-block w-auto rounded bg-accent text-accent-foreground px-1",+ }),+ `#${node.attrs.tag}`,+ ];+ },++ addInputRules() {+ return [+ new InputRule({+ find: TAG_INPUT_RULE,+ handler: ({ state, range, match }) => {+ // The match may include a leading space/start anchor — only replace+ // from the `#` so we don't eat the separator before the tag.+ const start = range.from + match[0].indexOf("#");+ state.tr.replaceWith(start, range.to, [this.type.create({ tag: match[1] }), state.schema.text(" ")]);+ },+ }),+ ];+ },++ markdownTokenName: "memoTag",+ markdownTokenizer: {+ name: "memoTag",+ level: "inline",+ start: (src: string) => src.indexOf("#"),+ tokenize(src: string) {+ const match = TAG_TOKEN_RULE.exec(src);+ if (!match) {+ return undefined;+ }+ // Parity with remark-tag: `##x` is not a tag boundary.+ if (src[match[0].length] === "#") {+ return undefined;+ }+ return { type: "memoTag", raw: match[0], text: match[0], tag: match[1] };+ },+ },+ parseMarkdown: (token, helpers) => helpers.createNode("tag", { tag: (token as MarkdownToken & { tag?: string }).tag ?? "" }),+ renderMarkdown: (node) => `#${node.attrs?.tag ?? ""}`,+});+```++Register in `extensions.ts` (inside the `buildExtensions()` array, after the preserved extensions):++```ts+import { Tag } from "./Tag";+// …+ Tag,+```++- [ ] **Step 4: Run the tag tests and the full corpus**++```bash+pnpm test -- tiptap-tag markdown-roundtrip tiptap-preserved+```++Expected: PASS. (The corpus must stay green — the `#` tokenizer must not affect headings, which marked tokenizes at block level before inline rules run.)++- [ ] **Step 5: Commit**++```bash+git add web/src/components/MemoEditor/TiptapEditor web/tests/tiptap-tag.test.ts+git commit -m "feat(web): add memos tag node to tiptap editor with verbatim serialization"+```++---++### Task 5: `EditorController` interface + textarea adapter + MemoEditor rewiring++Introduce the shared interface and make the **existing textarea editor** implement it, so every consumer in `MemoEditor` stops depending on `EditorRefActions`. No Tiptap in the UI yet; behavior must be unchanged.++**Files:**+- Create: `web/src/components/MemoEditor/types/editorController.ts`+- Create: `web/src/components/MemoEditor/Editor/controllerAdapter.ts`+- Modify: `web/src/components/MemoEditor/Editor/shortcuts.ts` (export `toggleTextStyle`)+- Modify: `web/src/components/MemoEditor/components/EditorContent.tsx`+- Modify: `web/src/components/MemoEditor/hooks/useKeyboard.ts`+- Modify: `web/src/components/MemoEditor/hooks/useMemoInit.ts`+- Modify: `web/src/components/MemoEditor/index.tsx`+- Test: `web/tests/editor-controller-adapter.test.tsx`++- [ ] **Step 1: Define the interface**++`web/src/components/MemoEditor/types/editorController.ts`:++```ts+/**+ * 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;+ 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, with blank-line separation as needed. */+ insertMarkdown(markdown: string): void;+ scrollToCursor(): void;+ // Formatting intents — each editor realizes them natively.+ toggleBold(): void;+ toggleItalic(): void;+ toggleTaskList(): void;+}+```++- [ ] **Step 2: Export `toggleTextStyle` from shortcuts.ts**++In `web/src/components/MemoEditor/Editor/shortcuts.ts` change the declaration on line 43 from:++```ts+function toggleTextStyle(editor: EditorRefActions, delimiter: string): void {+```++to:++```ts+export function toggleTextStyle(editor: EditorRefActions, delimiter: string): void {+```++- [ ] **Step 3: Write the failing adapter test**++`web/tests/editor-controller-adapter.test.tsx`:++```tsx+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("hasFocus reflects the active element", () => {+ const { controller, textarea } = setup("x");+ expect(controller.hasFocus()).toBe(false);+ textarea.focus();+ expect(controller.hasFocus()).toBe(true);+ });+});+```++- [ ] **Step 4: Run it to verify it fails**++```bash+pnpm test -- editor-controller-adapter+```++Expected: FAIL — `controllerAdapter` module not found.++- [ ] **Step 5: Implement the adapter**++`web/src/components/MemoEditor/Editor/controllerAdapter.ts`:++```ts+import type { EditorController } from "../types/editorController";+import { toggleTextStyle } from "./shortcuts";+import type { EditorRefActions } from "./index";++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;+ 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(),+ 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);+ actions.setLine(lineNumber, line.startsWith(TASK_PREFIX) ? line.slice(TASK_PREFIX.length) : `${TASK_PREFIX}${line}`);+ },+ };+}+```++- [ ] **Step 6: Run the adapter test**++```bash+pnpm test -- editor-controller-adapter+```++Expected: PASS.++- [ ] **Step 7: Rewire EditorContent to expose EditorController**++Replace `web/src/components/MemoEditor/components/EditorContent.tsx` imports and component shell (the drag/paste/composition handlers stay exactly as they are):++```tsx+import { forwardRef, useImperativeHandle, useRef } from "react";+import Editor, { type EditorRefActions } from "../Editor";+import { createTextareaController } from "../Editor/controllerAdapter";+import { useBlobUrls, useDragAndDrop } from "../hooks";+import { useEditorContext } from "../state";+import type { EditorContentProps } from "../types";+import type { LocalFile } from "../types/attachment";+import type { EditorController } from "../types/editorController";++export const EditorContent = forwardRef<EditorController, EditorContentProps>(({ placeholder }, ref) => {+ const { state, actions, dispatch } = useEditorContext();+ const { createBlobUrl } = useBlobUrls();+ const textareaActionsRef = useRef<EditorRefActions>(null);++ useImperativeHandle(ref, () => createTextareaController(() => textareaActionsRef.current), []);++ // …existing dragHandlers / handleCompositionStart / handleCompositionEnd /+ // handleContentChange / handlePaste bodies unchanged…++ return (+ <div className="w-full flex flex-col flex-1" {...dragHandlers}>+ <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>+ );+});++EditorContent.displayName = "EditorContent";+```++- [ ] **Step 8: Switch the MemoEditor consumers to the controller**++In `web/src/components/MemoEditor/hooks/useKeyboard.ts`, replace the whole file:++```ts+import { useEffect, useRef } from "react";+import type { EditorController } from "../types/editorController";++export const useKeyboard = (editorRef: React.RefObject<EditorController | null>, onSave: () => void) => {+ const onSaveRef = useRef(onSave);+ onSaveRef.current = onSave;++ useEffect(() => {+ const handleKeyDown = (event: KeyboardEvent) => {+ if (!(event.metaKey || event.ctrlKey) || event.key !== "Enter") {+ return;+ }++ if (!editorRef.current?.hasFocus()) {+ return;+ }++ event.preventDefault();+ onSaveRef.current();+ };++ window.addEventListener("keydown", handleKeyDown);+ return () => window.removeEventListener("keydown", handleKeyDown);+ }, [editorRef]);+};+```++In `web/src/components/MemoEditor/hooks/useMemoInit.ts`, change only the type import/usage:++```ts+// remove: import type { EditorRefActions } from "../Editor";+import type { EditorController } from "../types/editorController";++interface UseMemoInitOptions {+ editorRef: React.RefObject<EditorController | null>;+ // …rest unchanged+}+```++In `web/src/components/MemoEditor/index.tsx`:++```ts+// remove: import type { EditorRefActions } from "./Editor";+import type { EditorController } from "./types/editorController";+// …+const editorRef = useRef<EditorController>(null);+```++and replace the `insertTranscribedText` callback body with:++```ts+const insertTranscribedText = useCallback((text: string) => {+ const editor = editorRef.current;+ if (!editor) {+ return;+ }+ editor.insertMarkdown(text);+ editor.scrollToCursor();+}, []);+```++- [ ] **Step 9: Run the full suite + lint**++```bash+pnpm lint && pnpm test+```++Expected: PASS — including the untouched `memo-editor-shortcuts` and `memo-editor-paste` tests (they render `Editor` directly and are unaffected).++- [ ] **Step 10: Commit**++```bash+git add web/src web/tests/editor-controller-adapter.test.tsx+git commit -m "refactor(web): introduce EditorController abstraction over the textarea editor"+```++---++### Task 6: TiptapEditor component++The WYSIWYG editor component: `useEditor` with the Task-2 extension list + `Placeholder`, markdown in/out on every update, file-paste delegation, composition events, and a `forwardRef` `EditorController`.++**Files:**+- Create: `web/src/components/MemoEditor/TiptapEditor/index.tsx`+- Modify: `web/src/index.css` (task-list + placeholder styles)+- Test: `web/tests/tiptap-editor-controller.test.tsx`++- [ ] **Step 1: Extend EditorController with `selectAll` (needed to test selection-based intents)**++Add to the `EditorController` interface in `web/src/components/MemoEditor/types/editorController.ts` (after `scrollToCursor`):++```ts+ /** Select the entire document (used by tests and select-all flows). */+ selectAll(): void;+```++and add the textarea implementation in `web/src/components/MemoEditor/Editor/controllerAdapter.ts` (after `scrollToCursor`):++```ts+ selectAll: () => {+ const actions = getActions();+ if (!actions) return;+ actions.setCursorPosition(0, actions.getContent().length);+ },+```++- [ ] **Step 2: Write the failing test**++`web/tests/tiptap-editor-controller.test.tsx`:++```tsx+import { act, 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";++function setup(initialContent = "") {+ const ref = createRef<EditorController>();+ const onContentChange = vi.fn();+ render(+ <TiptapEditor+ initialContent={initialContent}+ placeholder="memo"+ onContentChange={onContentChange}+ onPaste={vi.fn()}+ />,+ );+ return { ref, onContentChange };+}++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("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");+ });+});+```++- [ ] **Step 3: Run it to verify it fails**++```bash+pnpm test -- tiptap-editor-controller+```++Expected: FAIL — `@/components/MemoEditor/TiptapEditor` has no `index.tsx` default export yet.++- [ ] **Step 4: Implement the component**++`web/src/components/MemoEditor/TiptapEditor/index.tsx`:++```tsx+import { EditorContent as TiptapEditorContent, useEditor } from "@tiptap/react";+import { Placeholder } from "@tiptap/extensions";+import { forwardRef, useEffect, useImperativeHandle } from "react";+import { cn } from "@/lib/utils";+import { EDITOR_HEIGHT } from "../constants";+import type { EditorController } from "../types/editorController";+import { buildExtensions } from "./extensions";++export interface TiptapEditorProps {+ className?: string;+ initialContent: string;+ placeholder: string;+ isFocusMode?: boolean;+ onContentChange: (content: string) => void;+ onPaste: (event: React.ClipboardEvent) => void;+ onCompositionStart?: () => void;+ onCompositionEnd?: () => void;+}++/**+ * WYSIWYG memo editor on Tiptap/ProseMirror. Markdown is the only format+ * crossing its boundary: in via setContent(contentType: "markdown"), out via+ * getMarkdown() 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, onCompositionStart, onCompositionEnd } = props;++ const editor = useEditor({+ extensions: [...buildExtensions(), Placeholder.configure({ placeholder })],+ content: initialContent,+ contentType: "markdown",+ editorProps: {+ 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) {+ onPaste(event as unknown as React.ClipboardEvent);+ return true;+ }+ // Text paste (incl. URL-over-selection → link) is handled natively.+ return false;+ },+ handleDOMEvents: {+ compositionstart: () => {+ onCompositionStart?.();+ return false;+ },+ compositionend: () => {+ onCompositionEnd?.();+ return false;+ },+ },+ },+ onUpdate: ({ editor: currentEditor }) => {+ onContentChange(currentEditor.getMarkdown());+ },+ });++ // 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;+ }+ if (editor.getMarkdown() !== initialContent) {+ editor.commands.setContent(initialContent, { contentType: "markdown", emitUpdate: false });+ }+ }, [initialContent, editor]);++ useImperativeHandle(+ ref,+ (): EditorController => ({+ focus: () => editor?.commands.focus(),+ hasFocus: () => editor?.isFocused ?? false,+ isEmpty: () => editor?.isEmpty ?? true,+ getMarkdown: () => editor?.getMarkdown() ?? "",+ 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,+ )}+ >+ <TiptapEditorContent editor={editor} className="w-full" />+ </div>+ );+});++export default TiptapEditor;+```++- [ ] **Step 5: Add minimal global styles**++Append to `web/src/index.css`:++```css+/* 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;+}++.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;+}+```++(If `var(--border)` / `var(--muted)` are not defined in this project's Tailwind theme, check `web/src/index.css` for the actual CSS custom property names used by shadcn components — they exist because classes like `bg-muted`/`border-border` are used throughout — and substitute the real names.)++- [ ] **Step 6: Run the test until green**++```bash+pnpm test -- tiptap-editor-controller+```++Expected: PASS.++Troubleshooting:+- jsdom missing APIs when the ProseMirror view mounts (`getClientRects`, `elementFromPoint`): add to `web/tests/setup.ts`:++```ts+// 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;+ }+}+```++- `useEditor` returning `null` on first render in React 19 → wrap assertions in `await waitFor(...)` from @testing-library/react, or pass `immediatelyRender: true` to `useEditor` (Tiptap v3 option) — prefer `immediatelyRender: true` since this app is client-only.++- [ ] **Step 7: Verify the corpus is still green, lint, commit**++```bash+pnpm lint && pnpm test+git add web/src web/tests+git commit -m "feat(web): add tiptap wysiwyg editor component behind EditorController"+```++---++### Task 7: Dual-mode `EditorContent`, mode toggle UI, localStorage persistence++**Files:**+- Create: `web/src/components/MemoEditor/editorMode.ts`+- Modify: `web/src/components/MemoEditor/state/types.ts`+- Modify: `web/src/components/MemoEditor/state/actions.ts`+- Modify: `web/src/components/MemoEditor/state/reducer.ts`+- Modify: `web/src/components/MemoEditor/state/context.tsx`+- Modify: `web/src/components/MemoEditor/components/EditorContent.tsx`+- Modify: `web/src/components/MemoEditor/components/EditorToolbar.tsx`+- Modify: `web/src/locales/en.json`+- Test: `web/tests/editor-mode.test.ts`, `web/tests/editor-mode-toggle.test.tsx`++- [ ] **Step 1: Write the failing preference-helper test**++`web/tests/editor-mode.test.ts`:++```ts+import { beforeEach, describe, expect, it } from "vitest";+import { getPreferredEditorMode, setPreferredEditorMode } from "@/components/MemoEditor/editorMode";++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");+ });+});+```++- [ ] **Step 2: Run it to verify it fails, then implement the helper**++```bash+pnpm test -- editor-mode.test+```++Expected: FAIL (module missing). Then create `web/src/components/MemoEditor/editorMode.ts`:++```ts+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.+ }+}+```++Re-run: `pnpm test -- editor-mode.test` → PASS.++- [ ] **Step 3: Add editor mode to the reducer state**++In `web/src/components/MemoEditor/state/types.ts`:++1. Add the import at the top:++```ts+import { getPreferredEditorMode, type EditorMode } from "../editorMode";+```++2. In `EditorState["ui"]`, add a field after `isComposing: boolean;`:++```ts+ editorMode: EditorMode;+```++3. Add to the `EditorAction` union:++```ts+ | { type: "SET_EDITOR_MODE"; payload: EditorMode }+```++4. In `initialState.ui`, after `isComposing: false,` add:++```ts+ editorMode: "wysiwyg",+```++5. After the `initialState` declaration, add:++```ts+/**+ * 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 {+ ...initialState,+ ui: { ...initialState.ui, editorMode: getPreferredEditorMode() },+ };+}+```++In `web/src/components/MemoEditor/state/actions.ts`, add to `editorActions` (and add `import type { EditorMode } from "../editorMode";`):++```ts+ setEditorMode: (mode: EditorMode): EditorAction => ({+ type: "SET_EDITOR_MODE",+ payload: mode,+ }),+```++In `web/src/components/MemoEditor/state/reducer.ts`:++1. Change the import line `import { initialState } from "./types";` to `import { createInitialState } from "./types";`+2. Add a case before `RESET`:++```ts+ case "SET_EDITOR_MODE":+ return {+ ...state,+ ui: {+ ...state.ui,+ editorMode: action.payload,+ },+ };+```++3. Change the `RESET` case to re-read the persisted preference:++```ts+ case "RESET":+ return createInitialState();+```++In `web/src/components/MemoEditor/state/context.tsx`, change the import of `initialState` to `createInitialState` and the `useReducer` line to lazy-init:++```ts+import { createInitialState } from "./types";+// …+ const [state, dispatch] = useReducer(editorReducer, initialEditorState, (provided) => provided ?? createInitialState());+```++Check `web/src/components/MemoEditor/state/index.ts` re-exports and add `createInitialState` / `EditorMode` exports if it enumerates names explicitly.++- [ ] **Step 4: Write the failing dual-mode test**++`web/tests/editor-mode-toggle.test.tsx`:++```tsx+import { 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("@/components/MemoEditor/Editor/TagSuggestions", () => ({ default: () => null }));+vi.mock("@/components/MemoEditor/Editor/SlashCommands", () => ({ default: () => null }));++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>+ );+}++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");+ });+});+```++Run `pnpm test -- editor-mode-toggle` — expected FAIL (`EditorContent` always renders the textarea).++- [ ] **Step 5: Make EditorContent host both editors**++Replace `web/src/components/MemoEditor/components/EditorContent.tsx` with:++```tsx+import { forwardRef, useCallback, useImperativeHandle, useMemo, useRef } from "react";+import Editor, { type EditorRefActions } from "../Editor";+import { createTextareaController } from "../Editor/controllerAdapter";+import { useBlobUrls, useDragAndDrop } from "../hooks";+import { useEditorContext } from "../state";+import TiptapEditor from "../TiptapEditor";+import type { EditorContentProps } from "../types";+import type { LocalFile } from "../types/attachment";+import type { EditorController } from "../types/editorController";++/**+ * 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 { 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],+ );++ 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 localFiles: LocalFile[] = Array.from(files).map((file) => ({+ file,+ previewUrl: createBlobUrl(file),+ origin: "upload",+ }));+ localFiles.forEach((localFile) => dispatch(actions.addLocalFile(localFile)));+ });++ const handleCompositionStart = () => {+ dispatch(actions.setComposing(true));+ };++ const handleCompositionEnd = () => {+ dispatch(actions.setComposing(false));+ };++ const handleContentChange = (content: string) => {+ dispatch(actions.updateContent(content));+ };++ const handlePaste = (event: React.ClipboardEvent<Element>) => {+ const clipboard = event.clipboardData;+ if (!clipboard) return;++ const files: File[] = [];+ if (clipboard.items && clipboard.items.length > 0) {+ for (const item of Array.from(clipboard.items)) {+ if (item.kind !== "file") continue;+ const file = item.getAsFile();+ if (file) files.push(file);+ }+ } else if (clipboard.files && clipboard.files.length > 0) {+ files.push(...Array.from(clipboard.files));+ }++ if (files.length === 0) return;++ const localFiles: LocalFile[] = files.map((file) => ({+ file,+ previewUrl: createBlobUrl(file),+ origin: "upload",+ }));+ localFiles.forEach((localFile) => dispatch(actions.addLocalFile(localFile)));+ event.preventDefault();+ };++ return (+ <div className="w-full flex flex-col flex-1" {...dragHandlers}>+ {mode === "wysiwyg" ? (+ <TiptapEditor+ ref={tiptapControllerRef}+ className="memo-editor-content"+ initialContent={state.content}+ placeholder={placeholder || ""}+ isFocusMode={state.ui.isFocusMode}+ onContentChange={handleContentChange}+ onPaste={handlePaste}+ onCompositionStart={handleCompositionStart}+ onCompositionEnd={handleCompositionEnd}+ />+ ) : (+ <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>+ );+});++EditorContent.displayName = "EditorContent";+```++Run `pnpm test -- editor-mode-toggle` → PASS.++- [ ] **Step 6: Add the toggle button to the toolbar + i18n strings**++In `web/src/locales/en.json`, inside the `"editor"` object (alphabetical-ish placement next to its siblings), add:++```json+ "switch-to-raw": "Edit raw Markdown",+ "switch-to-wysiwyg": "Edit rich text",+```++In `web/src/components/MemoEditor/components/EditorToolbar.tsx`:++1. Add imports:++```tsx+import { CodeXmlIcon, TypeIcon } from "lucide-react";+import { setPreferredEditorMode } from "../editorMode";+```++2. Inside the component, add a handler after `handleToggleFocusMode`:++```tsx+ const handleToggleEditorMode = () => {+ const next = state.ui.editorMode === "wysiwyg" ? "raw" : "wysiwyg";+ dispatch(actions.setEditorMode(next));+ setPreferredEditorMode(next);+ };+```++3. In the left button group, right after `<InsertMenu …/>`, add:++```tsx+ <Button+ variant="ghost"+ size="icon"+ className="ml-1 shadow-none text-muted-foreground"+ onClick={handleToggleEditorMode}+ title={state.ui.editorMode === "wysiwyg" ? t("editor.switch-to-raw") : t("editor.switch-to-wysiwyg")}+ >+ {state.ui.editorMode === "wysiwyg" ? <CodeXmlIcon className="size-4" /> : <TypeIcon className="size-4" />}+ </Button>+```++- [ ] **Step 7: Add a toolbar toggle test**++Append to `web/tests/editor-mode-toggle.test.tsx` (extend the existing file; add the import `import { EditorToolbar } from "@/components/MemoEditor/components/EditorToolbar";`):++```tsx+describe("toolbar mode toggle button", () => {+ it("switches mode and persists the preference", async () => {+ localStorage.clear();+ render(+ <EditorProvider>+ <EditorContent placeholder="memo" />+ <EditorToolbar onSave={vi.fn()} onAudioRecorderClick={vi.fn()} />+ </EditorProvider>,+ );++ // i18n resources load through a lazy backend — await the translated title.+ fireEvent.click(await screen.findByTitle("Edit raw Markdown"));++ expect(screen.getByPlaceholderText("memo")).toBeInTheDocument();+ expect(localStorage.getItem("memos-editor-mode")).toBe("raw");+ expect(await screen.findByTitle("Edit rich text")).toBeInTheDocument();+ });+});+```++(If the translated title never resolves because the test environment leaves i18next uninitialized, `t()` returns the key — query `findByTitle("editor.switch-to-raw")` instead and leave a comment. Check how the suite behaves before reaching for an i18n test bootstrap.)++(If `EditorToolbar` pulls in providers that explode in jsdom — e.g. `VisibilitySelector`'s radix Select — mock the offending child: `vi.mock("@/components/MemoEditor/Toolbar/VisibilitySelector", () => ({ default: () => null }));` and same for `InsertMenu` if needed. Note `Toolbar/index.ts` may re-export; mock the exact module path the component imports.)++- [ ] **Step 8: Full suite + lint + commit**++```bash+pnpm lint && pnpm test+git add web/src web/tests+git commit -m "feat(web): dual-mode memo editor with wysiwyg/raw toggle persisted per device"+```++---++### Task 8: Tag suggestions popup in WYSIWYG mode++**Files:**+- Create: `web/src/components/MemoEditor/TiptapEditor/suggestionMenu.tsx`+- Create: `web/src/components/MemoEditor/TiptapEditor/TagSuggestion.ts`+- Modify: `web/src/components/MemoEditor/TiptapEditor/index.tsx`+- Test: `web/tests/suggestion-menu.test.tsx`++- [ ] **Step 1: Write the failing popup-component test**++`web/tests/suggestion-menu.test.tsx`:++```tsx+import { fireEvent, render, screen } from "@testing-library/react";+import { createRef } from "react";+import { describe, expect, it, vi } from "vitest";+import { SuggestionMenu, 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);+ });+});+```++Run `pnpm test -- suggestion-menu` — expected FAIL (module missing).++- [ ] **Step 2: Implement the shared menu + suggestion renderer factory**++`web/src/components/MemoEditor/TiptapEditor/suggestionMenu.tsx`:++```tsx+import { ReactRenderer } from "@tiptap/react";+import type { SuggestionKeyDownProps, SuggestionOptions, SuggestionProps } from "@tiptap/suggestion";+import { forwardRef, useEffect, useImperativeHandle, useState, type ReactNode } 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);++ useEffect(() => setSelectedIndex(0), [items]);++ useImperativeHandle(+ ref,+ () => ({+ onKeyDown: ({ event }) => {+ if (items.length === 0) {+ return false;+ }+ if (event.key === "ArrowDown") {+ setSelectedIndex((index) => (index + 1) % items.length);+ return true;+ }+ if (event.key === "ArrowUp") {+ setSelectedIndex((index) => (index - 1 + items.length) % items.length);+ return true;+ }+ if (event.key === "Enter" || event.key === "Tab") {+ command(items[selectedIndex]);+ return true;+ }+ return false;+ },+ }),+ [items, selectedIndex, command],+ );++ if (items.length === 0) {+ return null;+ }++ return (+ <div data-suggestion-menu className={MENU_STYLES.container}>+ {items.map((item, index) => (+ <div+ key={getItemKey(item)}+ 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> },+) => ReturnType<typeof SuggestionMenuInner>;++/**+ * 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;++ 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 = () => {+ renderer?.destroy();+ container?.remove();+ renderer = null;+ container = null;+ };++ const menuProps = (props: SuggestionProps<T>) => ({+ items: props.items,+ command: (item: T) => props.command(item),+ renderItem: menu.renderItem,+ getItemKey: menu.getItemKey,+ });++ return {+ onStart: (props) => {+ renderer = new ReactRenderer(SuggestionMenu, { 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);+ },+ 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,+ };+ };+}+```++Run `pnpm test -- suggestion-menu` → PASS.++- [ ] **Step 3: Implement the TagSuggestion extension**++`web/src/components/MemoEditor/TiptapEditor/TagSuggestion.ts`:++```ts+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 a Tag node + 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: "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),+ }),+ }),+ ];+ },+});+```++- [ ] **Step 4: Wire tags into the editor component**++In `web/src/components/MemoEditor/TiptapEditor/index.tsx`:++1. Add imports:++```tsx+import { useMemo, useRef } from "react";+import { matchPath } from "react-router-dom";+import { useTagCounts } from "@/hooks/useUserQueries";+import { Routes } from "@/router";+import { TagSuggestion } from "./TagSuggestion";+```++2. Inside the component before `useEditor`, mirror the textarea's tag sourcing (`Editor/TagSuggestions.tsx`):++```tsx+ // On the explore page suggestions include all users' tags; otherwise the+ // current user's. Same sourcing as the raw editor's TagSuggestions.+ const isExplorePage = 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;+```++3. Add to the `useEditor` extensions array:++```tsx+ TagSuggestion.configure({ getTags: () => tagsRef.current }),+```++- [ ] **Step 5: Fix tests that now need the query hook mocked**++`useTagCounts` is a react-query hook; any test rendering `TiptapEditor` without a `QueryClientProvider` will now throw. Add to the TOP of `web/tests/tiptap-editor-controller.test.tsx` AND `web/tests/editor-mode-toggle.test.tsx`:++```tsx+vi.mock("@/hooks/useUserQueries", async (importOriginal) => ({+ ...(await importOriginal<object>()),+ useTagCounts: () => ({ data: {} }),+}));+```++(If `importOriginal` drags in transitive modules that fail at import time, replace with a plain object mock exporting just `useTagCounts` and any names those tests touch.)++- [ ] **Step 6: Full suite + lint + commit**++```bash+pnpm lint && pnpm test+git add web/src web/tests+git commit -m "feat(web): tag suggestion popup for wysiwyg editor"+```++---++### Task 9: Slash commands in WYSIWYG mode++**Files:**+- Create: `web/src/components/MemoEditor/TiptapEditor/SlashCommand.ts`+- Modify: `web/src/components/MemoEditor/TiptapEditor/index.tsx`+- Test: `web/tests/tiptap-slash-commands.test.ts`++- [ ] **Step 1: Write the failing test**++`web/tests/tiptap-slash-commands.test.ts`:++```ts+import { Editor } from "@tiptap/core";+import { afterEach, describe, expect, it } from "vitest";+import { buildExtensions } from "@/components/MemoEditor/TiptapEditor/extensions";+import { 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 the document: range covers a typed "/".+ editor.commands.insertContent("/");+ const end = editor.state.doc.content.size;+ item.apply(editor, { from: end - 1, to: end });+ return editor.getMarkdown();+}++afterEach(() => editor?.destroy());++describe("WYSIWYG slash commands", () => {+ it("todo converts the block into a task list", () => {+ expect(applyCommand("todo")).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("table inserts a preserved markdown table", () => {+ const markdown = applyCommand("table");+ expect(markdown).toContain("| Header | Header |");+ expect(markdown).toContain("| ------ | ------ |");+ });+});+```++Run `pnpm test -- tiptap-slash-commands` — expected FAIL (module missing).++Note: if the `todo` expectation fails on exact whitespace (e.g. `"- [ ] "` vs `"- [ ]"`), assert with `expect(markdown.trimEnd()).toBe("- [ ]")` — the meaningful claim is the empty task item, not trailing-space geometry.++- [ ] **Step 2: Implement the SlashCommand extension**++`web/src/components/MemoEditor/TiptapEditor/SlashCommand.ts`:++```ts+import { Extension, type Editor, 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",+ apply: (editor, range) =>+ editor.chain().focus().deleteRange(range).insertContent("[text](url)", { contentType: "markdown" }).run(),+ },+ {+ name: "table",+ apply: (editor, range) =>+ editor+ .chain()+ .focus()+ .deleteRange(range)+ .insertContent("| Header | Header |\n| ------ | ------ |\n| Cell | Cell |", { contentType: "markdown" })+ .run(),+ },+];++/** `/` 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 }) => {+ const q = query.toLowerCase();+ return q ? slashCommandItems.filter((item) => item.name.startsWith(q)) : slashCommandItems;+ },+ 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,+ ),+ }),+ }),+ ];+ },+});+```++- [ ] **Step 3: Register in the editor component**++In `web/src/components/MemoEditor/TiptapEditor/index.tsx` add the import and append to the `useEditor` extensions array (after `TagSuggestion.configure(…)`):++```tsx+import { SlashCommand } from "./SlashCommand";+// …+ SlashCommand,+```++- [ ] **Step 4: Run tests + lint + commit**++```bash+pnpm lint && pnpm test+git add web/src web/tests/tiptap-slash-commands.test.ts+git commit -m "feat(web): slash command popup for wysiwyg editor"+```++---++### Task 10: Load guard (round-trip tripwire on opening existing memos)++When opening an **existing** memo in WYSIWYG mode, verify the round trip is lossless; if not, switch this editor session to raw mode (without persisting the preference) and tell the user. Expected never to fire — `PreservedBlock` should make every input lossless — but this is the safety net the fidelity contract demands.++**Files:**+- Modify: `web/src/components/MemoEditor/hooks/useMemoInit.ts`+- Modify: `web/src/locales/en.json`+- Test: `web/tests/editor-load-guard.test.tsx`++- [ ] **Step 1: Add the i18n string**++In `web/src/locales/en.json`, in the `"editor"` object next to the Task-7 keys:++```json+ "unsupported-syntax-raw-mode": "This memo contains syntax the rich-text editor can't safely edit, so it opened in raw Markdown mode.",+```++- [ ] **Step 2: Write the failing test**++`web/tests/editor-load-guard.test.tsx`:++```tsx+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", () => ({ toast: Object.assign(toastMock, { error: vi.fn(), success: vi.fn() }) }));++const isLosslessMock = vi.hoisted(() => vi.fn());+vi.mock("@/components/MemoEditor/TiptapEditor/markdownCodec", () => ({+ isLosslessRoundTrip: isLosslessMock,+}));++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();+ // 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");+ });+});+```++(Adjust the `Memo` construction to this repo's proto runtime: check how other tests build a `Memo` — e.g. grep `MemoSchema` in `web/tests/` — and mirror that. If none exists, `create(MemoSchema, { name, content })` with `@bufbuild/protobuf` is correct for protobuf-es v2.)++Run `pnpm test -- editor-load-guard` — expected FAIL (mode stays `wysiwyg`, no toast).++- [ ] **Step 3: Implement the guard in useMemoInit**++In `web/src/components/MemoEditor/hooks/useMemoInit.ts`:++1. Add imports:++```ts+import { toast } from "react-hot-toast";+import { useTranslate } from "@/utils/i18n";+import { getPreferredEditorMode } from "../editorMode";+import { isLosslessRoundTrip } from "../TiptapEditor/markdownCodec";+```++2. Add `const t = useTranslate();` next to the existing `useEditorContext()` call.++3. In the `if (memo)` branch, after `dispatch(actions.initMemo(initialState));`, add:++```ts+ // Load guard (tripwire): if the WYSIWYG round trip would change this+ // memo's meaning, edit it raw for this session. Preference untouched.+ 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"));+ }+```++4. Add `t` to the effect's dependency array.++- [ ] **Step 4: Run tests + lint + commit**++```bash+pnpm lint && pnpm test+git add web/src web/tests/editor-load-guard.test.tsx+git commit -m "feat(web): raw-mode load guard for memos the wysiwyg editor cannot round-trip"+```++---++### Task 11: Final verification, docs, release build++**Files:**+- Modify: `web/src/components/MemoEditor/README.md`++- [ ] **Step 1: Full verification**++```bash+cd /Users/steven/Projects/usememos/memos/web+pnpm lint && pnpm test && pnpm build+```++Expected: all PASS; the build completes. Note the reported gzip size of chunks containing tiptap — the budget from the spec is ~100 KB gzipped for the editor stack; if it lands wildly above (>150 KB), flag it in the final report (do not silently accept).++- [ ] **Step 2: Update the MemoEditor README**++Read `web/src/components/MemoEditor/README.md` and update it to describe the new architecture: the `EditorController` contract, the two implementations (`Editor/` textarea = raw mode, `TiptapEditor/` = WYSIWYG default), the mode toggle + localStorage key `memos-editor-mode`, the markdown codec + corpus tests as the fidelity gate, and the load guard. Keep its existing tone/format; do not document internals that the code already states.++- [ ] **Step 3: Manual QA checklist (requires a running dev server: `pnpm dev` against a local memos server)**++Walk through and record results — these are the spec's manual-QA items that jsdom cannot cover:++1. Type `**bold**`, `# heading`, `- ` list, `> quote`, ` ``` ` fence — each converts live as you type.+2. Type `#` — tag popup opens, filter works, Enter inserts a styled tag chip; saved memo renders the tag.+3. Type `/` — command popup opens; todo/code/link/table all insert.+4. Paste an image — it appears in the attachment strip (upload path), not as text.+5. Select text and paste a URL over it — it becomes a link.+6. Toggle to raw mode mid-edit — markdown matches what was typed; toggle back — nothing lost; reload — preference remembered.+7. Edit a memo containing a table + `$math$` — both visible as literal mono text; save without touching them; verify the stored content is byte-identical (compare in raw mode before/after).+8. CJK IME composition (macOS Japanese/Chinese input): no duplicated or dropped characters while composing.+9. Focus mode: editor grows to fill; typing/scrolling fine.+10. Mobile Safari/Chrome (or responsive emulation): soft keyboard works, popups usable.+11. Ctrl/Cmd+B/I in WYSIWYG; Ctrl/Cmd+Enter saves from inside the editor.+12. Draft persistence: type in a new memo, reload the page, content restored (in both modes).++- [ ] **Step 4: Final commit**++```bash+cd /Users/steven/Projects/usememos/memos+git add web/src/components/MemoEditor/README.md+git commit -m "docs(web): document dual-mode memo editor architecture"+```++Then use the **superpowers:finishing-a-development-branch** skill to decide merge/PR handling.++---++## Self-review notes (already applied)++- Spec coverage: raw-mode toggle (Task 7), fidelity contract + corpus-first spike (Tasks 2–3), v1 live set via StarterKit/TaskList/Tag (Tasks 2, 4), tables/math/inline-HTML literal (Task 3), suggestion popups (Tasks 8–9), file paste/drag (Task 6 + existing container drag), load guard (Task 10), draft/save path untouched (state.content unchanged throughout), manual QA list (Task 11). Out-of-scope items from the spec are not implemented anywhere.+- Known accepted deviations, each annotated inline: serialize-on-update instead of debounce (Task header note); `##x` tokenizer edge differs from remark-tag but serializes identically (Task 4); slash `link` command can't preselect the URL placeholder in WYSIWYG (raw mode retains that nicety).+- Type-consistency check: `EditorController` gains `selectAll()` in Task 6 — implementers executing tasks out of order should add it to the interface + textarea adapter as described there; all later facades (Task 7) already include it.diff --git a/docs/superpowers/specs/2026-06-11-markdown-wysiwyg-editor-design.md b/docs/superpowers/specs/2026-06-11-markdown-wysiwyg-editor-design.mdnew file mode 100644index 000000000..94302a472--- /dev/null+++ b/docs/superpowers/specs/2026-06-11-markdown-wysiwyg-editor-design.md@@ -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).diff --git a/web/package.json b/web/package.jsonindex da2da5720..b6d636485 100644--- a/web/package.json+++ b/web/package.json@@ -36,6 +36,14 @@"@tailwindcss/vite": "^4.2.4","@tanstack/react-query": "^5.100.9","@tanstack/react-query-devtools": "^5.100.9",+ "@tiptap/core": "3.26.0",+ "@tiptap/extension-list": "3.26.0",+ "@tiptap/extensions": "3.26.0",+ "@tiptap/markdown": "3.26.0",+ "@tiptap/pm": "3.26.0",+ "@tiptap/react": "3.26.0",+ "@tiptap/starter-kit": "3.26.0",+ "@tiptap/suggestion": "3.26.0","class-variance-authority": "^0.7.1","clsx": "^2.1.1","copy-to-clipboard": "^4.0.2",@@ -49,6 +57,7 @@"leaflet.markercluster": "^1.5.3","lodash-es": "^4.18.1","lucide-react": "^1.14.0",+ "marked": "^17.0.6","mdast-util-from-markdown": "^2.0.3","mdast-util-gfm": "^3.1.0","mermaid": "^11.14.0",diff --git a/web/pnpm-lock.yaml b/web/pnpm-lock.yamlindex 1dddc7441..40249744d 100644--- a/web/pnpm-lock.yaml+++ b/web/pnpm-lock.yaml@@ -65,6 +65,30 @@ importers:'@tanstack/react-query-devtools':specifier: ^5.100.9+ '@tiptap/core':+ specifier: 3.26.0+ version: 3.26.0(@tiptap/[email protected])+ '@tiptap/extension-list':+ specifier: 3.26.0+ '@tiptap/extensions':+ specifier: 3.26.0+ '@tiptap/markdown':+ specifier: 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/[email protected])(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])+ '@tiptap/starter-kit':+ specifier: 3.26.0+ version: 3.26.0+ '@tiptap/suggestion':+ specifier: 3.26.0class-variance-authority:specifier: ^0.7.1version: 0.7.1@@ -104,6 +128,9 @@ importers:lucide-react:specifier: ^1.14.0version: 1.14.0([email protected])+ marked:+ specifier: ^17.0.6+ version: 17.0.6mdast-util-from-markdown:specifier: ^2.0.3version: 2.0.3@@ -1328,6 +1355,167 @@ packages:'@types/react-dom':optional: true+ '@tiptap/[email protected]':+ resolution: {integrity: sha512-7jTed/RirIVsp+lLdLvGzGqF3EBGpnGHGYKOwz6t28V2BIJLAFdUhfEVdWie7xPxQNWK0TP+fPlsqZS0vxfHBg==}+ peerDependencies:+ '@tiptap/pm': 3.26.0++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-57accpka9affjiJRjP2LMNCDJDTMjTvO23RJCxtP43sp9cTIZ7YZnyDfRxCINTRBNK0X4o4w2+emOLyRwsk3CA==}+ peerDependencies:+ '@tiptap/core': 3.26.0++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-j6CzTMofcGJ5iMoUgDRQpM0FkG00jBID3aKqs+UBbgtzLgtG/CI/91tMFv0XPC30LeFA895qYgvGZtHdejZhiQ==}+ peerDependencies:+ '@tiptap/core': 3.26.0++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-H2E3Hp0lV79jQV8YGtdDJkXkUalXZeYzKCx+vCZlDpb2ChS7/rNT9YY7poRA1NlJLUO0DH1wbAnFhx9KZMUx5g==}+ peerDependencies:+ '@tiptap/core': 3.26.0+ '@tiptap/pm': 3.26.0++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-Jv7BX+kBB2wUIvO/NhuUjv+T3kAed2Tjr664fgQ2zKT6X69jKIkYuCCedrIHuOyaOQ+SBDuH9h51wYv/E97QgQ==}+ peerDependencies:+ '@tiptap/extension-list': 3.26.0++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-WPN9iZ3UjeDD2ckDzSs9tleibXv0cLj7j575NxuvjhwZTehYGNeYDSUTi+6DQUG6bKbhGg9Wcei5H0131vvJHg==}+ peerDependencies:+ '@tiptap/core': 3.26.0+ '@tiptap/pm': 3.26.0++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-VJYcV6rvjnENRTroOi9tDcHWW6G0pmCoRETwatlbgfDzuCmkTOwVwQjeJCXOVMMLNPzNiXZzibsRCUt+Azq/jw==}+ peerDependencies:+ '@tiptap/core': 3.26.0++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-Xhd6DCjaxCN4otQNvV6qra+XuoIjk6Vyjm87E5xn5Y/BMw7UGAG7LTkk3C2IEvxKrVZwJjalfxEqdHOgXQzVfw==}+ peerDependencies:+ '@tiptap/core': 3.26.0++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-rhAtp5J/YVDUCUIc5T7b0XY9dLeuI72JgOr53w0QQc0VA0uwbfTn7sx0LI9PDCE9uwmDH8H3snVRZRnAvlM8oA==}+ peerDependencies:+ '@tiptap/extensions': 3.26.0++ '@tiptap/[email protected]':+ 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/[email protected]':+ resolution: {integrity: sha512-SIe68SDwx2fozt/XKG0FhCwzz/yRN6Bvo4D5TqvfDg6NK3PQb1DS4GN9PilmJqbY+kXryuiWEEJOWi7HpO8SuQ==}+ peerDependencies:+ '@tiptap/extensions': 3.26.0++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-baXvv/rtOTVd2Axjb7Zbb41Y9Qmy3U2fP7EHqLuhViqGxVX8LwQtP0PHUXEZkPokbBpRez10+dmOlvvsYFKAZQ==}+ peerDependencies:+ '@tiptap/core': 3.26.0++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-qenEQEgzE5FjQay/H6iKOnwIt6DPO27cS+v0mGhXmrL1MjrNER4X0ZkATJbVd0WA6ffsAGaP44NKYDworGeidw==}+ peerDependencies:+ '@tiptap/core': 3.26.0++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-a+N/C4wkQV+/8x4ShdoiC2JdTW3Tw84C5cAloYLFMeaWmRa2me9ACSI+zo0SO9bbH9RJwsoRp7eaxBbk27eF1Q==}+ peerDependencies:+ '@tiptap/core': 3.26.0+ '@tiptap/pm': 3.26.0++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-s8oFpH+0xmhvY19f452/2dExO3p1tjxh761g6cg4irwEUNUEAJKF2VLcjiaeOhNJ+pmnQYxb+VSkwkXvO+7vHQ==}+ peerDependencies:+ '@tiptap/core': 3.26.0++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-FA/d157aBxyvZFvsdc5eSu46tmHWXebAsqOQSvivOMyw+deBb00VlMsf+iD2J8+sekjbMYwx/hvbsu+xUoX43Q==}+ peerDependencies:+ '@tiptap/core': 3.26.0+ '@tiptap/pm': 3.26.0++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-MccGyj9HY4fkl04eIiFoTCkr8067Jku/VVdJNtRWW104Spx43C/7V2zpbxPvpcDhq3dW384fDxYXfpnb186xLg==}+ peerDependencies:+ '@tiptap/extension-list': 3.26.0++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-oBcj6qaNrRHQ+N0+pDuOVAQa4Nx9r8Cm5ANvyM2lTpoy60sOLOizuVvcvw1andVxbSrsZ1N/Sk+RZWyv1uoWyQ==}+ peerDependencies:+ '@tiptap/extension-list': 3.26.0++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-EM8woyHDNKLEQ+lWUEoDtA4KrwP6fei/mYX1NxseMzKHHo7LFecx7wk6sovAXZrUvdML/yFBihgiMiO5VIsfkg==}+ peerDependencies:+ '@tiptap/core': 3.26.0+ '@tiptap/pm': 3.26.0++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-ItLdFlcMsJz2vhbs1PcUfcN7nzVqGBOwPeCrrWxjrgscp+K3JoOGD+HhVVpBACOMwivUrlh8Ry5Ohvues2nOeA==}+ peerDependencies:+ '@tiptap/extension-list': 3.26.0++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-h8fYLikg4qN39IghQ1y9g+zzUsgxBpDi5YS3IZbWoxWYYx1YqLL8nAvOiPr7Us14aQ0TjA2/xY7zqmyf29rX1A==}+ peerDependencies:+ '@tiptap/core': 3.26.0++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-jUll3Pqhq7u1JKvO0B6USW/bmVmUsO6sRcxo/d5tXqLhS0tWAobOGoGU2IgwXnQDSjf+vF73RYD5tRGDLkRC9Q==}+ peerDependencies:+ '@tiptap/core': 3.26.0++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-yZXdevp3/8omGbb40Z52VfvID+tsRNhPQ1GNUToD56XSr2BjdJyAzAb9rWGgDKgVMUPLgJ26yT0O278RFqOKhA==}+ peerDependencies:+ '@tiptap/core': 3.26.0++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-LlVkivH5cBwov/EMD8BL7ZRcU6YcadiSVIffLW1hyalw9YfhaFzoLxjtWhL7jiU/n2Kg+9dXSZxmV2hTeTwyrQ==}+ peerDependencies:+ '@tiptap/core': 3.26.0++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-4wajuqnO2X0+LVvsBjW/xk3/tmdb16bNL939QhicAay4YYqXITeV2v3XJsryzmG4L5GkK1yLxvRGk4aLoxWrnA==}+ peerDependencies:+ '@tiptap/core': 3.26.0+ '@tiptap/pm': 3.26.0++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-jg5xrwl1gTXUl5JA3+g8YYfhOzplM9CVecwKZeFtlYtPLyxLCmIDvqV/vULoGu57HwtY4819nNpMZwY6jBNtrw==}+ peerDependencies:+ '@tiptap/core': 3.26.0+ '@tiptap/pm': 3.26.0++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-q4RDeWwVrhOL0jJCGRgGxLSdjOYwzQ4h2InURZVhC66433ipcHd6f3bqSOhcXZ4r0sFmMNsuF7aZmUntjWLc7w==}++ '@tiptap/[email protected]':+ 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/[email protected]':+ resolution: {integrity: sha512-o34EtMfqtBaljdmeElZsRG/067oGx9Zcq+j2GWo71KlZe22ga/ALexeTf1c+ETsjCxSTKR6eyQ4RZvz/2JpYfg==}++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-3jxBvjmfooQroR0eCw61kSgr+g90KFVD3dM5bANhpQbCpCYRydp/iXDQmpoPHjv8FpeU5JZgcnJ3R9vhjeIM2A==}+ peerDependencies:+ '@tiptap/core': 3.26.0+ '@tiptap/pm': 3.26.0+'@tybys/[email protected]':resolution: {integrity: sha512-RoBvJ2X0wuKlWFIjrwffGw1IqZHKQqzIchKaadZZfnNpsAYp2mM0h36JtPCjNDAHGgYez/15uMBpfGwchhiMgg==}@@ -1507,6 +1695,9 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==}+ '@types/[email protected]':+ resolution: {integrity: sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg==}+'@ungap/[email protected]':resolution: {integrity: sha512-WmoN8qaIAo7WTYWbAZuG8PYEhn5fkz7dZrqTBZ7dtt//lL2Gwms1IcnQ5yHqjDfX8Ft5j4YzDM23f87zBfDe9g==}@@ -1978,6 +2169,10 @@ packages:resolution: {integrity: sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==}+ resolution: {integrity: sha512-jt2DW/aNFNwke7AUd+Z+e6pz39KO5rzdbbFCg2sGafS4mk13MI7Z8O5z9cADNn5lhGODIgLwug6TZO2ctf7kcw==}+ engines: {node: '>=6.0.0'}+resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==}engines: {node: '>=12.0.0'}@@ -2274,6 +2469,9 @@ packages:resolution: {integrity: sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==}+ resolution: {integrity: sha512-P8aEP5U/D1/IlTY2OeYsErdwh9bGuLE30NcXtKEjgdHcahveQoQwM2yZNsioQHsWFz0P7KKudisbrzCgR0sDHg==}+resolution: {integrity: sha512-J8xewKD/Gk22OZbhpOVSwcs60zhd95ESDwezOFuA3/099925PdHJ7OFHNTGtajL3AlZkykD32HykiMo+BIBI8A==}@@ -2313,6 +2511,11 @@ packages:engines: {node: '>= 20'}hasBin: true+ resolution: {integrity: sha512-gB0gkNafnonOw0obSTEGZTT86IuhILt2Wfx0mWH/1Au83kybTayroZ/V6nS25mN7u8ASy+5fMhgB3XPNrOZdmA==}+ engines: {node: '>= 20'}+ hasBin: true+resolution: {integrity: sha512-Tmd1Vg/m3Xz43afeNxDIhWRtFZgM2VLyaf4vSTYwudTyeuTneoL3qtWMA5jeLyz/O1vDJmmV4QuScFCA2tBPwg==}@@ -2483,6 +2686,9 @@ packages:resolution: {integrity: sha512-uTqF9MuPraAQ+IsnPf366RG4cP9RtUi7MLO1N3KEc+wb0a6yKpeL0lmk2IB1jY5KHPAlTc6T/JRdC/YqxHNwkQ==}+ resolution: {integrity: sha512-TvAWxi0nDe1j/rtMcWcIj94+Ffe6n7zhow33h40SKxmsmozs6dz/e+EajymfoFcHd7sxNn8yHM8839uixMOV6g==}+resolution: {integrity: sha512-61A5ThoTiDG/C8s8UMZwSorAGwMJ0ERVGj2OjoW5pAalsNOg15+iQiPzrLJ4jhZ1HJzmC2PIHT2oEiH3R5fzNA==}@@ -2543,6 +2749,45 @@ packages:resolution: {integrity: sha512-TwEZ+X+yCJmYfL7TPUOcvBZ4QfoT5YenQiJuX//0th53DE6w0xxLEtfK3iyryQFddXuvkIk51EEgrJQ0WJkOmQ==}+ resolution: {integrity: sha512-96WBLhOaYhJ+kPhLg3uW359Tz6I/MfcrQfL4EGv4SrcqKEMC1gmoGrXHecPE8eOwTVCJ4IwgfzM8fFad25wNfw==}++ resolution: {integrity: sha512-rT7qZnQtx5c0/y/KlYaGvtG411S97UaL6gdp6RIZ23DLHanMYLyfGBV5DtSnZdthQql7W+lEVbpSfwtO8T+L2w==}++ resolution: {integrity: sha512-CCk6Gyx9+Tt2sbYk5NK0nB1ukHi2ryaRgadV/LvyNuO3ena1payM2z6Cg0vO1ebK8cxbzo41ku2DE5Axj1Zuiw==}++ resolution: {integrity: sha512-pMdYaEnjNMSwl11yjEGtgTmLkR08m/Vl+Jj443167p9eB3HVQKhYCc4gmHVDsLPODfZfjr/MmirsdyZziXbQKw==}++ resolution: {integrity: sha512-zlzTiH01eKA55UAf1MEjtssJeHnGxO0j4K4Dpx+gnmX9n+SHNlDqI2oO1Kv1iPN5B1dm5fsljCfqKF9nFL6HRg==}++ resolution: {integrity: sha512-7wj4uMjKaXWAQ1CDgxNzNtR9AlsuwzHfdFH1ygEHA2KHF2DOEaXl1CJfNPAKCg9qNEh4rum975QLaCiQPyY6Fw==}++ resolution: {integrity: sha512-4HucRlpiLd1IPQQXNqeo81BGtkY8Ai5smHhKW9jjPKRc2wQIxksg7Hl1tTI2IfT2B/LgX6bfYvXxEpJl7aKYKw==}++ resolution: {integrity: sha512-BswA4BLSFEiORV6Vjj/yZBXDbos1zTEnhyeSSgT8psGFhstQS7UJ8/WOLiDos9Byaee27+tml0/DuMNxYR84zg==}++ resolution: {integrity: sha512-927lFx/uwyQaGwJxLWCZRkjXG0p48KpMj6ueoYiu4JX05GGuGcgzAy62dfiV8eFZftgyBUvLx76RsMe20fJl+Q==}++ resolution: {integrity: sha512-6jiYHH2CIGbCfnxdHbXZ12gySFY/fz/ulZE333G6bPqIZ4F+TXo9ifiR86nAHpWnfoNjOb3o5ESi7J8Uz1jXHw==}++ resolution: {integrity: sha512-V/0cDCsHKHe/tfWkeCmthNUcEp1IVO3p6vwN8XtwE9PZQLAZJigbw3QoraAdfJPir4NKJtNvOB8oYGKRl+t0Dw==}++ resolution: {integrity: sha512-GxboyN4AMIsoHNtz5uf2r2Ru551i5hWeCMD6E2Ib4Eogqoub0NflniaBPVQ4MrGE5yZ8JV9tUHg9qcZTTrcN4w==}++ resolution: {integrity: sha512-clTunTX+eaLbr87L1V1QPheRlEQJyTlL3gXe9x3jQIk3rL0RVWxviDGz8tFaydwIVm+hKhYCyr+R/zBtWr9s6A==}+resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==}engines: {node: '>=6'}@@ -2706,6 +2951,9 @@ packages:engines: {node: ^20.19.0 || >=22.12.0}hasBin: true+ resolution: {integrity: sha512-UT5EDe2cu2E/6O4igUr5PSFs23nvvukicWHx6GnOPlHAiiYbzNuCRQCuiUdHJQcqKalLKlrYJnjY0ySGsXNQXQ==}+resolution: {integrity: sha512-ZUz/69+SYpFN/g/lUlo2FXcIjRkSu3nDarreVdGGndHEBJ6cXPdKguS8JGxwj5HA5xIbVKSmLgr5b3AWxtRfvQ==}@@ -3041,6 +3289,9 @@ packages:resolution: {integrity: sha512-/BpdSx+yCQGnCvecbyXdxHDkuk55/G3xwnC0GqY4gmQ3j+A+g8kzzgB4Nk/SINjqn6+waqw3EgbVF2QKExkRxQ==}+ resolution: {integrity: sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==}+resolution: {integrity: sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==}engines: {node: '>=18'}@@ -4112,6 +4363,189 @@ snapshots:'@types/react': 19.2.14'@types/react-dom': 19.2.3(@types/[email protected])+ '@tiptap/[email protected](@tiptap/[email protected])':+ dependencies:+ '@tiptap/pm': 3.26.0++ dependencies:+ '@tiptap/core': 3.26.0(@tiptap/[email protected])++ dependencies:+ '@tiptap/core': 3.26.0(@tiptap/[email protected])++ '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])':+ dependencies:+ '@floating-ui/dom': 1.7.6+ '@tiptap/core': 3.26.0(@tiptap/[email protected])+ '@tiptap/pm': 3.26.0+ optional: true++ '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))':+ dependencies:+ '@tiptap/extension-list': 3.26.0(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])++ '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])':+ dependencies:+ '@tiptap/core': 3.26.0(@tiptap/[email protected])+ '@tiptap/pm': 3.26.0++ dependencies:+ '@tiptap/core': 3.26.0(@tiptap/[email protected])++ dependencies:+ '@tiptap/core': 3.26.0(@tiptap/[email protected])++ '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))':+ dependencies:+ '@tiptap/extensions': 3.26.0(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])++ '@tiptap/[email protected](@floating-ui/[email protected])(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])':+ dependencies:+ '@floating-ui/dom': 1.7.6+ '@tiptap/core': 3.26.0(@tiptap/[email protected])+ '@tiptap/pm': 3.26.0+ optional: true++ '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))':+ dependencies:+ '@tiptap/extensions': 3.26.0(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])++ dependencies:+ '@tiptap/core': 3.26.0(@tiptap/[email protected])++ dependencies:+ '@tiptap/core': 3.26.0(@tiptap/[email protected])++ '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])':+ dependencies:+ '@tiptap/core': 3.26.0(@tiptap/[email protected])+ '@tiptap/pm': 3.26.0++ dependencies:+ '@tiptap/core': 3.26.0(@tiptap/[email protected])++ '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])':+ dependencies:+ '@tiptap/core': 3.26.0(@tiptap/[email protected])+ '@tiptap/pm': 3.26.0+ linkifyjs: 4.3.3++ '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))':+ dependencies:+ '@tiptap/extension-list': 3.26.0(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])++ '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))':+ dependencies:+ '@tiptap/extension-list': 3.26.0(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])++ '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])':+ dependencies:+ '@tiptap/core': 3.26.0(@tiptap/[email protected])+ '@tiptap/pm': 3.26.0++ '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))':+ dependencies:+ '@tiptap/extension-list': 3.26.0(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])++ dependencies:+ '@tiptap/core': 3.26.0(@tiptap/[email protected])++ dependencies:+ '@tiptap/core': 3.26.0(@tiptap/[email protected])++ dependencies:+ '@tiptap/core': 3.26.0(@tiptap/[email protected])++ dependencies:+ '@tiptap/core': 3.26.0(@tiptap/[email protected])++ '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])':+ dependencies:+ '@tiptap/core': 3.26.0(@tiptap/[email protected])+ '@tiptap/pm': 3.26.0++ '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])':+ dependencies:+ '@tiptap/core': 3.26.0(@tiptap/[email protected])+ '@tiptap/pm': 3.26.0+ marked: 17.0.6++ '@tiptap/[email protected]':+ 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/[email protected](@floating-ui/[email protected])(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':+ dependencies:+ '@tiptap/core': 3.26.0(@tiptap/[email protected])+ '@tiptap/pm': 3.26.0+ '@types/react': 19.2.14+ '@types/react-dom': 19.2.3(@types/[email protected])+ '@types/use-sync-external-store': 0.0.6+ fast-equals: 5.4.0+ react: 19.2.6+ react-dom: 19.2.6([email protected])+ use-sync-external-store: 1.6.0([email protected])+ optionalDependencies:+ '@tiptap/extension-bubble-menu': 3.26.0(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])+ '@tiptap/extension-floating-menu': 3.26.0(@floating-ui/[email protected])(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])+ transitivePeerDependencies:+ - '@floating-ui/dom'++ '@tiptap/[email protected]':+ dependencies:+ '@tiptap/core': 3.26.0(@tiptap/[email protected])+ '@tiptap/extension-blockquote': 3.26.0(@tiptap/[email protected](@tiptap/[email protected]))+ '@tiptap/extension-bold': 3.26.0(@tiptap/[email protected](@tiptap/[email protected]))+ '@tiptap/extension-bullet-list': 3.26.0(@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))+ '@tiptap/extension-code': 3.26.0(@tiptap/[email protected](@tiptap/[email protected]))+ '@tiptap/extension-code-block': 3.26.0(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])+ '@tiptap/extension-document': 3.26.0(@tiptap/[email protected](@tiptap/[email protected]))+ '@tiptap/extension-dropcursor': 3.26.0(@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))+ '@tiptap/extension-gapcursor': 3.26.0(@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))+ '@tiptap/extension-hard-break': 3.26.0(@tiptap/[email protected](@tiptap/[email protected]))+ '@tiptap/extension-heading': 3.26.0(@tiptap/[email protected](@tiptap/[email protected]))+ '@tiptap/extension-horizontal-rule': 3.26.0(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])+ '@tiptap/extension-italic': 3.26.0(@tiptap/[email protected](@tiptap/[email protected]))+ '@tiptap/extension-link': 3.26.0(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])+ '@tiptap/extension-list': 3.26.0(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])+ '@tiptap/extension-list-item': 3.26.0(@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))+ '@tiptap/extension-list-keymap': 3.26.0(@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))+ '@tiptap/extension-ordered-list': 3.26.0(@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))+ '@tiptap/extension-paragraph': 3.26.0(@tiptap/[email protected](@tiptap/[email protected]))+ '@tiptap/extension-strike': 3.26.0(@tiptap/[email protected](@tiptap/[email protected]))+ '@tiptap/extension-text': 3.26.0(@tiptap/[email protected](@tiptap/[email protected]))+ '@tiptap/extension-underline': 3.26.0(@tiptap/[email protected](@tiptap/[email protected]))+ '@tiptap/extensions': 3.26.0(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])+ '@tiptap/pm': 3.26.0++ '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])':+ dependencies:+ '@tiptap/core': 3.26.0(@tiptap/[email protected])+ '@tiptap/pm': 3.26.0+'@tybys/[email protected]':dependencies:tslib: 2.8.1@@ -4323,6 +4757,8 @@ snapshots:'@types/[email protected]': {}+ '@types/[email protected]': {}+'@ungap/[email protected]': {}'@upsetjs/[email protected]':@@ -4793,6 +5229,8 @@ snapshots:+ [email protected]: {}+optionalDependencies:picomatch: 4.0.4@@ -5110,6 +5548,8 @@ snapshots:+ [email protected]: {}+@@ -5138,6 +5578,8 @@ snapshots:+ [email protected]: {}+dependencies:'@types/mdast': 4.0.4@@ -5554,6 +5996,8 @@ snapshots:+ [email protected]: {}+@@ -5624,6 +6068,80 @@ snapshots:+ dependencies:+ prosemirror-transform: 1.12.0++ dependencies:+ prosemirror-model: 1.25.8+ prosemirror-state: 1.4.4+ prosemirror-transform: 1.12.0++ dependencies:+ prosemirror-state: 1.4.4+ prosemirror-transform: 1.12.0+ prosemirror-view: 1.41.9++ dependencies:+ prosemirror-keymap: 1.2.3+ prosemirror-model: 1.25.8+ prosemirror-state: 1.4.4+ prosemirror-view: 1.41.9++ dependencies:+ prosemirror-state: 1.4.4+ prosemirror-transform: 1.12.0+ prosemirror-view: 1.41.9+ rope-sequence: 1.3.4++ dependencies:+ prosemirror-state: 1.4.4+ prosemirror-transform: 1.12.0++ dependencies:+ prosemirror-state: 1.4.4+ w3c-keyname: 2.2.8++ dependencies:+ orderedmap: 2.1.1++ dependencies:+ prosemirror-model: 1.25.8+ prosemirror-state: 1.4.4+ prosemirror-transform: 1.12.0++ dependencies:+ prosemirror-model: 1.25.8+ prosemirror-transform: 1.12.0+ prosemirror-view: 1.41.9++ 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++ dependencies:+ prosemirror-model: 1.25.8++ dependencies:+ prosemirror-model: 1.25.8+ prosemirror-state: 1.4.4+ prosemirror-transform: 1.12.0+@@ -5839,6 +6357,8 @@ snapshots:'@rolldown/binding-win32-arm64-msvc': 1.0.0-rc.18'@rolldown/binding-win32-x64-msvc': 1.0.0-rc.18+ [email protected]: {}+dependencies:hachure-fill: 0.5.2@@ -6109,6 +6629,8 @@ snapshots:+ [email protected]: {}+dependencies:xml-name-validator: 5.0.0diff --git a/web/src/components/MemoEditor/Editor/controllerAdapter.ts b/web/src/components/MemoEditor/Editor/controllerAdapter.tsnew file mode 100644index 000000000..f9dfa0b57--- /dev/null+++ b/web/src/components/MemoEditor/Editor/controllerAdapter.ts@@ -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)}`);+ }+ },+ };+}diff --git a/web/src/components/MemoEditor/Editor/shortcuts.ts b/web/src/components/MemoEditor/Editor/shortcuts.tsindex 5ce3e18f1..7c77f746f 100644--- a/web/src/components/MemoEditor/Editor/shortcuts.ts+++ b/web/src/components/MemoEditor/Editor/shortcuts.ts@@ -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 selectedContent = editor.getSelectedContent();const isStyled = isTextStyled(selectedContent, delimiter);diff --git a/web/src/components/MemoEditor/README.md b/web/src/components/MemoEditor/README.mdindex 46bf71608..908efe772 100644--- a/web/src/components/MemoEditor/README.md+++ b/web/src/components/MemoEditor/README.md@@ -2,7 +2,7 @@## Overview-MemoEditor uses a three-layer architecture for better separation of concerns and testability.+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@@ -11,10 +11,12 @@ MemoEditor uses a three-layer architecture for better separation of concerns and│ Presentation Layer (Components) ││ - EditorToolbar, EditorContent, etc. │└─────────────────┬───────────────────────┘- │+ │ EditorController┌─────────────────▼───────────────────────┐│ State Layer (Reducer + Context) ││ - 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/├── state/ # State management (reducer, actions, context)-├── services/ # Business logic (pure functions)-├── components/ # UI components-├── hooks/ # React hooks (utilities)-├── Editor/ # Core editor component-├── Toolbar/ # Toolbar components+├── services/ # Business logic (pure functions)+├── components/ # UI components+│ ├── EditorContent.tsx # Hosts the active editor; exposes mode-routing controller+│ ├── EditorToolbar.tsx # Toolbar including the mode toggle button+│ └── ...+├── 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└── types/+ ├── editorController.ts # EditorController interface (the cross-mode contract)+ └── ...```## Key Concepts@@ -43,6 +66,42 @@ MemoEditor/Uses `useReducer` + Context for predictable state transitions. All state changes go through action creators.+`state.content` holds the document as a **markdown string** and is the single source of truth for both editor modes. Each editor serializes its current content into the reducer on every change via `onContentChange`; neither editor reads content back from the other.++### 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.+### ServicesPure 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 tesThin presentation components that dispatch actions and render UI.+## Markdown fidelity contract++The round-trip corpus tests in `web/tests/markdown-roundtrip.test.ts`, backed by fixtures under `web/tests/fixtures/markdown-corpus/`, enforce two guarantees:++- **Supported syntax** (`supported/`): a parse → serialize → parse cycle produces an identical document tree (semantic equality; marker style may normalize).+- **Preserved syntax** (`preserved/`): tables, math, and raw HTML round-trip byte-for-byte.+## Usage```typescript@@ -65,7 +131,7 @@ import MemoEditor from "@/components/MemoEditor";## Testing-Services are pure functions - easy to unit test without React.+Services are pure functions — easy to unit test without React.```typescriptconst state = mockEditorState();diff --git a/web/src/components/MemoEditor/TiptapEditor/PreservedBlock.ts b/web/src/components/MemoEditor/TiptapEditor/PreservedBlock.tsnew file mode 100644index 000000000..c177b9d79--- /dev/null+++ b/web/src/components/MemoEditor/TiptapEditor/PreservedBlock.ts@@ -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 <[email protected]>+ // (`:`/`@` 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,+];diff --git a/web/src/components/MemoEditor/TiptapEditor/SlashCommand.ts b/web/src/components/MemoEditor/TiptapEditor/SlashCommand.tsnew file mode 100644index 000000000..a1a0bd56f--- /dev/null+++ b/web/src/components/MemoEditor/TiptapEditor/SlashCommand.ts@@ -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,+ ),+ }),+ }),+ ];+ },+});diff --git a/web/src/components/MemoEditor/TiptapEditor/Tag.ts b/web/src/components/MemoEditor/TiptapEditor/Tag.tsnew file mode 100644index 000000000..9281c4e95--- /dev/null+++ b/web/src/components/MemoEditor/TiptapEditor/Tag.ts@@ -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) : ""),+});diff --git a/web/src/components/MemoEditor/TiptapEditor/TagSuggestion.ts b/web/src/components/MemoEditor/TiptapEditor/TagSuggestion.tsnew file mode 100644index 000000000..8143991f6--- /dev/null+++ b/web/src/components/MemoEditor/TiptapEditor/TagSuggestion.ts@@ -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),+ }),+ }),+ ];+ },+});diff --git a/web/src/components/MemoEditor/TiptapEditor/extensions.ts b/web/src/components/MemoEditor/TiptapEditor/extensions.tsnew file mode 100644index 000000000..bfa203b4a--- /dev/null+++ b/web/src/components/MemoEditor/TiptapEditor/extensions.ts@@ -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,+ ];+}diff --git a/web/src/components/MemoEditor/TiptapEditor/index.tsx b/web/src/components/MemoEditor/TiptapEditor/index.tsxnew file mode 100644index 000000000..8dbc618a3--- /dev/null+++ b/web/src/components/MemoEditor/TiptapEditor/index.tsx@@ -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;diff --git a/web/src/components/MemoEditor/TiptapEditor/markdownCodec.ts b/web/src/components/MemoEditor/TiptapEditor/markdownCodec.tsnew file mode 100644index 000000000..27086f6df--- /dev/null+++ b/web/src/components/MemoEditor/TiptapEditor/markdownCodec.ts@@ -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;+ }+}diff --git a/web/src/components/MemoEditor/TiptapEditor/suggestionMenu.tsx b/web/src/components/MemoEditor/TiptapEditor/suggestionMenu.tsxnew file mode 100644index 000000000..10240bfd6--- /dev/null+++ b/web/src/components/MemoEditor/TiptapEditor/suggestionMenu.tsx@@ -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,+ };+ };+}diff --git a/web/src/components/MemoEditor/Toolbar/InsertMenu.tsx b/web/src/components/MemoEditor/Toolbar/InsertMenu.tsxindex 67d06e1cf..3d333e1c7 100644--- a/web/src/components/MemoEditor/Toolbar/InsertMenu.tsx+++ b/web/src/components/MemoEditor/Toolbar/InsertMenu.tsx@@ -1,5 +1,6 @@import { uniqBy } from "lodash-es";import {+ CodeXmlIcon,FileIcon,ImageIcon,LinkIcon,@@ -10,6 +11,7 @@ import {MicIcon,MoreHorizontalIcon,PlusIcon,+ TypeIcon,} from "lucide-react";import { useCallback, useEffect, useMemo, useState } from "react";import { LinkMemoDialog, LocationDialog } from "@/components/MemoMetadata";@@ -30,6 +32,7 @@ import {import { useDebouncedEffect } from "@/hooks";import type { MemoRelation } from "@/types/proto/api/v1/memo_service_pb";import { useTranslate } from "@/utils/i18n";+import { setPreferredEditorMode } from "../editorMode";import { useFileUpload, useLinkMemo, useLocation } from "../hooks";import { useEditorContext } from "../state";import type { InsertMenuProps } from "../types";@@ -132,6 +135,12 @@ const InsertMenu = (props: InsertMenuProps) => {setMoreSubmenuOpen(false);}, [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(() => {handleUploadClick("image/*,video/*");}, [handleUploadClick]);@@ -200,6 +209,11 @@ const InsertMenu = (props: InsertMenuProps) => {</DropdownMenuItem>))}<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 */}<DropdownMenuSub open={moreSubmenuOpen} onOpenChange={setMoreSubmenuOpen}><DropdownMenuSubTrigger onPointerEnter={handleTriggerEnter} onPointerLeave={handleTriggerLeave}>diff --git a/web/src/components/MemoEditor/components/EditorContent.tsx b/web/src/components/MemoEditor/components/EditorContent.tsxindex dab0f32d7..abd1417a9 100644--- a/web/src/components/MemoEditor/components/EditorContent.tsx+++ b/web/src/components/MemoEditor/components/EditorContent.tsx@@ -1,13 +1,63 @@-import { forwardRef } from "react";+import { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef } from "react";import Editor, { type EditorRefActions } from "../Editor";+import { createTextareaController } from "../Editor/controllerAdapter";import { useBlobUrls, useDragAndDrop } from "../hooks";import { useEditorContext } from "../state";+import TiptapEditor from "../TiptapEditor";import type { EditorContentProps } from "../types";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 { 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 localFiles: LocalFile[] = Array.from(files).map((file) => ({@@ -58,18 +108,33 @@ export const EditorContent = forwardRef<EditorRefActions, EditorContentProps>(({return (<div className="w-full flex flex-col flex-1" {...dragHandlers}>- <Editor- ref={ref}- 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}- />+ {mode === "wysiwyg" ? (+ // No composition wiring: ProseMirror handles IME natively, and+ // state.ui.isComposing is only read by the raw editor below — feeding+ // it from here could only strand the flag across a mode switch.+ <TiptapEditor+ ref={tiptapControllerRef}+ className="memo-editor-content"+ initialContent={state.content}+ placeholder={placeholder || ""}+ isFocusMode={state.ui.isFocusMode}+ 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>);});diff --git a/web/src/components/MemoEditor/editorMode.ts b/web/src/components/MemoEditor/editorMode.tsnew file mode 100644index 000000000..6359253a5--- /dev/null+++ b/web/src/components/MemoEditor/editorMode.ts@@ -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.+ }+}diff --git a/web/src/components/MemoEditor/hooks/useKeyboard.ts b/web/src/components/MemoEditor/hooks/useKeyboard.tsindex b09307e4d..291201be8 100644--- a/web/src/components/MemoEditor/hooks/useKeyboard.ts+++ b/web/src/components/MemoEditor/hooks/useKeyboard.ts@@ -1,7 +1,7 @@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);onSaveRef.current = onSave;@@ -11,14 +11,7 @@ export const useKeyboard = (editorRef: React.RefObject<EditorRefActions | null>,return;}- const editor = editorRef.current?.getEditor();- if (!editor) {- return;- }-- const activeElement = document.activeElement;- const target = event.target;- if (activeElement !== editor && target !== editor) {+ if (!editorRef.current?.hasFocus()) {return;}diff --git a/web/src/components/MemoEditor/hooks/useMemoInit.ts b/web/src/components/MemoEditor/hooks/useMemoInit.tsindex 8933c547d..dba2c89bc 100644--- a/web/src/components/MemoEditor/hooks/useMemoInit.ts+++ b/web/src/components/MemoEditor/hooks/useMemoInit.ts@@ -1,11 +1,15 @@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 { EditorRefActions } from "../Editor";+import { useTranslate } from "@/utils/i18n";+import { getPreferredEditorMode } from "../editorMode";import { cacheService, memoService } from "../services";import { useEditorContext } from "../state";+import { isLosslessRoundTrip } from "../TiptapEditor/markdownCodec";+import type { EditorController } from "../types/editorController";interface UseMemoInitOptions {- editorRef: React.RefObject<EditorRefActions | null>;+ editorRef: React.RefObject<EditorController | null>;memo?: Memo;cacheKey?: string;username: string;@@ -23,6 +27,7 @@ export const useMemoInit = ({defaultVisibility,defaultCreateTime,}: UseMemoInitOptions) => {+ const t = useTranslate();const { actions, dispatch } = useEditorContext();const initializedRef = useRef(false);const [isInitialized, setIsInitialized] = useState(false);@@ -36,6 +41,16 @@ export const useMemoInit = ({const initialState = memoService.fromMemo(memo);cacheService.clear(key);dispatch(actions.initMemo(initialState));+ // Load guard (tripwire): if the WYSIWYG round trip would change this+ // memo's meaning, edit it raw for this session. Preference untouched —+ // and INIT_MEMO ignores ui state, so the mode must be dispatched here.+ // No length cap: the check runs in a useEffect (post-paint). Add a cap+ // if profiling ever identifies cost on very large memos.+ if (getPreferredEditorMode() === "wysiwyg" && initialState.content && !isLosslessRoundTrip(initialState.content)) {+ console.warn("memo content failed wysiwyg round-trip; falling back to raw editor", memo.name);+ dispatch(actions.setEditorMode("raw"));+ toast(t("editor.unsupported-syntax-raw-mode"));+ }} else {const cachedContent = cacheService.load(key);if (cachedContent) {@@ -54,7 +69,7 @@ export const useMemoInit = ({}setIsInitialized(true);- }, [memo, cacheKey, username, autoFocus, defaultVisibility, defaultCreateTime, actions, dispatch, editorRef]);+ }, [memo, cacheKey, username, autoFocus, defaultVisibility, defaultCreateTime, actions, dispatch, editorRef, t]);return { isInitialized };};diff --git a/web/src/components/MemoEditor/index.tsx b/web/src/components/MemoEditor/index.tsxindex abd1c06f1..0ace54767 100644--- a/web/src/components/MemoEditor/index.tsx+++ b/web/src/components/MemoEditor/index.tsx@@ -21,12 +21,12 @@ import {TimestampPopover,} from "./components";import { FOCUS_MODE_STYLES } from "./constants";-import type { EditorRefActions } from "./Editor";import { useAudioRecorder, useAutoSave, useFocusMode, useKeyboard, useMemoInit } from "./hooks";import { errorService, memoService, transcriptionService, validationService } from "./services";import { EditorProvider, useEditorContext } from "./state";import type { MemoEditorProps } from "./types";import type { LocalFile } from "./types/attachment";+import type { EditorController } from "./types/editorController";const MemoEditor = (props: MemoEditorProps) => (<EditorProvider>@@ -48,7 +48,7 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({const t = useTranslate();const queryClient = useQueryClient();const currentUser = useCurrentUser();- const editorRef = useRef<EditorRefActions>(null);+ const editorRef = useRef<EditorController>(null);const { state, actions, dispatch } = useEditorContext();const { userGeneralSetting } = useAuth();const { aiSetting, fetchSetting } = useInstance();@@ -112,15 +112,7 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({if (!editor) {return;}-- 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.insertMarkdown(text);editor.scrollToCursor();}, []);diff --git a/web/src/components/MemoEditor/services/memoService.ts b/web/src/components/MemoEditor/services/memoService.tsindex 20eee213b..02b47c32e 100644--- a/web/src/components/MemoEditor/services/memoService.ts+++ b/web/src/components/MemoEditor/services/memoService.ts@@ -122,8 +122,12 @@ export const memoService = {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 {content: memo.content,metadata: {@@ -132,23 +136,10 @@ export const memoService = {relations: memo.relations,location: memo.location,},- ui: {- isFocusMode: false,- isLoading: { saving: false, uploading: false, loading: false },- isComposing: false,- },timestamps: {createTime: memo.createTime ? timestampDate(memo.createTime) : undefined,updateTime: memo.updateTime ? timestampDate(memo.updateTime) : undefined,},- localFiles: [],- audioRecorder: {- isSupported: true,- permission: "unknown",- status: "idle",- elapsedSeconds: 0,- error: undefined,- },};},};diff --git a/web/src/components/MemoEditor/state/actions.ts b/web/src/components/MemoEditor/state/actions.tsindex 392a96bb3..983956108 100644--- a/web/src/components/MemoEditor/state/actions.ts+++ b/web/src/components/MemoEditor/state/actions.ts@@ -1,5 +1,6 @@import type { Attachment } from "@/types/proto/api/v1/attachment_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 { AudioRecorderPermission, AudioRecorderStatus, EditorAction, EditorState, LoadingKey } from "./types";@@ -102,6 +103,11 @@ export const editorActions = {payload: value,}),+ setEditorMode: (mode: EditorMode): EditorAction => ({+ type: "SET_EDITOR_MODE",+ payload: mode,+ }),+reset: (): EditorAction => ({type: "RESET",}),diff --git a/web/src/components/MemoEditor/state/context.tsx b/web/src/components/MemoEditor/state/context.tsxindex 4b0eb4e81..fbc1f67f8 100644--- a/web/src/components/MemoEditor/state/context.tsx+++ b/web/src/components/MemoEditor/state/context.tsx@@ -2,7 +2,7 @@ import { createContext, type Dispatch, type FC, type PropsWithChildren, useConteimport { editorActions } from "./actions";import { editorReducer } from "./reducer";import type { EditorAction, EditorState } from "./types";-import { initialState } from "./types";+import { createInitialState } from "./types";interface EditorContextValue {state: EditorState;@@ -25,7 +25,7 @@ interface EditorProviderProps extends PropsWithChildren {}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>(() => ({diff --git a/web/src/components/MemoEditor/state/reducer.ts b/web/src/components/MemoEditor/state/reducer.tsindex 820282317..05b2fdfb7 100644--- a/web/src/components/MemoEditor/state/reducer.ts+++ b/web/src/components/MemoEditor/state/reducer.ts@@ -1,5 +1,5 @@import type { EditorAction, EditorState } from "./types";-import { initialState } from "./types";+import { createInitialState } from "./types";export function editorReducer(state: EditorState, action: EditorAction): EditorState {switch (action.type) {@@ -171,11 +171,21 @@ export function editorReducer(state: EditorState, action: EditorAction): EditorS},};- case "RESET":+ case "SET_EDITOR_MODE":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:return state;}diff --git a/web/src/components/MemoEditor/state/types.ts b/web/src/components/MemoEditor/state/types.tsindex f06c33366..8a3da9345 100644--- a/web/src/components/MemoEditor/state/types.ts+++ b/web/src/components/MemoEditor/state/types.ts@@ -1,6 +1,7 @@import type { Attachment } from "@/types/proto/api/v1/attachment_service_pb";import type { Location, MemoRelation } from "@/types/proto/api/v1/memo_service_pb";import { Visibility } from "@/types/proto/api/v1/memo_service_pb";+import { type EditorMode, getPreferredEditorMode } from "../editorMode";import type { LocalFile } from "../types/attachment";export type LoadingKey = "saving" | "uploading" | "loading";@@ -23,6 +24,7 @@ export interface EditorState {loading: boolean;};isComposing: boolean;+ editorMode: EditorMode;};timestamps: {createTime?: Date;@@ -59,9 +61,13 @@ export type EditorAction =| { type: "SET_AUDIO_RECORDER_STATUS"; payload: AudioRecorderStatus }| { type: "SET_AUDIO_RECORDER_ELAPSED"; payload: number }| { type: "SET_AUDIO_RECORDER_ERROR"; payload?: string }+ | { type: "SET_EDITOR_MODE"; payload: EditorMode }| { 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: "",metadata: {visibility: Visibility.PRIVATE,@@ -77,6 +83,7 @@ export const initialState: EditorState = {loading: false,},isComposing: false,+ editorMode: "wysiwyg",},timestamps: {createTime: undefined,@@ -91,3 +98,15 @@ export const initialState: EditorState = {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() },+ };+}diff --git a/web/src/components/MemoEditor/types/editorController.ts b/web/src/components/MemoEditor/types/editorController.tsnew file mode 100644index 000000000..eb97dd17e--- /dev/null+++ b/web/src/components/MemoEditor/types/editorController.ts@@ -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;+}diff --git a/web/src/components/MemoEditor/types/index.ts b/web/src/components/MemoEditor/types/index.tsindex 6b81f232b..169c705fa 100644--- a/web/src/components/MemoEditor/types/index.ts+++ b/web/src/components/MemoEditor/types/index.ts@@ -13,4 +13,5 @@ export type {TagSuggestionsProps,VisibilitySelectorProps,} from "./components";+export type { EditorController } from "./editorController";export type { LocationState } from "./insert-menu";diff --git a/web/src/index.css b/web/src/index.cssindex 532aba00e..c736c545a 100644--- a/web/src/index.css+++ b/web/src/index.css@@ -31,3 +31,126 @@@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;+}diff --git a/web/src/locales/en.json b/web/src/locales/en.jsonindex 1f17a635c..6414148fd 100644--- a/web/src/locales/en.json+++ b/web/src/locales/en.json@@ -173,6 +173,9 @@"save": "Save","saving": "Saving...","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": {"attachment-label": "Audio recording","attachment-label-with-time": "Audio recording {{time}}",diff --git a/web/tests/editor-controller-adapter.test.tsx b/web/tests/editor-controller-adapter.test.tsxnew file mode 100644index 000000000..aea9a3fc6--- /dev/null+++ b/web/tests/editor-controller-adapter.test.tsx@@ -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);+ });+});diff --git a/web/tests/editor-load-guard.test.tsx b/web/tests/editor-load-guard.test.tsxnew file mode 100644index 000000000..5096f4c50--- /dev/null+++ b/web/tests/editor-load-guard.test.tsx@@ -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();+ });+});diff --git a/web/tests/editor-mode-toggle.test.tsx b/web/tests/editor-mode-toggle.test.tsxnew file mode 100644index 000000000..9fab55f4f--- /dev/null+++ b/web/tests/editor-mode-toggle.test.tsx@@ -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();+ });+});diff --git a/web/tests/editor-mode.test.ts b/web/tests/editor-mode.test.tsnew file mode 100644index 000000000..11bea032b--- /dev/null+++ b/web/tests/editor-mode.test.ts@@ -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);+ });+});diff --git a/web/tests/fixtures/markdown-corpus/preserved/block-html.md b/web/tests/fixtures/markdown-corpus/preserved/block-html.mdnew file mode 100644index 000000000..cce1cf106--- /dev/null+++ b/web/tests/fixtures/markdown-corpus/preserved/block-html.md@@ -0,0 +1,7 @@+Paragraph before.++<div class="custom">+ <p>Raw HTML block content</p>+</div>++Paragraph after.diff --git a/web/tests/fixtures/markdown-corpus/preserved/inline-html.md b/web/tests/fixtures/markdown-corpus/preserved/inline-html.mdnew file mode 100644index 000000000..18a229a46--- /dev/null+++ b/web/tests/fixtures/markdown-corpus/preserved/inline-html.md@@ -0,0 +1 @@+Use <em>emphasis</em> and a line<br>break and <span class="x">spans</span> here.diff --git a/web/tests/fixtures/markdown-corpus/preserved/math-block.md b/web/tests/fixtures/markdown-corpus/preserved/math-block.mdnew file mode 100644index 000000000..b258e5605--- /dev/null+++ b/web/tests/fixtures/markdown-corpus/preserved/math-block.md@@ -0,0 +1,7 @@+Before the math.++$$+E = mc^2 \cdot \frac{1}{\sqrt{1 - v^2/c^2}}+$$++After the math.diff --git a/web/tests/fixtures/markdown-corpus/preserved/math-inline.md b/web/tests/fixtures/markdown-corpus/preserved/math-inline.mdnew file mode 100644index 000000000..c279931f0--- /dev/null+++ b/web/tests/fixtures/markdown-corpus/preserved/math-inline.md@@ -0,0 +1 @@+Energy is $E=mc^2$ and the index is $x_1$ in this sentence.diff --git a/web/tests/fixtures/markdown-corpus/preserved/table.md b/web/tests/fixtures/markdown-corpus/preserved/table.mdnew file mode 100644index 000000000..62fdd5729--- /dev/null+++ b/web/tests/fixtures/markdown-corpus/preserved/table.md@@ -0,0 +1,4 @@+| Name | Role |+| --- | --- |+| Ada | Engineer |+| Grace | Admiral |diff --git a/web/tests/fixtures/markdown-corpus/supported/basic.md b/web/tests/fixtures/markdown-corpus/supported/basic.mdnew file mode 100644index 000000000..e7faea1dc--- /dev/null+++ b/web/tests/fixtures/markdown-corpus/supported/basic.md@@ -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.diff --git a/web/tests/fixtures/markdown-corpus/supported/blockquote-mixed.md b/web/tests/fixtures/markdown-corpus/supported/blockquote-mixed.mdnew file mode 100644index 000000000..bf063247a--- /dev/null+++ b/web/tests/fixtures/markdown-corpus/supported/blockquote-mixed.md@@ -0,0 +1,7 @@+> Outer quote line one.+> Still the same quote.++Paragraph after.++> - a list in a quote+> - second itemdiff --git a/web/tests/fixtures/markdown-corpus/supported/cjk-emoji.md b/web/tests/fixtures/markdown-corpus/supported/cjk-emoji.mdnew file mode 100644index 000000000..1ebf4cd67--- /dev/null+++ b/web/tests/fixtures/markdown-corpus/supported/cjk-emoji.md@@ -0,0 +1,9 @@+# 日本語の見出し++これは**太字**と*斜体*のテストです。改行も確認します。++- 中文列表项+- 한국어 항목+- emoji 🎉 in a list 🚀++> 引用文です 😀diff --git a/web/tests/fixtures/markdown-corpus/supported/code-blocks.md b/web/tests/fixtures/markdown-corpus/supported/code-blocks.mdnew file mode 100644index 000000000..421195e4f--- /dev/null+++ b/web/tests/fixtures/markdown-corpus/supported/code-blocks.md@@ -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+```diff --git a/web/tests/fixtures/markdown-corpus/supported/headings.md b/web/tests/fixtures/markdown-corpus/supported/headings.mdnew file mode 100644index 000000000..911de0ee0--- /dev/null+++ b/web/tests/fixtures/markdown-corpus/supported/headings.md@@ -0,0 +1,13 @@+# H1++## H2++### H3++#### H4++##### H5++###### H6++Body under headings.diff --git a/web/tests/fixtures/markdown-corpus/supported/lists.md b/web/tests/fixtures/markdown-corpus/supported/lists.mdnew file mode 100644index 000000000..9a9bc0fb9--- /dev/null+++ b/web/tests/fixtures/markdown-corpus/supported/lists.md@@ -0,0 +1,11 @@+- alpha+- beta+ - nested one+ - nested two+- gamma++1. first+2. second+ 1. second-a+ 2. second-b+3. thirddiff --git a/web/tests/fixtures/markdown-corpus/supported/task-lists.md b/web/tests/fixtures/markdown-corpus/supported/task-lists.mdnew file mode 100644index 000000000..ddcd57809--- /dev/null+++ b/web/tests/fixtures/markdown-corpus/supported/task-lists.md@@ -0,0 +1,8 @@+- [ ] open task+- [x] done task+- [ ] task with **bold** text++Regular paragraph between.++- [ ] another list+ - [x] nested donediff --git a/web/tests/insert-menu-mode-toggle.test.tsx b/web/tests/insert-menu-mode-toggle.test.tsxnew file mode 100644index 000000000..567bcfa0a--- /dev/null+++ b/web/tests/insert-menu-mode-toggle.test.tsx@@ -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");+ });+});diff --git a/web/tests/markdown-roundtrip.test.ts b/web/tests/markdown-roundtrip.test.tsnew file mode 100644index 000000000..bb860491e--- /dev/null+++ b/web/tests/markdown-roundtrip.test.ts@@ -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);+ });+ }+});diff --git a/web/tests/setup.ts b/web/tests/setup.tsindex e69ded96c..ffda4f481 100644--- a/web/tests/setup.ts+++ b/web/tests/setup.ts@@ -9,6 +9,43 @@ afterEach(() => {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// to coordinate token refreshes across tabs. jsdom historically has not shipped// BroadcastChannel, so any future test that transitively imports auth-statediff --git a/web/tests/suggestion-menu.test.tsx b/web/tests/suggestion-menu.test.tsxnew file mode 100644index 000000000..03973178a--- /dev/null+++ b/web/tests/suggestion-menu.test.tsx@@ -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);+ });+});diff --git a/web/tests/tiptap-editor-controller.test.tsx b/web/tests/tiptap-editor-controller.test.tsxnew file mode 100644index 000000000..c98d081a6--- /dev/null+++ b/web/tests/tiptap-editor-controller.test.tsx@@ -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");+ });+});diff --git a/web/tests/tiptap-preserved.test.ts b/web/tests/tiptap-preserved.test.tsnew file mode 100644index 000000000..2de48f3bd--- /dev/null+++ b/web/tests/tiptap-preserved.test.ts@@ -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");+ });+});diff --git a/web/tests/tiptap-slash-commands.test.ts b/web/tests/tiptap-slash-commands.test.tsnew file mode 100644index 000000000..5e8d4057a--- /dev/null+++ b/web/tests/tiptap-slash-commands.test.ts@@ -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([]);+ });+});diff --git a/web/tests/tiptap-tag.test.ts b/web/tests/tiptap-tag.test.tsnew file mode 100644index 000000000..84edda4f4--- /dev/null+++ b/web/tests/tiptap-tag.test.ts@@ -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+ });+});