Memos is an open-source, self-hosted note-taking app that brings your everyday thoughts together in a personal timeline. Your data stays yours, and you choose what to keep private or share.
Go dockerfossgomarkdownmemomicroblognote-takingnotesopen-sourceown-your-datareactself-hostedsqlitetimeline
feat(editor): add focus-mode formatting toolbar
johnnyjoyghdeddf71d7b4b
diff --git a/web/src/components/MemoEditor/Editor/SlashCommand.ts b/web/src/components/MemoEditor/Editor/SlashCommand.tsdeleted file mode 100644index a1a0bd56f..000000000--- 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<SlashCommandItem>({- 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<SlashCommandItem>({- 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.tsxindex d00066251..bd32ffcad 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<EditorController, EditorProps>(function Editor(props, ref) {+const Editor = forwardRef<EditorController & FormattingController, EditorProps>(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<string | null>(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<EditorController, EditorProps>(function Editor(props,...buildExtensions(),Placeholder.configure({ placeholder: () => placeholderRef.current }),TagSuggestion.configure({ getTags: () => tagsRef.current }),- SlashCommand,SaveShortcutPassthrough,CollapseAllSelectionAfterDelete,],@@ -183,9 +184,23 @@ const Editor = forwardRef<EditorController, EditorProps>(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<EditorController, EditorProps>(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.mdindex 93c104b90..2b2a40ad6 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 guarddiff --git a/web/src/components/MemoEditor/Toolbar/InsertMenu.tsx b/web/src/components/MemoEditor/Toolbar/InsertMenu.tsxindex a8fcdc6a2..295ed22a8 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) => {</DropdownMenuCheckboxItem></DropdownMenuSubContent></DropdownMenuSub>- <div className="px-2 py-1 text-xs text-muted-foreground opacity-80">{t("editor.slash-commands")}</div></DropdownMenuContent></DropdownMenu>diff --git a/web/src/components/MemoEditor/components/EditorContent.tsx b/web/src/components/MemoEditor/components/EditorContent.tsxindex c1501ab4e..b3e49bc28 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<EditorController, EditorContentProps>(({ placeholder }, ref) => {+export const EditorContent = forwardRef<EditorController & FormattingController, EditorContentProps>(({ 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<EditorController>(null);+ const wysiwygRef = useRef<EditorController & FormattingController>(null);const plainRef = useRef<EditorController>(null);const modeRef = useRef(mode);@@ -40,7 +40,7 @@ export const EditorContent = forwardRef<EditorController, EditorContentProps>(({useImperativeHandle(ref,- (): EditorController => ({+ (): EditorController & FormattingController => ({focus: () => getActive()?.focus(),hasFocus: () => getActive()?.hasFocus() ?? false,isEmpty: () => getActive()?.isEmpty() ?? true,@@ -52,6 +52,17 @@ export const EditorContent = forwardRef<EditorController, EditorContentProps>(({toggleBold: () => getActive()?.toggleBold(),toggleItalic: () => getActive()?.toggleItalic(),toggleTaskList: () => getActive()?.toggleTaskList(),+ // Formatting surface — only the WYSIWYG editor implements it; inert in raw+ // mode, where the toolbar is never shown.+ toggleCode: () => wysiwygRef.current?.toggleCode(),+ toggleBulletList: () => wysiwygRef.current?.toggleBulletList(),+ toggleOrderedList: () => wysiwygRef.current?.toggleOrderedList(),+ setHeading: (level: ToolbarHeadingLevel) => wysiwygRef.current?.setHeading(level),+ setParagraph: () => wysiwygRef.current?.setParagraph(),+ toggleLink: (url?: string) => wysiwygRef.current?.toggleLink(url),+ getSelectedText: () => wysiwygRef.current?.getSelectedText() ?? "",+ isActive: (name: string, attrs?: Record<string, unknown>) => wysiwygRef.current?.isActive(name, attrs) ?? false,+ subscribe: (listener: () => void) => wysiwygRef.current?.subscribe(listener) ?? (() => {}),}),[getActive],);diff --git a/web/src/components/MemoEditor/components/FormattingToolbar.tsx b/web/src/components/MemoEditor/components/FormattingToolbar.tsxnew file mode 100644index 000000000..f23ebab36--- /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<HTMLDivElement>(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 (+ <div+ ref={rootRef}+ className={cn("w-full flex flex-row items-center gap-1 flex-nowrap", className)}+ role="toolbar"+ aria-label={t("editor.format.heading")}+ >+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button variant="ghost" size="sm" aria-label={t("editor.format.heading")}>+ <HeadingIcon className="w-4 h-4" />+ {!compact && <span className="ml-1 text-xs">{headingLabel}</span>}+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start">+ <DropdownMenuItem onClick={() => controllerRef.current?.setParagraph()}>{t("editor.format.paragraph")}</DropdownMenuItem>+ {HEADING_LEVELS.map((level) => (+ <DropdownMenuItem key={level} onClick={() => controllerRef.current?.setHeading(level)}>+ {t(`editor.format.heading-${level}`)}+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>++ <Divider />++ {markButtons.map((button) => (+ <FmtButton key={button.label} {...button} />+ ))}++ {compact ? (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button variant="ghost" size="icon" aria-label={t("editor.format.more")}>+ <MoreHorizontalIcon className="w-4 h-4" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start">+ {listButtons.map((button) => (+ <DropdownMenuItem key={button.label} onClick={button.onClick}>+ {button.label}+ </DropdownMenuItem>+ ))}+ <DropdownMenuSeparator />+ <DropdownMenuItem onClick={linkButton.onClick}>{linkButton.label}</DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ ) : (+ <>+ <Divider />+ {listButtons.map((button) => (+ <FmtButton key={button.label} {...button} />+ ))}+ <Divider />+ <FmtButton {...linkButton} />+ </>+ )}++ <div className="flex-1" />++ <Button variant="ghost" size="icon" aria-label={t("editor.exit-focus-mode")} title={t("editor.exit-focus-mode")} onClick={onExit}>+ <Minimize2Icon className="w-4 h-4" />+ </Button>+ </div>+ );+}++function Divider() {+ return <span aria-hidden="true" className="w-px h-5 bg-border mx-1 shrink-0" />;+}++function FmtButton({ Icon, active, label, onClick }: ToolbarButton) {+ // Active state shown by switching the kit variant (prop-only, per the shadcn+ // kit usage policy) rather than overriding className.+ return (+ <Button variant={active ? "secondary" : "ghost"} size="icon" aria-label={label} aria-pressed={active} title={label} onClick={onClick}>+ <Icon className="w-4 h-4" />+ </Button>+ );+}diff --git a/web/src/components/MemoEditor/components/index.ts b/web/src/components/MemoEditor/components/index.tsindex 73faf0f16..4510bcd52 100644--- a/web/src/components/MemoEditor/components/index.ts+++ b/web/src/components/MemoEditor/components/index.ts@@ -5,4 +5,5 @@ export * from "./EditorContent";export * from "./EditorMetadata";export * from "./EditorToolbar";export { FocusModeExitButton, FocusModeOverlay } from "./FocusModeOverlay";+export { FormattingToolbar } from "./FormattingToolbar";export { TimestampPopover } from "./TimestampPopover";diff --git a/web/src/components/MemoEditor/constants.ts b/web/src/components/MemoEditor/constants.tsindex c135a3300..5b46c969d 100644--- a/web/src/components/MemoEditor/constants.ts+++ b/web/src/components/MemoEditor/constants.ts@@ -6,6 +6,11 @@ export const FOCUS_MODE_STYLES = {},transition: "transition-all duration-300 ease-in-out",exitButton: "absolute top-2 right-2 z-10 opacity-60 hover:opacity-100",+ // Full-bleed formatting-toolbar header band. The negative margins + width+ // counteract the card's px-4 pt-3 padding (1rem each side) so the band sits+ // flush to the inner borders; w-[calc(100%+2rem)] overrides the toolbar's own+ // w-full (twMerge keeps this later width). Keep in sync with the card padding.+ formattingHeader: "-mx-4 -mt-3 mb-1 w-[calc(100%+2rem)] px-3 py-2 bg-muted/50 border-b border-border rounded-t-lg",} as const;export const EDITOR_HEIGHT = {diff --git a/web/src/components/MemoEditor/hooks/index.ts b/web/src/components/MemoEditor/hooks/index.tsindex 5854dfd1d..6c2078500 100644--- a/web/src/components/MemoEditor/hooks/index.ts+++ b/web/src/components/MemoEditor/hooks/index.ts@@ -1,9 +1,12 @@// Custom hooks for MemoEditor (internal use only)+export { useAudioRecorder } from "./useAudioRecorder";export { useAudioWaveform } from "./useAudioWaveform";export { useAutoSave } from "./useAutoSave";export { useBlobUrls } from "./useBlobUrls";export { useDragAndDrop } from "./useDragAndDrop";+export { type ActiveMarks, useEditorActiveState } from "./useEditorActiveState";+export { COMPACT_TOOLBAR_WIDTH, isCompactWidth, useElementWidth } from "./useElementWidth";export { useFileUpload } from "./useFileUpload";export { useFocusMode } from "./useFocusMode";export { useKeyboard } from "./useKeyboard";diff --git a/web/src/components/MemoEditor/hooks/useEditorActiveState.ts b/web/src/components/MemoEditor/hooks/useEditorActiveState.tsnew file mode 100644index 000000000..9e32204ff--- /dev/null+++ b/web/src/components/MemoEditor/hooks/useEditorActiveState.ts@@ -0,0 +1,78 @@+import { type RefObject, useEffect, useState } from "react";+import type { EditorController, FormattingController, ToolbarHeadingLevel } from "../types/editorController";++export interface ActiveMarks {+ bold: boolean;+ italic: boolean;+ code: boolean;+ bulletList: boolean;+ orderedList: boolean;+ taskList: boolean;+ link: boolean;+ headingLevel: ToolbarHeadingLevel | null;+}++const EMPTY_ACTIVE: ActiveMarks = {+ bold: false,+ italic: false,+ code: false,+ bulletList: false,+ orderedList: false,+ taskList: false,+ link: false,+ headingLevel: null,+};++const HEADING_LEVELS: ToolbarHeadingLevel[] = [1, 2, 3];++function sameActiveMarks(a: ActiveMarks, b: ActiveMarks): boolean {+ return (+ a.bold === b.bold &&+ a.italic === b.italic &&+ a.code === b.code &&+ a.bulletList === b.bulletList &&+ a.orderedList === b.orderedList &&+ a.taskList === b.taskList &&+ a.link === b.link &&+ a.headingLevel === b.headingLevel+ );+}++function readActiveMarks(controller: FormattingController): ActiveMarks {+ const headingLevel = HEADING_LEVELS.find((level) => controller.isActive("heading", { level })) ?? null;+ return {+ bold: controller.isActive("bold"),+ italic: controller.isActive("italic"),+ code: controller.isActive("code"),+ bulletList: controller.isActive("bulletList"),+ orderedList: controller.isActive("orderedList"),+ taskList: controller.isActive("taskList"),+ link: controller.isActive("link"),+ headingLevel,+ };+}++/**+ * Subscribes to the editor controller and recomputes which marks/nodes are+ * active whenever the selection or document changes, so toolbar buttons can+ * highlight live. Returns the empty map until a controller is available.+ */+export function useEditorActiveState(controllerRef: RefObject<(EditorController & FormattingController) | null>): ActiveMarks {+ const [active, setActive] = useState<ActiveMarks>(EMPTY_ACTIVE);+ useEffect(() => {+ const controller = controllerRef.current;+ if (!controller) {+ return;+ }+ // Fires on every transaction; keep the previous object identity when the+ // derived map is unchanged (the common case while typing) so React skips+ // the toolbar re-render.+ const recompute = () => {+ const next = readActiveMarks(controller);+ setActive((prev) => (sameActiveMarks(prev, next) ? prev : next));+ };+ recompute();+ return controller.subscribe(recompute);+ }, [controllerRef]);+ return active;+}diff --git a/web/src/components/MemoEditor/hooks/useElementWidth.ts b/web/src/components/MemoEditor/hooks/useElementWidth.tsnew file mode 100644index 000000000..fc6135389--- /dev/null+++ b/web/src/components/MemoEditor/hooks/useElementWidth.ts@@ -0,0 +1,31 @@+import { type RefObject, useEffect, useState } from "react";++/** Below this content width (px) the formatting toolbar uses its compact layout. */+export const COMPACT_TOOLBAR_WIDTH = 380;++/** Pure decision so it can be unit-tested without a DOM. Width 0 = unmeasured. */+export function isCompactWidth(width: number): boolean {+ return width > 0 && width < COMPACT_TOOLBAR_WIDTH;+}++/**+ * Tracks an element's content-box width via ResizeObserver. Returns 0 until the+ * first measurement (or when ResizeObserver is unavailable, e.g. jsdom), which+ * isCompactWidth() treats as the full (non-compact) layout.+ */+export function useElementWidth<T extends HTMLElement>(ref: RefObject<T | null>): number {+ const [width, setWidth] = useState(0);+ useEffect(() => {+ const element = ref.current;+ if (!element || typeof ResizeObserver === "undefined") {+ return;+ }+ const observer = new ResizeObserver((entries) => {+ setWidth(entries[0].contentRect.width);+ });+ observer.observe(element);+ setWidth(element.getBoundingClientRect().width);+ return () => observer.disconnect();+ }, [ref]);+ return width;+}diff --git a/web/src/components/MemoEditor/index.tsx b/web/src/components/MemoEditor/index.tsxindex 0ace54767..c2c59d036 100644--- a/web/src/components/MemoEditor/index.tsx+++ b/web/src/components/MemoEditor/index.tsx@@ -18,6 +18,7 @@ import {EditorToolbar,FocusModeExitButton,FocusModeOverlay,+ FormattingToolbar,TimestampPopover,} from "./components";import { FOCUS_MODE_STYLES } from "./constants";@@ -26,7 +27,7 @@ import { errorService, memoService, transcriptionService, validationService } frimport { EditorProvider, useEditorContext } from "./state";import type { MemoEditorProps } from "./types";import type { LocalFile } from "./types/attachment";-import type { EditorController } from "./types/editorController";+import type { EditorController, FormattingController } from "./types/editorController";const MemoEditor = (props: MemoEditorProps) => (<EditorProvider>@@ -48,7 +49,7 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({const t = useTranslate();const queryClient = useQueryClient();const currentUser = useCurrentUser();- const editorRef = useRef<EditorController>(null);+ const editorRef = useRef<EditorController & FormattingController>(null);const { state, actions, dispatch } = useEditorContext();const { userGeneralSetting } = useAuth();const { aiSetting, fetchSetting } = useInstance();@@ -309,8 +310,14 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({className,)}>- {/* Exit button is absolutely positioned in top-right corner when active */}- <FocusModeExitButton isActive={state.ui.isFocusMode} onToggle={handleToggleFocusMode} title={t("editor.exit-focus-mode")} />+ {/* Focus-mode header. WYSIWYG gets the formatting toolbar (exit lives in+ it); raw mode falls back to the floating exit button. */}+ {state.ui.isFocusMode &&+ (state.ui.editorMode === "wysiwyg" ? (+ <FormattingToolbar controllerRef={editorRef} onExit={handleToggleFocusMode} className={FOCUS_MODE_STYLES.formattingHeader} />+ ) : (+ <FocusModeExitButton isActive onToggle={handleToggleFocusMode} title={t("editor.exit-focus-mode")} />+ ))}{(memoName || (!memo && state.timestamps.createTime)) && (<div className="w-full -mb-1">diff --git a/web/src/components/MemoEditor/types/editorController.ts b/web/src/components/MemoEditor/types/editorController.tsindex 9b591a3c6..c371dc7e8 100644--- a/web/src/components/MemoEditor/types/editorController.ts+++ b/web/src/components/MemoEditor/types/editorController.ts@@ -22,3 +22,38 @@ export interface EditorController {toggleItalic(): void;toggleTaskList(): void;}++/** Heading levels surfaced in the formatting toolbar's heading dropdown. */+export type ToolbarHeadingLevel = 1 | 2 | 3;++/**+ * Rich-formatting surface used by the focus-mode FormattingToolbar. Additive to+ * EditorController and implemented only by the WYSIWYG editor — the toolbar is+ * never shown for the raw editor, so EditorContent routes these to the WYSIWYG+ * handle and returns inert defaults in raw mode.+ *+ * isActive / subscribe are the sanctioned (and only) place ProseMirror state+ * leaks across the editor boundary, so toolbar buttons can reflect live state.+ */+export interface FormattingController {+ // toggleBold / toggleItalic / toggleTaskList come from EditorController — the+ // toolbar always consumes `EditorController & FormattingController`.+ toggleCode(): void;+ toggleBulletList(): void;+ toggleOrderedList(): void;+ /** Set the current block to a heading of the given level. */+ setHeading(level: ToolbarHeadingLevel): void;+ /** Set the current block back to a paragraph. */+ setParagraph(): void;+ /**+ * Toggle a link. When a link is active it is removed; otherwise the given URL+ * is applied to the current selection/word. No-ops when adding without a URL.+ */+ toggleLink(url?: string): void;+ /** Plain text of the current selection ("" when the selection is empty). */+ getSelectedText(): string;+ /** Whether a mark/node (optionally with attrs) is active at the selection. */+ isActive(name: string, attrs?: Record<string, unknown>): boolean;+ /** Register a listener fired on every editor transaction/selection change. Returns an unsubscribe. */+ subscribe(listener: () => void): () => void;+}diff --git a/web/src/locales/ar.json b/web/src/locales/ar.jsonindex bc707c091..47947c440 100644--- a/web/src/locales/ar.json+++ b/web/src/locales/ar.json@@ -127,7 +127,6 @@"no-changes-detected": "لم يتم الكشف عن تغييرات","save": "حفظ","saving": "جارِ الحفظ...",- "slash-commands": "اكتب `/` للأوامر","insert-menu": {"add-location": "أضف الموقع","link-memo": "مذكرة الارتباط",diff --git a/web/src/locales/bg.json b/web/src/locales/bg.jsonindex cbc9b6c07..bd80316cb 100644--- a/web/src/locales/bg.json+++ b/web/src/locales/bg.json@@ -172,7 +172,6 @@"no-changes-detected": "Не са открити промени","save": "Запазване","saving": "Запазва се...",- "slash-commands": "Въведете `/` за команди","audio-recorder": {"attachment-label": "Аудио запис","attachment-label-with-time": "Аудио запис {{time}}",diff --git a/web/src/locales/ca.json b/web/src/locales/ca.jsonindex e69bdf921..e5ee0c417 100644--- a/web/src/locales/ca.json+++ b/web/src/locales/ca.json@@ -135,7 +135,6 @@"no-changes-detected": "No s'han detectat canvis","save": "Guarda","saving": "Guardant...",- "slash-commands": "Escriu `/` per a comandaments","audio-recorder": {"attachment-label": "Gravació d'àudio","attachment-label-with-time": "Gravació d'àudio {{time}}",diff --git a/web/src/locales/cs.json b/web/src/locales/cs.jsonindex 925c7f909..a9decef1a 100644--- a/web/src/locales/cs.json+++ b/web/src/locales/cs.json@@ -135,7 +135,6 @@"no-changes-detected": "Nebyly zjištěny žádné změny","save": "Uložit","saving": "Ukládání...",- "slash-commands": "Pro příkazy zadejte `/`","audio-recorder": {"attachment-label": "Záznam zvuku","attachment-label-with-time": "Záznam zvuku {{time}}",diff --git a/web/src/locales/da.json b/web/src/locales/da.jsonindex 505bc6bb7..4fe18e595 100644--- a/web/src/locales/da.json+++ b/web/src/locales/da.json@@ -172,7 +172,6 @@"no-changes-detected": "Ingen ændringer registreret","save": "Spare","saving": "Gemmer...",- "slash-commands": "Skriv `/` for kommandoer","audio-recorder": {"attachment-label": "Lydoptagelse","attachment-label-with-time": "Lydoptagelse {{time}}",diff --git a/web/src/locales/de.json b/web/src/locales/de.jsonindex bca72e3c4..c8f427b38 100644--- a/web/src/locales/de.json+++ b/web/src/locales/de.json@@ -135,7 +135,6 @@"no-changes-detected": "Keine Änderungen erkannt","save": "Speichern","saving": "Speichern...",- "slash-commands": "Nutze `/` für Befehle","audio-recorder": {"attachment-label": "Audioaufnahme","attachment-label-with-time": "Audioaufnahme {{time}}",diff --git a/web/src/locales/el.json b/web/src/locales/el.jsonindex cca1890f9..0cc8d9443 100644--- a/web/src/locales/el.json+++ b/web/src/locales/el.json@@ -172,7 +172,6 @@"no-changes-detected": "Δεν εντοπίστηκαν αλλαγές","save": "Εκτός","saving": "Οικονομία...",- "slash-commands": "Πληκτρολογήστε `/` για εντολές","audio-recorder": {"attachment-label": "Ηχογράφηση","attachment-label-with-time": "Εγγραφή ήχου {{time}}",diff --git a/web/src/locales/en-GB.json b/web/src/locales/en-GB.jsonindex a8f2e498d..15efbd303 100644--- a/web/src/locales/en-GB.json+++ b/web/src/locales/en-GB.json@@ -135,7 +135,6 @@"no-changes-detected": "No changes detected","save": "Save","saving": "Saving...",- "slash-commands": "Type `/` for commands","audio-recorder": {"attachment-label": "Audio recording","attachment-label-with-time": "Audio recording {{time}}",diff --git a/web/src/locales/en.json b/web/src/locales/en.jsonindex ae4619cd6..3a5ad4eba 100644--- a/web/src/locales/en.json+++ b/web/src/locales/en.json@@ -164,6 +164,22 @@"any-thoughts": "Any thoughts...","exit-focus-mode": "Exit Focus Mode","focus-mode": "Focus Mode",+ "format": {+ "heading": "Heading",+ "paragraph": "Paragraph",+ "heading-1": "Heading 1",+ "heading-2": "Heading 2",+ "heading-3": "Heading 3",+ "bold": "Bold",+ "italic": "Italic",+ "code": "Inline code",+ "bullet-list": "Bullet list",+ "ordered-list": "Numbered list",+ "task-list": "To-do list",+ "link": "Link",+ "link-prompt": "Enter a URL",+ "more": "More formatting"+ },"insert-menu": {"add-location": "Add location","link-memo": "Link memo",@@ -172,7 +188,6 @@"no-changes-detected": "No changes detected","save": "Save","saving": "Saving...",- "slash-commands": "Type `/` for commands","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": {diff --git a/web/src/locales/es.json b/web/src/locales/es.jsonindex 4c103117e..b1c4c1943 100644--- a/web/src/locales/es.json+++ b/web/src/locales/es.json@@ -135,7 +135,6 @@"no-changes-detected": "No se detectaron cambios","save": "Guardar","saving": "Guardando...",- "slash-commands": "Escribe `/` para comandos","audio-recorder": {"attachment-label": "Grabación de audio","attachment-label-with-time": "Grabación de audio {{time}}",diff --git a/web/src/locales/et.json b/web/src/locales/et.jsonindex 0b3db07e0..36f1e4b8a 100644--- a/web/src/locales/et.json+++ b/web/src/locales/et.json@@ -172,7 +172,6 @@"no-changes-detected": "Muudatusi ei tuvastatud","save": "Salvesta","saving": "Salvestamine...",- "slash-commands": "Käskude jaoks tippige `/`","audio-recorder": {"attachment-label": "Helisalvestus","attachment-label-with-time": "Helisalvestus {{time}}",diff --git a/web/src/locales/fa.json b/web/src/locales/fa.jsonindex 8bf41f752..b5f361d37 100644--- a/web/src/locales/fa.json+++ b/web/src/locales/fa.json@@ -127,7 +127,6 @@"no-changes-detected": "تغییری شناسایی نشد","save": "ذخیره","saving": "در حال ذخیره...",- "slash-commands": "برای دستورات '/' را تایپ کنید","insert-menu": {"add-location": "اضافه کردن مکان","link-memo": "پیوند یادداشت",diff --git a/web/src/locales/fi.json b/web/src/locales/fi.jsonindex 20d21e585..42e277270 100644--- a/web/src/locales/fi.json+++ b/web/src/locales/fi.json@@ -172,7 +172,6 @@"no-changes-detected": "Muutoksia ei havaittu","save": "Tallentaa","saving": "Tallennetaan...",- "slash-commands": "Kirjoita komentoja varten `/`","audio-recorder": {"attachment-label": "Äänen tallennus","attachment-label-with-time": "Äänen tallennus {{time}}",diff --git a/web/src/locales/fr.json b/web/src/locales/fr.jsonindex 218c7422e..c33b73461 100644--- a/web/src/locales/fr.json+++ b/web/src/locales/fr.json@@ -135,7 +135,6 @@"no-changes-detected": "Aucun changement détecté","save": "Enregistrer","saving": "Enregistrement...",- "slash-commands": "Tapez `/` pour les commandes","audio-recorder": {"attachment-label": "Enregistrement audio","attachment-label-with-time": "Enregistrement audio {{time}}",diff --git a/web/src/locales/gl.json b/web/src/locales/gl.jsonindex 3de258ed4..dfa7caeaa 100644--- a/web/src/locales/gl.json+++ b/web/src/locales/gl.json@@ -135,7 +135,6 @@"no-changes-detected": "Non se detectaron cambios","save": "Gardar","saving": "Gardando...",- "slash-commands": "Escribe `/` para ordes","audio-recorder": {"attachment-label": "Gravación de audio","attachment-label-with-time": "Gravación de audio {{time}}",diff --git a/web/src/locales/hi.json b/web/src/locales/hi.jsonindex 309b4c56d..03385cb24 100644--- a/web/src/locales/hi.json+++ b/web/src/locales/hi.json@@ -127,7 +127,6 @@"no-changes-detected": "कोई बदलाव नहीं पाया गया","save": "सहेजें","saving": "सहेज रहा है...",- "slash-commands": "कमांड के लिए `/` टाइप करें","insert-menu": {"add-location": "स्थान जोड़ें","link-memo": "लिंक मेमो",diff --git a/web/src/locales/hr.json b/web/src/locales/hr.jsonindex 575487a99..7a6f7cc56 100644--- a/web/src/locales/hr.json+++ b/web/src/locales/hr.json@@ -135,7 +135,6 @@"no-changes-detected": "Nema promjena","save": "Sačuvaj","saving": "Spremanje...",- "slash-commands": "Upisi `/` za naredbe","audio-recorder": {"attachment-label": "Audio snimanje","attachment-label-with-time": "Audio snimak {{time}}",diff --git a/web/src/locales/hu.json b/web/src/locales/hu.jsonindex f0a4b415c..e9811c091 100644--- a/web/src/locales/hu.json+++ b/web/src/locales/hu.json@@ -135,7 +135,6 @@"no-changes-detected": "Nincs változás","save": "Mentés","saving": "Mentés...",- "slash-commands": "Írj `/` parancsokat","audio-recorder": {"attachment-label": "Hangfelvétel","attachment-label-with-time": "Hangfelvétel {{time}}",diff --git a/web/src/locales/id.json b/web/src/locales/id.jsonindex 6f518be4d..ab4f40269 100644--- a/web/src/locales/id.json+++ b/web/src/locales/id.json@@ -127,7 +127,6 @@"no-changes-detected": "Tidak ada perubahan yang terdeteksi","save": "Simpan","saving": "Menyimpan...",- "slash-commands": "Ketik `/` untuk perintah","insert-menu": {"add-location": "Tambahkan lokasi","link-memo": "Tautan memo",diff --git a/web/src/locales/it.json b/web/src/locales/it.jsonindex 034aae949..4eb2acfc2 100644--- a/web/src/locales/it.json+++ b/web/src/locales/it.json@@ -135,7 +135,6 @@"no-changes-detected": "Nessuna modifica rilevata","save": "Salva","saving": "Salvataggio...",- "slash-commands": "Digita `/` per i comandi","audio-recorder": {"attachment-label": "Registrazione audio","attachment-label-with-time": "Registrazione audio {{time}}",diff --git a/web/src/locales/ja.json b/web/src/locales/ja.jsonindex ee391bd96..ee4b80d00 100644--- a/web/src/locales/ja.json+++ b/web/src/locales/ja.json@@ -130,7 +130,6 @@"no-changes-detected": "変更はありません","save": "保存","saving": "保存中...",- "slash-commands": "コマンドを入力するには `/` を入力","insert-menu": {"add-location": "場所を追加","link-memo": "リンクメモ",diff --git a/web/src/locales/ka-GE.json b/web/src/locales/ka-GE.jsonindex 9c472aca1..3a92e1828 100644--- a/web/src/locales/ka-GE.json+++ b/web/src/locales/ka-GE.json@@ -135,7 +135,6 @@"no-changes-detected": "ცვლილებები არ აღმოჩენილა","save": "შენახვა","saving": "შენახვა...",- "slash-commands": "შეიყვანეთ `/` ბრძანებებისთვის","audio-recorder": {"attachment-label": "აუდიო ჩანაწერი","attachment-label-with-time": "აუდიო ჩანაწერი {{time}}",diff --git a/web/src/locales/ko.json b/web/src/locales/ko.jsonindex 5818a94b6..ec90894fb 100644--- a/web/src/locales/ko.json+++ b/web/src/locales/ko.json@@ -127,7 +127,6 @@"no-changes-detected": "변경사항이 없습니다","save": "저장","saving": "저장 중...",- "slash-commands": "명령어를 보시려면 /를 입력하세요.","insert-menu": {"add-location": "위치 추가","link-memo": "링크 메모",diff --git a/web/src/locales/lt.json b/web/src/locales/lt.jsonindex c0e8ff3ab..07868f947 100644--- a/web/src/locales/lt.json+++ b/web/src/locales/lt.json@@ -172,7 +172,6 @@"no-changes-detected": "Pakeitimų neaptikta","save": "Išsaugoti","saving": "Išsaugoma...",- "slash-commands": "Įveskite `/` komandoms","audio-recorder": {"attachment-label": "Garso įrašymas","attachment-label-with-time": "Garso įrašymas {{time}}",diff --git a/web/src/locales/lv.json b/web/src/locales/lv.jsonindex 23ac6889d..c6da87160 100644--- a/web/src/locales/lv.json+++ b/web/src/locales/lv.json@@ -172,7 +172,6 @@"no-changes-detected": "Izmaiņas nav konstatētas","save": "Saglabāt","saving": "Notiek saglabāšana...",- "slash-commands": "Komandām ierakstiet `/`","audio-recorder": {"attachment-label": "Audio ieraksts","attachment-label-with-time": "Audio ieraksts {{time}}",diff --git a/web/src/locales/mr.json b/web/src/locales/mr.jsonindex f3507f3a0..b37482308 100644--- a/web/src/locales/mr.json+++ b/web/src/locales/mr.json@@ -127,7 +127,6 @@"no-changes-detected": "कोणतेही बदल आढळले नाहीत","save": "जतन","saving": "जतन होत आहे...",- "slash-commands": "कमांडसाठी `/` टाइप करा","insert-menu": {"add-location": "स्थान जोडा","link-memo": "लिंक मेमो",diff --git a/web/src/locales/nb.json b/web/src/locales/nb.jsonindex c1c70d733..4a38bba68 100644--- a/web/src/locales/nb.json+++ b/web/src/locales/nb.json@@ -135,7 +135,6 @@"no-changes-detected": "Ingen endringer oppdaget","save": "Lagre","saving": "Lagrer...",- "slash-commands": "Skriv `/` for kommandoer","audio-recorder": {"attachment-label": "Lydopptak","attachment-label-with-time": "Lydopptak {{time}}",diff --git a/web/src/locales/nl.json b/web/src/locales/nl.jsonindex 03f822f64..e42d5a508 100644--- a/web/src/locales/nl.json+++ b/web/src/locales/nl.json@@ -135,7 +135,6 @@"no-changes-detected": "Geen wijzigingen gedetecteerd","save": "Opslaan","saving": "Opslaan...",- "slash-commands": "Typ `/` voor opdrachten","audio-recorder": {"attachment-label": "Audio-opname","attachment-label-with-time": "Audio-opname {{time}}",diff --git a/web/src/locales/pl.json b/web/src/locales/pl.jsonindex b524f80d2..91f3db5ee 100644--- a/web/src/locales/pl.json+++ b/web/src/locales/pl.json@@ -135,7 +135,6 @@"no-changes-detected": "Brak wykrytych zmian","save": "Zapisz","saving": "Zapisywanie...",- "slash-commands": "Wciśnij `/` aby wydawać komendy","audio-recorder": {"attachment-label": "Nagrywanie dźwięku","attachment-label-with-time": "Nagranie dźwięku {{time}}",diff --git a/web/src/locales/pt-BR.json b/web/src/locales/pt-BR.jsonindex b4a4c247a..d44d7349e 100644--- a/web/src/locales/pt-BR.json+++ b/web/src/locales/pt-BR.json@@ -127,7 +127,6 @@"no-changes-detected": "Nenhuma alteração detectada","save": "Salvar","saving": "Salvando…",- "slash-commands": "Digite `/` para comandos","insert-menu": {"add-location": "Adicionar local","link-memo": "Vincular memorando",diff --git a/web/src/locales/pt-PT.json b/web/src/locales/pt-PT.jsonindex 4a7ba8906..284d1e96a 100644--- a/web/src/locales/pt-PT.json+++ b/web/src/locales/pt-PT.json@@ -135,7 +135,6 @@"no-changes-detected": "Nenhuma alteração detetada","save": "Guardar","saving": "A guardar...",- "slash-commands": "Digite `/` para comandos","audio-recorder": {"attachment-label": "Gravação de áudio","attachment-label-with-time": "Gravação de áudio {{time}}",diff --git a/web/src/locales/ro.json b/web/src/locales/ro.jsonindex a3ec6086e..cd1c6f6eb 100644--- a/web/src/locales/ro.json+++ b/web/src/locales/ro.json@@ -172,7 +172,6 @@"no-changes-detected": "Nu au fost detectate modificări","save": "Salva","saving": "Economisire...",- "slash-commands": "Tastați `/` pentru comenzi","audio-recorder": {"attachment-label": "Înregistrare audio","attachment-label-with-time": "Înregistrare audio {{time}}",diff --git a/web/src/locales/ru.json b/web/src/locales/ru.jsonindex 02d9d3793..04935dba6 100644--- a/web/src/locales/ru.json+++ b/web/src/locales/ru.json@@ -135,7 +135,6 @@"no-changes-detected": "Изменений не обнаружено","save": "Сохранить","saving": "Сохранение...",- "slash-commands": "Введите `/` для команд","audio-recorder": {"attachment-label": "Аудиозапись","attachment-label-with-time": "Аудиозапись {{time}}",diff --git a/web/src/locales/sk.json b/web/src/locales/sk.jsonindex 72ec9fd6c..368009d53 100644--- a/web/src/locales/sk.json+++ b/web/src/locales/sk.json@@ -172,7 +172,6 @@"no-changes-detected": "Nezistili sa žiadne zmeny","save": "Uložiť","saving": "Ukladá sa...",- "slash-commands": "Pre príkazy zadajte `/`","audio-recorder": {"attachment-label": "Zvukový záznam","attachment-label-with-time": "Záznam zvuku {{time}}",diff --git a/web/src/locales/sl.json b/web/src/locales/sl.jsonindex 3caa38458..7c96aa569 100644--- a/web/src/locales/sl.json+++ b/web/src/locales/sl.json@@ -135,7 +135,6 @@"no-changes-detected": "Ni zaznanih sprememb","save": "Shrani","saving": "Shranjujem...",- "slash-commands": "Vnesi `/` za ukaze","audio-recorder": {"attachment-label": "Zvočni posnetek","attachment-label-with-time": "Zvočni posnetek {{time}}",diff --git a/web/src/locales/sr.json b/web/src/locales/sr.jsonindex 9011322b2..b7ab1ebe9 100644--- a/web/src/locales/sr.json+++ b/web/src/locales/sr.json@@ -172,7 +172,6 @@"no-changes-detected": "Нису откривене промене","save": "Сачувај","saving": "Чување...",- "slash-commands": "Унесите `/` за команде","audio-recorder": {"attachment-label": "Аудио снимак","attachment-label-with-time": "Аудио запис {{time}}",diff --git a/web/src/locales/sv.json b/web/src/locales/sv.jsonindex 00a7f2194..64f6ebe95 100644--- a/web/src/locales/sv.json+++ b/web/src/locales/sv.json@@ -135,7 +135,6 @@"no-changes-detected": "Inga ändringar upptäckta","save": "Spara","saving": "Sparar...",- "slash-commands": "Skriv `/` för kommandon","audio-recorder": {"attachment-label": "Ljudinspelning","attachment-label-with-time": "Ljudinspelning {{time}}",diff --git a/web/src/locales/th.json b/web/src/locales/th.jsonindex 409c11b24..b4dbb171e 100644--- a/web/src/locales/th.json+++ b/web/src/locales/th.json@@ -127,7 +127,6 @@"no-changes-detected": "ไม่มีการเปลี่ยนแปลง","save": "บันทึก","saving": "กำลังบันทึก...",- "slash-commands": "พิมพ์ `/` สำหรับคำสั่ง","insert-menu": {"add-location": "เพิ่มสถานที่","link-memo": "บันทึกการเชื่อมโยง",diff --git a/web/src/locales/tr.json b/web/src/locales/tr.jsonindex 95dc3f26d..a47c48616 100644--- a/web/src/locales/tr.json+++ b/web/src/locales/tr.json@@ -135,7 +135,6 @@"no-changes-detected": "Değişiklik yok","save": "Kaydet","saving": "Kaydediliyor...",- "slash-commands": "Komutlar için `/` yazın","audio-recorder": {"attachment-label": "Ses kaydı","attachment-label-with-time": "Ses kaydı {{time}}",diff --git a/web/src/locales/uk.json b/web/src/locales/uk.jsonindex 445553475..bfaeaa843 100644--- a/web/src/locales/uk.json+++ b/web/src/locales/uk.json@@ -135,7 +135,6 @@"no-changes-detected": "Змін не виявлено","save": "Зберегти","saving": "Збереження...",- "slash-commands": "Введіть `/` для команд","audio-recorder": {"attachment-label": "Аудіозапис","attachment-label-with-time": "Аудіозапис {{time}}",diff --git a/web/src/locales/vi.json b/web/src/locales/vi.jsonindex ced9b3b50..0e77a1aa7 100644--- a/web/src/locales/vi.json+++ b/web/src/locales/vi.json@@ -127,7 +127,6 @@"no-changes-detected": "Không phát hiện thay đổi","save": "Lưu","saving": "Đang lưu...",- "slash-commands": "Nhập `/` để sử dụng lệnh","insert-menu": {"add-location": "Thêm vị trí","link-memo": "Liên kết bản ghi nhớ",diff --git a/web/src/locales/zh-Hans.json b/web/src/locales/zh-Hans.jsonindex 91a13804f..8b15fe33a 100644--- a/web/src/locales/zh-Hans.json+++ b/web/src/locales/zh-Hans.json@@ -135,7 +135,6 @@"no-changes-detected": "未检测到更改","save": "保存","saving": "保存中...",- "slash-commands": "按下 `/` 输入命令","insert-menu": {"add-location": "添加位置","link-memo": "链接备忘录",diff --git a/web/src/locales/zh-Hant.json b/web/src/locales/zh-Hant.jsonindex bc3eaaa3d..4279287ed 100644--- a/web/src/locales/zh-Hant.json+++ b/web/src/locales/zh-Hant.json@@ -172,7 +172,6 @@"no-changes-detected": "未發現變更","save": "儲存","saving": "儲存中...",- "slash-commands": "輸入 `/` 以使用指令","audio-recorder": {"attachment-label": "錄音","attachment-label-with-time": "錄音 {{time}}",diff --git a/web/tests/editor-slash-commands.test.ts b/web/tests/editor-slash-commands.test.tsdeleted file mode 100644index 0c8ddd4f6..000000000--- a/web/tests/editor-slash-commands.test.ts+++ /dev/null@@ -1,80 +0,0 @@-import { Editor } from "@tiptap/core";-import { afterEach, describe, expect, it } from "vitest";-import { buildExtensions } from "@/components/MemoEditor/Editor/extensions";-import { filterSlashCommands, slashCommandItems } from "@/components/MemoEditor/Editor/SlashCommand";--let editor: Editor;--function applyCommand(name: string, content = "") {- editor = new Editor({ extensions: buildExtensions(), content, contentType: "markdown" });- const item = slashCommandItems.find((candidate) => candidate.name === name);- if (!item) throw new Error(`unknown slash command: ${name}`);- // Simulate a trigger at the end of an empty paragraph (the only case this- // range math is correct for). After inserting "/" into an empty paragraph,- // the doc is doc(paragraph(text"/")), with the slash at positions 1..2- // (doc.content.size = 3). We replicate that range so deleteRange removes the- // trigger character exactly as the real Suggestion plugin would.- editor.commands.insertContent("/");- const end = editor.state.doc.content.size;- item.apply(editor, { from: end - 2, to: end - 1 });- return editor.getMarkdown();-}--afterEach(() => editor?.destroy());--describe("WYSIWYG slash commands", () => {- it("todo converts the block into a task list", () => {- expect(applyCommand("todo").trimEnd()).toBe("- [ ]");- });-- it("code converts the block into a code block", () => {- expect(applyCommand("code")).toContain("```");- });-- it("link inserts a markdown link", () => {- expect(applyCommand("link")).toContain("[text](url)");- });-- it("link places cursor selecting the display text", () => {- // After deleteRange(from:1, to:2) + insertContent the marked text node- // "text" occupies positions 1..5 (range.from=1, text length=4).- // The command chains .setTextSelection({ from: 1, to: 5 }) so the user- // can immediately overtype the placeholder label.- applyCommand("link");- const sel = editor.state.selection;- expect(sel.from).toBe(1);- expect(sel.to).toBe(5);- });-- it("table inserts a preserved markdown table", () => {- const markdown = applyCommand("table");- expect(markdown).toContain("| Header | Header |");- expect(markdown).toContain("| ------ | ------ |");- });-- it("table places cursor at the first header cell", () => {- // The preservedBlock text starts at range.from (pos 1). "| Header …" has- // "| " (2 chars) before the first label, so the command chains- // .setTextSelection(range.from + 2) = position 3, landing on the "H".- applyCommand("table");- const sel = editor.state.selection;- expect(sel.from).toBe(3);- expect(sel.to).toBe(3);- });-});--describe("filterSlashCommands", () => {- it("returns all items for an empty query", () => {- expect(filterSlashCommands("").map((i) => i.name)).toEqual(["todo", "code", "link", "table"]);- });-- it("filters items by case-insensitive prefix", () => {- expect(filterSlashCommands("t").map((i) => i.name)).toEqual(["todo", "table"]);- expect(filterSlashCommands("T").map((i) => i.name)).toEqual(["todo", "table"]);- expect(filterSlashCommands("c").map((i) => i.name)).toEqual(["code"]);- });-- it("returns an empty array for a non-matching query", () => {- expect(filterSlashCommands("x")).toEqual([]);- });-});diff --git a/web/tests/formatting-controller.test.tsx b/web/tests/formatting-controller.test.tsxnew file mode 100644index 000000000..fda4b1937--- /dev/null+++ b/web/tests/formatting-controller.test.tsx@@ -0,0 +1,93 @@+import { act, render } from "@testing-library/react";+import { createRef } from "react";+import { describe, expect, it, vi } from "vitest";+import Editor from "@/components/MemoEditor/Editor";+import type { EditorController, FormattingController } from "@/components/MemoEditor/types/editorController";++vi.mock("@/hooks/useUserQueries", async (importOriginal) => ({+ ...(await importOriginal<object>()),+ useTagCounts: () => ({ data: {} }),+}));++type Handle = EditorController & FormattingController;++function setup(initialContent = "") {+ const ref = createRef<Handle>();+ render(<Editor ref={ref} initialContent={initialContent} placeholder="memo" onContentChange={vi.fn()} onPaste={vi.fn()} />);+ return ref;+}++describe("FormattingController (WYSIWYG)", () => {+ it("toggleCode wraps the selection in inline code", () => {+ const ref = setup("code me");+ act(() => ref.current?.selectAll());+ act(() => ref.current?.toggleCode());+ expect(ref.current?.getMarkdown()).toBe("`code me`");+ });++ it("toggleBulletList converts the current block", () => {+ const ref = setup("item");+ act(() => ref.current?.toggleBulletList());+ expect(ref.current?.getMarkdown()).toBe("- item");+ });++ it("toggleOrderedList converts the current block", () => {+ const ref = setup("item");+ act(() => ref.current?.toggleOrderedList());+ expect(ref.current?.getMarkdown()).toBe("1. item");+ });++ it("setHeading makes the block a heading and isActive reflects the level", () => {+ const ref = setup("title");+ act(() => ref.current?.setHeading(2));+ expect(ref.current?.getMarkdown()).toBe("## title");+ expect(ref.current?.isActive("heading", { level: 2 })).toBe(true);+ expect(ref.current?.isActive("heading", { level: 1 })).toBe(false);+ });++ it("setParagraph reverts a heading", () => {+ const ref = setup("# title");+ act(() => ref.current?.setParagraph());+ expect(ref.current?.getMarkdown()).toBe("title");+ });++ it("isActive('bold') tracks the bold mark", () => {+ const ref = setup("x");+ expect(ref.current?.isActive("bold")).toBe(false);+ act(() => ref.current?.selectAll());+ act(() => ref.current?.toggleBold());+ expect(ref.current?.isActive("bold")).toBe(true);+ });++ it("toggleLink applies a link over the selection, and removes it when active", () => {+ const ref = setup("memos");+ act(() => ref.current?.selectAll());+ act(() => ref.current?.toggleLink("https://usememos.com"));+ expect(ref.current?.getMarkdown()).toBe("[memos](https://usememos.com)");+ act(() => ref.current?.selectAll());+ act(() => ref.current?.toggleLink());+ expect(ref.current?.getMarkdown()).toBe("memos");+ });++ it("getSelectedText returns the current selection text", () => {+ const ref = setup("hello world");+ act(() => ref.current?.selectAll());+ expect(ref.current?.getSelectedText()).toBe("hello world");+ });++ it("subscribe fires on transactions and unsubscribe stops it", () => {+ const ref = setup("x");+ const listener = vi.fn();+ let unsubscribe = () => {};+ act(() => {+ unsubscribe = ref.current!.subscribe(listener);+ });+ act(() => ref.current?.selectAll());+ act(() => ref.current?.toggleBold());+ const callsWhileSubscribed = listener.mock.calls.length;+ expect(callsWhileSubscribed).toBeGreaterThan(0);+ act(() => unsubscribe());+ act(() => ref.current?.toggleItalic());+ expect(listener.mock.calls.length).toBe(callsWhileSubscribed);+ });+});diff --git a/web/tests/formatting-toolbar.test.tsx b/web/tests/formatting-toolbar.test.tsxnew file mode 100644index 000000000..a29191752--- /dev/null+++ b/web/tests/formatting-toolbar.test.tsx@@ -0,0 +1,104 @@+import { fireEvent, render, screen } from "@testing-library/react";+import { createRef } from "react";+import { beforeAll, describe, expect, it, vi } from "vitest";+import { FormattingToolbar } from "@/components/MemoEditor/components/FormattingToolbar";+import type { EditorController, FormattingController } from "@/components/MemoEditor/types/editorController";++// Match the repo convention: t echoes the i18n key (no i18next backend in tests),+// so accessible names below are the keys themselves.+vi.mock("@/utils/i18n", () => ({ useTranslate: () => (key: string) => key }));++// Radix DropdownMenu reaches for layout/pointer APIs jsdom doesn't implement.+beforeAll(() => {+ Element.prototype.scrollIntoView = vi.fn();+ Element.prototype.hasPointerCapture = vi.fn(() => false);+ Element.prototype.setPointerCapture = vi.fn();+ Element.prototype.releasePointerCapture = vi.fn();+});++type Handle = EditorController & FormattingController;++function makeController(overrides: Partial<Handle> = {}): Handle {+ const noop = () => {};+ return {+ focus: noop,+ hasFocus: () => false,+ isEmpty: () => true,+ getMarkdown: () => "",+ setMarkdown: noop,+ insertMarkdown: noop,+ scrollToCursor: noop,+ selectAll: noop,+ toggleBold: vi.fn(),+ toggleItalic: vi.fn(),+ toggleTaskList: vi.fn(),+ toggleCode: vi.fn(),+ toggleBulletList: vi.fn(),+ toggleOrderedList: vi.fn(),+ setHeading: vi.fn(),+ setParagraph: vi.fn(),+ toggleLink: vi.fn(),+ getSelectedText: () => "",+ isActive: () => false,+ subscribe: () => () => {},+ ...overrides,+ };+}++function renderToolbar(controller: Handle, onExit = vi.fn()) {+ const ref = createRef<Handle>();+ ref.current = controller;+ render(<FormattingToolbar controllerRef={ref} onExit={onExit} />);+ return { onExit };+}++describe("FormattingToolbar", () => {+ it("invokes toggleBold when the bold button is clicked", () => {+ const controller = makeController();+ renderToolbar(controller);+ fireEvent.click(screen.getByRole("button", { name: "editor.format.bold" }));+ expect(controller.toggleBold).toHaveBeenCalledTimes(1);+ });++ it("invokes setHeading when a heading level is chosen", () => {+ const controller = makeController();+ renderToolbar(controller);+ // Keyboard open is the most reliable path for Radix menus in jsdom.+ fireEvent.keyDown(screen.getByRole("button", { name: "editor.format.heading" }), { key: "Enter" });+ fireEvent.click(screen.getByRole("menuitem", { name: "editor.format.heading-2" }));+ expect(controller.setHeading).toHaveBeenCalledWith(2);+ });++ it("reflects active marks via aria-pressed", () => {+ const controller = makeController({ isActive: (name) => name === "bold" });+ renderToolbar(controller);+ expect(screen.getByRole("button", { name: "editor.format.bold" })).toHaveAttribute("aria-pressed", "true");+ expect(screen.getByRole("button", { name: "editor.format.italic" })).toHaveAttribute("aria-pressed", "false");+ });++ it("prompts for a URL and links the selection when adding a link", () => {+ const controller = makeController({ getSelectedText: () => "memos" });+ const promptSpy = vi.spyOn(window, "prompt").mockReturnValue("https://usememos.com");+ renderToolbar(controller);+ fireEvent.click(screen.getByRole("button", { name: "editor.format.link" }));+ expect(controller.toggleLink).toHaveBeenCalledWith("https://usememos.com");+ promptSpy.mockRestore();+ });++ it("removes an active link without prompting", () => {+ const controller = makeController({ isActive: (name) => name === "link" });+ const promptSpy = vi.spyOn(window, "prompt");+ renderToolbar(controller);+ fireEvent.click(screen.getByRole("button", { name: "editor.format.link" }));+ expect(promptSpy).not.toHaveBeenCalled();+ expect(controller.toggleLink).toHaveBeenCalledWith();+ promptSpy.mockRestore();+ });++ it("calls onExit when the exit button is clicked", () => {+ const controller = makeController();+ const { onExit } = renderToolbar(controller);+ fireEvent.click(screen.getByRole("button", { name: "editor.exit-focus-mode" }));+ expect(onExit).toHaveBeenCalledTimes(1);+ });+});diff --git a/web/tests/toolbar-compact-width.test.ts b/web/tests/toolbar-compact-width.test.tsnew file mode 100644index 000000000..13006f88b--- /dev/null+++ b/web/tests/toolbar-compact-width.test.ts@@ -0,0 +1,17 @@+import { describe, expect, it } from "vitest";+import { COMPACT_TOOLBAR_WIDTH, isCompactWidth } from "@/components/MemoEditor/hooks/useElementWidth";++describe("isCompactWidth", () => {+ it("treats an unmeasured (0) width as not compact (full layout default)", () => {+ expect(isCompactWidth(0)).toBe(false);+ });++ it("is compact below the threshold", () => {+ expect(isCompactWidth(COMPACT_TOOLBAR_WIDTH - 1)).toBe(true);+ });++ it("is not compact at or above the threshold", () => {+ expect(isCompactWidth(COMPACT_TOOLBAR_WIDTH)).toBe(false);+ expect(isCompactWidth(COMPACT_TOOLBAR_WIDTH + 200)).toBe(false);+ });+});