diff --git a/web/src/components/MemoEditor/Editor/SlashCommand.ts b/web/src/components/MemoEditor/Editor/SlashCommand.ts deleted file mode 100644 index a1a0bd56..00000000 --- a/web/src/components/MemoEditor/Editor/SlashCommand.ts +++ /dev/null @@ -1,91 +0,0 @@ -import { type Editor, Extension, type Range } from "@tiptap/core"; -import { PluginKey } from "@tiptap/pm/state"; -import Suggestion from "@tiptap/suggestion"; -import { createElement } from "react"; -import { createSuggestionRenderer } from "./suggestionMenu"; - -export interface SlashCommandItem { - name: string; - apply: (editor: Editor, range: Range) => void; -} - -// WYSIWYG counterparts of the raw editor's commands (Editor/commands.ts): -// the same four entries, realized as editor commands instead of raw strings. -export const slashCommandItems: SlashCommandItem[] = [ - { - name: "todo", - apply: (editor, range) => editor.chain().focus().deleteRange(range).toggleTaskList().run(), - }, - { - name: "code", - apply: (editor, range) => editor.chain().focus().deleteRange(range).toggleCodeBlock().run(), - }, - { - name: "link", - // After deleteRange + insertContent the marked text node "text" occupies - // positions range.from..range.from+4. Select it so the user can overtype - // the display text immediately — matching the textarea editor's cursorOffset=1. - apply: (editor, range) => - editor - .chain() - .focus() - .deleteRange(range) - .insertContent("[text](url)", { contentType: "markdown" }) - .setTextSelection({ from: range.from, to: range.from + 4 }) - .run(), - }, - { - name: "table", - // After insert the preservedBlock text starts at range.from. "| Header …" - // has "| " (2 chars) before the first cell label, so range.from+2 lands on - // the "H" of "Header" — matching the textarea editor's first-header-cell - // cursor placement. - apply: (editor, range) => - editor - .chain() - .focus() - .deleteRange(range) - .insertContent("| Header | Header |\n| ------ | ------ |\n| Cell | Cell |", { contentType: "markdown" }) - .setTextSelection(range.from + 2) - .run(), - }, -]; - -/** - * Returns the subset of slash commands whose name starts with `query` - * (case-insensitive). Returns the full list when `query` is empty. - */ -export function filterSlashCommands(query: string): SlashCommandItem[] { - const q = query.toLowerCase(); - return q ? slashCommandItems.filter((item) => item.name.startsWith(q)) : slashCommandItems; -} - -/** `/` command popup; replaces the raw editor's SlashCommands in WYSIWYG mode. */ -export const SlashCommand = Extension.create({ - name: "slashCommand", - - addProseMirrorPlugins() { - return [ - Suggestion({ - editor: this.editor, - pluginKey: new PluginKey("slashCommand"), - char: "/", - allowSpaces: false, - items: ({ query }) => filterSlashCommands(query), - command: ({ editor, range, props: item }) => { - item.apply(editor, range); - }, - render: createSuggestionRenderer({ - getItemKey: (item) => item.name, - renderItem: (item) => - createElement( - "span", - { className: "tracking-wide" }, - createElement("span", { className: "text-muted-foreground" }, "/"), - item.name, - ), - }), - }), - ]; - }, -}); diff --git a/web/src/components/MemoEditor/Editor/index.tsx b/web/src/components/MemoEditor/Editor/index.tsx index d0006625..bd32ffca 100644 --- a/web/src/components/MemoEditor/Editor/index.tsx +++ b/web/src/components/MemoEditor/Editor/index.tsx @@ -9,9 +9,8 @@ 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 type { EditorController, FormattingController } 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 @@ -83,12 +82,15 @@ function serializeMarkdown(editor: { getMarkdown: () => string } | null): string * serializeMarkdown() on every update. IME, list continuation, input rules, * and auto-grow are native ProseMirror/contenteditable behavior. */ -const Editor = forwardRef(function Editor(props, ref) { +const Editor = forwardRef(function Editor(props, ref) { const { className, initialContent, placeholder, isFocusMode, onContentChange, onPaste } = props; // Last markdown emitted through onContentChange, so the sync effect can // recognize the parent echoing our own value back without re-serializing. const lastEmittedRef = useRef(null); + // Stable across editor re-creation so the toolbar can subscribe once. The + // effect below binds the live editor's transaction/selection events to it. + const activeListenersRef = useRef(new Set<() => void>()); // Read through refs so the memoized extension/editorProps closures below // always see the latest props (Placeholder decorations recompute per // transaction; handlePaste resolves per event). @@ -122,7 +124,6 @@ const Editor = forwardRef(function Editor(props, ...buildExtensions(), Placeholder.configure({ placeholder: () => placeholderRef.current }), TagSuggestion.configure({ getTags: () => tagsRef.current }), - SlashCommand, SaveShortcutPassthrough, CollapseAllSelectionAfterDelete, ], @@ -183,9 +184,23 @@ const Editor = forwardRef(function Editor(props, } }, [initialContent, editor]); + // Fan editor transactions out to toolbar subscribers so active-state + // highlighting tracks the cursor live. Every change — including a pure + // selection move — is a transaction, so this single event covers both. + useEffect(() => { + if (!editor) { + return; + } + const notify = () => activeListenersRef.current.forEach((listener) => listener()); + editor.on("transaction", notify); + return () => { + editor.off("transaction", notify); + }; + }, [editor]); + useImperativeHandle( ref, - (): EditorController => ({ + (): EditorController & FormattingController => ({ focus: () => editor?.commands.focus(), hasFocus: () => editor?.isFocused ?? false, // Contract: whitespace-only counts as empty. The editor's structural @@ -199,6 +214,39 @@ const Editor = forwardRef(function Editor(props, toggleBold: () => editor?.chain().focus().toggleBold().run(), toggleItalic: () => editor?.chain().focus().toggleItalic().run(), toggleTaskList: () => editor?.chain().focus().toggleTaskList().run(), + toggleCode: () => editor?.chain().focus().toggleCode().run(), + toggleBulletList: () => editor?.chain().focus().toggleBulletList().run(), + toggleOrderedList: () => editor?.chain().focus().toggleOrderedList().run(), + setHeading: (level) => editor?.chain().focus().setHeading({ level }).run(), + setParagraph: () => editor?.chain().focus().setParagraph().run(), + toggleLink: (url) => { + if (!editor) { + return; + } + if (editor.isActive("link")) { + editor.chain().focus().unsetLink().run(); + return; + } + const href = url?.trim(); + if (!href) { + return; + } + editor.chain().focus().extendMarkRange("link").setLink({ href }).run(); + }, + getSelectedText: () => { + if (!editor) { + return ""; + } + const { from, to } = editor.state.selection; + return editor.state.doc.textBetween(from, to, " "); + }, + isActive: (name, attrs) => editor?.isActive(name, attrs ?? {}) ?? false, + subscribe: (listener) => { + activeListenersRef.current.add(listener); + return () => { + activeListenersRef.current.delete(listener); + }; + }, }), [editor], ); diff --git a/web/src/components/MemoEditor/README.md b/web/src/components/MemoEditor/README.md index 93c104b9..2b2a40ad 100644 --- a/web/src/components/MemoEditor/README.md +++ b/web/src/components/MemoEditor/README.md @@ -47,8 +47,7 @@ MemoEditor/ │ ├── PreservedBlock.ts # Byte-for-byte preservation of tables, math, raw HTML │ ├── Tag.ts # Memos #tag mark │ ├── TagSuggestion.ts # # popup for WYSIWYG mode -│ ├── SlashCommand.ts # / popup for WYSIWYG mode -│ └── suggestionMenu.tsx # Shared suggestion popup renderer (used by both above) +│ └── suggestionMenu.tsx # Shared suggestion popup renderer (used by TagSuggestion) ├── Toolbar/ # Toolbar sub-components (InsertMenu, VisibilitySelector) ├── editorMode.ts # EditorMode type + localStorage persistence helpers ├── constants.ts @@ -90,7 +89,7 @@ Mode switching is a markdown handoff: because both editors write into `state.con ### Suggestions -`#` 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. +The `#` tag suggestion popup is a **WYSIWYG-only** feature: `Editor/TagSuggestion.ts`, using the shared `Editor/suggestionMenu.tsx` renderer. Raw mode is a plain textarea with no suggestions. (Formatting actions that a `/` command menu would once have offered — lists, code, link — are now available from the focus-mode `FormattingToolbar` header.) ### Load guard diff --git a/web/src/components/MemoEditor/Toolbar/InsertMenu.tsx b/web/src/components/MemoEditor/Toolbar/InsertMenu.tsx index a8fcdc6a..295ed22a 100644 --- a/web/src/components/MemoEditor/Toolbar/InsertMenu.tsx +++ b/web/src/components/MemoEditor/Toolbar/InsertMenu.tsx @@ -228,7 +228,6 @@ const InsertMenu = (props: InsertMenuProps) => { -
{t("editor.slash-commands")}
diff --git a/web/src/components/MemoEditor/components/EditorContent.tsx b/web/src/components/MemoEditor/components/EditorContent.tsx index c1501ab4..b3e49bc2 100644 --- a/web/src/components/MemoEditor/components/EditorContent.tsx +++ b/web/src/components/MemoEditor/components/EditorContent.tsx @@ -5,7 +5,7 @@ import PlainEditor from "../PlainEditor"; import { useEditorContext } from "../state"; import type { EditorContentProps } from "../types"; import type { LocalFile } from "../types/attachment"; -import type { EditorController } from "../types/editorController"; +import type { EditorController, FormattingController, ToolbarHeadingLevel } from "../types/editorController"; /** * Hosts one of the two editor implementations behind the EditorController @@ -13,14 +13,14 @@ import type { EditorController } from "../types/editorController"; * handoff: both editors serialize into state.content on every change, so the * incoming editor simply initializes from it. */ -export const EditorContent = forwardRef(({ placeholder }, ref) => { +export const EditorContent = forwardRef(({ placeholder }, ref) => { const { state, actions, dispatch } = useEditorContext(); const { createBlobUrl } = useBlobUrls(); const mode = state.ui.editorMode; // Both editors implement EditorController; the host holds one ref each and // routes the parent's single ref to whichever mode is active. - const wysiwygRef = useRef(null); + const wysiwygRef = useRef(null); const plainRef = useRef(null); const modeRef = useRef(mode); @@ -40,7 +40,7 @@ export const EditorContent = forwardRef(({ useImperativeHandle( ref, - (): EditorController => ({ + (): EditorController & FormattingController => ({ focus: () => getActive()?.focus(), hasFocus: () => getActive()?.hasFocus() ?? false, isEmpty: () => getActive()?.isEmpty() ?? true, @@ -52,6 +52,17 @@ export const EditorContent = forwardRef(({ toggleBold: () => getActive()?.toggleBold(), toggleItalic: () => getActive()?.toggleItalic(), toggleTaskList: () => getActive()?.toggleTaskList(), + // Formatting surface — only the WYSIWYG editor implements it; inert in raw + // mode, where the toolbar is never shown. + toggleCode: () => wysiwygRef.current?.toggleCode(), + toggleBulletList: () => wysiwygRef.current?.toggleBulletList(), + toggleOrderedList: () => wysiwygRef.current?.toggleOrderedList(), + setHeading: (level: ToolbarHeadingLevel) => wysiwygRef.current?.setHeading(level), + setParagraph: () => wysiwygRef.current?.setParagraph(), + toggleLink: (url?: string) => wysiwygRef.current?.toggleLink(url), + getSelectedText: () => wysiwygRef.current?.getSelectedText() ?? "", + isActive: (name: string, attrs?: Record) => wysiwygRef.current?.isActive(name, attrs) ?? false, + subscribe: (listener: () => void) => wysiwygRef.current?.subscribe(listener) ?? (() => {}), }), [getActive], ); diff --git a/web/src/components/MemoEditor/components/FormattingToolbar.tsx b/web/src/components/MemoEditor/components/FormattingToolbar.tsx new file mode 100644 index 00000000..f23ebab3 --- /dev/null +++ b/web/src/components/MemoEditor/components/FormattingToolbar.tsx @@ -0,0 +1,188 @@ +import { + BoldIcon, + CodeIcon, + HeadingIcon, + ItalicIcon, + LinkIcon, + ListIcon, + ListOrderedIcon, + ListTodoIcon, + type LucideIcon, + Minimize2Icon, + MoreHorizontalIcon, +} from "lucide-react"; +import { type RefObject, useRef } from "react"; +import { Button } from "@/components/ui/button"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuSeparator, + DropdownMenuTrigger, +} from "@/components/ui/dropdown-menu"; +import { cn } from "@/lib/utils"; +import { useTranslate } from "@/utils/i18n"; +import { isCompactWidth, useEditorActiveState, useElementWidth } from "../hooks"; +import type { EditorController, FormattingController, ToolbarHeadingLevel } from "../types/editorController"; + +interface FormattingToolbarProps { + controllerRef: RefObject<(EditorController & FormattingController) | null>; + onExit: () => void; + /** Extra classes for the host to frame the toolbar (e.g. the focus-mode header band). */ + className?: string; +} + +const HEADING_LEVELS: ToolbarHeadingLevel[] = [1, 2, 3]; + +interface ToolbarButton { + Icon: LucideIcon; + label: string; + active: boolean; + onClick: () => void; +} + +/** + * Focus-mode header: a rich-text formatting toolbar driven entirely through the + * editor controller. Purely presentational — owns no editor state beyond the + * derived active-marks map. Responsive: below COMPACT_TOOLBAR_WIDTH the list and + * link controls fold into a "more" menu while marks stay inline. + */ +export function FormattingToolbar({ controllerRef, onExit, className }: FormattingToolbarProps) { + const t = useTranslate(); + const rootRef = useRef(null); + const width = useElementWidth(rootRef); + const compact = isCompactWidth(width); + const active = useEditorActiveState(controllerRef); + + const handleLink = () => { + const controller = controllerRef.current; + if (!controller) { + return; + } + if (controller.isActive("link")) { + controller.toggleLink(); + return; + } + const url = window.prompt(t("editor.format.link-prompt")); + if (!url) { + return; + } + const selected = controller.getSelectedText(); + if (selected) { + controller.toggleLink(url); + } else { + controller.insertMarkdown(`[${url}](${url})`); + } + }; + + const headingLabel = active.headingLevel === null ? t("editor.format.paragraph") : t(`editor.format.heading-${active.headingLevel}`); + + // One descriptor per control drives both layouts, so each action's icon, + // label, active flag, and command live in a single place. + const markButtons: ToolbarButton[] = [ + { Icon: BoldIcon, label: t("editor.format.bold"), active: active.bold, onClick: () => controllerRef.current?.toggleBold() }, + { Icon: ItalicIcon, label: t("editor.format.italic"), active: active.italic, onClick: () => controllerRef.current?.toggleItalic() }, + { Icon: CodeIcon, label: t("editor.format.code"), active: active.code, onClick: () => controllerRef.current?.toggleCode() }, + ]; + const listButtons: ToolbarButton[] = [ + { + Icon: ListIcon, + label: t("editor.format.bullet-list"), + active: active.bulletList, + onClick: () => controllerRef.current?.toggleBulletList(), + }, + { + Icon: ListOrderedIcon, + label: t("editor.format.ordered-list"), + active: active.orderedList, + onClick: () => controllerRef.current?.toggleOrderedList(), + }, + { + Icon: ListTodoIcon, + label: t("editor.format.task-list"), + active: active.taskList, + onClick: () => controllerRef.current?.toggleTaskList(), + }, + ]; + const linkButton: ToolbarButton = { Icon: LinkIcon, label: t("editor.format.link"), active: active.link, onClick: handleLink }; + + return ( +
+ + + + + + controllerRef.current?.setParagraph()}>{t("editor.format.paragraph")} + {HEADING_LEVELS.map((level) => ( + controllerRef.current?.setHeading(level)}> + {t(`editor.format.heading-${level}`)} + + ))} + + + + + + {markButtons.map((button) => ( + + ))} + + {compact ? ( + + + + + + {listButtons.map((button) => ( + + {button.label} + + ))} + + {linkButton.label} + + + ) : ( + <> + + {listButtons.map((button) => ( + + ))} + + + + )} + +
+ + +
+ ); +} + +function Divider() { + return