diff --git a/web/src/components/MemoEditor/Editor/Tag.ts b/web/src/components/MemoEditor/Editor/Tag.ts index 16bdc495..12734d03 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 ef584103..94f72357 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({ - name: "tagSuggestion", - - addOptions() { - return { getTags: () => [] }; - }, - - addProseMirrorPlugins() { - return [ - Suggestion({ - 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({ - 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({ + 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 00000000..39d3941e --- /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 bd32ffca..71049493 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(function Editor(props, ref) { +const Editor = forwardRef(function Editor(props, ref) { const { className, initialContent, placeholder, isFocusMode, onContentChange, onPaste } = props; // Last markdown emitted through onContentChange, so the sync effect can @@ -100,7 +101,7 @@ const Editor = forwardRef( 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( () => [ ...buildExtensions(), Placeholder.configure({ placeholder: () => placeholderRef.current }), - TagSuggestion.configure({ getTags: () => tagsRef.current }), + createTagSuggestion({ getTags: () => tagsRef.current }), SaveShortcutPassthrough, CollapseAllSelectionAfterDelete, ], @@ -200,7 +201,7 @@ const Editor = forwardRef( 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( 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 00000000..fec95d7a --- /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 { + /** Unique extension + plugin-key name, e.g. "tagSuggestion". */ + name: string; + /** The character that opens the popup, e.g. "#" or "/". */ + char: string; + /** Whether a space inside the query keeps the popup open. Defaults to false. */ + allowSpaces?: boolean; + /** Resolve the items to show for the current query (already stripped of `char`). */ + items: (query: string) => T[]; + /** Apply the chosen item to the document. */ + command: SuggestionOptions["command"]; + /** Render a single item row. */ + renderItem: (item: T, isSelected: boolean) => ReactNode; + /** Stable React key for an item. */ + getItemKey: (item: T) => string; +} + +/** + * Build a Tiptap extension that shows the shared suggestion popup when `char` + * is typed. Mirrors the original hand-written TagSuggestion exactly; it just + * factors out the parts every trigger repeats so adding another is ~10 lines. + */ +export function createSuggestionExtension(config: SuggestionExtensionConfig): Extension { + return Extension.create({ + name: config.name, + + addProseMirrorPlugins() { + return [ + Suggestion({ + editor: this.editor, + pluginKey: new PluginKey(config.name), + char: config.char, + allowSpaces: config.allowSpaces ?? false, + items: ({ query }) => config.items(query), + command: config.command, + render: createSuggestionRenderer({ + renderItem: config.renderItem, + getItemKey: config.getItemKey, + }), + }), + ]; + }, + }); +} diff --git a/web/src/components/MemoEditor/Editor/suggestionMenu.tsx b/web/src/components/MemoEditor/Editor/suggestionMenu.tsx index 10240bfd..3cf955f0 100644 --- a/web/src/components/MemoEditor/Editor/suggestionMenu.tsx +++ b/web/src/components/MemoEditor/Editor/suggestionMenu.tsx @@ -25,7 +25,7 @@ interface SuggestionMenuProps { 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 9ddb04ef..86ec3a1e 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) { const { className, initialContent, placeholder, onPaste, onContentChange: handleContentChangeCallback, isFocusMode } = props; const editorRef = useRef(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 295ed22a..6241b257 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")} {/* Editor display mode: checked = rich text (WYSIWYG), unchecked = raw Markdown */} - + {t("editor.wysiwyg-editor")} diff --git a/web/src/components/MemoEditor/components/EditorContent.tsx b/web/src/components/MemoEditor/components/EditorContent.tsx index b3e49bc2..38990c70 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(({ placeholder }, ref) => { - const { state, actions, dispatch } = useEditorContext(); +export const EditorContent = forwardRef(({ 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(null); + const wysiwygRef = useRef(null); const plainRef = useRef(null); const modeRef = useRef(mode); @@ -40,7 +42,7 @@ export const EditorContent = forwardRef ({ + (): EditorController => ({ focus: () => getActive()?.focus(), hasFocus: () => getActive()?.hasFocus() ?? false, isEmpty: () => getActive()?.isEmpty() ?? true, @@ -49,20 +51,12 @@ export const EditorContent = forwardRef 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) => 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 @@ -122,9 +116,9 @@ export const EditorContent = forwardRef diff --git a/web/src/components/MemoEditor/components/EditorMetadata.tsx b/web/src/components/MemoEditor/components/EditorMetadata.tsx index ee984e13..da89d25e 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 = ({ 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 (
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))} /> dispatch(actions.setMetadata({ relations }))} + relations={relations} + onRelationsChange={(next) => dispatch(actions.setMetadata({ relations: next }))} memoName={memoName} /> - {state.metadata.location && ( - dispatch(actions.setMetadata({ location: undefined }))} /> - )} + {location && dispatch(actions.setMetadata({ location: undefined }))} />}
); }; diff --git a/web/src/components/MemoEditor/components/EditorToolbar.tsx b/web/src/components/MemoEditor/components/EditorToolbar.tsx index 5205e0b5..a6cbbe1c 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 = ({ onSave, onCancel, memoName, onAudioRecorderClick }) => { const t = useTranslate(); - const { state, actions, dispatch } = useEditorContext(); - const { valid } = validationService.canSave(state); + 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 isSaving = state.ui.isLoading.saving; - - const handleLocationChange = (location: typeof state.metadata.location) => { - dispatch(actions.setMetadata({ location })); + 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 (
= ({ onSave, onCancel, memoNa
- + {onCancel && ( ); } diff --git a/web/src/components/MemoEditor/components/TimestampPopover.tsx b/web/src/components/MemoEditor/components/TimestampPopover.tsx index f25989eb..6c7bdd70 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 6c207850..18013b64 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 63722e59..42b431e3 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("idle"); + const [elapsedSeconds, setElapsedSeconds] = useState(0); + const [error, setError] = useState(undefined); + const [recordingStream, setRecordingStream] = useState(null); + const mediaRecorderRef = useRef(null); const mediaStreamRef = useRef(null); - const [recordingStream, setRecordingStream] = useState(null); const chunksRef = useRef([]); const startedAtRef = useRef(null); const elapsedTimerRef = useRef(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 18eb903e..6b4ef4e4 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(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 72959cc7..e7a1cb89 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 9e32204f..24bc379a 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(EMPTY_ACTIVE); +export function useEditorActiveState(controllerRef: RefObject): ActiveFormatState { + const [active, setActive] = useState(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 ae69db2b..142968a9 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(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) => { 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 1ba5ff32..340984ab 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) => ( @@ -50,8 +50,14 @@ const MemoEditorImpl: React.FC = ({ const t = useTranslate(); const queryClient = useQueryClient(); const currentUser = useCurrentUser(); - const editorRef = useRef(null); - const { state, actions, dispatch } = useEditorContext(); + const editorRef = useRef(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 = ({ }); 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 = ({ [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 = ({ }; const handleAudioRecorderClick = () => { - if (state.audioRecorder.status === "recording" || state.audioRecorder.status === "requesting_permission") { + if (audioRecorder.isBusy) { return; } @@ -229,6 +231,9 @@ const MemoEditorImpl: React.FC = ({ 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 = ({ return ( <> - + {/* Layout structure: @@ -314,20 +319,20 @@ const MemoEditorImpl: React.FC = ({ 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" ? ( ) : ( ))} - {(memoName || (!memo && state.timestamps.createTime)) && ( + {(memoName || (!memo && hasTimestamp)) && (
@@ -336,18 +341,17 @@ const MemoEditorImpl: React.FC = ({ {/* Editor content grows to fill available space in focus mode */} - {isAudioRecorderOpen && - (state.audioRecorder.status === "recording" || state.audioRecorder.status === "requesting_permission" || isTranscribingAudio) && ( - - )} + {isAudioRecorderOpen && (audioRecorder.isBusy || isTranscribingAudio) && ( + + )} {/* Metadata and toolbar grouped together at bottom */}
diff --git a/web/src/components/MemoEditor/services/validationService.ts b/web/src/components/MemoEditor/services/validationService.ts index 8c2509dc..4693e0cb 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 15a4e385..cddbf742 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 fbc1f67f..994ff262 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; actions: typeof editorActions; } -const EditorContext = createContext(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(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(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 = ({ children, initialEditorState }) => { - const [state, dispatch] = useReducer(editorReducer, initialEditorState, (provided) => provided ?? createInitialState()); - - const value = useMemo( - () => ({ - state, - dispatch, - actions: editorActions, - }), - [state], - ); - - return {children}; + // Created once; the store instance is stable across renders. + const storeRef = useRef(null); + if (!storeRef.current) { + storeRef.current = createEditorStore(initialEditorState ?? createInitialState()); + } + return {children}; }; diff --git a/web/src/components/MemoEditor/state/reducer.ts b/web/src/components/MemoEditor/state/reducer.ts index 200c0465..6aff7ceb 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": + case "SET_RECORDER_BUSY": 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": - 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 883390e1..2a586936 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 } - | { 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 } - | { 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 7f55747d..914e828c 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 c371dc7e..1deb2866 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): 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 96f11408..e2184718 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 00000000..b35d16f8 --- /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 00000000..d1a8b777 --- /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 607f6c0b..4769854b 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 83dd19b3..85d40966 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 {state.ui.editorMode}; + const editorMode = useEditorSelector((s) => s.ui.editorMode); + return {editorMode}; } function renderGuard(content: string) { diff --git a/web/tests/editor-mode-toggle.test.tsx b/web/tests/editor-mode-toggle.test.tsx index 3431fc4b..d29d011a 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 ( <>