AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.
HTML ai-agentcloudflarecloudflare-d1cloudflare-r2cloudflare-workersdockerelectronevernoteevernote-alternativeknowledge-basemcpnote-takingobsidian-alternativeoffline-firstpersonal-knowledge-basepwaself-hostedsqlitetiptapweb-clipper
fix(editor): add slash command menu (#236)
tianma-if9c4d6eea5447
diff --git a/apps/web/src/components/EditorPane.tsx b/apps/web/src/components/EditorPane.tsxindex 8e8f3b29..f0483ba2 100644--- a/apps/web/src/components/EditorPane.tsx+++ b/apps/web/src/components/EditorPane.tsx@@ -79,6 +79,11 @@ import { EditorToolbar } from "./EditorToolbar";import { EditorOutline } from "./EditorOutline";import { EditorTagPicker } from "./EditorTagPicker";import { useAiBubbleMenu } from "./editor/useAiBubbleMenu";+import {+ createSlashCommandExtension,+ type SlashCommandActions,+ type SlashCommandLabels,+} from "./editor/SlashCommandMenu";import { WeChatIcon } from "./WeChatIcon";import { ThemeToggle } from "./ThemeToggle";import { useEditorTheme } from "./ThemeProvider";@@ -874,6 +879,72 @@ const RichEditorPane = ({const noteSearchAutoSelectionRef = useRef<{ editor: Editor; identity: string } | null>(null);const markdownTextAreaRef = useRef<HTMLTextAreaElement | null>(null);const openExternalLinkDialogRef = useRef<() => void>(() => undefined);+ const slashCommandLabelsRef = useRef<SlashCommandLabels>({+ menu: "",+ empty: "",+ close: "",+ groups: { suggested: "", basic: "", insert: "" },+ items: {+ ai: "",+ paragraph: "",+ "heading-1": "",+ "heading-2": "",+ "heading-3": "",+ "bullet-list": "",+ "ordered-list": "",+ "task-list": "",+ blockquote: "",+ "code-block": "",+ divider: "",+ table: "",+ attachment: "",+ "note-link": "",+ "external-link": "",+ },+ });+ slashCommandLabelsRef.current = {+ menu: t("slashMenu.menu"),+ empty: t("slashMenu.empty"),+ close: t("slashMenu.close"),+ groups: {+ suggested: t("slashMenu.groups.suggested"),+ basic: t("slashMenu.groups.basic"),+ insert: t("slashMenu.groups.insert"),+ },+ items: {+ ai: t("slashMenu.items.ai"),+ paragraph: t("editorToolbar.paragraph"),+ "heading-1": t("editorToolbar.heading1"),+ "heading-2": t("editorToolbar.heading2"),+ "heading-3": t("editorToolbar.heading3"),+ "bullet-list": t("editorToolbar.bulletList"),+ "ordered-list": t("editorToolbar.orderedList"),+ "task-list": t("editorToolbar.taskList"),+ blockquote: t("editorToolbar.quote"),+ "code-block": t("editorToolbar.codeBlock"),+ divider: t("editorToolbar.horizontalRule"),+ table: t("editorToolbar.table"),+ attachment: t("editorToolbar.attachment"),+ "note-link": t("editorToolbar.noteLink"),+ "external-link": t("editorToolbar.externalLink"),+ },+ };+ const slashCommandActionsRef = useRef<SlashCommandActions | null>(null);+ if (!slashCommandActionsRef.current) {+ slashCommandActionsRef.current = {+ openAi: () => openAiAssistantRef.current(),+ openAttachmentPicker: () => fileInputRef.current?.click(),+ openExternalLinkPicker: () => openExternalLinkDialogRef.current(),+ openNoteLinkPicker: () => setNoteLinkPickerOpen(true),+ };+ }+ const slashCommandExtensionRef = useRef<ReturnType<typeof createSlashCommandExtension> | null>(null);+ if (!slashCommandExtensionRef.current) {+ slashCommandExtensionRef.current = createSlashCommandExtension({+ actions: slashCommandActionsRef.current,+ getLabels: () => slashCommandLabelsRef.current,+ });+ }const hydratingRef = useRef(false);const hydratedMemoIdRef = useRef<string | null>(null);/** Last content source applied to the editor — used to skip redundant setContent. */@@ -1124,6 +1195,7 @@ const RichEditorPane = ({Placeholder.configure({placeholder: t("editor.placeholder"),}),+ slashCommandExtensionRef.current,],content: memo? resolveMemoContentDoc(memo.contentJson, memo.contentMarkdown)diff --git a/apps/web/src/components/editor/SlashCommandMenu.test.mjs b/apps/web/src/components/editor/SlashCommandMenu.test.mjsnew file mode 100644index 00000000..35df275a--- /dev/null+++ b/apps/web/src/components/editor/SlashCommandMenu.test.mjs@@ -0,0 +1,40 @@+import { describe, expect, test } from "bun:test";+import { createSlashCommandItems, filterSlashCommandItems } from "./SlashCommandMenu.tsx";++const labels = {+ menu: "插入功能菜单",+ empty: "没有匹配的功能。",+ close: "关闭菜单",+ groups: { suggested: "建议", basic: "基本区块", insert: "插入" },+ items: {+ ai: "用 AI 处理",+ paragraph: "正文",+ "heading-1": "标题 1",+ "heading-2": "标题 2",+ "heading-3": "标题 3",+ "bullet-list": "无序列表",+ "ordered-list": "有序列表",+ "task-list": "任务清单",+ blockquote: "引用",+ "code-block": "代码块",+ divider: "分割线",+ table: "表格",+ attachment: "上传附件",+ "note-link": "引用笔记",+ "external-link": "插入超链接",+ },+};++describe("slash command menu", () => {+ const items = createSlashCommandItems(labels);++ test("shows all commands for a bare slash", () => {+ expect(filterSlashCommandItems(items, "")).toHaveLength(15);+ });++ test("searches localized labels and aliases", () => {+ expect(filterSlashCommandItems(items, "AI").map((item) => item.id)).toEqual(["ai"]);+ expect(filterSlashCommandItems(items, "待办").map((item) => item.id)).toEqual(["task-list"]);+ expect(filterSlashCommandItems(items, "h2").map((item) => item.id)).toEqual(["heading-2"]);+ });+});diff --git a/apps/web/src/components/editor/SlashCommandMenu.tsx b/apps/web/src/components/editor/SlashCommandMenu.tsxnew file mode 100644index 00000000..0f247eb7--- /dev/null+++ b/apps/web/src/components/editor/SlashCommandMenu.tsx@@ -0,0 +1,276 @@+import { forwardRef, useEffect, useImperativeHandle, useState, type ComponentType } from "react";+import { Extension, type Editor, type Range } from "@tiptap/core";+import { ReactRenderer } from "@tiptap/react";+import { PluginKey } from "@tiptap/pm/state";+import Suggestion, { type SuggestionKeyDownProps, type SuggestionProps } from "@tiptap/suggestion";+import {+ BetweenHorizontalStart,+ Bot,+ Braces,+ FileUp,+ Heading1,+ Heading2,+ Heading3,+ Link,+ List,+ ListOrdered,+ ListTodo,+ Pilcrow,+ Quote,+ Table2,+} from "lucide-react";+import {+ Command,+ CommandEmpty,+ CommandGroup,+ CommandItem,+ CommandList,+ CommandShortcut,+} from "@/components/ui/command";++export type SlashCommandId =+ | "ai"+ | "paragraph"+ | "heading-1"+ | "heading-2"+ | "heading-3"+ | "bullet-list"+ | "ordered-list"+ | "task-list"+ | "blockquote"+ | "code-block"+ | "divider"+ | "table"+ | "attachment"+ | "note-link"+ | "external-link";++type SlashCommandGroup = "suggested" | "basic" | "insert";+type SlashCommandIcon = ComponentType<{ className?: string }>;++export type SlashCommandLabels = {+ menu: string;+ empty: string;+ close: string;+ groups: Record<SlashCommandGroup, string>;+ items: Record<SlashCommandId, string>;+};++export type SlashCommandActions = {+ openAi: () => void;+ openAttachmentPicker: () => void;+ openExternalLinkPicker: () => void;+ openNoteLinkPicker: () => void;+};++export type SlashCommandItem = {+ id: SlashCommandId;+ group: SlashCommandGroup;+ icon: SlashCommandIcon;+ keywords: string[];+ label: string;+ shortcut?: string;+};++const slashCommandPluginKey = new PluginKey("edgeever-slash-command");++export const createSlashCommandItems = (labels: SlashCommandLabels): SlashCommandItem[] => [+ { id: "ai", group: "suggested", icon: Bot, label: labels.items.ai, shortcut: "/ai", keywords: ["ai", "assistant", "人工智能", "智能", "写作"] },+ { id: "paragraph", group: "basic", icon: Pilcrow, label: labels.items.paragraph, keywords: ["text", "paragraph", "正文", "文本"] },+ { id: "heading-1", group: "basic", icon: Heading1, label: labels.items["heading-1"], shortcut: "#", keywords: ["h1", "heading", "标题"] },+ { id: "heading-2", group: "basic", icon: Heading2, label: labels.items["heading-2"], shortcut: "##", keywords: ["h2", "heading", "标题"] },+ { id: "heading-3", group: "basic", icon: Heading3, label: labels.items["heading-3"], shortcut: "###", keywords: ["h3", "heading", "标题"] },+ { id: "bullet-list", group: "basic", icon: List, label: labels.items["bullet-list"], shortcut: "-", keywords: ["bullet", "list", "无序", "列表"] },+ { id: "ordered-list", group: "basic", icon: ListOrdered, label: labels.items["ordered-list"], shortcut: "1.", keywords: ["ordered", "numbered", "list", "有序", "编号"] },+ { id: "task-list", group: "basic", icon: ListTodo, label: labels.items["task-list"], shortcut: "[ ]", keywords: ["task", "todo", "check", "任务", "待办"] },+ { id: "blockquote", group: "basic", icon: Quote, label: labels.items.blockquote, shortcut: ">", keywords: ["quote", "引用"] },+ { id: "code-block", group: "basic", icon: Braces, label: labels.items["code-block"], shortcut: "```", keywords: ["code", "代码"] },+ { id: "divider", group: "insert", icon: BetweenHorizontalStart, label: labels.items.divider, shortcut: "---", keywords: ["divider", "rule", "分割", "分隔"] },+ { id: "table", group: "insert", icon: Table2, label: labels.items.table, keywords: ["table", "表格"] },+ { id: "attachment", group: "insert", icon: FileUp, label: labels.items.attachment, keywords: ["file", "upload", "attachment", "文件", "上传", "附件"] },+ { id: "note-link", group: "insert", icon: Link, label: labels.items["note-link"], keywords: ["note", "link", "memo", "笔记", "引用"] },+ { id: "external-link", group: "insert", icon: Link, label: labels.items["external-link"], keywords: ["url", "link", "web", "链接", "网址"] },+];++export const filterSlashCommandItems = (items: SlashCommandItem[], query: string) => {+ const normalizedQuery = query.trim().toLocaleLowerCase();+ if (!normalizedQuery) return items;+ return items.filter((item) => [item.label, item.id, ...item.keywords]+ .some((value) => value.toLocaleLowerCase().includes(normalizedQuery)));+};++type SlashCommandMenuProps = SuggestionProps<SlashCommandItem, SlashCommandItem> & {+ labels: SlashCommandLabels;+};++export type SlashCommandMenuHandle = {+ onKeyDown: (props: SuggestionKeyDownProps) => boolean;+};++const GROUP_ORDER: SlashCommandGroup[] = ["suggested", "basic", "insert"];++export const SlashCommandMenu = forwardRef<SlashCommandMenuHandle, SlashCommandMenuProps>(+ ({ command, items, labels }, ref) => {+ const [selectedIndex, setSelectedIndex] = useState(0);+ const selectedItem = items[Math.min(selectedIndex, Math.max(0, items.length - 1))];++ useEffect(() => setSelectedIndex(0), [items]);++ useImperativeHandle(ref, () => ({+ onKeyDown: ({ event }) => {+ if (!items.length) return false;+ if (event.key === "ArrowUp") {+ setSelectedIndex((current) => (current + items.length - 1) % items.length);+ return true;+ }+ if (event.key === "ArrowDown") {+ setSelectedIndex((current) => (current + 1) % items.length);+ return true;+ }+ if (event.key === "Enter") {+ command(items[Math.min(selectedIndex, items.length - 1)]);+ return true;+ }+ return false;+ },+ }), [command, items, selectedIndex]);++ return (+ <Command+ aria-label={labels.menu}+ className="w-[min(22rem,calc(100vw-1.5rem))] rounded-xl border border-slate-200 shadow-2xl ring-1 ring-slate-950/5"+ shouldFilter={false}+ value={selectedItem?.id}+ onValueChange={(value) => {+ const index = items.findIndex((item) => item.id === value);+ if (index >= 0) setSelectedIndex(index);+ }}+ >+ <CommandList className="max-h-[min(24rem,60dvh)] p-1.5">+ <CommandEmpty>{labels.empty}</CommandEmpty>+ {GROUP_ORDER.map((group) => {+ const groupItems = items.filter((item) => item.group === group);+ return groupItems.length ? (+ <CommandGroup key={group} heading={labels.groups[group]}>+ {groupItems.map((item) => {+ const Icon = item.icon;+ return (+ <CommandItem+ key={item.id}+ value={item.id}+ keywords={item.keywords}+ onMouseDown={(event) => event.preventDefault()}+ onSelect={() => command(item)}+ >+ <Icon className="h-4 w-4 shrink-0 text-slate-500" />+ <span className="min-w-0 flex-1 truncate">{item.label}</span>+ {item.shortcut ? <CommandShortcut>{item.shortcut}</CommandShortcut> : null}+ </CommandItem>+ );+ })}+ </CommandGroup>+ ) : null;+ })}+ </CommandList>+ <div className="flex items-center justify-between border-t border-slate-100 px-3 py-2 text-xs text-slate-400">+ <span>↑↓ · Enter</span>+ <span>{labels.close} · Esc</span>+ </div>+ </Command>+ );+ },+);+SlashCommandMenu.displayName = "SlashCommandMenu";++const runSlashCommand = ({+ actions,+ editor,+ item,+ range,+}: {+ actions: SlashCommandActions;+ editor: Editor;+ item: SlashCommandItem;+ range: Range;+}) => {+ const chain = editor.chain().focus().deleteRange(range);+ switch (item.id) {+ case "ai":+ chain.run();+ window.requestAnimationFrame(actions.openAi);+ break;+ case "paragraph": chain.setParagraph().run(); break;+ case "heading-1": chain.setHeading({ level: 1 }).run(); break;+ case "heading-2": chain.setHeading({ level: 2 }).run(); break;+ case "heading-3": chain.setHeading({ level: 3 }).run(); break;+ case "bullet-list": chain.toggleBulletList().run(); break;+ case "ordered-list": chain.toggleOrderedList().run(); break;+ case "task-list": chain.toggleTaskList().run(); break;+ case "blockquote": chain.toggleBlockquote().run(); break;+ case "code-block": chain.setCodeBlock().run(); break;+ case "divider": chain.setHorizontalRule().run(); break;+ case "table": chain.insertTable({ rows: 3, cols: 3, withHeaderRow: true }).run(); break;+ case "attachment":+ chain.run();+ window.requestAnimationFrame(actions.openAttachmentPicker);+ break;+ case "note-link":+ chain.run();+ window.requestAnimationFrame(actions.openNoteLinkPicker);+ break;+ case "external-link":+ chain.run();+ window.requestAnimationFrame(actions.openExternalLinkPicker);+ break;+ }+};++export const createSlashCommandExtension = ({+ actions,+ getLabels,+}: {+ actions: SlashCommandActions;+ getLabels: () => SlashCommandLabels;+}) => Extension.create({+ name: "edgeeverSlashCommand",+ addProseMirrorPlugins() {+ const initialItems = createSlashCommandItems(getLabels());+ return [Suggestion<SlashCommandItem, SlashCommandItem>({+ editor: this.editor,+ pluginKey: slashCommandPluginKey,+ char: "/",+ allowedPrefixes: [" "],+ placement: "bottom-start",+ offset: { mainAxis: 6 },+ decorationClass: "edgeever-slash-command-query",+ initialItems,+ allow: ({ state, range }) => {+ const position = state.doc.resolve(range.from);+ return this.editor.isEditable && position.parent.type.name === "paragraph";+ },+ items: ({ query }) => filterSlashCommandItems(createSlashCommandItems(getLabels()), query),+ command: ({ editor, range, props }) => runSlashCommand({ actions, editor, item: props, range }),+ render: () => {+ let renderer: ReactRenderer<SlashCommandMenuHandle, SlashCommandMenuProps> | null = null;+ let unmount: (() => void) | null = null;+ return {+ onStart: (props) => {+ renderer = new ReactRenderer(SlashCommandMenu, {+ editor: props.editor,+ props: { ...props, labels: getLabels() },+ });+ unmount = props.mount(renderer.element);+ },+ onUpdate: (props) => renderer?.updateProps({ ...props, labels: getLabels() }),+ onKeyDown: (props) => renderer?.ref?.onKeyDown(props) ?? false,+ onExit: () => {+ unmount?.();+ renderer?.destroy();+ unmount = null;+ renderer = null;+ },+ };+ },+ })];+ },+});diff --git a/bun.lock b/bun.lockindex ba2e7ba9..13a26972 100644--- a/bun.lock+++ b/bun.lock@@ -30,6 +30,7 @@"@tiptap/extension-table": "3.27.1","@tiptap/react": "latest","@tiptap/starter-kit": "latest",+ "@tiptap/suggestion": "3.27.1","ai": "^7.0.58","aws4fetch": "^1.0.20","class-variance-authority": "latest",@@ -1304,6 +1305,8 @@"@tiptap/starter-kit": ["@tiptap/[email protected]", "", { "dependencies": { "@tiptap/core": "^3.27.1", "@tiptap/extension-blockquote": "^3.27.1", "@tiptap/extension-bold": "^3.27.1", "@tiptap/extension-bullet-list": "^3.27.1", "@tiptap/extension-code": "^3.27.1", "@tiptap/extension-code-block": "^3.27.1", "@tiptap/extension-document": "^3.27.1", "@tiptap/extension-dropcursor": "^3.27.1", "@tiptap/extension-gapcursor": "^3.27.1", "@tiptap/extension-hard-break": "^3.27.1", "@tiptap/extension-heading": "^3.27.1", "@tiptap/extension-horizontal-rule": "^3.27.1", "@tiptap/extension-italic": "^3.27.1", "@tiptap/extension-link": "^3.27.1", "@tiptap/extension-list": "^3.27.1", "@tiptap/extension-list-item": "^3.27.1", "@tiptap/extension-list-keymap": "^3.27.1", "@tiptap/extension-ordered-list": "^3.27.1", "@tiptap/extension-paragraph": "^3.27.1", "@tiptap/extension-strike": "^3.27.1", "@tiptap/extension-text": "^3.27.1", "@tiptap/extension-underline": "^3.27.1", "@tiptap/extensions": "^3.27.1", "@tiptap/pm": "^3.27.1" } }, "sha512-vfxRsqW8rCc0k4pzo0ilU3wobVi2wqVj88VZI2SlgZlNnUAkrDGDIAph7CTa9k9fshV+O1ivpEgPC5yC046jow=="],+ "@tiptap/suggestion": ["@tiptap/[email protected]", "", { "peerDependencies": { "@floating-ui/dom": "^1.0.0", "@tiptap/core": "3.27.1", "@tiptap/pm": "3.27.1" } }, "sha512-GNBPRav+lAfXzqmmUAS6ylRAn3G8JfsP6XosjoORxJIQJLx1ktDqwp6tm1Vgz9aGIM2TrBxLS1uBbI1Gb2/1VA=="],+"@trickfilm400/rollup-plugin-off-main-thread": ["@trickfilm400/[email protected]", "", { "dependencies": { "ejs": "^3.1.10", "json5": "^2.2.3", "magic-string": "^0.30.21", "string.prototype.matchall": "^4.0.12" } }, "sha512-/67zpWDBLV+oYAEL682s1ktXL0HgqX76f6gaVGkGnVZlBbm1zd0v4Bz8MFF2GGhoX9rvfq3KSQHubFHwa6w6/Q=="],"@tybys/wasm-util": ["@tybys/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-F3fo1MYrRJYL3zER0OUOmkutjr1Vp23m7OsSgp7nq4SP6OqX6C/56XFIPAl5bt3zaBRjmW7SGz3u/6LwFpYcOg=="],diff --git a/package.json b/package.jsonindex b099afe1..0a2e2e44 100644--- a/package.json+++ b/package.json@@ -135,6 +135,7 @@"@tiptap/extension-table": "3.27.1","@tiptap/react": "latest","@tiptap/starter-kit": "latest",+ "@tiptap/suggestion": "3.27.1","ai": "^7.0.58","aws4fetch": "^1.0.20","class-variance-authority": "latest",diff --git a/packages/shared/src/i18n/en-US.ts b/packages/shared/src/i18n/en-US.tsindex e96aa29c..87976df1 100644--- a/packages/shared/src/i18n/en-US.ts+++ b/packages/shared/src/i18n/en-US.ts@@ -1086,6 +1086,19 @@ export const enUS = {publicUnavailable: "This shared note is unavailable",publicUnavailableHint: "The link may be invalid, the owner may have revoked it, or the note may have been deleted.",},+ slashMenu: {+ menu: "Insert menu",+ empty: "No matching commands.",+ close: "Close menu",+ groups: {+ suggested: "Suggested",+ basic: "Basic blocks",+ insert: "Insert",+ },+ items: {+ ai: "Ask AI",+ },+ },editorToolbar: {toolbar: "Editor toolbar",paragraph: "Body",diff --git a/packages/shared/src/i18n/zh-CN.ts b/packages/shared/src/i18n/zh-CN.tsindex 73bb5637..1b7ea44a 100644--- a/packages/shared/src/i18n/zh-CN.ts+++ b/packages/shared/src/i18n/zh-CN.ts@@ -1086,6 +1086,19 @@ export const zhCN = {publicUnavailable: "这篇分享笔记不可用",publicUnavailableHint: "链接可能无效、已被分享者撤销,或原笔记已经删除。",},+ slashMenu: {+ menu: "插入功能菜单",+ empty: "没有匹配的功能。",+ close: "关闭菜单",+ groups: {+ suggested: "建议",+ basic: "基本区块",+ insert: "插入",+ },+ items: {+ ai: "用 AI 处理",+ },+ },editorToolbar: {toolbar: "编辑器工具栏",paragraph: "正文",diff --git a/tests/e2e/ai-custom-prompts.spec.ts b/tests/e2e/ai-custom-prompts.spec.tsindex ba9c3fc5..12908345 100644--- a/tests/e2e/ai-custom-prompts.spec.ts+++ b/tests/e2e/ai-custom-prompts.spec.ts@@ -147,6 +147,36 @@ test.describe("AI custom prompts", () => {await expect(composer).toBeVisible();});+ test("opens the function menu from a bare slash and runs its AI command", async ({ page }) => {+ const memo = await createMemo(page, `e2e-slash-menu-${Date.now()}`, "斜杠菜单测试");+ await ensureAuthenticatedPage(page);+ await page.getByRole("button", { name: new RegExp(notebookName) }).click();+ await page.locator(`[data-memo-id="${memo.id}"]`).locator("button").first().click();+ const editor = page.locator(".ProseMirror[contenteditable='true']");+ await expect(editor).toBeVisible();++ await editor.click();+ await page.keyboard.press("End");+ await page.keyboard.press("Enter");+ await page.keyboard.type("/");+ const slashMenu = page.getByLabel("插入功能菜单");+ await expect(slashMenu).toBeVisible();+ await expect(slashMenu.getByText("基本区块", { exact: true })).toBeVisible();+ await expect(slashMenu.getByText("标题 1", { exact: true })).toBeVisible();++ await page.keyboard.press("ArrowDown");+ await page.keyboard.press("Enter");+ await expect(slashMenu).toBeHidden();+ await expect(editor).not.toContainText("/");++ await page.keyboard.type("/");+ await expect(slashMenu).toBeVisible();+ await slashMenu.getByText("用 AI 处理", { exact: true }).click();+ await expect(slashMenu).toBeHidden();+ await expect(editor).not.toContainText("/");+ await expect(page.getByRole("dialog", { name: "AI 笔记助手" })).toBeVisible();+ });+test("sends temporary files with one AI request", async ({ page }) => {const memo = await createMemo(page, `e2e-ai-attachment-${Date.now()}`, "请结合附件处理。 ");let submittedBody: Record<string, unknown> | null = null;