Skip to content

armgit / memos

Public Imported from GitHub
0

Memos is an open-source, self-hosted note-taking app that brings your everyday thoughts together in a personal timeline. Your data stays yours, and you choose what to keep private or share.

refactor(editor): modularize formatting and simplify editor state

boojack1e3ec38fa10a
diff --git a/web/src/components/MemoEditor/Editor/Tag.ts b/web/src/components/MemoEditor/Editor/Tag.ts
index 16bdc495e..12734d037 100644
--- a/web/src/components/MemoEditor/Editor/Tag.ts
+++ b/web/src/components/MemoEditor/Editor/Tag.ts
@@ -3,19 +3,20 @@ import { InputRule, Mark, mergeAttributes } from "@tiptap/core";
import type { TokenizerThis, Tokens } from "marked";
import { marked } from "marked";
import { tagStyles } from "@/lib/markdownStyles";
+import { MAX_TAG_LENGTH, TAG_CHAR_CLASS } 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}`;
-// Mirrors the renderer's tag lexer (web/src/utils/remark-plugins/remark-tag.ts):
-// letters, numbers, symbols, plus _ - / &, max 100 chars. Keep the two in sync.
-const TAG_CHAR = "[\\p{L}\\p{N}\\p{S}_\\-/&]";
-const TAG_INPUT_RULE = new RegExp(`(?:^|\\s)#(${TAG_CHAR}{1,100})\\s$`, "u");
-const TAG_TOKEN_RULE = new RegExp(`^#(${TAG_CHAR}{1,100})`, "u");
+// Built from the shared tag grammar (@/utils/tag-grammar) so the editor's
+// tokenizer/input rule can't drift from the read-only renderer's lexer
+// (web/src/utils/remark-plugins/remark-tag.ts).
+const TAG_INPUT_RULE = new RegExp(`(?:^|\\s)#(${TAG_CHAR_CLASS}{1,${MAX_TAG_LENGTH}})\\s$`, "u");
+const TAG_TOKEN_RULE = new RegExp(`^#(${TAG_CHAR_CLASS}{1,${MAX_TAG_LENGTH}})`, "u");
// Tests the REMAINDER of the source (not a single code unit) so astral-plane
// tag characters (emoji et al.) are seen whole, not as lone surrogates.
-const TAG_CHAR_AHEAD = new RegExp(`^${TAG_CHAR}`, "u");
+const TAG_CHAR_AHEAD = new RegExp(`^${TAG_CHAR_CLASS}`, "u");
/**
* Tag tokenizer, registered DIRECTLY on the global marked singleton instead of
diff --git a/web/src/components/MemoEditor/Editor/TagSuggestion.ts b/web/src/components/MemoEditor/Editor/TagSuggestion.ts
index ef584103c..94f723579 100644
--- a/web/src/components/MemoEditor/Editor/TagSuggestion.ts
+++ b/web/src/components/MemoEditor/Editor/TagSuggestion.ts
@@ -1,8 +1,5 @@
-import { Extension } from "@tiptap/core";
-import { PluginKey } from "@tiptap/pm/state";
-import Suggestion from "@tiptap/suggestion";
import { createElement } from "react";
-import { createSuggestionRenderer } from "./suggestionMenu";
+import { createSuggestionExtension } from "./suggestionExtension";
export interface TagSuggestionOptions {
/** Getter (not a snapshot) so the popup always sees freshly fetched tags. */
@@ -12,48 +9,34 @@ export interface TagSuggestionOptions {
const MAX_SUGGESTIONS = 20;
/** `#` popup backed by the user's existing tags; inserts tag-marked text + a space. */
-export const TagSuggestion = Extension.create<TagSuggestionOptions>({
- name: "tagSuggestion",
-
- addOptions() {
- return { getTags: () => [] };
- },
-
- addProseMirrorPlugins() {
- return [
- Suggestion<string>({
- editor: this.editor,
- pluginKey: new PluginKey("tagSuggestion"),
- char: "#",
- allowSpaces: false,
- items: ({ query }) => {
- // 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 this.options
- .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();
- },
- render: createSuggestionRenderer<string>({
- getItemKey: (tag) => tag,
- renderItem: (tag) =>
- createElement("span", { className: "truncate" }, createElement("span", { className: "text-muted-foreground mr-1" }, "#"), tag),
- }),
- }),
- ];
- },
-});
+export function createTagSuggestion({ getTags }: TagSuggestionOptions) {
+ return createSuggestionExtension<string>({
+ 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/editorCommands.ts b/web/src/components/MemoEditor/Editor/editorCommands.ts
new file mode 100644
index 000000000..39d3941e3
--- /dev/null
+++ b/web/src/components/MemoEditor/Editor/editorCommands.ts
@@ -0,0 +1,197 @@
+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).
+ *
+ * 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.
+ */
+
+export type ToolbarHeadingLevel = 1 | 2 | 3;
+
+export type EditorCommandId =
+ | "bold"
+ | "italic"
+ | "code"
+ | "bulletList"
+ | "orderedList"
+ | "taskList"
+ | "paragraph"
+ | "heading1"
+ | "heading2"
+ | "heading3"
+ | "link";
+
+/** Which marks/blocks are active at the current selection (toolbar highlighting). */
+export interface ActiveFormatState {
+ bold: boolean;
+ italic: boolean;
+ code: boolean;
+ bulletList: boolean;
+ orderedList: boolean;
+ taskList: boolean;
+ link: boolean;
+ headingLevel: ToolbarHeadingLevel | null;
+}
+
+export const EMPTY_ACTIVE_FORMATS: ActiveFormatState = {
+ bold: false,
+ italic: false,
+ code: false,
+ bulletList: false,
+ orderedList: false,
+ taskList: false,
+ link: false,
+ headingLevel: null,
+};
+
+export interface EditorCommandContext {
+ /** Link target, read by the `link` command when adding a link. */
+ url?: string;
+}
+
+/** Toolbar grouping — the toolbar builds each group by filtering on this. */
+export type EditorCommandGroup = "mark" | "list" | "heading" | "link";
+
+export interface EditorCommand {
+ id: EditorCommandId;
+ /** i18n key for label / tooltip / aria-label. */
+ labelKey: Translations;
+ /** 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[] = [
+ {
+ id: "bold",
+ 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();
+ },
+ },
+];
+
+export const EDITOR_COMMANDS_BY_ID = Object.fromEntries(EDITOR_COMMANDS.map((command) => [command.id, command])) as Record<
+ EditorCommandId,
+ 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. */
+export function isCommandActive(active: ActiveFormatState, id: EditorCommandId): boolean {
+ switch (id) {
+ case "paragraph":
+ return active.headingLevel === null;
+ case "heading1":
+ return active.headingLevel === 1;
+ case "heading2":
+ return active.headingLevel === 2;
+ case "heading3":
+ return active.headingLevel === 3;
+ // bold/italic/code/bulletList/orderedList/taskList/link map 1:1 to the snapshot.
+ default:
+ return active[id];
+ }
+}
diff --git a/web/src/components/MemoEditor/Editor/index.tsx b/web/src/components/MemoEditor/Editor/index.tsx
index bd32ffcad..71049493c 100644
--- a/web/src/components/MemoEditor/Editor/index.tsx
+++ b/web/src/components/MemoEditor/Editor/index.tsx
@@ -9,9 +9,10 @@ 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, FormattingController } from "../types/editorController";
+import type { EditorController } from "../types/editorController";
+import { EDITOR_COMMANDS_BY_ID, EMPTY_ACTIVE_FORMATS, getActiveFormats } from "./editorCommands";
import { buildExtensions } from "./extensions";
-import { TagSuggestion } from "./TagSuggestion";
+import { createTagSuggestion } from "./TagSuggestion";
// Mod-Enter is the app-wide "save memo" shortcut (useKeyboard). StarterKit's
// HardBreak extension also binds Mod-Enter to insert a hard break, which would
@@ -82,7 +83,7 @@ function serializeMarkdown(editor: { getMarkdown: () => string } | null): string
* serializeMarkdown() on every update. IME, list continuation, input rules,
* and auto-grow are native ProseMirror/contenteditable behavior.
*/
-const Editor = forwardRef<EditorController & FormattingController, EditorProps>(function Editor(props, ref) {
+const Editor = forwardRef<EditorController, EditorProps>(function Editor(props, ref) {
const { className, initialContent, placeholder, isFocusMode, onContentChange, onPaste } = props;
// Last markdown emitted through onContentChange, so the sync effect can
@@ -100,7 +101,7 @@ const Editor = forwardRef<EditorController & FormattingController, EditorProps>(
onPasteRef.current = onPaste;
// On the explore page suggestions include all users' tags; otherwise the
- // current user's. Same sourcing as the raw editor's TagSuggestions.
+ // current user's.
const isExplorePage = useMemo(() => Boolean(matchPath(Routes.EXPLORE, window.location.pathname)), []);
const { data: tagCount = {} } = useTagCounts(!isExplorePage);
const sortedTags = useMemo(
@@ -123,7 +124,7 @@ const Editor = forwardRef<EditorController & FormattingController, EditorProps>(
() => [
...buildExtensions(),
Placeholder.configure({ placeholder: () => placeholderRef.current }),
- TagSuggestion.configure({ getTags: () => tagsRef.current }),
+ createTagSuggestion({ getTags: () => tagsRef.current }),
SaveShortcutPassthrough,
CollapseAllSelectionAfterDelete,
],
@@ -200,7 +201,7 @@ const Editor = forwardRef<EditorController & FormattingController, EditorProps>(
useImperativeHandle(
ref,
- (): EditorController & FormattingController => ({
+ (): EditorController => ({
focus: () => editor?.commands.focus(),
hasFocus: () => editor?.isFocused ?? false,
// Contract: whitespace-only counts as empty. The editor's structural
@@ -211,41 +212,29 @@ const Editor = forwardRef<EditorController & FormattingController, EditorProps>(
insertMarkdown: (markdown) => editor?.chain().focus().insertContent(markdown, { contentType: "markdown" }).run(),
scrollToCursor: () => editor?.commands.scrollIntoView(),
selectAll: () => editor?.commands.selectAll(),
- toggleBold: () => editor?.chain().focus().toggleBold().run(),
- toggleItalic: () => editor?.chain().focus().toggleItalic().run(),
- toggleTaskList: () => editor?.chain().focus().toggleTaskList().run(),
- toggleCode: () => editor?.chain().focus().toggleCode().run(),
- toggleBulletList: () => editor?.chain().focus().toggleBulletList().run(),
- toggleOrderedList: () => editor?.chain().focus().toggleOrderedList().run(),
- setHeading: (level) => editor?.chain().focus().setHeading({ level }).run(),
- setParagraph: () => editor?.chain().focus().setParagraph().run(),
- toggleLink: (url) => {
- if (!editor) {
- return;
- }
- if (editor.isActive("link")) {
- editor.chain().focus().unsetLink().run();
- return;
- }
- const href = url?.trim();
- if (!href) {
- return;
- }
- editor.chain().focus().extendMarkRange("link").setLink({ href }).run();
- },
- getSelectedText: () => {
- if (!editor) {
- return "";
- }
- const { from, to } = editor.state.selection;
- return editor.state.doc.textBetween(from, to, " ");
- },
- isActive: (name, attrs) => editor?.isActive(name, attrs ?? {}) ?? false,
- subscribe: (listener) => {
- activeListenersRef.current.add(listener);
- return () => {
- activeListenersRef.current.delete(listener);
- };
+ // 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],
diff --git a/web/src/components/MemoEditor/Editor/suggestionExtension.ts b/web/src/components/MemoEditor/Editor/suggestionExtension.ts
new file mode 100644
index 000000000..fec95d7a4
--- /dev/null
+++ b/web/src/components/MemoEditor/Editor/suggestionExtension.ts
@@ -0,0 +1,56 @@
+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<T> {
+ /** 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<T, T>["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<T>(config: SuggestionExtensionConfig<T>): Extension {
+ return Extension.create({
+ name: config.name,
+
+ addProseMirrorPlugins() {
+ return [
+ Suggestion<T, T>({
+ 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<T>({
+ renderItem: config.renderItem,
+ getItemKey: config.getItemKey,
+ }),
+ }),
+ ];
+ },
+ });
+}
diff --git a/web/src/components/MemoEditor/Editor/suggestionMenu.tsx b/web/src/components/MemoEditor/Editor/suggestionMenu.tsx
index 10240bfd6..3cf955f03 100644
--- a/web/src/components/MemoEditor/Editor/suggestionMenu.tsx
+++ b/web/src/components/MemoEditor/Editor/suggestionMenu.tsx
@@ -25,7 +25,7 @@ interface SuggestionMenuProps<T> {
getItemKey: (item: T) => string;
}
-// Visual parity with the textarea editor's popup (Editor/SuggestionsPopup.tsx).
+// 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",
diff --git a/web/src/components/MemoEditor/PlainEditor/index.tsx b/web/src/components/MemoEditor/PlainEditor/index.tsx
index 9ddb04ef0..86ec3a1e9 100644
--- a/web/src/components/MemoEditor/PlainEditor/index.tsx
+++ b/web/src/components/MemoEditor/PlainEditor/index.tsx
@@ -22,16 +22,10 @@ interface TextareaActions {
insertText: (text: string, prefix?: string, suffix?: string) => void;
setContent: (text: string) => void;
getContent: () => string;
- getSelectedContent: () => string;
getCursorPosition: () => number;
setCursorPosition: (startPos: number, endPos?: number) => void;
- getCursorLineNumber: () => number;
- getLine: (lineNumber: number) => string;
- setLine: (lineNumber: number, text: string) => void;
}
-const TASK_PREFIX = "- [ ] ";
-
const PlainEditor = forwardRef(function PlainEditor(props: PlainEditorProps, ref: React.ForwardedRef<EditorController>) {
const { className, initialContent, placeholder, onPaste, onContentChange: handleContentChangeCallback, isFocusMode } = props;
const editorRef = useRef<HTMLTextAreaElement>(null);
@@ -117,11 +111,6 @@ const PlainEditor = forwardRef(function PlainEditor(props: PlainEditorProps, ref
}
},
getContent: () => editorRef.current?.value ?? "",
- getSelectedContent: () => {
- const editor = editorRef.current;
- if (!editor) return "";
- return editor.value.slice(editor.selectionStart, editor.selectionEnd);
- },
getCursorPosition: () => editorRef.current?.selectionStart ?? 0,
setCursorPosition: (startPos: number, endPos?: number) => {
const editor = editorRef.current;
@@ -130,28 +119,14 @@ const PlainEditor = forwardRef(function PlainEditor(props: PlainEditorProps, ref
const endPosition = endPos !== undefined && !Number.isNaN(endPos) ? endPos : startPos;
editor.setSelectionRange(startPos, endPosition);
},
- getCursorLineNumber: () => {
- const editor = editorRef.current;
- if (!editor) return 0;
- const lines = editor.value.slice(0, editor.selectionStart).split("\n");
- return lines.length - 1;
- },
- getLine: (lineNumber: number) => editorRef.current?.value.split("\n")[lineNumber] ?? "",
- setLine: (lineNumber: number, text: string) => {
- const editor = editorRef.current;
- if (!editor) return;
- const lines = editor.value.split("\n");
- lines[lineNumber] = text;
- editor.value = lines.join("\n");
- editor.focus();
- updateContent();
- },
}),
[updateContent, scrollToCaret],
);
- // Realize the shared EditorController contract on top of textarea surgery, so
- // the toolbar's formatting toggles and the mode-routing host talk markdown.
+ // 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 => ({
@@ -175,19 +150,6 @@ const PlainEditor = forwardRef(function PlainEditor(props: PlainEditorProps, ref
},
scrollToCursor: () => actions.scrollToCursor(),
selectAll: () => actions.setCursorPosition(0, actions.getContent().length),
- toggleBold: () => toggleTextStyle(actions, "**"),
- toggleItalic: () => toggleTextStyle(actions, "*"),
- toggleTaskList: () => {
- const lineNumber = actions.getCursorLineNumber();
- const line = actions.getLine(lineNumber);
- const taskMatch = line.match(/^(\s*)- \[[ xX]\] /);
- if (taskMatch) {
- actions.setLine(lineNumber, taskMatch[1] + line.slice(taskMatch[0].length));
- } else {
- const indent = line.match(/^(\s*)/)?.[1] ?? "";
- actions.setLine(lineNumber, `${indent}${TASK_PREFIX}${line.slice(indent.length)}`);
- }
- },
}),
[actions],
);
@@ -233,41 +195,4 @@ const PlainEditor = forwardRef(function PlainEditor(props: PlainEditorProps, ref
);
});
-function toggleTextStyle(editor: TextareaActions, delimiter: string): void {
- const cursorPosition = editor.getCursorPosition();
- const selectedContent = editor.getSelectedContent();
- const isStyled = isTextStyled(selectedContent, delimiter);
-
- if (isStyled) {
- const unstyled = selectedContent.slice(delimiter.length, -delimiter.length);
- editor.insertText(unstyled);
- editor.setCursorPosition(cursorPosition, cursorPosition + unstyled.length);
- } else {
- editor.insertText(`${delimiter}${selectedContent}${delimiter}`);
- editor.setCursorPosition(cursorPosition + delimiter.length, cursorPosition + delimiter.length + selectedContent.length);
- }
-}
-
-function isTextStyled(text: string, delimiter: string): boolean {
- if (!text.startsWith(delimiter) || !text.endsWith(delimiter)) {
- return false;
- }
- if (delimiter !== "*") {
- return true;
- }
- const leadingAsterisks = countConsecutive(text, "*", "start");
- const trailingAsterisks = countConsecutive(text, "*", "end");
- return leadingAsterisks % 2 === 1 && trailingAsterisks % 2 === 1;
-}
-
-function countConsecutive(text: string, character: string, position: "start" | "end"): number {
- let count = 0;
- let index = position === "start" ? 0 : text.length - 1;
- while (index >= 0 && index < text.length && text[index] === character) {
- count += 1;
- index += position === "start" ? 1 : -1;
- }
- return count;
-}
-
export default PlainEditor;
diff --git a/web/src/components/MemoEditor/Toolbar/InsertMenu.tsx b/web/src/components/MemoEditor/Toolbar/InsertMenu.tsx
index 295ed22a8..6241b2573 100644
--- a/web/src/components/MemoEditor/Toolbar/InsertMenu.tsx
+++ b/web/src/components/MemoEditor/Toolbar/InsertMenu.tsx
@@ -33,13 +33,15 @@ import type { MemoRelation } from "@/types/proto/api/v1/memo_service_pb";
import { useTranslate } from "@/utils/i18n";
import { setPreferredEditorMode } from "../editorMode";
import { useFileUpload, useLinkMemo, useLocation } from "../hooks";
-import { useEditorContext } from "../state";
+import { useEditorContext, useEditorSelector } from "../state";
import type { InsertMenuProps } from "../types";
import type { LocalFile } from "../types/attachment";
const InsertMenu = (props: InsertMenuProps) => {
const t = useTranslate();
- const { state, actions, dispatch } = useEditorContext();
+ 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);
@@ -58,9 +60,9 @@ const InsertMenu = (props: InsertMenuProps) => {
const linkMemo = useLinkMemo({
isOpen: linkDialogOpen,
currentMemoName: props.memoName,
- existingRelations: state.metadata.relations,
+ existingRelations: relations,
onAddRelation: (relation: MemoRelation) => {
- dispatch(actions.setMetadata({ relations: uniqBy([...state.metadata.relations, relation], (r) => r.relatedMemo?.name) }));
+ dispatch(actions.setMetadata({ relations: uniqBy([...relations, relation], (r) => r.relatedMemo?.name) }));
setLinkDialogOpen(false);
},
});
@@ -223,7 +225,7 @@ const InsertMenu = (props: InsertMenuProps) => {
{t("editor.focus-mode")}
</DropdownMenuItem>
{/* Editor display mode: checked = rich text (WYSIWYG), unchecked = raw Markdown */}
- <DropdownMenuCheckboxItem checked={state.ui.editorMode === "wysiwyg"} onCheckedChange={handleEditorModeChange}>
+ <DropdownMenuCheckboxItem checked={editorMode === "wysiwyg"} onCheckedChange={handleEditorModeChange}>
{t("editor.wysiwyg-editor")}
</DropdownMenuCheckboxItem>
</DropdownMenuSubContent>
diff --git a/web/src/components/MemoEditor/components/EditorContent.tsx b/web/src/components/MemoEditor/components/EditorContent.tsx
index b3e49bc28..38990c70e 100644
--- a/web/src/components/MemoEditor/components/EditorContent.tsx
+++ b/web/src/components/MemoEditor/components/EditorContent.tsx
@@ -2,10 +2,10 @@ import { forwardRef, useCallback, useEffect, useImperativeHandle, useRef } from
import Editor from "../Editor";
import { useBlobUrls, useDragAndDrop } from "../hooks";
import PlainEditor from "../PlainEditor";
-import { useEditorContext } from "../state";
+import { useEditorContext, useEditorSelector } from "../state";
import type { EditorContentProps } from "../types";
import type { LocalFile } from "../types/attachment";
-import type { EditorController, FormattingController, ToolbarHeadingLevel } from "../types/editorController";
+import type { EditorController } from "../types/editorController";
/**
* Hosts one of the two editor implementations behind the EditorController
@@ -13,14 +13,16 @@ import type { EditorController, FormattingController, ToolbarHeadingLevel } from
* handoff: both editors serialize into state.content on every change, so the
* incoming editor simply initializes from it.
*/
-export const EditorContent = forwardRef<EditorController & FormattingController, EditorContentProps>(({ placeholder }, ref) => {
- const { state, actions, dispatch } = useEditorContext();
+export const EditorContent = forwardRef<EditorController, EditorContentProps>(({ placeholder }, ref) => {
+ const { actions, dispatch } = useEditorContext();
const { createBlobUrl } = useBlobUrls();
- const mode = state.ui.editorMode;
+ 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<EditorController & FormattingController>(null);
+ const wysiwygRef = useRef<EditorController>(null);
const plainRef = useRef<EditorController>(null);
const modeRef = useRef(mode);
@@ -40,7 +42,7 @@ export const EditorContent = forwardRef<EditorController & FormattingController,
useImperativeHandle(
ref,
- (): EditorController & FormattingController => ({
+ (): EditorController => ({
focus: () => getActive()?.focus(),
hasFocus: () => getActive()?.hasFocus() ?? false,
isEmpty: () => getActive()?.isEmpty() ?? true,
@@ -49,20 +51,12 @@ export const EditorContent = forwardRef<EditorController & FormattingController,
insertMarkdown: (markdown) => getActive()?.insertMarkdown(markdown),
scrollToCursor: () => getActive()?.scrollToCursor(),
selectAll: () => getActive()?.selectAll(),
- toggleBold: () => getActive()?.toggleBold(),
- toggleItalic: () => getActive()?.toggleItalic(),
- toggleTaskList: () => getActive()?.toggleTaskList(),
- // Formatting surface — only the WYSIWYG editor implements it; inert in raw
- // mode, where the toolbar is never shown.
- toggleCode: () => wysiwygRef.current?.toggleCode(),
- toggleBulletList: () => wysiwygRef.current?.toggleBulletList(),
- toggleOrderedList: () => wysiwygRef.current?.toggleOrderedList(),
- setHeading: (level: ToolbarHeadingLevel) => wysiwygRef.current?.setHeading(level),
- setParagraph: () => wysiwygRef.current?.setParagraph(),
- toggleLink: (url?: string) => wysiwygRef.current?.toggleLink(url),
- getSelectedText: () => wysiwygRef.current?.getSelectedText() ?? "",
- isActive: (name: string, attrs?: Record<string, unknown>) => wysiwygRef.current?.isActive(name, attrs) ?? false,
- subscribe: (listener: () => void) => wysiwygRef.current?.subscribe(listener) ?? (() => {}),
+ // 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],
);
@@ -112,9 +106,9 @@ export const EditorContent = forwardRef<EditorController & FormattingController,
<Editor
ref={wysiwygRef}
className="memo-editor-content"
- initialContent={state.content}
+ initialContent={content}
placeholder={placeholder || ""}
- isFocusMode={state.ui.isFocusMode}
+ isFocusMode={isFocusMode}
onContentChange={handleContentChange}
onPaste={handlePaste}
/>
@@ -122,9 +116,9 @@ export const EditorContent = forwardRef<EditorController & FormattingController,
<PlainEditor
ref={plainRef}
className="memo-editor-content"
- initialContent={state.content}
+ initialContent={content}
placeholder={placeholder || ""}
- isFocusMode={state.ui.isFocusMode}
+ isFocusMode={isFocusMode}
onContentChange={handleContentChange}
onPaste={handlePaste}
/>
diff --git a/web/src/components/MemoEditor/components/EditorMetadata.tsx b/web/src/components/MemoEditor/components/EditorMetadata.tsx
index ee984e13d..da89d25e0 100644
--- a/web/src/components/MemoEditor/components/EditorMetadata.tsx
+++ b/web/src/components/MemoEditor/components/EditorMetadata.tsx
@@ -1,30 +1,32 @@
import type { FC } from "react";
import { AttachmentListEditor, LocationDisplayEditor, RelationListEditor } from "@/components/MemoMetadata";
-import { useEditorContext } from "../state";
+import { useEditorContext, useEditorSelector } from "../state";
import type { EditorMetadataProps } from "../types";
export const EditorMetadata: FC<EditorMetadataProps> = ({ memoName }) => {
- const { state, actions, dispatch } = useEditorContext();
+ const { actions, dispatch } = useEditorContext();
+ const attachments = useEditorSelector((s) => s.metadata.attachments);
+ const localFiles = useEditorSelector((s) => s.localFiles);
+ const relations = useEditorSelector((s) => s.metadata.relations);
+ const location = useEditorSelector((s) => s.metadata.location);
return (
<div className="w-full flex flex-col gap-2">
<AttachmentListEditor
- attachments={state.metadata.attachments}
- localFiles={state.localFiles}
- onAttachmentsChange={(attachments) => dispatch(actions.setMetadata({ attachments }))}
- onLocalFilesChange={(localFiles) => dispatch(actions.setLocalFiles(localFiles))}
+ attachments={attachments}
+ localFiles={localFiles}
+ onAttachmentsChange={(next) => dispatch(actions.setMetadata({ attachments: next }))}
+ onLocalFilesChange={(next) => dispatch(actions.setLocalFiles(next))}
onRemoveLocalFile={(previewUrl) => dispatch(actions.removeLocalFile(previewUrl))}
/>
<RelationListEditor
- relations={state.metadata.relations}
- onRelationsChange={(relations) => dispatch(actions.setMetadata({ relations }))}
+ relations={relations}
+ onRelationsChange={(next) => dispatch(actions.setMetadata({ relations: next }))}
memoName={memoName}
/>
- {state.metadata.location && (
- <LocationDisplayEditor location={state.metadata.location} onRemove={() => dispatch(actions.setMetadata({ location: undefined }))} />
- )}
+ {location && <LocationDisplayEditor location={location} onRemove={() => dispatch(actions.setMetadata({ location: undefined }))} />}
</div>
);
};
diff --git a/web/src/components/MemoEditor/components/EditorToolbar.tsx b/web/src/components/MemoEditor/components/EditorToolbar.tsx
index 5205e0b5b..a6cbbe1c5 100644
--- a/web/src/components/MemoEditor/components/EditorToolbar.tsx
+++ b/web/src/components/MemoEditor/components/EditorToolbar.tsx
@@ -1,37 +1,43 @@
import type { FC } from "react";
import { Button } from "@/components/ui/button";
+import type { Location, Visibility } from "@/types/proto/api/v1/memo_service_pb";
import { useTranslate } from "@/utils/i18n";
import { validationService } from "../services";
-import { useEditorContext } from "../state";
+import { useEditorContext, useEditorSelector } from "../state";
import InsertMenu from "../Toolbar/InsertMenu";
import VisibilitySelector from "../Toolbar/VisibilitySelector";
import type { EditorToolbarProps } from "../types";
export const EditorToolbar: FC<EditorToolbarProps> = ({ onSave, onCancel, memoName, onAudioRecorderClick }) => {
const t = useTranslate();
- const { state, actions, dispatch } = useEditorContext();
- const { valid } = validationService.canSave(state);
-
- const isSaving = state.ui.isLoading.saving;
-
- const handleLocationChange = (location: typeof state.metadata.location) => {
- dispatch(actions.setMetadata({ location }));
+ const { actions, dispatch } = useEditorContext();
+ // Subscribe to narrow/derived slices so typing (which only changes content)
+ // doesn't re-render the toolbar or the heavy InsertMenu it hosts. `valid`
+ // flips only on empty↔non-empty / loading transitions, not per keystroke.
+ const valid = useEditorSelector((s) => validationService.canSave(s).valid);
+ const isSaving = useEditorSelector((s) => s.ui.isLoading.saving);
+ const isUploading = useEditorSelector((s) => s.ui.isLoading.uploading);
+ const location = useEditorSelector((s) => s.metadata.location);
+ const visibility = useEditorSelector((s) => s.metadata.visibility);
+
+ const handleLocationChange = (next?: Location) => {
+ dispatch(actions.setMetadata({ location: next }));
};
const handleToggleFocusMode = () => {
dispatch(actions.toggleFocusMode());
};
- const handleVisibilityChange = (visibility: typeof state.metadata.visibility) => {
- dispatch(actions.setMetadata({ visibility }));
+ const handleVisibilityChange = (next: Visibility) => {
+ dispatch(actions.setMetadata({ visibility: next }));
};
return (
<div className="w-full flex flex-row justify-between items-center mb-2">
<div className="flex flex-row justify-start items-center">
<InsertMenu
- isUploading={state.ui.isLoading.uploading}
- location={state.metadata.location}
+ isUploading={isUploading}
+ location={location}
onLocationChange={handleLocationChange}
onToggleFocusMode={handleToggleFocusMode}
memoName={memoName}
@@ -40,7 +46,7 @@ export const EditorToolbar: FC<EditorToolbarProps> = ({ onSave, onCancel, memoNa
</div>
<div className="flex flex-row justify-end items-center gap-2">
- <VisibilitySelector value={state.metadata.visibility} onChange={handleVisibilityChange} />
+ <VisibilitySelector value={visibility} onChange={handleVisibilityChange} />
{onCancel && (
<Button variant="ghost" onClick={onCancel} disabled={isSaving}>
diff --git a/web/src/components/MemoEditor/components/FormattingToolbar.tsx b/web/src/components/MemoEditor/components/FormattingToolbar.tsx
index f23ebab36..4a0a49bf2 100644
--- a/web/src/components/MemoEditor/components/FormattingToolbar.tsx
+++ b/web/src/components/MemoEditor/components/FormattingToolbar.tsx
@@ -1,16 +1,4 @@
-import {
- BoldIcon,
- CodeIcon,
- HeadingIcon,
- ItalicIcon,
- LinkIcon,
- ListIcon,
- ListOrderedIcon,
- ListTodoIcon,
- type LucideIcon,
- Minimize2Icon,
- MoreHorizontalIcon,
-} from "lucide-react";
+import { HeadingIcon, type LucideIcon, Minimize2Icon, MoreHorizontalIcon } from "lucide-react";
import { type RefObject, useRef } from "react";
import { Button } from "@/components/ui/button";
import {
@@ -22,20 +10,30 @@ 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 { isCompactWidth, useEditorActiveState, useElementWidth } from "../hooks";
-import type { EditorController, FormattingController, ToolbarHeadingLevel } from "../types/editorController";
+import type { EditorController } from "../types/editorController";
interface FormattingToolbarProps {
- controllerRef: RefObject<(EditorController & FormattingController) | null>;
+ controllerRef: RefObject<EditorController | null>;
onExit: () => void;
/** Extra classes for the host to frame the toolbar (e.g. the focus-mode header band). */
className?: string;
}
-const HEADING_LEVELS: ToolbarHeadingLevel[] = [1, 2, 3];
+const MARK_COMMANDS = EDITOR_COMMANDS.filter((command) => command.group === "mark");
+const LIST_COMMANDS = EDITOR_COMMANDS.filter((command) => command.group === "list");
+// Paragraph + headings render as a single label-only dropdown (a closed set).
+const HEADING_COMMANDS = EDITOR_COMMANDS.filter((command) => command.group === "heading");
interface ToolbarButton {
- Icon: LucideIcon;
+ Icon?: LucideIcon;
label: string;
active: boolean;
onClick: () => void;
@@ -43,9 +41,10 @@ interface ToolbarButton {
/**
* Focus-mode header: a rich-text formatting toolbar driven entirely through the
- * editor controller. Purely presentational — owns no editor state beyond the
- * derived active-marks map. Responsive: below COMPACT_TOOLBAR_WIDTH the list and
- * link controls fold into a "more" menu while marks stay inline.
+ * editor controller's formatting capability. Every button is derived from the
+ * shared command catalog (Editor/editorCommands.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.
*/
export function FormattingToolbar({ controllerRef, onExit, className }: FormattingToolbarProps) {
const t = useTranslate();
@@ -54,57 +53,42 @@ export function FormattingToolbar({ controllerRef, onExit, className }: Formatti
const compact = isCompactWidth(width);
const active = useEditorActiveState(controllerRef);
+ const run = (id: EditorCommandId) => controllerRef.current?.formatting?.run(id);
+
const handleLink = () => {
- const controller = controllerRef.current;
- if (!controller) {
+ const formatting = controllerRef.current?.formatting;
+ if (!formatting) {
return;
}
- if (controller.isActive("link")) {
- controller.toggleLink();
+ if (formatting.getActiveFormats().link) {
+ formatting.run("link");
return;
}
const url = window.prompt(t("editor.format.link-prompt"));
if (!url) {
return;
}
- const selected = controller.getSelectedText();
+ const selected = formatting.getSelectedText();
if (selected) {
- controller.toggleLink(url);
+ formatting.run("link", { url });
} else {
- controller.insertMarkdown(`[${url}](${url})`);
+ controllerRef.current?.insertMarkdown(`[${url}](${url})`);
}
};
- const headingLabel = active.headingLevel === null ? t("editor.format.paragraph") : t(`editor.format.heading-${active.headingLevel}`);
+ // Map a catalog command to a toolbar button. `link` keeps its bespoke
+ // prompt-then-apply flow; everything else just runs its command.
+ const toButton = (command: EditorCommand): ToolbarButton => ({
+ Icon: command.icon,
+ label: t(command.labelKey),
+ active: isCommandActive(active, command.id),
+ onClick: command.id === "link" ? handleLink : () => run(command.id),
+ });
- // One descriptor per control drives both layouts, so each action's icon,
- // label, active flag, and command live in a single place.
- const markButtons: ToolbarButton[] = [
- { Icon: BoldIcon, label: t("editor.format.bold"), active: active.bold, onClick: () => controllerRef.current?.toggleBold() },
- { Icon: ItalicIcon, label: t("editor.format.italic"), active: active.italic, onClick: () => controllerRef.current?.toggleItalic() },
- { Icon: CodeIcon, label: t("editor.format.code"), active: active.code, onClick: () => controllerRef.current?.toggleCode() },
- ];
- const listButtons: ToolbarButton[] = [
- {
- Icon: ListIcon,
- label: t("editor.format.bullet-list"),
- active: active.bulletList,
- onClick: () => controllerRef.current?.toggleBulletList(),
- },
- {
- Icon: ListOrderedIcon,
- label: t("editor.format.ordered-list"),
- active: active.orderedList,
- onClick: () => controllerRef.current?.toggleOrderedList(),
- },
- {
- Icon: ListTodoIcon,
- label: t("editor.format.task-list"),
- active: active.taskList,
- onClick: () => controllerRef.current?.toggleTaskList(),
- },
- ];
- const linkButton: ToolbarButton = { Icon: LinkIcon, label: t("editor.format.link"), active: active.link, onClick: handleLink };
+ const headingLabel = active.headingLevel === null ? t("editor.format.paragraph") : t(`editor.format.heading-${active.headingLevel}`);
+ const markButtons = MARK_COMMANDS.map(toButton);
+ const listButtons = LIST_COMMANDS.map(toButton);
+ const linkButton = toButton(EDITOR_COMMANDS_BY_ID.link);
return (
<div
@@ -121,10 +105,9 @@ export function FormattingToolbar({ controllerRef, onExit, className }: Formatti
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start">
- <DropdownMenuItem onClick={() => controllerRef.current?.setParagraph()}>{t("editor.format.paragraph")}</DropdownMenuItem>
- {HEADING_LEVELS.map((level) => (
- <DropdownMenuItem key={level} onClick={() => controllerRef.current?.setHeading(level)}>
- {t(`editor.format.heading-${level}`)}
+ {HEADING_COMMANDS.map((command) => (
+ <DropdownMenuItem key={command.id} onClick={() => run(command.id)}>
+ {t(command.labelKey)}
</DropdownMenuItem>
))}
</DropdownMenuContent>
@@ -182,7 +165,7 @@ function FmtButton({ Icon, active, label, onClick }: ToolbarButton) {
// kit usage policy) rather than overriding className.
return (
<Button variant={active ? "secondary" : "ghost"} size="icon" aria-label={label} aria-pressed={active} title={label} onClick={onClick}>
- <Icon className="w-4 h-4" />
+ {Icon && <Icon className="w-4 h-4" />}
</Button>
);
}
diff --git a/web/src/components/MemoEditor/components/TimestampPopover.tsx b/web/src/components/MemoEditor/components/TimestampPopover.tsx
index f25989ebb..6c7bdd706 100644
--- a/web/src/components/MemoEditor/components/TimestampPopover.tsx
+++ b/web/src/components/MemoEditor/components/TimestampPopover.tsx
@@ -1,7 +1,7 @@
import { type FC, useRef, useState } from "react";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { useTranslate } from "@/utils/i18n";
-import { useEditorContext } from "../state";
+import { useEditorContext, useEditorSelector } from "../state";
const DATETIME_FORMAT = "YYYY-MM-DD HH:mm:ss";
@@ -57,8 +57,9 @@ const TimestampInput: FC<{
export const TimestampPopover: FC = () => {
const t = useTranslate();
- const { state, actions, dispatch } = useEditorContext();
- const { createTime, updateTime } = state.timestamps;
+ const { actions, dispatch } = useEditorContext();
+ const createTime = useEditorSelector((s) => s.timestamps.createTime);
+ const updateTime = useEditorSelector((s) => s.timestamps.updateTime);
if (!createTime) return null;
diff --git a/web/src/components/MemoEditor/hooks/index.ts b/web/src/components/MemoEditor/hooks/index.ts
index 6c2078500..18013b645 100644
--- a/web/src/components/MemoEditor/hooks/index.ts
+++ b/web/src/components/MemoEditor/hooks/index.ts
@@ -5,7 +5,7 @@ export { useAudioWaveform } from "./useAudioWaveform";
export { useAutoSave } from "./useAutoSave";
export { useBlobUrls } from "./useBlobUrls";
export { useDragAndDrop } from "./useDragAndDrop";
-export { type ActiveMarks, useEditorActiveState } from "./useEditorActiveState";
+export { useEditorActiveState } from "./useEditorActiveState";
export { COMPACT_TOOLBAR_WIDTH, isCompactWidth, useElementWidth } from "./useElementWidth";
export { useFileUpload } from "./useFileUpload";
export { useFocusMode } from "./useFocusMode";
diff --git a/web/src/components/MemoEditor/hooks/useAudioRecorder.ts b/web/src/components/MemoEditor/hooks/useAudioRecorder.ts
index 63722e59e..42b431e36 100644
--- a/web/src/components/MemoEditor/hooks/useAudioRecorder.ts
+++ b/web/src/components/MemoEditor/hooks/useAudioRecorder.ts
@@ -4,13 +4,9 @@ import { useBlobUrls } from "./useBlobUrls";
const FALLBACK_AUDIO_MIME_TYPE = "audio/webm";
export type AudioRecordingCompleteMode = "attach" | "transcribe";
+export type AudioRecorderStatus = "idle" | "requesting_permission" | "recording" | "error" | "unsupported";
-interface AudioRecorderActions {
- setAudioRecorderSupport: (value: boolean) => void;
- setAudioRecorderPermission: (value: "unknown" | "granted" | "denied") => void;
- setAudioRecorderStatus: (value: "idle" | "requesting_permission" | "recording" | "error" | "unsupported") => void;
- setAudioRecorderElapsed: (value: number) => void;
- setAudioRecorderError: (value?: string) => void;
+interface UseAudioRecorderOptions {
onRecordingComplete: (localFile: LocalFile, mode: AudioRecordingCompleteMode) => void;
onRecordingEmpty?: (mode: AudioRecordingCompleteMode) => void;
}
@@ -49,10 +45,22 @@ function createRecordedFile(blob: Blob, mimeType: string): File {
return new File([blob], `voice-note-${datePart}-${timePart}.${extension}`, { type: mimeType });
}
-export const useAudioRecorder = (actions: AudioRecorderActions) => {
+/**
+ * Owns the full audio-recording lifecycle and its display state (status,
+ * elapsed time, error, live stream). This is component-private state — only the
+ * editor that mounts the hook reads it — so it lives here rather than in the
+ * shared editor reducer. The single bit other components care about (whether a
+ * recording is in flight, for save-gating) is derived from `status` by the
+ * caller.
+ */
+export const useAudioRecorder = (options: UseAudioRecorderOptions) => {
+ const [status, setStatus] = useState<AudioRecorderStatus>("idle");
+ const [elapsedSeconds, setElapsedSeconds] = useState(0);
+ const [error, setError] = useState<string | undefined>(undefined);
+ const [recordingStream, setRecordingStream] = useState<MediaStream | null>(null);
+
const mediaRecorderRef = useRef<MediaRecorder | null>(null);
const mediaStreamRef = useRef<MediaStream | null>(null);
- const [recordingStream, setRecordingStream] = useState<MediaStream | null>(null);
const chunksRef = useRef<Blob[]>([]);
const startedAtRef = useRef<number | null>(null);
const elapsedTimerRef = useRef<number | null>(null);
@@ -61,6 +69,12 @@ export const useAudioRecorder = (actions: AudioRecorderActions) => {
const startRequestIdRef = useRef(0);
const { createBlobUrl } = useBlobUrls();
+ // The MediaRecorder "stop" listener is registered once per recording but may
+ // fire after later renders, so read completion callbacks through a ref to
+ // always invoke the latest ones (avoids a stale-closure bug).
+ const optionsRef = useRef(options);
+ optionsRef.current = options;
+
const cleanupTimer = () => {
if (elapsedTimerRef.current !== null) {
window.clearInterval(elapsedTimerRef.current);
@@ -89,20 +103,21 @@ export const useAudioRecorder = (actions: AudioRecorderActions) => {
typeof navigator.mediaDevices?.getUserMedia === "function" &&
typeof MediaRecorder !== "undefined";
- actions.setAudioRecorderSupport(isSupported);
if (!isSupported) {
- actions.setAudioRecorderStatus("unsupported");
- actions.setAudioRecorderError("Audio recording is not supported in this browser.");
+ setStatus("unsupported");
+ setError("Audio recording is not supported in this browser.");
return;
}
- actions.setAudioRecorderStatus("idle");
- actions.setAudioRecorderError(undefined);
+ setStatus("idle");
+ setError(undefined);
return () => {
resetRecorderRefs();
};
- }, [actions]);
+ // Mount-only: detect support once and tear down on unmount.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
const startRecording = async () => {
const requestId = startRequestIdRef.current + 1;
@@ -113,15 +128,14 @@ export const useAudioRecorder = (actions: AudioRecorderActions) => {
typeof navigator.mediaDevices?.getUserMedia !== "function" ||
typeof MediaRecorder === "undefined"
) {
- actions.setAudioRecorderSupport(false);
- actions.setAudioRecorderStatus("unsupported");
- actions.setAudioRecorderError("Audio recording is not supported in this browser.");
+ setStatus("unsupported");
+ setError("Audio recording is not supported in this browser.");
return;
}
- actions.setAudioRecorderError(undefined);
- actions.setAudioRecorderStatus("requesting_permission");
- actions.setAudioRecorderElapsed(0);
+ setError(undefined);
+ setStatus("requesting_permission");
+ setElapsedSeconds(0);
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
@@ -159,10 +173,10 @@ export const useAudioRecorder = (actions: AudioRecorderActions) => {
const completionMode = completionModeRef.current;
completionModeRef.current = "attach";
if (blob.size === 0) {
- actions.setAudioRecorderElapsed(0);
- actions.setAudioRecorderError(undefined);
- actions.setAudioRecorderStatus("idle");
- actions.onRecordingEmpty?.(completionMode);
+ setElapsedSeconds(0);
+ setError(undefined);
+ setStatus("idle");
+ optionsRef.current.onRecordingEmpty?.(completionMode);
resetRecorderRefs();
return;
}
@@ -170,7 +184,7 @@ export const useAudioRecorder = (actions: AudioRecorderActions) => {
const file = createRecordedFile(blob, recorderMimeTypeRef.current);
const previewUrl = createBlobUrl(file);
- actions.onRecordingComplete(
+ optionsRef.current.onRecordingComplete(
{
file,
previewUrl,
@@ -181,20 +195,19 @@ export const useAudioRecorder = (actions: AudioRecorderActions) => {
},
completionMode,
);
- actions.setAudioRecorderElapsed(0);
- actions.setAudioRecorderError(undefined);
- actions.setAudioRecorderStatus("idle");
+ setElapsedSeconds(0);
+ setError(undefined);
+ setStatus("idle");
resetRecorderRefs();
});
mediaRecorder.start();
startedAtRef.current = Date.now();
- actions.setAudioRecorderPermission("granted");
- actions.setAudioRecorderStatus("recording");
+ setStatus("recording");
elapsedTimerRef.current = window.setInterval(() => {
if (startedAtRef.current) {
- actions.setAudioRecorderElapsed(Math.max(0, Math.floor((Date.now() - startedAtRef.current) / 1000)));
+ setElapsedSeconds(Math.max(0, Math.floor((Date.now() - startedAtRef.current) / 1000)));
}
}, 250);
} catch (error) {
@@ -205,9 +218,8 @@ export const useAudioRecorder = (actions: AudioRecorderActions) => {
const permissionDenied =
error instanceof DOMException && (error.name === "NotAllowedError" || error.name === "PermissionDeniedError");
- actions.setAudioRecorderPermission(permissionDenied ? "denied" : "unknown");
- actions.setAudioRecorderStatus("error");
- actions.setAudioRecorderError(permissionDenied ? "Microphone permission was denied." : "Failed to start audio recording.");
+ setStatus("error");
+ setError(permissionDenied ? "Microphone permission was denied." : "Failed to start audio recording.");
resetRecorderRefs();
}
};
@@ -227,15 +239,23 @@ export const useAudioRecorder = (actions: AudioRecorderActions) => {
startRequestIdRef.current += 1;
completionModeRef.current = "attach";
resetRecorderRefs();
- actions.setAudioRecorderElapsed(0);
- actions.setAudioRecorderError(undefined);
- actions.setAudioRecorderStatus("idle");
+ setElapsedSeconds(0);
+ setError(undefined);
+ setStatus("idle");
};
+ // "Busy" = requesting permission or actively recording. The single derived
+ // concept callers need (save-gating, UI guards), owned here next to `status`.
+ const isBusy = status === "recording" || status === "requesting_permission";
+
return {
+ status,
+ isBusy,
+ elapsedSeconds,
+ error,
+ recordingStream,
startRecording,
stopRecording,
resetRecording,
- recordingStream,
};
};
diff --git a/web/src/components/MemoEditor/hooks/useAutoSave.ts b/web/src/components/MemoEditor/hooks/useAutoSave.ts
index 18eb903e7..6b4ef4e4a 100644
--- a/web/src/components/MemoEditor/hooks/useAutoSave.ts
+++ b/web/src/components/MemoEditor/hooks/useAutoSave.ts
@@ -1,23 +1,38 @@
import { useCallback, useEffect, useRef } from "react";
import { cacheService } from "../services";
+import { useEditorStore } from "../state";
-export const useAutoSave = (content: string, username: string, cacheKey: string | undefined, enabled = true) => {
- const latestContentRef = useRef(content);
+/**
+ * Persists the editor's content to localStorage as a draft. Subscribes to the
+ * editor store directly for content rather than taking it as a prop, so the
+ * component that mounts this hook does not re-render on every keystroke.
+ */
+export const useAutoSave = (username: string, cacheKey: string | undefined, enabled = true) => {
+ const store = useEditorStore();
+ const latestContentRef = useRef(store.getState().content);
const discardedContentRef = useRef<string | undefined>(undefined);
- useEffect(() => {
- latestContentRef.current = content;
- if (discardedContentRef.current !== undefined && discardedContentRef.current !== content) {
- discardedContentRef.current = undefined;
- }
- }, [content]);
-
useEffect(() => {
if (!enabled) return;
const key = cacheService.key(username, cacheKey);
- cacheService.save(key, content);
- }, [content, username, cacheKey, enabled]);
+ const persist = (content: string) => {
+ latestContentRef.current = content;
+ if (discardedContentRef.current !== undefined && discardedContentRef.current !== content) {
+ discardedContentRef.current = undefined;
+ }
+ cacheService.save(key, content);
+ };
+
+ // Persist the current content on mount/enable, then on every change.
+ persist(store.getState().content);
+ return store.subscribe(() => {
+ const content = store.getState().content;
+ if (content !== latestContentRef.current) {
+ persist(content);
+ }
+ });
+ }, [store, username, cacheKey, enabled]);
useEffect(() => {
if (!enabled) return;
@@ -46,7 +61,7 @@ export const useAutoSave = (content: string, username: string, cacheKey: string
window.removeEventListener("pagehide", flushDraft);
document.removeEventListener("visibilitychange", handleVisibilityChange);
};
- }, [username, cacheKey, enabled]);
+ }, [store, username, cacheKey, enabled]);
const discardDraft = useCallback(() => {
const key = cacheService.key(username, cacheKey);
diff --git a/web/src/components/MemoEditor/hooks/useBlobUrls.ts b/web/src/components/MemoEditor/hooks/useBlobUrls.ts
index 72959cc78..e7a1cb89d 100644
--- a/web/src/components/MemoEditor/hooks/useBlobUrls.ts
+++ b/web/src/components/MemoEditor/hooks/useBlobUrls.ts
@@ -18,11 +18,5 @@ export function useBlobUrls() {
urlsRef.current.add(url);
return url;
},
- revokeBlobUrl: (url: string) => {
- if (urlsRef.current.has(url)) {
- URL.revokeObjectURL(url);
- urlsRef.current.delete(url);
- }
- },
};
}
diff --git a/web/src/components/MemoEditor/hooks/useEditorActiveState.ts b/web/src/components/MemoEditor/hooks/useEditorActiveState.ts
index 9e32204ff..24bc379a5 100644
--- a/web/src/components/MemoEditor/hooks/useEditorActiveState.ts
+++ b/web/src/components/MemoEditor/hooks/useEditorActiveState.ts
@@ -1,31 +1,8 @@
import { type RefObject, useEffect, useState } from "react";
-import type { EditorController, FormattingController, ToolbarHeadingLevel } from "../types/editorController";
+import { type ActiveFormatState, EMPTY_ACTIVE_FORMATS } from "../Editor/editorCommands";
+import type { EditorController } from "../types/editorController";
-export interface ActiveMarks {
- bold: boolean;
- italic: boolean;
- code: boolean;
- bulletList: boolean;
- orderedList: boolean;
- taskList: boolean;
- link: boolean;
- headingLevel: ToolbarHeadingLevel | null;
-}
-
-const EMPTY_ACTIVE: ActiveMarks = {
- bold: false,
- italic: false,
- code: false,
- bulletList: false,
- orderedList: false,
- taskList: false,
- link: false,
- headingLevel: null,
-};
-
-const HEADING_LEVELS: ToolbarHeadingLevel[] = [1, 2, 3];
-
-function sameActiveMarks(a: ActiveMarks, b: ActiveMarks): boolean {
+function sameActiveFormats(a: ActiveFormatState, b: ActiveFormatState): boolean {
return (
a.bold === b.bold &&
a.italic === b.italic &&
@@ -38,41 +15,28 @@ function sameActiveMarks(a: ActiveMarks, b: ActiveMarks): boolean {
);
}
-function readActiveMarks(controller: FormattingController): ActiveMarks {
- const headingLevel = HEADING_LEVELS.find((level) => controller.isActive("heading", { level })) ?? null;
- return {
- bold: controller.isActive("bold"),
- italic: controller.isActive("italic"),
- code: controller.isActive("code"),
- bulletList: controller.isActive("bulletList"),
- orderedList: controller.isActive("orderedList"),
- taskList: controller.isActive("taskList"),
- link: controller.isActive("link"),
- headingLevel,
- };
-}
-
/**
- * Subscribes to the editor controller and recomputes which marks/nodes are
- * active whenever the selection or document changes, so toolbar buttons can
- * highlight live. Returns the empty map until a controller is available.
+ * Subscribes to the editor's formatting capability and recomputes which
+ * marks/nodes are active whenever the selection or document changes, so toolbar
+ * buttons can highlight live. Returns the empty snapshot until a formatting-
+ * capable controller is available (e.g. raw mode, which has none).
*/
-export function useEditorActiveState(controllerRef: RefObject<(EditorController & FormattingController) | null>): ActiveMarks {
- const [active, setActive] = useState<ActiveMarks>(EMPTY_ACTIVE);
+export function useEditorActiveState(controllerRef: RefObject<EditorController | null>): ActiveFormatState {
+ const [active, setActive] = useState<ActiveFormatState>(EMPTY_ACTIVE_FORMATS);
useEffect(() => {
- const controller = controllerRef.current;
- if (!controller) {
+ const formatting = controllerRef.current?.formatting;
+ if (!formatting) {
return;
}
// Fires on every transaction; keep the previous object identity when the
- // derived map is unchanged (the common case while typing) so React skips
- // the toolbar re-render.
+ // derived snapshot is unchanged (the common case while typing) so React
+ // skips the toolbar re-render.
const recompute = () => {
- const next = readActiveMarks(controller);
- setActive((prev) => (sameActiveMarks(prev, next) ? prev : next));
+ const next = formatting.getActiveFormats();
+ setActive((prev) => (sameActiveFormats(prev, next) ? prev : next));
};
recompute();
- return controller.subscribe(recompute);
+ return formatting.subscribe(recompute);
}, [controllerRef]);
return active;
}
diff --git a/web/src/components/MemoEditor/hooks/useFileUpload.ts b/web/src/components/MemoEditor/hooks/useFileUpload.ts
index ae69db2b3..142968a97 100644
--- a/web/src/components/MemoEditor/hooks/useFileUpload.ts
+++ b/web/src/components/MemoEditor/hooks/useFileUpload.ts
@@ -2,10 +2,14 @@ import { create } from "@bufbuild/protobuf";
import { useRef } from "react";
import { type MotionMedia, MotionMediaFamily, MotionMediaRole, MotionMediaSchema } from "@/types/proto/api/v1/attachment_service_pb";
import type { LocalFile } from "../types/attachment";
+import { useBlobUrls } from "./useBlobUrls";
export const useFileUpload = (onFilesSelected: (localFiles: LocalFile[]) => void) => {
const fileInputRef = useRef<HTMLInputElement>(null);
const selectingFlagRef = useRef(false);
+ // Track preview blob URLs so they're revoked on unmount instead of leaking
+ // (matches the paste/drop/audio paths, which all go through useBlobUrls).
+ const { createBlobUrl } = useBlobUrls();
const handleFileInputChange = (event?: React.ChangeEvent<HTMLInputElement>) => {
const files = Array.from(fileInputRef.current?.files || event?.target.files || []);
@@ -16,7 +20,7 @@ export const useFileUpload = (onFilesSelected: (localFiles: LocalFile[]) => void
const localFiles: LocalFile[] = pairAppleLivePhotoFiles(
files.map((file) => ({
file,
- previewUrl: URL.createObjectURL(file),
+ previewUrl: createBlobUrl(file),
origin: "upload",
})),
);
diff --git a/web/src/components/MemoEditor/index.tsx b/web/src/components/MemoEditor/index.tsx
index 1ba5ff32a..340984abd 100644
--- a/web/src/components/MemoEditor/index.tsx
+++ b/web/src/components/MemoEditor/index.tsx
@@ -25,10 +25,10 @@ import {
import { FOCUS_MODE_STYLES } from "./constants";
import { useAudioRecorder, useAutoSave, useFocusMode, useKeyboard, useMemoInit } from "./hooks";
import { errorService, memoService, transcriptionService, validationService } from "./services";
-import { EditorProvider, useEditorContext } from "./state";
+import { EditorProvider, useEditorContext, useEditorSelector } from "./state";
import type { MemoEditorProps } from "./types";
import type { LocalFile } from "./types/attachment";
-import type { EditorController, FormattingController } from "./types/editorController";
+import type { EditorController } from "./types/editorController";
const MemoEditor = (props: MemoEditorProps) => (
<EditorProvider>
@@ -50,8 +50,14 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({
const t = useTranslate();
const queryClient = useQueryClient();
const currentUser = useCurrentUser();
- const editorRef = useRef<EditorController & FormattingController>(null);
- const { state, actions, dispatch } = useEditorContext();
+ const editorRef = useRef<EditorController>(null);
+ const { actions, dispatch, getState } = useEditorContext();
+ // Subscribe only to the low-frequency slices this component renders from, so
+ // 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();
const { markNewMemo } = useNewMemo();
@@ -80,11 +86,11 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({
});
const isDraftCacheEnabled = !memo;
- // Auto-save content to localStorage
- const { discardDraft } = useAutoSave(state.content, currentUser?.name ?? "", cacheKey, isInitialized && isDraftCacheEnabled);
+ // Auto-save content to localStorage (subscribes to the store internally).
+ const { discardDraft } = useAutoSave(currentUser?.name ?? "", cacheKey, isInitialized && isDraftCacheEnabled);
// Focus mode management with body scroll lock
- useFocusMode(state.ui.isFocusMode);
+ useFocusMode(isFocusMode);
// Live-sync the draft's createTime/updateTime to the calendar-derived prop.
// Only applies in create mode; edit mode owns its own timestamps. Runs after
@@ -150,46 +156,42 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({
[actions, canTranscribe, dispatch, insertTranscribedText, t],
);
- const audioRecorderActions = useMemo(
- () => ({
- setAudioRecorderSupport: (value: boolean) => dispatch(actions.setAudioRecorderSupport(value)),
- setAudioRecorderPermission: (value: "unknown" | "granted" | "denied") => dispatch(actions.setAudioRecorderPermission(value)),
- setAudioRecorderStatus: (value: "idle" | "requesting_permission" | "recording" | "error" | "unsupported") =>
- dispatch(actions.setAudioRecorderStatus(value)),
- setAudioRecorderElapsed: (value: number) => dispatch(actions.setAudioRecorderElapsed(value)),
- setAudioRecorderError: (value?: string) => dispatch(actions.setAudioRecorderError(value)),
- onRecordingComplete: (localFile: LocalFile, mode: "attach" | "transcribe") => {
- if (mode === "transcribe") {
- void handleTranscribeRecordedAudio(localFile);
- return;
- }
+ const audioRecorder = useAudioRecorder({
+ onRecordingComplete: (localFile, mode) => {
+ if (mode === "transcribe") {
+ void handleTranscribeRecordedAudio(localFile);
+ return;
+ }
- dispatch(actions.addLocalFile(localFile));
- setIsAudioRecorderOpen(false);
- },
- onRecordingEmpty: (mode: "attach" | "transcribe") => {
- if (mode === "transcribe") {
- setIsTranscribingAudio(false);
- toast.error(t("editor.audio-recorder.transcribe-empty"));
- }
- setIsAudioRecorderOpen(false);
- },
- }),
- [actions, dispatch, handleTranscribeRecordedAudio, t],
- );
+ dispatch(actions.addLocalFile(localFile));
+ setIsAudioRecorderOpen(false);
+ },
+ onRecordingEmpty: (mode) => {
+ if (mode === "transcribe") {
+ setIsTranscribingAudio(false);
+ toast.error(t("editor.audio-recorder.transcribe-empty"));
+ }
+ setIsAudioRecorderOpen(false);
+ },
+ });
- const audioRecorder = useAudioRecorder(audioRecorderActions);
+ // Mirror the recorder's busy state into the store so validationService.canSave
+ // (consumed here and by EditorToolbar) can block saves mid-recording without
+ // the reducer owning the recorder's full state.
+ useEffect(() => {
+ dispatch(actions.setRecorderBusy(audioRecorder.isBusy));
+ }, [audioRecorder.isBusy, actions, dispatch]);
useEffect(() => {
if (!isAudioRecorderOpen) {
return;
}
- if (state.audioRecorder.status === "error" || state.audioRecorder.status === "unsupported") {
- toast.error(state.audioRecorder.error || t("editor.audio-recorder.error-description"));
+ if (audioRecorder.status === "error" || audioRecorder.status === "unsupported") {
+ toast.error(audioRecorder.error || t("editor.audio-recorder.error-description"));
setIsAudioRecorderOpen(false);
}
- }, [isAudioRecorderOpen, state.audioRecorder.error, state.audioRecorder.status, t]);
+ }, [isAudioRecorderOpen, audioRecorder.error, audioRecorder.status, t]);
const handleToggleFocusMode = () => {
dispatch(actions.toggleFocusMode());
@@ -201,7 +203,7 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({
};
const handleAudioRecorderClick = () => {
- if (state.audioRecorder.status === "recording" || state.audioRecorder.status === "requesting_permission") {
+ if (audioRecorder.isBusy) {
return;
}
@@ -229,6 +231,9 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({
useKeyboard(editorRef, handleSave);
async function handleSave() {
+ // Read the latest state imperatively — this component no longer subscribes
+ // to content, so the closure can't rely on a per-render `state` snapshot.
+ const state = getState();
// Validate before saving
const { valid, reason } = validationService.canSave(state);
if (!valid) {
@@ -302,7 +307,7 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({
return (
<>
- <FocusModeOverlay isActive={state.ui.isFocusMode} onToggle={handleToggleFocusMode} />
+ <FocusModeOverlay isActive={isFocusMode} onToggle={handleToggleFocusMode} />
{/*
Layout structure:
@@ -314,20 +319,20 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({
className={cn(
"group relative w-full flex flex-col justify-between items-start bg-card px-4 pt-3 pb-1 rounded-lg border border-border gap-2",
FOCUS_MODE_STYLES.transition,
- state.ui.isFocusMode && cn(FOCUS_MODE_STYLES.container.base, FOCUS_MODE_STYLES.container.spacing),
+ isFocusMode && cn(FOCUS_MODE_STYLES.container.base, FOCUS_MODE_STYLES.container.spacing),
className,
)}
>
{/* Focus-mode header. WYSIWYG gets the formatting toolbar (exit lives in
it); raw mode falls back to the floating exit button. */}
- {state.ui.isFocusMode &&
- (state.ui.editorMode === "wysiwyg" ? (
+ {isFocusMode &&
+ (editorMode === "wysiwyg" ? (
<FormattingToolbar controllerRef={editorRef} onExit={handleToggleFocusMode} className={FOCUS_MODE_STYLES.formattingHeader} />
) : (
<FocusModeExitButton isActive onToggle={handleToggleFocusMode} title={t("editor.exit-focus-mode")} />
))}
- {(memoName || (!memo && state.timestamps.createTime)) && (
+ {(memoName || (!memo && hasTimestamp)) && (
<div className="w-full -mb-1">
<TimestampPopover />
</div>
@@ -336,18 +341,17 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({
{/* Editor content grows to fill available space in focus mode */}
<EditorContent ref={editorRef} placeholder={placeholder} />
- {isAudioRecorderOpen &&
- (state.audioRecorder.status === "recording" || state.audioRecorder.status === "requesting_permission" || isTranscribingAudio) && (
- <AudioRecorderPanel
- audioRecorder={state.audioRecorder}
- mediaStream={audioRecorder.recordingStream}
- onStop={audioRecorder.stopRecording}
- onCancel={handleCancelAudioRecording}
- onTranscribe={handleTranscribeAudioRecording}
- canTranscribe={canTranscribe}
- isTranscribing={isTranscribingAudio}
- />
- )}
+ {isAudioRecorderOpen && (audioRecorder.isBusy || isTranscribingAudio) && (
+ <AudioRecorderPanel
+ audioRecorder={{ status: audioRecorder.status, elapsedSeconds: audioRecorder.elapsedSeconds }}
+ mediaStream={audioRecorder.recordingStream}
+ onStop={audioRecorder.stopRecording}
+ onCancel={handleCancelAudioRecording}
+ onTranscribe={handleTranscribeAudioRecording}
+ canTranscribe={canTranscribe}
+ isTranscribing={isTranscribingAudio}
+ />
+ )}
{/* Metadata and toolbar grouped together at bottom */}
<div className="w-full flex flex-col gap-2">
diff --git a/web/src/components/MemoEditor/services/validationService.ts b/web/src/components/MemoEditor/services/validationService.ts
index 8c2509dcb..4693e0cbb 100644
--- a/web/src/components/MemoEditor/services/validationService.ts
+++ b/web/src/components/MemoEditor/services/validationService.ts
@@ -23,7 +23,7 @@ export const validationService = {
}
// Cannot save while audio recorder is active
- if (state.audioRecorder.status === "recording" || state.audioRecorder.status === "requesting_permission") {
+ if (state.recorderBusy) {
return { valid: false, reason: "Finish audio recording before saving" };
}
diff --git a/web/src/components/MemoEditor/state/actions.ts b/web/src/components/MemoEditor/state/actions.ts
index 15a4e385a..cddbf742e 100644
--- a/web/src/components/MemoEditor/state/actions.ts
+++ b/web/src/components/MemoEditor/state/actions.ts
@@ -1,8 +1,6 @@
-import type { Attachment } from "@/types/proto/api/v1/attachment_service_pb";
-import type { MemoRelation } from "@/types/proto/api/v1/memo_service_pb";
import type { EditorMode } from "../editorMode";
import type { LocalFile } from "../types/attachment";
-import type { AudioRecorderPermission, AudioRecorderStatus, EditorAction, EditorState, LoadingKey } from "./types";
+import type { EditorAction, EditorState, LoadingKey } from "./types";
export const editorActions = {
initMemo: (payload: { content: string; metadata: EditorState["metadata"]; timestamps: EditorState["timestamps"] }): EditorAction => ({
@@ -20,26 +18,6 @@ export const editorActions = {
payload: metadata,
}),
- addAttachment: (attachment: Attachment): EditorAction => ({
- type: "ADD_ATTACHMENT",
- payload: attachment,
- }),
-
- removeAttachment: (name: string): EditorAction => ({
- type: "REMOVE_ATTACHMENT",
- payload: name,
- }),
-
- addRelation: (relation: MemoRelation): EditorAction => ({
- type: "ADD_RELATION",
- payload: relation,
- }),
-
- removeRelation: (name: string): EditorAction => ({
- type: "REMOVE_RELATION",
- payload: name,
- }),
-
addLocalFile: (file: LocalFile): EditorAction => ({
type: "ADD_LOCAL_FILE",
payload: file,
@@ -55,10 +33,6 @@ export const editorActions = {
payload: files,
}),
- clearLocalFiles: (): EditorAction => ({
- type: "CLEAR_LOCAL_FILES",
- }),
-
toggleFocusMode: (): EditorAction => ({
type: "TOGGLE_FOCUS_MODE",
}),
@@ -73,28 +47,8 @@ export const editorActions = {
payload: timestamps,
}),
- setAudioRecorderSupport: (value: boolean): EditorAction => ({
- type: "SET_AUDIO_RECORDER_SUPPORT",
- payload: value,
- }),
-
- setAudioRecorderPermission: (value: AudioRecorderPermission): EditorAction => ({
- type: "SET_AUDIO_RECORDER_PERMISSION",
- payload: value,
- }),
-
- setAudioRecorderStatus: (value: AudioRecorderStatus): EditorAction => ({
- type: "SET_AUDIO_RECORDER_STATUS",
- payload: value,
- }),
-
- setAudioRecorderElapsed: (value: number): EditorAction => ({
- type: "SET_AUDIO_RECORDER_ELAPSED",
- payload: value,
- }),
-
- setAudioRecorderError: (value?: string): EditorAction => ({
- type: "SET_AUDIO_RECORDER_ERROR",
+ setRecorderBusy: (value: boolean): EditorAction => ({
+ type: "SET_RECORDER_BUSY",
payload: value,
}),
diff --git a/web/src/components/MemoEditor/state/context.tsx b/web/src/components/MemoEditor/state/context.tsx
index fbc1f67f8..994ff2629 100644
--- a/web/src/components/MemoEditor/state/context.tsx
+++ b/web/src/components/MemoEditor/state/context.tsx
@@ -1,40 +1,88 @@
-import { createContext, type Dispatch, type FC, type PropsWithChildren, useContext, useMemo, useReducer } from "react";
+import { createContext, type Dispatch, type FC, type PropsWithChildren, useContext, useRef, useSyncExternalStore } from "react";
import { editorActions } from "./actions";
import { editorReducer } from "./reducer";
import type { EditorAction, EditorState } from "./types";
import { createInitialState } from "./types";
-interface EditorContextValue {
- state: EditorState;
+/**
+ * The editor's shared state is an external store (not a useReducer in the
+ * provider) so consumers can subscribe to just the slice they read via
+ * `useEditorSelector`. Content changes on every keystroke; routing it through a
+ * single context value would re-render every consumer (toolbar, insert menu,
+ * metadata) per keystroke. With per-slice subscriptions, only the components
+ * whose slice actually changed re-render.
+ */
+export interface EditorStore {
+ getState: () => EditorState;
+ subscribe: (listener: () => void) => () => void;
dispatch: Dispatch<EditorAction>;
actions: typeof editorActions;
}
-const EditorContext = createContext<EditorContextValue | null>(null);
+function createEditorStore(initial: EditorState): EditorStore {
+ let state = initial;
+ const listeners = new Set<() => void>();
+ return {
+ getState: () => state,
+ subscribe: (listener) => {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+ },
+ dispatch: (action) => {
+ const next = editorReducer(state, action);
+ if (next === state) {
+ return;
+ }
+ state = next;
+ for (const listener of listeners) {
+ listener();
+ }
+ },
+ actions: editorActions,
+ };
+}
-export const useEditorContext = () => {
- const context = useContext(EditorContext);
- if (!context) {
- throw new Error("useEditorContext must be used within EditorProvider");
+const EditorStoreContext = createContext<EditorStore | null>(null);
+
+export const useEditorStore = (): EditorStore => {
+ const store = useContext(EditorStoreContext);
+ if (!store) {
+ throw new Error("useEditorStore must be used within EditorProvider");
}
- return context;
+ return store;
};
+/**
+ * Dispatch + imperative state access. Does NOT subscribe — components that only
+ * dispatch (or read state on-demand, e.g. on save) won't re-render on changes.
+ */
+export const useEditorContext = () => {
+ const store = useEditorStore();
+ return { dispatch: store.dispatch, actions: store.actions, getState: store.getState };
+};
+
+/**
+ * Subscribe to a derived slice of editor state. Re-renders only when the
+ * selected value changes (Object.is). Selectors must return primitives or
+ * stable references (raw state slices) — not freshly-built objects/arrays.
+ */
+export function useEditorSelector<T>(selector: (state: EditorState) => T): T {
+ const store = useEditorStore();
+ const snapshot = () => selector(store.getState());
+ return useSyncExternalStore(store.subscribe, snapshot, snapshot);
+}
+
interface EditorProviderProps extends PropsWithChildren {
initialEditorState?: EditorState;
}
export const EditorProvider: FC<EditorProviderProps> = ({ children, initialEditorState }) => {
- const [state, dispatch] = useReducer(editorReducer, initialEditorState, (provided) => provided ?? createInitialState());
-
- const value = useMemo<EditorContextValue>(
- () => ({
- state,
- dispatch,
- actions: editorActions,
- }),
- [state],
- );
-
- return <EditorContext.Provider value={value}>{children}</EditorContext.Provider>;
+ // Created once; the store instance is stable across renders.
+ const storeRef = useRef<EditorStore | null>(null);
+ if (!storeRef.current) {
+ storeRef.current = createEditorStore(initialEditorState ?? createInitialState());
+ }
+ return <EditorStoreContext.Provider value={storeRef.current}>{children}</EditorStoreContext.Provider>;
};
diff --git a/web/src/components/MemoEditor/state/reducer.ts b/web/src/components/MemoEditor/state/reducer.ts
index 200c0465b..6aff7ceba 100644
--- a/web/src/components/MemoEditor/state/reducer.ts
+++ b/web/src/components/MemoEditor/state/reducer.ts
@@ -26,42 +26,6 @@ export function editorReducer(state: EditorState, action: EditorAction): EditorS
},
};
- case "ADD_ATTACHMENT":
- return {
- ...state,
- metadata: {
- ...state.metadata,
- attachments: [...state.metadata.attachments, action.payload],
- },
- };
-
- case "REMOVE_ATTACHMENT":
- return {
- ...state,
- metadata: {
- ...state.metadata,
- attachments: state.metadata.attachments.filter((a) => a.name !== action.payload),
- },
- };
-
- case "ADD_RELATION":
- return {
- ...state,
- metadata: {
- ...state.metadata,
- relations: [...state.metadata.relations, action.payload],
- },
- };
-
- case "REMOVE_RELATION":
- return {
- ...state,
- metadata: {
- ...state.metadata,
- relations: state.metadata.relations.filter((r) => r.relatedMemo?.name !== action.payload),
- },
- };
-
case "ADD_LOCAL_FILE":
return {
...state,
@@ -80,12 +44,6 @@ export function editorReducer(state: EditorState, action: EditorAction): EditorS
localFiles: action.payload,
};
- case "CLEAR_LOCAL_FILES":
- return {
- ...state,
- localFiles: [],
- };
-
case "TOGGLE_FOCUS_MODE":
return {
...state,
@@ -116,50 +74,10 @@ export function editorReducer(state: EditorState, action: EditorAction): EditorS
},
};
- case "SET_AUDIO_RECORDER_SUPPORT":
- return {
- ...state,
- audioRecorder: {
- ...state.audioRecorder,
- isSupported: action.payload,
- status: action.payload ? state.audioRecorder.status : "unsupported",
- },
- };
-
- case "SET_AUDIO_RECORDER_PERMISSION":
- return {
- ...state,
- audioRecorder: {
- ...state.audioRecorder,
- permission: action.payload,
- },
- };
-
- case "SET_AUDIO_RECORDER_STATUS":
- return {
- ...state,
- audioRecorder: {
- ...state.audioRecorder,
- status: action.payload,
- },
- };
-
- case "SET_AUDIO_RECORDER_ELAPSED":
+ case "SET_RECORDER_BUSY":
return {
...state,
- audioRecorder: {
- ...state.audioRecorder,
- elapsedSeconds: action.payload,
- },
- };
-
- case "SET_AUDIO_RECORDER_ERROR":
- return {
- ...state,
- audioRecorder: {
- ...state.audioRecorder,
- error: action.payload,
- },
+ recorderBusy: action.payload,
};
case "SET_EDITOR_MODE":
diff --git a/web/src/components/MemoEditor/state/types.ts b/web/src/components/MemoEditor/state/types.ts
index 883390e10..2a5869368 100644
--- a/web/src/components/MemoEditor/state/types.ts
+++ b/web/src/components/MemoEditor/state/types.ts
@@ -5,8 +5,6 @@ import { type EditorMode, getPreferredEditorMode } from "../editorMode";
import type { LocalFile } from "../types/attachment";
export type LoadingKey = "saving" | "uploading" | "loading";
-export type AudioRecorderPermission = "unknown" | "granted" | "denied";
-export type AudioRecorderStatus = "idle" | "requesting_permission" | "recording" | "error" | "unsupported";
export interface EditorState {
content: string;
@@ -30,35 +28,22 @@ export interface EditorState {
updateTime?: Date;
};
localFiles: LocalFile[];
- audioRecorder: {
- isSupported: boolean;
- permission: AudioRecorderPermission;
- status: AudioRecorderStatus;
- elapsedSeconds: number;
- error?: string;
- };
+ /** Whether an audio recording is in flight; gates save. The recorder's full
+ * state lives in useAudioRecorder — only this shared bit reaches the store. */
+ recorderBusy: boolean;
}
export type EditorAction =
| { type: "INIT_MEMO"; payload: { content: string; metadata: EditorState["metadata"]; timestamps: EditorState["timestamps"] } }
| { type: "UPDATE_CONTENT"; payload: string }
| { type: "SET_METADATA"; payload: Partial<EditorState["metadata"]> }
- | { type: "ADD_ATTACHMENT"; payload: Attachment }
- | { type: "REMOVE_ATTACHMENT"; payload: string }
- | { type: "ADD_RELATION"; payload: MemoRelation }
- | { type: "REMOVE_RELATION"; payload: string }
| { type: "ADD_LOCAL_FILE"; payload: LocalFile }
| { type: "REMOVE_LOCAL_FILE"; payload: string }
| { type: "SET_LOCAL_FILES"; payload: LocalFile[] }
- | { type: "CLEAR_LOCAL_FILES" }
| { type: "TOGGLE_FOCUS_MODE" }
| { type: "SET_LOADING"; payload: { key: LoadingKey; value: boolean } }
| { type: "SET_TIMESTAMPS"; payload: Partial<EditorState["timestamps"]> }
- | { type: "SET_AUDIO_RECORDER_SUPPORT"; payload: boolean }
- | { type: "SET_AUDIO_RECORDER_PERMISSION"; payload: AudioRecorderPermission }
- | { type: "SET_AUDIO_RECORDER_STATUS"; payload: AudioRecorderStatus }
- | { type: "SET_AUDIO_RECORDER_ELAPSED"; payload: number }
- | { type: "SET_AUDIO_RECORDER_ERROR"; payload?: string }
+ | { type: "SET_RECORDER_BUSY"; payload: boolean }
| { type: "SET_EDITOR_MODE"; payload: EditorMode }
| { type: "RESET" };
@@ -87,13 +72,7 @@ const defaultState: EditorState = {
updateTime: undefined,
},
localFiles: [],
- audioRecorder: {
- isSupported: true,
- permission: "unknown",
- status: "idle",
- elapsedSeconds: 0,
- error: undefined,
- },
+ recorderBusy: false,
};
/**
diff --git a/web/src/components/MemoEditor/types/components.ts b/web/src/components/MemoEditor/types/components.ts
index 7f55747dc..914e828c5 100644
--- a/web/src/components/MemoEditor/types/components.ts
+++ b/web/src/components/MemoEditor/types/components.ts
@@ -1,5 +1,5 @@
import type { Location, Memo, Visibility } from "@/types/proto/api/v1/memo_service_pb";
-import type { EditorState } from "../state";
+import type { AudioRecorderStatus } from "../hooks/useAudioRecorder";
export interface MemoEditorProps {
className?: string;
@@ -37,7 +37,7 @@ export interface EditorMetadataProps {
}
export interface AudioRecorderPanelProps {
- audioRecorder: EditorState["audioRecorder"];
+ audioRecorder: { status: AudioRecorderStatus; elapsedSeconds: number };
/** Active mic stream while recording; used for live waveform visualization. */
mediaStream: MediaStream | null;
onStop: () => void;
diff --git a/web/src/components/MemoEditor/types/editorController.ts b/web/src/components/MemoEditor/types/editorController.ts
index c371dc7e8..1deb28666 100644
--- a/web/src/components/MemoEditor/types/editorController.ts
+++ b/web/src/components/MemoEditor/types/editorController.ts
@@ -1,7 +1,9 @@
+import type { ActiveFormatState, EditorCommandContext, EditorCommandId } from "../Editor/editorCommands";
+
/**
* The contract both memo editors (raw textarea and WYSIWYG) implement.
- * Everything outside an editor implementation must talk markdown through this
- * interface and never reach for an editor's internal DOM/ProseMirror APIs.
+ * Everything outside an editor implementation talks markdown through this
+ * interface and never reaches for an editor's internal DOM/ProseMirror APIs.
*/
export interface EditorController {
focus(): void;
@@ -17,43 +19,28 @@ export interface EditorController {
scrollToCursor(): void;
/** Select the entire document (used by tests and select-all flows). */
selectAll(): void;
- // Formatting intents — each editor realizes them natively.
- toggleBold(): void;
- toggleItalic(): void;
- toggleTaskList(): void;
+ /**
+ * 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.
+ */
+ formatting?: FormattingController;
}
-/** Heading levels surfaced in the formatting toolbar's heading dropdown. */
-export type ToolbarHeadingLevel = 1 | 2 | 3;
-
/**
- * Rich-formatting surface used by the focus-mode FormattingToolbar. Additive to
- * EditorController and implemented only by the WYSIWYG editor — the toolbar is
- * never shown for the raw editor, so EditorContent routes these to the WYSIWYG
- * handle and returns inert defaults in raw mode.
- *
- * isActive / subscribe are the sanctioned (and only) place ProseMirror state
- * leaks across the editor boundary, so toolbar buttons can reflect live state.
+ * 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.
*/
export interface FormattingController {
- // toggleBold / toggleItalic / toggleTaskList come from EditorController — the
- // toolbar always consumes `EditorController & FormattingController`.
- toggleCode(): void;
- toggleBulletList(): void;
- toggleOrderedList(): void;
- /** Set the current block to a heading of the given level. */
- setHeading(level: ToolbarHeadingLevel): void;
- /** Set the current block back to a paragraph. */
- setParagraph(): void;
- /**
- * Toggle a link. When a link is active it is removed; otherwise the given URL
- * is applied to the current selection/word. No-ops when adding without a URL.
- */
- toggleLink(url?: string): void;
+ /** Run a catalog command (e.g. "bold", "heading2", "link"). */
+ run(command: EditorCommandId, ctx?: EditorCommandContext): void;
+ /** Snapshot of which marks/blocks are active at the current selection. */
+ getActiveFormats(): ActiveFormatState;
/** Plain text of the current selection ("" when the selection is empty). */
getSelectedText(): string;
- /** Whether a mark/node (optionally with attrs) is active at the selection. */
- isActive(name: string, attrs?: Record<string, unknown>): boolean;
- /** Register a listener fired on every editor transaction/selection change. Returns an unsubscribe. */
+ /** Register a listener fired on every transaction/selection change. Returns an unsubscribe. */
subscribe(listener: () => void): () => void;
}
diff --git a/web/src/utils/remark-plugins/remark-tag.ts b/web/src/utils/remark-plugins/remark-tag.ts
index 96f11408e..e21847189 100644
--- a/web/src/utils/remark-plugins/remark-tag.ts
+++ b/web/src/utils/remark-plugins/remark-tag.ts
@@ -1,24 +1,7 @@
import type { Root, Text } from "mdast";
import type { Node as UnistNode } from "unist";
import type { TagNode, TagNodeData } from "@/types/markdown";
-
-const MAX_TAG_LENGTH = 100;
-
-function isTagChar(char: string): boolean {
- if (/\p{L}/u.test(char)) {
- return true;
- }
-
- if (/\p{N}/u.test(char)) {
- return true;
- }
-
- if (/\p{S}/u.test(char)) {
- return true;
- }
-
- return char === "_" || char === "-" || char === "/" || char === "&";
-}
+import { isTagChar, MAX_TAG_LENGTH } from "@/utils/tag-grammar";
function parseTagsFromText(text: string): Array<{ type: "text"; value: string } | { type: "tag"; value: string }> {
const segments: Array<{ type: "text"; value: string } | { type: "tag"; value: string }> = [];
diff --git a/web/src/utils/tag-grammar.ts b/web/src/utils/tag-grammar.ts
new file mode 100644
index 000000000..b35d16f80
--- /dev/null
+++ b/web/src/utils/tag-grammar.ts
@@ -0,0 +1,21 @@
+/**
+ * The single source of truth for memos' `#tag` lexing grammar, shared by the
+ * editor tokenizer (components/MemoEditor/Editor/Tag.ts) and the read-only
+ * renderer (utils/remark-plugins/remark-tag.ts) so the two can't drift.
+ *
+ * A tag character is any Unicode letter, number, or symbol, plus `_ - / &`.
+ * A tag run is capped at MAX_TAG_LENGTH characters.
+ */
+export const TAG_CHAR_CLASS = "[\\p{L}\\p{N}\\p{S}_\\-/&]";
+
+export const MAX_TAG_LENGTH = 100;
+
+// Matches exactly one tag character. The `u` flag makes the class match whole
+// code points, so astral-plane symbols (emoji et al.) are tested intact rather
+// than as lone surrogates.
+const SINGLE_TAG_CHAR = new RegExp(`^${TAG_CHAR_CLASS}$`, "u");
+
+/** Whether a single character (one code point) is allowed inside a tag. */
+export function isTagChar(char: string): boolean {
+ return SINGLE_TAG_CHAR.test(char);
+}
diff --git a/web/tests/editor-commands.test.ts b/web/tests/editor-commands.test.ts
new file mode 100644
index 000000000..d1a8b777f
--- /dev/null
+++ b/web/tests/editor-commands.test.ts
@@ -0,0 +1,65 @@
+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.tsx b/web/tests/editor-controller.test.tsx
index 607f6c0b3..4769854b6 100644
--- a/web/tests/editor-controller.test.tsx
+++ b/web/tests/editor-controller.test.tsx
@@ -71,16 +71,16 @@ describe("Editor EditorController", () => {
expect(onContentChange).toHaveBeenCalledWith(expect.stringContaining("hello"));
});
- it("toggleBold bolds the selected text", () => {
+ it("formatting.run('bold') bolds the selected text", () => {
const { ref } = setup("bold me");
act(() => ref.current?.selectAll());
- act(() => ref.current?.toggleBold());
+ act(() => ref.current?.formatting?.run("bold"));
expect(ref.current?.getMarkdown()).toBe("**bold me**");
});
- it("toggleTaskList converts the current block", () => {
+ it("formatting.run('taskList') converts the current block", () => {
const { ref } = setup("buy milk");
- act(() => ref.current?.toggleTaskList());
+ act(() => ref.current?.formatting?.run("taskList"));
expect(ref.current?.getMarkdown()).toBe("- [ ] buy milk");
});
});
diff --git a/web/tests/editor-load-guard.test.tsx b/web/tests/editor-load-guard.test.tsx
index 83dd19b31..85d40966e 100644
--- a/web/tests/editor-load-guard.test.tsx
+++ b/web/tests/editor-load-guard.test.tsx
@@ -2,7 +2,7 @@ import { create } from "@bufbuild/protobuf";
import { render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { useMemoInit } from "@/components/MemoEditor/hooks";
-import { EditorProvider, useEditorContext } from "@/components/MemoEditor/state";
+import { EditorProvider, useEditorSelector } from "@/components/MemoEditor/state";
import { MemoSchema } from "@/types/proto/api/v1/memo_service_pb";
const toastMock = vi.hoisted(() => vi.fn());
@@ -21,8 +21,8 @@ vi.mock("@/utils/i18n", () => ({ useTranslate: () => (key: string) => key }));
function Harness({ content }: { content: string }) {
const memo = create(MemoSchema, { name: "memos/1", content });
useMemoInit({ editorRef: { current: null }, memo, username: "users/test" });
- const { state } = useEditorContext();
- return <span data-testid="mode">{state.ui.editorMode}</span>;
+ const editorMode = useEditorSelector((s) => s.ui.editorMode);
+ return <span data-testid="mode">{editorMode}</span>;
}
function renderGuard(content: string) {
diff --git a/web/tests/editor-mode-toggle.test.tsx b/web/tests/editor-mode-toggle.test.tsx
index 3431fc4b0..d29d011aa 100644
--- a/web/tests/editor-mode-toggle.test.tsx
+++ b/web/tests/editor-mode-toggle.test.tsx
@@ -1,7 +1,7 @@
import { act, fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { EditorContent } from "@/components/MemoEditor/components/EditorContent";
-import { EditorProvider, useEditorContext } from "@/components/MemoEditor/state";
+import { EditorProvider, useEditorContext, useEditorSelector } from "@/components/MemoEditor/state";
vi.mock("@/hooks/useUserQueries", () => ({
useTagCounts: () => ({ data: {} }),
@@ -11,15 +11,16 @@ vi.mock("@/hooks/useUserQueries", () => ({
vi.mock("@/utils/i18n", () => ({ useTranslate: () => (key: string) => key }));
function ModeProbe() {
- const { state, actions, dispatch } = useEditorContext();
+ const { actions, dispatch } = useEditorContext();
+ const editorMode = useEditorSelector((s) => s.ui.editorMode);
return (
<>
<button
type="button"
data-testid="probe-toggle"
- onClick={() => dispatch(actions.setEditorMode(state.ui.editorMode === "wysiwyg" ? "raw" : "wysiwyg"))}
+ onClick={() => dispatch(actions.setEditorMode(editorMode === "wysiwyg" ? "raw" : "wysiwyg"))}
>
- {state.ui.editorMode}
+ {editorMode}
</button>
<button type="button" data-testid="probe-set-content" onClick={() => dispatch(actions.updateContent("from **wysiwyg**"))}>
set content
diff --git a/web/tests/formatting-controller.test.tsx b/web/tests/formatting-controller.test.tsx
index fda4b1937..cdf71c884 100644
--- a/web/tests/formatting-controller.test.tsx
+++ b/web/tests/formatting-controller.test.tsx
@@ -2,77 +2,79 @@ import { act, render } from "@testing-library/react";
import { createRef } from "react";
import { describe, expect, it, vi } from "vitest";
import Editor from "@/components/MemoEditor/Editor";
-import type { EditorController, FormattingController } from "@/components/MemoEditor/types/editorController";
+import type { EditorController } from "@/components/MemoEditor/types/editorController";
vi.mock("@/hooks/useUserQueries", async (importOriginal) => ({
...(await importOriginal<object>()),
useTagCounts: () => ({ data: {} }),
}));
-type Handle = EditorController & FormattingController;
-
function setup(initialContent = "") {
- const ref = createRef<Handle>();
+ const ref = createRef<EditorController>();
render(<Editor ref={ref} initialContent={initialContent} placeholder="memo" onContentChange={vi.fn()} onPaste={vi.fn()} />);
return ref;
}
-describe("FormattingController (WYSIWYG)", () => {
- it("toggleCode wraps the selection in inline code", () => {
+describe("WYSIWYG formatting capability", () => {
+ it("the WYSIWYG editor exposes a formatting capability", () => {
+ const ref = setup("x");
+ expect(ref.current?.formatting).toBeDefined();
+ });
+
+ it("run('code') wraps the selection in inline code", () => {
const ref = setup("code me");
act(() => ref.current?.selectAll());
- act(() => ref.current?.toggleCode());
+ act(() => ref.current?.formatting?.run("code"));
expect(ref.current?.getMarkdown()).toBe("`code me`");
});
- it("toggleBulletList converts the current block", () => {
+ it("run('bulletList') converts the current block", () => {
const ref = setup("item");
- act(() => ref.current?.toggleBulletList());
+ act(() => ref.current?.formatting?.run("bulletList"));
expect(ref.current?.getMarkdown()).toBe("- item");
});
- it("toggleOrderedList converts the current block", () => {
+ it("run('orderedList') converts the current block", () => {
const ref = setup("item");
- act(() => ref.current?.toggleOrderedList());
+ act(() => ref.current?.formatting?.run("orderedList"));
expect(ref.current?.getMarkdown()).toBe("1. item");
});
- it("setHeading makes the block a heading and isActive reflects the level", () => {
+ it("run('heading2') makes the block a heading and getActiveFormats reflects the level", () => {
const ref = setup("title");
- act(() => ref.current?.setHeading(2));
+ act(() => ref.current?.formatting?.run("heading2"));
expect(ref.current?.getMarkdown()).toBe("## title");
- expect(ref.current?.isActive("heading", { level: 2 })).toBe(true);
- expect(ref.current?.isActive("heading", { level: 1 })).toBe(false);
+ expect(ref.current?.formatting?.getActiveFormats().headingLevel).toBe(2);
});
- it("setParagraph reverts a heading", () => {
+ it("run('paragraph') reverts a heading", () => {
const ref = setup("# title");
- act(() => ref.current?.setParagraph());
+ act(() => ref.current?.formatting?.run("paragraph"));
expect(ref.current?.getMarkdown()).toBe("title");
});
- it("isActive('bold') tracks the bold mark", () => {
+ it("getActiveFormats().bold tracks the bold mark", () => {
const ref = setup("x");
- expect(ref.current?.isActive("bold")).toBe(false);
+ expect(ref.current?.formatting?.getActiveFormats().bold).toBe(false);
act(() => ref.current?.selectAll());
- act(() => ref.current?.toggleBold());
- expect(ref.current?.isActive("bold")).toBe(true);
+ act(() => ref.current?.formatting?.run("bold"));
+ expect(ref.current?.formatting?.getActiveFormats().bold).toBe(true);
});
- it("toggleLink applies a link over the selection, and removes it when active", () => {
+ it("run('link') applies a link over the selection, and removes it when active", () => {
const ref = setup("memos");
act(() => ref.current?.selectAll());
- act(() => ref.current?.toggleLink("https://usememos.com"));
+ act(() => ref.current?.formatting?.run("link", { url: "https://usememos.com" }));
expect(ref.current?.getMarkdown()).toBe("[memos](https://usememos.com)");
act(() => ref.current?.selectAll());
- act(() => ref.current?.toggleLink());
+ act(() => ref.current?.formatting?.run("link"));
expect(ref.current?.getMarkdown()).toBe("memos");
});
it("getSelectedText returns the current selection text", () => {
const ref = setup("hello world");
act(() => ref.current?.selectAll());
- expect(ref.current?.getSelectedText()).toBe("hello world");
+ expect(ref.current?.formatting?.getSelectedText()).toBe("hello world");
});
it("subscribe fires on transactions and unsubscribe stops it", () => {
@@ -80,14 +82,14 @@ describe("FormattingController (WYSIWYG)", () => {
const listener = vi.fn();
let unsubscribe = () => {};
act(() => {
- unsubscribe = ref.current!.subscribe(listener);
+ unsubscribe = ref.current!.formatting!.subscribe(listener);
});
act(() => ref.current?.selectAll());
- act(() => ref.current?.toggleBold());
+ act(() => ref.current?.formatting?.run("bold"));
const callsWhileSubscribed = listener.mock.calls.length;
expect(callsWhileSubscribed).toBeGreaterThan(0);
act(() => unsubscribe());
- act(() => ref.current?.toggleItalic());
+ act(() => ref.current?.formatting?.run("italic"));
expect(listener.mock.calls.length).toBe(callsWhileSubscribed);
});
});
diff --git a/web/tests/formatting-toolbar.test.tsx b/web/tests/formatting-toolbar.test.tsx
index a29191752..f1e5a920c 100644
--- a/web/tests/formatting-toolbar.test.tsx
+++ b/web/tests/formatting-toolbar.test.tsx
@@ -2,7 +2,8 @@ import { fireEvent, render, screen } from "@testing-library/react";
import { createRef } from "react";
import { beforeAll, describe, expect, it, vi } from "vitest";
import { FormattingToolbar } from "@/components/MemoEditor/components/FormattingToolbar";
-import type { EditorController, FormattingController } from "@/components/MemoEditor/types/editorController";
+import { type ActiveFormatState, EMPTY_ACTIVE_FORMATS } from "@/components/MemoEditor/Editor/editorCommands";
+import type { EditorController } from "@/components/MemoEditor/types/editorController";
// Match the repo convention: t echoes the i18n key (no i18next backend in tests),
// so accessible names below are the keys themselves.
@@ -16,87 +17,80 @@ beforeAll(() => {
Element.prototype.releasePointerCapture = vi.fn();
});
-type Handle = EditorController & FormattingController;
-
-function makeController(overrides: Partial<Handle> = {}): Handle {
- const noop = () => {};
- return {
- focus: noop,
+function makeController(opts: { active?: Partial<ActiveFormatState>; getSelectedText?: () => string } = {}) {
+ const run = vi.fn();
+ const activeFormats: ActiveFormatState = { ...EMPTY_ACTIVE_FORMATS, ...opts.active };
+ const controller: EditorController = {
+ focus: () => {},
hasFocus: () => false,
isEmpty: () => true,
getMarkdown: () => "",
- setMarkdown: noop,
- insertMarkdown: noop,
- scrollToCursor: noop,
- selectAll: noop,
- toggleBold: vi.fn(),
- toggleItalic: vi.fn(),
- toggleTaskList: vi.fn(),
- toggleCode: vi.fn(),
- toggleBulletList: vi.fn(),
- toggleOrderedList: vi.fn(),
- setHeading: vi.fn(),
- setParagraph: vi.fn(),
- toggleLink: vi.fn(),
- getSelectedText: () => "",
- isActive: () => false,
- subscribe: () => () => {},
- ...overrides,
+ setMarkdown: () => {},
+ insertMarkdown: vi.fn(),
+ scrollToCursor: () => {},
+ selectAll: () => {},
+ formatting: {
+ run,
+ getActiveFormats: () => activeFormats,
+ getSelectedText: opts.getSelectedText ?? (() => ""),
+ subscribe: () => () => {},
+ },
};
+ return { controller, run };
}
-function renderToolbar(controller: Handle, onExit = vi.fn()) {
- const ref = createRef<Handle>();
+function renderToolbar(controller: EditorController, onExit = vi.fn()) {
+ const ref = createRef<EditorController>();
ref.current = controller;
render(<FormattingToolbar controllerRef={ref} onExit={onExit} />);
return { onExit };
}
describe("FormattingToolbar", () => {
- it("invokes toggleBold when the bold button is clicked", () => {
- const controller = makeController();
+ it("runs the bold command when the bold button is clicked", () => {
+ const { controller, run } = makeController();
renderToolbar(controller);
fireEvent.click(screen.getByRole("button", { name: "editor.format.bold" }));
- expect(controller.toggleBold).toHaveBeenCalledTimes(1);
+ expect(run).toHaveBeenCalledWith("bold");
});
- it("invokes setHeading when a heading level is chosen", () => {
- const controller = makeController();
+ it("runs the heading command when a heading level is chosen", () => {
+ const { controller, run } = makeController();
renderToolbar(controller);
// Keyboard open is the most reliable path for Radix menus in jsdom.
fireEvent.keyDown(screen.getByRole("button", { name: "editor.format.heading" }), { key: "Enter" });
fireEvent.click(screen.getByRole("menuitem", { name: "editor.format.heading-2" }));
- expect(controller.setHeading).toHaveBeenCalledWith(2);
+ expect(run).toHaveBeenCalledWith("heading2");
});
it("reflects active marks via aria-pressed", () => {
- const controller = makeController({ isActive: (name) => name === "bold" });
+ const { controller } = makeController({ active: { bold: true } });
renderToolbar(controller);
expect(screen.getByRole("button", { name: "editor.format.bold" })).toHaveAttribute("aria-pressed", "true");
expect(screen.getByRole("button", { name: "editor.format.italic" })).toHaveAttribute("aria-pressed", "false");
});
it("prompts for a URL and links the selection when adding a link", () => {
- const controller = makeController({ getSelectedText: () => "memos" });
+ const { controller, run } = makeController({ getSelectedText: () => "memos" });
const promptSpy = vi.spyOn(window, "prompt").mockReturnValue("https://usememos.com");
renderToolbar(controller);
fireEvent.click(screen.getByRole("button", { name: "editor.format.link" }));
- expect(controller.toggleLink).toHaveBeenCalledWith("https://usememos.com");
+ expect(run).toHaveBeenCalledWith("link", { url: "https://usememos.com" });
promptSpy.mockRestore();
});
it("removes an active link without prompting", () => {
- const controller = makeController({ isActive: (name) => name === "link" });
+ const { controller, run } = makeController({ active: { link: true } });
const promptSpy = vi.spyOn(window, "prompt");
renderToolbar(controller);
fireEvent.click(screen.getByRole("button", { name: "editor.format.link" }));
expect(promptSpy).not.toHaveBeenCalled();
- expect(controller.toggleLink).toHaveBeenCalledWith();
+ expect(run).toHaveBeenCalledWith("link");
promptSpy.mockRestore();
});
it("calls onExit when the exit button is clicked", () => {
- const controller = makeController();
+ const { controller } = makeController();
const { onExit } = renderToolbar(controller);
fireEvent.click(screen.getByRole("button", { name: "editor.exit-focus-mode" }));
expect(onExit).toHaveBeenCalledTimes(1);
diff --git a/web/tests/insert-menu-mode-toggle.test.tsx b/web/tests/insert-menu-mode-toggle.test.tsx
index 3c44ff914..92f265ce9 100644
--- a/web/tests/insert-menu-mode-toggle.test.tsx
+++ b/web/tests/insert-menu-mode-toggle.test.tsx
@@ -1,7 +1,7 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { fireEvent, render, screen } from "@testing-library/react";
import { beforeAll, describe, expect, it, vi } from "vitest";
-import { EditorProvider, useEditorContext } from "@/components/MemoEditor/state";
+import { EditorProvider, useEditorSelector } from "@/components/MemoEditor/state";
import InsertMenu from "@/components/MemoEditor/Toolbar/InsertMenu";
// useTranslate returns the i18n key directly (no i18next backend in tests).
@@ -20,8 +20,8 @@ beforeAll(() => {
});
function ModeProbe() {
- const { state } = useEditorContext();
- return <span data-testid="mode">{state.ui.editorMode}</span>;
+ const editorMode = useEditorSelector((s) => s.ui.editorMode);
+ return <span data-testid="mode">{editorMode}</span>;
}
function renderInsertMenu() {
diff --git a/web/tests/plain-editor-controller.test.tsx b/web/tests/plain-editor-controller.test.tsx
index 362df2d00..dd9e10062 100644
--- a/web/tests/plain-editor-controller.test.tsx
+++ b/web/tests/plain-editor-controller.test.tsx
@@ -34,36 +34,11 @@ describe("PlainEditor EditorController", () => {
expect(textarea.value).toBe("first line\n\ntranscribed");
});
- it("toggleBold wraps the selection in **", () => {
- const { controller, textarea } = setup("read the docs");
- textarea.setSelectionRange(9, 13);
- controller.toggleBold();
- expect(textarea.value).toBe("read the **docs**");
- });
-
- it("toggleTaskList prefixes and unprefixes the current line", () => {
- const { controller, textarea } = setup("buy milk");
- textarea.setSelectionRange(4, 4);
- controller.toggleTaskList();
- expect(textarea.value).toBe("- [ ] buy milk");
- controller.toggleTaskList();
- expect(textarea.value).toBe("buy milk");
- });
-
- it("toggleTaskList unprefixes a checked task line", () => {
- const { controller, textarea } = setup("- [x] done thing");
- textarea.setSelectionRange(8, 8);
- controller.toggleTaskList();
- expect(textarea.value).toBe("done thing");
- });
-
- it("toggleTaskList preserves indentation", () => {
- const { controller, textarea } = setup(" nested item");
- textarea.setSelectionRange(4, 4);
- controller.toggleTaskList();
- expect(textarea.value).toBe(" - [ ] nested item");
- controller.toggleTaskList();
- expect(textarea.value).toBe(" nested item");
+ // The raw textarea is an honest fallback with no rich-formatting capability
+ // (controller.formatting is undefined); the focus-mode toolbar is WYSIWYG-only.
+ it("exposes no formatting capability", () => {
+ const { controller } = setup("x");
+ expect(controller.formatting).toBeUndefined();
});
it("insertMarkdown with an empty string is a no-op", () => {
diff --git a/web/tests/suggestion-extension.test.ts b/web/tests/suggestion-extension.test.ts
new file mode 100644
index 000000000..5939be929
--- /dev/null
+++ b/web/tests/suggestion-extension.test.ts
@@ -0,0 +1,77 @@
+import { Editor } from "@tiptap/core";
+import { describe, expect, it } from "vitest";
+import { buildExtensions } from "@/components/MemoEditor/Editor/extensions";
+import { createSuggestionExtension } from "@/components/MemoEditor/Editor/suggestionExtension";
+
+describe("createSuggestionExtension", () => {
+ it("creates a Tiptap extension with the configured name", () => {
+ const ext = createSuggestionExtension<string>({
+ name: "fooSuggestion",
+ char: "@",
+ items: () => [],
+ command: () => {},
+ renderItem: (item) => item,
+ getItemKey: (item) => item,
+ });
+ expect(ext.name).toBe("fooSuggestion");
+ });
+
+ it("contributes its suggestion plugin to the editor", () => {
+ const base = new Editor({ extensions: buildExtensions(), content: "", contentType: "markdown" });
+ const baseline = base.state.plugins.length;
+ base.destroy();
+
+ const withSuggestion = new Editor({
+ extensions: [
+ ...buildExtensions(),
+ createSuggestionExtension<string>({
+ name: "pluginProbe",
+ char: "@",
+ items: () => [],
+ command: () => {},
+ renderItem: (item) => item,
+ getItemKey: (item) => item,
+ }),
+ ],
+ content: "",
+ contentType: "markdown",
+ });
+ try {
+ expect(withSuggestion.state.plugins.length).toBeGreaterThan(baseline);
+ } finally {
+ withSuggestion.destroy();
+ }
+ });
+
+ it("lets multiple triggers coexist in one editor without plugin-key collision", () => {
+ const tagLike = createSuggestionExtension<string>({
+ name: "tagLike",
+ char: "#",
+ items: () => ["alpha"],
+ command: () => {},
+ renderItem: (item) => item,
+ getItemKey: (item) => item,
+ });
+ const slashLike = createSuggestionExtension<string>({
+ name: "slashLike",
+ char: "/",
+ items: () => ["heading"],
+ command: () => {},
+ renderItem: (item) => item,
+ getItemKey: (item) => item,
+ });
+
+ const editor = new Editor({
+ extensions: [...buildExtensions(), tagLike, slashLike],
+ content: "",
+ contentType: "markdown",
+ });
+ try {
+ const names = editor.extensionManager.extensions.map((e) => e.name);
+ expect(names).toContain("tagLike");
+ expect(names).toContain("slashLike");
+ } finally {
+ editor.destroy();
+ }
+ });
+});
diff --git a/web/tests/use-auto-save.test.tsx b/web/tests/use-auto-save.test.tsx
new file mode 100644
index 000000000..f96ded3f2
--- /dev/null
+++ b/web/tests/use-auto-save.test.tsx
@@ -0,0 +1,85 @@
+import { act, render } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { useAutoSave } from "@/components/MemoEditor/hooks/useAutoSave";
+import { cacheService } from "@/components/MemoEditor/services/cacheService";
+import { EditorProvider, useEditorContext } from "@/components/MemoEditor/state";
+
+// Probe surfaces the store's dispatch/actions plus the autosave API so tests can
+// drive content changes the way the editor does and assert on cache writes.
+let api: {
+ dispatch: ReturnType<typeof useEditorContext>["dispatch"];
+ actions: ReturnType<typeof useEditorContext>["actions"];
+ discardDraft: () => void;
+};
+
+function Probe({ username, cacheKey, enabled }: { username: string; cacheKey?: string; enabled?: boolean }) {
+ const { dispatch, actions } = useEditorContext();
+ const { discardDraft } = useAutoSave(username, cacheKey, enabled);
+ api = { dispatch, actions, discardDraft };
+ return null;
+}
+
+describe("useAutoSave (store-subscribed)", () => {
+ let saveSpy: ReturnType<typeof vi.spyOn>;
+ let saveNowSpy: ReturnType<typeof vi.spyOn>;
+ let clearSpy: ReturnType<typeof vi.spyOn>;
+
+ beforeEach(() => {
+ saveSpy = vi.spyOn(cacheService, "save").mockImplementation(() => {});
+ saveNowSpy = vi.spyOn(cacheService, "saveNow").mockImplementation(() => {});
+ clearSpy = vi.spyOn(cacheService, "clear").mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it("persists content to the draft cache when content changes", () => {
+ render(
+ <EditorProvider>
+ <Probe username="users/steven" cacheKey="k" enabled />
+ </EditorProvider>,
+ );
+ const key = cacheService.key("users/steven", "k");
+ saveSpy.mockClear(); // ignore the mount-time persist of the initial empty content
+ act(() => {
+ api.dispatch(api.actions.updateContent("hello world"));
+ });
+ expect(saveSpy).toHaveBeenCalledWith(key, "hello world");
+ });
+
+ it("does not persist when disabled", () => {
+ render(
+ <EditorProvider>
+ <Probe username="users/steven" cacheKey="k" enabled={false} />
+ </EditorProvider>,
+ );
+ saveSpy.mockClear();
+ act(() => {
+ api.dispatch(api.actions.updateContent("ignored"));
+ });
+ expect(saveSpy).not.toHaveBeenCalled();
+ });
+
+ it("discardDraft clears the cache and suppresses the unmount flush", () => {
+ const { unmount } = render(
+ <EditorProvider>
+ <Probe username="users/steven" cacheKey="k2" enabled />
+ </EditorProvider>,
+ );
+ const key = cacheService.key("users/steven", "k2");
+ act(() => {
+ api.dispatch(api.actions.updateContent("draft body"));
+ });
+ act(() => {
+ api.discardDraft();
+ });
+ expect(clearSpy).toHaveBeenCalledWith(key);
+
+ saveNowSpy.mockClear();
+ unmount();
+ // The just-discarded content equals the latest content, so the unmount
+ // flush must NOT re-persist it as a stale draft.
+ expect(saveNowSpy).not.toHaveBeenCalled();
+ });
+});