feat(editor): add focus-mode formatting toolbar

Add a rich-text formatting toolbar as the focus-mode header when the
WYSIWYG editor is active: heading dropdown, bold/italic/code, lists, and
link, with a priority+overflow responsive layout and live active-state
highlighting. The toolbar is a self-contained component driven through a
new FormattingController surface routed via EditorContent.

Remove the now-redundant slash-command feature (/todo, /code, /link,
/table) and its "Type / for commands" hint, since the toolbar covers
those actions; the shared suggestion renderer stays for #tag.
This commit is contained in:
johnnyjoygh 2026-06-21 11:57:45 +08:00
parent f727ad217c
commit deddf71d7b
60 changed files with 652 additions and 231 deletions

View file

@ -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,
),
}),
}),
];
},
});

View file

@ -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],
);

View file

@ -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

View file

@ -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>

View file

@ -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],
);

View file

@ -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>
);
}

View file

@ -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";

View file

@ -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 = {

View file

@ -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";

View file

@ -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;
}

View file

@ -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;
}

View file

@ -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 } fr
import { 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">

View file

@ -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;
}

View file

@ -127,7 +127,6 @@
"no-changes-detected": "لم يتم الكشف عن تغييرات",
"save": "حفظ",
"saving": "جارِ الحفظ...",
"slash-commands": "اكتب `/` للأوامر",
"insert-menu": {
"add-location": "أضف الموقع",
"link-memo": "مذكرة الارتباط",

View file

@ -172,7 +172,6 @@
"no-changes-detected": "Не са открити промени",
"save": "Запазване",
"saving": "Запазва се...",
"slash-commands": "Въведете `/` за команди",
"audio-recorder": {
"attachment-label": "Аудио запис",
"attachment-label-with-time": "Аудио запис {{time}}",

View file

@ -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}}",

View file

@ -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}}",

View file

@ -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}}",

View file

@ -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}}",

View file

@ -172,7 +172,6 @@
"no-changes-detected": "Δεν εντοπίστηκαν αλλαγές",
"save": "Εκτός",
"saving": "Οικονομία...",
"slash-commands": "Πληκτρολογήστε `/` για εντολές",
"audio-recorder": {
"attachment-label": "Ηχογράφηση",
"attachment-label-with-time": "Εγγραφή ήχου {{time}}",

View file

@ -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}}",

View file

@ -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": {

View file

@ -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}}",

View file

@ -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}}",

View file

@ -127,7 +127,6 @@
"no-changes-detected": "تغییری شناسایی نشد",
"save": "ذخیره",
"saving": "در حال ذخیره...",
"slash-commands": "برای دستورات '/' را تایپ کنید",
"insert-menu": {
"add-location": "اضافه کردن مکان",
"link-memo": "پیوند یادداشت",

View file

@ -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}}",

View file

@ -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}}",

View file

@ -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}}",

View file

@ -127,7 +127,6 @@
"no-changes-detected": "कोई बदलाव नहीं पाया गया",
"save": "सहेजें",
"saving": "सहेज रहा है...",
"slash-commands": "कमांड के लिए `/` टाइप करें",
"insert-menu": {
"add-location": "स्थान जोड़ें",
"link-memo": "लिंक मेमो",

View file

@ -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}}",

View file

@ -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}}",

View file

@ -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",

View file

@ -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}}",

View file

@ -130,7 +130,6 @@
"no-changes-detected": "変更はありません",
"save": "保存",
"saving": "保存中...",
"slash-commands": "コマンドを入力するには `/` を入力",
"insert-menu": {
"add-location": "場所を追加",
"link-memo": "リンクメモ",

View file

@ -135,7 +135,6 @@
"no-changes-detected": "ცვლილებები არ აღმოჩენილა",
"save": "შენახვა",
"saving": "შენახვა...",
"slash-commands": "შეიყვანეთ `/` ბრძანებებისთვის",
"audio-recorder": {
"attachment-label": "აუდიო ჩანაწერი",
"attachment-label-with-time": "აუდიო ჩანაწერი {{time}}",

View file

@ -127,7 +127,6 @@
"no-changes-detected": "변경사항이 없습니다",
"save": "저장",
"saving": "저장 중...",
"slash-commands": "명령어를 보시려면 /를 입력하세요.",
"insert-menu": {
"add-location": "위치 추가",
"link-memo": "링크 메모",

View file

@ -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}}",

View file

@ -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}}",

View file

@ -127,7 +127,6 @@
"no-changes-detected": "कोणतेही बदल आढळले नाहीत",
"save": "जतन",
"saving": "जतन होत आहे...",
"slash-commands": "कमांडसाठी `/` टाइप करा",
"insert-menu": {
"add-location": "स्थान जोडा",
"link-memo": "लिंक मेमो",

View file

@ -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}}",

View file

@ -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}}",

View file

@ -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}}",

View file

@ -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",

View file

@ -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}}",

View file

@ -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}}",

View file

@ -135,7 +135,6 @@
"no-changes-detected": "Изменений не обнаружено",
"save": "Сохранить",
"saving": "Сохранение...",
"slash-commands": "Введите `/` для команд",
"audio-recorder": {
"attachment-label": "Аудиозапись",
"attachment-label-with-time": "Аудиозапись {{time}}",

View file

@ -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}}",

View file

@ -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}}",

View file

@ -172,7 +172,6 @@
"no-changes-detected": "Нису откривене промене",
"save": "Сачувај",
"saving": "Чување...",
"slash-commands": "Унесите `/` за команде",
"audio-recorder": {
"attachment-label": "Аудио снимак",
"attachment-label-with-time": "Аудио запис {{time}}",

View file

@ -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}}",

View file

@ -127,7 +127,6 @@
"no-changes-detected": "ไม่มีการเปลี่ยนแปลง",
"save": "บันทึก",
"saving": "กำลังบันทึก...",
"slash-commands": "พิมพ์ `/` สำหรับคำสั่ง",
"insert-menu": {
"add-location": "เพิ่มสถานที่",
"link-memo": "บันทึกการเชื่อมโยง",

View file

@ -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}}",

View file

@ -135,7 +135,6 @@
"no-changes-detected": "Змін не виявлено",
"save": "Зберегти",
"saving": "Збереження...",
"slash-commands": "Введіть `/` для команд",
"audio-recorder": {
"attachment-label": "Аудіозапис",
"attachment-label-with-time": "Аудіозапис {{time}}",

View file

@ -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ớ",

View file

@ -135,7 +135,6 @@
"no-changes-detected": "未检测到更改",
"save": "保存",
"saving": "保存中...",
"slash-commands": "按下 `/` 输入命令",
"insert-menu": {
"add-location": "添加位置",
"link-memo": "链接备忘录",

View file

@ -172,7 +172,6 @@
"no-changes-detected": "未發現變更",
"save": "儲存",
"saving": "儲存中...",
"slash-commands": "輸入 `/` 以使用指令",
"audio-recorder": {
"attachment-label": "錄音",
"attachment-label-with-time": "錄音 {{time}}",

View file

@ -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([]);
});
});

View file

@ -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);
});
});

View file

@ -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);
});
});

View file

@ -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);
});
});