);
diff --git a/web/src/components/MemoEditor/Editor/Mention.ts b/web/src/components/MemoEditor/Editor/Mention.ts
deleted file mode 100644
index a8f0dc3c..00000000
--- a/web/src/components/MemoEditor/Editor/Mention.ts
+++ /dev/null
@@ -1,124 +0,0 @@
-import type { MarkdownToken } from "@tiptap/core";
-import { InputRule, Mark, mergeAttributes } from "@tiptap/core";
-import { mentionStyles } from "@/lib/markdownStyles";
-import { isMentionChar, MENTION_RUN } from "@/utils/mention-grammar";
-
-// Default mention accent, shared with the read-only view (MemoContent/Mention.tsx).
-// Computed once — renderHTML runs on every view update.
-const MENTION_CLASS = mentionStyles.base;
-
-// Built from the shared MENTION_RUN (@/utils/mention-grammar) so the editor's
-// input rule and tokenizer can't drift from the read-only renderer's lexer
-// (web/src/utils/remark-plugins/remark-mention.ts). The `(? element.getAttribute("data-mention") ?? "",
- renderHTML: (attributes) => ({ "data-mention": attributes.username }),
- },
- };
- },
-
- parseHTML() {
- return [{ tag: "span[data-mention]" }];
- },
-
- renderHTML({ HTMLAttributes }) {
- return [
- "span",
- mergeAttributes(HTMLAttributes, {
- class: MENTION_CLASS,
- }),
- 0,
- ];
- },
-
- addInputRules() {
- return [
- new InputRule({
- find: MENTION_INPUT_RULE,
- handler: ({ state, range, match }) => {
- // Mark only from the `@`; the trailing space stays outside the mark
- // and is re-inserted explicitly (the handler's steps suppress the
- // typed space), mirroring the Tag input rule.
- const start = range.from + match[0].indexOf("@");
- state.tr
- .addMark(start, range.to, this.type.create({ username: match[1] }))
- .insertText(" ", range.to)
- .removeStoredMark(this.type);
- },
- }),
- ];
- },
-
- markdownTokenizer: {
- name: "memoMention",
- level: "inline",
- // Point marked only at an `@` that could *begin* a mention — one at a
- // boundary (string start, or a non-mention char before it). An `@` glued to
- // a preceding word/username char belongs to an email (`support@example.com`)
- // or the tail of `@a@b`; surfacing its index here would make marked split
- // the text at the `@` and rob its GFM autolinker of the contiguous email,
- // suppressing the mailto link. Skipping such `@`s leaves emails to autolink.
- start: (src: string) => {
- for (let i = src.indexOf("@"); i !== -1; i = src.indexOf("@", i + 1)) {
- if (i === 0 || !isMentionChar(src[i - 1])) {
- return i;
- }
- }
- return -1;
- },
- tokenize: (src: string, tokens: MarkdownToken[]) => {
- const match = MENTION_TOKEN_RULE.exec(src);
- if (!match) {
- return undefined;
- }
- // A mention only starts at a boundary. The previous token's last source
- // character is exactly the character before this `@`; if it is a mention
- // character the `@` is glued to a word or username (`support@example`,
- // the second `@` in `@a@b`) and must stay literal — mirroring the
- // read-only renderer's isMentionBoundary check (remark-mention.ts).
- const prevChar = (tokens[tokens.length - 1]?.raw ?? "").slice(-1);
- if (prevChar && isMentionChar(prevChar)) {
- return undefined;
- }
- return { type: "memoMention", raw: match[0], username: match[1] };
- },
- },
- markdownTokenName: "memoMention",
- parseMarkdown: (token, helpers) => {
- const t = token as MarkdownToken & { username?: string };
- return helpers.createTextNode(t.raw ?? "", [{ type: "mention", attrs: { username: t.username ?? "" } }]);
- },
- // No delimiters: the literal `@username` text carries the syntax.
- renderMarkdown: (node, helpers) => (node.content ? helpers.renderChildren(node.content) : ""),
-});
diff --git a/web/src/components/MemoEditor/Editor/PreservedBlock.ts b/web/src/components/MemoEditor/Editor/PreservedBlock.ts
deleted file mode 100644
index c177b9d7..00000000
--- a/web/src/components/MemoEditor/Editor/PreservedBlock.ts
+++ /dev/null
@@ -1,217 +0,0 @@
-import type { MarkdownParseHelpers, MarkdownToken } from "@tiptap/core";
-import { Extension, Mark, mergeAttributes, Node } from "@tiptap/core";
-import type { Tokens } from "marked";
-import { marked } from "marked";
-
-/**
- * Fidelity workhorse for syntax the WYSIWYG editor does not model (tables,
- * math, raw HTML). Constructs are captured at parse time with their raw
- * markdown source, shown as editable literal mono text, and re-emitted
- * byte-for-byte on serialize. `code: true` keeps the serializer from
- * escaping/entity-encoding the inner text.
- */
-export const PreservedBlock = Node.create({
- name: "preservedBlock",
- group: "block",
- content: "text*",
- marks: "",
- code: true,
- defining: true,
-
- parseHTML() {
- return [{ tag: "pre[data-preserved-block]", preserveWhitespace: "full" }];
- },
-
- renderHTML({ HTMLAttributes }) {
- return [
- "pre",
- mergeAttributes(HTMLAttributes, {
- "data-preserved-block": "",
- class: "font-mono text-sm opacity-80 whitespace-pre-wrap my-0",
- }),
- 0,
- ];
- },
-
- // The literal source is the node's text; Document joins blocks with \n\n.
- renderMarkdown: (node, helpers) => (node.content ? helpers.renderChildren(node.content) : ""),
-});
-
-/** Inline counterpart: a `code: true` mark that emits its text verbatim. */
-export const PreservedInline = Mark.create({
- name: "preservedInline",
- code: true,
-
- parseHTML() {
- return [{ tag: "span[data-preserved-inline]" }];
- },
-
- renderHTML({ HTMLAttributes }) {
- return ["span", mergeAttributes(HTMLAttributes, { "data-preserved-inline": "", class: "font-mono opacity-80" }), 0];
- },
-
- // No delimiters: the preserved text already contains its own syntax.
- renderMarkdown: (node, helpers) => (node.content ? helpers.renderChildren(node.content) : ""),
-});
-
-// Note: `MarkdownParseResult` in @tiptap/core 3.26.0 does not admit `null`;
-// the manager treats an empty array as "handler declined" (it requires
-// `normalized.length > 0` before accepting a result), so `[]` is the
-// type-safe way to fall through to the next handler / fallback.
-function preservedBlockFromToken(token: MarkdownToken, helpers: MarkdownParseHelpers) {
- const source = (token.raw ?? "").replace(/\n+$/, "");
- if (!source) {
- return [];
- }
- return helpers.createNode("preservedBlock", {}, [helpers.createTextNode(source)]);
-}
-
-/** Inline counterpart: the token's raw source as preservedInline-marked text. */
-function preservedInlineFromToken(token: MarkdownToken, helpers: MarkdownParseHelpers) {
- return helpers.createTextNode(token.raw ?? "", [{ type: "preservedInline" }]);
-}
-
-/** Routes marked's `table` tokens into preservedBlock instead of dropping them. */
-export const PreservedTableBridge = Extension.create({
- name: "preservedTableBridge",
- markdownTokenName: "table",
- parseMarkdown: preservedBlockFromToken,
-});
-
-/**
- * Routes block-level raw HTML into preservedBlock. Inline HTML never reaches
- * the handler registry (the markdown manager intercepts it and would convert
- * recognized tags like into marks), so inline tags are captured earlier
- * by the custom tokenizer in PreservedHtmlInlineBridge below.
- */
-export const PreservedHtmlBlockBridge = Extension.create({
- name: "preservedHtmlBlockBridge",
- markdownTokenName: "html",
- parseMarkdown: (token, helpers) => {
- if (!token.block) {
- return [];
- }
- return preservedBlockFromToken(token, helpers);
- },
-});
-
-function tokenizePreservedHtmlInline(src: string): Tokens.Generic | undefined {
- // One HTML comment, or one opening/closing/self-closing HTML tag. For
- // tags, the first character after `<` (or ``) must be a letter and the
- // tag name only [a-zA-Z0-9-], followed by attributes/`>` — this never
- // matches autolinks such as or
- // (`:`/`@` break the match). Attribute values are matched quote-aware so
- // `>` inside a quoted value (e.g. data-x="1 > 0") does not end the tag.
- // The alternatives are disjoint: the catch-all class [^<>"'] excludes both
- // quote characters so it cannot overlap with the quoted branches, which
- // eliminates catastrophic backtracking on unterminated tags with many quotes.
- const match = /^(?:|<\/?[a-zA-Z][a-zA-Z0-9-]*(?:\s(?:"[^"]*"|'[^']*'|[^<>"'])*)?\/?>)/.exec(src);
- if (!match) {
- return undefined;
- }
- return { type: "preservedHtmlInline", raw: match[0], text: match[0] };
-}
-
-function tokenizePreservedMathBlock(src: string): Tokens.Generic | undefined {
- // Anchored to line geometry: opens at line start (guaranteed by marked
- // handing us `src` from the current block position) and closes with `$$`
- // at end-of-line. Trailing newlines are NOT consumed into `raw` (the
- // `(?=\n|$)` lookahead): marked tolerates this for block tokens — its
- // "space" tokenizer absorbs the leftover `\n` and the following block
- // tokenizes normally (verified by the round-trip tests). Either way,
- // "$$\nx\n$$\nnext" serializes as "$$\nx\n$$\n\nnext": the \n\n comes
- // from the Document serializer joining sibling blocks, and
- // preservedBlockFromToken strips trailing \n from raw regardless — so
- // we keep raw minimal rather than swallow separators we don't re-emit.
- const match = /^\$\$[\s\S]+?\$\$(?=\n|$)/.exec(src);
- if (!match) {
- return undefined;
- }
- return { type: "preservedMathBlock", raw: match[0], text: match[0] };
-}
-
-function tokenizePreservedMathInline(src: string): Tokens.Generic | undefined {
- const match = /^\$[^$\n]+\$/.exec(src);
- if (!match) {
- return undefined;
- }
- return { type: "preservedMathInline", raw: match[0], text: match[0] };
-}
-
-/**
- * The three preserved-syntax tokenizers are registered DIRECTLY on the global
- * marked singleton, module-scope and idempotent — the Tag.ts pattern (see the
- * rationale there). Routing them through each Extension's `markdownTokenizer`
- * would make every `new Editor()` re-register them on the shared `marked`
- * instance forever (the accumulation hazard documented in markdownCodec.ts).
- * The Extensions below keep `markdownTokenName` + `parseMarkdown`, which is
- * all the manager needs to route the tokens.
- */
-let preservedTokenizersRegistered = false;
-function registerPreservedTokenizers() {
- if (preservedTokenizersRegistered) {
- return;
- }
- preservedTokenizersRegistered = true;
- marked.use({
- extensions: [
- {
- name: "preservedHtmlInline",
- level: "inline",
- start: (src: string) => src.indexOf("<"),
- tokenizer: tokenizePreservedHtmlInline,
- },
- {
- name: "preservedMathBlock",
- level: "block",
- // Marked truncates the preceding paragraph at whatever index `start`
- // returns, even if `tokenizer` then declines — so only report `$$` that
- // sits at the start of a line, never a mid-line `$$` (e.g. "costs $$").
- // Marked invokes block `start` callbacks exclusively from its paragraph
- // interrupt check, on `src.slice(1)` — index 0 of the string we receive
- // is always mid-line, so a `^`-anchored branch would false-positive
- // (e.g. "$$$$" → "$\n$\n$$"). Only a `$$` right after `\n` is line-start.
- start: (src: string) => {
- const match = /\n\$\$/.exec(src);
- return match ? match.index + 1 : -1;
- },
- tokenizer: tokenizePreservedMathBlock,
- },
- {
- name: "preservedMathInline",
- level: "inline",
- start: (src: string) => src.indexOf("$"),
- tokenizer: tokenizePreservedMathInline,
- },
- ],
- });
-}
-registerPreservedTokenizers();
-
-export const PreservedHtmlInlineBridge = Extension.create({
- name: "preservedHtmlInlineBridge",
- markdownTokenName: "preservedHtmlInline",
- parseMarkdown: preservedInlineFromToken,
-});
-
-export const PreservedMathBlockBridge = Extension.create({
- name: "preservedMathBlockBridge",
- markdownTokenName: "preservedMathBlock",
- parseMarkdown: preservedBlockFromToken,
-});
-
-export const PreservedMathInlineBridge = Extension.create({
- name: "preservedMathInlineBridge",
- markdownTokenName: "preservedMathInline",
- parseMarkdown: preservedInlineFromToken,
-});
-
-export const preservedExtensions = [
- PreservedBlock,
- PreservedInline,
- PreservedTableBridge,
- PreservedHtmlBlockBridge,
- PreservedHtmlInlineBridge,
- PreservedMathBlockBridge,
- PreservedMathInlineBridge,
-];
diff --git a/web/src/components/MemoEditor/Editor/Tag.ts b/web/src/components/MemoEditor/Editor/Tag.ts
deleted file mode 100644
index 478cabc9..00000000
--- a/web/src/components/MemoEditor/Editor/Tag.ts
+++ /dev/null
@@ -1,122 +0,0 @@
-import type { MarkdownToken } from "@tiptap/core";
-import { InputRule, Mark, mergeAttributes } from "@tiptap/core";
-import { tagStyles } from "@/lib/markdownStyles";
-import { TAG_RUN } from "@/utils/tag-grammar";
-
-// Default tag pill, shared with the read-only view (MemoContent/Tag.tsx).
-// Computed once — renderHTML runs on every view update.
-const TAG_CLASS = `${tagStyles.base} ${tagStyles.defaultColor}`;
-
-// Built from the shared TAG_RUN (@/utils/tag-grammar) so the editor's input
-// rule and tokenizer can't drift from the serialize-escape or the read-only
-// renderer's lexer (web/src/utils/remark-plugins/remark-tag.ts). The capped-run
-// lookahead in TAG_RUN also makes an over-long run decline to match — no
-// separate length check needed.
-const TAG_INPUT_RULE = new RegExp(`(?:^|\\s)#(${TAG_RUN})\\s$`, "u");
-const TAG_TOKEN_RULE = new RegExp(`^#(${TAG_RUN})`, "u");
-
-/**
- * Mark for memos `#tags`: styled in the editor, serialized back to `#tag`
- * verbatim. Modeled as a `code: true` text mark (the PreservedInline pattern,
- * see PreservedBlock.ts) rather than an inline atom node: text marks compose
- * through the serializer's mark open/close machinery, so a tag inside
- * `**bold**` or a heading round-trips byte-identically, and `code: true`
- * keeps the literal text (`#a_b`) unescaped. Inline atoms cannot do either —
- * `applyMarkToContent` only attaches enclosing marks to text nodes, so an
- * atom inside bold silently drops the bold delimiters.
- *
- * Parsed live while typing (the input rule) and from markdown (the
- * `markdownTokenizer` below — the canonical @tiptap/markdown extension point,
- * https://tiptap.dev/docs/editor/markdown/advanced-usage/custom-tokenizer).
- *
- * Two consequences of going through the manager (vs. registering on `marked`
- * directly) are handled in tagMarkdown.ts:
- * - The tokenizer can't see whether it sits inside a link label — the manager
- * forwards only `{ inlineTokens, blockTokens }`, not the lexer's `inLink`
- * state — so tag-in-link skipping is a tree pass there, mirroring how the
- * read-only renderer (remark-tag) skips link nodes.
- * - The manager re-registers this tokenizer onto the global `marked` on every
- * Editor construction (the accumulation noted in markdownCodec.ts). The
- * impact is sub-millisecond for memo-sized content and the test codec is a
- * singleton; accepted as the cost of the canonical API.
- */
-export const Tag = Mark.create({
- name: "tag",
- // Typing immediately after a tag must not extend it.
- inclusive: false,
- // Serializer emits the inner text verbatim, without escaping.
- code: true,
-
- addAttributes() {
- return {
- // The tag name without `#`, for downstream consumers (e.g. suggestion
- // insertion). Stored as `tag` but rendered/parsed as `data-tag`.
- tag: {
- default: "",
- parseHTML: (element) => element.getAttribute("data-tag") ?? "",
- renderHTML: (attributes) => ({ "data-tag": attributes.tag }),
- },
- };
- },
-
- parseHTML() {
- return [{ tag: "span[data-tag]" }];
- },
-
- renderHTML({ HTMLAttributes }) {
- return [
- "span",
- mergeAttributes(HTMLAttributes, {
- class: TAG_CLASS,
- }),
- 0,
- ];
- },
-
- addInputRules() {
- return [
- new InputRule({
- find: TAG_INPUT_RULE,
- handler: ({ state, range, match }) => {
- // The match may include a leading separator — only mark from the
- // `#`. The trailing space stays outside the mark; because the
- // handler produces steps the typed space is suppressed, so it is
- // re-inserted explicitly after the marked range.
- const start = range.from + match[0].indexOf("#");
- state.tr
- .addMark(start, range.to, this.type.create({ tag: match[1] }))
- .insertText(" ", range.to)
- .removeStoredMark(this.type);
- },
- }),
- ];
- },
-
- markdownTokenizer: {
- name: "memoTag",
- level: "inline",
- start: (src: string) => src.indexOf("#"),
- tokenize: (src: string) => {
- const match = TAG_TOKEN_RULE.exec(src);
- if (!match) {
- return undefined;
- }
- // `#a#b`: decline when the run is directly followed by another `#`, so the
- // FIRST run stays plain text "#a" + tag "b" (`##x` likewise → text "#" +
- // tag "x"). The serialize-escape then escapes the tag-shaped literal "#a",
- // so `#a#b` round-trips as `\#a#b` — doc-equivalent and stable thereafter.
- // (An over-long run already declines: TAG_RUN's lookahead fails to match.)
- if (src.slice(match[0].length).startsWith("#")) {
- return undefined;
- }
- return { type: "memoTag", raw: match[0], tag: match[1] };
- },
- },
- markdownTokenName: "memoTag",
- parseMarkdown: (token, helpers) => {
- const t = token as MarkdownToken & { tag?: string };
- return helpers.createTextNode(t.raw ?? "", [{ type: "tag", attrs: { tag: t.tag ?? "" } }]);
- },
- // No delimiters: the literal `#tag` text carries the syntax.
- renderMarkdown: (node, helpers) => (node.content ? helpers.renderChildren(node.content) : ""),
-});
diff --git a/web/src/components/MemoEditor/Editor/TagSuggestion.ts b/web/src/components/MemoEditor/Editor/TagSuggestion.ts
deleted file mode 100644
index 94f72357..00000000
--- a/web/src/components/MemoEditor/Editor/TagSuggestion.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-import { createElement } from "react";
-import { createSuggestionExtension } from "./suggestionExtension";
-
-export interface TagSuggestionOptions {
- /** Getter (not a snapshot) so the popup always sees freshly fetched tags. */
- getTags: () => string[];
-}
-
-const MAX_SUGGESTIONS = 20;
-
-/** `#` popup backed by the user's existing tags; inserts tag-marked text + a space. */
-export function createTagSuggestion({ getTags }: TagSuggestionOptions) {
- return createSuggestionExtension({
- name: "tagSuggestion",
- char: "#",
- allowSpaces: false,
- items: (query) => {
- // Require at least one char after `#` so a bare `#` (or `# ` heading)
- // doesn't pop the tag menu and conflict with markdown headings.
- if (query.length === 0) {
- return [];
- }
- const q = query.toLowerCase();
- return getTags()
- .filter((tag) => tag.toLowerCase().includes(q))
- .slice(0, MAX_SUGGESTIONS);
- },
- command: ({ editor, range, props: tag }) => {
- editor
- .chain()
- .focus()
- .insertContentAt(range, [
- { type: "text", text: `#${tag}`, marks: [{ type: "tag", attrs: { tag } }] },
- { type: "text", text: " " },
- ])
- .run();
- },
- renderItem: (tag) =>
- createElement("span", { className: "truncate" }, createElement("span", { className: "text-muted-foreground mr-1" }, "#"), tag),
- getItemKey: (tag) => tag,
- });
-}
diff --git a/web/src/components/MemoEditor/Editor/controller.ts b/web/src/components/MemoEditor/Editor/controller.ts
new file mode 100644
index 00000000..759477ce
--- /dev/null
+++ b/web/src/components/MemoEditor/Editor/controller.ts
@@ -0,0 +1,37 @@
+import { EditorSelection, type EditorState } from "@codemirror/state";
+import { EditorView } from "@codemirror/view";
+import type { EditorController, FormattingController } from "../types/editorController";
+
+const isEmptyDoc = (state: EditorState) => state.doc.toString().trim() === "";
+
+/** Block padding for insertMarkdown: ensure the inserted text is its own block. */
+function blockPad(before: string, after: string): { prefix: string; suffix: string } {
+ const prefix = before.length === 0 || before.endsWith("\n\n") ? "" : before.endsWith("\n") ? "\n" : "\n\n";
+ const suffix = after.length === 0 || after.startsWith("\n\n") ? "" : after.startsWith("\n") ? "\n" : "\n\n";
+ return { prefix, suffix };
+}
+
+export function createController(view: EditorView, formatting: FormattingController): EditorController {
+ return {
+ focus: () => view.focus(),
+ hasFocus: () => view.hasFocus,
+ isEmpty: () => isEmptyDoc(view.state),
+ getMarkdown: () => view.state.doc.toString(),
+ setMarkdown: (markdown) => {
+ view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: markdown } });
+ },
+ insertMarkdown: (markdown) => {
+ if (!markdown) return;
+ const { from, to } = view.state.selection.main;
+ const doc = view.state.doc.toString();
+ const { prefix, suffix } = blockPad(doc.slice(0, from), doc.slice(to));
+ const insert = prefix + markdown + suffix;
+ const caret = from + insert.length;
+ view.dispatch({ changes: { from, to, insert }, selection: { anchor: caret }, scrollIntoView: true });
+ view.focus();
+ },
+ scrollToCursor: () => view.dispatch({ effects: EditorView.scrollIntoView(view.state.selection.main.head) }),
+ selectAll: () => view.dispatch({ selection: EditorSelection.range(0, view.state.doc.length) }),
+ formatting,
+ };
+}
diff --git a/web/src/components/MemoEditor/Editor/editor.css b/web/src/components/MemoEditor/Editor/editor.css
new file mode 100644
index 00000000..52f1ab89
--- /dev/null
+++ b/web/src/components/MemoEditor/Editor/editor.css
@@ -0,0 +1,133 @@
+/*
+ * Styling for the CodeMirror source editor, in plain CSS with the app's theme
+ * variables — the same model Obsidian / GitHub use for an app-integrated CM6
+ * editor (class-based tokens + CSS, not a CSS-in-JS theme). Co-located with the
+ * component and scoped to its wrapper so nothing leaks to other CM instances.
+ *
+ * Token classes (.cm-md-*) come from the tagHighlighter in theme.ts; heading
+ * line classes (.cm-md-h*) from headingDecorations.ts; #tag/@mention
+ * (.cm-memo-*) from tagMentionDecorations.ts; the rest are CodeMirror's own.
+ */
+.memo-editor-content {
+ & .cm-editor {
+ background: transparent;
+ font-size: 1rem;
+ }
+ & .cm-editor.cm-focused {
+ outline: none;
+ }
+ & .cm-content {
+ font-family: inherit;
+ padding: 0;
+ caret-color: var(--foreground);
+ }
+ & .cm-line {
+ padding: 0;
+ }
+ & .cm-scroller {
+ font-family: inherit;
+ line-height: 1.5;
+ }
+ & .cm-placeholder {
+ color: var(--muted-foreground);
+ opacity: 0.7;
+ }
+
+ /* drawSelection() caret + selection (no base color theme is loaded). */
+ & .cm-cursor,
+ & .cm-dropCursor {
+ border-left-color: var(--foreground);
+ }
+ & .cm-selectionBackground,
+ & .cm-focused .cm-selectionBackground {
+ background: var(--accent);
+ }
+
+ /* Markdown tokens. Markers (#, *, fences, bullets) stay visible but muted
+ (.cm-md-mark); styled text leads. */
+ & .cm-md-strong {
+ font-weight: 700;
+ }
+ & .cm-md-emphasis {
+ font-style: italic;
+ }
+ & .cm-md-strike {
+ text-decoration: line-through;
+ }
+ & .cm-md-code {
+ font-family: var(--font-mono, monospace);
+ color: var(--foreground);
+ }
+ & .cm-md-link {
+ color: var(--primary);
+ text-decoration: underline;
+ }
+ & .cm-md-url {
+ color: var(--muted-foreground);
+ }
+ & .cm-md-quote {
+ color: var(--muted-foreground);
+ font-style: italic;
+ }
+ & .cm-md-mark {
+ color: var(--muted-foreground);
+ }
+
+ /* Heading lines (require a space after the hashes; headingDecorations.ts). */
+ & .cm-md-h1 {
+ font-size: 1.5em;
+ font-weight: 600;
+ line-height: 1.3;
+ }
+ & .cm-md-h2 {
+ font-size: 1.3em;
+ font-weight: 600;
+ }
+ & .cm-md-h3 {
+ font-size: 1.15em;
+ font-weight: 600;
+ }
+ & .cm-md-h4,
+ & .cm-md-h5,
+ & .cm-md-h6 {
+ font-weight: 600;
+ }
+
+ /* #tag / @mention decorations. */
+ & .cm-memo-tag,
+ & .cm-memo-mention {
+ color: var(--primary);
+ }
+
+ /* Tag autocomplete popover — app surface, not CodeMirror defaults. */
+ & .cm-tooltip.cm-tooltip-autocomplete {
+ background: var(--popover);
+ color: var(--popover-foreground);
+ border: 1px solid var(--border);
+ border-radius: 0.5rem;
+ box-shadow: var(--shadow-md);
+ overflow: hidden;
+ font-family: inherit;
+ font-size: 0.9rem;
+ }
+ & .cm-tooltip-autocomplete > ul {
+ font-family: inherit;
+ color: var(--popover-foreground);
+ }
+ & .cm-tooltip-autocomplete > ul > li {
+ padding: 0.25rem 0.5rem;
+ color: var(--popover-foreground);
+ }
+ & .cm-tooltip-autocomplete > ul > li[aria-selected] {
+ background: var(--accent);
+ color: var(--accent-foreground);
+ }
+ & .cm-completionIcon {
+ display: none;
+ }
+ & .cm-completionMatchedText {
+ text-decoration: none;
+ font-weight: 600;
+ color: inherit;
+ }
+}
diff --git a/web/src/components/MemoEditor/Editor/extensions.ts b/web/src/components/MemoEditor/Editor/extensions.ts
index d24f40e7..395b7663 100644
--- a/web/src/components/MemoEditor/Editor/extensions.ts
+++ b/web/src/components/MemoEditor/Editor/extensions.ts
@@ -1,55 +1,67 @@
-import { type AnyExtension, mergeAttributes } from "@tiptap/core";
-import { Heading } from "@tiptap/extension-heading";
-import { TaskItem, TaskList } from "@tiptap/extension-list";
-import StarterKit from "@tiptap/starter-kit";
-import { type HeadingLevel, headingClass, markdownStyles } from "@/lib/markdownStyles";
-import { Mention } from "./Mention";
-import { preservedExtensions } from "./PreservedBlock";
-import { Tag } from "./Tag";
-import { TagAwareMarkdown } from "./tagMarkdown";
+import { defaultKeymap, history, historyKeymap, indentWithTab } from "@codemirror/commands";
+import { markdown } from "@codemirror/lang-markdown";
+import { indentUnit } from "@codemirror/language";
+import { EditorState, type Extension } from "@codemirror/state";
+import { placeholder as cmPlaceholder, drawSelection, dropCursor, EditorView, type KeyBinding, keymap } from "@codemirror/view";
+import { GFM } from "@lezer/markdown";
+import { headingDecorations } from "./headingDecorations";
+import { liftListItem, sinkListItem } from "./listIndent";
+import { tagAutocomplete } from "./tagAutocomplete";
+import { tagMentionDecorations } from "./tagMentionDecorations";
+import { memoEditorTheme } from "./theme";
-/**
- * StarterKit's Heading is bundled and cannot vary classes by level via static
- * HTMLAttributes, so we disable it (heading: false) and render headings here.
- * renderHTML only affects the editable DOM — heading markdown serialization is
- * unchanged — so the round-trip codec is unaffected.
- */
-const StyledHeading = Heading.extend({
- renderHTML({ node, HTMLAttributes }) {
- const { levels } = this.options;
- const level = (levels.includes(node.attrs.level) ? node.attrs.level : levels[0]) as HeadingLevel;
- return [`h${level}`, mergeAttributes(this.options.HTMLAttributes, HTMLAttributes, { class: headingClass(level) }), 0];
+// Key bindings layered below the autocomplete keymap so the completion popup's
+// own Tab/Escape win while it is open. On a list item, Tab/Shift-Tab nest /
+// outdent it (marker-aware, CommonMark-valid); elsewhere they fall through to
+// indentWithTab's plain indent. Escape blurs the editor so keyboard users keep
+// an escape hatch out of the otherwise Tab-trapping editor.
+const editorKeys: KeyBinding[] = [
+ {
+ key: "Escape",
+ run: (view) => {
+ view.contentDOM.blur();
+ return true;
+ },
},
-});
+ { key: "Tab", run: sinkListItem },
+ { key: "Shift-Tab", run: liftListItem },
+];
-/**
- * The canonical schema-relevant extension set, shared by the live editor and
- * the headless markdown codec so that parse/serialize behavior is identical
- * in both. UI-only extensions (Placeholder, suggestion popups) are added by
- * the editor component on top of this list and must never affect the schema.
- */
-export function buildExtensions(): AnyExtension[] {
+export interface EditorExtensionsOptions {
+ placeholder: string;
+ onChange: (markdown: string) => void;
+ onUpdate: () => void;
+ getTags: () => string[];
+}
+
+export function buildEditorExtensions({ placeholder, onChange, onUpdate, getTags }: EditorExtensionsOptions): Extension[] {
return [
- StarterKit.configure({
- heading: false,
- link: { openOnClick: false, HTMLAttributes: { class: markdownStyles.link } },
- // Markdown has no underline syntax; keeping the extension would let
- // Ctrl+U create marks that cannot serialize. Out of the schema entirely.
- underline: false,
- paragraph: { HTMLAttributes: { class: markdownStyles.paragraph } },
- blockquote: { HTMLAttributes: { class: markdownStyles.blockquote } },
- bulletList: { HTMLAttributes: { class: markdownStyles.bulletList } },
- orderedList: { HTMLAttributes: { class: markdownStyles.orderedList } },
- listItem: { HTMLAttributes: { class: markdownStyles.listItem } },
- code: { HTMLAttributes: { class: markdownStyles.inlineCode } },
- horizontalRule: { HTMLAttributes: { class: markdownStyles.horizontalRule } },
+ // Core editing behavior. Without these the editor relies on raw
+ // contenteditable: typing works but there is no visible caret on focus
+ // (drawSelection), no undo/redo (history), and Enter/selection/word-motion
+ // keys are unwired (defaultKeymap). They are NOT part of CodeMirror's
+ // minimal core — basicSetup bundles them, and we assemble them here.
+ history(),
+ drawSelection(),
+ dropCursor(),
+ EditorState.allowMultipleSelections.of(true),
+ // Indent with spaces (markdown), matching the 2-space bullet nesting.
+ indentUnit.of(" "),
+ markdown({ extensions: [GFM] }),
+ ...memoEditorTheme,
+ EditorView.lineWrapping,
+ cmPlaceholder(placeholder),
+ tagMentionDecorations,
+ headingDecorations,
+ // tagAutocomplete must precede the editing keymap so the completion popup's
+ // Enter/Tab/arrow bindings win while it is open.
+ tagAutocomplete(getTags),
+ keymap.of([...editorKeys, indentWithTab, ...defaultKeymap, ...historyKeymap]),
+ EditorView.updateListener.of((u) => {
+ if (u.docChanged) onChange(u.state.doc.toString());
+ // Toolbar active-state depends only on the doc and selection; skip the
+ // getActiveFormats tree walk on focus/viewport/measure-only updates.
+ if (u.docChanged || u.selectionSet) onUpdate();
}),
- StyledHeading.configure({ levels: [1, 2, 3, 4, 5, 6] }),
- TaskList,
- TaskItem.configure({ nested: true }),
- TagAwareMarkdown,
- ...preservedExtensions,
- Tag,
- Mention,
];
}
diff --git a/web/src/components/MemoEditor/Editor/formatting.ts b/web/src/components/MemoEditor/Editor/formatting.ts
new file mode 100644
index 00000000..c9f1a530
--- /dev/null
+++ b/web/src/components/MemoEditor/Editor/formatting.ts
@@ -0,0 +1,138 @@
+import { syntaxTree } from "@codemirror/language";
+import type { EditorView } from "@codemirror/view";
+import {
+ type ActiveFormatState,
+ type EditorCommandContext,
+ type EditorCommandId,
+ EMPTY_ACTIVE_FORMATS,
+ type ToolbarHeadingLevel,
+} from "../formatting/commands";
+import type { FormattingController } from "../types/editorController";
+
+const MARK: Partial> = { bold: "**", italic: "*", code: "`" };
+const LINE_PREFIX: Partial> = { bulletList: "- ", orderedList: "1. ", taskList: "- [ ] " };
+
+// Enclosing syntax-tree node and the delimiter child node for each inline mark.
+// Delimiter names verified empirically against the Lezer markdown parser:
+// StrongEmphasis/Emphasis use `EmphasisMark`, InlineCode uses `CodeMark`.
+const MARK_NODES: Partial> = {
+ bold: { wrapper: "StrongEmphasis", delimiter: "EmphasisMark" },
+ italic: { wrapper: "Emphasis", delimiter: "EmphasisMark" },
+ code: { wrapper: "InlineCode", delimiter: "CodeMark" },
+};
+
+function wrapSelection(view: EditorView, token: string) {
+ const { from, to } = view.state.selection.main;
+ const sel = view.state.sliceDoc(from, to);
+ view.dispatch({
+ changes: { from, to, insert: `${token}${sel}${token}` },
+ selection: { anchor: from + token.length, head: from + token.length + sel.length },
+ });
+}
+
+/**
+ * Toggle an inline mark (bold/italic/code). When the selection head already sits
+ * inside the corresponding mark, strip the surrounding delimiter nodes instead of
+ * nesting a new pair. Deleting the actual delimiter child ranges handles the
+ * differing delimiter lengths (`**` vs `*` vs `` ` ``) automatically.
+ */
+function toggleMark(view: EditorView, command: EditorCommandId, token: string) {
+ const nodes = MARK_NODES[command];
+ if (nodes) {
+ const head = view.state.selection.main.head;
+ const tree = syntaxTree(view.state);
+ for (let n: ReturnType | null = tree.resolve(head, -1); n; n = n.parent) {
+ if (n.name !== nodes.wrapper) continue;
+ // Collect the opening and closing delimiter child node ranges.
+ const marks: { from: number; to: number }[] = [];
+ for (let child = n.firstChild; child; child = child.nextSibling) {
+ if (child.name === nodes.delimiter) marks.push({ from: child.from, to: child.to });
+ }
+ if (marks.length >= 2) {
+ const opening = marks[0];
+ const closing = marks[marks.length - 1];
+ // Delete the later range first so the earlier offsets stay valid.
+ view.dispatch({
+ changes: [
+ { from: closing.from, to: closing.to, insert: "" },
+ { from: opening.from, to: opening.to, insert: "" },
+ ],
+ });
+ return;
+ }
+ }
+ }
+ wrapSelection(view, token);
+}
+
+function toggleLinePrefix(view: EditorView, prefix: string) {
+ const line = view.state.doc.lineAt(view.state.selection.main.head);
+ const has = line.text.startsWith(prefix);
+ view.dispatch({
+ changes: has ? { from: line.from, to: line.from + prefix.length, insert: "" } : { from: line.from, insert: prefix },
+ });
+}
+
+function setHeading(view: EditorView, level: number) {
+ const line = view.state.doc.lineAt(view.state.selection.main.head);
+ const stripped = line.text.replace(/^#{1,6}\s+/, "");
+ const insert = level === 0 ? stripped : `${"#".repeat(level)} ${stripped}`;
+ view.dispatch({ changes: { from: line.from, to: line.to, insert } });
+}
+
+export function createFormattingController(view: EditorView, listeners: Set<() => void>): FormattingController {
+ return {
+ run(command: EditorCommandId, ctx?: EditorCommandContext) {
+ const mark = MARK[command];
+ if (mark) return toggleMark(view, command, mark);
+ const prefix = LINE_PREFIX[command];
+ if (prefix) return toggleLinePrefix(view, prefix);
+ if (command === "heading1") return setHeading(view, 1);
+ if (command === "heading2") return setHeading(view, 2);
+ if (command === "heading3") return setHeading(view, 3);
+ if (command === "paragraph") return setHeading(view, 0);
+ if (command === "link") {
+ const { from, to } = view.state.selection.main;
+ const sel = view.state.sliceDoc(from, to);
+ view.dispatch({ changes: { from, to, insert: `[${sel}](${ctx?.url ?? ""})` } });
+ }
+ },
+ getActiveFormats(): ActiveFormatState {
+ const pos = view.state.selection.main.head;
+ const tree = syntaxTree(view.state);
+ const active: ActiveFormatState = { ...EMPTY_ACTIVE_FORMATS };
+ for (let n: ReturnType | null = tree.resolve(pos, -1); n; n = n.parent) {
+ const name = n.name;
+ if (name === "StrongEmphasis") active.bold = true;
+ else if (name === "Emphasis") active.italic = true;
+ else if (name === "InlineCode") active.code = true;
+ else if (name === "Link") active.link = true;
+ else if (name === "BulletList") active.bulletList = true;
+ else if (name === "OrderedList") active.orderedList = true;
+ else {
+ const h = /^ATXHeading([1-6])$/.exec(name);
+ if (h) {
+ const lvl = Number(h[1]);
+ if (lvl <= 3) active.headingLevel = lvl as ToolbarHeadingLevel;
+ }
+ }
+ }
+ const line = view.state.doc.lineAt(pos).text;
+ if (/^\s*- \[[ xX]\] /.test(line)) {
+ active.taskList = true;
+ active.bulletList = false;
+ }
+ return active;
+ },
+ getSelectedText() {
+ const { from, to } = view.state.selection.main;
+ return view.state.sliceDoc(from, to);
+ },
+ subscribe(listener: () => void) {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+ },
+ };
+}
diff --git a/web/src/components/MemoEditor/Editor/headingDecorations.ts b/web/src/components/MemoEditor/Editor/headingDecorations.ts
new file mode 100644
index 00000000..177436e3
--- /dev/null
+++ b/web/src/components/MemoEditor/Editor/headingDecorations.ts
@@ -0,0 +1,27 @@
+import { RangeSetBuilder } from "@codemirror/state";
+import { Decoration, type DecorationSet, EditorView } from "@codemirror/view";
+import { viewportDecorations } from "./viewportDecorations";
+
+// A heading is a line that starts with 1-6 hashes followed by a space or tab.
+// A bare "#" or a "#tag" (no space) is intentionally NOT a heading.
+const HEADING_RE = /^(#{1,6})[ \t]/;
+
+const lineDecorations = [1, 2, 3, 4, 5, 6].map((level) => Decoration.line({ class: `cm-md-h${level}` }));
+
+function build(view: EditorView): DecorationSet {
+ const builder = new RangeSetBuilder();
+ for (const { from, to } of view.visibleRanges) {
+ const startLine = view.state.doc.lineAt(from).number;
+ const endLine = view.state.doc.lineAt(to).number;
+ for (let n = startLine; n <= endLine; n++) {
+ const line = view.state.doc.line(n);
+ const m = HEADING_RE.exec(line.text);
+ if (m) {
+ builder.add(line.from, line.from, lineDecorations[m[1].length - 1]);
+ }
+ }
+ }
+ return builder.finish();
+}
+
+export const headingDecorations = viewportDecorations(build);
diff --git a/web/src/components/MemoEditor/Editor/index.tsx b/web/src/components/MemoEditor/Editor/index.tsx
index 71049493..4b13562a 100644
--- a/web/src/components/MemoEditor/Editor/index.tsx
+++ b/web/src/components/MemoEditor/Editor/index.tsx
@@ -1,261 +1,85 @@
-import { Extension } from "@tiptap/core";
-import { Placeholder } from "@tiptap/extensions";
-import { AllSelection, Plugin, PluginKey, Selection } from "@tiptap/pm/state";
-import type { EditorProps as ProseMirrorEditorProps } from "@tiptap/pm/view";
-import { EditorContent as RichTextContent, useEditor } from "@tiptap/react";
-import { forwardRef, useEffect, useImperativeHandle, useMemo, useRef } from "react";
-import { matchPath } from "react-router-dom";
+import { EditorState } from "@codemirror/state";
+import { EditorView } from "@codemirror/view";
+import { forwardRef, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef } from "react";
import { useTagCounts } from "@/hooks/useUserQueries";
import { cn } from "@/lib/utils";
-import { ROUTES as Routes } from "@/router/routes";
import { EDITOR_HEIGHT } from "../constants";
import type { EditorController } from "../types/editorController";
-import { EDITOR_COMMANDS_BY_ID, EMPTY_ACTIVE_FORMATS, getActiveFormats } from "./editorCommands";
-import { buildExtensions } from "./extensions";
-import { createTagSuggestion } from "./TagSuggestion";
+import { createController } from "./controller";
+import "./editor.css";
+import { buildEditorExtensions } from "./extensions";
+import { createFormattingController } from "./formatting";
-// Mod-Enter is the app-wide "save memo" shortcut (useKeyboard). StarterKit's
-// HardBreak extension also binds Mod-Enter to insert a hard break, which would
-// mutate the document right before save fires. This extension swallows the
-// shortcut (returning true stops further keymap handlers) while preserving
-// DOM event bubbling — preventDefault does NOT stopPropagation, so the window-
-// level save listener in useKeyboard still receives and handles the keystroke.
-// Priority 1000 > HardBreak's default 100, so this handler runs first.
-// Shift-Enter still inserts a hard break as expected.
-const SaveShortcutPassthrough = Extension.create({
- name: "saveShortcutPassthrough",
- priority: 1000,
- addKeyboardShortcuts() {
- return {
- "Mod-Enter": () => true,
- };
- },
-});
-
-// Ctrl+A makes ProseMirror's whole-document AllSelection. Deleting it
-// (Backspace / Delete / Cut) empties the document, but AllSelection.map()
-// always returns another AllSelection — so the editor is left holding a
-// non-empty selection spanning the now-empty paragraph, which the view paints
-// as a "selected" empty block (the reported artifact). After any doc-changing
-// edit that leaves an AllSelection behind, collapse it to a caret at the start,
-// the same way deleting an ordinary text selection collapses to a cursor.
-// The `instanceof AllSelection` guard re-evaluates against the post-collapse
-// state, so the appended selection-only transaction is not re-processed.
-const CollapseAllSelectionAfterDelete = Extension.create({
- name: "collapseAllSelectionAfterDelete",
- addProseMirrorPlugins() {
- return [
- new Plugin({
- key: new PluginKey("collapseAllSelectionAfterDelete"),
- appendTransaction: (transactions, _oldState, newState) => {
- if (!transactions.some((tr) => tr.docChanged) || !(newState.selection instanceof AllSelection)) {
- return null;
- }
- return newState.tr.setSelection(Selection.atStart(newState.doc));
- },
- }),
- ];
- },
-});
-
-export interface EditorProps {
- className?: string;
+interface EditorProps {
+ className: string;
initialContent: string;
placeholder: string;
- isFocusMode?: boolean;
onContentChange: (content: string) => void;
onPaste: (event: React.ClipboardEvent) => void;
+ isFocusMode?: boolean;
}
-/**
- * The Document serializer joins/terminates blocks with `\n\n`, so e.g. a task
- * list serializes with a trailing blank line. Outer whitespace is meaningless
- * at the document level (the round-trip corpus compares modulo outer trim),
- * so every markdown string leaving this component is trimmed.
- */
-function serializeMarkdown(editor: { getMarkdown: () => string } | null): string {
- return (editor?.getMarkdown() ?? "").trim();
-}
+const Editor = forwardRef(function Editor(props: EditorProps, ref: React.ForwardedRef) {
+ const { className, initialContent, placeholder, onContentChange, onPaste, isFocusMode } = props;
+ const hostRef = useRef(null);
+ const viewRef = useRef(null);
+ const controllerRef = useRef(null);
+ const onChangeRef = useRef(onContentChange);
+ onChangeRef.current = onContentChange;
+ const listenersRef = useRef(new Set<() => void>());
+ const { data: tagData } = useTagCounts();
+ const tags = useMemo(() => Object.keys(tagData ?? {}), [tagData]);
+ const tagsRef = useRef(tags);
+ tagsRef.current = tags;
-/**
- * WYSIWYG memo editor built on ProseMirror. Markdown is the only format
- * crossing its boundary: in via setContent(contentType: "markdown"), out via
- * serializeMarkdown() on every update. IME, list continuation, input rules,
- * and auto-grow are native ProseMirror/contenteditable behavior.
- */
-const Editor = forwardRef(function Editor(props, ref) {
- const { className, initialContent, placeholder, isFocusMode, onContentChange, onPaste } = props;
-
- // Last markdown emitted through onContentChange, so the sync effect can
- // recognize the parent echoing our own value back without re-serializing.
- const lastEmittedRef = useRef(null);
- // Stable across editor re-creation so the toolbar can subscribe once. The
- // effect below binds the live editor's transaction/selection events to it.
- const activeListenersRef = useRef(new Set<() => void>());
- // Read through refs so the memoized extension/editorProps closures below
- // always see the latest props (Placeholder decorations recompute per
- // transaction; handlePaste resolves per event).
- const placeholderRef = useRef(placeholder);
- placeholderRef.current = placeholder;
- const onPasteRef = useRef(onPaste);
- onPasteRef.current = onPaste;
-
- // On the explore page suggestions include all users' tags; otherwise the
- // current user's.
- const isExplorePage = useMemo(() => Boolean(matchPath(Routes.EXPLORE, window.location.pathname)), []);
- const { data: tagCount = {} } = useTagCounts(!isExplorePage);
- const sortedTags = useMemo(
- () =>
- Object.entries(tagCount)
- .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
- .map(([tag]) => tag),
- [tagCount],
- );
- const tagsRef = useRef([]);
- tagsRef.current = sortedTags;
-
- // Stable option identities so useEditor's compareOptions stays equal across
- // renders and the editor skips a needless setOptions/view.setProps pass per
- // keystroke. All dynamic values reach the closures through refs above.
- // `content` is only consumed at editor creation — later external changes
- // flow through the sync effect — so the mount-time value is frozen too.
- const mountContentRef = useRef(initialContent);
- const extensions = useMemo(
- () => [
- ...buildExtensions(),
- Placeholder.configure({ placeholder: () => placeholderRef.current }),
- createTagSuggestion({ getTags: () => tagsRef.current }),
- SaveShortcutPassthrough,
- CollapseAllSelectionAfterDelete,
- ],
- [],
- );
- const editorProps = useMemo(
- () => ({
- attributes: {
- class: "memo-wysiwyg outline-none w-full text-base break-words min-h-6",
- },
- handlePaste: (_view, event) => {
- const hasFiles = Array.from(event.clipboardData?.items ?? []).some((item) => item.kind === "file");
- if (hasFiles) {
- onPasteRef.current(event as unknown as React.ClipboardEvent);
- return true;
- }
- // Text paste (incl. URL-over-selection → link) is handled natively.
- return false;
- },
- }),
- [],
- );
-
- const editor = useEditor({
- extensions,
- content: mountContentRef.current,
- contentType: "markdown",
- editorProps,
- onUpdate: ({ editor: currentEditor }) => {
- const markdown = serializeMarkdown(currentEditor);
- lastEmittedRef.current = markdown;
- onContentChange(markdown);
- },
- });
-
- // Sync external content changes (e.g. reset after save, draft restore)
- // without clobbering the document the user is typing into: only apply when
- // the markdown actually differs.
- useEffect(() => {
- if (!editor) {
- return;
- }
- // Parent echo of our own emission — nothing to sync (O(1) fast path).
- // Comparing against the live document instead would race: a keystroke
- // landing between the emission and this passive effect would make the
- // echo look like an external change and clobber the keystroke/cursor.
- if (initialContent === lastEmittedRef.current) {
- return;
- }
- // Never clobber an in-progress IME composition.
- if (editor.view.composing) {
- return;
- }
- if (serializeMarkdown(editor) !== initialContent.trim()) {
- editor.commands.setContent(initialContent, { contentType: "markdown", emitUpdate: false });
- // A subsequent identical echo of this value is also a no-op.
- lastEmittedRef.current = initialContent;
- }
- }, [initialContent, editor]);
-
- // Fan editor transactions out to toolbar subscribers so active-state
- // highlighting tracks the cursor live. Every change — including a pure
- // selection move — is a transaction, so this single event covers both.
- useEffect(() => {
- if (!editor) {
- return;
- }
- const notify = () => activeListenersRef.current.forEach((listener) => listener());
- editor.on("transaction", notify);
+ // useLayoutEffect (not useEffect) so the EditorView — and its placeholder —
+ // mount before the browser paints. With useEffect the first painted frame
+ // shows an empty host, then the placeholder pops in (a load flicker).
+ useLayoutEffect(() => {
+ if (!hostRef.current) return;
+ const view = new EditorView({
+ state: EditorState.create({
+ doc: initialContent,
+ extensions: buildEditorExtensions({
+ placeholder,
+ onChange: (md) => onChangeRef.current(md),
+ onUpdate: () => listenersRef.current.forEach((l) => l()),
+ getTags: () => tagsRef.current,
+ }),
+ }),
+ parent: hostRef.current,
+ });
+ viewRef.current = view;
+ controllerRef.current = createController(view, createFormattingController(view, listenersRef.current));
return () => {
- editor.off("transaction", notify);
+ view.destroy();
+ viewRef.current = null;
+ controllerRef.current = null;
};
- }, [editor]);
+ // Mount once; external sync handled below.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
- useImperativeHandle(
- ref,
- (): EditorController => ({
- focus: () => editor?.commands.focus(),
- hasFocus: () => editor?.isFocused ?? false,
- // Contract: whitespace-only counts as empty. The editor's structural
- // `editor.isEmpty` would call a paragraph of spaces non-empty.
- isEmpty: () => serializeMarkdown(editor) === "",
- getMarkdown: () => serializeMarkdown(editor),
- setMarkdown: (markdown) => editor?.commands.setContent(markdown, { contentType: "markdown" }),
- insertMarkdown: (markdown) => editor?.chain().focus().insertContent(markdown, { contentType: "markdown" }).run(),
- scrollToCursor: () => editor?.commands.scrollIntoView(),
- selectAll: () => editor?.commands.selectAll(),
- // WYSIWYG supports rich formatting; the whole surface is driven by the
- // shared command catalog (editorCommands.ts), so adding a verb there
- // flows here — and to the toolbar and active-state — with no edit here.
- formatting: {
- run: (command, ctx) => {
- if (editor) {
- EDITOR_COMMANDS_BY_ID[command]?.run(editor, ctx);
- }
- },
- getActiveFormats: () => (editor ? getActiveFormats(editor) : EMPTY_ACTIVE_FORMATS),
- getSelectedText: () => {
- if (!editor) {
- return "";
- }
- const { from, to } = editor.state.selection;
- return editor.state.doc.textBetween(from, to, " ");
- },
- subscribe: (listener) => {
- activeListenersRef.current.add(listener);
- return () => {
- activeListenersRef.current.delete(listener);
- };
- },
- },
- }),
- [editor],
- );
+ useEffect(() => {
+ const view = viewRef.current;
+ if (!view) return;
+ if (view.state.doc.toString() === initialContent) return;
+ view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: initialContent } });
+ }, [initialContent]);
+
+ // The controller is created in the mount layout effect above, which runs
+ // before this (also layout-phase) handle, so controllerRef.current is set.
+ useImperativeHandle(ref, () => controllerRef.current as EditorController, []);
return (
{
- // In focus mode the wrapper extends below the content; a click on the
- // empty area should land the caret at the end instead of doing nothing.
- if (event.target === event.currentTarget) {
- editor?.commands.focus("end");
- }
- }}
>
-
+
);
});
diff --git a/web/src/components/MemoEditor/Editor/listIndent.ts b/web/src/components/MemoEditor/Editor/listIndent.ts
new file mode 100644
index 00000000..21df239a
--- /dev/null
+++ b/web/src/components/MemoEditor/Editor/listIndent.ts
@@ -0,0 +1,119 @@
+import type { Text } from "@codemirror/state";
+import type { EditorView } from "@codemirror/view";
+
+// A list item line: leading whitespace + bullet (-, *, +) or ordered marker
+// (1. / 1)) + at least one space.
+const LIST_ITEM = /^(\s*)(?:[-*+]|\d+[.)])\s/;
+const ORDERED_ITEM = /^(\s*)(\d+)([.)])(\s+)(.*)$/;
+// The full marker prefix (indent + marker + trailing spaces); its length is the
+// column where the item's content — and therefore a nested child — begins.
+const LIST_PREFIX = /^\s*(?:[-*+]|\d+[.)])\s+/;
+
+const leadingWhitespace = (text: string): number => text.length - text.trimStart().length;
+
+function selectedLineNumbers(view: EditorView): number[] {
+ const { doc, selection } = view.state;
+ const nums = new Set();
+ for (const range of selection.ranges) {
+ for (let n = doc.lineAt(range.from).number; n <= doc.lineAt(range.to).number; n++) {
+ nums.add(n);
+ }
+ }
+ return [...nums];
+}
+
+/** Preceding lines, nearest first, stopping at the first blank line (list end). */
+function* previousListLines(doc: Text, from: number): Generator<{ text: string; indent: number }> {
+ for (let p = from - 1; p >= 1; p--) {
+ const { text } = doc.line(p);
+ if (text.trim() === "") return;
+ yield { text, indent: leadingWhitespace(text) };
+ }
+}
+
+/**
+ * The number an ordered item should take at `indent`: one more than the nearest
+ * preceding sibling ordered item at the same indent, else 1 (first child of a
+ * new sublist). CommonMark only nests an ordered sublist whose first item is
+ * `1.`, so renumbering — not just re-indenting — is what makes a nested ordered
+ * list actually render as nested.
+ */
+function nextOrderedNumber(doc: Text, lineNumber: number, indent: number): number {
+ for (const prev of previousListLines(doc, lineNumber)) {
+ if (prev.indent < indent) break; // reached the parent
+ if (prev.indent === indent) {
+ const ordered = ORDERED_ITEM.exec(prev.text);
+ return ordered ? Number.parseInt(ordered[2], 10) + 1 : 1;
+ }
+ // deeper line — part of a sibling's subtree; keep scanning up
+ }
+ return 1;
+}
+
+/** Rewrite a list line to a new indent, renumbering it if it is an ordered item. */
+function reindented(doc: Text, lineNumber: number, text: string, indent: number): string {
+ const ordered = ORDERED_ITEM.exec(text);
+ if (ordered) {
+ const [, , , delimiter, spaces, content] = ordered;
+ return `${" ".repeat(indent)}${nextOrderedNumber(doc, lineNumber, indent)}${delimiter}${spaces}${content}`;
+ }
+ return " ".repeat(indent) + text.slice(leadingWhitespace(text));
+}
+
+/**
+ * Tab on a list item: nest it under the preceding item by aligning its indent to
+ * that item's content column (past the marker) and renumbering ordered items so
+ * the nested list is CommonMark-valid. Returns false when not on a list item so
+ * the caller's default Tab (plain indent) applies.
+ */
+export function sinkListItem(view: EditorView): boolean {
+ const { doc } = view.state;
+ const changes: { from: number; to: number; insert: string }[] = [];
+ for (const n of selectedLineNumbers(view)) {
+ const line = doc.line(n);
+ const match = LIST_ITEM.exec(line.text);
+ if (!match) return false;
+ const indent = match[1].length;
+ let target = indent + 2; // fallback when there is no item to nest under
+ for (const prev of previousListLines(doc, n)) {
+ if (prev.indent > indent) continue; // deeper subtree — skip past it
+ const prevPrefix = LIST_PREFIX.exec(prev.text);
+ if (prevPrefix) target = prevPrefix[0].length;
+ break;
+ }
+ if (target > indent) {
+ changes.push({ from: line.from, to: line.to, insert: reindented(doc, n, line.text, target) });
+ }
+ }
+ if (changes.length === 0) return false;
+ view.dispatch({ changes, userEvent: "input.indent" });
+ return true;
+}
+
+/**
+ * Shift-Tab on a list item: outdent it to its parent's indent (or the margin),
+ * renumbering ordered items for the new level. Returns false when not on an
+ * indented list item so the default outdent applies.
+ */
+export function liftListItem(view: EditorView): boolean {
+ const { doc } = view.state;
+ const changes: { from: number; to: number; insert: string }[] = [];
+ for (const n of selectedLineNumbers(view)) {
+ const line = doc.line(n);
+ const match = LIST_ITEM.exec(line.text);
+ if (!match) return false;
+ const indent = match[1].length;
+ if (indent === 0) return false;
+ let target = 0;
+ for (const prev of previousListLines(doc, n)) {
+ if (prev.indent < indent) {
+ target = LIST_ITEM.test(prev.text) ? prev.indent : 0;
+ break;
+ }
+ }
+ changes.push({ from: line.from, to: line.to, insert: reindented(doc, n, line.text, target) });
+ }
+ if (changes.length === 0) return false;
+ view.dispatch({ changes, userEvent: "delete.dedent" });
+ return true;
+}
diff --git a/web/src/components/MemoEditor/Editor/markdownCodec.ts b/web/src/components/MemoEditor/Editor/markdownCodec.ts
deleted file mode 100644
index 27086f6d..00000000
--- a/web/src/components/MemoEditor/Editor/markdownCodec.ts
+++ /dev/null
@@ -1,70 +0,0 @@
-import { Editor, type JSONContent } from "@tiptap/core";
-import { buildExtensions } from "./extensions";
-
-/**
- * Headless markdown ⇄ ProseMirror document helpers built on the exact same
- * extension list as the live editor. Used by the round-trip corpus tests and
- * the memo-open load guard.
- *
- * WHY A SINGLETON:
- * `@tiptap/markdown`'s MarkdownManager registers each extension's
- * `markdownTokenizer` onto the global `marked` singleton via `marked.use(...)`
- * inside every `new Editor(...)` construction, and `editor.destroy()` never
- * unregisters those tokenizers. `@tiptap/extension-list` ships 2 block
- * tokenizers, so every per-call editor construction leaks 2 registrations onto
- * the global marked instance. The resulting accumulation causes parse time to
- * degrade measurably (observed: ~0.7 s → 14.5 s over ~120 calls). The
- * preserved-syntax bridges (PreservedBlock.ts) add more custom tokenizers per
- * Editor construction — each live editor mount registers them globally too —
- * so the codec singleton keeps the tests/load-guard pinned at one registration.
- *
- * WHY NOT `Markdown.configure({ marked: new Marked() })`:
- * Upstream `MarkdownManager.createLexer()` calls
- * `new this.markedInstance.Lexer()` without passing the options object that
- * carries the instance-registered tokenizer extensions, so any tokenizers
- * registered on the private Marked instance are silently ignored. Task-list
- * syntax breaks: `- [ ] open` round-trips to `- open`.
- *
- * The singleton is created lazily on first use and reused forever.
- */
-let _singletonEditor: Editor | null = null;
-
-function getSingletonEditor(): Editor {
- if (!_singletonEditor) {
- _singletonEditor = new Editor({
- extensions: buildExtensions(),
- content: "",
- contentType: "markdown",
- });
- }
- return _singletonEditor;
-}
-
-function getMarkdownManager() {
- const editor = getSingletonEditor();
- if (!editor.markdown) {
- throw new Error("markdownCodec: editor.markdown is not available — ensure @tiptap/markdown is in the extension list");
- }
- return editor.markdown;
-}
-
-export function parseMarkdown(markdown: string): JSONContent {
- return getMarkdownManager().parse(markdown);
-}
-
-export function roundTripMarkdown(markdown: string): string {
- const manager = getMarkdownManager();
- return manager.serialize(manager.parse(markdown));
-}
-
-/** True when a serialize cycle would not change the document's meaning. */
-export function isLosslessRoundTrip(markdown: string): boolean {
- try {
- const manager = getMarkdownManager();
- const once = manager.parse(markdown);
- const twice = manager.parse(manager.serialize(once));
- return JSON.stringify(once) === JSON.stringify(twice);
- } catch {
- return false;
- }
-}
diff --git a/web/src/components/MemoEditor/Editor/suggestionExtension.ts b/web/src/components/MemoEditor/Editor/suggestionExtension.ts
deleted file mode 100644
index fec95d7a..00000000
--- a/web/src/components/MemoEditor/Editor/suggestionExtension.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-import { Extension } from "@tiptap/core";
-import { PluginKey } from "@tiptap/pm/state";
-import Suggestion, { type SuggestionOptions } from "@tiptap/suggestion";
-import type { ReactNode } from "react";
-import { createSuggestionRenderer } from "./suggestionMenu";
-
-/**
- * Everything a single `@tiptap/suggestion` trigger needs, minus the boilerplate
- * (the Extension wrapper, the PluginKey, and the React popup renderer). Each
- * trigger — `#` tags today, `/` commands or `@` mentions tomorrow — is now a
- * small config object instead of a hand-wired extension.
- */
-export interface SuggestionExtensionConfig {
- /** Unique extension + plugin-key name, e.g. "tagSuggestion". */
- name: string;
- /** The character that opens the popup, e.g. "#" or "/". */
- char: string;
- /** Whether a space inside the query keeps the popup open. Defaults to false. */
- allowSpaces?: boolean;
- /** Resolve the items to show for the current query (already stripped of `char`). */
- items: (query: string) => T[];
- /** Apply the chosen item to the document. */
- command: SuggestionOptions["command"];
- /** Render a single item row. */
- renderItem: (item: T, isSelected: boolean) => ReactNode;
- /** Stable React key for an item. */
- getItemKey: (item: T) => string;
-}
-
-/**
- * Build a Tiptap extension that shows the shared suggestion popup when `char`
- * is typed. Mirrors the original hand-written TagSuggestion exactly; it just
- * factors out the parts every trigger repeats so adding another is ~10 lines.
- */
-export function createSuggestionExtension(config: SuggestionExtensionConfig): Extension {
- return Extension.create({
- name: config.name,
-
- addProseMirrorPlugins() {
- return [
- Suggestion({
- editor: this.editor,
- pluginKey: new PluginKey(config.name),
- char: config.char,
- allowSpaces: config.allowSpaces ?? false,
- items: ({ query }) => config.items(query),
- command: config.command,
- render: createSuggestionRenderer({
- renderItem: config.renderItem,
- getItemKey: config.getItemKey,
- }),
- }),
- ];
- },
- });
-}
diff --git a/web/src/components/MemoEditor/Editor/suggestionMenu.tsx b/web/src/components/MemoEditor/Editor/suggestionMenu.tsx
deleted file mode 100644
index 3cf955f0..00000000
--- a/web/src/components/MemoEditor/Editor/suggestionMenu.tsx
+++ /dev/null
@@ -1,194 +0,0 @@
-import { ReactRenderer } from "@tiptap/react";
-import type { SuggestionKeyDownProps, SuggestionOptions, SuggestionProps } from "@tiptap/suggestion";
-import {
- type ForwardRefExoticComponent,
- forwardRef,
- type PropsWithoutRef,
- type ReactElement,
- type ReactNode,
- type RefAttributes,
- useEffect,
- useImperativeHandle,
- useRef,
- useState,
-} from "react";
-import { cn } from "@/lib/utils";
-
-export interface SuggestionMenuHandle {
- onKeyDown: (props: SuggestionKeyDownProps) => boolean;
-}
-
-interface SuggestionMenuProps {
- items: T[];
- command: (item: T) => void;
- renderItem: (item: T, isSelected: boolean) => ReactNode;
- getItemKey: (item: T) => string;
-}
-
-// Floating popup chrome shared by every suggestion trigger (tags today, more later).
-const MENU_STYLES = {
- container:
- "z-50 p-1 max-w-48 max-h-60 rounded border bg-popover text-popover-foreground shadow-lg font-mono flex flex-col overflow-y-auto overflow-x-hidden",
- item: "rounded p-1 px-2 w-full text-sm cursor-pointer transition-colors select-none hover:bg-accent hover:text-accent-foreground",
-};
-
-function SuggestionMenuInner(
- { items, command, renderItem, getItemKey }: SuggestionMenuProps,
- ref: React.ForwardedRef,
-) {
- const [selectedIndex, setSelectedIndex] = useState(0);
- // Keep a ref so the imperative onKeyDown handler always reads the latest
- // selected index even between React batched renders (e.g. Arrow then Enter
- // in the same synchronous tick in tests).
- const selectedIndexRef = useRef(selectedIndex);
- selectedIndexRef.current = selectedIndex;
-
- // Ref assigned to the currently-highlighted item so we can scroll it into
- // view when arrow navigation moves the highlight off-screen.
- const selectedItemRef = useRef(null);
-
- useEffect(() => {
- setSelectedIndex(0);
- selectedIndexRef.current = 0;
- }, [items]);
-
- // Scroll the highlighted item into view whenever it changes.
- useEffect(() => {
- selectedItemRef.current?.scrollIntoView?.({ block: "nearest" });
- }, [selectedIndex]);
-
- useImperativeHandle(
- ref,
- () => ({
- onKeyDown: ({ event }) => {
- if (items.length === 0) {
- return false;
- }
- if (event.key === "ArrowDown") {
- const next = (selectedIndexRef.current + 1) % items.length;
- selectedIndexRef.current = next;
- setSelectedIndex(next);
- return true;
- }
- if (event.key === "ArrowUp") {
- const prev = (selectedIndexRef.current - 1 + items.length) % items.length;
- selectedIndexRef.current = prev;
- setSelectedIndex(prev);
- return true;
- }
- if (event.key === "Enter" || event.key === "Tab") {
- command(items[selectedIndexRef.current]);
- return true;
- }
- return false;
- },
- }),
- [items, command],
- );
-
- if (items.length === 0) {
- return null;
- }
-
- return (
-
- );
-}
-
-export const SuggestionMenu = forwardRef(SuggestionMenuInner) as (
- props: SuggestionMenuProps & { ref?: React.ForwardedRef },
-) => ReactElement | null;
-
-/**
- * Builds the Suggestion-plugin `render` lifecycle: mounts SuggestionMenu in a
- * floating container positioned at the trigger's caret rect. No tippy —
- * a plain absolutely-positioned element on document.body.
- */
-export function createSuggestionRenderer(menu: {
- renderItem: (item: T, isSelected: boolean) => ReactNode;
- getItemKey: (item: T) => string;
-}): SuggestionOptions["render"] {
- return () => {
- let renderer: ReactRenderer | null = null;
- let container: HTMLDivElement | null = null;
- // Unsubscribes the editor blur listener; null once run (idempotent destroy).
- let removeBlurListener: (() => void) | null = null;
-
- const reposition = (props: SuggestionProps) => {
- const rect = props.clientRect?.();
- if (!rect || !container) {
- return;
- }
- container.style.left = `${rect.left + window.scrollX}px`;
- container.style.top = `${rect.bottom + window.scrollY + 4}px`;
- };
-
- const destroy = () => {
- removeBlurListener?.();
- removeBlurListener = null;
- renderer?.destroy();
- container?.remove();
- renderer = null;
- container = null;
- };
-
- const menuProps = (props: SuggestionProps) => ({
- items: props.items,
- command: props.command,
- renderItem: menu.renderItem,
- getItemKey: menu.getItemKey,
- });
-
- return {
- onStart: (props) => {
- // SuggestionMenu is a generic forwardRef component; the ReactRenderer
- // constructor expects a concrete ComponentType. We cast via
- // top-level type imports for readability (runtime shape is correct).
- type MenuProps = ReturnType;
- renderer = new ReactRenderer(
- SuggestionMenu as unknown as ForwardRefExoticComponent & RefAttributes>,
- {
- props: menuProps(props),
- editor: props.editor,
- },
- );
- container = document.createElement("div");
- container.style.position = "absolute";
- container.style.zIndex = "50";
- container.appendChild(renderer.element);
- document.body.appendChild(container);
- reposition(props);
- // Hide the popup when the editor loses focus so it doesn't linger.
- const handleBlur = () => destroy();
- props.editor.on("blur", handleBlur);
- removeBlurListener = () => props.editor.off("blur", handleBlur);
- },
- onUpdate: (props) => {
- renderer?.updateProps(menuProps(props));
- reposition(props);
- },
- onKeyDown: (props) => {
- if (props.event.key === "Escape") {
- destroy();
- return true;
- }
- return renderer?.ref?.onKeyDown(props) ?? false;
- },
- onExit: destroy,
- };
- };
-}
diff --git a/web/src/components/MemoEditor/Editor/tagAutocomplete.ts b/web/src/components/MemoEditor/Editor/tagAutocomplete.ts
new file mode 100644
index 00000000..91770f43
--- /dev/null
+++ b/web/src/components/MemoEditor/Editor/tagAutocomplete.ts
@@ -0,0 +1,25 @@
+import { autocompletion, type CompletionContext, type CompletionResult } from "@codemirror/autocomplete";
+import type { Extension } from "@codemirror/state";
+import { TAG_CHAR_CLASS } from "@/utils/tag-grammar";
+
+const TAG_BEFORE = new RegExp(`#(${TAG_CHAR_CLASS}*)$`, "u");
+
+export function makeTagCompletionSource(getTags: () => string[]) {
+ return (ctx: CompletionContext): CompletionResult | null => {
+ const before = ctx.matchBefore(TAG_BEFORE);
+ if (!before || (before.from === before.to && !ctx.explicit)) return null;
+ const typed = before.text.slice(1).toLowerCase();
+ // Require at least one character after `#` unless completion was explicitly
+ // invoked, so a bare `#` doesn't pop the menu while typing.
+ if (typed.length < 1 && !ctx.explicit) return null;
+ const options = getTags()
+ .filter((tag) => tag.toLowerCase().startsWith(typed))
+ .map((tag) => ({ label: tag, type: "keyword" }));
+ if (options.length === 0) return null;
+ return { from: before.from + 1, options };
+ };
+}
+
+export function tagAutocomplete(getTags: () => string[]): Extension {
+ return autocompletion({ override: [makeTagCompletionSource(getTags)] });
+}
diff --git a/web/src/components/MemoEditor/Editor/tagMarkdown.ts b/web/src/components/MemoEditor/Editor/tagMarkdown.ts
deleted file mode 100644
index eedfe463..00000000
--- a/web/src/components/MemoEditor/Editor/tagMarkdown.ts
+++ /dev/null
@@ -1,113 +0,0 @@
-import type { JSONContent } from "@tiptap/core";
-import { Markdown } from "@tiptap/markdown";
-import type { Schema } from "@tiptap/pm/model";
-import { TAG_RUN } from "@/utils/tag-grammar";
-
-// A `#` begins a memo tag when a capped TAG_RUN follows it — the same grammar
-// the editor tokenizer (Tag.ts) matches, so escape and parse can't disagree.
-// The lookahead matches only the `#`, leaving the run itself untouched.
-const TAG_HASH = new RegExp(`#(?=${TAG_RUN})`, "gu");
-
-/**
- * Backslash-escape a `#` that would otherwise re-parse into a `#tag`.
- *
- * memos layers hashtag syntax on top of CommonMark, so — exactly as
- * prosemirror-markdown escapes inline syntax characters like `*` and `_` —
- * plain text that looks like a tag must be escaped on serialize, or it silently
- * becomes a tag on the next parse.
- */
-export function escapeTagHashes(text: string): string {
- return text.replace(TAG_HASH, "\\#");
-}
-
-type JsonMark = string | { type?: string };
-type JsonNode = { type?: string; marks?: JsonMark[] };
-type PatchableManager = {
- encodeTextForMarkdown?: (text: string, node: JsonNode, parentNode?: JsonNode) => string;
- parse?: (markdown: string) => JSONContent;
-};
-
-const markName = (mark: JsonMark): string => (typeof mark === "string" ? mark : (mark.type ?? ""));
-const hasMark = (node: JsonNode, name: string): boolean => (node.marks ?? []).some((mark) => markName(mark) === name);
-
-/**
- * A `#tag` only forms in plain inline prose. The tokenizer declines inside
- * links, and `code: true` marks/nodes (the Tag mark itself, inline code,
- * preserved spans/blocks, code blocks) serialize verbatim — so escaping a `#`
- * in any of those contexts would be wrong (and would corrupt the byte-identical
- * round-trips those constructs rely on).
- */
-function escapesTagsHere(schema: Schema, node: JsonNode, parentNode?: JsonNode): boolean {
- for (const mark of node.marks ?? []) {
- const name = markName(mark);
- if (name === "link") {
- return false;
- }
- if (schema.marks[name]?.spec.code) {
- return false;
- }
- }
- const parentType = parentNode?.type;
- if (parentType && schema.nodes[parentType]?.spec.code) {
- return false;
- }
- return true;
-}
-
-/**
- * Strip the `tag` mark from any text that also carries a `link` mark.
- *
- * The `markdownTokenizer` in Tag.ts cannot tell it is inside a link label — the
- * manager forwards only `{ inlineTokens, blockTokens }`, never the lexer's
- * `inLink` state — so `[see #x](url)` parses with `#x` tagged. We undo that as a
- * tree pass, the same way the read-only renderer (remark-tag) skips link nodes,
- * keeping the editor and renderer in agreement: a `#` in a link label is link
- * text, never a tag pill.
- */
-function stripTagInsideLinks(node: JSONContent): JSONContent {
- if (Array.isArray(node.marks) && hasMark(node, "link")) {
- node.marks = node.marks.filter((mark) => markName(mark) !== "tag");
- }
- node.content?.forEach(stripTagInsideLinks);
- return node;
-}
-
-/**
- * The `markdownTokenizer` in Tag.ts handles `#tag` the canonical
- * @tiptap/markdown way, but two memos-specific concerns sit above the tokenizer
- * and have no public hook, so we compose them onto the manager here:
- *
- * - serialize: escape a tag-shaped `#` in plain prose ({@link escapeTagHashes})
- * so a literal `#NAS` can't silently re-parse into a tag;
- * - parse: skip tags inside link labels ({@link stripTagInsideLinks}).
- *
- * Escapes stay a purely lexical concern — the document model carries no
- * "escaped tag" node or mark. A literal `#NAS` is just text: parsing strips a
- * leading `\` (marked's built-in escape) and serializing adds it back, the same
- * way TipTap handles every other escapable character.
- */
-export const TagAwareMarkdown = Markdown.extend({
- onBeforeCreate(props) {
- this.parent?.(props);
- const { editor } = this;
- const manager = editor.markdown as unknown as PatchableManager | undefined;
- if (!manager) {
- return;
- }
-
- const encode = manager.encodeTextForMarkdown;
- if (typeof encode === "function") {
- const bound = encode.bind(manager);
- manager.encodeTextForMarkdown = (text, node, parentNode) => {
- const encoded = bound(text, node, parentNode);
- return escapesTagsHere(editor.schema, node, parentNode) ? escapeTagHashes(encoded) : encoded;
- };
- }
-
- const parse = manager.parse;
- if (typeof parse === "function") {
- const bound = parse.bind(manager);
- manager.parse = (markdown) => stripTagInsideLinks(bound(markdown));
- }
- },
-});
diff --git a/web/src/components/MemoEditor/Editor/tagMentionDecorations.ts b/web/src/components/MemoEditor/Editor/tagMentionDecorations.ts
new file mode 100644
index 00000000..dc318ddb
--- /dev/null
+++ b/web/src/components/MemoEditor/Editor/tagMentionDecorations.ts
@@ -0,0 +1,34 @@
+import { RangeSetBuilder } from "@codemirror/state";
+import { Decoration, type DecorationSet, EditorView } from "@codemirror/view";
+import { MENTION_RUN } from "@/utils/mention-grammar";
+import { TAG_RUN } from "@/utils/tag-grammar";
+import { viewportDecorations } from "./viewportDecorations";
+
+const TAG_RE = new RegExp(`(^|[^\\p{L}\\p{N}])#(${TAG_RUN})`, "gu");
+const MENTION_RE = new RegExp(`(^|[^A-Za-z0-9])@(${MENTION_RUN})`, "gu");
+const tagMark = Decoration.mark({ class: "cm-memo-tag" });
+const mentionMark = Decoration.mark({ class: "cm-memo-mention" });
+
+function build(view: EditorView): DecorationSet {
+ const ranges: { from: number; to: number; deco: Decoration }[] = [];
+ for (const { from, to } of view.visibleRanges) {
+ const text = view.state.doc.sliceString(from, to);
+ for (const [re, deco] of [
+ [TAG_RE, tagMark],
+ [MENTION_RE, mentionMark],
+ ] as const) {
+ re.lastIndex = 0;
+ let m: RegExpExecArray | null;
+ while ((m = re.exec(text)) !== null) {
+ const start = from + m.index + m[1].length; // skip the boundary char
+ ranges.push({ from: start, to: start + 1 + m[2].length, deco });
+ }
+ }
+ }
+ ranges.sort((a, b) => a.from - b.from || a.to - b.to);
+ const builder = new RangeSetBuilder();
+ for (const r of ranges) builder.add(r.from, r.to, r.deco);
+ return builder.finish();
+}
+
+export const tagMentionDecorations = viewportDecorations(build);
diff --git a/web/src/components/MemoEditor/Editor/theme.ts b/web/src/components/MemoEditor/Editor/theme.ts
new file mode 100644
index 00000000..18589659
--- /dev/null
+++ b/web/src/components/MemoEditor/Editor/theme.ts
@@ -0,0 +1,23 @@
+import { syntaxHighlighting } from "@codemirror/language";
+import { tags as t, tagHighlighter } from "@lezer/highlight";
+
+/**
+ * Map markdown syntax tokens to stable class names. ALL visual styling lives in
+ * plain CSS (the `.memo-editor-content` block in `src/index.css`) so the editor
+ * is themed like the rest of the app — Tailwind/theme tokens in a stylesheet —
+ * rather than a CodeMirror CSS-in-JS theme object. Headings (`.cm-md-h*`) and
+ * `#tag`/`@mention` (`.cm-memo-*`) classes come from the decoration plugins;
+ * the rest of the `.cm-*` chrome is CodeMirror's own and is styled in that CSS.
+ */
+const markdownHighlighter = tagHighlighter([
+ { tag: t.strong, class: "cm-md-strong" },
+ { tag: t.emphasis, class: "cm-md-emphasis" },
+ { tag: t.strikethrough, class: "cm-md-strike" },
+ { tag: t.monospace, class: "cm-md-code" },
+ { tag: t.link, class: "cm-md-link" },
+ { tag: t.url, class: "cm-md-url" },
+ { tag: t.quote, class: "cm-md-quote" },
+ { tag: [t.processingInstruction, t.meta, t.contentSeparator], class: "cm-md-mark" },
+]);
+
+export const memoEditorTheme = [syntaxHighlighting(markdownHighlighter)];
diff --git a/web/src/components/MemoEditor/Editor/viewportDecorations.ts b/web/src/components/MemoEditor/Editor/viewportDecorations.ts
new file mode 100644
index 00000000..78ec7f29
--- /dev/null
+++ b/web/src/components/MemoEditor/Editor/viewportDecorations.ts
@@ -0,0 +1,23 @@
+import { type DecorationSet, EditorView, ViewPlugin, type ViewUpdate } from "@codemirror/view";
+
+/**
+ * A ViewPlugin that maintains viewport-scoped decorations, rebuilding when the
+ * document or viewport changes. Shared by the tag/mention and heading
+ * decoration plugins, which differ only in their `build` function.
+ */
+export function viewportDecorations(build: (view: EditorView) => DecorationSet) {
+ return ViewPlugin.fromClass(
+ class {
+ decorations: DecorationSet;
+ constructor(view: EditorView) {
+ this.decorations = build(view);
+ }
+ update(u: ViewUpdate) {
+ if (u.docChanged || u.viewportChanged) {
+ this.decorations = build(u.view);
+ }
+ }
+ },
+ { decorations: (v) => v.decorations },
+ );
+}
diff --git a/web/src/components/MemoEditor/PlainEditor/index.tsx b/web/src/components/MemoEditor/PlainEditor/index.tsx
deleted file mode 100644
index 86ec3a1e..00000000
--- a/web/src/components/MemoEditor/PlainEditor/index.tsx
+++ /dev/null
@@ -1,198 +0,0 @@
-import { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef } from "react";
-import getCaretCoordinates from "textarea-caret";
-import { cn } from "@/lib/utils";
-import { EDITOR_HEIGHT } from "../constants";
-import type { EditorController } from "../types/editorController";
-
-interface PlainEditorProps {
- className: string;
- initialContent: string;
- placeholder: string;
- onContentChange: (content: string) => void;
- onPaste: (event: React.ClipboardEvent) => void;
- isFocusMode?: boolean;
-}
-
-// Low-level string-surgery handle over the textarea. Internal to this file —
-// outside callers only ever see the EditorController exposed via the ref.
-interface TextareaActions {
- getEditor: () => HTMLTextAreaElement | null;
- focus: () => void;
- scrollToCursor: () => void;
- insertText: (text: string, prefix?: string, suffix?: string) => void;
- setContent: (text: string) => void;
- getContent: () => string;
- getCursorPosition: () => number;
- setCursorPosition: (startPos: number, endPos?: number) => void;
-}
-
-const PlainEditor = forwardRef(function PlainEditor(props: PlainEditorProps, ref: React.ForwardedRef) {
- const { className, initialContent, placeholder, onPaste, onContentChange: handleContentChangeCallback, isFocusMode } = props;
- const editorRef = useRef(null);
-
- const updateEditorHeight = useCallback(() => {
- if (editorRef.current) {
- editorRef.current.style.height = "auto";
- editorRef.current.style.height = `${editorRef.current.scrollHeight ?? 0}px`;
- }
- }, []);
-
- const updateContent = useCallback(() => {
- if (editorRef.current) {
- handleContentChangeCallback(editorRef.current.value);
- updateEditorHeight();
- }
- }, [handleContentChangeCallback, updateEditorHeight]);
-
- const scrollToCaret = useCallback((options: { force?: boolean } = {}) => {
- const editor = editorRef.current;
- if (!editor) return;
-
- const { force = false } = options;
- const caret = getCaretCoordinates(editor, editor.selectionEnd);
-
- if (force) {
- editor.scrollTop = Math.max(0, caret.top - editor.clientHeight / 2);
- return;
- }
-
- const lineHeight = parseFloat(getComputedStyle(editor).lineHeight) || 24;
- const viewportBottom = editor.scrollTop + editor.clientHeight;
- // Scroll if cursor is near or beyond bottom edge (within 2 lines)
- if (caret.top + lineHeight * 2 > viewportBottom) {
- editor.scrollTop = Math.max(0, caret.top - editor.clientHeight / 2);
- }
- }, []);
-
- useEffect(() => {
- if (editorRef.current && initialContent) {
- editorRef.current.value = initialContent;
- handleContentChangeCallback(initialContent);
- updateEditorHeight();
- }
- // Only run once on mount to set initial content
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, []);
-
- // Update editor when content is externally changed (e.g., reset after save)
- useEffect(() => {
- if (editorRef.current && editorRef.current.value !== initialContent) {
- editorRef.current.value = initialContent;
- updateEditorHeight();
- }
- }, [initialContent, updateEditorHeight]);
-
- const actions: TextareaActions = useMemo(
- () => ({
- getEditor: () => editorRef.current,
- focus: () => editorRef.current?.focus(),
- scrollToCursor: () => {
- scrollToCaret({ force: true });
- },
- insertText: (content = "", prefix = "", suffix = "") => {
- const editor = editorRef.current;
- if (!editor) return;
-
- const cursorPos = editor.selectionStart;
- const endPos = editor.selectionEnd;
- const prev = editor.value;
- const actual = content || prev.slice(cursorPos, endPos);
- editor.value = prev.slice(0, cursorPos) + prefix + actual + suffix + prev.slice(endPos);
-
- editor.focus();
- editor.setSelectionRange(cursorPos + prefix.length + actual.length, cursorPos + prefix.length + actual.length);
- updateContent();
- },
- setContent: (text: string) => {
- const editor = editorRef.current;
- if (editor) {
- editor.value = text;
- updateContent();
- }
- },
- getContent: () => editorRef.current?.value ?? "",
- getCursorPosition: () => editorRef.current?.selectionStart ?? 0,
- setCursorPosition: (startPos: number, endPos?: number) => {
- const editor = editorRef.current;
- if (!editor) return;
- // setSelectionRange requires valid arguments; default to startPos if endPos is undefined
- const endPosition = endPos !== undefined && !Number.isNaN(endPos) ? endPos : startPos;
- editor.setSelectionRange(startPos, endPosition);
- },
- }),
- [updateContent, scrollToCaret],
- );
-
- // The raw textarea is an honest fallback: it realizes only the core
- // EditorController surface (markdown in/out, focus, selection) on top of
- // textarea string ops. It exposes no `formatting` capability — the focus-mode
- // toolbar is WYSIWYG-only — so rich formatting is never faked here.
- useImperativeHandle(
- ref,
- (): EditorController => ({
- focus: () => actions.focus(),
- hasFocus: () => {
- const element = actions.getEditor();
- return Boolean(element) && document.activeElement === element;
- },
- isEmpty: () => actions.getContent().trim() === "",
- getMarkdown: () => actions.getContent(),
- setMarkdown: (markdown) => actions.setContent(markdown),
- insertMarkdown: (markdown) => {
- if (!markdown) return;
- const content = actions.getContent();
- const cursor = actions.getCursorPosition();
- const before = content.slice(0, cursor);
- const after = content.slice(cursor);
- const prefix = before.length === 0 || before.endsWith("\n\n") ? "" : before.endsWith("\n") ? "\n" : "\n\n";
- const suffix = after.length === 0 || after.startsWith("\n\n") ? "" : after.startsWith("\n") ? "\n" : "\n\n";
- actions.insertText(markdown, prefix, suffix);
- },
- scrollToCursor: () => actions.scrollToCursor(),
- selectAll: () => actions.setCursorPosition(0, actions.getContent().length),
- }),
- [actions],
- );
-
- const handleEditorInput = useCallback(() => {
- if (editorRef.current) {
- handleContentChangeCallback(editorRef.current.value);
- updateEditorHeight();
-
- // Auto-scroll to keep cursor visible when typing
- // See: https://github.com/usememos/memos/issues/5469
- scrollToCaret();
- }
- }, [handleContentChangeCallback, updateEditorHeight, scrollToCaret]);
-
- // Recalculate editor height when focus mode changes
- useEffect(() => {
- updateEditorHeight();
- }, [isFocusMode, updateEditorHeight]);
-
- return (
-
-
-
- );
-});
-
-export default PlainEditor;
diff --git a/web/src/components/MemoEditor/README.md b/web/src/components/MemoEditor/README.md
index afbd46a5..64fce3ae 100644
--- a/web/src/components/MemoEditor/README.md
+++ b/web/src/components/MemoEditor/README.md
@@ -2,7 +2,7 @@
## Overview
-MemoEditor uses a three-layer architecture for better separation of concerns and testability. It ships two editor implementations — a WYSIWYG rich-text editor (Tiptap/ProseMirror, the default) and a plain-text textarea — behind a single `EditorController` contract, so all layers above the editor boundary are mode-agnostic.
+MemoEditor is a three-layer component. At its core is a single editor — `Editor/`, a CodeMirror 6 "decorated source" editor. It stores the memo as **raw markdown, verbatim** (no parse/serialize round-trip) and styles that source in place with CodeMirror decorations: the markers (`#`, `*`, `` ` ``, list bullets, fences) stay visible but de-emphasized while the styled text leads. There is one editor and one storage format; everything above the editor boundary talks markdown through the `EditorController` contract.
## Architecture
@@ -15,8 +15,8 @@ MemoEditor uses a three-layer architecture for better separation of concerns and
┌─────────────────▼───────────────────────┐
│ State Layer (Reducer + Context) │
│ - state/, useEditorContext() │
-│ - state.content ← markdown (source │
-│ of truth for both editor modes) │
+│ - state.content ← markdown (the │
+│ single source of truth) │
└─────────────────┬───────────────────────┘
│
┌─────────────────▼───────────────────────┐
@@ -32,29 +32,25 @@ MemoEditor/
├── state/ # State management (reducer, actions, context)
├── services/ # Business logic (pure functions)
├── components/ # UI components
-│ ├── EditorContent.tsx # Hosts the active editor; exposes mode-routing controller
-│ ├── EditorToolbar.tsx # Toolbar including the mode toggle button
+│ ├── EditorContent.tsx # Hosts Editor; forwards its EditorController ref
+│ ├── EditorToolbar.tsx # Toolbar
│ └── ...
├── hooks/ # React hooks (utilities)
-│ ├── useMemoInit.ts # Initializes editor content; load guard for WYSIWYG
-│ └── ...
-├── PlainEditor/ # Plain textarea (raw mode) implementation
-│ └── index.tsx # Bare textarea implementing EditorController directly
-├── Editor/ # Tiptap WYSIWYG implementation (default)
-│ ├── index.tsx # Editor component; implements EditorController
-│ ├── extensions.ts # Canonical schema-relevant extension set (shared with codec)
-│ ├── markdownCodec.ts # Headless parse/serialize helpers (singleton editor)
-│ ├── PreservedBlock.ts # Byte-for-byte preservation of tables, math, raw HTML
-│ ├── Tag.ts # Memos #tag mark (markdownTokenizer + input rule)
-│ ├── tagMarkdown.ts # Tag-aware Markdown: # escape on serialize, link-skip on parse
-│ ├── TagSuggestion.ts # # popup for WYSIWYG mode
-│ └── suggestionMenu.tsx # Shared suggestion popup renderer (used by TagSuggestion)
+├── Editor/ # The CodeMirror 6 decorated-source editor
+│ ├── index.tsx # React wrapper: mounts the EditorView, owns the
+│ │ # controller refs, syncs initialContent in/out
+│ ├── extensions.ts # buildEditorExtensions(): assembles the CM extension set
+│ ├── theme.ts # Syntax-highlight style + editor theme (CSS-var colors)
+│ ├── tagMentionDecorations.ts# ViewPlugin that decorates #tag / @mention spans
+│ ├── tagAutocomplete.ts # CM autocompletion source for #tag
+│ ├── formatting.ts # FormattingController impl (toggle marks, headings, lists)
+│ └── controller.ts # EditorController impl over an EditorView
+├── formatting/
+│ └── commands.ts # Backend-agnostic catalog of formatting verbs
├── Toolbar/ # Toolbar sub-components (InsertMenu, VisibilitySelector)
-├── editorMode.ts # EditorMode type + localStorage persistence helpers
├── constants.ts
└── types/
- ├── editorController.ts # EditorController interface (the cross-mode contract)
- └── ...
+ └── editorController.ts # EditorController / FormattingController interfaces
```
## Key Concepts
@@ -63,48 +59,32 @@ MemoEditor/
Uses `useReducer` + Context for predictable state transitions. All state changes go through action creators.
-`state.content` holds the document as a **markdown string** and is the single source of truth for both editor modes. Each editor serializes its current content into the reducer on every change via `onContentChange`; neither editor reads content back from the other.
+`state.content` holds the document as a **markdown string** and is the single source of truth. Because the editor stores markdown verbatim, `state.content` is exactly the editor's document — there is no encoding or normalization step.
-### Dual-mode editor
+### The editor contract
-`types/editorController.ts` defines the `EditorController` interface — `focus`, `getMarkdown`, `setMarkdown`, `insertMarkdown`, formatting toggles, etc. — that callers outside an editor implementation must use exclusively.
+`types/editorController.ts` defines `EditorController` — `focus`, `getMarkdown`, `setMarkdown`, `insertMarkdown`, `selectAll`, `scrollToCursor`, plus an optional `formatting` capability. Callers outside the editor implementation use this interface exclusively and never reach into CodeMirror internals.
-- **WYSIWYG mode** (`Editor/`): Tiptap/ProseMirror rich-text editor. The default mode. Implements `EditorController` directly via `useImperativeHandle` in `Editor/index.tsx`.
-- **Raw mode** (`PlainEditor/`): a bare textarea with no in-editor assistance (no suggestion popups, list continuation, or keyboard markdown shortcuts) — just auto-grow and cursor-visibility scrolling. It implements `EditorController` directly (markdown is just the textarea value), so the toolbar's formatting toggles still work.
+`Editor/controller.ts` implements `EditorController` over a CodeMirror `EditorView`: `getMarkdown` is just `view.state.doc.toString()`, `setMarkdown` replaces the whole document, and `insertMarkdown` block-pads the insertion so it lands as its own block.
-`components/EditorContent.tsx` hosts whichever implementation `state.ui.editorMode` selects and exposes a single mode-routing `EditorController` facade to the rest of the component tree via `forwardRef`.
+`FormattingController` (same file in `types/`) is the rich-formatting surface the focus-mode `FormattingToolbar` drives: `run(commandId, ctx?)`, `getActiveFormats()`, `getSelectedText()`, and `subscribe(listener)`. `Editor/formatting.ts` implements it by editing the markdown source directly — toggling inline marks (`**`/`*`/`` ` ``), line prefixes (`- `, `1. `, `- [ ] `), and ATX heading prefixes (`#`…) — and by reading active state from the Lezer syntax tree at the caret.
-### Mode toggle
+### Formatting command catalog
-The toolbar button in `EditorToolbar.tsx` dispatches `SET_EDITOR_MODE` and calls `setPreferredEditorMode` (from `editorMode.ts`) to persist the preference per device in `localStorage["memos-editor-mode"]`. WYSIWYG is the default when no preference is stored.
+`formatting/commands.ts` is the single, editor-agnostic catalog of formatting verbs (`EDITOR_COMMANDS`, `EditorCommandId`, `ActiveFormatState`, `isCommandActive`). It is metadata only — labels (i18n keys), icons, and grouping — with no dependency on any concrete editor. The toolbar and the active-state highlighting derive everything from this catalog; `Editor/formatting.ts` supplies how each verb is applied to the live CodeMirror document. To add a verb, add one entry here (and its field on `ActiveFormatState`).
-Mode switching is a markdown handoff: because both editors write into `state.content` on every keystroke, the incoming editor simply initializes from it — no content is ever pushed between editors directly.
+### Editor extensions
-### Markdown fidelity layer (Editor)
+`Editor/extensions.ts` exports `buildEditorExtensions()`, which composes the CodeMirror extension set: `@codemirror/lang-markdown` (with GFM), line wrapping, a placeholder, the editor theme, the `#tag`/`@mention` decoration plugin, the `#tag` autocomplete, and an update listener that pushes document changes back to the reducer via `onChange`.
-`Editor/extensions.ts` exports `buildExtensions()`, the canonical schema-relevant extension set. It is shared by the live editor and the headless `markdownCodec.ts` (parse/serialize/round-trip helpers over a singleton Tiptap instance) so parse and serialize behavior is identical in both contexts.
+`Editor/theme.ts` defines the decorated-source look: a `HighlightStyle` over the Lezer markdown highlight tags (headings, strong, emphasis, code, links, quotes, markers) and an `EditorView.theme`. Colors come from CSS custom properties so light/dark themes just work. This is the editor's own styling — the read-only memo view styles itself separately via `@/lib/markdownStyles`.
-`PreservedBlock.ts` handles syntax the WYSIWYG editor does not model richly: tables, `$$math$$`, and raw HTML are captured at parse time with their raw markdown source, shown as editable monospace literal text, and re-emitted byte-for-byte on serialize.
+### Tags and mentions
-`Tag.ts` models memos `#tags` as a `code: true` text mark, letting tags round-trip byte-identically even inside bold or heading spans. Its `#tag` lexing is a `markdownTokenizer` (the canonical `@tiptap/markdown` extension point); `tagMarkdown.ts` adds the two things that tokenizer can't do — on serialize it backslash-escapes a literal `#` that would otherwise re-parse into a tag (escapes are lexical, so there is no "escaped tag" node), and on parse it strips the tag mark from text inside link labels. The `#tag` grammar itself lives once in `utils/tag-grammar.ts` (`TAG_RUN`), shared by the tokenizer, the serialize-escape, and the read-only `remark-tag` renderer so they can't drift.
+`#tag` autocomplete and `#tag`/`@mention` decoration both reuse the shared grammar so the editor can't drift from the rest of the app:
-### Why the markdown manager is worked around in several places
-
-`@tiptap/markdown` (3.26.0) exposes no public, per-instance hook for custom tokenizers or for text escaping, and it registers each extension's tokenizer onto the **global** `marked` singleton on every `new Editor()` — registrations it never removes. That one limitation is the reason for three otherwise-surprising choices, each documented in detail at its call site:
-
-- **`markdownCodec.ts` keeps a single editor instance** — re-creating editors would leak tokenizer registrations onto global `marked` and measurably degrade parse time.
-- **`PreservedBlock.ts` registers its tokenizers on `marked` once at module scope** (idempotent) instead of via the per-extension `markdownTokenizer`, to avoid that per-construction accumulation.
-- **`tagMarkdown.ts` composes onto the manager in `onBeforeCreate`** (escape, link-skip) because the relevant manager methods are `private` with no public seam.
-
-`Tag.ts` deliberately uses the canonical `markdownTokenizer` API and accepts the per-construction re-registration as its cost; `PreservedBlock.ts` refuses it for its seven tokenizers. The asymmetry is intentional — collapse both onto one path if upstream ever ships a public per-instance tokenizer hook.
-
-### Suggestions
-
-The `#` tag suggestion popup is a **WYSIWYG-only** feature: `Editor/TagSuggestion.ts`, using the shared `Editor/suggestionMenu.tsx` renderer. Raw mode is a plain textarea with no suggestions. (Formatting actions that a `/` command menu would once have offered — lists, code, link — are now available from the focus-mode `FormattingToolbar` header.)
-
-### Load guard
-
-`hooks/useMemoInit.ts` runs a round-trip check on every existing memo when the editor opens. If the preferred mode is WYSIWYG and `isLosslessRoundTrip` (from `markdownCodec.ts`) returns false for the memo's content, the editor falls back to raw mode for that session only (preference is not changed) and shows a toast. This is a safety net; the corpus tests are designed to make it never fire in practice.
+- `Editor/tagMentionDecorations.ts` is a `ViewPlugin` that scans the visible ranges and adds `cm-memo-tag` / `cm-memo-mention` marks, matching against `TAG_RUN` (`@/utils/tag-grammar`) and `MENTION_RUN` (`@/utils/mention-grammar`).
+- `Editor/tagAutocomplete.ts` is a CodeMirror autocompletion source for `#tag`, matching the in-progress token with `TAG_CHAR_CLASS` (`@/utils/tag-grammar`) and offering known tags (from `useTagCounts`).
### Services
@@ -114,13 +94,6 @@ Pure TypeScript functions containing business logic. No React hooks, easy to tes
Thin presentation components that dispatch actions and render UI.
-## Markdown fidelity contract
-
-The round-trip corpus tests in `web/tests/markdown-roundtrip.test.ts`, backed by fixtures under `web/tests/fixtures/markdown-corpus/`, enforce two guarantees:
-
-- **Supported syntax** (`supported/`): a parse → serialize → parse cycle produces an identical document tree (semantic equality; marker style may normalize).
-- **Preserved syntax** (`preserved/`): tables, math, and raw HTML round-trip byte-for-byte.
-
## Usage
```typescript
diff --git a/web/src/components/MemoEditor/components/EditorToolbar.tsx b/web/src/components/MemoEditor/Toolbar/EditorToolbar.tsx
similarity index 95%
rename from web/src/components/MemoEditor/components/EditorToolbar.tsx
rename to web/src/components/MemoEditor/Toolbar/EditorToolbar.tsx
index 866a009e..a216df93 100644
--- a/web/src/components/MemoEditor/components/EditorToolbar.tsx
+++ b/web/src/components/MemoEditor/Toolbar/EditorToolbar.tsx
@@ -4,9 +4,9 @@ import type { Location, Visibility } from "@/types/proto/api/v1/memo_service_pb"
import { useTranslate } from "@/utils/i18n";
import { validationService } from "../services";
import { useEditorContext, useEditorSelector } from "../state";
-import InsertMenu from "../Toolbar/InsertMenu";
-import VisibilitySelector from "../Toolbar/VisibilitySelector";
import type { EditorToolbarProps } from "../types";
+import InsertMenu from "./InsertMenu";
+import VisibilitySelector from "./VisibilitySelector";
export const EditorToolbar: FC = ({ onSave, onCancel, memoName, onAudioRecorderClick }) => {
const t = useTranslate();
diff --git a/web/src/components/MemoEditor/components/FormattingToolbar.tsx b/web/src/components/MemoEditor/Toolbar/FormattingToolbar.tsx
similarity index 95%
rename from web/src/components/MemoEditor/components/FormattingToolbar.tsx
rename to web/src/components/MemoEditor/Toolbar/FormattingToolbar.tsx
index 4a0a49bf..185a059e 100644
--- a/web/src/components/MemoEditor/components/FormattingToolbar.tsx
+++ b/web/src/components/MemoEditor/Toolbar/FormattingToolbar.tsx
@@ -10,15 +10,9 @@ import {
} from "@/components/ui/dropdown-menu";
import { cn } from "@/lib/utils";
import { useTranslate } from "@/utils/i18n";
-import {
- EDITOR_COMMANDS,
- EDITOR_COMMANDS_BY_ID,
- type EditorCommand,
- type EditorCommandId,
- isCommandActive,
-} from "../Editor/editorCommands";
+import { EDITOR_COMMANDS, EDITOR_COMMANDS_BY_ID, type EditorCommand, type EditorCommandId, isCommandActive } from "../formatting/commands";
import { isCompactWidth, useEditorActiveState, useElementWidth } from "../hooks";
-import type { EditorController } from "../types/editorController";
+import type { EditorController } from "../types";
interface FormattingToolbarProps {
controllerRef: RefObject;
@@ -42,7 +36,7 @@ interface ToolbarButton {
/**
* Focus-mode header: a rich-text formatting toolbar driven entirely through the
* editor controller's formatting capability. Every button is derived from the
- * shared command catalog (Editor/editorCommands.ts), so adding a verb there
+ * shared command catalog (formatting/commands.ts), so adding a verb there
* surfaces it here automatically. Responsive: below COMPACT_TOOLBAR_WIDTH the
* list and link controls fold into a "more" menu while marks stay inline.
*/
diff --git a/web/src/components/MemoEditor/Toolbar/InsertMenu.tsx b/web/src/components/MemoEditor/Toolbar/InsertMenu.tsx
index 79ac72e0..e6a9be6d 100644
--- a/web/src/components/MemoEditor/Toolbar/InsertMenu.tsx
+++ b/web/src/components/MemoEditor/Toolbar/InsertMenu.tsx
@@ -18,7 +18,6 @@ import { useReverseGeocoding } from "@/components/map/useReverseGeocoding";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
- DropdownMenuCheckboxItem,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
@@ -31,7 +30,6 @@ import {
import { useDebouncedEffect } from "@/hooks";
import type { MemoRelation } from "@/types/proto/api/v1/memo_service_pb";
import { useTranslate } from "@/utils/i18n";
-import { setPreferredEditorMode } from "../editorMode";
import { useFileUpload, useLinkMemo, useLocation } from "../hooks";
import { useEditorContext, useEditorSelector } from "../state";
import type { InsertMenuProps } from "../types";
@@ -41,7 +39,6 @@ const InsertMenu = (props: InsertMenuProps) => {
const t = useTranslate();
const { actions, dispatch } = useEditorContext();
const relations = useEditorSelector((s) => s.metadata.relations);
- const editorMode = useEditorSelector((s) => s.ui.editorMode);
const { location: initialLocation, onLocationChange, onToggleFocusMode, isUploading: isUploadingProp } = props;
const [linkDialogOpen, setLinkDialogOpen] = useState(false);
@@ -136,15 +133,6 @@ const InsertMenu = (props: InsertMenuProps) => {
setMoreSubmenuOpen(false);
}, [onToggleFocusMode]);
- const handleEditorModeChange = useCallback(
- (checked: boolean) => {
- const next = checked ? "wysiwyg" : "raw";
- dispatch(actions.setEditorMode(next));
- setPreferredEditorMode(next);
- },
- [actions, dispatch],
- );
-
const handleMediaUploadClick = useCallback(() => {
handleUploadClick("image/*,video/*");
}, [handleUploadClick]);
@@ -224,10 +212,6 @@ const InsertMenu = (props: InsertMenuProps) => {
{t("editor.focus-mode")}
- {/* Editor display mode: checked = rich text (WYSIWYG), unchecked = raw Markdown */}
-
- {t("editor.wysiwyg-editor")}
-
diff --git a/web/src/components/MemoEditor/Toolbar/index.ts b/web/src/components/MemoEditor/Toolbar/index.ts
index 35034fc8..676ca402 100644
--- a/web/src/components/MemoEditor/Toolbar/index.ts
+++ b/web/src/components/MemoEditor/Toolbar/index.ts
@@ -1,3 +1,5 @@
// Toolbar components for MemoEditor
+export { EditorToolbar } from "./EditorToolbar";
+export { FormattingToolbar } from "./FormattingToolbar";
export { default as InsertMenu } from "./InsertMenu";
export { default as VisibilitySelector } from "./VisibilitySelector";
diff --git a/web/src/components/MemoEditor/components/AudioRecorderPanel.tsx b/web/src/components/MemoEditor/components/AudioRecorderPanel.tsx
index f153f670..014210ab 100644
--- a/web/src/components/MemoEditor/components/AudioRecorderPanel.tsx
+++ b/web/src/components/MemoEditor/components/AudioRecorderPanel.tsx
@@ -6,7 +6,7 @@ import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip
import { cn } from "@/lib/utils";
import { useTranslate } from "@/utils/i18n";
import { useAudioWaveform } from "../hooks/useAudioWaveform";
-import type { AudioRecorderPanelProps } from "../types/components";
+import type { AudioRecorderPanelProps } from "../types";
import { VoiceWaveform } from "./VoiceWaveform";
export const AudioRecorderPanel: FC = ({
diff --git a/web/src/components/MemoEditor/components/EditorContent.tsx b/web/src/components/MemoEditor/components/EditorContent.tsx
index 38990c70..4ea7d975 100644
--- a/web/src/components/MemoEditor/components/EditorContent.tsx
+++ b/web/src/components/MemoEditor/components/EditorContent.tsx
@@ -1,66 +1,27 @@
-import { forwardRef, useCallback, useEffect, useImperativeHandle, useRef } from "react";
+import { forwardRef } from "react";
import Editor from "../Editor";
import { useBlobUrls, useDragAndDrop } from "../hooks";
-import PlainEditor from "../PlainEditor";
import { useEditorContext, useEditorSelector } from "../state";
import type { EditorContentProps } from "../types";
import type { LocalFile } from "../types/attachment";
import type { EditorController } from "../types/editorController";
+// Imported eagerly (not React.lazy): the editor is the always-present compose
+// box on the home route, which is already code-split — so deferring the
+// CodeMirror bundle separately bought nothing and made the editor paint empty
+// for a beat before its placeholder appeared (a visible flicker on load).
+
/**
- * Hosts one of the two editor implementations behind the EditorController
- * contract, selected by state.ui.editorMode. Mode switching is a markdown
- * handoff: both editors serialize into state.content on every change, so the
- * incoming editor simply initializes from it.
+ * Hosts the CodeMirror Editor behind the EditorController contract. The
+ * editor serializes into state.content on every change and exposes its
+ * formatting capability for the focus-mode toolbar.
*/
export const EditorContent = forwardRef(({ placeholder }, ref) => {
const { actions, dispatch } = useEditorContext();
const { createBlobUrl } = useBlobUrls();
const content = useEditorSelector((s) => s.content);
- const mode = useEditorSelector((s) => s.ui.editorMode);
const isFocusMode = useEditorSelector((s) => s.ui.isFocusMode);
- // Both editors implement EditorController; the host holds one ref each and
- // routes the parent's single ref to whichever mode is active.
- const wysiwygRef = useRef(null);
- const plainRef = useRef(null);
-
- const modeRef = useRef(mode);
- modeRef.current = mode;
- const getActive = useCallback((): EditorController | null => (modeRef.current === "wysiwyg" ? wysiwygRef.current : plainRef.current), []);
-
- // Mid-edit mode switches should land the user back in the editor, not on
- // the toolbar button. Skipped on first mount (useMemoInit owns autofocus).
- const previousModeRef = useRef(mode);
- useEffect(() => {
- if (previousModeRef.current === mode) {
- return;
- }
- previousModeRef.current = mode;
- getActive()?.focus();
- }, [mode, getActive]);
-
- useImperativeHandle(
- ref,
- (): EditorController => ({
- focus: () => getActive()?.focus(),
- hasFocus: () => getActive()?.hasFocus() ?? false,
- isEmpty: () => getActive()?.isEmpty() ?? true,
- getMarkdown: () => getActive()?.getMarkdown() ?? "",
- setMarkdown: (markdown) => getActive()?.setMarkdown(markdown),
- insertMarkdown: (markdown) => getActive()?.insertMarkdown(markdown),
- scrollToCursor: () => getActive()?.scrollToCursor(),
- selectAll: () => getActive()?.selectAll(),
- // Formatting is whatever the active editor exposes: the WYSIWYG editor
- // provides it, the raw textarea leaves it undefined. No more faking a
- // per-verb inert surface — the toolbar simply isn't shown in raw mode.
- get formatting() {
- return getActive()?.formatting;
- },
- }),
- [getActive],
- );
-
const { dragHandlers } = useDragAndDrop((files: FileList) => {
const localFiles: LocalFile[] = Array.from(files).map((file) => ({
file,
@@ -102,27 +63,15 @@ export const EditorContent = forwardRef(({
return (
- {mode === "wysiwyg" ? (
-
- ) : (
-
- )}
+
);
});
diff --git a/web/src/components/MemoEditor/components/index.ts b/web/src/components/MemoEditor/components/index.ts
index 4510bcd5..c7445720 100644
--- a/web/src/components/MemoEditor/components/index.ts
+++ b/web/src/components/MemoEditor/components/index.ts
@@ -3,7 +3,5 @@
export * from "./AudioRecorderPanel";
export * from "./EditorContent";
export * from "./EditorMetadata";
-export * from "./EditorToolbar";
export { FocusModeExitButton, FocusModeOverlay } from "./FocusModeOverlay";
-export { FormattingToolbar } from "./FormattingToolbar";
export { TimestampPopover } from "./TimestampPopover";
diff --git a/web/src/components/MemoEditor/editorMode.ts b/web/src/components/MemoEditor/editorMode.ts
deleted file mode 100644
index 6359253a..00000000
--- a/web/src/components/MemoEditor/editorMode.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-export type EditorMode = "wysiwyg" | "raw";
-
-const STORAGE_KEY = "memos-editor-mode";
-
-/** Per-device editor mode preference. WYSIWYG is the default for everyone. */
-export function getPreferredEditorMode(): EditorMode {
- try {
- return localStorage.getItem(STORAGE_KEY) === "raw" ? "raw" : "wysiwyg";
- } catch {
- return "wysiwyg";
- }
-}
-
-export function setPreferredEditorMode(mode: EditorMode): void {
- try {
- localStorage.setItem(STORAGE_KEY, mode);
- } catch {
- // localStorage unavailable (e.g. blocked storage) — preference won't persist.
- }
-}
diff --git a/web/src/components/MemoEditor/Editor/editorCommands.ts b/web/src/components/MemoEditor/formatting/commands.ts
similarity index 61%
rename from web/src/components/MemoEditor/Editor/editorCommands.ts
rename to web/src/components/MemoEditor/formatting/commands.ts
index 39d3941e..a3be993c 100644
--- a/web/src/components/MemoEditor/Editor/editorCommands.ts
+++ b/web/src/components/MemoEditor/formatting/commands.ts
@@ -1,13 +1,13 @@
-import type { Editor } from "@tiptap/core";
import { BoldIcon, CodeIcon, ItalicIcon, LinkIcon, ListIcon, ListOrderedIcon, ListTodoIcon, type LucideIcon } from "lucide-react";
import type { Translations } from "@/utils/i18n";
/**
- * The single source of truth for the editor's formatting verbs. Every surface
- * that needs them — the focus-mode toolbar, the active-state hook, and any
- * future `/` slash menu — derives from this catalog instead of re-declaring the
- * verb, its icon, and its command in its own file. Commands act directly on the
- * live Tiptap editor (the only place that holds it).
+ * Backend-agnostic catalog of the editor's formatting verbs — metadata only, no
+ * dependency on the concrete editor. Every surface that needs the verbs — the
+ * focus-mode toolbar, the active-state hook, and any future `/` slash menu —
+ * derives its labels, icons, and grouping from this catalog instead of
+ * re-declaring them. How a verb is applied to the live editor is supplied
+ * separately (Editor/formatting.ts).
*
* To add a formatting verb, add one entry here (and, if it's a new mark/list,
* its field on ActiveFormatState); the toolbar and active-state pick it up.
@@ -66,8 +66,6 @@ export interface EditorCommand {
/** Button icon. Omitted for headings/paragraph, which render as label-only dropdown items. */
icon?: LucideIcon;
group: EditorCommandGroup;
- /** Apply to the live editor. The `link` command reads `ctx.url`. */
- run: (editor: Editor, ctx?: EditorCommandContext) => void;
}
export const EDITOR_COMMANDS: EditorCommand[] = [
@@ -76,83 +74,62 @@ export const EDITOR_COMMANDS: EditorCommand[] = [
labelKey: "editor.format.bold",
icon: BoldIcon,
group: "mark",
- run: (editor) => editor.chain().focus().toggleBold().run(),
},
{
id: "italic",
labelKey: "editor.format.italic",
icon: ItalicIcon,
group: "mark",
- run: (editor) => editor.chain().focus().toggleItalic().run(),
},
{
id: "code",
labelKey: "editor.format.code",
icon: CodeIcon,
group: "mark",
- run: (editor) => editor.chain().focus().toggleCode().run(),
},
{
id: "bulletList",
labelKey: "editor.format.bullet-list",
icon: ListIcon,
group: "list",
- run: (editor) => editor.chain().focus().toggleBulletList().run(),
},
{
id: "orderedList",
labelKey: "editor.format.ordered-list",
icon: ListOrderedIcon,
group: "list",
- run: (editor) => editor.chain().focus().toggleOrderedList().run(),
},
{
id: "taskList",
labelKey: "editor.format.task-list",
icon: ListTodoIcon,
group: "list",
- run: (editor) => editor.chain().focus().toggleTaskList().run(),
},
{
id: "paragraph",
labelKey: "editor.format.paragraph",
group: "heading",
- run: (editor) => editor.chain().focus().setParagraph().run(),
},
{
id: "heading1",
labelKey: "editor.format.heading-1",
group: "heading",
- run: (editor) => editor.chain().focus().setHeading({ level: 1 }).run(),
},
{
id: "heading2",
labelKey: "editor.format.heading-2",
group: "heading",
- run: (editor) => editor.chain().focus().setHeading({ level: 2 }).run(),
},
{
id: "heading3",
labelKey: "editor.format.heading-3",
group: "heading",
- run: (editor) => editor.chain().focus().setHeading({ level: 3 }).run(),
},
{
id: "link",
labelKey: "editor.format.link",
icon: LinkIcon,
group: "link",
- run: (editor, ctx) => {
- if (editor.isActive("link")) {
- editor.chain().focus().unsetLink().run();
- return;
- }
- const href = ctx?.url?.trim();
- if (!href) {
- return;
- }
- editor.chain().focus().extendMarkRange("link").setLink({ href }).run();
- },
},
];
@@ -161,25 +138,9 @@ export const EDITOR_COMMANDS_BY_ID = Object.fromEntries(EDITOR_COMMANDS.map((com
EditorCommand
>;
-const HEADING_LEVELS: ToolbarHeadingLevel[] = [1, 2, 3];
-
-/** Derive the full active-format snapshot from the live editor in one pass. */
-export function getActiveFormats(editor: Editor): ActiveFormatState {
- const headingLevel = HEADING_LEVELS.find((level) => editor.isActive("heading", { level })) ?? null;
- return {
- bold: editor.isActive("bold"),
- italic: editor.isActive("italic"),
- code: editor.isActive("code"),
- bulletList: editor.isActive("bulletList"),
- orderedList: editor.isActive("orderedList"),
- taskList: editor.isActive("taskList"),
- link: editor.isActive("link"),
- headingLevel,
- };
-}
-
/** Whether a given command is active for an active-format snapshot. Lets any
- * surface (toolbar, slash menu) highlight commands without re-deriving state. */
+ * surface (toolbar, slash menu) highlight commands by reading the backend-
+ * agnostic ActiveFormatState — no live-editor dependency. */
export function isCommandActive(active: ActiveFormatState, id: EditorCommandId): boolean {
switch (id) {
case "paragraph":
diff --git a/web/src/components/MemoEditor/hooks/useEditorActiveState.ts b/web/src/components/MemoEditor/hooks/useEditorActiveState.ts
index 24bc379a..da3e7e00 100644
--- a/web/src/components/MemoEditor/hooks/useEditorActiveState.ts
+++ b/web/src/components/MemoEditor/hooks/useEditorActiveState.ts
@@ -1,5 +1,5 @@
import { type RefObject, useEffect, useState } from "react";
-import { type ActiveFormatState, EMPTY_ACTIVE_FORMATS } from "../Editor/editorCommands";
+import { type ActiveFormatState, EMPTY_ACTIVE_FORMATS } from "../formatting/commands";
import type { EditorController } from "../types/editorController";
function sameActiveFormats(a: ActiveFormatState, b: ActiveFormatState): boolean {
diff --git a/web/src/components/MemoEditor/hooks/useLocation.ts b/web/src/components/MemoEditor/hooks/useLocation.ts
index e0a979a5..ffed6ada 100644
--- a/web/src/components/MemoEditor/hooks/useLocation.ts
+++ b/web/src/components/MemoEditor/hooks/useLocation.ts
@@ -2,7 +2,7 @@ import { create } from "@bufbuild/protobuf";
import { useCallback, useMemo, useRef, useState } from "react";
import type { MapPoint } from "@/components/map/types";
import { Location, LocationSchema } from "@/types/proto/api/v1/memo_service_pb";
-import { LocationState } from "../types/insert-menu";
+import { LocationState } from "../types/insertMenu";
export const useLocation = (initialLocation?: Location) => {
const [locationInitialized, setLocationInitialized] = useState(false);
diff --git a/web/src/components/MemoEditor/hooks/useMemoInit.ts b/web/src/components/MemoEditor/hooks/useMemoInit.ts
index 544c0338..2aa59a29 100644
--- a/web/src/components/MemoEditor/hooks/useMemoInit.ts
+++ b/web/src/components/MemoEditor/hooks/useMemoInit.ts
@@ -1,9 +1,5 @@
import { useEffect, useRef, useState } from "react";
-import toast from "react-hot-toast";
import type { Memo, Visibility } from "@/types/proto/api/v1/memo_service_pb";
-import { useTranslate } from "@/utils/i18n";
-import { isLosslessRoundTrip } from "../Editor/markdownCodec";
-import { getPreferredEditorMode } from "../editorMode";
import { cacheService, memoService } from "../services";
import { useEditorContext } from "../state";
import type { EditorController } from "../types/editorController";
@@ -27,7 +23,6 @@ export const useMemoInit = ({
defaultVisibility,
defaultCreateTime,
}: UseMemoInitOptions) => {
- const t = useTranslate();
const { actions, dispatch } = useEditorContext();
const initializedRef = useRef(false);
const [isInitialized, setIsInitialized] = useState(false);
@@ -41,16 +36,6 @@ export const useMemoInit = ({
const initialState = memoService.fromMemo(memo);
cacheService.clear(key);
dispatch(actions.initMemo(initialState));
- // Load guard (tripwire): if the WYSIWYG round trip would change this
- // memo's meaning, edit it raw for this session. Preference untouched —
- // and INIT_MEMO ignores ui state, so the mode must be dispatched here.
- // No length cap: the check runs in a useEffect (post-paint). Add a cap
- // if profiling ever identifies cost on very large memos.
- if (getPreferredEditorMode() === "wysiwyg" && initialState.content && !isLosslessRoundTrip(initialState.content)) {
- console.warn("memo content failed wysiwyg round-trip; falling back to raw editor", memo.name);
- dispatch(actions.setEditorMode("raw"));
- toast(t("editor.unsupported-syntax-raw-mode"));
- }
} else {
const cachedContent = cacheService.load(key);
if (cachedContent) {
@@ -69,7 +54,7 @@ export const useMemoInit = ({
}
setIsInitialized(true);
- }, [memo, cacheKey, username, autoFocus, defaultVisibility, defaultCreateTime, actions, dispatch, editorRef, t]);
+ }, [memo, cacheKey, username, autoFocus, defaultVisibility, defaultCreateTime, actions, dispatch, editorRef]);
return { isInitialized };
};
diff --git a/web/src/components/MemoEditor/index.tsx b/web/src/components/MemoEditor/index.tsx
index 340984ab..bbf37785 100644
--- a/web/src/components/MemoEditor/index.tsx
+++ b/web/src/components/MemoEditor/index.tsx
@@ -12,20 +12,12 @@ import { cn } from "@/lib/utils";
import { InstanceSetting_Key } from "@/types/proto/api/v1/instance_service_pb";
import { useTranslate } from "@/utils/i18n";
import { convertVisibilityFromString } from "@/utils/memo";
-import {
- AudioRecorderPanel,
- EditorContent,
- EditorMetadata,
- EditorToolbar,
- FocusModeExitButton,
- FocusModeOverlay,
- FormattingToolbar,
- TimestampPopover,
-} from "./components";
+import { AudioRecorderPanel, EditorContent, EditorMetadata, FocusModeOverlay, TimestampPopover } from "./components";
import { FOCUS_MODE_STYLES } from "./constants";
import { useAudioRecorder, useAutoSave, useFocusMode, useKeyboard, useMemoInit } from "./hooks";
import { errorService, memoService, transcriptionService, validationService } from "./services";
import { EditorProvider, useEditorContext, useEditorSelector } from "./state";
+import { EditorToolbar, FormattingToolbar } from "./Toolbar";
import type { MemoEditorProps } from "./types";
import type { LocalFile } from "./types/attachment";
import type { EditorController } from "./types/editorController";
@@ -56,7 +48,6 @@ const MemoEditorImpl: React.FC = ({
// typing (which changes content) does not re-render the editor shell and its
// toolbar/metadata children.
const isFocusMode = useEditorSelector((s) => s.ui.isFocusMode);
- const editorMode = useEditorSelector((s) => s.ui.editorMode);
const hasTimestamp = useEditorSelector((s) => Boolean(s.timestamps.createTime));
const { userGeneralSetting } = useAuth();
const { aiSetting, fetchSetting } = useInstance();
@@ -323,14 +314,10 @@ const MemoEditorImpl: React.FC = ({
className,
)}
>
- {/* Focus-mode header. WYSIWYG gets the formatting toolbar (exit lives in
- it); raw mode falls back to the floating exit button. */}
- {isFocusMode &&
- (editorMode === "wysiwyg" ? (
-
- ) : (
-
- ))}
+ {/* Focus-mode header: the formatting toolbar (exit lives in it). */}
+ {isFocusMode && (
+
+ )}
{(memoName || (!memo && hasTimestamp)) && (
diff --git a/web/src/components/MemoEditor/state/actions.ts b/web/src/components/MemoEditor/state/actions.ts
index cddbf742..8c80fcac 100644
--- a/web/src/components/MemoEditor/state/actions.ts
+++ b/web/src/components/MemoEditor/state/actions.ts
@@ -1,4 +1,3 @@
-import type { EditorMode } from "../editorMode";
import type { LocalFile } from "../types/attachment";
import type { EditorAction, EditorState, LoadingKey } from "./types";
@@ -52,11 +51,6 @@ export const editorActions = {
payload: value,
}),
- setEditorMode: (mode: EditorMode): EditorAction => ({
- type: "SET_EDITOR_MODE",
- payload: mode,
- }),
-
reset: (): EditorAction => ({
type: "RESET",
}),
diff --git a/web/src/components/MemoEditor/state/reducer.ts b/web/src/components/MemoEditor/state/reducer.ts
index 6aff7ceb..31ea0ce8 100644
--- a/web/src/components/MemoEditor/state/reducer.ts
+++ b/web/src/components/MemoEditor/state/reducer.ts
@@ -80,15 +80,6 @@ export function editorReducer(state: EditorState, action: EditorAction): EditorS
recorderBusy: action.payload,
};
- case "SET_EDITOR_MODE":
- return {
- ...state,
- ui: {
- ...state.ui,
- editorMode: action.payload,
- },
- };
-
case "RESET":
return createInitialState();
diff --git a/web/src/components/MemoEditor/state/types.ts b/web/src/components/MemoEditor/state/types.ts
index 2a586936..9bd9735a 100644
--- a/web/src/components/MemoEditor/state/types.ts
+++ b/web/src/components/MemoEditor/state/types.ts
@@ -1,7 +1,6 @@
import type { Attachment } from "@/types/proto/api/v1/attachment_service_pb";
import type { Location, MemoRelation } from "@/types/proto/api/v1/memo_service_pb";
import { Visibility } from "@/types/proto/api/v1/memo_service_pb";
-import { type EditorMode, getPreferredEditorMode } from "../editorMode";
import type { LocalFile } from "../types/attachment";
export type LoadingKey = "saving" | "uploading" | "loading";
@@ -21,7 +20,6 @@ export interface EditorState {
uploading: boolean;
loading: boolean;
};
- editorMode: EditorMode;
};
timestamps: {
createTime?: Date;
@@ -44,12 +42,9 @@ export type EditorAction =
| { type: "SET_LOADING"; payload: { key: LoadingKey; value: boolean } }
| { type: "SET_TIMESTAMPS"; payload: Partial }
| { type: "SET_RECORDER_BUSY"; payload: boolean }
- | { type: "SET_EDITOR_MODE"; payload: EditorMode }
| { type: "RESET" };
-// Module-private template for createInitialState — not exported because its
-// hardcoded editorMode ignores the persisted preference; always go through
-// createInitialState() for a real initial state.
+// Module-private template for createInitialState.
const defaultState: EditorState = {
content: "",
metadata: {
@@ -65,7 +60,6 @@ const defaultState: EditorState = {
uploading: false,
loading: false,
},
- editorMode: "wysiwyg",
},
timestamps: {
createTime: undefined,
@@ -75,14 +69,10 @@ const defaultState: EditorState = {
recorderBusy: false,
};
-/**
- * Fresh initial state for a mounting editor. Reads the persisted mode
- * preference at call time (not module load) so newly opened editors honor a
- * toggle made earlier in the session.
- */
+/** Fresh initial state for a mounting editor. */
export function createInitialState(): EditorState {
return {
...defaultState,
- ui: { ...defaultState.ui, editorMode: getPreferredEditorMode() },
+ ui: { ...defaultState.ui },
};
}
diff --git a/web/src/components/MemoEditor/types/editorController.ts b/web/src/components/MemoEditor/types/editorController.ts
index 1deb2866..2ac012a7 100644
--- a/web/src/components/MemoEditor/types/editorController.ts
+++ b/web/src/components/MemoEditor/types/editorController.ts
@@ -1,9 +1,9 @@
-import type { ActiveFormatState, EditorCommandContext, EditorCommandId } from "../Editor/editorCommands";
+import type { ActiveFormatState, EditorCommandContext, EditorCommandId } from "../formatting/commands";
/**
- * The contract both memo editors (raw textarea and WYSIWYG) implement.
- * Everything outside an editor implementation talks markdown through this
- * interface and never reaches for an editor's internal DOM/ProseMirror APIs.
+ * The contract the memo editor (Editor) implements. Everything outside the
+ * editor implementation talks markdown through this interface and never reaches
+ * for the editor's internal CodeMirror/DOM APIs.
*/
export interface EditorController {
focus(): void;
@@ -20,19 +20,18 @@ export interface EditorController {
/** Select the entire document (used by tests and select-all flows). */
selectAll(): void;
/**
- * Rich-formatting capability. Present only on editors that support it — the
- * WYSIWYG editor sets it; the raw textarea leaves it undefined. The
- * focus-mode FormattingToolbar (its only consumer) is shown solely in WYSIWYG
- * mode, so it can rely on this being present.
+ * Rich-formatting capability driving the focus-mode FormattingToolbar.
+ * Editor always sets it; the field is optional so the contract stays
+ * decoupled from any one editor implementation.
*/
formatting?: FormattingController;
}
/**
* Rich-formatting surface, backed by the editor command catalog
- * (Editor/editorCommands.ts). `getActiveFormats` is the sanctioned, typed place
- * editor state crosses the boundary — ProseMirror node/mark names never leak
- * out as stringly-typed `isActive(name)` calls.
+ * (formatting/commands.ts). `getActiveFormats` is the sanctioned, typed place
+ * editor state crosses the boundary — the editor's internal node/mark names
+ * never leak out as stringly-typed `isActive(name)` calls.
*/
export interface FormattingController {
/** Run a catalog command (e.g. "bold", "heading2", "link"). */
diff --git a/web/src/components/MemoEditor/types/index.ts b/web/src/components/MemoEditor/types/index.ts
index 394eae75..299a934f 100644
--- a/web/src/components/MemoEditor/types/index.ts
+++ b/web/src/components/MemoEditor/types/index.ts
@@ -1,6 +1,7 @@
// MemoEditor type exports
export type {
+ AudioRecorderPanelProps,
EditorContentProps,
EditorMetadataProps,
EditorToolbarProps,
@@ -11,4 +12,4 @@ export type {
VisibilitySelectorProps,
} from "./components";
export type { EditorController } from "./editorController";
-export type { LocationState } from "./insert-menu";
+export type { LocationState } from "./insertMenu";
diff --git a/web/src/components/MemoEditor/types/insert-menu.ts b/web/src/components/MemoEditor/types/insertMenu.ts
similarity index 100%
rename from web/src/components/MemoEditor/types/insert-menu.ts
rename to web/src/components/MemoEditor/types/insertMenu.ts
diff --git a/web/src/components/MemoMetadata/Location/LocationDialog.tsx b/web/src/components/MemoMetadata/Location/LocationDialog.tsx
index a47b5642..d3b918a0 100644
--- a/web/src/components/MemoMetadata/Location/LocationDialog.tsx
+++ b/web/src/components/MemoMetadata/Location/LocationDialog.tsx
@@ -1,4 +1,4 @@
-import type { LocationState } from "@/components/MemoEditor/types/insert-menu";
+import type { LocationState } from "@/components/MemoEditor/types/insertMenu";
import { LazyLocationPicker } from "@/components/map/LazyLocationPicker";
import type { MapPoint } from "@/components/map/types";
import { Button } from "@/components/ui/button";
diff --git a/web/src/index.css b/web/src/index.css
index 5ad8f1eb..532aba00 100644
--- a/web/src/index.css
+++ b/web/src/index.css
@@ -31,60 +31,3 @@
@apply bg-background text-foreground;
}
}
-
-/* Tiptap WYSIWYG memo editor */
-.memo-wysiwyg p.is-editor-empty:first-child::before {
- content: attr(data-placeholder);
- float: left;
- height: 0;
- opacity: 0.7;
- pointer-events: none;
-}
-
-/* Block styles (e.g. a paragraph's mb-2) add a trailing bottom margin that the
- raw textarea editor — whose box has no trailing space — does not have, so the
- WYSIWYG editor renders ~8px taller. Most visible when empty: a lone empty
- paragraph sits a line-plus-margin tall against the textarea's single line.
- Dropping the final block's bottom margin keeps both editor modes the same
- height. Scoped with `>` to the top-level block only (nested last children,
- e.g. the last list item, keep their spacing). */
-.memo-wysiwyg > :last-child {
- margin-bottom: 0;
-}
-
-/* Editor-only element styles: task lists and code blocks have no shared markup
- with the read-only memo view (MemoContent renders those via TaskListItem.tsx
- and CodeBlock.tsx), so unlike the elements in markdownStyles.ts they stay
- local to the editor here rather than in the shared style token. */
-.memo-wysiwyg ul[data-type="taskList"] {
- list-style: none;
- padding-left: 0;
-}
-
-.memo-wysiwyg ul[data-type="taskList"] li {
- display: flex;
- gap: 0.5rem;
-}
-
-.memo-wysiwyg ul[data-type="taskList"] li > label {
- flex: 0 0 auto;
- user-select: none;
-}
-
-.memo-wysiwyg ul[data-type="taskList"] li > div {
- flex: 1 1 auto;
-}
-
-.memo-wysiwyg pre {
- background: var(--muted);
- border-radius: 0.375rem;
- padding: 0.5rem 0.75rem;
- font-family: var(--font-mono, monospace);
- font-size: 0.875rem;
- white-space: pre-wrap;
-}
-
-.memo-wysiwyg pre code {
- background: transparent;
- padding: 0;
-}
diff --git a/web/src/lib/markdownStyles.ts b/web/src/lib/markdownStyles.ts
index c7cb686b..3edef3b2 100644
--- a/web/src/lib/markdownStyles.ts
+++ b/web/src/lib/markdownStyles.ts
@@ -18,8 +18,7 @@ const headingBaseClasses = "mt-3 mb-2 leading-tight";
/**
* Complete heading class per level, precomputed once at module load (base +
* per-level). headingClass is a hot path — MemoContent renders it per heading
- * and the editor's renderHTML runs it on essentially every keystroke — so the
- * cn() merge happens here, not per call.
+ * on every content render — so the cn() merge happens here, not per call.
*/
const headingClasses: Record = {
1: cn(headingBaseClasses, headingLevelClasses[1]),
@@ -32,10 +31,10 @@ const headingClasses: Record = {
/**
* Single source of truth for the styling of common markdown elements rendered
- * by BOTH the read-only memo view (MemoContent) and the WYSIWYG editor
- * (MemoEditor). Each value is a complete, standalone Tailwind class string so it
- * can be dropped onto a DOM element as-is (the editor sets these via Tiptap
- * `HTMLAttributes`; MemoContent merges them with `cn`).
+ * by the read-only memo view (MemoContent). Each value is a complete, standalone
+ * Tailwind class string so it can be dropped onto a DOM element as-is (MemoContent
+ * merges them with `cn`). The editor does not use these — it styles its raw
+ * markdown source via CodeMirror decorations in `MemoEditor/Editor/theme.ts`.
*
* These are static string literals so Tailwind's JIT scanner detects them.
*/
@@ -45,6 +44,10 @@ export const markdownStyles = {
bulletList: "my-0 mb-2 list-outside pl-6 list-disc",
orderedList: "my-0 mb-2 list-outside pl-6 list-decimal",
listItem: "mt-0.5 leading-6",
+ // Shared by the read-only task item (MemoContent/markdown/List.tsx) and the
+ // editor so the checkbox + text grid stays identical in both.
+ taskListItem: "mt-0.5 min-w-0 leading-6 list-none grid grid-cols-[auto_minmax(0,1fr)] items-start gap-x-2 [&>[data-slot=checkbox]]:mt-1",
+ taskItemContent: "min-w-0 [overflow-wrap:anywhere] [&>*:last-child]:mb-0",
inlineCode: "font-mono text-sm bg-muted px-1 py-0.5 rounded-md",
link: "text-primary underline decoration-primary/50 underline-offset-2 transition-colors hover:decoration-primary",
horizontalRule: "my-2 h-0 border-0 border-b border-border",
@@ -54,12 +57,10 @@ export const markdownStyles = {
export const headingClass = (level: HeadingLevel): string => headingClasses[level];
/**
- * Tag pill styling, shared by the read-only memo view (MemoContent/Tag.tsx) and
- * the editor's tag mark (MemoEditor/Editor/Tag.ts) so a `#tag` looks identical
- * while typing and after saving. Split into two tokens so the viewer can swap
- * `defaultColor` for an inline custom color, and so the editor — which is never
- * custom-colored and is not a filter button — takes the shape + default color
- * without the viewer's click/hover affordances.
+ * Tag pill styling for the read-only memo view (MemoContent/Tag.tsx). Split into
+ * two tokens so the viewer can swap `defaultColor` for an inline custom color.
+ * (The editor does not use these; it colors `#tag` source via the
+ * `cm-memo-tag` decoration in Editor/theme.ts.)
*/
export const tagStyles = {
/** Shape, padding, and typography — always applied. */
@@ -69,11 +70,11 @@ export const tagStyles = {
} as const;
/**
- * `@mention` styling, shared by the read-only memo view (MemoContent/Mention.tsx)
- * and the editor's mention mark (MemoEditor/Editor/Mention.ts) so a mention looks
- * identical while typing and after saving. Unlike a tag this is not a pill — it
- * is the same primary-colored accent the resolved read-only mention uses in its
- * resting state (the read-only view adds `hover:underline` for its link).
+ * `@mention` styling for the read-only memo view (MemoContent/Mention.tsx).
+ * Unlike a tag this is not a pill — it is a primary-colored accent (the read-only
+ * view adds `hover:underline` for its link). (The editor does not use these; it
+ * colors `@mention` source via the `cm-memo-mention` decoration in
+ * Editor/theme.ts.)
*/
export const mentionStyles = {
base: "text-primary underline-offset-2",
diff --git a/web/src/utils/mention-grammar.ts b/web/src/utils/mention-grammar.ts
index de87284d..63024992 100644
--- a/web/src/utils/mention-grammar.ts
+++ b/web/src/utils/mention-grammar.ts
@@ -1,7 +1,7 @@
/**
* The single source of truth for memos' `@mention` lexing grammar, shared by the
- * editor tokenizer (components/MemoEditor/Editor/Mention.ts) and the read-only
- * renderer (utils/remark-plugins/remark-mention.ts) so they can't drift.
+ * editor and the read-only renderer (utils/remark-plugins/remark-mention.ts) so
+ * they can't drift.
*
* A mention character is an ASCII letter, digit, or hyphen. A username is capped
* at MAX_MENTION_LENGTH characters and must contain at least one letter or digit
diff --git a/web/src/utils/tag-grammar.ts b/web/src/utils/tag-grammar.ts
index de394b8e..491de772 100644
--- a/web/src/utils/tag-grammar.ts
+++ b/web/src/utils/tag-grammar.ts
@@ -1,8 +1,7 @@
/**
* The single source of truth for memos' `#tag` lexing grammar, shared by the
- * editor tokenizer + serialize-escape (components/MemoEditor/Editor/Tag.ts and
- * tagMarkdown.ts) and the read-only renderer (utils/remark-plugins/remark-tag.ts)
- * so they can't drift.
+ * editor and the read-only renderer (utils/remark-plugins/remark-tag.ts) so they
+ * can't drift.
*
* A tag character is any Unicode letter, mark, number, or symbol, plus
* `_ - / &`. The mark class (`\p{M}`) keeps combining marks — Indic vowel
diff --git a/web/tests/editor-commands.test.ts b/web/tests/editor-commands.test.ts
deleted file mode 100644
index d1a8b777..00000000
--- a/web/tests/editor-commands.test.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-import { Editor } from "@tiptap/core";
-import { describe, expect, it } from "vitest";
-import { EDITOR_COMMANDS, EDITOR_COMMANDS_BY_ID, getActiveFormats } from "@/components/MemoEditor/Editor/editorCommands";
-import { buildExtensions } from "@/components/MemoEditor/Editor/extensions";
-
-function makeEditor(content = "") {
- return new Editor({ extensions: buildExtensions(), content, contentType: "markdown" });
-}
-
-describe("editor command catalog", () => {
- it("exposes every command keyed by id", () => {
- for (const command of EDITOR_COMMANDS) {
- expect(EDITOR_COMMANDS_BY_ID[command.id]).toBe(command);
- }
- });
-
- it("bold command toggles the bold mark, reflected by getActiveFormats", () => {
- const editor = makeEditor("hello");
- try {
- editor.commands.selectAll();
- expect(getActiveFormats(editor).bold).toBe(false);
- EDITOR_COMMANDS_BY_ID.bold.run(editor);
- expect(getActiveFormats(editor).bold).toBe(true);
- } finally {
- editor.destroy();
- }
- });
-
- it("heading2 command sets the level, reported by getActiveFormats.headingLevel", () => {
- const editor = makeEditor("title");
- try {
- expect(getActiveFormats(editor).headingLevel).toBeNull();
- EDITOR_COMMANDS_BY_ID.heading2.run(editor);
- expect(getActiveFormats(editor).headingLevel).toBe(2);
- EDITOR_COMMANDS_BY_ID.paragraph.run(editor);
- expect(getActiveFormats(editor).headingLevel).toBeNull();
- } finally {
- editor.destroy();
- }
- });
-
- it("taskList command toggles a task list", () => {
- const editor = makeEditor("buy milk");
- try {
- EDITOR_COMMANDS_BY_ID.taskList.run(editor);
- expect(getActiveFormats(editor).taskList).toBe(true);
- } finally {
- editor.destroy();
- }
- });
-
- it("link command applies a link from ctx.url and clears it when already active", () => {
- const editor = makeEditor("memos");
- try {
- editor.commands.selectAll();
- EDITOR_COMMANDS_BY_ID.link.run(editor, { url: "https://usememos.com" });
- expect(getActiveFormats(editor).link).toBe(true);
- editor.commands.selectAll();
- EDITOR_COMMANDS_BY_ID.link.run(editor); // active → unset (ignores missing url)
- expect(getActiveFormats(editor).link).toBe(false);
- } finally {
- editor.destroy();
- }
- });
-});
diff --git a/web/tests/editor-controller.test.ts b/web/tests/editor-controller.test.ts
new file mode 100644
index 00000000..e159137f
--- /dev/null
+++ b/web/tests/editor-controller.test.ts
@@ -0,0 +1,32 @@
+import { EditorState } from "@codemirror/state";
+import { EditorView } from "@codemirror/view";
+import { describe, expect, it } from "vitest";
+import { createController } from "@/components/MemoEditor/Editor/controller";
+
+function view(doc = "") {
+ return new EditorView({ state: EditorState.create({ doc }) });
+}
+
+describe("source editor controller", () => {
+ it("round-trips markdown verbatim, including previously-lossy inputs", () => {
+ const v = view();
+ const c = createController(v, {} as never);
+ for (const md of ["", "Title\n===", "1. a\n 1. b\n 1. c", "a b"]) {
+ c.setMarkdown(md);
+ expect(c.getMarkdown()).toBe(md);
+ }
+ });
+
+ it("reports emptiness on whitespace", () => {
+ const c = createController(view(" \n "), {} as never);
+ expect(c.isEmpty()).toBe(true);
+ });
+
+ it("inserts markdown as its own block", () => {
+ const v = view("alpha");
+ const c = createController(v, {} as never);
+ v.dispatch({ selection: { anchor: 5 } });
+ c.insertMarkdown("beta");
+ expect(c.getMarkdown()).toBe("alpha\n\nbeta");
+ });
+});
diff --git a/web/tests/editor-controller.test.tsx b/web/tests/editor-controller.test.tsx
deleted file mode 100644
index bbe1ca61..00000000
--- a/web/tests/editor-controller.test.tsx
+++ /dev/null
@@ -1,249 +0,0 @@
-import { act, fireEvent, render } from "@testing-library/react";
-import type { Editor as EditorInstance } from "@tiptap/core";
-import { AllSelection } from "@tiptap/pm/state";
-import { createRef } from "react";
-import { describe, expect, it, vi } from "vitest";
-import Editor from "@/components/MemoEditor/Editor";
-import type { EditorController } from "@/components/MemoEditor/types/editorController";
-
-vi.mock("@/hooks/useUserQueries", async (importOriginal) => ({
- ...(await importOriginal