From daa71d0456d07a25ff5ea435e46577d31d030728 Mon Sep 17 00:00:00 2001 From: boojack Date: Fri, 26 Jun 2026 09:28:41 +0800 Subject: [PATCH] feat(editor): recognize and style @mentions in the rich editor Mirror the #tag mark so the TipTap editor styles @username while typing and on load, matching the read-only view. A shared mention grammar (utils/mention-grammar.ts) feeds both the editor tokenizer and the read-only remark renderer so they can't drift. Styling only -- no autocomplete dropdown (ListUsers is admin-only and there is no user-search RPC). Bare emails still autolink to mailto: and are never treated as mentions: the tokenizer's start() skips email-glued @s so marked's GFM autolinker keeps seeing the whole address. --- web/src/components/MemoContent/Mention.tsx | 3 +- .../components/MemoEditor/Editor/Mention.ts | 124 ++++++++++++++++++ .../MemoEditor/Editor/extensions.ts | 2 + .../MemoEditor/Toolbar/InsertMenu.tsx | 2 +- .../MemoEditor/Toolbar/VisibilitySelector.tsx | 4 +- .../MemoEditor/components/EditorToolbar.tsx | 5 +- web/src/components/ui/button.tsx | 2 +- web/src/lib/markdownStyles.ts | 11 ++ web/src/pages/About.tsx | 79 ----------- web/src/utils/mention-grammar.ts | 30 +++++ .../utils/remark-plugins/remark-mention.ts | 7 +- web/tests/about-page.test.tsx | 33 ----- web/tests/editor-mention.test.ts | 96 ++++++++++++++ 13 files changed, 272 insertions(+), 126 deletions(-) create mode 100644 web/src/components/MemoEditor/Editor/Mention.ts create mode 100644 web/src/utils/mention-grammar.ts create mode 100644 web/tests/editor-mention.test.ts diff --git a/web/src/components/MemoContent/Mention.tsx b/web/src/components/MemoContent/Mention.tsx index 49a3b8c6..c3e32e64 100644 --- a/web/src/components/MemoContent/Mention.tsx +++ b/web/src/components/MemoContent/Mention.tsx @@ -1,4 +1,5 @@ import type { Element } from "hast"; +import { mentionStyles } from "@/lib/markdownStyles"; import { cn } from "@/lib/utils"; interface MentionProps extends React.HTMLAttributes { @@ -29,7 +30,7 @@ export const Mention: React.FC = ({ return ( element.getAttribute("data-mention") ?? "", + renderHTML: (attributes) => ({ "data-mention": attributes.username }), + }, + }; + }, + + parseHTML() { + return [{ tag: "span[data-mention]" }]; + }, + + renderHTML({ HTMLAttributes }) { + return [ + "span", + mergeAttributes(HTMLAttributes, { + class: MENTION_CLASS, + }), + 0, + ]; + }, + + addInputRules() { + return [ + new InputRule({ + find: MENTION_INPUT_RULE, + handler: ({ state, range, match }) => { + // Mark only from the `@`; the trailing space stays outside the mark + // and is re-inserted explicitly (the handler's steps suppress the + // typed space), mirroring the Tag input rule. + const start = range.from + match[0].indexOf("@"); + state.tr + .addMark(start, range.to, this.type.create({ username: match[1] })) + .insertText(" ", range.to) + .removeStoredMark(this.type); + }, + }), + ]; + }, + + markdownTokenizer: { + name: "memoMention", + level: "inline", + // Point marked only at an `@` that could *begin* a mention — one at a + // boundary (string start, or a non-mention char before it). An `@` glued to + // a preceding word/username char belongs to an email (`support@example.com`) + // or the tail of `@a@b`; surfacing its index here would make marked split + // the text at the `@` and rob its GFM autolinker of the contiguous email, + // suppressing the mailto link. Skipping such `@`s leaves emails to autolink. + start: (src: string) => { + for (let i = src.indexOf("@"); i !== -1; i = src.indexOf("@", i + 1)) { + if (i === 0 || !isMentionChar(src[i - 1])) { + return i; + } + } + return -1; + }, + tokenize: (src: string, tokens: MarkdownToken[]) => { + const match = MENTION_TOKEN_RULE.exec(src); + if (!match) { + return undefined; + } + // A mention only starts at a boundary. The previous token's last source + // character is exactly the character before this `@`; if it is a mention + // character the `@` is glued to a word or username (`support@example`, + // the second `@` in `@a@b`) and must stay literal — mirroring the + // read-only renderer's isMentionBoundary check (remark-mention.ts). + const prevChar = (tokens[tokens.length - 1]?.raw ?? "").slice(-1); + if (prevChar && isMentionChar(prevChar)) { + return undefined; + } + return { type: "memoMention", raw: match[0], username: match[1] }; + }, + }, + markdownTokenName: "memoMention", + parseMarkdown: (token, helpers) => { + const t = token as MarkdownToken & { username?: string }; + return helpers.createTextNode(t.raw ?? "", [{ type: "mention", attrs: { username: t.username ?? "" } }]); + }, + // No delimiters: the literal `@username` text carries the syntax. + renderMarkdown: (node, helpers) => (node.content ? helpers.renderChildren(node.content) : ""), +}); diff --git a/web/src/components/MemoEditor/Editor/extensions.ts b/web/src/components/MemoEditor/Editor/extensions.ts index fa941a08..d24f40e7 100644 --- a/web/src/components/MemoEditor/Editor/extensions.ts +++ b/web/src/components/MemoEditor/Editor/extensions.ts @@ -3,6 +3,7 @@ import { Heading } from "@tiptap/extension-heading"; import { TaskItem, TaskList } from "@tiptap/extension-list"; import StarterKit from "@tiptap/starter-kit"; import { type HeadingLevel, headingClass, markdownStyles } from "@/lib/markdownStyles"; +import { Mention } from "./Mention"; import { preservedExtensions } from "./PreservedBlock"; import { Tag } from "./Tag"; import { TagAwareMarkdown } from "./tagMarkdown"; @@ -49,5 +50,6 @@ export function buildExtensions(): AnyExtension[] { TagAwareMarkdown, ...preservedExtensions, Tag, + Mention, ]; } diff --git a/web/src/components/MemoEditor/Toolbar/InsertMenu.tsx b/web/src/components/MemoEditor/Toolbar/InsertMenu.tsx index 6241b257..79ac72e0 100644 --- a/web/src/components/MemoEditor/Toolbar/InsertMenu.tsx +++ b/web/src/components/MemoEditor/Toolbar/InsertMenu.tsx @@ -194,7 +194,7 @@ const InsertMenu = (props: InsertMenuProps) => { <> - diff --git a/web/src/components/MemoEditor/Toolbar/VisibilitySelector.tsx b/web/src/components/MemoEditor/Toolbar/VisibilitySelector.tsx index e74f6d24..b24c3831 100644 --- a/web/src/components/MemoEditor/Toolbar/VisibilitySelector.tsx +++ b/web/src/components/MemoEditor/Toolbar/VisibilitySelector.tsx @@ -20,13 +20,13 @@ const VisibilitySelector = (props: VisibilitySelectorProps) => { return ( - - + {visibilityOptions.map((option) => ( onChange(option.value)}> diff --git a/web/src/components/MemoEditor/components/EditorToolbar.tsx b/web/src/components/MemoEditor/components/EditorToolbar.tsx index a6cbbe1c..866a009e 100644 --- a/web/src/components/MemoEditor/components/EditorToolbar.tsx +++ b/web/src/components/MemoEditor/components/EditorToolbar.tsx @@ -34,7 +34,7 @@ export const EditorToolbar: FC = ({ onSave, onCancel, memoNa return (
-
+
= ({ onSave, onCancel, memoNa memoName={memoName} onAudioRecorderClick={onAudioRecorderClick} /> +
- - {onCancel && (
- -
- {SPONSORS.map((sponsor) => ( - -
- - -
-
-

{sponsor.description}

- - Visit {sponsor.label} - -
-
- ))} -
- -
{TILE_SPRITES.map((sprite) => ( diff --git a/web/src/utils/mention-grammar.ts b/web/src/utils/mention-grammar.ts new file mode 100644 index 00000000..de87284d --- /dev/null +++ b/web/src/utils/mention-grammar.ts @@ -0,0 +1,30 @@ +/** + * The single source of truth for memos' `@mention` lexing grammar, shared by the + * editor tokenizer (components/MemoEditor/Editor/Mention.ts) and the read-only + * renderer (utils/remark-plugins/remark-mention.ts) so they can't drift. + * + * A mention character is an ASCII letter, digit, or hyphen. A username is capped + * at MAX_MENTION_LENGTH characters and must contain at least one letter or digit + * (a run of only hyphens is not a mention). This matches the Go backend parser + * (internal/markdown/parser/mention.go). + */ +export const MENTION_CHAR_CLASS = "[A-Za-z0-9-]"; + +export const MAX_MENTION_LENGTH = 32; + +/** + * Regex source for a username run: 1..MAX_MENTION_LENGTH mention characters that + * include at least one letter or digit. Unlike TAG_RUN this does not refuse an + * over-long run — a 33rd mention character simply falls outside the capture and + * becomes ordinary text, mirroring the read-only parser's truncation. The + * leading lookahead enforces the "must contain an alphanumeric" rule so `@---` + * is left as plain text. Embed after an `@`, e.g. `^@(${MENTION_RUN})`. + */ +export const MENTION_RUN = `(?=${MENTION_CHAR_CLASS}{0,${MAX_MENTION_LENGTH - 1}}[A-Za-z0-9])${MENTION_CHAR_CLASS}{1,${MAX_MENTION_LENGTH}}`; + +const SINGLE_MENTION_CHAR = /^[A-Za-z0-9-]$/; + +/** Whether a single character is allowed inside a username. */ +export function isMentionChar(char: string): boolean { + return SINGLE_MENTION_CHAR.test(char); +} diff --git a/web/src/utils/remark-plugins/remark-mention.ts b/web/src/utils/remark-plugins/remark-mention.ts index 4fd567ce..1b6f7241 100644 --- a/web/src/utils/remark-plugins/remark-mention.ts +++ b/web/src/utils/remark-plugins/remark-mention.ts @@ -2,12 +2,7 @@ import type { Root, Text } from "mdast"; import type { Node as UnistNode } from "unist"; import { visit } from "unist-util-visit"; import type { MentionNode, MentionNodeData } from "@/types/markdown"; - -const MAX_MENTION_LENGTH = 32; - -function isMentionChar(char: string): boolean { - return /[A-Za-z0-9-]/.test(char); -} +import { isMentionChar, MAX_MENTION_LENGTH } from "@/utils/mention-grammar"; function isMentionBoundary(char: string): boolean { if (!char) return true; diff --git a/web/tests/about-page.test.tsx b/web/tests/about-page.test.tsx index 101eb878..fb79c600 100644 --- a/web/tests/about-page.test.tsx +++ b/web/tests/about-page.test.tsx @@ -15,24 +15,6 @@ describe("", () => { expect(screen.getByText(/Capture first/i)).toBeInTheDocument(); expect(screen.getByText(/quick capture/i)).toBeInTheDocument(); - const sponsors = screen.getByRole("region", { name: "Sponsors" }); - expect(within(sponsors).getByRole("link", { name: /CodeRabbit/i })).toHaveAttribute("href", "https://coderabbit.link/usememos"); - expect(within(sponsors).getByRole("link", { name: /Warp/i })).toHaveAttribute("href", "https://go.warp.dev/memos"); - expect(within(sponsors).getByText(/Cut code review time/i)).toBeInTheDocument(); - expect(within(sponsors).getByText(/agentic development environment/i)).toBeInTheDocument(); - expect(within(sponsors).getByAltText("CodeRabbit").closest("a")).toHaveAttribute("href", "https://coderabbit.link/usememos"); - expect( - within(sponsors) - .getByText(/Cut code review time/i) - .closest("a"), - ).toHaveAttribute("href", "https://coderabbit.link/usememos"); - expect(within(sponsors).getByAltText("Warp").closest("a")).toHaveAttribute("href", "https://go.warp.dev/memos"); - expect( - within(sponsors) - .getByText(/agentic development environment/i) - .closest("a"), - ).toHaveAttribute("href", "https://go.warp.dev/memos"); - const birds = screen.getByRole("region", { name: "Birds" }); expect(within(birds).getAllByTestId("about-bird-sprite")).toHaveLength(TILE_SPRITES.length); @@ -49,19 +31,4 @@ describe("", () => { expect(contentWrapper).toHaveClass("w-full"); expect(contentWrapper).not.toHaveClass("px-4"); }); - - it("uses dark sponsor logos when the app theme is dark", () => { - document.documentElement.setAttribute("data-theme", "default-dark"); - - render(); - - expect(screen.getByAltText("CodeRabbit")).toHaveAttribute( - "src", - "https://victorious-bubble-f69a016683.media.strapiapp.com/White_Typemark_79b9189d19.svg", - ); - expect(screen.getByAltText("Warp")).toHaveAttribute( - "src", - "https://raw.githubusercontent.com/warpdotdev/brand-assets/refs/heads/main/Logos/Warp-Wordmark-White.png", - ); - }); }); diff --git a/web/tests/editor-mention.test.ts b/web/tests/editor-mention.test.ts new file mode 100644 index 00000000..ab9f5e66 --- /dev/null +++ b/web/tests/editor-mention.test.ts @@ -0,0 +1,96 @@ +import type { JSONContent } from "@tiptap/core"; +import { describe, expect, it } from "vitest"; +import { parseMarkdown, roundTripMarkdown } from "@/components/MemoEditor/Editor/markdownCodec"; + +function firstParagraphChildren(markdown: string) { + return parseMarkdown(markdown).content?.[0]?.content ?? []; +} + +function hasMentionMark(node: JSONContent) { + return (node.marks ?? []).some((m) => m.type === "mention"); +} + +describe("Mention mark", () => { + it("parses @username into mention-marked text", () => { + const mentioned = firstParagraphChildren("hey @alice there").find(hasMentionMark); + expect(mentioned).toMatchObject({ type: "text", text: "@alice", marks: [{ type: "mention", attrs: { username: "alice" } }] }); + }); + + it("serializes mention-marked text back to @username verbatim", () => { + expect(roundTripMarkdown("ping @bob now").trim()).toBe("ping @bob now"); + }); + + it("preserves username case in the editor model (no lowercasing)", () => { + const mentioned = firstParagraphChildren("@Alice").find(hasMentionMark); + expect(mentioned).toMatchObject({ text: "@Alice", marks: [{ type: "mention", attrs: { username: "Alice" } }] }); + expect(roundTripMarkdown("@Alice").trim()).toBe("@Alice"); + }); + + it("supports hyphenated usernames", () => { + const username = firstParagraphChildren("@jane-doe ok") + .find(hasMentionMark) + ?.marks?.find((m) => m.type === "mention")?.attrs?.username; + expect(username).toBe("jane-doe"); + expect(roundTripMarkdown("@jane-doe ok").trim()).toBe("@jane-doe ok"); + }); + + it("autolinks a bare email to mailto and never treats it as a mention", () => { + // The `@` in an email must not become a mention, and the email itself must + // still autolink to a mailto: link (GFM, same as the read-only view) — for + // a standalone email and one mid-sentence alike. The mention tokenizer must + // stay out of the email's way rather than splitting the text at its `@`. + for (const input of ["support@example.com", "mail support@example.com please"]) { + expect(firstParagraphChildren(input).some(hasMentionMark)).toBe(false); + expect(roundTripMarkdown(input)).toContain("[support@example.com](mailto:support@example.com)"); + } + }); + + it("stops at a mention-char boundary: @a@b is mention `a` then literal `@b`", () => { + const mentioned = firstParagraphChildren("@a@b").filter(hasMentionMark); + expect(mentioned).toHaveLength(1); + expect(mentioned[0]).toMatchObject({ text: "@a", marks: [{ type: "mention", attrs: { username: "a" } }] }); + expect(roundTripMarkdown("@a@b").trim()).toBe("@a@b"); + }); + + it("carries both bold and mention marks on **@bob** and round-trips", () => { + const input = "**hi @bob**"; + expect(roundTripMarkdown(input).trim()).toBe(input); + const markTypes = (firstParagraphChildren(input).find((n) => n.text === "@bob")?.marks ?? []).map((m) => m.type); + expect(markTypes).toContain("bold"); + expect(markTypes).toContain("mention"); + }); + + it("keeps a mention inside a link label and round-trips byte-identically", () => { + const input = "[ping @bob](https://example.com)"; + expect(roundTripMarkdown(input).trim()).toBe(input); + }); + + it("does not create a mention from an all-hyphen run", () => { + const children = firstParagraphChildren("@--- nope"); + expect(children.some(hasMentionMark)).toBe(false); + expect(roundTripMarkdown("@--- nope").trim()).toBe("@--- nope"); + }); + + it("caps the username at 32 chars, leaving the overflow as plain text", () => { + const input = `@${"a".repeat(40)}`; + const username = firstParagraphChildren(input) + .find(hasMentionMark) + ?.marks?.find((m) => m.type === "mention")?.attrs?.username; + expect(username).toBe("a".repeat(32)); + expect(roundTripMarkdown(input).trim()).toBe(input); + }); + + it("marks the mentions, autolinks the email, in a mixed line", () => { + // Mentions stay mentions (editor preserves case, unlike backend extraction + // which lowercases), the email autolinks to mailto, and the two never + // collide. Based on the backend's canonical case (markdown_test.go). + const input = "Hi @Alice and @bob. Email support@example.com today."; + const usernames = firstParagraphChildren(input) + .filter(hasMentionMark) + .map((n) => n.marks?.find((m) => m.type === "mention")?.attrs?.username); + expect(usernames).toEqual(["Alice", "bob"]); + + const out = roundTripMarkdown(input).trim(); + expect(out).toBe("Hi @Alice and @bob. Email [support@example.com](mailto:support@example.com) today."); + }); +});