fix(tags): refine inline styling and enable keyboard access

This commit is contained in:
johnnyjoygh
2026-11-14 22:57:09 +08:00
parent 509e41bd1a
commit 390797ed1a
5 changed files with 141 additions and 24 deletions
+2 -2
View File
@@ -23,8 +23,8 @@ MemoEditor memo level: name | draft seed, mode, data, draft stor
└── Editor MemoMarkdown editable, with the composer's extensions, behind EditorController
```
- **`MemoMarkdown.tsx`** binds the editor to memos once: the memo Markdown dialect, the theme in the app's CSS variables, translated labels, the image and link URL policy, the memo syntax extensions (math, footnotes, tags, mentions, highlighted code, Mermaid diagrams drawn by Pele), raw HTML through the editor's `sanitizeHtml` option (`memoSanitizeHtml`: DOMPurify with memos' allowlist in `lib/html-sanitize-schema.ts`, trusted iframe hosts, and link and image defaults; loaded on first use) and the stylesheet. `useMemoDecorations` is the one flow for tag colors and resolved mentions, with one redecorate effect. Everything a surface adds sits around this component; nothing in memos styles the editor's own classes. The tag and mention classes memos hands the editor apply in source mode too, so the parts that draw a pill take the `rich:` variant (index.css), which is everything outside the editor's `.mbe-source-mode` root; source mode shows a tag as text in its color.
- **`view/`** is the read-only surface over `MemoMarkdown`: tags and mentions navigate, in-memo anchors scroll, a paragraph that is one bare link becomes a preview card through the editor's block view (`linkCards.ts`), the page's search matches are painted, and heading ids match the outline. Tag and mention clicks arrive through the editor's `onClick` callbacks, so nothing in memos matches the editor's class names or mutates its DOM. Previews that have Markdown but no memo query (the link-memo search, the share image) use `MemoContentView` directly.
- **`MemoMarkdown.tsx`** binds the editor to memos once: the memo Markdown dialect, the theme in the app's CSS variables, translated labels, the image and link URL policy, the memo syntax extensions (math, footnotes, tags, mentions, highlighted code, Mermaid diagrams drawn by Pele), raw HTML through the editor's `sanitizeHtml` option (`memoSanitizeHtml`: DOMPurify with memos' allowlist in `lib/html-sanitize-schema.ts`, trusted iframe hosts, and link and image defaults; loaded on first use) and the stylesheet. `useMemoDecorations` is the one flow for tag colors and resolved mentions, with one redecorate effect. Everything a surface adds sits around this component; nothing in memos styles the editor's own classes. The tag and mention classes memos hands the editor apply in source mode too, so the parts that draw an inline tint take the `rich:` variant (index.css), which is everything outside the editor's `.mbe-source-mode` root; source mode shows a tag as text in its color.
- **`view/`** is the read-only surface over `MemoMarkdown`: tags and mentions navigate, in-memo anchors scroll, a paragraph that is one bare link becomes a preview card through the editor's block view (`linkCards.ts`), the page's search matches are painted, and heading ids match the outline. Tag and mention clicks arrive through the editor's `onClick` callbacks. Read-only tags with a click handler are focusable buttons; Enter activates on press and Space on release through the same click callback. Editable tags remain text. Nothing in memos matches the editor's class names or mutates its DOM. Previews that have Markdown but no memo query (the link-memo search, the share image) use `MemoContentView` directly.
- **`edit/`** is the editing surface: `EditSession` renders the chrome (timestamp, attachments, suggestions, toolbar, focus mode, audio recording) over the draft store `MemoEditor` provides, persists the draft while open, and saves through the memo mutations. `Editor.tsx` is the composer's editor: `MemoMarkdown` editable with the composer's own extensions (`#tag` and `:emoji` autocomplete, file paste and drop), behind the `EditorController` contract in `controller.ts`.
Code blocks use lazy-loaded `@pierre/highlights` tokens as editor decorations, without an HTML conversion. GitHub Light and GitHub Dark Dimmed colors follow the document's color scheme; ordinary text and structural punctuation keep the editor's text color. Unsupported languages, unavailable WebAssembly, or browsers without `light-dark()` colors leave the code as plain text. Highlighting never changes the saved Markdown.
@@ -9,7 +9,7 @@ import { memoMentionOptions, memoTagOptions } from "@/lib/memo-markdown";
const MENTION_LOOKUP_DELAY_MS = 400;
export interface MemoDecorations {
/** `tags()` class, attributes and click: pills in the viewer's custom tag colors. */
/** `tags()` class, attributes and click: inline tints in the viewer's custom tag colors. */
readonly tags: Pick<TagsOptions, "class" | "attributes" | "onClick">;
/** `mentions()` class, attributes and click: the primary color for people who exist. */
readonly mentions: Pick<TagsOptions, "class" | "attributes" | "onClick">;
@@ -47,23 +47,66 @@ export function useMemoDecorations(
tagsSettingRef.current = userTagsSetting;
const resolvedRef = useRef(resolved);
resolvedRef.current = resolved;
const handlersRef = useRef(handlers);
handlersRef.current = handlers;
const handlersRef = useRef({ ...handlers, editable });
handlersRef.current = { ...handlers, editable };
const tagsInteractive = !editable && Boolean(handlers.onTagClick);
useEffect(() => {
if (!editor || !tagsInteractive) return;
let pressedTag: HTMLElement | null = null;
const handleKeyDown = (event: KeyboardEvent) => {
if (editor.isEditable || event.defaultPrevented || event.isComposing || event.altKey || event.ctrlKey || event.metaKey) return;
const tag = event.target;
if (!(tag instanceof HTMLElement) || !tag.matches('[data-tag][role="button"]')) return;
if (event.key !== "Enter" && event.key !== " ") return;
event.preventDefault();
event.stopPropagation();
if (event.repeat) return;
if (event.key === "Enter") tag.click();
else pressedTag = tag;
};
const handleKeyUp = (event: KeyboardEvent) => {
if (event.key !== " ") return;
const tag = pressedTag;
pressedTag = null;
if (!tag || event.target !== tag || editor.isEditable) return;
event.preventDefault();
event.stopPropagation();
tag.click();
};
const handleFocusOut = () => {
pressedTag = null;
};
editor.root.addEventListener("keydown", handleKeyDown);
editor.root.addEventListener("keyup", handleKeyUp);
editor.root.addEventListener("focusout", handleFocusOut);
return () => {
editor.root.removeEventListener("keydown", handleKeyDown);
editor.root.removeEventListener("keyup", handleKeyUp);
editor.root.removeEventListener("focusout", handleFocusOut);
};
}, [editor, tagsInteractive]);
// Decorate again only when what the decorations read changed: a new editor already
// decorates with the current values, and a lookup that answers the same is a no-op.
const mentionKey = useMemo(() => [...resolved].sort().join(" "), [resolved]);
const decorated = useRef({ mentionKey, userTagsSetting });
const decorated = useRef({ mentionKey, userTagsSetting, tagsInteractive });
useEffect(() => {
const changed = decorated.current.mentionKey !== mentionKey || decorated.current.userTagsSetting !== userTagsSetting;
decorated.current = { mentionKey, userTagsSetting };
const changed =
decorated.current.mentionKey !== mentionKey ||
decorated.current.userTagsSetting !== userTagsSetting ||
decorated.current.tagsInteractive !== tagsInteractive;
decorated.current = { mentionKey, userTagsSetting, tagsInteractive };
if (changed) editor?.redecorate();
}, [editor, mentionKey, userTagsSetting]);
}, [editor, mentionKey, userTagsSetting, tagsInteractive]);
return useMemo(
() => ({
tags: {
...memoTagOptions(() => tagsSettingRef.current),
...memoTagOptions(
() => tagsSettingRef.current,
() => !handlersRef.current.editable && Boolean(handlersRef.current.onTagClick),
),
onClick: ({ match }) => {
const onTagClick = handlersRef.current.onTagClick;
if (!onTagClick) return false;
+7 -9
View File
@@ -28,23 +28,21 @@ export const markdownStyles = {
/**
* `#tag` styling wherever the editor shows a memo. In rich text and the memo view a tag
* is a chip in the Badge's grammar (20px, 4px corners, a quiet fill, no outline) at caption
* size, in the well or a tint of the color the user gave it; in source mode the `rich:`
* variant (index.css) leaves only the text and its color, as the editor's own syntax
* highlighting does around it. The size is spelled out because `mu-caption` can't carry
* the variant and source mode must keep the editor's own size.
* inherits the surrounding typography with a quiet inline fill. In source mode the
* `rich:` variant (index.css) leaves only the text and its color.
*/
export const tagStyles = {
/** The pill: shape, padding and typography. */
base: "rich:inline-flex rich:h-5 rich:items-center rich:align-baseline rich:rounded-mu-sm rich:px-1.5 rich:text-[13px] rich:leading-[18px] rich:font-normal",
base: "rich:inline rich:rounded-mu-sm rich:border rich:border-transparent rich:px-0.5 rich:box-decoration-clone",
interactive: "mu-focus rich:focus-visible:border-mu-focus touch-manipulation",
/** Ink in the well, used when the tag has no color of its own. */
defaultColor: "text-mu-text rich:bg-mu-well",
defaultColor: "text-mu-text rich:bg-mu-well rich:[&[role=button]]:hover:bg-mu-hover",
/**
* The user's color, read from `--tag-color` on the element, as the package's Badge `color` draws
* it: an 18% tint behind ink text, the same in both themes. The text never takes the color, since
* no chosen color is readable as text on its own tint in both themes.
*/
customColor: "text-mu-text rich:bg-[color-mix(in_srgb,var(--tag-color)_18%,transparent)]",
customColor:
"text-mu-text rich:bg-[color-mix(in_srgb,var(--tag-color)_18%,transparent)] rich:[&[role=button]]:hover:bg-[color-mix(in_srgb,var(--tag-color)_26%,transparent)]",
} as const;
/**
+13 -5
View File
@@ -146,16 +146,24 @@ const CUSTOM_TAG_CLASS = cn(TAG_CLASS, tagStyles.customColor);
/**
* How a #tag looks wherever a memo is shown, in the composer and the memo view alike:
* a pill in the theme color, or in the color the user gave the tag, which the element
* an inline tint in the theme color, or in the color the user gave the tag, which the element
* carries as `--tag-color` for tagStyles.customColor to draw from. `getTagsSetting`
* is read when a block is decorated; call `editor.redecorate()` when it changes.
*/
export const memoTagOptions = (getTagsSetting: () => UserSetting_TagsSetting | undefined): Pick<TagsOptions, "class" | "attributes"> => ({
class: (match) => (tagColor(match.slice(1), getTagsSetting()) ? CUSTOM_TAG_CLASS : DEFAULT_TAG_CLASS),
export const memoTagOptions = (
getTagsSetting: () => UserSetting_TagsSetting | undefined,
isInteractive: () => boolean = () => false,
): Pick<TagsOptions, "class" | "attributes"> => ({
class: (match) =>
cn(tagColor(match.slice(1), getTagsSetting()) ? CUSTOM_TAG_CLASS : DEFAULT_TAG_CLASS, isInteractive() && tagStyles.interactive),
attributes: (match): Record<string, string> => {
const tag = match.slice(1);
const color = tagColor(tag, getTagsSetting());
return color ? { "data-tag": tag, style: `--tag-color: ${color}` } : { "data-tag": tag };
return {
"data-tag": tag,
...(color ? { style: `--tag-color: ${color}` } : {}),
...(isInteractive() ? { role: "button", tabindex: "0" } : {}),
};
},
});
@@ -177,7 +185,7 @@ export const memoMentionOptions = (isResolved: (username: string) => boolean): P
});
interface MemoExtensionOptions {
/** `tags()` class and attributes, for the memo view's pills and colors. */
/** `tags()` class and attributes, for the memo view's inline tags and colors. */
readonly tags?: Pick<TagsOptions, "class" | "attributes" | "onClick">;
/** `mentions()` class and attributes, for links to the people who exist. */
readonly mentions?: Pick<TagsOptions, "class" | "attributes" | "onClick">;
+68
View File
@@ -97,6 +97,74 @@ describe("tags and mentions", () => {
expect(state.addFilter).toHaveBeenCalledWith({ factor: "tagSearch", value: "work" });
});
it.each(["Enter", " "])("activates a focusable tag with %j without scrolling or bubbling", (key) => {
const onKeyDown = vi.fn();
const onTagClick = vi.fn();
render(
<div onKeyDown={onKeyDown}>
<MemoMarkdown value="Plan #work today" onTagClick={onTagClick} />
</div>,
);
const tag = screen.getByRole("button", { name: "#work" });
expect(tag).toHaveAttribute("tabindex", "0");
expect(tag).toHaveClass("mu-focus");
tag.focus();
expect(tag).toHaveFocus();
expect(fireEvent.keyDown(tag, { key })).toBe(false);
expect(onTagClick).toHaveBeenCalledTimes(key === "Enter" ? 1 : 0);
fireEvent.keyDown(tag, { key, repeat: true });
fireEvent.keyUp(tag, { key });
expect(onTagClick).toHaveBeenCalledExactlyOnceWith("work");
expect(onKeyDown).not.toHaveBeenCalled();
});
it("cancels Space activation when focus leaves the tag", () => {
const onTagClick = vi.fn();
render(<MemoMarkdown value="#work #life" onTagClick={onTagClick} />);
const work = screen.getByRole("button", { name: "#work" });
const life = screen.getByRole("button", { name: "#life" });
work.focus();
fireEvent.keyDown(work, { key: " " });
life.focus();
fireEvent.keyUp(life, { key: " " });
expect(onTagClick).not.toHaveBeenCalled();
});
it("keeps tags as text without a click handler and while editing", () => {
const onTagClick = vi.fn();
const { rerender } = render(<MemoMarkdown value="#work" />);
expect(screen.queryByRole("button", { name: "#work" })).not.toBeInTheDocument();
rerender(<MemoMarkdown value="#work" onTagClick={onTagClick} />);
expect(screen.getByRole("button", { name: "#work" })).toHaveAttribute("tabindex", "0");
rerender(<MemoMarkdown value="#work" editable onTagClick={onTagClick} />);
const tag = screen.getByText("#work");
expect(tag).not.toHaveAttribute("role");
expect(tag).not.toHaveAttribute("tabindex");
fireEvent.keyDown(tag, { key: "Enter" });
fireEvent.keyUp(tag, { key: " " });
expect(onTagClick).not.toHaveBeenCalled();
rerender(<MemoMarkdown value="#work" onTagClick={onTagClick} />);
const button = screen.getByRole("button", { name: "#work" });
fireEvent.keyDown(button, { key: "Enter" });
expect(onTagClick).toHaveBeenCalledExactlyOnceWith("work");
rerender(<MemoMarkdown value="#work" />);
expect(screen.getByText("#work")).not.toHaveAttribute("tabindex");
});
it("uses the latest tag handler for keyboard activation", () => {
const first = vi.fn();
const latest = vi.fn();
const { rerender } = render(<MemoMarkdown value="#work" onTagClick={first} />);
rerender(<MemoMarkdown value="#work" onTagClick={latest} />);
fireEvent.keyDown(screen.getByRole("button", { name: "#work" }), { key: "Enter" });
expect(first).not.toHaveBeenCalled();
expect(latest).toHaveBeenCalledExactlyOnceWith("work");
});
it("opens the collection filtered by the tag from a memo detail page", () => {
renderMemo("Plan #work today", { parentPage: "/?creator=alice" }, "/memos/1");
fireEvent.click(screen.getByText("#work"));