From 2c0efeba7c026bf282e2f406856a5e81aa4e846f Mon Sep 17 00:00:00 2001 From: boojack Date: Sat, 13 Jun 2026 01:08:38 +0800 Subject: [PATCH] refactor(web): rename editor dirs and simplify raw mode to a plain textarea --- .../PreservedBlock.ts | 0 .../{TiptapEditor => Editor}/SlashCommand.ts | 0 .../MemoEditor/Editor/SlashCommands.tsx | 45 --- .../MemoEditor/Editor/SuggestionsPopup.tsx | 49 --- .../{TiptapEditor => Editor}/Tag.ts | 0 .../{TiptapEditor => Editor}/TagSuggestion.ts | 0 .../MemoEditor/Editor/TagSuggestions.tsx | 50 --- .../components/MemoEditor/Editor/commands.ts | 28 -- .../MemoEditor/Editor/controllerAdapter.ts | 63 --- .../{TiptapEditor => Editor}/extensions.ts | 0 .../components/MemoEditor/Editor/index.tsx | 380 ++++++++---------- .../{TiptapEditor => Editor}/markdownCodec.ts | 0 .../components/MemoEditor/Editor/shortcuts.ts | 102 ----- .../suggestionMenu.tsx | 0 .../MemoEditor/Editor/useListCompletion.ts | 82 ---- .../MemoEditor/Editor/useSuggestions.ts | 165 -------- .../MemoEditor/PlainEditor/index.tsx | 273 +++++++++++++ web/src/components/MemoEditor/README.md | 22 +- .../MemoEditor/TiptapEditor/index.tsx | 198 --------- .../MemoEditor/Toolbar/InsertMenu.tsx | 27 +- .../MemoEditor/components/EditorContent.tsx | 41 +- .../MemoEditor/hooks/useMemoInit.ts | 2 +- .../components/MemoEditor/state/actions.ts | 5 - .../components/MemoEditor/state/reducer.ts | 12 - web/src/components/MemoEditor/state/types.ts | 3 - .../components/MemoEditor/types/components.ts | 26 -- .../MemoEditor/types/editorController.ts | 4 +- web/src/components/MemoEditor/types/index.ts | 3 - web/src/locales/en.json | 3 +- ...er.test.tsx => editor-controller.test.tsx} | 16 +- web/tests/editor-load-guard.test.tsx | 4 +- web/tests/editor-mode-toggle.test.tsx | 12 +- web/tests/editor-mode.test.ts | 7 - ...erved.test.ts => editor-preserved.test.ts} | 2 +- ....test.ts => editor-slash-commands.test.ts} | 4 +- ...{tiptap-tag.test.ts => editor-tag.test.ts} | 4 +- web/tests/insert-menu-mode-toggle.test.tsx | 25 +- web/tests/markdown-roundtrip.test.ts | 2 +- web/tests/memo-editor-paste.test.tsx | 58 +-- web/tests/memo-editor-shortcuts.test.tsx | 116 ------ ...t.tsx => plain-editor-controller.test.tsx} | 22 +- web/tests/suggestion-menu.test.tsx | 4 +- 42 files changed, 525 insertions(+), 1334 deletions(-) rename web/src/components/MemoEditor/{TiptapEditor => Editor}/PreservedBlock.ts (100%) rename web/src/components/MemoEditor/{TiptapEditor => Editor}/SlashCommand.ts (100%) delete mode 100644 web/src/components/MemoEditor/Editor/SlashCommands.tsx delete mode 100644 web/src/components/MemoEditor/Editor/SuggestionsPopup.tsx rename web/src/components/MemoEditor/{TiptapEditor => Editor}/Tag.ts (100%) rename web/src/components/MemoEditor/{TiptapEditor => Editor}/TagSuggestion.ts (100%) delete mode 100644 web/src/components/MemoEditor/Editor/TagSuggestions.tsx delete mode 100644 web/src/components/MemoEditor/Editor/commands.ts delete mode 100644 web/src/components/MemoEditor/Editor/controllerAdapter.ts rename web/src/components/MemoEditor/{TiptapEditor => Editor}/extensions.ts (100%) rename web/src/components/MemoEditor/{TiptapEditor => Editor}/markdownCodec.ts (100%) delete mode 100644 web/src/components/MemoEditor/Editor/shortcuts.ts rename web/src/components/MemoEditor/{TiptapEditor => Editor}/suggestionMenu.tsx (100%) delete mode 100644 web/src/components/MemoEditor/Editor/useListCompletion.ts delete mode 100644 web/src/components/MemoEditor/Editor/useSuggestions.ts create mode 100644 web/src/components/MemoEditor/PlainEditor/index.tsx delete mode 100644 web/src/components/MemoEditor/TiptapEditor/index.tsx rename web/tests/{tiptap-editor-controller.test.tsx => editor-controller.test.tsx} (91%) rename web/tests/{tiptap-preserved.test.ts => editor-preserved.test.ts} (98%) rename web/tests/{tiptap-slash-commands.test.ts => editor-slash-commands.test.ts} (96%) rename web/tests/{tiptap-tag.test.ts => editor-tag.test.ts} (99%) delete mode 100644 web/tests/memo-editor-shortcuts.test.tsx rename web/tests/{editor-controller-adapter.test.tsx => plain-editor-controller.test.tsx} (79%) diff --git a/web/src/components/MemoEditor/TiptapEditor/PreservedBlock.ts b/web/src/components/MemoEditor/Editor/PreservedBlock.ts similarity index 100% rename from web/src/components/MemoEditor/TiptapEditor/PreservedBlock.ts rename to web/src/components/MemoEditor/Editor/PreservedBlock.ts diff --git a/web/src/components/MemoEditor/TiptapEditor/SlashCommand.ts b/web/src/components/MemoEditor/Editor/SlashCommand.ts similarity index 100% rename from web/src/components/MemoEditor/TiptapEditor/SlashCommand.ts rename to web/src/components/MemoEditor/Editor/SlashCommand.ts diff --git a/web/src/components/MemoEditor/Editor/SlashCommands.tsx b/web/src/components/MemoEditor/Editor/SlashCommands.tsx deleted file mode 100644 index d1ab6c12..00000000 --- a/web/src/components/MemoEditor/Editor/SlashCommands.tsx +++ /dev/null @@ -1,45 +0,0 @@ -import type { SlashCommandsProps } from "../types"; -import type { EditorRefActions } from "."; -import { SuggestionsPopup } from "./SuggestionsPopup"; -import { useSuggestions } from "./useSuggestions"; - -const SlashCommands = ({ editorRef, editorActions, commands }: SlashCommandsProps) => { - const handleCommandAutocomplete = (cmd: (typeof commands)[0], word: string, index: number, actions: EditorRefActions) => { - // Remove trigger char + word, then insert command output - actions.removeText(index, word.length); - actions.insertText(cmd.run()); - // Position cursor relative to insertion point, if specified - if (cmd.cursorOffset) { - actions.setCursorPosition(index + cmd.cursorOffset); - } - }; - - const { position, suggestions, selectedIndex, isVisible, handleItemSelect } = useSuggestions({ - editorRef, - editorActions, - triggerChar: "/", - items: commands, - filterItems: (items, query) => (!query ? items : items.filter((cmd) => cmd.name.toLowerCase().startsWith(query))), - onAutocomplete: handleCommandAutocomplete, - }); - - if (!isVisible || !position) return null; - - return ( - cmd.name} - renderItem={(cmd) => ( - - / - {cmd.name} - - )} - /> - ); -}; - -export default SlashCommands; diff --git a/web/src/components/MemoEditor/Editor/SuggestionsPopup.tsx b/web/src/components/MemoEditor/Editor/SuggestionsPopup.tsx deleted file mode 100644 index 1e7129b9..00000000 --- a/web/src/components/MemoEditor/Editor/SuggestionsPopup.tsx +++ /dev/null @@ -1,49 +0,0 @@ -import { ReactNode, useEffect, useRef } from "react"; -import { cn } from "@/lib/utils"; -import { Position } from "./useSuggestions"; - -interface SuggestionsPopupProps { - position: Position; - suggestions: T[]; - selectedIndex: number; - onItemSelect: (item: T) => void; - renderItem: (item: T, isSelected: boolean) => ReactNode; - getItemKey: (item: T, index: number) => string; -} - -const POPUP_STYLES = { - container: - "z-20 absolute p-1 mt-1 -ml-2 max-w-48 max-h-60 rounded border bg-popover text-popover-foreground shadow-lg font-mono flex flex-col overflow-y-auto overflow-x-hidden", - item: "rounded p-1 px-2 w-full text-sm cursor-pointer transition-colors select-none hover:bg-accent hover:text-accent-foreground", -}; - -export function SuggestionsPopup({ - position, - suggestions, - selectedIndex, - onItemSelect, - renderItem, - getItemKey, -}: SuggestionsPopupProps) { - const containerRef = useRef(null); - const selectedItemRef = useRef(null); - - useEffect(() => { - selectedItemRef.current?.scrollIntoView({ block: "nearest", behavior: "smooth" }); - }, [selectedIndex]); - - return ( -
- {suggestions.map((item, i) => ( -
onItemSelect(item)} - className={cn(POPUP_STYLES.item, i === selectedIndex && "bg-accent text-accent-foreground")} - > - {renderItem(item, i === selectedIndex)} -
- ))} -
- ); -} diff --git a/web/src/components/MemoEditor/TiptapEditor/Tag.ts b/web/src/components/MemoEditor/Editor/Tag.ts similarity index 100% rename from web/src/components/MemoEditor/TiptapEditor/Tag.ts rename to web/src/components/MemoEditor/Editor/Tag.ts diff --git a/web/src/components/MemoEditor/TiptapEditor/TagSuggestion.ts b/web/src/components/MemoEditor/Editor/TagSuggestion.ts similarity index 100% rename from web/src/components/MemoEditor/TiptapEditor/TagSuggestion.ts rename to web/src/components/MemoEditor/Editor/TagSuggestion.ts diff --git a/web/src/components/MemoEditor/Editor/TagSuggestions.tsx b/web/src/components/MemoEditor/Editor/TagSuggestions.tsx deleted file mode 100644 index 6ef6cd8a..00000000 --- a/web/src/components/MemoEditor/Editor/TagSuggestions.tsx +++ /dev/null @@ -1,50 +0,0 @@ -import { useMemo } from "react"; -import { matchPath } from "react-router-dom"; -import OverflowTip from "@/components/kit/OverflowTip"; -import { useTagCounts } from "@/hooks/useUserQueries"; -import { Routes } from "@/router"; -import type { TagSuggestionsProps } from "../types"; -import { SuggestionsPopup } from "./SuggestionsPopup"; -import { useSuggestions } from "./useSuggestions"; - -export default function TagSuggestions({ editorRef, editorActions }: TagSuggestionsProps) { - // On explore page, show all users' tags; otherwise show current user's tags - const isExplorePage = Boolean(matchPath(Routes.EXPLORE, window.location.pathname)); - const { data: tagCount = {} } = useTagCounts(!isExplorePage); - - const sortedTags = useMemo(() => { - return Object.entries(tagCount) - .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])) - .map(([tag]) => tag); - }, [tagCount]); - - const { position, suggestions, selectedIndex, isVisible, handleItemSelect } = useSuggestions({ - editorRef, - editorActions, - triggerChar: "#", - items: sortedTags, - filterItems: (items, query) => (!query ? items : items.filter((tag) => tag.toLowerCase().includes(query))), - onAutocomplete: (tag, word, index, actions) => { - actions.removeText(index, word.length); - actions.insertText(`#${tag} `); - }, - }); - - if (!isVisible || !position) return null; - - return ( - tag} - renderItem={(tag) => ( - - # - {tag} - - )} - /> - ); -} diff --git a/web/src/components/MemoEditor/Editor/commands.ts b/web/src/components/MemoEditor/Editor/commands.ts deleted file mode 100644 index 4aa58b44..00000000 --- a/web/src/components/MemoEditor/Editor/commands.ts +++ /dev/null @@ -1,28 +0,0 @@ -export interface Command { - name: string; - run: () => string; - cursorOffset?: number; -} - -export const editorCommands: Command[] = [ - { - name: "todo", - run: () => "- [ ] ", - cursorOffset: 6, - }, - { - name: "code", - run: () => "```\n\n```", - cursorOffset: 4, - }, - { - name: "link", - run: () => "[text](url)", - cursorOffset: 1, - }, - { - name: "table", - run: () => "| Header | Header |\n| ------ | ------ |\n| Cell | Cell |", - cursorOffset: 1, - }, -]; diff --git a/web/src/components/MemoEditor/Editor/controllerAdapter.ts b/web/src/components/MemoEditor/Editor/controllerAdapter.ts deleted file mode 100644 index f9dfa0b5..00000000 --- a/web/src/components/MemoEditor/Editor/controllerAdapter.ts +++ /dev/null @@ -1,63 +0,0 @@ -import type { EditorController } from "../types/editorController"; -import type { EditorRefActions } from "./index"; -import { toggleTextStyle } from "./shortcuts"; - -const TASK_PREFIX = "- [ ] "; - -/** - * Adapts the textarea editor's imperative string-surgery API to the shared - * EditorController contract. Takes a getter because the underlying ref is - * populated after mount and may swap when the editor remounts. - */ -export function createTextareaController(getActions: () => EditorRefActions | null): EditorController { - return { - focus: () => getActions()?.focus(), - hasFocus: () => { - const element = getActions()?.getEditor(); - return Boolean(element) && document.activeElement === element; - }, - isEmpty: () => (getActions()?.getContent() ?? "").trim() === "", - getMarkdown: () => getActions()?.getContent() ?? "", - setMarkdown: (markdown) => getActions()?.setContent(markdown), - insertMarkdown: (markdown) => { - const actions = getActions(); - if (!actions) return; - if (!markdown) return; - const content = actions.getContent(); - const cursor = actions.getCursorPosition(); - const before = content.slice(0, cursor); - const after = content.slice(cursor); - const prefix = before.length === 0 || before.endsWith("\n\n") ? "" : before.endsWith("\n") ? "\n" : "\n\n"; - const suffix = after.length === 0 || after.startsWith("\n\n") ? "" : after.startsWith("\n") ? "\n" : "\n\n"; - actions.insertText(markdown, prefix, suffix); - }, - scrollToCursor: () => getActions()?.scrollToCursor(), - selectAll: () => { - const actions = getActions(); - if (!actions) return; - actions.setCursorPosition(0, actions.getContent().length); - }, - toggleBold: () => { - const actions = getActions(); - if (actions) toggleTextStyle(actions, "**"); - }, - toggleItalic: () => { - const actions = getActions(); - if (actions) toggleTextStyle(actions, "*"); - }, - toggleTaskList: () => { - const actions = getActions(); - if (!actions) return; - const lineNumber = actions.getCursorLineNumber(); - const line = actions.getLine(lineNumber); - const taskMatch = line.match(/^(\s*)- \[[ xX]\] /); - if (taskMatch) { - actions.setLine(lineNumber, taskMatch[1] + line.slice(taskMatch[0].length)); - } else { - const indentMatch = line.match(/^(\s*)/); - const indent = indentMatch?.[1] ?? ""; - actions.setLine(lineNumber, `${indent}${TASK_PREFIX}${line.slice(indent.length)}`); - } - }, - }; -} diff --git a/web/src/components/MemoEditor/TiptapEditor/extensions.ts b/web/src/components/MemoEditor/Editor/extensions.ts similarity index 100% rename from web/src/components/MemoEditor/TiptapEditor/extensions.ts rename to web/src/components/MemoEditor/Editor/extensions.ts diff --git a/web/src/components/MemoEditor/Editor/index.tsx b/web/src/components/MemoEditor/Editor/index.tsx index 1d2ff135..bdaa4865 100644 --- a/web/src/components/MemoEditor/Editor/index.tsx +++ b/web/src/components/MemoEditor/Editor/index.tsx @@ -1,244 +1,196 @@ -import { type ClipboardEvent, forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef } from "react"; -import getCaretCoordinates from "textarea-caret"; +import { Extension } from "@tiptap/core"; +import { Placeholder } from "@tiptap/extensions"; +import type { EditorProps as ProseMirrorEditorProps } from "@tiptap/pm/view"; +import { EditorContent as RichTextContent, useEditor } from "@tiptap/react"; +import { forwardRef, useEffect, useImperativeHandle, useMemo, useRef } from "react"; +import { matchPath } from "react-router-dom"; +import { useTagCounts } from "@/hooks/useUserQueries"; import { cn } from "@/lib/utils"; +import { ROUTES as Routes } from "@/router/routes"; import { EDITOR_HEIGHT } from "../constants"; -import type { EditorProps } from "../types"; -import { editorCommands } from "./commands"; -import SlashCommands from "./SlashCommands"; -import { getMarkdownLinkForPastedUrl, handleMarkdownShortcuts } from "./shortcuts"; -import TagSuggestions from "./TagSuggestions"; -import { useListCompletion } from "./useListCompletion"; +import type { EditorController } from "../types/editorController"; +import { buildExtensions } from "./extensions"; +import { SlashCommand } from "./SlashCommand"; +import { TagSuggestion } from "./TagSuggestion"; -export interface EditorRefActions { - getEditor: () => HTMLTextAreaElement | null; - focus: () => void; - scrollToCursor: () => void; - insertText: (text: string, prefix?: string, suffix?: string) => void; - removeText: (start: number, length: number) => 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; +// Mod-Enter is the app-wide "save memo" shortcut (useKeyboard). StarterKit's +// HardBreak extension also binds Mod-Enter to insert a hard break, which would +// mutate the document right before save fires. This extension swallows the +// shortcut (returning true stops further keymap handlers) while preserving +// DOM event bubbling — preventDefault does NOT stopPropagation, so the window- +// level save listener in useKeyboard still receives and handles the keystroke. +// Priority 1000 > HardBreak's default 100, so this handler runs first. +// Shift-Enter still inserts a hard break as expected. +const SaveShortcutPassthrough = Extension.create({ + name: "saveShortcutPassthrough", + priority: 1000, + addKeyboardShortcuts() { + return { + "Mod-Enter": () => true, + }; + }, +}); + +export interface EditorProps { + className?: string; + initialContent: string; + placeholder: string; + isFocusMode?: boolean; + onContentChange: (content: string) => void; + onPaste: (event: React.ClipboardEvent) => void; } -const Editor = forwardRef(function Editor(props: EditorProps, ref: React.ForwardedRef) { - const { - className, - initialContent, - placeholder, - onPaste, - onContentChange: handleContentChangeCallback, - isFocusMode, - isInIME = false, - onCompositionStart, - onCompositionEnd, - } = props; - const editorRef = useRef(null); +/** + * The Document serializer joins/terminates blocks with `\n\n`, so e.g. a task + * list serializes with a trailing blank line. Outer whitespace is meaningless + * at the document level (the round-trip corpus compares modulo outer trim), + * so every markdown string leaving this component is trimmed. + */ +function serializeMarkdown(editor: { getMarkdown: () => string } | null): string { + return (editor?.getMarkdown() ?? "").trim(); +} - const updateEditorHeight = useCallback(() => { - if (editorRef.current) { - editorRef.current.style.height = "auto"; - editorRef.current.style.height = `${editorRef.current.scrollHeight ?? 0}px`; - } - }, []); +/** + * WYSIWYG memo editor built on ProseMirror. Markdown is the only format + * crossing its boundary: in via setContent(contentType: "markdown"), out via + * serializeMarkdown() on every update. IME, list continuation, input rules, + * and auto-grow are native ProseMirror/contenteditable behavior. + */ +const Editor = forwardRef(function Editor(props, ref) { + const { className, initialContent, placeholder, isFocusMode, onContentChange, onPaste } = props; - const updateContent = useCallback(() => { - if (editorRef.current) { - handleContentChangeCallback(editorRef.current.value); - updateEditorHeight(); - } - }, [handleContentChangeCallback, updateEditorHeight]); + // Last markdown emitted through onContentChange, so the sync effect can + // recognize the parent echoing our own value back without re-serializing. + const lastEmittedRef = useRef(null); + // Read through refs so the memoized extension/editorProps closures below + // always see the latest props (Placeholder decorations recompute per + // transaction; handlePaste resolves per event). + const placeholderRef = useRef(placeholder); + placeholderRef.current = placeholder; + const onPasteRef = useRef(onPaste); + onPasteRef.current = onPaste; - const scrollToCaret = useCallback((options: { force?: boolean } = {}) => { - const editor = editorRef.current; - if (!editor) return; + // On the explore page suggestions include all users' tags; otherwise the + // current user's. Same sourcing as the raw editor's TagSuggestions. + const isExplorePage = useMemo(() => Boolean(matchPath(Routes.EXPLORE, window.location.pathname)), []); + const { data: tagCount = {} } = useTagCounts(!isExplorePage); + const sortedTags = useMemo( + () => + Object.entries(tagCount) + .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])) + .map(([tag]) => tag), + [tagCount], + ); + const tagsRef = useRef([]); + tagsRef.current = sortedTags; - const { force = false } = options; - const caret = getCaretCoordinates(editor, editor.selectionEnd); - - if (force) { - editor.scrollTop = Math.max(0, caret.top - editor.clientHeight / 2); - return; - } - - const lineHeight = parseFloat(getComputedStyle(editor).lineHeight) || 24; - const viewportBottom = editor.scrollTop + editor.clientHeight; - // Scroll if cursor is near or beyond bottom edge (within 2 lines) - if (caret.top + lineHeight * 2 > viewportBottom) { - editor.scrollTop = Math.max(0, caret.top - editor.clientHeight / 2); - } - }, []); - - useEffect(() => { - if (editorRef.current && initialContent) { - editorRef.current.value = initialContent; - handleContentChangeCallback(initialContent); - updateEditorHeight(); - } - // Only run once on mount to set initial content - // eslint-disable-next-line react-hooks/exhaustive-deps - }, []); - - // Update editor when content is externally changed (e.g., reset after save) - useEffect(() => { - if (editorRef.current && editorRef.current.value !== initialContent) { - editorRef.current.value = initialContent; - updateEditorHeight(); - } - }, [initialContent, updateEditorHeight]); - - const editorActions: EditorRefActions = useMemo( + // Stable option identities so useEditor's compareOptions stays equal across + // renders and the editor skips a needless setOptions/view.setProps pass per + // keystroke. All dynamic values reach the closures through refs above. + // `content` is only consumed at editor creation — later external changes + // flow through the sync effect — so the mount-time value is frozen too. + const mountContentRef = useRef(initialContent); + const extensions = useMemo( + () => [ + ...buildExtensions(), + Placeholder.configure({ placeholder: () => placeholderRef.current }), + TagSuggestion.configure({ getTags: () => tagsRef.current }), + SlashCommand, + SaveShortcutPassthrough, + ], + [], + ); + const editorProps = useMemo( () => ({ - getEditor: () => editorRef.current, - focus: () => editorRef.current?.focus(), - scrollToCursor: () => { - scrollToCaret({ force: true }); + attributes: { + class: "memo-wysiwyg outline-none w-full text-base break-words min-h-6", }, - insertText: (content = "", prefix = "", suffix = "") => { - const editor = editorRef.current; - if (!editor) return; - - const cursorPos = editor.selectionStart; - const endPos = editor.selectionEnd; - const prev = editor.value; - const actual = content || prev.slice(cursorPos, endPos); - editor.value = prev.slice(0, cursorPos) + prefix + actual + suffix + prev.slice(endPos); - - editor.focus(); - editor.setSelectionRange(cursorPos + prefix.length + actual.length, cursorPos + prefix.length + actual.length); - updateContent(); - }, - removeText: (start: number, length: number) => { - const editor = editorRef.current; - if (!editor) return; - - editor.value = editor.value.slice(0, start) + editor.value.slice(start + length); - editor.focus(); - editor.setSelectionRange(start, start); - updateContent(); - }, - setContent: (text: string) => { - const editor = editorRef.current; - if (editor) { - editor.value = text; - updateContent(); + handlePaste: (_view, event) => { + const hasFiles = Array.from(event.clipboardData?.items ?? []).some((item) => item.kind === "file"); + if (hasFiles) { + onPasteRef.current(event as unknown as React.ClipboardEvent); + return true; } - }, - getContent: () => editorRef.current?.value ?? "", - getCursorPosition: () => editorRef.current?.selectionStart ?? 0, - getSelectedContent: () => { - const editor = editorRef.current; - if (!editor) return ""; - return editor.value.slice(editor.selectionStart, editor.selectionEnd); - }, - setCursorPosition: (startPos: number, endPos?: number) => { - const editor = editorRef.current; - if (!editor) return; - // setSelectionRange requires valid arguments; default to startPos if endPos is undefined - const endPosition = endPos !== undefined && !Number.isNaN(endPos) ? endPos : startPos; - editor.setSelectionRange(startPos, endPosition); - }, - 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(); + // Text paste (incl. URL-over-selection → link) is handled natively. + return false; }, }), - [updateContent, scrollToCaret], + [], ); - useImperativeHandle(ref, () => editorActions, [editorActions]); - - const handleEditorInput = useCallback(() => { - if (editorRef.current) { - handleContentChangeCallback(editorRef.current.value); - updateEditorHeight(); - - // Auto-scroll to keep cursor visible when typing - // See: https://github.com/usememos/memos/issues/5469 - scrollToCaret(); - } - }, [handleContentChangeCallback, updateEditorHeight, scrollToCaret]); - - // Auto-complete markdown lists when pressing Enter - useListCompletion({ - editorRef, - editorActions, - isInIME, + const editor = useEditor({ + extensions, + content: mountContentRef.current, + contentType: "markdown", + editorProps, + onUpdate: ({ editor: currentEditor }) => { + const markdown = serializeMarkdown(currentEditor); + lastEmittedRef.current = markdown; + onContentChange(markdown); + }, }); - const handleKeyDown = useCallback( - (event: React.KeyboardEvent) => { - if ((event.ctrlKey || event.metaKey) && !isInIME) { - handleMarkdownShortcuts(event, editorActions); - } - }, - [editorActions, isInIME], - ); - - const handleEditorPaste = useCallback( - (event: ClipboardEvent) => { - const editor = editorRef.current; - const pastedText = event.clipboardData?.getData("text/plain") || event.clipboardData?.getData("text"); - const markdownLink = editor ? getMarkdownLinkForPastedUrl(editorActions.getSelectedContent(), pastedText) : undefined; - - if (markdownLink) { - event.preventDefault(); - editorActions.insertText(markdownLink); - return; - } - - onPaste(event); - }, - [editorActions, onPaste], - ); - - // Recalculate editor height when focus mode changes + // Sync external content changes (e.g. reset after save, draft restore) + // without clobbering the document the user is typing into: only apply when + // the markdown actually differs. useEffect(() => { - updateEditorHeight(); - }, [isFocusMode, updateEditorHeight]); + if (!editor) { + return; + } + // Parent echo of our own emission — nothing to sync (O(1) fast path). + // Comparing against the live document instead would race: a keystroke + // landing between the emission and this passive effect would make the + // echo look like an external change and clobber the keystroke/cursor. + if (initialContent === lastEmittedRef.current) { + return; + } + // Never clobber an in-progress IME composition. + if (editor.view.composing) { + return; + } + if (serializeMarkdown(editor) !== initialContent.trim()) { + editor.commands.setContent(initialContent, { contentType: "markdown", emitUpdate: false }); + // A subsequent identical echo of this value is also a no-op. + lastEmittedRef.current = initialContent; + } + }, [initialContent, editor]); + + useImperativeHandle( + ref, + (): EditorController => ({ + focus: () => editor?.commands.focus(), + hasFocus: () => editor?.isFocused ?? false, + // Contract: whitespace-only counts as empty. The editor's structural + // `editor.isEmpty` would call a paragraph of spaces non-empty. + isEmpty: () => serializeMarkdown(editor) === "", + getMarkdown: () => serializeMarkdown(editor), + setMarkdown: (markdown) => editor?.commands.setContent(markdown, { contentType: "markdown" }), + insertMarkdown: (markdown) => editor?.chain().focus().insertContent(markdown, { contentType: "markdown" }).run(), + scrollToCursor: () => editor?.commands.scrollIntoView(), + selectAll: () => editor?.commands.selectAll(), + toggleBold: () => editor?.chain().focus().toggleBold().run(), + toggleItalic: () => editor?.chain().focus().toggleItalic().run(), + toggleTaskList: () => editor?.chain().focus().toggleTaskList().run(), + }), + [editor], + ); return (
{ + // In focus mode the wrapper extends below the content; a click on the + // empty area should land the caret at the end instead of doing nothing. + if (event.target === event.currentTarget) { + editor?.commands.focus("end"); + } + }} > - - - +
); }); diff --git a/web/src/components/MemoEditor/TiptapEditor/markdownCodec.ts b/web/src/components/MemoEditor/Editor/markdownCodec.ts similarity index 100% rename from web/src/components/MemoEditor/TiptapEditor/markdownCodec.ts rename to web/src/components/MemoEditor/Editor/markdownCodec.ts diff --git a/web/src/components/MemoEditor/Editor/shortcuts.ts b/web/src/components/MemoEditor/Editor/shortcuts.ts deleted file mode 100644 index 7c77f746..00000000 --- a/web/src/components/MemoEditor/Editor/shortcuts.ts +++ /dev/null @@ -1,102 +0,0 @@ -import type { EditorRefActions } from "./index"; - -const SHORTCUTS = { - BOLD: { key: "b", delimiter: "**" }, - ITALIC: { key: "i", delimiter: "*" }, -} as const; - -const URL_PLACEHOLDER = "url"; -const URL_REGEX = /^https?:\/\/[^\s]+$/; -const LINK_OFFSET = 3; // Length of "]()" - -export function handleMarkdownShortcuts(event: React.KeyboardEvent, editor: EditorRefActions): void { - const key = event.key.toLowerCase(); - if (key === SHORTCUTS.BOLD.key) { - event.preventDefault(); - toggleTextStyle(editor, SHORTCUTS.BOLD.delimiter); - } else if (key === SHORTCUTS.ITALIC.key) { - event.preventDefault(); - toggleTextStyle(editor, SHORTCUTS.ITALIC.delimiter); - } -} - -export function insertHyperlink(editor: EditorRefActions, url?: string): void { - const cursorPosition = editor.getCursorPosition(); - const selectedContent = editor.getSelectedContent(); - const isUrlSelected = !url && URL_REGEX.test(selectedContent.trim()); - - if (isUrlSelected) { - editor.insertText(`[](${selectedContent})`); - editor.setCursorPosition(cursorPosition + 1, cursorPosition + 1); - return; - } - - const href = url ?? URL_PLACEHOLDER; - editor.insertText(`[${selectedContent}](${href})`); - - if (href === URL_PLACEHOLDER) { - const urlStart = cursorPosition + selectedContent.length + LINK_OFFSET; - editor.setCursorPosition(urlStart, urlStart + href.length); - } -} - -export function toggleTextStyle(editor: EditorRefActions, 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 function hyperlinkHighlightedText(editor: EditorRefActions, url: string): void { - const selectedContent = editor.getSelectedContent(); - const cursorPosition = editor.getCursorPosition(); - - editor.insertText(`[${selectedContent}](${url})`); - - const newPosition = cursorPosition + selectedContent.length + url.length + 4; - editor.setCursorPosition(newPosition, newPosition); -} - -export function getMarkdownLinkForPastedUrl(selectedContent: string, pastedText: string): string | undefined { - const url = pastedText.trim(); - - if (!selectedContent || !URL_REGEX.test(url) || URL_REGEX.test(selectedContent.trim())) { - return undefined; - } - - return `[${selectedContent}](${url})`; -} diff --git a/web/src/components/MemoEditor/TiptapEditor/suggestionMenu.tsx b/web/src/components/MemoEditor/Editor/suggestionMenu.tsx similarity index 100% rename from web/src/components/MemoEditor/TiptapEditor/suggestionMenu.tsx rename to web/src/components/MemoEditor/Editor/suggestionMenu.tsx diff --git a/web/src/components/MemoEditor/Editor/useListCompletion.ts b/web/src/components/MemoEditor/Editor/useListCompletion.ts deleted file mode 100644 index e6ff8b4d..00000000 --- a/web/src/components/MemoEditor/Editor/useListCompletion.ts +++ /dev/null @@ -1,82 +0,0 @@ -import { type RefObject, useEffect, useRef } from "react"; -import { detectLastListItem, generateListContinuation } from "@/utils/markdown-list-detection"; -import { EditorRefActions } from "."; - -interface UseListCompletionOptions { - editorRef: RefObject; - editorActions: EditorRefActions; - isInIME: boolean; -} - -// Patterns to detect empty list items -const EMPTY_LIST_PATTERNS = [ - /^(\s*)([-*+])\s*$/, // Empty unordered list - /^(\s*)([-*+])\s+\[([ xX])\]\s*$/, // Empty task list - /^(\s*)(\d+)[.)]\s*$/, // Empty ordered list -]; - -const isEmptyListItem = (line: string) => EMPTY_LIST_PATTERNS.some((pattern) => pattern.test(line)); - -export function useListCompletion({ editorRef, editorActions, isInIME }: UseListCompletionOptions) { - const isInIMERef = useRef(isInIME); - isInIMERef.current = isInIME; - - const editorActionsRef = useRef(editorActions); - editorActionsRef.current = editorActions; - - // Track when composition ends to handle Safari race condition - // Safari fires keydown(Enter) immediately after compositionend, while Chrome doesn't - // See: https://github.com/usememos/memos/issues/5469 - const lastCompositionEndRef = useRef(0); - - useEffect(() => { - const editor = editorRef.current; - if (!editor) return; - - const handleCompositionEnd = () => { - lastCompositionEndRef.current = Date.now(); - }; - - const handleKeyDown = (event: KeyboardEvent) => { - if (event.key !== "Enter" || isInIMERef.current || event.shiftKey || event.ctrlKey || event.metaKey || event.altKey) { - return; - } - - // Safari fix: Ignore Enter key within 100ms of composition end - // This prevents double-enter behavior when confirming IME input in lists - if (Date.now() - lastCompositionEndRef.current < 100) { - return; - } - - const actions = editorActionsRef.current; - const cursorPosition = actions.getCursorPosition(); - const contentBeforeCursor = actions.getContent().substring(0, cursorPosition); - const listInfo = detectLastListItem(contentBeforeCursor); - - if (!listInfo.type) return; - - event.preventDefault(); - - const lines = contentBeforeCursor.split("\n"); - const currentLine = lines[lines.length - 1]; - - if (isEmptyListItem(currentLine)) { - const lineStartPos = cursorPosition - currentLine.length; - actions.removeText(lineStartPos, currentLine.length); - } else { - const continuation = generateListContinuation(listInfo); - actions.insertText("\n" + continuation); - - // Auto-scroll to keep cursor visible after inserting list item - setTimeout(() => actions.scrollToCursor(), 0); - } - }; - - editor.addEventListener("compositionend", handleCompositionEnd); - editor.addEventListener("keydown", handleKeyDown); - return () => { - editor.removeEventListener("compositionend", handleCompositionEnd); - editor.removeEventListener("keydown", handleKeyDown); - }; - }, []); -} diff --git a/web/src/components/MemoEditor/Editor/useSuggestions.ts b/web/src/components/MemoEditor/Editor/useSuggestions.ts deleted file mode 100644 index acccff10..00000000 --- a/web/src/components/MemoEditor/Editor/useSuggestions.ts +++ /dev/null @@ -1,165 +0,0 @@ -import { type ForwardedRef, type RefObject, useEffect, useRef, useState } from "react"; -import getCaretCoordinates from "textarea-caret"; -import { EditorRefActions } from "."; - -export interface Position { - left: number; - top: number; - height: number; -} - -export interface UseSuggestionsOptions { - editorRef: RefObject; - editorActions: ForwardedRef; - triggerChar: string; - items: T[]; - filterItems: (items: T[], searchQuery: string) => T[]; - onAutocomplete: (item: T, word: string, startIndex: number, actions: EditorRefActions) => void; -} - -export interface UseSuggestionsReturn { - position: Position | null; - suggestions: T[]; - selectedIndex: number; - isVisible: boolean; - searchQuery: string; - handleItemSelect: (item: T) => void; -} - -export function useSuggestions({ - editorRef, - editorActions, - triggerChar, - items, - filterItems, - onAutocomplete, -}: UseSuggestionsOptions): UseSuggestionsReturn { - const [position, setPosition] = useState(null); - const [selectedIndex, setSelectedIndex] = useState(0); - const isProcessingRef = useRef(false); - - const selectedRef = useRef(selectedIndex); - selectedRef.current = selectedIndex; - - const getCurrentWord = (): [word: string, startIndex: number] => { - const editor = editorRef.current; - if (!editor) return ["", 0]; - const cursorPos = editor.selectionEnd; - const before = editor.value.slice(0, cursorPos).match(/\S*$/) || { 0: "", index: cursorPos }; - const after = editor.value.slice(cursorPos).match(/^\S*/) || { 0: "" }; - return [before[0] + after[0], before.index ?? cursorPos]; - }; - - const hide = () => setPosition(null); - - const suggestionsRef = useRef([]); - const searchQueryRef = useRef(""); - suggestionsRef.current = (() => { - const [word] = getCurrentWord(); - if (!word.startsWith(triggerChar)) return []; - searchQueryRef.current = word.slice(triggerChar.length).toLowerCase(); - return filterItems(items, searchQueryRef.current); - })(); - if (suggestionsRef.current.length === 0) { - const [word] = getCurrentWord(); - searchQueryRef.current = word.startsWith(triggerChar) ? word.slice(triggerChar.length).toLowerCase() : ""; - } - - const isVisibleRef = useRef(false); - isVisibleRef.current = !!(position && suggestionsRef.current.length > 0); - - const handleAutocomplete = (item: T) => { - if (!editorActions || !("current" in editorActions) || !editorActions.current) { - console.warn("useSuggestions: editorActions not available"); - return; - } - isProcessingRef.current = true; - const [word, index] = getCurrentWord(); - onAutocomplete(item, word, index, editorActions.current); - hide(); - // Re-enable input handling after all DOM operations complete - queueMicrotask(() => { - isProcessingRef.current = false; - }); - }; - - const handleNavigation = (e: KeyboardEvent, selected: number, suggestionsCount: number) => { - if (e.code === "ArrowDown") { - setSelectedIndex((selected + 1) % suggestionsCount); - e.preventDefault(); - e.stopPropagation(); - } else if (e.code === "ArrowUp") { - setSelectedIndex((selected - 1 + suggestionsCount) % suggestionsCount); - e.preventDefault(); - e.stopPropagation(); - } - }; - - const handleKeyDown = (e: KeyboardEvent) => { - if (!isVisibleRef.current) return; - - const suggestions = suggestionsRef.current; - const selected = selectedRef.current; - - if (["Escape", "ArrowLeft", "ArrowRight"].includes(e.code)) { - hide(); - return; - } - - if (["ArrowDown", "ArrowUp"].includes(e.code)) { - handleNavigation(e, selected, suggestions.length); - return; - } - - if (["Enter", "Tab"].includes(e.code)) { - handleAutocomplete(suggestions[selected]); - e.preventDefault(); - e.stopImmediatePropagation(); - } - }; - - const handleInput = () => { - if (isProcessingRef.current) return; - - const editor = editorRef.current; - if (!editor) return; - - setSelectedIndex(0); - const [word, index] = getCurrentWord(); - const currentChar = editor.value[editor.selectionEnd]; - const isActive = word.startsWith(triggerChar) && currentChar !== triggerChar; - - if (isActive) { - const coords = getCaretCoordinates(editor, index); - coords.top -= editor.scrollTop; - setPosition(coords); - } else { - hide(); - } - }; - - useEffect(() => { - const editor = editorRef.current; - if (!editor) return; - - const handlers = { click: hide, blur: hide, keydown: handleKeyDown, input: handleInput }; - Object.entries(handlers).forEach(([event, handler]) => { - editor.addEventListener(event, handler as EventListener); - }); - - return () => { - Object.entries(handlers).forEach(([event, handler]) => { - editor.removeEventListener(event, handler as EventListener); - }); - }; - }, []); - - return { - position, - suggestions: suggestionsRef.current, - selectedIndex, - isVisible: isVisibleRef.current, - searchQuery: searchQueryRef.current, - handleItemSelect: handleAutocomplete, - }; -} diff --git a/web/src/components/MemoEditor/PlainEditor/index.tsx b/web/src/components/MemoEditor/PlainEditor/index.tsx new file mode 100644 index 00000000..9ddb04ef --- /dev/null +++ b/web/src/components/MemoEditor/PlainEditor/index.tsx @@ -0,0 +1,273 @@ +import { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef } from "react"; +import getCaretCoordinates from "textarea-caret"; +import { cn } from "@/lib/utils"; +import { EDITOR_HEIGHT } from "../constants"; +import type { EditorController } from "../types/editorController"; + +interface PlainEditorProps { + className: string; + initialContent: string; + placeholder: string; + onContentChange: (content: string) => void; + onPaste: (event: React.ClipboardEvent) => void; + isFocusMode?: boolean; +} + +// Low-level string-surgery handle over the textarea. Internal to this file — +// outside callers only ever see the EditorController exposed via the ref. +interface TextareaActions { + getEditor: () => HTMLTextAreaElement | null; + focus: () => void; + scrollToCursor: () => void; + insertText: (text: string, prefix?: string, suffix?: string) => void; + setContent: (text: string) => void; + getContent: () => string; + 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); + + const updateEditorHeight = useCallback(() => { + if (editorRef.current) { + editorRef.current.style.height = "auto"; + editorRef.current.style.height = `${editorRef.current.scrollHeight ?? 0}px`; + } + }, []); + + const updateContent = useCallback(() => { + if (editorRef.current) { + handleContentChangeCallback(editorRef.current.value); + updateEditorHeight(); + } + }, [handleContentChangeCallback, updateEditorHeight]); + + const scrollToCaret = useCallback((options: { force?: boolean } = {}) => { + const editor = editorRef.current; + if (!editor) return; + + const { force = false } = options; + const caret = getCaretCoordinates(editor, editor.selectionEnd); + + if (force) { + editor.scrollTop = Math.max(0, caret.top - editor.clientHeight / 2); + return; + } + + const lineHeight = parseFloat(getComputedStyle(editor).lineHeight) || 24; + const viewportBottom = editor.scrollTop + editor.clientHeight; + // Scroll if cursor is near or beyond bottom edge (within 2 lines) + if (caret.top + lineHeight * 2 > viewportBottom) { + editor.scrollTop = Math.max(0, caret.top - editor.clientHeight / 2); + } + }, []); + + useEffect(() => { + if (editorRef.current && initialContent) { + editorRef.current.value = initialContent; + handleContentChangeCallback(initialContent); + updateEditorHeight(); + } + // Only run once on mount to set initial content + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + + // Update editor when content is externally changed (e.g., reset after save) + useEffect(() => { + if (editorRef.current && editorRef.current.value !== initialContent) { + editorRef.current.value = initialContent; + updateEditorHeight(); + } + }, [initialContent, updateEditorHeight]); + + const actions: TextareaActions = useMemo( + () => ({ + getEditor: () => editorRef.current, + focus: () => editorRef.current?.focus(), + scrollToCursor: () => { + scrollToCaret({ force: true }); + }, + insertText: (content = "", prefix = "", suffix = "") => { + const editor = editorRef.current; + if (!editor) return; + + const cursorPos = editor.selectionStart; + const endPos = editor.selectionEnd; + const prev = editor.value; + const actual = content || prev.slice(cursorPos, endPos); + editor.value = prev.slice(0, cursorPos) + prefix + actual + suffix + prev.slice(endPos); + + editor.focus(); + editor.setSelectionRange(cursorPos + prefix.length + actual.length, cursorPos + prefix.length + actual.length); + updateContent(); + }, + setContent: (text: string) => { + const editor = editorRef.current; + if (editor) { + editor.value = text; + updateContent(); + } + }, + getContent: () => editorRef.current?.value ?? "", + 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; + if (!editor) return; + // setSelectionRange requires valid arguments; default to startPos if endPos is undefined + const endPosition = endPos !== undefined && !Number.isNaN(endPos) ? endPos : startPos; + editor.setSelectionRange(startPos, endPosition); + }, + 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. + useImperativeHandle( + ref, + (): EditorController => ({ + focus: () => actions.focus(), + hasFocus: () => { + const element = actions.getEditor(); + return Boolean(element) && document.activeElement === element; + }, + isEmpty: () => actions.getContent().trim() === "", + getMarkdown: () => actions.getContent(), + setMarkdown: (markdown) => actions.setContent(markdown), + insertMarkdown: (markdown) => { + if (!markdown) return; + const content = actions.getContent(); + const cursor = actions.getCursorPosition(); + const before = content.slice(0, cursor); + const after = content.slice(cursor); + const prefix = before.length === 0 || before.endsWith("\n\n") ? "" : before.endsWith("\n") ? "\n" : "\n\n"; + const suffix = after.length === 0 || after.startsWith("\n\n") ? "" : after.startsWith("\n") ? "\n" : "\n\n"; + actions.insertText(markdown, prefix, suffix); + }, + scrollToCursor: () => actions.scrollToCursor(), + selectAll: () => actions.setCursorPosition(0, actions.getContent().length), + 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], + ); + + const handleEditorInput = useCallback(() => { + if (editorRef.current) { + handleContentChangeCallback(editorRef.current.value); + updateEditorHeight(); + + // Auto-scroll to keep cursor visible when typing + // See: https://github.com/usememos/memos/issues/5469 + scrollToCaret(); + } + }, [handleContentChangeCallback, updateEditorHeight, scrollToCaret]); + + // Recalculate editor height when focus mode changes + useEffect(() => { + updateEditorHeight(); + }, [isFocusMode, updateEditorHeight]); + + return ( +
+ +
+ ); +}); + +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/README.md b/web/src/components/MemoEditor/README.md index 908efe77..93c104b9 100644 --- a/web/src/components/MemoEditor/README.md +++ b/web/src/components/MemoEditor/README.md @@ -38,12 +38,9 @@ MemoEditor/ ├── hooks/ # React hooks (utilities) │ ├── useMemoInit.ts # Initializes editor content; load guard for WYSIWYG │ └── ... -├── Editor/ # Textarea (raw mode) implementation -│ ├── controllerAdapter.ts # Adapts EditorRefActions → EditorController -│ ├── TagSuggestions.tsx # # popup for raw mode -│ ├── SlashCommands.tsx # / popup for raw mode -│ └── ... -├── TiptapEditor/ # Tiptap WYSIWYG implementation +├── PlainEditor/ # Plain textarea (raw mode) implementation +│ └── index.tsx # Bare textarea implementing EditorController directly +├── Editor/ # Tiptap WYSIWYG implementation (default) │ ├── index.tsx # Editor component; implements EditorController │ ├── extensions.ts # Canonical schema-relevant extension set (shared with codec) │ ├── markdownCodec.ts # Headless parse/serialize helpers (singleton editor) @@ -72,8 +69,8 @@ Uses `useReducer` + Context for predictable state transitions. All state changes `types/editorController.ts` defines the `EditorController` interface — `focus`, `getMarkdown`, `setMarkdown`, `insertMarkdown`, formatting toggles, etc. — that callers outside an editor implementation must use exclusively. -- **WYSIWYG mode** (`TiptapEditor/`): Tiptap/ProseMirror rich-text editor. The default mode. Implements `EditorController` directly via `useImperativeHandle` in `TiptapEditor/index.tsx`. -- **Raw mode** (`Editor/`): plain textarea. `Editor/controllerAdapter.ts` adapts the textarea's imperative string-surgery API (`EditorRefActions`) to the same `EditorController` contract. +- **WYSIWYG mode** (`Editor/`): Tiptap/ProseMirror rich-text editor. The default mode. Implements `EditorController` directly via `useImperativeHandle` in `Editor/index.tsx`. +- **Raw mode** (`PlainEditor/`): a bare textarea with no in-editor assistance (no suggestion popups, list continuation, or keyboard markdown shortcuts) — just auto-grow and cursor-visibility scrolling. It implements `EditorController` directly (markdown is just the textarea value), so the toolbar's formatting toggles still work. `components/EditorContent.tsx` hosts whichever implementation `state.ui.editorMode` selects and exposes a single mode-routing `EditorController` facade to the rest of the component tree via `forwardRef`. @@ -83,9 +80,9 @@ The toolbar button in `EditorToolbar.tsx` dispatches `SET_EDITOR_MODE` and calls Mode switching is a markdown handoff: because both editors write into `state.content` on every keystroke, the incoming editor simply initializes from it — no content is ever pushed between editors directly. -### Markdown fidelity layer (TiptapEditor) +### Markdown fidelity layer (Editor) -`TiptapEditor/extensions.ts` exports `buildExtensions()`, the canonical schema-relevant extension set. It is shared by the live editor and the headless `markdownCodec.ts` (parse/serialize/round-trip helpers over a singleton Tiptap instance) so parse and serialize behavior is identical in both contexts. +`Editor/extensions.ts` exports `buildExtensions()`, the canonical schema-relevant extension set. It is shared by the live editor and the headless `markdownCodec.ts` (parse/serialize/round-trip helpers over a singleton Tiptap instance) so parse and serialize behavior is identical in both contexts. `PreservedBlock.ts` handles syntax the WYSIWYG editor does not model richly: tables, `$$math$$`, and raw HTML are captured at parse time with their raw markdown source, shown as editable monospace literal text, and re-emitted byte-for-byte on serialize. @@ -93,10 +90,7 @@ Mode switching is a markdown handoff: because both editors write into `state.con ### Suggestions -Both modes provide `#` tag and `/` slash-command suggestion popups, but they are implemented separately: - -- WYSIWYG mode: `TiptapEditor/TagSuggestion.ts` and `TiptapEditor/SlashCommand.ts`, both using the shared `TiptapEditor/suggestionMenu.tsx` renderer. -- Raw mode: `Editor/TagSuggestions.tsx` and `Editor/SlashCommands.tsx`. +`#` tag and `/` slash-command suggestion popups are a **WYSIWYG-only** feature: `Editor/TagSuggestion.ts` and `Editor/SlashCommand.ts`, both using the shared `Editor/suggestionMenu.tsx` renderer. Raw mode is a plain textarea with no suggestions. ### Load guard diff --git a/web/src/components/MemoEditor/TiptapEditor/index.tsx b/web/src/components/MemoEditor/TiptapEditor/index.tsx deleted file mode 100644 index 8dbc618a..00000000 --- a/web/src/components/MemoEditor/TiptapEditor/index.tsx +++ /dev/null @@ -1,198 +0,0 @@ -import { Extension } from "@tiptap/core"; -import { Placeholder } from "@tiptap/extensions"; -import type { EditorProps as ProseMirrorEditorProps } from "@tiptap/pm/view"; -import { EditorContent as TiptapEditorContent, useEditor } from "@tiptap/react"; -import { forwardRef, useEffect, useImperativeHandle, useMemo, useRef } from "react"; -import { matchPath } from "react-router-dom"; -import { useTagCounts } from "@/hooks/useUserQueries"; -import { cn } from "@/lib/utils"; -import { ROUTES as Routes } from "@/router/routes"; -import { EDITOR_HEIGHT } from "../constants"; -import type { EditorController } from "../types/editorController"; -import { buildExtensions } from "./extensions"; -import { SlashCommand } from "./SlashCommand"; -import { TagSuggestion } from "./TagSuggestion"; - -// Mod-Enter is the app-wide "save memo" shortcut (useKeyboard). StarterKit's -// HardBreak extension also binds Mod-Enter to insert a hard break, which would -// mutate the document right before save fires. This extension swallows the -// shortcut (returning true stops further keymap handlers) while preserving -// DOM event bubbling — preventDefault does NOT stopPropagation, so the window- -// level save listener in useKeyboard still receives and handles the keystroke. -// Priority 1000 > HardBreak's default 100, so this handler runs first. -// Shift-Enter still inserts a hard break as expected. -const SaveShortcutPassthrough = Extension.create({ - name: "saveShortcutPassthrough", - priority: 1000, - addKeyboardShortcuts() { - return { - "Mod-Enter": () => true, - }; - }, -}); - -export interface TiptapEditorProps { - className?: string; - initialContent: string; - placeholder: string; - isFocusMode?: boolean; - onContentChange: (content: string) => void; - onPaste: (event: React.ClipboardEvent) => void; -} - -/** - * The Document serializer joins/terminates blocks with `\n\n`, so e.g. a task - * list serializes with a trailing blank line. Outer whitespace is meaningless - * at the document level (the round-trip corpus compares modulo outer trim), - * so every markdown string leaving this component is trimmed. - */ -function serializeMarkdown(editor: { getMarkdown: () => string } | null): string { - return (editor?.getMarkdown() ?? "").trim(); -} - -/** - * WYSIWYG memo editor on Tiptap/ProseMirror. Markdown is the only format - * crossing its boundary: in via setContent(contentType: "markdown"), out via - * serializeMarkdown() on every update. IME, list continuation, input rules, - * and auto-grow are native ProseMirror/contenteditable behavior. - */ -const TiptapEditor = forwardRef(function TiptapEditor(props, ref) { - const { className, initialContent, placeholder, isFocusMode, onContentChange, onPaste } = props; - - // Last markdown emitted through onContentChange, so the sync effect can - // recognize the parent echoing our own value back without re-serializing. - const lastEmittedRef = useRef(null); - // Read through refs so the memoized extension/editorProps closures below - // always see the latest props (Placeholder decorations recompute per - // transaction; handlePaste resolves per event). - const placeholderRef = useRef(placeholder); - placeholderRef.current = placeholder; - const onPasteRef = useRef(onPaste); - onPasteRef.current = onPaste; - - // On the explore page suggestions include all users' tags; otherwise the - // current user's. Same sourcing as the raw editor's TagSuggestions. - const isExplorePage = useMemo(() => Boolean(matchPath(Routes.EXPLORE, window.location.pathname)), []); - const { data: tagCount = {} } = useTagCounts(!isExplorePage); - const sortedTags = useMemo( - () => - Object.entries(tagCount) - .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])) - .map(([tag]) => tag), - [tagCount], - ); - const tagsRef = useRef([]); - tagsRef.current = sortedTags; - - // Stable option identities so useEditor's compareOptions stays equal across - // renders and Tiptap skips a needless setOptions/view.setProps pass per - // keystroke. All dynamic values reach the closures through refs above. - // `content` is only consumed at editor creation — later external changes - // flow through the sync effect — so the mount-time value is frozen too. - const mountContentRef = useRef(initialContent); - const extensions = useMemo( - () => [ - ...buildExtensions(), - Placeholder.configure({ placeholder: () => placeholderRef.current }), - TagSuggestion.configure({ getTags: () => tagsRef.current }), - SlashCommand, - SaveShortcutPassthrough, - ], - [], - ); - const editorProps = useMemo( - () => ({ - attributes: { - class: "memo-wysiwyg outline-none w-full text-base break-words min-h-6", - }, - handlePaste: (_view, event) => { - const hasFiles = Array.from(event.clipboardData?.items ?? []).some((item) => item.kind === "file"); - if (hasFiles) { - onPasteRef.current(event as unknown as React.ClipboardEvent); - return true; - } - // Text paste (incl. URL-over-selection → link) is handled natively. - return false; - }, - }), - [], - ); - - const editor = useEditor({ - extensions, - content: mountContentRef.current, - contentType: "markdown", - editorProps, - onUpdate: ({ editor: currentEditor }) => { - const markdown = serializeMarkdown(currentEditor); - lastEmittedRef.current = markdown; - onContentChange(markdown); - }, - }); - - // Sync external content changes (e.g. reset after save, draft restore) - // without clobbering the document the user is typing into: only apply when - // the markdown actually differs. - useEffect(() => { - if (!editor) { - return; - } - // Parent echo of our own emission — nothing to sync (O(1) fast path). - // Comparing against the live document instead would race: a keystroke - // landing between the emission and this passive effect would make the - // echo look like an external change and clobber the keystroke/cursor. - if (initialContent === lastEmittedRef.current) { - return; - } - // Never clobber an in-progress IME composition. - if (editor.view.composing) { - return; - } - if (serializeMarkdown(editor) !== initialContent.trim()) { - editor.commands.setContent(initialContent, { contentType: "markdown", emitUpdate: false }); - // A subsequent identical echo of this value is also a no-op. - lastEmittedRef.current = initialContent; - } - }, [initialContent, editor]); - - useImperativeHandle( - ref, - (): EditorController => ({ - focus: () => editor?.commands.focus(), - hasFocus: () => editor?.isFocused ?? false, - // Contract: whitespace-only counts as empty. Tiptap's structural - // `editor.isEmpty` would call a paragraph of spaces non-empty. - isEmpty: () => serializeMarkdown(editor) === "", - getMarkdown: () => serializeMarkdown(editor), - setMarkdown: (markdown) => editor?.commands.setContent(markdown, { contentType: "markdown" }), - insertMarkdown: (markdown) => editor?.chain().focus().insertContent(markdown, { contentType: "markdown" }).run(), - scrollToCursor: () => editor?.commands.scrollIntoView(), - selectAll: () => editor?.commands.selectAll(), - toggleBold: () => editor?.chain().focus().toggleBold().run(), - toggleItalic: () => editor?.chain().focus().toggleItalic().run(), - toggleTaskList: () => editor?.chain().focus().toggleTaskList().run(), - }), - [editor], - ); - - return ( -
{ - // In focus mode the wrapper extends below the content; a click on the - // empty area should land the caret at the end instead of doing nothing. - if (event.target === event.currentTarget) { - editor?.commands.focus("end"); - } - }} - > - -
- ); -}); - -export default TiptapEditor; diff --git a/web/src/components/MemoEditor/Toolbar/InsertMenu.tsx b/web/src/components/MemoEditor/Toolbar/InsertMenu.tsx index 3d333e1c..a8fcdc6a 100644 --- a/web/src/components/MemoEditor/Toolbar/InsertMenu.tsx +++ b/web/src/components/MemoEditor/Toolbar/InsertMenu.tsx @@ -1,6 +1,5 @@ import { uniqBy } from "lodash-es"; import { - CodeXmlIcon, FileIcon, ImageIcon, LinkIcon, @@ -11,7 +10,6 @@ import { MicIcon, MoreHorizontalIcon, PlusIcon, - TypeIcon, } from "lucide-react"; import { useCallback, useEffect, useMemo, useState } from "react"; import { LinkMemoDialog, LocationDialog } from "@/components/MemoMetadata"; @@ -20,6 +18,7 @@ import { useReverseGeocoding } from "@/components/map/useReverseGeocoding"; import { Button } from "@/components/ui/button"; import { DropdownMenu, + DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, @@ -135,11 +134,14 @@ const InsertMenu = (props: InsertMenuProps) => { setMoreSubmenuOpen(false); }, [onToggleFocusMode]); - const handleToggleEditorMode = useCallback(() => { - const next = state.ui.editorMode === "wysiwyg" ? "raw" : "wysiwyg"; - dispatch(actions.setEditorMode(next)); - setPreferredEditorMode(next); - }, [state.ui.editorMode, actions, dispatch]); + const handleEditorModeChange = useCallback( + (checked: boolean) => { + const next = checked ? "wysiwyg" : "raw"; + dispatch(actions.setEditorMode(next)); + setPreferredEditorMode(next); + }, + [actions, dispatch], + ); const handleMediaUploadClick = useCallback(() => { handleUploadClick("image/*,video/*"); @@ -209,12 +211,7 @@ const InsertMenu = (props: InsertMenuProps) => { ))} - {/* Editor display mode: raw Markdown ↔ rich text (WYSIWYG) */} - - {state.ui.editorMode === "wysiwyg" ? : } - {state.ui.editorMode === "wysiwyg" ? t("editor.switch-to-raw") : t("editor.switch-to-wysiwyg")} - - {/* View submenu with Focus Mode */} + {/* View submenu with Focus Mode + editor display mode */} @@ -225,6 +222,10 @@ const InsertMenu = (props: InsertMenuProps) => { {t("editor.focus-mode")} + {/* Editor display mode: checked = rich text (WYSIWYG), unchecked = raw Markdown */} + + {t("editor.wysiwyg-editor")} +
{t("editor.slash-commands")}
diff --git a/web/src/components/MemoEditor/components/EditorContent.tsx b/web/src/components/MemoEditor/components/EditorContent.tsx index abd1417a..c1501ab4 100644 --- a/web/src/components/MemoEditor/components/EditorContent.tsx +++ b/web/src/components/MemoEditor/components/EditorContent.tsx @@ -1,9 +1,8 @@ -import { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef } from "react"; -import Editor, { type EditorRefActions } from "../Editor"; -import { createTextareaController } from "../Editor/controllerAdapter"; +import { forwardRef, useCallback, useEffect, useImperativeHandle, useRef } from "react"; +import Editor from "../Editor"; import { useBlobUrls, useDragAndDrop } from "../hooks"; +import PlainEditor from "../PlainEditor"; import { useEditorContext } from "../state"; -import TiptapEditor from "../TiptapEditor"; import type { EditorContentProps } from "../types"; import type { LocalFile } from "../types/attachment"; import type { EditorController } from "../types/editorController"; @@ -19,16 +18,14 @@ export const EditorContent = forwardRef(({ const { createBlobUrl } = useBlobUrls(); const mode = state.ui.editorMode; - const textareaActionsRef = useRef(null); - const tiptapControllerRef = useRef(null); - const textareaController = useMemo(() => createTextareaController(() => textareaActionsRef.current), []); + // Both editors implement EditorController; the host holds one ref each and + // routes the parent's single ref to whichever mode is active. + const wysiwygRef = useRef(null); + const plainRef = useRef(null); const modeRef = useRef(mode); modeRef.current = mode; - const getActive = useCallback( - (): EditorController | null => (modeRef.current === "wysiwyg" ? tiptapControllerRef.current : textareaController), - [textareaController], - ); + const getActive = useCallback((): EditorController | null => (modeRef.current === "wysiwyg" ? wysiwygRef.current : plainRef.current), []); // Mid-edit mode switches should land the user back in the editor, not on // the toolbar button. Skipped on first mount (useMemoInit owns autofocus). @@ -68,14 +65,6 @@ export const EditorContent = forwardRef(({ localFiles.forEach((localFile) => dispatch(actions.addLocalFile(localFile))); }); - const handleCompositionStart = () => { - dispatch(actions.setComposing(true)); - }; - - const handleCompositionEnd = () => { - dispatch(actions.setComposing(false)); - }; - const handleContentChange = (content: string) => { dispatch(actions.updateContent(content)); }; @@ -109,11 +98,8 @@ export const EditorContent = forwardRef(({ return (
{mode === "wysiwyg" ? ( - // No composition wiring: ProseMirror handles IME natively, and - // state.ui.isComposing is only read by the raw editor below — feeding - // it from here could only strand the flag across a mode switch. - (({ onPaste={handlePaste} /> ) : ( - )}
diff --git a/web/src/components/MemoEditor/hooks/useMemoInit.ts b/web/src/components/MemoEditor/hooks/useMemoInit.ts index dba2c89b..544c0338 100644 --- a/web/src/components/MemoEditor/hooks/useMemoInit.ts +++ b/web/src/components/MemoEditor/hooks/useMemoInit.ts @@ -2,10 +2,10 @@ import { useEffect, useRef, useState } from "react"; import toast from "react-hot-toast"; import type { Memo, Visibility } from "@/types/proto/api/v1/memo_service_pb"; import { useTranslate } from "@/utils/i18n"; +import { isLosslessRoundTrip } from "../Editor/markdownCodec"; import { getPreferredEditorMode } from "../editorMode"; import { cacheService, memoService } from "../services"; import { useEditorContext } from "../state"; -import { isLosslessRoundTrip } from "../TiptapEditor/markdownCodec"; import type { EditorController } from "../types/editorController"; interface UseMemoInitOptions { diff --git a/web/src/components/MemoEditor/state/actions.ts b/web/src/components/MemoEditor/state/actions.ts index 98395610..15a4e385 100644 --- a/web/src/components/MemoEditor/state/actions.ts +++ b/web/src/components/MemoEditor/state/actions.ts @@ -68,11 +68,6 @@ export const editorActions = { payload: { key, value }, }), - setComposing: (value: boolean): EditorAction => ({ - type: "SET_COMPOSING", - payload: value, - }), - setTimestamps: (timestamps: Partial): EditorAction => ({ type: "SET_TIMESTAMPS", payload: timestamps, diff --git a/web/src/components/MemoEditor/state/reducer.ts b/web/src/components/MemoEditor/state/reducer.ts index 05b2fdfb..200c0465 100644 --- a/web/src/components/MemoEditor/state/reducer.ts +++ b/web/src/components/MemoEditor/state/reducer.ts @@ -107,15 +107,6 @@ export function editorReducer(state: EditorState, action: EditorAction): EditorS }, }; - case "SET_COMPOSING": - return { - ...state, - ui: { - ...state.ui, - isComposing: action.payload, - }, - }; - case "SET_TIMESTAMPS": return { ...state, @@ -177,9 +168,6 @@ export function editorReducer(state: EditorState, action: EditorAction): EditorS ui: { ...state.ui, editorMode: action.payload, - // A composition can't survive an editor swap; a stuck flag would - // disable the textarea's IME-guarded features until the next IME cycle. - isComposing: false, }, }; diff --git a/web/src/components/MemoEditor/state/types.ts b/web/src/components/MemoEditor/state/types.ts index 8a3da934..883390e1 100644 --- a/web/src/components/MemoEditor/state/types.ts +++ b/web/src/components/MemoEditor/state/types.ts @@ -23,7 +23,6 @@ export interface EditorState { uploading: boolean; loading: boolean; }; - isComposing: boolean; editorMode: EditorMode; }; timestamps: { @@ -54,7 +53,6 @@ export type EditorAction = | { type: "CLEAR_LOCAL_FILES" } | { type: "TOGGLE_FOCUS_MODE" } | { type: "SET_LOADING"; payload: { key: LoadingKey; value: boolean } } - | { type: "SET_COMPOSING"; payload: boolean } | { type: "SET_TIMESTAMPS"; payload: Partial } | { type: "SET_AUDIO_RECORDER_SUPPORT"; payload: boolean } | { type: "SET_AUDIO_RECORDER_PERMISSION"; payload: AudioRecorderPermission } @@ -82,7 +80,6 @@ const defaultState: EditorState = { uploading: false, loading: false, }, - isComposing: false, editorMode: "wysiwyg", }, timestamps: { diff --git a/web/src/components/MemoEditor/types/components.ts b/web/src/components/MemoEditor/types/components.ts index 047368c9..7f55747d 100644 --- a/web/src/components/MemoEditor/types/components.ts +++ b/web/src/components/MemoEditor/types/components.ts @@ -1,7 +1,4 @@ -import type { ClipboardEvent, ForwardedRef, RefObject } from "react"; import type { Location, Memo, Visibility } from "@/types/proto/api/v1/memo_service_pb"; -import type { EditorRefActions } from "../Editor"; -import type { Command } from "../Editor/commands"; import type { EditorState } from "../state"; export interface MemoEditorProps { @@ -70,29 +67,6 @@ export interface InsertMenuProps { onAudioRecorderClick?: () => void; } -export interface TagSuggestionsProps { - editorRef: RefObject; - editorActions: ForwardedRef; -} - -export interface SlashCommandsProps { - editorRef: RefObject; - editorActions: ForwardedRef; - commands: Command[]; -} - -export interface EditorProps { - className: string; - initialContent: string; - placeholder: string; - onContentChange: (content: string) => void; - onPaste: (event: ClipboardEvent) => void; - isFocusMode?: boolean; - isInIME?: boolean; - onCompositionStart?: () => void; - onCompositionEnd?: () => void; -} - export interface VisibilitySelectorProps { value: Visibility; onChange: (visibility: Visibility) => void; diff --git a/web/src/components/MemoEditor/types/editorController.ts b/web/src/components/MemoEditor/types/editorController.ts index eb97dd17..9b591a3c 100644 --- a/web/src/components/MemoEditor/types/editorController.ts +++ b/web/src/components/MemoEditor/types/editorController.ts @@ -1,7 +1,7 @@ /** - * The contract both memo editors (raw textarea and Tiptap WYSIWYG) implement. + * 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 editor-specific APIs like EditorRefActions. + * interface and never reach for an editor's internal DOM/ProseMirror APIs. */ export interface EditorController { focus(): void; diff --git a/web/src/components/MemoEditor/types/index.ts b/web/src/components/MemoEditor/types/index.ts index 169c705f..394eae75 100644 --- a/web/src/components/MemoEditor/types/index.ts +++ b/web/src/components/MemoEditor/types/index.ts @@ -3,14 +3,11 @@ export type { EditorContentProps, EditorMetadataProps, - EditorProps, EditorToolbarProps, FocusModeExitButtonProps, FocusModeOverlayProps, InsertMenuProps, MemoEditorProps, - SlashCommandsProps, - TagSuggestionsProps, VisibilitySelectorProps, } from "./components"; export type { EditorController } from "./editorController"; diff --git a/web/src/locales/en.json b/web/src/locales/en.json index 6414148f..ae4619cd 100644 --- a/web/src/locales/en.json +++ b/web/src/locales/en.json @@ -173,9 +173,8 @@ "save": "Save", "saving": "Saving...", "slash-commands": "Type `/` for commands", - "switch-to-raw": "Edit raw Markdown", - "switch-to-wysiwyg": "Edit rich text", "unsupported-syntax-raw-mode": "This memo contains syntax the rich-text editor can't safely edit, so it opened in raw Markdown mode.", + "wysiwyg-editor": "WYSIWYG Editor", "audio-recorder": { "attachment-label": "Audio recording", "attachment-label-with-time": "Audio recording {{time}}", diff --git a/web/tests/tiptap-editor-controller.test.tsx b/web/tests/editor-controller.test.tsx similarity index 91% rename from web/tests/tiptap-editor-controller.test.tsx rename to web/tests/editor-controller.test.tsx index c98d081a..fadffb8b 100644 --- a/web/tests/tiptap-editor-controller.test.tsx +++ b/web/tests/editor-controller.test.tsx @@ -1,8 +1,8 @@ -import type { Editor } from "@tiptap/core"; import { act, fireEvent, render } from "@testing-library/react"; +import type { Editor as EditorInstance } from "@tiptap/core"; import { createRef } from "react"; import { describe, expect, it, vi } from "vitest"; -import TiptapEditor from "@/components/MemoEditor/TiptapEditor"; +import Editor from "@/components/MemoEditor/Editor"; import type { EditorController } from "@/components/MemoEditor/types/editorController"; vi.mock("@/hooks/useUserQueries", async (importOriginal) => ({ @@ -14,11 +14,11 @@ function setup(initialContent = "") { const ref = createRef(); const onContentChange = vi.fn(); const { container } = render( - , + , ); - // Tiptap exposes the editor instance on the ProseMirror DOM node; tests use - // it only where the EditorController surface cannot produce the state. - const editor = (container.querySelector(".ProseMirror") as HTMLElement & { editor?: Editor }).editor as Editor; + // The editor instance is exposed on the ProseMirror DOM node; tests use it + // only where the EditorController surface cannot produce the state. + const editor = (container.querySelector(".ProseMirror") as HTMLElement & { editor?: EditorInstance }).editor as EditorInstance; return { ref, onContentChange, editor }; } @@ -28,14 +28,14 @@ function setupRerenderable(initialContent = "") { const ref = createRef(); const onContentChange = vi.fn(); const renderEditor = (content: string) => ( - + ); const { rerender: rtlRerender } = render(renderEditor(initialContent)); const rerender = (content: string) => act(() => rtlRerender(renderEditor(content))); return { ref, onContentChange, rerender }; } -describe("TiptapEditor EditorController", () => { +describe("Editor EditorController", () => { it("loads markdown and serializes it back", () => { const { ref } = setup("# Title\n\nSome **bold** text."); expect(ref.current?.getMarkdown()).toBe("# Title\n\nSome **bold** text."); diff --git a/web/tests/editor-load-guard.test.tsx b/web/tests/editor-load-guard.test.tsx index 5096f4c5..83dd19b3 100644 --- a/web/tests/editor-load-guard.test.tsx +++ b/web/tests/editor-load-guard.test.tsx @@ -1,6 +1,6 @@ +import { create } from "@bufbuild/protobuf"; import { render, screen } from "@testing-library/react"; import { describe, expect, it, vi } from "vitest"; -import { create } from "@bufbuild/protobuf"; import { useMemoInit } from "@/components/MemoEditor/hooks"; import { EditorProvider, useEditorContext } from "@/components/MemoEditor/state"; import { MemoSchema } from "@/types/proto/api/v1/memo_service_pb"; @@ -12,7 +12,7 @@ vi.mock("react-hot-toast", () => ({ })); const isLosslessMock = vi.hoisted(() => vi.fn()); -vi.mock("@/components/MemoEditor/TiptapEditor/markdownCodec", () => ({ +vi.mock("@/components/MemoEditor/Editor/markdownCodec", () => ({ isLosslessRoundTrip: isLosslessMock, })); diff --git a/web/tests/editor-mode-toggle.test.tsx b/web/tests/editor-mode-toggle.test.tsx index 9fab55f4..3431fc4b 100644 --- a/web/tests/editor-mode-toggle.test.tsx +++ b/web/tests/editor-mode-toggle.test.tsx @@ -7,8 +7,6 @@ vi.mock("@/hooks/useUserQueries", () => ({ useTagCounts: () => ({ data: {} }), })); -vi.mock("@/components/MemoEditor/Editor/TagSuggestions", () => ({ default: () => null })); -vi.mock("@/components/MemoEditor/Editor/SlashCommands", () => ({ default: () => null })); // useTranslate returns the key string in tests (no i18next backend initialised). vi.mock("@/utils/i18n", () => ({ useTranslate: () => (key: string) => key })); @@ -23,11 +21,7 @@ function ModeProbe() { > {state.ui.editorMode} - @@ -103,7 +97,7 @@ describe("editor mode switching", () => { it("focuses the incoming editor after a toggle", () => { localStorage.setItem("memos-editor-mode", "raw"); - // Tiptap's focus command schedules the actual DOM focus via + // The WYSIWYG editor's focus command schedules the actual DOM focus via // requestAnimationFrame. Mock rAF to fire synchronously so we can assert // that HTMLElement.prototype.focus() was called within the act() boundary. const pendingRafs: FrameRequestCallback[] = []; @@ -119,7 +113,7 @@ describe("editor mode switching", () => { act(() => { fireEvent.click(screen.getByTestId("probe-toggle")); // raw → wysiwyg }); - // Flush pending animation frames (captures Tiptap's deferred view.focus()). + // Flush pending animation frames (captures the editor's deferred view.focus()). act(() => { pendingRafs.splice(0).forEach((cb) => cb(0)); }); diff --git a/web/tests/editor-mode.test.ts b/web/tests/editor-mode.test.ts index 11bea032..b934db17 100644 --- a/web/tests/editor-mode.test.ts +++ b/web/tests/editor-mode.test.ts @@ -31,11 +31,4 @@ describe("editor mode in reducer", () => { const reset = editorReducer(state, { type: "RESET" }); expect(reset.ui.editorMode).toBe("raw"); }); - - it("SET_EDITOR_MODE clears isComposing", () => { - const state = { ...createInitialState() }; - state.ui = { ...state.ui, isComposing: true }; - const next = editorReducer(state, { type: "SET_EDITOR_MODE", payload: "raw" }); - expect(next.ui.isComposing).toBe(false); - }); }); diff --git a/web/tests/tiptap-preserved.test.ts b/web/tests/editor-preserved.test.ts similarity index 98% rename from web/tests/tiptap-preserved.test.ts rename to web/tests/editor-preserved.test.ts index 2de48f3b..118b33c3 100644 --- a/web/tests/tiptap-preserved.test.ts +++ b/web/tests/editor-preserved.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { parseMarkdown, roundTripMarkdown } from "@/components/MemoEditor/TiptapEditor/markdownCodec"; +import { parseMarkdown, roundTripMarkdown } from "@/components/MemoEditor/Editor/markdownCodec"; function blockTypes(markdown: string): string[] { return (parseMarkdown(markdown).content ?? []).map((node) => node.type ?? ""); diff --git a/web/tests/tiptap-slash-commands.test.ts b/web/tests/editor-slash-commands.test.ts similarity index 96% rename from web/tests/tiptap-slash-commands.test.ts rename to web/tests/editor-slash-commands.test.ts index 5e8d4057..0c8ddd4f 100644 --- a/web/tests/tiptap-slash-commands.test.ts +++ b/web/tests/editor-slash-commands.test.ts @@ -1,7 +1,7 @@ import { Editor } from "@tiptap/core"; import { afterEach, describe, expect, it } from "vitest"; -import { buildExtensions } from "@/components/MemoEditor/TiptapEditor/extensions"; -import { filterSlashCommands, slashCommandItems } from "@/components/MemoEditor/TiptapEditor/SlashCommand"; +import { buildExtensions } from "@/components/MemoEditor/Editor/extensions"; +import { filterSlashCommands, slashCommandItems } from "@/components/MemoEditor/Editor/SlashCommand"; let editor: Editor; diff --git a/web/tests/tiptap-tag.test.ts b/web/tests/editor-tag.test.ts similarity index 99% rename from web/tests/tiptap-tag.test.ts rename to web/tests/editor-tag.test.ts index 84edda4f..e23e1cd7 100644 --- a/web/tests/tiptap-tag.test.ts +++ b/web/tests/editor-tag.test.ts @@ -1,6 +1,6 @@ -import { describe, expect, it } from "vitest"; import type { JSONContent } from "@tiptap/core"; -import { parseMarkdown, roundTripMarkdown } from "@/components/MemoEditor/TiptapEditor/markdownCodec"; +import { describe, expect, it } from "vitest"; +import { parseMarkdown, roundTripMarkdown } from "@/components/MemoEditor/Editor/markdownCodec"; function firstParagraphChildren(markdown: string) { return parseMarkdown(markdown).content?.[0]?.content ?? []; diff --git a/web/tests/insert-menu-mode-toggle.test.tsx b/web/tests/insert-menu-mode-toggle.test.tsx index 567bcfa0..3c44ff91 100644 --- a/web/tests/insert-menu-mode-toggle.test.tsx +++ b/web/tests/insert-menu-mode-toggle.test.tsx @@ -1,8 +1,8 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { fireEvent, render, screen } from "@testing-library/react"; import { beforeAll, describe, expect, it, vi } from "vitest"; -import InsertMenu from "@/components/MemoEditor/Toolbar/InsertMenu"; import { EditorProvider, useEditorContext } from "@/components/MemoEditor/state"; +import InsertMenu from "@/components/MemoEditor/Toolbar/InsertMenu"; // useTranslate returns the i18n key directly (no i18next backend in tests). vi.mock("@/utils/i18n", () => ({ useTranslate: () => (key: string) => key })); @@ -36,29 +36,34 @@ function renderInsertMenu() { ); } +// Opens the "+" dropdown, then its "More" submenu, and returns the +// "WYSIWYG Editor" checkbox item. +function openWysiwygCheckbox() { + // Open the dropdown (keyboard open is the most reliable path in jsdom). + fireEvent.keyDown(screen.getByRole("button"), { key: "Enter" }); + // Open the "More" submenu (controlled open state toggles on trigger click). + fireEvent.click(screen.getByText("common.more")); + return screen.getByText("editor.wysiwyg-editor"); +} + describe("InsertMenu editor-mode toggle", () => { - it("switches mode and persists the preference when the item is selected", () => { + it("unchecking the WYSIWYG item switches to raw and persists the preference", () => { localStorage.clear(); renderInsertMenu(); expect(screen.getByTestId("mode").textContent).toBe("wysiwyg"); - // Open the dropdown (keyboard open is the most reliable path in jsdom). - fireEvent.keyDown(screen.getByRole("button"), { key: "Enter" }); - - // Default mode is wysiwyg, so the item offers to switch to raw. - fireEvent.click(screen.getByText("editor.switch-to-raw")); + fireEvent.click(openWysiwygCheckbox()); expect(screen.getByTestId("mode").textContent).toBe("raw"); expect(localStorage.getItem("memos-editor-mode")).toBe("raw"); }); - it("offers to switch back to rich text when already in raw mode", () => { + it("checking the WYSIWYG item switches back to rich text from raw mode", () => { localStorage.setItem("memos-editor-mode", "raw"); renderInsertMenu(); expect(screen.getByTestId("mode").textContent).toBe("raw"); - fireEvent.keyDown(screen.getByRole("button"), { key: "Enter" }); - fireEvent.click(screen.getByText("editor.switch-to-wysiwyg")); + fireEvent.click(openWysiwygCheckbox()); expect(screen.getByTestId("mode").textContent).toBe("wysiwyg"); expect(localStorage.getItem("memos-editor-mode")).toBe("wysiwyg"); diff --git a/web/tests/markdown-roundtrip.test.ts b/web/tests/markdown-roundtrip.test.ts index bb860491..918b1974 100644 --- a/web/tests/markdown-roundtrip.test.ts +++ b/web/tests/markdown-roundtrip.test.ts @@ -1,7 +1,7 @@ import { readdirSync, readFileSync } from "node:fs"; import { join } from "node:path"; import { describe, expect, it } from "vitest"; -import { parseMarkdown, roundTripMarkdown } from "@/components/MemoEditor/TiptapEditor/markdownCodec"; +import { parseMarkdown, roundTripMarkdown } from "@/components/MemoEditor/Editor/markdownCodec"; const CORPUS_DIR = join(__dirname, "fixtures", "markdown-corpus"); diff --git a/web/tests/memo-editor-paste.test.tsx b/web/tests/memo-editor-paste.test.tsx index f4f1110a..c959e90a 100644 --- a/web/tests/memo-editor-paste.test.tsx +++ b/web/tests/memo-editor-paste.test.tsx @@ -1,14 +1,6 @@ import { fireEvent, render, screen } from "@testing-library/react"; import { describe, expect, it, vi } from "vitest"; -import Editor from "@/components/MemoEditor/Editor"; - -vi.mock("@/components/MemoEditor/Editor/TagSuggestions", () => ({ - default: () => null, -})); - -vi.mock("@/components/MemoEditor/Editor/SlashCommands", () => ({ - default: () => null, -})); +import PlainEditor from "@/components/MemoEditor/PlainEditor"; function pastePlainText(textarea: HTMLTextAreaElement, text: string) { fireEvent.paste(textarea, { @@ -20,15 +12,7 @@ function pastePlainText(textarea: HTMLTextAreaElement, text: string) { function renderEditor(initialContent: string) { const onPaste = vi.fn(); - render( - , - ); + render(); return { onPaste, @@ -36,46 +20,16 @@ function renderEditor(initialContent: string) { }; } -describe("memo editor paste handling", () => { - it("wraps selected text with a pasted URL", () => { +describe("plain editor paste handling", () => { + // The plain textarea does no in-editor paste transformation (no URL → link + // wrapping); it forwards every paste to onPaste so the host can handle files. + it("forwards pasted text to onPaste without altering the value", () => { const { onPaste, textarea } = renderEditor("read the docs"); textarea.setSelectionRange(9, 13); pastePlainText(textarea, "https://example.com"); - expect(textarea).toHaveValue("read the [docs](https://example.com)"); - expect(textarea.selectionStart).toBe("read the [docs](https://example.com)".length); - expect(textarea.selectionEnd).toBe("read the [docs](https://example.com)".length); - expect(onPaste).not.toHaveBeenCalled(); - }); - - it("delegates non-URL text paste", () => { - const { onPaste, textarea } = renderEditor("read the docs"); - textarea.setSelectionRange(9, 13); - - pastePlainText(textarea, "not a url"); - expect(textarea).toHaveValue("read the docs"); expect(onPaste).toHaveBeenCalledOnce(); }); - - it("delegates pasted URLs when no text is selected", () => { - const { onPaste, textarea } = renderEditor("read the docs"); - textarea.setSelectionRange(13, 13); - - pastePlainText(textarea, "https://example.com"); - - expect(textarea).toHaveValue("read the docs"); - expect(onPaste).toHaveBeenCalledOnce(); - }); - - it("delegates pasted URLs when the selected text is already a URL", () => { - const { onPaste, textarea } = renderEditor("https://memos.example"); - textarea.setSelectionRange(0, "https://memos.example".length); - - pastePlainText(textarea, "https://example.com"); - - expect(textarea).toHaveValue("https://memos.example"); - expect(onPaste).toHaveBeenCalledOnce(); - }); }); diff --git a/web/tests/memo-editor-shortcuts.test.tsx b/web/tests/memo-editor-shortcuts.test.tsx deleted file mode 100644 index 46090029..00000000 --- a/web/tests/memo-editor-shortcuts.test.tsx +++ /dev/null @@ -1,116 +0,0 @@ -import { fireEvent, render, screen } from "@testing-library/react"; -import { describe, expect, it, vi } from "vitest"; -import Editor from "@/components/MemoEditor/Editor"; - -vi.mock("@/components/MemoEditor/Editor/TagSuggestions", () => ({ - default: () => null, -})); - -vi.mock("@/components/MemoEditor/Editor/SlashCommands", () => ({ - default: () => null, -})); - -function renderEditor(initialContent: string, isInIME = false) { - render( - , - ); - return screen.getByPlaceholderText("memo") as HTMLTextAreaElement; -} - -describe("memo editor markdown shortcuts", () => { - describe("Ctrl+B (bold)", () => { - it("wraps selected text with **", () => { - const textarea = renderEditor("read the docs"); - textarea.setSelectionRange(9, 13); - - fireEvent.keyDown(textarea, { key: "b", ctrlKey: true }); - - expect(textarea).toHaveValue("read the **docs**"); - }); - - it("removes ** from already-bolded text", () => { - const textarea = renderEditor("read the **docs**"); - textarea.setSelectionRange(9, 17); - - fireEvent.keyDown(textarea, { key: "b", ctrlKey: true }); - - expect(textarea).toHaveValue("read the docs"); - }); - - it("works with metaKey (Mac Cmd+B)", () => { - const textarea = renderEditor("read the docs"); - textarea.setSelectionRange(9, 13); - - fireEvent.keyDown(textarea, { key: "b", metaKey: true }); - - expect(textarea).toHaveValue("read the **docs**"); - }); - }); - - describe("Ctrl+I (italic)", () => { - it("wraps selected text with *", () => { - const textarea = renderEditor("read the docs"); - textarea.setSelectionRange(9, 13); - - fireEvent.keyDown(textarea, { key: "i", ctrlKey: true }); - - expect(textarea).toHaveValue("read the *docs*"); - }); - - it("removes * from already-italicized text", () => { - const textarea = renderEditor("read the *docs*"); - textarea.setSelectionRange(9, 15); - - fireEvent.keyDown(textarea, { key: "i", ctrlKey: true }); - - expect(textarea).toHaveValue("read the docs"); - }); - - it("works with metaKey (Mac Cmd+I)", () => { - const textarea = renderEditor("read the docs"); - textarea.setSelectionRange(9, 13); - - fireEvent.keyDown(textarea, { key: "i", metaKey: true }); - - expect(textarea).toHaveValue("read the *docs*"); - }); - - it("preserves bold when italicizing already-bolded text", () => { - const textarea = renderEditor("read the **docs**"); - textarea.setSelectionRange(9, 17); - - fireEvent.keyDown(textarea, { key: "i", ctrlKey: true }); - - expect(textarea).toHaveValue("read the ***docs***"); - }); - }); - - describe("shortcuts suppressed during IME composition", () => { - it("does not apply bold during IME input", () => { - const textarea = renderEditor("テスト", true); - textarea.setSelectionRange(0, 3); - - fireEvent.keyDown(textarea, { key: "b", ctrlKey: true }); - - expect(textarea).toHaveValue("テスト"); - }); - }); - - describe("no modifier key — no action", () => { - it("does not apply bold when Ctrl/Cmd is not held", () => { - const textarea = renderEditor("read the docs"); - textarea.setSelectionRange(9, 13); - - fireEvent.keyDown(textarea, { key: "b" }); - - expect(textarea).toHaveValue("read the docs"); - }); - }); -}); diff --git a/web/tests/editor-controller-adapter.test.tsx b/web/tests/plain-editor-controller.test.tsx similarity index 79% rename from web/tests/editor-controller-adapter.test.tsx rename to web/tests/plain-editor-controller.test.tsx index aea9a3fc..362df2d0 100644 --- a/web/tests/editor-controller-adapter.test.tsx +++ b/web/tests/plain-editor-controller.test.tsx @@ -1,30 +1,20 @@ import { render, screen } from "@testing-library/react"; import { createRef } from "react"; import { describe, expect, it, vi } from "vitest"; -import Editor, { type EditorRefActions } from "@/components/MemoEditor/Editor"; -import { createTextareaController } from "@/components/MemoEditor/Editor/controllerAdapter"; - -vi.mock("@/components/MemoEditor/Editor/TagSuggestions", () => ({ default: () => null })); -vi.mock("@/components/MemoEditor/Editor/SlashCommands", () => ({ default: () => null })); +import PlainEditor from "@/components/MemoEditor/PlainEditor"; +import type { EditorController } from "@/components/MemoEditor/types/editorController"; function setup(initialContent = "") { - const ref = createRef(); + const ref = createRef(); render( - , + , ); - const controller = createTextareaController(() => ref.current); + const controller = ref.current as EditorController; const textarea = screen.getByPlaceholderText("memo") as HTMLTextAreaElement; return { controller, textarea }; } -describe("textarea EditorController adapter", () => { +describe("PlainEditor EditorController", () => { it("getMarkdown/setMarkdown mirror the textarea value", () => { const { controller, textarea } = setup("hello"); expect(controller.getMarkdown()).toBe("hello"); diff --git a/web/tests/suggestion-menu.test.tsx b/web/tests/suggestion-menu.test.tsx index 03973178..d28e3b84 100644 --- a/web/tests/suggestion-menu.test.tsx +++ b/web/tests/suggestion-menu.test.tsx @@ -1,7 +1,8 @@ import { act, fireEvent, render, screen } from "@testing-library/react"; import { createRef } from "react"; +import { createRoot } from "react-dom/client"; import { describe, expect, it, vi } from "vitest"; -import { SuggestionMenu, createSuggestionRenderer, type SuggestionMenuHandle } from "@/components/MemoEditor/TiptapEditor/suggestionMenu"; +import { createSuggestionRenderer, SuggestionMenu, type SuggestionMenuHandle } from "@/components/MemoEditor/Editor/suggestionMenu"; function setup(items = ["alpha", "beta", "gamma"]) { const command = vi.fn(); @@ -79,7 +80,6 @@ describe("createSuggestionRenderer blur handling", () => { setRenderer: vi.fn((_id: string, renderer: { reactElement: React.ReactNode; element: HTMLElement }) => { // Mimic the real portal: render the element directly into renderer.element // via React so it shows up in the DOM when appended to document.body. - const { createRoot } = require("react-dom/client") as typeof import("react-dom/client"); const root = createRoot(renderer.element); act(() => { root.render(renderer.reactElement as React.ReactElement);