Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

Feat/editor heading lists (#22762)

Patrick Tienadc3d2435a33
diff --git a/apps/server/src/services/agentDocuments/headlessEditor.test.ts b/apps/server/src/services/agentDocuments/headlessEditor.test.ts
index 7eec01d035f..db799435ba3 100644
--- a/apps/server/src/services/agentDocuments/headlessEditor.test.ts
+++ b/apps/server/src/services/agentDocuments/headlessEditor.test.ts
@@ -49,6 +49,21 @@ describe('agent document headless editor', () => {
expect(hasNodeType(snapshot.editorData, 'mathBlock')).toBe(true);
});
+ it('should round-trip a heading list item between Markdown and editor data', async () => {
+ const markdown = '1. ## Overview\n2. Details\n';
+
+ const fromMarkdown = await createMarkdownEditorSnapshot(markdown);
+ const [overview, details] = (fromMarkdown.editorData as any).root.children[0].children;
+
+ expect(overview.$.listHeading).toBe('h2');
+ expect(details.$.listHeading).toBeUndefined();
+ expect(hasNodeType(fromMarkdown.editorData, 'heading')).toBe(false);
+
+ const fromEditorData = await exportEditorDataSnapshot({ editorData: fromMarkdown.editorData });
+
+ expect(fromEditorData.content).toBe(markdown);
+ });
+
it('should safely serialize concurrent headless document lifecycles', async () => {
const sources = await Promise.all(
Array.from({ length: 6 }, (_, index) =>
diff --git a/apps/server/src/services/agentDocuments/headlessEditor.ts b/apps/server/src/services/agentDocuments/headlessEditor.ts
index 62d484355c7..1edeed5f767 100644
--- a/apps/server/src/services/agentDocuments/headlessEditor.ts
+++ b/apps/server/src/services/agentDocuments/headlessEditor.ts
@@ -8,6 +8,7 @@ import {
indexLiteXMLDocument,
normalizeLiteXMLFragment,
planLiteXMLEditSteps,
+ RichListDocumentPlugin,
} from '@lobechat/editor-runtime';
import type { HeadlessEditorOptions, HeadlessLiteXMLOperation } from '@lobehub/editor/headless';
import { createHeadlessEditor, DEFAULT_HEADLESS_EDITOR_PLUGINS } from '@lobehub/editor/headless';
@@ -113,9 +114,18 @@ const DOCUMENT_HEADLESS_PLUGINS = DEFAULT_HEADLESS_EDITOR_PLUGINS.map(
: plugin,
);
+// Pages hold what PageEditor's own plugins put in them. A headless editor that
+// lacks one of those exports Markdown that disagrees with the page, and drops
+// the plugin's node state when it seeds a collaboration room.
+const PAGE_DOCUMENT_PLUGINS = [RichListDocumentPlugin as unknown as HeadlessEditorPlugin];
+
export const createDocumentHeadlessEditor = (
options?: Pick<HeadlessEditorOptions, 'additionalPlugins'>,
-) => createHeadlessEditor({ ...options, plugins: DOCUMENT_HEADLESS_PLUGINS });
+) =>
+ createHeadlessEditor({
+ additionalPlugins: [...PAGE_DOCUMENT_PLUGINS, ...(options?.additionalPlugins ?? [])],
+ plugins: DOCUMENT_HEADLESS_PLUGINS,
+ });
let headlessEditorTail: Promise<void> = Promise.resolve();
const insideHeadlessEditorLock = new AsyncLocalStorage<true>();
diff --git a/apps/server/src/services/pageCollab/__tests__/fork.test.ts b/apps/server/src/services/pageCollab/__tests__/fork.test.ts
index e17932f796c..58975868fcd 100644
--- a/apps/server/src/services/pageCollab/__tests__/fork.test.ts
+++ b/apps/server/src/services/pageCollab/__tests__/fork.test.ts
@@ -3,6 +3,8 @@ import { createHeadlessEditor } from '@lobehub/editor/headless';
import { describe, expect, it } from 'vitest';
import * as Y from 'yjs';
+import { createDocumentHeadlessEditor } from '@/server/services/agentDocuments/headlessEditor';
+
import { openPageFork, projectPageState } from '../fork';
const editorDataOf = (markdown: string) => {
@@ -13,6 +15,12 @@ const editorDataOf = (markdown: string) => {
return editorData;
};
+// The list items of a page's first block, as the stored editor JSON holds them.
+const listItemStates = (editorData: unknown) =>
+ ((editorData as any).root.children[0].children as any[]).map(
+ ({ $: { listHeading, listNumber } = {} as any }) => ({ listHeading, listNumber }),
+ );
+
const idOf = (litexml: string, text: string) =>
litexml.match(new RegExp(`<p id="(\\w+)">\\s*<span[^>]*>${text}`))?.[1];
@@ -83,4 +91,26 @@ describe('openPageFork', () => {
expect(projected.markdown).toContain('para two');
expect(projected.markdown).toContain('https://example.com/icon.png');
});
+
+ it('seeds a room with heading list items and numbering restarts, and projects them back', async () => {
+ const source = createDocumentHeadlessEditor();
+ source.hydrateMarkdown('1. ## Overview\n2. Details\n3. More\n', { keepId: true });
+ const editorData = source.export().editorData as any;
+ source.destroy();
+ // The page editor stores a restart on the item it was set on.
+ editorData.root.children[0].children[2].$.listNumber = 7;
+
+ const seed = await openPageFork(undefined, editorData);
+ const state = seed.diff();
+ seed.destroy();
+
+ const projected = await projectPageState(state);
+
+ expect(listItemStates(projected.editorData)).toEqual([
+ { listHeading: 'h2', listNumber: undefined },
+ { listHeading: undefined, listNumber: undefined },
+ { listHeading: undefined, listNumber: 7 },
+ ]);
+ expect(projected.markdown).toContain('1. ## Overview\n');
+ });
});
diff --git a/locales/en-US/editor.json b/locales/en-US/editor.json
index 5800b15a3b2..40cbefd9e09 100644
--- a/locales/en-US/editor.json
+++ b/locales/en-US/editor.json
@@ -105,6 +105,11 @@
"link.open": "Open link",
"link.placeholder": "Enter link URL",
"link.unlink": "Unlink",
+ "list.number.continue": "Continue previous numbering",
+ "list.number.continueHeading": "Continue heading numbering",
+ "list.number.restart": "Start new list",
+ "list.number.set": "Set number",
+ "list.number.value": "Change number",
"markdown.cancel": "Cancel",
"markdown.confirm": "Convert",
"markdown.parseMessage": "Convert to Markdown format. Existing content will be overwritten. Are you sure? (Closes automatically in 5 seconds)",
diff --git a/locales/zh-CN/editor.json b/locales/zh-CN/editor.json
index 38c6e7723f4..8122c809c7e 100644
--- a/locales/zh-CN/editor.json
+++ b/locales/zh-CN/editor.json
@@ -105,6 +105,11 @@
"link.open": "打开链接",
"link.placeholder": "输入链接 URL",
"link.unlink": "取消链接",
+ "list.number.continue": "继续之前的编号",
+ "list.number.continueHeading": "继续标题编号",
+ "list.number.restart": "开始新列表",
+ "list.number.set": "设置编号",
+ "list.number.value": "修改编号值",
"markdown.cancel": "取消",
"markdown.confirm": "转换",
"markdown.parseMessage": "将内容转换为 Markdown 格式,会覆盖当前内容且不可撤销。确认继续吗?(5 秒后自动关闭)",
diff --git a/package.json b/package.json
index a3810f01038..649a14fb0d7 100644
--- a/package.json
+++ b/package.json
@@ -229,6 +229,8 @@
"@icons-pack/react-simple-icons": "^13.15.1",
"@khmyznikov/pwa-install": "0.3.9",
"@larksuiteoapi/node-sdk": "^1.73.0",
+ "@lexical/list": "0.42.0",
+ "@lexical/rich-text": "0.42.0",
"@lexical/utils": "^0.42.0",
"@lobechat/agent-address-linq": "workspace:*",
"@lobechat/agent-address-mail": "workspace:*",
diff --git a/packages/editor-runtime/package.json b/packages/editor-runtime/package.json
index cc26b731c22..2e015cc9f69 100644
--- a/packages/editor-runtime/package.json
+++ b/packages/editor-runtime/package.json
@@ -15,9 +15,13 @@
"@lobechat/prompts": "workspace:*"
},
"devDependencies": {
+ "@lexical/list": "0.42.0",
+ "@lexical/rich-text": "0.42.0",
"lexical": "0.42.0"
},
"peerDependencies": {
+ "@lexical/list": "*",
+ "@lexical/rich-text": "*",
"@lobehub/editor": "^7.0.0",
"debug": "*",
"lexical": "*"
diff --git a/packages/editor-runtime/src/index.ts b/packages/editor-runtime/src/index.ts
index 6469f5c96b8..d9d5f7e2ee0 100644
--- a/packages/editor-runtime/src/index.ts
+++ b/packages/editor-runtime/src/index.ts
@@ -4,5 +4,6 @@ export { formatModifyNodesResult } from './formatModifyNodesResult';
export * from './liteXMLBlockDiff';
export * from './liteXMLEditPlan';
export * from './liteXMLWellFormed';
+export * from './richList';
export * from './selectionLiteXML';
export * from './types';
diff --git a/packages/editor-runtime/src/richList/RichListDocumentPlugin.ts b/packages/editor-runtime/src/richList/RichListDocumentPlugin.ts
new file mode 100644
index 00000000000..b405c3ea439
--- /dev/null
+++ b/packages/editor-runtime/src/richList/RichListDocumentPlugin.ts
@@ -0,0 +1,88 @@
+import { ListItemNode } from '@lexical/list';
+import type { LexicalEditor } from 'lexical';
+
+import { listHeadingState } from './headingState';
+import { listNumberState, registerListNumberOverrides } from './listNumbering';
+import { registerRichListMarkdown, type RichListMarkdownService } from './markdown';
+
+// @lobehub/editor's IMarkdownShortCutService. Kernels look services up by this
+// name; the constant itself lives in the package's main entry, which pulls in
+// React and so cannot be imported by modules the server loads.
+const MARKDOWN_SERVICE_ID = { __serviceId: 'MarkdownShortCutService' };
+
+interface ServiceKernel {
+ requireService: (serviceId: { __serviceId: string }) => unknown;
+}
+
+interface RegisteredNodeInternals {
+ sharedNodeState?: { sharedConfigMap?: Map<string, unknown> };
+}
+
+/**
+ * Lexical only treats a node state as its own once the editor has used its
+ * config on a node; until then it is an opaque key. `@lexical/yjs` leaves
+ * opaque keys out when it first writes a node to a room, so an editor that
+ * seeds a room from stored JSON without ever touching these states would drop
+ * them.
+ *
+ * Lexical has no public way to declare a state on a node class it does not
+ * own. Using the configs on a throwaway node would do it, but that is an
+ * update at start-up and takes a node key in editors that load pages with
+ * their stored keys. So this registers the configs where Lexical itself
+ * records them on first use.
+ */
+const knowListItemStates = (editor: LexicalEditor) => {
+ const registered = (editor as unknown as { _nodes: Map<string, RegisteredNodeInternals> })._nodes;
+ const configs = registered?.get(ListItemNode.getType())?.sharedNodeState?.sharedConfigMap;
+ if (!configs) return;
+
+ for (const config of [listHeadingState, listNumberState]) {
+ if (!configs.has(config.key)) configs.set(config.key, config);
+ }
+};
+
+/**
+ * What a document with rich lists needs wherever it is loaded, with or without
+ * a DOM: heading list items in Markdown (`- ### Title`), per-item numbering
+ * restarts, and both list item states surviving a collaboration room.
+ */
+export const registerRichListDocument = (
+ editor: LexicalEditor,
+ markdownService: RichListMarkdownService | null,
+) => {
+ knowListItemStates(editor);
+
+ const unregisterMarkdown = markdownService ? registerRichListMarkdown(markdownService) : () => {};
+ const unregisterNumbering = registerListNumberOverrides(editor);
+
+ return () => {
+ unregisterMarkdown();
+ unregisterNumbering();
+ };
+};
+
+/**
+ * Kernel plugin for editors without the page editor's UI, such as the server's
+ * headless document editor. Register it after ListPlugin and MarkdownPlugin.
+ */
+export class RichListDocumentPlugin {
+ static pluginName = 'LobeRichListDocumentPlugin';
+
+ private cleanup?: () => void;
+ private kernel: ServiceKernel;
+
+ constructor(kernel: ServiceKernel) {
+ this.kernel = kernel;
+ }
+
+ onInit(editor: LexicalEditor): void {
+ const service = this.kernel.requireService(
+ MARKDOWN_SERVICE_ID,
+ ) as RichListMarkdownService | null;
+ this.cleanup = registerRichListDocument(editor, service);
+ }
+
+ destroy(): void {
+ this.cleanup?.();
+ }
+}
diff --git a/packages/editor-runtime/src/richList/headingState.ts b/packages/editor-runtime/src/richList/headingState.ts
new file mode 100644
index 00000000000..f99ccdffabf
--- /dev/null
+++ b/packages/editor-runtime/src/richList/headingState.ts
@@ -0,0 +1,16 @@
+import type { ListItemNode } from '@lexical/list';
+import type { HeadingTagType } from '@lexical/rich-text';
+import { $getState, $setState, createState } from 'lexical';
+
+const HEADING_TAGS = new Set<string>(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']);
+
+/** The heading level a list item is styled as; unset for a plain item. */
+export const listHeadingState = createState('listHeading', {
+ parse: (value) =>
+ typeof value === 'string' && HEADING_TAGS.has(value) ? (value as HeadingTagType) : undefined,
+});
+
+export const $getListItemHeading = (item: ListItemNode) => $getState(item, listHeadingState);
+
+export const $setListItemHeading = (item: ListItemNode, tag: HeadingTagType | undefined) =>
+ $setState(item, listHeadingState, tag);
diff --git a/packages/editor-runtime/src/richList/index.ts b/packages/editor-runtime/src/richList/index.ts
new file mode 100644
index 00000000000..86a75e84693
--- /dev/null
+++ b/packages/editor-runtime/src/richList/index.ts
@@ -0,0 +1,10 @@
+export { $getListItemHeading, $setListItemHeading, listHeadingState } from './headingState';
+export {
+ $continueListNumbering,
+ $getListNumbering,
+ $setListItemNumber,
+ type ListNumbering,
+ listNumberState,
+} from './listNumbering';
+export { type RichListMarkdownService } from './markdown';
+export { registerRichListDocument, RichListDocumentPlugin } from './RichListDocumentPlugin';
diff --git a/packages/editor-runtime/src/richList/listNumbering.test.ts b/packages/editor-runtime/src/richList/listNumbering.test.ts
new file mode 100644
index 00000000000..7d613f5bad1
--- /dev/null
+++ b/packages/editor-runtime/src/richList/listNumbering.test.ts
@@ -0,0 +1,126 @@
+import { $isListItemNode, $isListNode, type ListItemNode } from '@lexical/list';
+import { CommonPlugin, Kernel, ListPlugin, MarkdownPlugin } from '@lobehub/editor';
+import { $getRoot, $getSelection, $isRangeSelection, type LexicalEditor } from 'lexical';
+import { describe, expect, it } from 'vitest';
+
+import { $continueListNumbering, $getListNumbering, $setListItemNumber } from './listNumbering';
+import { RichListDocumentPlugin } from './RichListDocumentPlugin';
+
+const setup = (markdown: string) => {
+ const kernel = new Kernel();
+ kernel.registerPlugins([
+ CommonPlugin,
+ MarkdownPlugin,
+ ListPlugin,
+ RichListDocumentPlugin as never,
+ ]);
+ const editor = kernel.initNodeEditor()!;
+ kernel.setDocument('markdown', markdown);
+ return editor;
+};
+
+// The numbered items of every top-level list, by text.
+const $items = (): Record<string, ListItemNode> =>
+ Object.fromEntries(
+ $getRoot()
+ .getChildren()
+ .filter($isListNode)
+ .flatMap((list) => list.getChildren().filter($isListItemNode))
+ .map((item) => [item.getTextContent(), item]),
+ );
+
+const act = (editor: LexicalEditor, fn: (items: Record<string, ListItemNode>) => void) =>
+ editor.update(() => fn($items()), { discrete: true });
+
+const numbers = (editor: LexicalEditor) =>
+ editor
+ .getEditorState()
+ .read(() => Object.entries($items()).map(([text, item]) => `${item.getValue()}. ${text}`));
+
+describe('list numbering', () => {
+ it('restarts numbering from a middle item and keeps the items after it in step', () => {
+ const editor = setup('1. a\n2. b\n3. c\n');
+
+ act(editor, (items) => $setListItemNumber(items.b, 5));
+
+ expect(numbers(editor)).toEqual(['1. a', '5. b', '6. c']);
+ });
+
+ it('sets the list start when the first item is renumbered', () => {
+ const editor = setup('1. a\n2. b\n');
+
+ act(editor, (items) => $setListItemNumber(items.a, 4));
+
+ expect(numbers(editor)).toEqual(['4. a', '5. b']);
+ });
+
+ it('starts a new list at an item, and continuing drops the restart again', () => {
+ const editor = setup('1. a\n2. b\n3. c\n');
+
+ act(editor, (items) => $setListItemNumber(items.b, 1));
+ expect(numbers(editor)).toEqual(['1. a', '1. b', '2. c']);
+
+ act(editor, (items) => $continueListNumbering(items.b));
+ expect(numbers(editor)).toEqual(['1. a', '2. b', '3. c']);
+ });
+
+ it('does not repeat a restart on the item Enter splits off', () => {
+ const editor = setup('1. a\n2. b\n');
+ act(editor, (items) => $setListItemNumber(items.b, 7));
+
+ editor.update(
+ () => {
+ $items().b.selectEnd();
+ const selection = $getSelection();
+ if ($isRangeSelection(selection)) {
+ selection.insertParagraph();
+ selection.insertText('c');
+ }
+ },
+ { discrete: true },
+ );
+
+ expect(numbers(editor)).toEqual(['1. a', '7. b', '8. c']);
+ });
+
+ it('keeps a restart on each of two items in a row', () => {
+ const editor = setup('1. a\n2. b\n3. c\n');
+
+ act(editor, (items) => $setListItemNumber(items.b, 1));
+ act(editor, (items) => $setListItemNumber(items.c, 1));
+
+ expect(numbers(editor)).toEqual(['1. a', '1. b', '1. c']);
+ });
+
+ it('continues the numbering of the previous list across other blocks', () => {
+ const editor = setup('1. a\n2. b\n\nbetween\n\n1. c\n2. d\n');
+
+ expect(editor.getEditorState().read(() => $getListNumbering($items().c).canContinue)).toBe(
+ true,
+ );
+ act(editor, (items) => $continueListNumbering(items.c));
+
+ expect(numbers(editor)).toEqual(['1. a', '2. b', '3. c', '4. d']);
+ });
+
+ it('continues heading numbering from earlier items of the same heading level', () => {
+ const editor = setup('1. ## Intro\n\nbody\n\n1. step\n2. step two\n\nmore\n\n1. ## Method\n');
+
+ const numbering = editor.getEditorState().read(() => $getListNumbering($items().Method));
+ expect(numbering).toEqual({ canContinue: true, isHeading: true, value: 1 });
+
+ act(editor, (items) => $continueListNumbering(items.Method));
+
+ expect(numbers(editor)).toEqual(['1. Intro', '1. step', '2. step two', '2. Method']);
+ });
+
+ it('offers nothing to continue for a first list or an item already in sequence', () => {
+ const editor = setup('1. a\n2. b\n');
+
+ const numbering = editor
+ .getEditorState()
+ .read(() => [$getListNumbering($items().a), $getListNumbering($items().b)]);
+
+ expect(numbering.map((n) => n.canContinue)).toEqual([false, false]);
+ });
+});
diff --git a/packages/editor-runtime/src/richList/listNumbering.ts b/packages/editor-runtime/src/richList/listNumbering.ts
new file mode 100644
index 00000000000..e7fd87cd90c
--- /dev/null
+++ b/packages/editor-runtime/src/richList/listNumbering.ts
@@ -0,0 +1,147 @@
+import { $isListItemNode, $isListNode, type ListItemNode, ListNode } from '@lexical/list';
+import {
+ $getNodeByKey,
+ $getState,
+ $setState,
+ createState,
+ type LexicalEditor,
+ type LexicalNode,
+} from 'lexical';
+
+import { $getListItemHeading } from './headingState';
+
+/**
+ * A number a list item restarts its list's numbering at.
+ *
+ * Lexical merges adjacent lists of the same type, so a list cannot be split to
+ * renumber from an item in its middle. The item carries the number instead and
+ * the transform below applies it.
+ */
+export const listNumberState = createState('listNumber', {
+ parse: (value) =>
+ typeof value === 'number' && Number.isInteger(value) && value >= 0 ? value : undefined,
+});
+
+// An item that only holds a nested list has no number of its own.
+const isWrapperItem = (node: LexicalNode): boolean =>
+ $isListItemNode(node) && $isListNode(node.getFirstChild());
+
+const numberedItems = (list: ListNode): ListItemNode[] =>
+ list
+ .getChildren()
+ .filter((child): child is ListItemNode => $isListItemNode(child) && !isWrapperItem(child));
+
+const $isFirstNumberedItem = (item: ListItemNode) =>
+ item
+ .getPreviousSiblings()
+ .every((sibling) => !$isListItemNode(sibling) || isWrapperItem(sibling));
+
+/**
+ * Renumbers ordered lists honouring per-item restarts. Runs after Lexical's own
+ * list transform, which numbers items from the list start alone.
+ */
+export const registerListNumberOverrides = (editor: LexicalEditor) =>
+ editor.registerNodeTransform(ListNode, (list) => {
+ if (list.getListType() !== 'number') return;
+
+ // The state before this update: a node missing from it was made just now.
+ const before = editor.getEditorState();
+ const existed = (node: LexicalNode) => before.read(() => $getNodeByKey(node.getKey()) !== null);
+
+ let value = list.getStart();
+ let previous: ListItemNode | undefined;
+
+ for (const child of list.getChildren()) {
+ if (!$isListItemNode(child)) continue;
+ if (isWrapperItem(child)) {
+ if (child.getValue() !== value) child.setValue(value);
+ continue;
+ }
+
+ let override = $getState(child, listNumberState);
+ // Enter copies an item together with its state; the copy continues the
+ // numbering instead of restarting it a second time. Only a new item
+ // right after an older one with the same restart is such a copy: two
+ // older items were each restarted on purpose, and two new ones arrived
+ // together (a paste, a loaded document) already holding what they mean.
+ if (
+ override !== undefined &&
+ previous &&
+ override === $getState(previous, listNumberState) &&
+ !existed(child) &&
+ existed(previous)
+ ) {
+ $setState(child, listNumberState, undefined);
+ override = undefined;
+ }
+ if (override !== undefined) value = override;
+ if (child.getValue() !== value) child.setValue(value);
+
+ previous = child;
+ value += 1;
+ }
+ });
+
+/**
+ * The last number an earlier ordered list gave an item of the same kind: a
+ * heading item continues earlier heading items of its level, a plain item
+ * earlier plain items.
+ */
+const $findPreviousNumber = (item: ListItemNode): number | undefined => {
+ const list = item.getParent();
+ if (!$isListNode(list)) return;
+ const heading = $getListItemHeading(item);
+
+ for (const sibling of list.getPreviousSiblings().reverse()) {
+ if (!$isListNode(sibling) || sibling.getListType() !== 'number') continue;
+ const match = numberedItems(sibling).findLast(
+ (candidate) => $getListItemHeading(candidate) === heading,
+ );
+ if (match) return match.getValue();
+ }
+};
+
+export interface ListNumbering {
+ /** Whether "continue numbering" changes anything. */
+ canContinue: boolean;
+ isHeading: boolean;
+ value: number;
+}
+
+export const $getListNumbering = (item: ListItemNode): ListNumbering => ({
+ canContinue: $isFirstNumberedItem(item)
+ ? $findPreviousNumber(item) !== undefined
+ : $getState(item, listNumberState) !== undefined,
+ isHeading: $getListItemHeading(item) !== undefined,
+ value: item.getValue(),
+});
+
+/** Number the item (and the items after it) from `value`. */
+export const $setListItemNumber = (item: ListItemNode, value: number) => {
+ const list = item.getParent();
+ if (!$isListNode(list)) return;
+
+ if ($isFirstNumberedItem(item)) {
+ $setState(item, listNumberState, undefined);
+ list.setStart(value);
+ } else {
+ $setState(item, listNumberState, value);
+ }
+ // Renumber even when only the item's state changed.
+ list.getWritable();
+};
+
+/**
+ * The first item continues the numbering of an earlier list; any other item
+ * drops its restart and continues the item above it.
+ */
+export const $continueListNumbering = (item: ListItemNode) => {
+ if (!$isFirstNumberedItem(item)) {
+ $setState(item, listNumberState, undefined);
+ item.getParent()?.getWritable();
+ return;
+ }
+
+ const previous = $findPreviousNumber(item);
+ if (previous !== undefined) $setListItemNumber(item, previous + 1);
+};
diff --git a/packages/editor-runtime/src/richList/markdown.ts b/packages/editor-runtime/src/richList/markdown.ts
new file mode 100644
index 00000000000..5c8c2be74c6
--- /dev/null
+++ b/packages/editor-runtime/src/richList/markdown.ts
@@ -0,0 +1,97 @@
+import { $isListItemNode, ListItemNode } from '@lexical/list';
+import type { LexicalNode } from 'lexical';
+
+import { $getListItemHeading } from './headingState';
+
+type MarkdownWriter = (
+ ctx: {
+ addProcessor: (processor: (before: string, content: string, after: string) => string) => void;
+ },
+ node: LexicalNode,
+) => void | boolean;
+
+/**
+ * The part of @lobehub/editor's markdown service the rich list needs.
+ * `markdownWriters` is the writer table it serialises with; it is not part of
+ * the service's exported interface.
+ */
+export interface RichListMarkdownService {
+ markdownWriters: Record<string, MarkdownWriter>;
+ registerMarkdownReader: (type: string, reader: never, level?: number) => void;
+}
+
+// @lobehub/editor's MARKDOWN_READER_LEVEL_HIGH. The package's main entry pulls
+// in React, so modules the server loads cannot import the constant from it.
+const MARKDOWN_READER_LEVEL_HIGH = 1;
+
+interface ReadNode {
+ [key: string]: unknown;
+ children?: ReadNode[];
+ type: string;
+}
+
+/** `- ### Title`: the item's heading level follows its list marker. */
+const patchListItemWriter = (service: RichListMarkdownService) => {
+ const type = ListItemNode.getType();
+ const write = service.markdownWriters[type];
+ if (!write) return () => {};
+
+ const patched: MarkdownWriter = (ctx, node) => {
+ const tag = $isListItemNode(node) ? $getListItemHeading(node) : undefined;
+ if (tag) {
+ const hashes = `${'#'.repeat(Number(tag.slice(1)))} `;
+ ctx.addProcessor((before, content, after) => `${before}${hashes}${content}${after}`);
+ }
+ return write(ctx, node);
+ };
+ service.markdownWriters[type] = patched;
+
+ return () => {
+ if (service.markdownWriters[type] === patched) service.markdownWriters[type] = write;
+ };
+};
+
+const readListItem = (
+ children: ReadNode[],
+ index: number,
+ { checked, heading }: { checked?: unknown; heading?: unknown } = {},
+): ReadNode => ({
+ checked: typeof checked === 'boolean' ? checked : undefined,
+ children,
+ direction: 'ltr',
+ format: '',
+ indent: 0,
+ type: 'listitem',
+ value: index + 1,
+ version: 1,
+ ...(heading ? { $: { listHeading: heading } } : {}),
+});
+
+/**
+ * Reads `- ### Title` back into a heading list item. Items without a heading
+ * fall through to ListPlugin's reader.
+ */
+const listItemReader = (node: { checked?: unknown }, children: ReadNode[], index: number) => {
+ if (!children.some((child) => child.type === 'heading')) return false;
+
+ return children.map((child) => {
+ if (child.type === 'heading')
+ return readListItem(child.children ?? [], index, {
+ checked: node.checked,
+ heading: child.tag,
+ });
+ if (child.type === 'paragraph')
+ return readListItem(child.children ?? [], index, { checked: node.checked });
+ if (child.type === 'list') return readListItem([child], index);
+ return child;
+ });
+};
+
+/**
+ * Makes the markdown service read and write heading list items. Register it
+ * after ListPlugin, whose list item writer it wraps.
+ */
+export const registerRichListMarkdown = (service: RichListMarkdownService) => {
+ service.registerMarkdownReader('listItem', listItemReader as never, MARKDOWN_READER_LEVEL_HIGH);
+ return patchListItemWriter(service);
+};
diff --git a/packages/locales/src/default/editor.ts b/packages/locales/src/default/editor.ts
index 0d97ad2a017..60dde7e7cfd 100644
--- a/packages/locales/src/default/editor.ts
+++ b/packages/locales/src/default/editor.ts
@@ -31,6 +31,11 @@ export default {
'link.open': 'Open link',
'link.placeholder': 'Enter link URL',
'link.unlink': 'Unlink',
+ 'list.number.continue': 'Continue previous numbering',
+ 'list.number.continueHeading': 'Continue heading numbering',
+ 'list.number.restart': 'Start new list',
+ 'list.number.set': 'Set number',
+ 'list.number.value': 'Change number',
'markdown.cancel': 'Cancel',
'markdown.confirm': 'Convert',
'markdown.parseMessage':
diff --git a/src/features/EditorCanvas/InternalEditor.readonly.test.tsx b/src/features/EditorCanvas/InternalEditor.readonly.test.tsx
index 45168e8248f..14549ce6fce 100644
--- a/src/features/EditorCanvas/InternalEditor.readonly.test.tsx
+++ b/src/features/EditorCanvas/InternalEditor.readonly.test.tsx
@@ -66,6 +66,13 @@ vi.mock('@/features/ChatInput/InputEditor/plugins', () => ({
createChatInputRichPlugins: () => [],
}));
+vi.mock('./richList/RichListPlugin', () => ({
+ LIST_HEADING_ATTRIBUTE: 'data-list-heading',
+ ReactRichListPlugin: vi.fn(),
+}));
+
+vi.mock('./richList/OrderedListNumberMenu', () => ({ default: () => null }));
+
vi.mock('./rehostImage', () => ({ needsImageRehost: () => true, rehostImage: vi.fn() }));
vi.mock('./InlineToolbar', () => ({
diff --git a/src/features/EditorCanvas/InternalEditor.tsx b/src/features/EditorCanvas/InternalEditor.tsx
index 62e46a5755d..5a84b952ddc 100644
--- a/src/features/EditorCanvas/InternalEditor.tsx
+++ b/src/features/EditorCanvas/InternalEditor.tsx
@@ -16,7 +16,7 @@ import {
ReactVideoPlugin,
} from '@lobehub/editor';
import { Editor, useEditorState } from '@lobehub/editor/react';
-import { createStaticStyles } from '@lobehub/ui';
+import { createStaticStyles, cx } from '@lobehub/ui';
import isEqual from 'fast-deep-equal';
import type { CSSProperties, RefObject } from 'react';
import { memo, useCallback, useEffect, useMemo, useRef } from 'react';
@@ -33,6 +33,8 @@ import { registerBlockDecoratorCaretGuard } from './registerBlockDecoratorCaretG
import { registerBlockDecoratorClickToWrite } from './registerBlockDecoratorClickToWrite';
import { registerImageFilePastePreference } from './registerImageFilePastePreference';
import { needsImageRehost, rehostImage } from './rehostImage';
+import OrderedListNumberMenu from './richList/OrderedListNumberMenu';
+import { LIST_HEADING_ATTRIBUTE, ReactRichListPlugin } from './richList/RichListPlugin';
import { useFileUpload, useImageUpload } from './useImageUpload';
interface FileFilter {
@@ -59,6 +61,94 @@ const fileNodeStyles = createStaticStyles(({ css }) => ({
`,
}));
+// A bullet item's marker at a given nesting depth. Lexical nests a list inside a
+// `.editor_listItemNested` item; items holding only a nested list, and check
+// list items, draw no bullet. `ul` outranks @lobehub/editor's own `-` marker rule.
+const bullet = (depth: number) =>
+ `${'.editor_listItemNested '.repeat(depth)}ul.editor_listUnordered > .editor_listItem:not(:has(ul), [role='checkbox'])::before`;
+
+// Notion-style list markers in the theme color: a solid disc, then a hollow
+// circle, then a square, repeating with depth; ordered list numbers match.
+// A text color applied to the item still colors its marker.
+const listMarkerStyles = createStaticStyles(({ css, cssVar }) => {
+ // Resolved on the item itself, where Lexical sets `--listitem-marker-color`.
+ const markerColor = `var(--listitem-marker-color, ${cssVar.colorPrimary})`;
+ const markerSize = '0.375em';
+
+ return {
+ content: css`
+ ol.editor_listOrdered > .editor_listItem::marker {
+ color: ${markerColor};
+ }
+
+ ${bullet(0)}, ${bullet(3)} {
+ content: '';
+
+ display: inline-block;
+
+ box-sizing: border-box;
+ width: ${markerSize};
+ height: ${markerSize};
+ margin-inline: -0.9em calc(0.9em - ${markerSize});
+ border-radius: 50%;
+
+ vertical-align: middle;
+
+ opacity: 1;
+ background: ${markerColor};
+ }
+
+ ${bullet(1)}, ${bullet(4)} {
+ border: 0.09em solid ${markerColor};
+ background: transparent;
+ }
+
+ ${bullet(2)}, ${bullet(5)} {
+ border: none;
+ border-radius: 0.06em;
+ background: ${markerColor};
+ }
+
+ /* A list item styled as a heading takes the heading's type scale
+ (@lobehub/editor's header styles); its marker scales with it. */
+ .editor_listItem[${LIST_HEADING_ATTRIBUTE}] {
+ margin-block-start: max(
+ calc(var(--lobe-markdown-header-multiple) * var(--lobe-markdown-margin-multiple) * 0.4em),
+ var(--lobe-markdown-font-size)
+ );
+ /* Indent by the body font, so heading items line up with plain ones. */
+ margin-inline-start: var(--lobe-markdown-font-size);
+ font-weight: bold;
+ line-height: 1.25;
+ }
+
+ .editor_listItem[${LIST_HEADING_ATTRIBUTE}='h1'] {
+ font-size: calc(
+ var(--lobe-markdown-font-size) * (1 + 1.5 * var(--lobe-markdown-header-multiple))
+ );
+ }
+
+ .editor_listItem[${LIST_HEADING_ATTRIBUTE}='h2'] {
+ font-size: calc(
+ var(--lobe-markdown-font-size) * (1 + var(--lobe-markdown-header-multiple))
+ );
+ }
+
+ .editor_listItem[${LIST_HEADING_ATTRIBUTE}='h3'] {
+ font-size: calc(
+ var(--lobe-markdown-font-size) * (1 + 0.5 * var(--lobe-markdown-header-multiple))
+ );
+ }
+
+ .editor_listItem[${LIST_HEADING_ATTRIBUTE}='h4'] {
+ font-size: calc(
+ var(--lobe-markdown-font-size) * (1 + 0.25 * var(--lobe-markdown-header-multiple))
+ );
+ }
+ `,
+ };
+});
+
/**
* Base plugins for the editor (without image and toolbar, which need dynamic config)
*/
@@ -75,6 +165,8 @@ const STATIC_PLUGINS = [
ReactAlertPlugin,
ReactFootnotePlugin,
ReactChartPlugin,
+ // After ReactListPlugin (in the rich plugins above), whose markdown it extends.
+ ReactRichListPlugin,
];
const EDITOR_INIT_DATA_SOURCE_TYPES = ['json', 'markdown'] as const;
@@ -397,32 +489,35 @@ const InternalEditor = memo<InternalEditorProps>(
}, [contentChangeLockRef, disabled, editor]); // Only depend on stable refs and editor
return (
- <div
- className={className}
- style={wrapperStyle}
- onClick={(e) => {
- e.stopPropagation();
- e.preventDefault();
- }}
- >
- <Editor
- content={''}
- editable={editable && !disabled}
- editor={editor}
- getPopupContainer={getPopupContainer}
- mentionOption={mentionOption}
- placeholder={finalPlaceholder}
- plugins={plugins}
- slashOption={slashItems ? { items: slashItems } : undefined}
- type={'text'}
- style={{
- paddingBottom: 32,
- ...style,
- ...contentStyle,
+ <>
+ <div
+ className={cx(listMarkerStyles.content, className)}
+ style={wrapperStyle}
+ onClick={(e) => {
+ e.stopPropagation();
+ e.preventDefault();
}}
- {...(onPressEnter ? { onPressEnter } : {})}
- />
- </div>
+ >
+ <Editor
+ content={''}
+ editable={editable && !disabled}
+ editor={editor}
+ getPopupContainer={getPopupContainer}
+ mentionOption={mentionOption}
+ placeholder={finalPlaceholder}
+ plugins={plugins}
+ slashOption={slashItems ? { items: slashItems } : undefined}
+ type={'text'}
+ style={{
+ paddingBottom: 32,
+ ...style,
+ ...contentStyle,
+ }}
+ {...(onPressEnter ? { onPressEnter } : {})}
+ />
+ </div>
+ {editable && !disabled && <OrderedListNumberMenu editor={editor} />}
+ </>
);
},
);
diff --git a/src/features/EditorCanvas/index.ts b/src/features/EditorCanvas/index.ts
index 9e5ee34724a..abd14c7d8e0 100644
--- a/src/features/EditorCanvas/index.ts
+++ b/src/features/EditorCanvas/index.ts
@@ -7,5 +7,6 @@ export {
type EditorCanvasWithEditorProps,
} from './EditorCanvas';
export { default as InlineToolbar, type InlineToolbarProps } from './InlineToolbar';
+export { requestListNumberMenu } from './richList/numberMenuRequest';
export { TypoBar } from './TypoBar';
export { useImageUpload } from './useImageUpload';
diff --git a/src/features/EditorCanvas/richList/OrderedListNumberMenu.test.ts b/src/features/EditorCanvas/richList/OrderedListNumberMenu.test.ts
new file mode 100644
index 00000000000..87cf2106545
--- /dev/null
+++ b/src/features/EditorCanvas/richList/OrderedListNumberMenu.test.ts
@@ -0,0 +1,25 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { submitNumberOnEnter } from './OrderedListNumberMenu';
+
+describe('submitNumberOnEnter', () => {
+ it('applies the number and cancels the Enter so the editor does not split the item', () => {
+ const event = { preventDefault: vi.fn() };
+ const onSetValue = vi.fn();
+
+ submitNumberOnEnter(event, 5, onSetValue);
+
+ expect(onSetValue).toHaveBeenCalledWith(5);
+ expect(event.preventDefault).toHaveBeenCalled();
+ });
+
+ it.each([null, -1, 2.5])('ignores %s but still cancels the Enter', (value) => {
+ const event = { preventDefault: vi.fn() };
+ const onSetValue = vi.fn();
+
+ submitNumberOnEnter(event, value, onSetValue);
+
+ expect(onSetValue).not.toHaveBeenCalled();
+ expect(event.preventDefault).toHaveBeenCalled();
+ });
+});
diff --git a/src/features/EditorCanvas/richList/OrderedListNumberMenu.tsx b/src/features/EditorCanvas/richList/OrderedListNumberMenu.tsx
new file mode 100644
index 00000000000..6dc0fecddc6
--- /dev/null
+++ b/src/features/EditorCanvas/richList/OrderedListNumberMenu.tsx
@@ -0,0 +1,303 @@
+'use client';
+
+import { $isListItemNode, type ListItemNode } from '@lexical/list';
+import {
+ $continueListNumbering,
+ $getListNumbering,
+ $setListItemNumber,
+ type ListNumbering,
+} from '@lobechat/editor-runtime';
+import type { IEditor } from '@lobehub/editor';
+import { Button, Flexbox, InputNumber, Popover, Text, Tooltip } from '@lobehub/ui';
+import { cssVar as vars } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { $getNearestNodeFromDOMNode, $getNodeByKey } from 'lexical';
+import { type CSSProperties, memo, useEffect, useRef, useState } from 'react';
+import { createPortal } from 'react-dom';
+import { useTranslation } from 'react-i18next';
+
+import { sx } from '@/styles/sx';
+
+import { findOrderedItemNear } from './markerHitTest';
+import { onListNumberMenuRequest } from './numberMenuRequest';
+
+const styles = stylex.create({
+ item: { justifyContent: 'flex-start', paddingInline: 8 },
+ // The popover anchors to this box, so it carries the position.
+ anchor: { display: 'block', position: 'fixed', zIndex: 10 },
+ marker: {
+ // The button only exists while the number is hovered.
+ backgroundColor: vars.colorPrimaryBgHover,
+ borderRadius: vars.borderRadiusSM,
+ borderStyle: 'none',
+ cursor: 'pointer',
+ display: 'block',
+ height: '100%',
+ paddingBlock: 0,
+ paddingInlineStart: 0,
+ textAlign: 'end',
+ whiteSpace: 'nowrap',
+ width: '100%',
+ },
+ valueRow: { paddingBlock: 4, paddingInline: 8 },
+});
+
+interface MarkerRect {
+ height: number;
+ left: number;
+ top: number;
+ width: number;
+}
+
+interface Marker {
+ key: string;
+ label: string;
+ rect: MarkerRect;
+ style: CSSProperties;
+}
+
+let measureContext: CanvasRenderingContext2D | null | undefined;
+
+const measure = (text: string, font: string, fallback: number) => {
+ measureContext ??= document.createElement('canvas').getContext('2d');
+ if (!measureContext) return fallback;
+ measureContext.font = font;
+ return measureContext.measureText(text).width;
+};
+
+/**
+ * The `::marker` box is not in the DOM and cannot take a background, so the
+ * button covering it redraws the number: same box, font and color, on top of
+ * the highlight.
+ */
+const getMarker = (li: HTMLLIElement): Omit<Marker, 'key'> => {
+ const range = document.createRange();
+ range.selectNodeContents(li);
+ const itemRect = li.getBoundingClientRect();
+ const line = range.getClientRects()[0] ?? itemRect;
+ const itemStyle = getComputedStyle(li);
+ const markerStyle = getComputedStyle(li, '::marker');
+ const fontSize = Number.parseFloat(itemStyle.fontSize);
+ const font = `${itemStyle.fontWeight} ${itemStyle.fontSize} ${itemStyle.fontFamily}`;
+
+ const label = `${li.value}.`;
+ // The marker reads "1. " and ends where the item's text starts.
+ const gap = measure(' ', font, fontSize * 0.3);
+ const width = measure(label, font, fontSize) + gap + 6;
+
+ return {
+ label,
+ rect: { height: line.height, left: itemRect.left - width, top: line.top, width },
+ style: {
+ color: markerStyle.color,
+ fontFamily: itemStyle.fontFamily,
+ fontSize: itemStyle.fontSize,
+ fontWeight: itemStyle.fontWeight as CSSProperties['fontWeight'],
+ lineHeight: `${line.height}px`,
+ paddingInlineEnd: gap,
+ },
+ };
+};
+
+const contains = (rect: MarkerRect, x: number, y: number) =>
+ x >= rect.left && x <= rect.left + rect.width && y >= rect.top && y <= rect.top + rect.height;
+
+const findMarkerItem = (root: HTMLElement, x: number, y: number) => {
+ const bounds = root.getBoundingClientRect();
+ // Markers hang outside the item, up to a few characters left of the root.
+ if (y < bounds.top || y > bounds.bottom || x < bounds.left - 64 || x > bounds.right) return;
+
+ const li = findOrderedItemNear(root, x, y);
+ if (!li) return;
+ const marker = getMarker(li);
+ if (contains(marker.rect, x, y)) return { li, marker };
+};
+
+/**
+ * Applies a valid number typed in the menu. The Enter is cancelled whether or
+ * not it applies: closing the menu hands focus back to the editor while this
+ * keydown still runs, and an uncancelled Enter splits the item at the caret.
+ */
+export const submitNumberOnEnter = (
+ event: { preventDefault: () => void },
+ value: number | null,
+ onSetValue: (value: number) => void,
+) => {
+ event.preventDefault();
+ if (value !== null && Number.isInteger(value) && value >= 0) onSetValue(value);
+};
+
+interface NumberMenuContentProps {
+ numbering: ListNumbering;
+ onContinue: () => void;
+ onRestart: () => void;
+ onSetValue: (value: number) => void;
+}
+
+const NumberMenuContent = memo<NumberMenuContentProps>(
+ ({ numbering, onContinue, onRestart, onSetValue }) => {
+ const { t } = useTranslation('editor');
+ const [value, setValue] = useState<number | null>(numbering.value);
+
+ return (
+ <Flexbox gap={2}>
+ <Button
+ block
+ className={stylex.props(styles.item).className}
+ disabled={!numbering.canContinue}
+ type="text"
+ onClick={onContinue}
+ >
+ {numbering.isHeading ? t('list.number.continueHeading') : t('list.number.continue')}
+ </Button>
+ <Flexbox
+ horizontal
+ align="center"
+ gap={8}
+ justify="space-between"
+ {...stylex.props(styles.valueRow)}
+ >
+ <Text>{t('list.number.value')}</Text>
+ <InputNumber
+ autoFocus
+ min={0}
+ precision={0}
+ size="small"
+ style={{ width: 72 }}
+ value={value}
+ onChange={setValue}
+ onPressEnter={(event) => submitNumberOnEnter(event, value, onSetValue)}
+ />
+ </Flexbox>
+ <Button
+ block
+ className={stylex.props(styles.item).className}
+ type="text"
+ onClick={onRestart}
+ >
+ {t('list.number.restart')}
+ </Button>
+ </Flexbox>
+ );
+ },
+);
+
+NumberMenuContent.displayName = 'NumberMenuContent';
+
+/**
+ * A menu on an ordered list's number to continue earlier numbering, set the
+ * number, or start a new list there. With the pointer: hovering the number
+ * highlights it and clicking opens the menu. Without it: `requestListNumberMenu`
+ * (the slash menu's "Set number") opens the menu on the caret's item.
+ */
+const OrderedListNumberMenu = memo<{ editor: IEditor }>(({ editor }) => {
+ const { t } = useTranslation('editor');
+ const [marker, setMarker] = useState<Marker>();
+ const [open, setOpen] = useState(false);
+ // A menu opened from the keyboard gives the caret back when it closes.
+ const openedFromKeyboard = useRef(false);
+
+ useEffect(
+ () =>
+ onListNumberMenuRequest(editor, (key) => {
+ const li = editor.getLexicalEditor?.()?.getElementByKey(key);
+ if (!(li instanceof HTMLLIElement)) return;
+ openedFromKeyboard.current = true;
+ setMarker({ key, ...getMarker(li) });
+ setOpen(true);
+ }),
+ [editor],
+ );
+
+ useEffect(() => {
+ if (open) return;
+
+ let frame = 0;
+ const onMove = (event: MouseEvent) => {
+ cancelAnimationFrame(frame);
+ frame = requestAnimationFrame(() => {
+ // The Lexical editor exists only once <Editor> has mounted.
+ const lexical = editor.getLexicalEditor?.();
+ const root = lexical?.getRootElement();
+ const hit = root ? findMarkerItem(root, event.clientX, event.clientY) : undefined;
+ const key = hit && lexical?.read(() => $getNearestNodeFromDOMNode(hit.li)?.getKey());
+ setMarker(hit && key ? { key, ...hit.marker } : undefined);
+ });
+ };
+ const onScroll = () => setMarker(undefined);
+
+ document.addEventListener('mousemove', onMove);
+ document.addEventListener('scroll', onScroll, true);
+
+ return () => {
+ cancelAnimationFrame(frame);
+ document.removeEventListener('mousemove', onMove);
+ document.removeEventListener('scroll', onScroll, true);
+ };
+ }, [editor, open]);
+
+ const lexical = editor.getLexicalEditor?.();
+ if (!lexical || !marker) return null;
+
+ const numbering = lexical.read(() => {
+ const node = $getNodeByKey(marker.key);
+ return $isListItemNode(node) ? $getListNumbering(node) : undefined;
+ });
+ if (!numbering) return null;
+
+ const close = () => {
+ setOpen(false);
+ setMarker(undefined);
+ if (openedFromKeyboard.current) {
+ openedFromKeyboard.current = false;
+ lexical.focus();
+ }
+ };
+
+ const update = (fn: (item: ListItemNode) => void) => {
+ lexical.update(() => {
+ const node = $getNodeByKey(marker.key);
+ if ($isListItemNode(node)) fn(node);
+ });
+ close();
+ };
+
+ const { height, left, top, width } = marker.rect;
+
+ return createPortal(
+ <Popover
+ arrow={false}
+ open={open}
+ placement="bottomLeft"
+ trigger="click"
+ content={
+ <NumberMenuContent
+ numbering={numbering}
+ onContinue={() => update($continueListNumbering)}
+ onRestart={() => update((item) => $setListItemNumber(item, 1))}
+ onSetValue={(value) => update((item) => $setListItemNumber(item, value))}
+ />
+ }
+ onOpenChange={(next) => (next ? setOpen(true) : close())}
+ >
+ <span {...sx(styles.anchor, { height, left, top, width })}>
+ <Tooltip open={open ? false : undefined} title={t('list.number.set')}>
+ <button
+ aria-label={t('list.number.set')}
+ type="button"
+ {...sx(styles.marker, marker.style)}
+ // Keep the editor's selection while the menu opens.
+ onMouseDown={(event) => event.preventDefault()}
+ >
+ {marker.label}
+ </button>
+ </Tooltip>
+ </span>
+ </Popover>,
+ document.body,
+ );
+});
+
+OrderedListNumberMenu.displayName = 'OrderedListNumberMenu';
+
+export default OrderedListNumberMenu;
diff --git a/src/features/EditorCanvas/richList/RichListPlugin.test.ts b/src/features/EditorCanvas/richList/RichListPlugin.test.ts
new file mode 100644
index 00000000000..dab02f1ed4a
--- /dev/null
+++ b/src/features/EditorCanvas/richList/RichListPlugin.test.ts
@@ -0,0 +1,178 @@
+import { $isListItemNode, $isListNode, INSERT_ORDERED_LIST_COMMAND } from '@lexical/list';
+import { $isHeadingNode } from '@lexical/rich-text';
+import { $getListItemHeading } from '@lobechat/editor-runtime';
+import {
+ CommonPlugin,
+ INSERT_HEADING_COMMAND,
+ Kernel,
+ ListPlugin,
+ MarkdownPlugin,
+} from '@lobehub/editor';
+import {
+ $createParagraphNode,
+ $getRoot,
+ $getSelection,
+ $isRangeSelection,
+ KEY_BACKSPACE_COMMAND,
+ type LexicalEditor,
+ type LexicalNode,
+} from 'lexical';
+import { describe, expect, it } from 'vitest';
+
+import { RichListPlugin } from './RichListPlugin';
+
+// Commit pending updates, then let follow-up updates queued from update
+// listeners (the markdown shortcuts) run before reading the editor state.
+const flush = async (editor: LexicalEditor) => {
+ await new Promise<void>((resolve) => {
+ editor.update(() => undefined, { onUpdate: resolve });
+ });
+ await new Promise<void>((resolve) => {
+ setTimeout(resolve, 0);
+ });
+};
+
+const setup = () => {
+ const kernel = new Kernel();
+ kernel.registerPlugins([CommonPlugin, MarkdownPlugin, ListPlugin, RichListPlugin as never]);
+ const editor = kernel.initNodeEditor()!;
+ return { editor, kernel };
+};
+
+// Types one character per update, the way the browser delivers keystrokes.
+const type = async (editor: LexicalEditor, text: string) => {
+ for (const char of text) {
+ editor.update(() => {
+ const selection = $getSelection();
+ if ($isRangeSelection(selection)) selection.insertText(char);
+ });
+ await flush(editor);
+ }
+};
+
+// An empty H3 with the caret in it, made the way the `/3` slash item does.
+const startHeading = async (editor: LexicalEditor) => {
+ editor.update(() => {
+ const paragraph = $createParagraphNode();
+ $getRoot().clear().append(paragraph);
+ paragraph.select();
+ });
+ await flush(editor);
+ editor.dispatchCommand(INSERT_HEADING_COMMAND, { tag: 'h3' });
+ await flush(editor);
+};
+
+const describeBlock = (node: LexicalNode): unknown => {
+ if ($isHeadingNode(node)) return { heading: node.getTag(), text: node.getTextContent() };
+ if ($isListNode(node))
+ return {
+ items: node
+ .getChildren()
+ .filter($isListItemNode)
+ .map((item) => ({ heading: $getListItemHeading(item), text: item.getTextContent() })),
+ list: node.getListType(),
+ };
+ return { [node.getType()]: node.getTextContent() };
+};
+
+const readBlocks = (editor: LexicalEditor) =>
+ editor.getEditorState().read(() => $getRoot().getChildren().map(describeBlock));
+
+describe('RichListPlugin', () => {
+ it.each([
+ ['- ', 'bullet'],
+ ['1. ', 'number'],
+ ['[ ] ', 'check'],
+ ])('turns "%s" typed in a heading into a %s item of that heading level', async (marker, list) => {
+ const { editor } = setup();
+ await startHeading(editor);
+
+ await type(editor, `${marker}Title`);
+
+ expect(readBlocks(editor)).toEqual([{ items: [{ heading: 'h3', text: 'Title' }], list }]);
+ });
+
+ it('still turns "- " in a paragraph into a plain list item', async () => {
+ const { editor } = setup();
+ editor.update(() => {
+ const paragraph = $createParagraphNode();
+ $getRoot().clear().append(paragraph);
+ paragraph.select();
+ });
+ await flush(editor);
+
+ await type(editor, '- item');
+
+ expect(readBlocks(editor)).toEqual([
+ { items: [{ heading: undefined, text: 'item' }], list: 'bullet' },
+ ]);
+ });
+
+ it('keeps the heading level when the list command runs on a heading', async () => {
+ const { editor } = setup();
+ await startHeading(editor);
+ await type(editor, 'Title');
+
+ editor.dispatchCommand(INSERT_ORDERED_LIST_COMMAND, undefined);
+ await flush(editor);
+
+ expect(readBlocks(editor)).toEqual([
+ { items: [{ heading: 'h3', text: 'Title' }], list: 'number' },
+ ]);
+ });
+
+ it('gives the heading back on Backspace at the start of a heading item', async () => {
+ const { editor } = setup();
+ await startHeading(editor);
+ await type(editor, '- Title');
+
+ editor.update(() => {
+ $getRoot().getFirstDescendant()?.selectStart();
+ });
+ await flush(editor);
+ editor.dispatchCommand(KEY_BACKSPACE_COMMAND, new KeyboardEvent('keydown'));
+ await flush(editor);
+
+ expect(readBlocks(editor)).toEqual([{ heading: 'h3', text: 'Title' }]);
+ });
+
+ it('writes the heading level after the list marker and reads it back', async () => {
+ const { kernel } = setup();
+ const markdown = '1. ## Overview\n2. Details\n';
+
+ kernel.setDocument('markdown', markdown);
+
+ expect(readBlocks(kernel.getLexicalEditor()!)).toEqual([
+ {
+ items: [
+ { heading: 'h2', text: 'Overview' },
+ { heading: undefined, text: 'Details' },
+ ],
+ list: 'number',
+ },
+ ]);
+ expect(kernel.getDocument('markdown')).toBe(markdown);
+ });
+
+ it('styles list items as headings with /3 instead of replacing the list', async () => {
+ const { editor, kernel } = setup();
+ kernel.setDocument('markdown', '- one\n- two\n');
+ editor.update(() => {
+ $getRoot().getFirstDescendant()?.selectEnd();
+ });
+ await flush(editor);
+
+ editor.dispatchCommand(INSERT_HEADING_COMMAND, { tag: 'h3' });
+ await flush(editor);
+
+ expect(readBlocks(editor)).toEqual([
+ {
+ items: [
+ { heading: 'h3', text: 'one' },
+ { heading: undefined, text: 'two' },
+ ],
+ list: 'bullet',
+ },
+ ]);
+ });
+});
diff --git a/src/features/EditorCanvas/richList/RichListPlugin.ts b/src/features/EditorCanvas/richList/RichListPlugin.ts
new file mode 100644
index 00000000000..53e5def9dc6
--- /dev/null
+++ b/src/features/EditorCanvas/richList/RichListPlugin.ts
@@ -0,0 +1,242 @@
+import {
+ $createListItemNode,
+ $createListNode,
+ $isListItemNode,
+ INSERT_CHECK_LIST_COMMAND,
+ INSERT_ORDERED_LIST_COMMAND,
+ INSERT_UNORDERED_LIST_COMMAND,
+ ListItemNode,
+ type ListType,
+} from '@lexical/list';
+import { $createHeadingNode, $isHeadingNode, type HeadingNode } from '@lexical/rich-text';
+import { mergeRegister } from '@lexical/utils';
+import {
+ $getListItemHeading,
+ $setListItemHeading,
+ registerRichListDocument,
+ type RichListMarkdownService,
+} from '@lobechat/editor-runtime';
+import {
+ type getKernelFromEditor,
+ IMarkdownShortCutService,
+ INSERT_HEADING_COMMAND,
+ useLexicalComposerContext,
+} from '@lobehub/editor';
+import {
+ $getNodeByKey,
+ $getSelection,
+ $isRangeSelection,
+ $isRootNode,
+ $isTextNode,
+ COMMAND_PRIORITY_NORMAL,
+ type ElementNode,
+ KEY_BACKSPACE_COMMAND,
+ type LexicalEditor,
+ type LexicalNode,
+ type TextNode,
+} from 'lexical';
+import { type FC, useLayoutEffect } from 'react';
+
+type IEditorKernel = NonNullable<ReturnType<typeof getKernelFromEditor>>;
+
+// The marker the caret has just completed: `- `, `* `, `+ `, `1. `, `[ ] `,
+// `- [x] ` — the same shortcuts @lobehub/editor's ListPlugin registers.
+const LIST_SHORTCUT_MARKER = /^\s*(?:[*+-]|\d+\.|(?:-\s)?\s?\[[\sx]?])\s$/i;
+
+/** Marks list items rendered as headings, for the editor's stylesheet. */
+export const LIST_HEADING_ATTRIBUTE = 'data-list-heading';
+
+type RunTransformers = (
+ parentNode: ElementNode,
+ anchorNode: TextNode,
+ anchorOffset: number,
+ trigger?: 'enter',
+) => boolean;
+
+interface MarkdownServiceInternals extends RichListMarkdownService {
+ // Not part of the exported interface: the entry point typing runs through.
+ runTransformers: RunTransformers;
+}
+
+/**
+ * Typing a list marker at the start of a heading makes a list item that keeps
+ * the heading level. @lobehub/editor replaces the heading with a plain list.
+ */
+const patchListShortcut = (service: MarkdownServiceInternals) => {
+ const runTransformers = service.runTransformers;
+ const patched: RunTransformers = function (this: unknown, ...args) {
+ const [parentNode, anchorNode, anchorOffset] = args;
+ const tag =
+ $isHeadingNode(parentNode) &&
+ LIST_SHORTCUT_MARKER.test(anchorNode.getTextContent().slice(0, anchorOffset))
+ ? parentNode.getTag()
+ : undefined;
+
+ const handled = runTransformers.apply(this, args);
+ if (handled && tag) {
+ const item = $getSelection()?.getNodes()[0];
+ const listItem = $isListItemNode(item) ? item : item?.getParent();
+ if ($isListItemNode(listItem)) $setListItemHeading(listItem, tag);
+ }
+ return handled;
+ };
+ service.runTransformers = patched;
+
+ return () => {
+ if (service.runTransformers === patched) service.runTransformers = runTransformers;
+ };
+};
+
+const LIST_COMMANDS: [typeof INSERT_UNORDERED_LIST_COMMAND, ListType][] = [
+ [INSERT_UNORDERED_LIST_COMMAND, 'bullet'],
+ [INSERT_ORDERED_LIST_COMMAND, 'number'],
+ [INSERT_CHECK_LIST_COMMAND, 'check'],
+];
+
+/** Turns the selected headings into list items of their level. */
+const $headingsToList = (listType: ListType): boolean => {
+ const selection = $getSelection();
+ if (!$isRangeSelection(selection)) return false;
+
+ const blocks = new Map<string, LexicalNode>();
+ for (const node of selection.getNodes()) {
+ const block = node.getTopLevelElement() ?? node;
+ blocks.set(block.getKey(), block);
+ }
+ const headings = [...blocks.values()];
+ if (headings.length === 0 || !headings.every($isHeadingNode)) return false;
+
+ const anchor = selection.anchor;
+ const caretKey = anchor.type === 'element' ? anchor.key : undefined;
+ const caretOffset = anchor.offset;
+
+ for (const heading of headings as HeadingNode[]) {
+ const item = $createListItemNode(listType === 'check' ? false : undefined);
+ item.append(...heading.getChildren());
+ item.setFormat(heading.getFormatType());
+ $setListItemHeading(item, heading.getTag());
+ const list = $createListNode(listType);
+ list.append(item);
+ heading.replace(list);
+ if (caretKey === heading.getKey()) item.select(caretOffset, caretOffset);
+ }
+ return true;
+};
+
+/** `/h3` inside list items styles them as headings rather than replacing them. */
+const $headingOnListItems = (tag: Parameters<typeof $createHeadingNode>[0]): boolean => {
+ const selection = $getSelection();
+ if (!$isRangeSelection(selection)) return false;
+
+ const items = new Map<string, ListItemNode>();
+ for (const node of selection.getNodes()) {
+ const item = $isListItemNode(node) ? node : node.getParents().find($isListItemNode);
+ if (!item) return false;
+ items.set(item.getKey(), item);
+ }
+ if (items.size === 0) return false;
+
+ const all = [...items.values()];
+ const next = all.every((item) => $getListItemHeading(item) === tag) ? undefined : tag;
+ for (const item of all) $setListItemHeading(item, next);
+ return true;
+};
+
+/** Backspace at the start of a heading list item gives back the heading. */
+const $listItemToHeading = (): boolean => {
+ const selection = $getSelection();
+ if (!$isRangeSelection(selection) || !selection.isCollapsed() || selection.anchor.offset !== 0)
+ return false;
+
+ const anchorNode = selection.anchor.getNode();
+ let item: LexicalNode | null = anchorNode;
+ if ($isTextNode(anchorNode)) {
+ if (anchorNode.getPreviousSibling()) return false;
+ item = anchorNode.getParent();
+ }
+ if (!$isListItemNode(item) || !$isRootNode(item.getParent()?.getParent())) return false;
+
+ const tag = $getListItemHeading(item);
+ if (!tag) return false;
+
+ const heading = $createHeadingNode(tag);
+ item.replace(heading, true);
+ heading.select(0, 0);
+ return true;
+};
+
+const registerHeadingAttribute = (editor: LexicalEditor) =>
+ editor.registerMutationListener(ListItemNode, (mutations) => {
+ editor.getEditorState().read(() => {
+ for (const [key, mutation] of mutations) {
+ if (mutation === 'destroyed') continue;
+ const element = editor.getElementByKey(key);
+ const node = $getNodeByKey(key);
+ if (!element || !$isListItemNode(node)) continue;
+ const tag = $getListItemHeading(node);
+ if (tag) element.setAttribute(LIST_HEADING_ATTRIBUTE, tag);
+ else element.removeAttribute(LIST_HEADING_ATTRIBUTE);
+ }
+ });
+ });
+
+/**
+ * The page editor's side of rich lists: typing, commands and rendering. What
+ * the document itself needs (Markdown, numbering) is shared with the server's
+ * headless editor through `registerRichListDocument`.
+ */
+export class RichListPlugin {
+ static pluginName = 'LobeRichListPlugin';
+
+ private cleanup?: () => void;
+ private kernel: IEditorKernel;
+
+ constructor(kernel: IEditorKernel) {
+ this.kernel = kernel;
+ }
+
+ onInit(editor: LexicalEditor): void {
+ const internals = this.kernel.requireService(
+ IMarkdownShortCutService,
+ ) as unknown as MarkdownServiceInternals | null;
+
+ this.cleanup = mergeRegister(
+ internals ? patchListShortcut(internals) : () => {},
+ registerRichListDocument(editor, internals),
+ registerHeadingAttribute(editor),
+ ...LIST_COMMANDS.map(([command, listType]) =>
+ editor.registerCommand(command, () => $headingsToList(listType), COMMAND_PRIORITY_NORMAL),
+ ),
+ editor.registerCommand(
+ INSERT_HEADING_COMMAND,
+ (payload) => $headingOnListItems(payload.tag),
+ COMMAND_PRIORITY_NORMAL,
+ ),
+ editor.registerCommand(
+ KEY_BACKSPACE_COMMAND,
+ (event) => {
+ if (!$listItemToHeading()) return false;
+ event?.preventDefault();
+ return true;
+ },
+ COMMAND_PRIORITY_NORMAL,
+ ),
+ );
+ }
+
+ destroy(): void {
+ this.cleanup?.();
+ }
+}
+
+export const ReactRichListPlugin: FC = () => {
+ const [editor] = useLexicalComposerContext();
+
+ useLayoutEffect(() => {
+ editor.registerPlugin(RichListPlugin as never);
+ }, [editor]);
+
+ return null;
+};
+
+ReactRichListPlugin.displayName = 'ReactRichListPlugin';
diff --git a/src/features/EditorCanvas/richList/markerHitTest.test.ts b/src/features/EditorCanvas/richList/markerHitTest.test.ts
new file mode 100644
index 00000000000..5117654d6e9
--- /dev/null
+++ b/src/features/EditorCanvas/richList/markerHitTest.test.ts
@@ -0,0 +1,88 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { findOrderedItemNear } from './markerHitTest';
+
+const ITEM_HEIGHT = 20;
+
+// A root holding one numbered list of `count` single-line items, laid out top
+// to bottom the way the browser stacks them.
+const setup = (count: number, inner = (index: number) => `<span>item ${index}</span>`) => {
+ const root = document.createElement('div');
+ root.innerHTML = `<p>intro</p><ol class="editor_listOrdered">${Array.from(
+ { length: count },
+ (_, index) => `<li>${inner(index)}</li>`,
+ ).join('')}</ol>`;
+ document.body.append(root);
+
+ const list = root.querySelector('ol')!;
+ const items = [...list.children] as HTMLLIElement[];
+ const measured = vi.fn();
+ for (const [index, item] of items.entries()) {
+ item.getBoundingClientRect = () => {
+ measured();
+ return { bottom: (index + 1) * ITEM_HEIGHT, top: index * ITEM_HEIGHT } as DOMRect;
+ };
+ }
+
+ return { items, list, measured, root };
+};
+
+afterEach(() => {
+ document.body.innerHTML = '';
+});
+
+describe('findOrderedItemNear', () => {
+ it('measures no item while the pointer is over ordinary text', () => {
+ const { measured, root } = setup(1000);
+ const paragraph = root.querySelector('p')!;
+
+ expect(findOrderedItemNear(root, 100, 10, () => paragraph)).toBeUndefined();
+ expect(measured).not.toHaveBeenCalled();
+ });
+
+ it('takes the item under the pointer without measuring any', () => {
+ const { items, measured, root } = setup(1000);
+ const text = items[500].querySelector('span')!;
+
+ expect(findOrderedItemNear(root, 100, 10_010, () => text)).toBe(items[500]);
+ expect(measured).not.toHaveBeenCalled();
+ });
+
+ it('finds the item beside the pointer in a long list by halving, not by scanning', () => {
+ const { items, list, measured, root } = setup(1000);
+
+ // Over the list's padding, level with item 742.
+ expect(findOrderedItemNear(root, 4, 742 * ITEM_HEIGHT + 5, () => list)).toBe(items[742]);
+ expect(measured.mock.calls.length).toBeLessThanOrEqual(10);
+ });
+
+ it('looks to the right when a long number hangs past the list edge', () => {
+ const { items, root } = setup(3);
+ const text = items[1].querySelector('span')!;
+ // The pointer is left of the list, over the editor root; the item starts 32px on.
+ const elementFromPoint = (x: number) => (x >= 32 ? text : root);
+
+ expect(findOrderedItemNear(root, 0, 30, elementFromPoint)).toBe(items[1]);
+ });
+
+ it('skips an item that only holds a nested list', () => {
+ const { items, root } = setup(2, (index) =>
+ index === 1 ? '<ul><li><span>nested bullet</span></li></ul>' : '<span>plain</span>',
+ );
+
+ expect(findOrderedItemNear(root, 0, 30, () => items[1])).toBeUndefined();
+ // Text in the nested bulleted list belongs to the bullet, not the wrapper.
+ const bullet = items[1].querySelector('span')!;
+ expect(findOrderedItemNear(root, 0, 30, () => bullet)).toBeUndefined();
+ });
+
+ it('ignores what lies outside the editor', () => {
+ const { root } = setup(2);
+ const outside = document.createElement('ol');
+ outside.className = 'editor_listOrdered';
+ outside.innerHTML = '<li><span>elsewhere</span></li>';
+ document.body.append(outside);
+
+ expect(findOrderedItemNear(root, 0, 10, () => outside.querySelector('span')!)).toBeUndefined();
+ });
+});
diff --git a/src/features/EditorCanvas/richList/markerHitTest.ts b/src/features/EditorCanvas/richList/markerHitTest.ts
new file mode 100644
index 00000000000..18403c8c03e
--- /dev/null
+++ b/src/features/EditorCanvas/richList/markerHitTest.ts
@@ -0,0 +1,57 @@
+const ORDERED_LIST = 'ol.editor_listOrdered';
+const ORDERED_ITEM = `${ORDERED_LIST} > li`;
+
+// A marker hangs left of its item: over the list's padding, or past the list's
+// own edge when the number is long. So the item is under the pointer or within
+// a few characters to its right.
+const PROBE_OFFSETS = [0, 16, 32, 48, 64];
+
+/** An item holding only a nested list has no number of its own. */
+const isWrapperItem = (li: Element) => {
+ const tag = li.firstElementChild?.tagName;
+ return tag === 'OL' || tag === 'UL';
+};
+
+/** The item of `list` whose box spans `y`. Items stack top to bottom. */
+const itemAt = (list: Element, y: number) => {
+ const items = list.children;
+ let low = 0;
+ let high = items.length - 1;
+
+ while (low <= high) {
+ const middle = (low + high) >> 1;
+ const item = items[middle];
+ const { bottom, top } = item.getBoundingClientRect();
+ if (y < top) high = middle - 1;
+ else if (y > bottom) low = middle + 1;
+ else return item.matches(ORDERED_ITEM) ? (item as HTMLLIElement) : undefined;
+ }
+};
+
+const itemOf = (element: Element | null, root: HTMLElement, y: number) => {
+ if (!element || !root.contains(element)) return;
+ if (element.matches(ORDERED_LIST)) return itemAt(element, y);
+
+ // The nearest item only: text in a bulleted list nested in a numbered one
+ // belongs to the bullet.
+ const item = element.closest('li');
+ return item?.matches(ORDERED_ITEM) ? (item as HTMLLIElement) : undefined;
+};
+
+/**
+ * The one numbered item whose marker could be under the pointer, found from
+ * what is at the pointer instead of by measuring every item in the document.
+ * The caller still checks the pointer against that item's marker box.
+ */
+export const findOrderedItemNear = (
+ root: HTMLElement,
+ x: number,
+ y: number,
+ elementFromPoint: (x: number, y: number) => Element | null = (px, py) =>
+ document.elementFromPoint(px, py),
+): HTMLLIElement | undefined => {
+ for (const offset of PROBE_OFFSETS) {
+ const item = itemOf(elementFromPoint(x + offset, y), root, y);
+ if (item && !isWrapperItem(item)) return item;
+ }
+};
diff --git a/src/features/EditorCanvas/richList/numberMenuRequest.test.ts b/src/features/EditorCanvas/richList/numberMenuRequest.test.ts
new file mode 100644
index 00000000000..28f5a983fb8
--- /dev/null
+++ b/src/features/EditorCanvas/richList/numberMenuRequest.test.ts
@@ -0,0 +1,90 @@
+import { $isListItemNode, $isListNode } from '@lexical/list';
+import { CommonPlugin, type IEditor, Kernel, ListPlugin, MarkdownPlugin } from '@lobehub/editor';
+import { $getNodeByKey, $getRoot, type LexicalEditor } from 'lexical';
+import { describe, expect, it } from 'vitest';
+
+import { onListNumberMenuRequest, requestListNumberMenu } from './numberMenuRequest';
+import { RichListPlugin } from './RichListPlugin';
+
+const flush = async (editor: LexicalEditor) => {
+ await new Promise<void>((resolve) => {
+ editor.update(() => undefined, { onUpdate: resolve });
+ });
+ await new Promise<void>((resolve) => {
+ setTimeout(resolve, 0);
+ });
+};
+
+// An editor holding `markdown`, with the caret at the end of the block whose text is `caretIn`.
+const setup = async (markdown: string, caretIn: string) => {
+ const kernel = new Kernel();
+ kernel.registerPlugins([CommonPlugin, MarkdownPlugin, ListPlugin, RichListPlugin as never]);
+ const lexical = kernel.initNodeEditor()!;
+ kernel.setDocument('markdown', markdown);
+ lexical.update(() => {
+ $getRoot()
+ .getAllTextNodes()
+ .find((node) => node.getTextContent() === caretIn)
+ ?.selectEnd();
+ });
+ await flush(lexical);
+
+ const editor = kernel as unknown as IEditor;
+ const requested: string[] = [];
+ onListNumberMenuRequest(editor, (key) => requested.push(key));
+
+ // What each requested key points at: the item's text and its list type.
+ const describeRequests = () =>
+ lexical.getEditorState().read(() =>
+ requested.map((key) => {
+ const item = $getNodeByKey(key);
+ const list = item?.getParent();
+ return $isListItemNode(item) && $isListNode(list)
+ ? `${list.getListType()}: ${item.getTextContent()}`
+ : 'not a list item';
+ }),
+ );
+
+ return { describeRequests, editor, lexical };
+};
+
+describe('requestListNumberMenu', () => {
+ it('opens the menu on the numbered item the caret is in', async () => {
+ const { describeRequests, editor, lexical } = await setup('1. a\n2. b\n3. c\n', 'b');
+
+ requestListNumberMenu(editor);
+ await flush(lexical);
+
+ expect(describeRequests()).toEqual(['number: b']);
+ });
+
+ it('makes a paragraph a numbered item first, then opens the menu on it', async () => {
+ const { describeRequests, editor, lexical } = await setup('intro\n\nbody\n', 'body');
+
+ requestListNumberMenu(editor);
+ await flush(lexical);
+
+ expect(describeRequests()).toEqual(['number: body']);
+ });
+
+ it('opens on the nested numbered item, not on the item wrapping it', async () => {
+ const { describeRequests, editor, lexical } = await setup('1. a\n 1. inner\n2. b\n', 'inner');
+
+ requestListNumberMenu(editor);
+ await flush(lexical);
+
+ expect(describeRequests()).toEqual(['number: inner']);
+ });
+
+ it('stops notifying a menu that unsubscribed', async () => {
+ const { editor, lexical } = await setup('1. a\n', 'a');
+ const requested: string[] = [];
+ const unsubscribe = onListNumberMenuRequest(editor, (key) => requested.push(key));
+ unsubscribe();
+
+ requestListNumberMenu(editor);
+ await flush(lexical);
+
+ expect(requested).toEqual([]);
+ });
+});
diff --git a/src/features/EditorCanvas/richList/numberMenuRequest.ts b/src/features/EditorCanvas/richList/numberMenuRequest.ts
new file mode 100644
index 00000000000..32741350c21
--- /dev/null
+++ b/src/features/EditorCanvas/richList/numberMenuRequest.ts
@@ -0,0 +1,55 @@
+import { $isListItemNode, $isListNode, INSERT_ORDERED_LIST_COMMAND } from '@lexical/list';
+import type { IEditor } from '@lobehub/editor';
+import { $getSelection, $isRangeSelection, type LexicalNode } from 'lexical';
+
+type Listener = (itemKey: string) => void;
+
+const listeners = new WeakMap<IEditor, Set<Listener>>();
+
+/** Subscribes the number menu of `editor` to requests to open it on an item. */
+export const onListNumberMenuRequest = (editor: IEditor, listener: Listener) => {
+ const set = listeners.get(editor) ?? new Set();
+ listeners.set(editor, set);
+ set.add(listener);
+
+ return () => {
+ set.delete(listener);
+ };
+};
+
+/** The numbered list item the caret is in; an item holding only a nested list has no number. */
+const $numberedItemAtCaret = () => {
+ const selection = $getSelection();
+ if (!$isRangeSelection(selection)) return;
+
+ let node: LexicalNode | null = selection.anchor.getNode();
+ while (node && !$isListItemNode(node)) node = node.getParent();
+ if (!node || $isListNode(node.getFirstChild())) return;
+
+ const list = node.getParent();
+ return $isListNode(list) && list.getListType() === 'number' ? node : undefined;
+};
+
+/**
+ * Opens the number menu on the item the caret is in, without the pointer. A
+ * block that is not a numbered item becomes one first, so the entry always
+ * leads to the menu.
+ */
+export const requestListNumberMenu = (editor: IEditor) => {
+ const lexical = editor.getLexicalEditor();
+ if (!lexical) return;
+
+ lexical.update(
+ () => {
+ if (!$numberedItemAtCaret()) lexical.dispatchCommand(INSERT_ORDERED_LIST_COMMAND, undefined);
+ },
+ {
+ // The menu anchors to the item's element, which exists once this commits.
+ onUpdate: () => {
+ const key = lexical.getEditorState().read(() => $numberedItemAtCaret()?.getKey());
+ if (!key) return;
+ for (const listener of listeners.get(editor) ?? []) listener(key);
+ },
+ },
+ );
+};
diff --git a/src/features/PageEditor/EditorCanvas/useSlashItems.test.ts b/src/features/PageEditor/EditorCanvas/useSlashItems.test.ts
index af158a438cd..b6b937aca61 100644
--- a/src/features/PageEditor/EditorCanvas/useSlashItems.test.ts
+++ b/src/features/PageEditor/EditorCanvas/useSlashItems.test.ts
@@ -8,6 +8,8 @@ import {
import { renderHook } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
+import { requestListNumberMenu } from '@/features/EditorCanvas';
+
import { useSlashItems } from './useSlashItems';
vi.mock('@lobehub/editor', () => ({
@@ -26,7 +28,10 @@ vi.mock('@lobehub/editor', () => ({
INSERT_VIDEO_COMMAND: 'INSERT_VIDEO_COMMAND',
}));
-vi.mock('@/features/EditorCanvas', () => ({ openFileSelector: vi.fn() }));
+vi.mock('@/features/EditorCanvas', () => ({
+ openFileSelector: vi.fn(),
+ requestListNumberMenu: vi.fn(),
+}));
type SlashItem = Extract<NonNullable<SlashOptions['items']>[number], { key: string }>;
@@ -49,6 +54,17 @@ describe('useSlashItems', () => {
expect(editor.dispatchCommand).toHaveBeenCalledWith(command, undefined);
});
+ it('opens the list number menu from the slash menu, for use without a pointer', () => {
+ const { result } = renderHook(() => useSlashItems());
+ const item = findItem(result.current, 'num');
+ const editor = { dispatchCommand: vi.fn(), focus: vi.fn() };
+
+ expect(item).toBeDefined();
+ item!.onSelect!(editor as any, {} as any);
+
+ expect(requestListNumberMenu).toHaveBeenCalledWith(editor);
+ });
+
it('inserts an empty video block from the slash menu', () => {
const { result } = renderHook(() => useSlashItems());
const item = findItem(result.current, 'video');
diff --git a/src/features/PageEditor/EditorCanvas/useSlashItems.tsx b/src/features/PageEditor/EditorCanvas/useSlashItems.tsx
index f13c848d596..3afb4d5f1e3 100644
--- a/src/features/PageEditor/EditorCanvas/useSlashItems.tsx
+++ b/src/features/PageEditor/EditorCanvas/useSlashItems.tsx
@@ -23,6 +23,7 @@ import {
ImageIcon,
ListIcon,
ListOrderedIcon,
+ ListRestartIcon,
ListTodoIcon,
MessageSquareWarningIcon,
MinusIcon,
@@ -35,7 +36,7 @@ import {
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import { openFileSelector } from '@/features/EditorCanvas';
+import { openFileSelector, requestListNumberMenu } from '@/features/EditorCanvas';
export const useSlashItems = (): SlashOptions['items'] => {
const { t } = useTranslation('editor');
@@ -93,6 +94,15 @@ export const useSlashItems = (): SlashOptions['items'] => {
editor.dispatchCommand(INSERT_ORDERED_LIST_COMMAND, undefined);
},
},
+ {
+ // The keyboard's way to the menu the pointer opens on a list number.
+ icon: ListRestartIcon,
+ key: 'num',
+ label: t('list.number.set'),
+ onSelect: (editor) => {
+ requestListNumberMenu(editor);
+ },
+ },
{
type: 'divider',
},