diff --git a/ui/src/components/ChatComposer.test.tsx b/ui/src/components/ChatComposer.test.tsx
new file mode 100644
index 00000000000..9badd3a31c5
--- /dev/null
+++ b/ui/src/components/ChatComposer.test.tsx
@@ -0,0 +1,163 @@
+// @vitest-environment jsdom
+
+import { useState } from "react";
+import { flushSync } from "react-dom";
+import { createRoot } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { ChatComposer } from "./ChatComposer";
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
+
+function Harness({
+ initialValue,
+ submitKey = "enter",
+ singleLine = false,
+ onSubmit = () => {},
+}: {
+ initialValue: string;
+ submitKey?: "enter" | "mod-enter";
+ singleLine?: boolean;
+ onSubmit?: () => void;
+}) {
+ const [value, setValue] = useState(initialValue);
+ return (
+
+ );
+}
+
+describe("ChatComposer list editing", () => {
+ let container: HTMLDivElement;
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ });
+
+ afterEach(() => {
+ container.remove();
+ });
+
+ it("supports adding, indenting, dedenting, and deleting bulleted and numbered lists in enter-to-submit mode", () => {
+ const onSubmit = vi.fn();
+ const root = createRoot(container);
+ flushSync(() => {
+ root.render();
+ });
+
+ const textarea = container.querySelector("textarea")!;
+ textarea.focus();
+ textarea.setSelectionRange(7, 7);
+
+ // Shift+Enter adds the next bullet without submitting.
+ const shiftEnter = new KeyboardEvent("keydown", {
+ key: "Enter",
+ shiftKey: true,
+ bubbles: true,
+ cancelable: true,
+ });
+ flushSync(() => {
+ textarea.dispatchEvent(shiftEnter);
+ });
+ expect(shiftEnter.defaultPrevented).toBe(true);
+ expect(onSubmit).not.toHaveBeenCalled();
+ expect(textarea.value).toBe("- first\n- ");
+
+ // Tab indents the new bullet item.
+ textarea.setSelectionRange(10, 10);
+ const tab = new KeyboardEvent("keydown", {
+ key: "Tab",
+ bubbles: true,
+ cancelable: true,
+ });
+ flushSync(() => {
+ textarea.dispatchEvent(tab);
+ });
+ expect(tab.defaultPrevented).toBe(true);
+ expect(textarea.value).toBe("- first\n - ");
+
+ // Shift+Tab dedents back to top level.
+ textarea.setSelectionRange(12, 12);
+ const shiftTab = new KeyboardEvent("keydown", {
+ key: "Tab",
+ shiftKey: true,
+ bubbles: true,
+ cancelable: true,
+ });
+ flushSync(() => {
+ textarea.dispatchEvent(shiftTab);
+ });
+ expect(shiftTab.defaultPrevented).toBe(true);
+ expect(textarea.value).toBe("- first\n- ");
+
+ // Backspace right after the top-level marker removes the empty bullet cleanly.
+ textarea.setSelectionRange(10, 10);
+ const backspace = new KeyboardEvent("keydown", {
+ key: "Backspace",
+ bubbles: true,
+ cancelable: true,
+ });
+ flushSync(() => {
+ textarea.dispatchEvent(backspace);
+ });
+ expect(backspace.defaultPrevented).toBe(true);
+ expect(textarea.value).toBe("- first\n");
+
+ // Plain Enter still submits.
+ const enter = new KeyboardEvent("keydown", {
+ key: "Enter",
+ bubbles: true,
+ cancelable: true,
+ });
+ flushSync(() => {
+ textarea.dispatchEvent(enter);
+ });
+ expect(enter.defaultPrevented).toBe(true);
+ expect(onSubmit).toHaveBeenCalledTimes(1);
+
+ flushSync(() => root.unmount());
+ });
+
+ it("leaves Tab untouched outside lists and in singleLine mode", () => {
+ const root = createRoot(container);
+ flushSync(() => {
+ root.render();
+ });
+
+ const textarea = container.querySelector("textarea")!;
+ textarea.setSelectionRange(10, 10);
+ const tab = new KeyboardEvent("keydown", {
+ key: "Tab",
+ bubbles: true,
+ cancelable: true,
+ });
+ flushSync(() => {
+ textarea.dispatchEvent(tab);
+ });
+ expect(tab.defaultPrevented).toBe(false);
+ expect(textarea.value).toBe("plain text");
+
+ flushSync(() => {
+ root.render();
+ });
+ const single = container.querySelector("textarea")!;
+ single.setSelectionRange(8, 8);
+ const singleTab = new KeyboardEvent("keydown", {
+ key: "Tab",
+ bubbles: true,
+ cancelable: true,
+ });
+ flushSync(() => {
+ single.dispatchEvent(singleTab);
+ });
+ expect(singleTab.defaultPrevented).toBe(false);
+
+ flushSync(() => root.unmount());
+ });
+});
diff --git a/ui/src/components/ChatComposer.tsx b/ui/src/components/ChatComposer.tsx
index 1834c88f5c7..4075e592f76 100644
--- a/ui/src/components/ChatComposer.tsx
+++ b/ui/src/components/ChatComposer.tsx
@@ -11,6 +11,7 @@ import {
} from "react";
import { AlertTriangle, Check, Loader2, Paperclip, Send } from "lucide-react";
import { cn } from "../lib/utils";
+import { applyTextareaListKeyDown } from "../lib/textarea-list-editing";
/**
* Shared chat composer (PAP-95a / PAP-96).
@@ -164,14 +165,44 @@ export const ChatComposer = forwardRef(fu
}
function handleKeyDown(evt: ReactKeyboardEvent) {
- if (evt.key !== "Enter") return;
- const wantsSubmit =
- submitKey === "mod-enter"
- ? evt.metaKey || evt.ctrlKey
- : !evt.shiftKey && !evt.metaKey && !evt.ctrlKey;
- if (!wantsSubmit) return;
+ if (evt.nativeEvent.isComposing || evt.keyCode === 229) return;
+ if (evt.key === "Enter") {
+ const wantsSubmit =
+ !evt.altKey &&
+ (submitKey === "mod-enter"
+ ? evt.metaKey || evt.ctrlKey
+ : !evt.shiftKey && !evt.metaKey && !evt.ctrlKey);
+ if (wantsSubmit) {
+ evt.preventDefault();
+ if (canSend) onSubmit();
+ return;
+ }
+ }
+ if (disabled || singleLine) return;
+ const textarea = evt.currentTarget;
+ const next = applyTextareaListKeyDown(
+ {
+ value,
+ selectionStart: textarea.selectionStart ?? value.length,
+ selectionEnd: textarea.selectionEnd ?? value.length,
+ },
+ {
+ key: evt.key,
+ shiftKey: evt.shiftKey,
+ metaKey: evt.metaKey,
+ ctrlKey: evt.ctrlKey,
+ altKey: evt.altKey,
+ isComposing: evt.nativeEvent.isComposing,
+ keyCode: evt.keyCode,
+ },
+ { submitKey, singleLine },
+ );
+ if (!next) return;
evt.preventDefault();
- if (canSend) onSubmit();
+ onChange(next.value);
+ requestAnimationFrame(() => {
+ textareaRef.current?.setSelectionRange(next.selectionStart, next.selectionEnd);
+ });
}
function triggerFilePicker() {
diff --git a/ui/src/components/MarkdownEditor.test.tsx b/ui/src/components/MarkdownEditor.test.tsx
index c6d65ccd825..7d463857191 100644
--- a/ui/src/components/MarkdownEditor.test.tsx
+++ b/ui/src/components/MarkdownEditor.test.tsx
@@ -376,6 +376,55 @@ describe("MarkdownEditor", () => {
await act(() => root.unmount());
});
+ it("supports bullet and numbered list editing in the raw fallback textarea", async () => {
+ mdxEditorMockState.emitMountParseError = true;
+ let currentValue = "1. first";
+ const root = createRoot(container);
+ const renderEditor = () => {
+ root.render(
+ {
+ currentValue = next;
+ renderEditor();
+ }}
+ onSubmit={vi.fn()}
+ submitKey="enter"
+ />,
+ );
+ };
+ await act(async () => { renderEditor(); });
+ await flush();
+ await vi.waitFor(() => expect(container.querySelector("textarea")).not.toBeNull());
+
+ const textarea = container.querySelector("textarea")!;
+ textarea.setSelectionRange(currentValue.length, currentValue.length);
+ await act(() => {
+ textarea.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", shiftKey: true, bubbles: true, cancelable: true }));
+ });
+ expect(currentValue).toBe("1. first\n2. ");
+
+ textarea.setSelectionRange(currentValue.length, currentValue.length);
+ await act(() => {
+ textarea.dispatchEvent(new KeyboardEvent("keydown", { key: "Tab", bubbles: true, cancelable: true }));
+ });
+ expect(currentValue).toBe("1. first\n 1. ");
+
+ textarea.setSelectionRange(currentValue.length, currentValue.length);
+ await act(() => {
+ textarea.dispatchEvent(new KeyboardEvent("keydown", { key: "Tab", shiftKey: true, bubbles: true, cancelable: true }));
+ });
+ expect(currentValue).toBe("1. first\n2. ");
+
+ textarea.setSelectionRange(currentValue.length, currentValue.length);
+ await act(() => {
+ textarea.dispatchEvent(new KeyboardEvent("keydown", { key: "Backspace", bubbles: true, cancelable: true }));
+ });
+ expect(currentValue).toBe("1. first\n");
+
+ await act(() => root.unmount());
+ });
+
it("keeps ordinary document editors on Command/Ctrl+Enter", async () => {
const onSubmit = vi.fn();
const root = createRoot(container);
diff --git a/ui/src/components/MarkdownEditor.tsx b/ui/src/components/MarkdownEditor.tsx
index 53eed89bbe8..2dd54d1bd04 100644
--- a/ui/src/components/MarkdownEditor.tsx
+++ b/ui/src/components/MarkdownEditor.tsx
@@ -51,6 +51,8 @@ import { Boxes, CalendarClock, Flag, Hash, User, X } from "lucide-react";
import { applyMentionChipDecoration, clearMentionChipDecoration, parseMentionChipHref } from "../lib/mention-chips";
import { MentionAwareLinkNode, mentionAwareLinkNodeReplacement } from "../lib/mention-aware-link-node";
import { mentionDeletionPlugin } from "../lib/mention-deletion";
+import { listEditingPlugin } from "../lib/list-editing";
+import { applyTextareaListKeyDown } from "../lib/textarea-list-editing";
import { looksLikeMarkdownPaste } from "../lib/markdownPaste";
import { normalizeMarkdown } from "../lib/normalize-markdown";
import {
@@ -212,7 +214,7 @@ function hasMeaningfulEditorContent(node: Node | null): boolean {
}
const element = node as HTMLElement;
- if (["IMG", "HR", "TABLE", "VIDEO", "IFRAME"].includes(element.tagName)) {
+ if (["IMG", "HR", "TABLE", "VIDEO", "IFRAME", "LI"].includes(element.tagName)) {
return true;
}
@@ -778,6 +780,8 @@ export const MarkdownEditor = forwardRef
readOnly = false,
}: MarkdownEditorProps, forwardedRef) {
const editorValue = useMemo(() => prepareMarkdownForEditor(value), [value]);
+ const submitKeyRef = useRef(submitKey);
+ submitKeyRef.current = submitKey;
function isSubmitShortcut(event: KeyboardEvent): boolean {
return !readOnly
&& event.key === "Enter"
@@ -1034,6 +1038,7 @@ export const MarkdownEditor = forwardRef
linkPlugin({ validateUrl: isSafeMarkdownLinkUrl }),
linkDialogPlugin(),
mentionDeletionPlugin(),
+ listEditingPlugin({ submitKeyRef }),
pasteNormalizationPlugin(),
thematicBreakPlugin(),
codeBlockPlugin({
@@ -1416,7 +1421,36 @@ export const MarkdownEditor = forwardRef
event.preventDefault();
event.stopPropagation();
onSubmit();
+ return;
}
+ if (readOnly) return;
+ const textarea = event.currentTarget;
+ const next = applyTextareaListKeyDown(
+ {
+ value,
+ selectionStart: textarea.selectionStart ?? value.length,
+ selectionEnd: textarea.selectionEnd ?? value.length,
+ },
+ {
+ key: event.key,
+ shiftKey: event.shiftKey,
+ metaKey: event.metaKey,
+ ctrlKey: event.ctrlKey,
+ altKey: event.altKey,
+ isComposing: event.nativeEvent.isComposing,
+ keyCode: event.keyCode,
+ },
+ { submitKey },
+ );
+ if (!next) return;
+ event.preventDefault();
+ onChange(next.value);
+ requestAnimationFrame(() => {
+ if (fallbackTextareaRef.current) {
+ fallbackTextareaRef.current.setSelectionRange(next.selectionStart, next.selectionEnd);
+ autoSizeFallbackTextarea(fallbackTextareaRef.current);
+ }
+ });
}}
className={cn(
"min-h-(--sz-12rem) w-full resize-none bg-transparent px-3 pb-3 pt-2 font-mono text-sm leading-6 outline-none",
@@ -1452,13 +1486,20 @@ export const MarkdownEditor = forwardRef
}}
onKeyDownCapture={(e) => {
if (readOnly || e.nativeEvent.isComposing || e.keyCode === 229) return;
- if (e.key === "Enter" && (e.shiftKey || e.altKey)) return;
+ const targetInsideEditable =
+ e.target instanceof HTMLElement
+ && Boolean(e.target.closest('[contenteditable="true"]'));
+ if (e.key === "Enter" && (e.shiftKey || e.altKey)) {
+ if (targetInsideEditable) {
+ initialChildOnChangeRef.current = false;
+ }
+ return;
+ }
if (
- (e.key === "Backspace" || e.key === "Delete")
- && e.target instanceof HTMLElement
- && e.target.closest('[contenteditable="true"]')
+ (e.key === "Backspace" || e.key === "Delete" || e.key === "Tab")
+ && targetInsideEditable
) {
- // Lexical handles deletion on keydown and may suppress DOM input.
+ // Lexical handles deletion/indentation on keydown and may suppress DOM input.
initialChildOnChangeRef.current = false;
}
// An explicit Cmd/Ctrl+Enter sends even while autocomplete is open.
@@ -1503,7 +1544,8 @@ export const MarkdownEditor = forwardRef
return;
}
if (
- shouldAcceptAutocompleteKey(
+ !(e.key === "Tab" && e.shiftKey)
+ && shouldAcceptAutocompleteKey(
e.key,
mentionStateRef.current?.trigger ?? null,
skillEnterArmedRef.current,
diff --git a/ui/src/components/task-chat/TaskChatComposer.test.tsx b/ui/src/components/task-chat/TaskChatComposer.test.tsx
index 4655a6294c4..651c54f6d3f 100644
--- a/ui/src/components/task-chat/TaskChatComposer.test.tsx
+++ b/ui/src/components/task-chat/TaskChatComposer.test.tsx
@@ -150,7 +150,7 @@ vi.mock("@mdxeditor/editor", async () => {
listsPlugin: () => ({}),
markdownShortcutPlugin: () => ({}),
quotePlugin: () => ({}),
- realmPlugin: (plugin: unknown) => plugin,
+ realmPlugin: (plugin: unknown) => () => plugin,
tablePlugin: () => ({}),
thematicBreakPlugin: () => ({}),
};
@@ -1433,6 +1433,45 @@ describe("TaskChatComposer", () => {
.toBe("ask");
});
+ it("does not hijack Shift+Tab for work mode cycling when the caret is inside a list item", () => {
+ const onWorkModeChange = vi.fn().mockResolvedValue(undefined);
+ renderComposer({
+ onAdd: vi.fn(),
+ workMode: "standard",
+ onWorkModeChange,
+ });
+
+ const editEl = editable();
+ const list = document.createElement("ul");
+ const item = document.createElement("li");
+ item.textContent = "nested bullet";
+ list.appendChild(item);
+ editEl.appendChild(list);
+
+ const selection = window.getSelection()!;
+ const range = document.createRange();
+ range.setStart(item.firstChild!, 4);
+ range.collapse(true);
+ selection.removeAllRanges();
+ selection.addRange(range);
+
+ const shiftTab = new KeyboardEvent("keydown", {
+ key: "Tab",
+ shiftKey: true,
+ bubbles: true,
+ cancelable: true,
+ });
+ flushSync(() => {
+ item.dispatchEvent(shiftTab);
+ });
+
+ // Wrapper must let Shift+Tab pass through to the editor's list dedent handler
+ // instead of toggling Plan mode.
+ expect(shiftTab.defaultPrevented).toBe(false);
+ expect(container.querySelector('[data-testid="task-chat-composer-mode"]')).toBeNull();
+ selection.removeAllRanges();
+ });
+
it("cycles Auto, Plan, and Ask modes with Cmd+Period while focused", () => {
const onWorkModeChange = vi.fn().mockResolvedValue(undefined);
renderComposer({
diff --git a/ui/src/components/task-chat/TaskChatComposer.tsx b/ui/src/components/task-chat/TaskChatComposer.tsx
index f6a5ac69700..58d1bbdc433 100644
--- a/ui/src/components/task-chat/TaskChatComposer.tsx
+++ b/ui/src/components/task-chat/TaskChatComposer.tsx
@@ -18,6 +18,7 @@ import { cn } from "@/lib/utils";
import { taskChatComposerSurfaceClasses } from "./composer-surface";
import { useComposerStop } from "@/hooks/useComposerStop";
import { useComposerSubmitKey } from "@/hooks/useComposerSubmitKey";
+import { isSelectionInsideList } from "@/lib/list-editing";
import { useStreamlinedTaskChatPresentation } from "./presentation-mode";
import {
DRAFT_DEBOUNCE_MS,
@@ -1404,9 +1405,12 @@ export function TaskChatComposer({
// `code` for Cmd+Period.
if (disabled || queuedEdit) return;
const isPeriod = e.key === "." || e.code === "Period";
+ const isShiftTab = e.key === "Tab" && e.shiftKey && !e.metaKey && !e.ctrlKey && !e.altKey;
+ // Let Shift+Tab dedent list items when the caret is inside a list;
+ // outside lists it continues to cycle the pending work mode.
const isModeShortcut =
(isPeriod && (e.metaKey || e.ctrlKey)) ||
- (e.key === "Tab" && e.shiftKey);
+ (isShiftTab && !isSelectionInsideList(e.target));
if (isModeShortcut) {
e.preventDefault();
e.stopPropagation();
diff --git a/ui/src/index.css b/ui/src/index.css
index 08d30c29cd0..8d9b7f78793 100644
--- a/ui/src/index.css
+++ b/ui/src/index.css
@@ -2339,20 +2339,48 @@ a.paperclip-mention-chip[data-mention-kind="agent"]::before {
padding-left: 1.6em;
}
+.paperclip-mdxeditor-content li > ul,
+.paperclip-mdxeditor-content li > ol {
+ margin: 0.25em 0;
+}
+
.paperclip-mdxeditor-content ul {
list-style: disc;
}
+.paperclip-mdxeditor-content ul ul {
+ list-style-type: circle;
+}
+
+.paperclip-mdxeditor-content ul ul ul {
+ list-style-type: square;
+}
+
.paperclip-mdxeditor-content ol {
list-style: decimal;
}
+.paperclip-mdxeditor-content ol ol {
+ list-style-type: lower-alpha;
+}
+
+.paperclip-mdxeditor-content ol ol ol {
+ list-style-type: lower-roman;
+}
+
.paperclip-mdxeditor-content li {
display: list-item;
margin: 0.3em 0;
line-height: inherit;
}
+.paperclip-mdxeditor-content li[class*="_nestedListItem_"],
+.paperclip-mdxeditor-content li:has(> ul:only-child),
+.paperclip-mdxeditor-content li:has(> ol:only-child) {
+ list-style-type: none;
+ margin: 0;
+}
+
.paperclip-mdxeditor-content li::marker {
color: var(--muted-foreground);
}
diff --git a/ui/src/lib/list-editing.test.ts b/ui/src/lib/list-editing.test.ts
new file mode 100644
index 00000000000..084c0ade4c8
--- /dev/null
+++ b/ui/src/lib/list-editing.test.ts
@@ -0,0 +1,830 @@
+// @vitest-environment jsdom
+
+import { createRequire } from "node:module";
+import { pathToFileURL } from "node:url";
+import { describe, expect, it } from "vitest";
+import {
+ $createParagraphNode,
+ $createRangeSelection,
+ $createTextNode,
+ $getRoot,
+ $getSelection,
+ $isElementNode,
+ $isParagraphNode,
+ $isRangeSelection,
+ $setSelection,
+ createEditor,
+ KEY_BACKSPACE_COMMAND,
+ KEY_DELETE_COMMAND,
+ KEY_ENTER_COMMAND,
+ KEY_TAB_COMMAND,
+ type ElementNode,
+ type Klass,
+ type LexicalEditor,
+ type LexicalNode,
+} from "lexical";
+import { registerRichText } from "@lexical/rich-text";
+import {
+ isSelectionInsideList,
+ registerListEditingCommands,
+ type ComposerSubmitKey,
+} from "./list-editing";
+
+// Load the exact ESM @lexical/* packages resolved by @mdxeditor/editor so tests
+// exercise the real runtime implementations with the same Lexical module instance.
+const requireFromUi = createRequire(import.meta.url);
+const requireFromMdxEditor = createRequire(requireFromUi.resolve("@mdxeditor/editor"));
+function resolveMdxEsm(pkg: string): string {
+ return pathToFileURL(requireFromMdxEditor.resolve(pkg).replace(/\.js$/, ".mjs")).href;
+}
+
+const lexicalList = (await import(/* @vite-ignore */ resolveMdxEsm("@lexical/list"))) as {
+ ListNode: Klass;
+ ListItemNode: Klass;
+ $createListNode: (listType: "bullet" | "number" | "check") => ElementNode;
+ $createListItemNode: (checked?: boolean) => ElementNode;
+ registerList: (editor: LexicalEditor) => () => void;
+};
+const lexicalExtension = (await import(/* @vite-ignore */ resolveMdxEsm("@lexical/extension"))) as {
+ registerTabIndentation: (editor: LexicalEditor) => () => void;
+};
+const lexicalMarkdown = (await import(/* @vite-ignore */ resolveMdxEsm("@lexical/markdown"))) as {
+ ORDERED_LIST: unknown;
+ UNORDERED_LIST: unknown;
+ CHECK_LIST: unknown;
+ registerMarkdownShortcuts: (editor: LexicalEditor, transformers: unknown[]) => () => void;
+};
+
+type SerializedNode =
+ | { type: "paragraph"; text: string }
+ | { type: "list"; listType: string; items: SerializedListItem[] };
+
+type SerializedListItem =
+ | { text: string; value: number; indent: number }
+ | { nested: SerializedNode };
+
+function serializeTree(editor: LexicalEditor): SerializedNode[] {
+ let result: SerializedNode[] = [];
+ editor.getEditorState().read(() => {
+ const serializeList = (listNode: ElementNode): SerializedNode => {
+ const items: SerializedListItem[] = [];
+ for (const child of listNode.getChildren()) {
+ if (!$isElementNode(child)) continue;
+ const firstChild = child.getFirstChild();
+ if (child.getChildrenSize() === 1 && firstChild && firstChild.getType() === "list" && $isElementNode(firstChild)) {
+ items.push({ nested: serializeList(firstChild) });
+ } else {
+ items.push({
+ text: child.getTextContent(),
+ value: (child as unknown as { getValue: () => number }).getValue(),
+ indent: child.getIndent(),
+ });
+ }
+ }
+ return {
+ type: "list",
+ listType: (listNode as unknown as { getListType: () => string }).getListType(),
+ items,
+ };
+ };
+
+ result = $getRoot()
+ .getChildren()
+ .map((child): SerializedNode => {
+ if ($isParagraphNode(child)) {
+ return { type: "paragraph", text: child.getTextContent() };
+ }
+ if ($isElementNode(child) && child.getType() === "list") {
+ return serializeList(child);
+ }
+ throw new Error(`Unexpected top-level node type: ${child.getType()}`);
+ });
+ });
+ return result;
+}
+
+function createRichListEditor(initialSubmitKey: ComposerSubmitKey = "enter") {
+ let submitKey: ComposerSubmitKey = initialSubmitKey;
+ const editor = createEditor({
+ namespace: "list-editing-test",
+ nodes: [lexicalList.ListNode, lexicalList.ListItemNode],
+ onError(error: Error) {
+ throw error;
+ },
+ });
+
+ const unregister = [
+ registerRichText(editor),
+ lexicalList.registerList(editor),
+ lexicalExtension.registerTabIndentation(editor),
+ lexicalMarkdown.registerMarkdownShortcuts(editor, [
+ lexicalMarkdown.ORDERED_LIST,
+ lexicalMarkdown.UNORDERED_LIST,
+ lexicalMarkdown.CHECK_LIST,
+ ]),
+ registerListEditingCommands(editor, { getSubmitKey: () => submitKey }),
+ ];
+
+ const typeText = (text: string) => {
+ // MarkdownShortcutPlugin checks single-character typing steps (anchorOffset <= prev + 1),
+ // so simulate live typing one character at a time.
+ for (const ch of text) {
+ editor.update(
+ () => {
+ const selection = $getSelection();
+ if ($isRangeSelection(selection)) {
+ selection.insertText(ch);
+ }
+ },
+ { discrete: true },
+ );
+ }
+ };
+
+ const dispatchKey = (
+ command:
+ | typeof KEY_ENTER_COMMAND
+ | typeof KEY_TAB_COMMAND
+ | typeof KEY_BACKSPACE_COMMAND
+ | typeof KEY_DELETE_COMMAND,
+ init: KeyboardEventInit,
+ ) => {
+ const event = new KeyboardEvent("keydown", { cancelable: true, ...init });
+ editor.update(
+ () => {
+ editor.dispatchCommand(command, event);
+ },
+ { discrete: true },
+ );
+ return event;
+ };
+
+ const cleanup = () => {
+ for (const fn of unregister) fn();
+ };
+
+ return {
+ editor,
+ setSubmitKey: (next: ComposerSubmitKey) => {
+ submitKey = next;
+ },
+ typeText,
+ pressShiftEnter: () => dispatchKey(KEY_ENTER_COMMAND, { key: "Enter", shiftKey: true }),
+ pressEnter: () => dispatchKey(KEY_ENTER_COMMAND, { key: "Enter" }),
+ pressTab: () => dispatchKey(KEY_TAB_COMMAND, { key: "Tab" }),
+ pressShiftTab: () => dispatchKey(KEY_TAB_COMMAND, { key: "Tab", shiftKey: true }),
+ pressBackspace: () => dispatchKey(KEY_BACKSPACE_COMMAND, { key: "Backspace" }),
+ pressDelete: () => dispatchKey(KEY_DELETE_COMMAND, { key: "Delete" }),
+ cleanup,
+ };
+}
+
+function seedList(
+ editor: LexicalEditor,
+ listType: "bullet" | "number",
+ labels: string[],
+ selectItemIndex = labels.length - 1,
+ selectOffset?: number,
+) {
+ const itemKeys: string[] = [];
+ editor.update(
+ () => {
+ const root = $getRoot();
+ root.clear();
+ const list = lexicalList.$createListNode(listType);
+ for (const label of labels) {
+ const item = lexicalList.$createListItemNode();
+ if (label.length > 0) {
+ item.append($createTextNode(label));
+ }
+ list.append(item);
+ itemKeys.push(item.getKey());
+ }
+ root.append(list);
+
+ const targetItem = list.getChildAtIndex(selectItemIndex) as ElementNode;
+ const firstChild = targetItem.getFirstChild();
+ if (firstChild && firstChild.getType() === "text") {
+ const textNode = firstChild as ReturnType;
+ const offset = selectOffset ?? textNode.getTextContentSize();
+ textNode.select(offset, offset);
+ } else {
+ targetItem.selectStart();
+ }
+ },
+ { discrete: true },
+ );
+ return itemKeys;
+}
+
+describe("list editing plugin (real Lexical)", () => {
+ it("creates rich bullet and numbered lists after Shift+Enter in enter-to-submit composers", () => {
+ const harness = createRichListEditor("enter");
+ try {
+ harness.editor.update(
+ () => {
+ const root = $getRoot();
+ root.clear();
+ const p = $createParagraphNode();
+ const text = $createTextNode("Agenda:");
+ p.append(text);
+ root.append(p);
+ text.selectEnd();
+ },
+ { discrete: true },
+ );
+
+ const shiftEnter = harness.pressShiftEnter();
+ expect(shiftEnter.defaultPrevented).toBe(true);
+
+ // Type "- " on the new paragraph; MarkdownShortcutPlugin must promote it to a bullet list.
+ harness.typeText("- first item");
+
+ expect(serializeTree(harness.editor)).toEqual([
+ { type: "paragraph", text: "Agenda:" },
+ {
+ type: "list",
+ listType: "bullet",
+ items: [{ text: "first item", value: 1, indent: 0 }],
+ },
+ ]);
+
+ // Shift+Enter adds the second bullet item rather than inserting a
.
+ harness.pressShiftEnter();
+ harness.typeText("second item");
+
+ expect(serializeTree(harness.editor)).toEqual([
+ { type: "paragraph", text: "Agenda:" },
+ {
+ type: "list",
+ listType: "bullet",
+ items: [
+ { text: "first item", value: 1, indent: 0 },
+ { text: "second item", value: 2, indent: 0 },
+ ],
+ },
+ ]);
+
+ // Shift+Enter twice exits the list back to a paragraph.
+ harness.pressShiftEnter();
+ harness.pressShiftEnter();
+ harness.typeText("1. numbered one");
+ harness.pressShiftEnter();
+ harness.typeText("numbered two");
+
+ expect(serializeTree(harness.editor)).toEqual([
+ { type: "paragraph", text: "Agenda:" },
+ {
+ type: "list",
+ listType: "bullet",
+ items: [
+ { text: "first item", value: 1, indent: 0 },
+ { text: "second item", value: 2, indent: 0 },
+ ],
+ },
+ {
+ type: "list",
+ listType: "number",
+ items: [
+ { text: "numbered one", value: 1, indent: 0 },
+ { text: "numbered two", value: 2, indent: 0 },
+ ],
+ },
+ ]);
+ } finally {
+ harness.cleanup();
+ }
+ });
+
+ it("indents with Tab and dedents with Shift+Tab from anywhere inside a list item", () => {
+ const harness = createRichListEditor("enter");
+ try {
+ // Caret at the END of "second" (not offset 0 — where Lexical's default TabIndentationPlugin inserts \t).
+ seedList(harness.editor, "bullet", ["first", "second"], 1, 6);
+
+ const tabEvent = harness.pressTab();
+ expect(tabEvent.defaultPrevented).toBe(true);
+ expect(serializeTree(harness.editor)).toEqual([
+ {
+ type: "list",
+ listType: "bullet",
+ items: [
+ { text: "first", value: 1, indent: 0 },
+ {
+ nested: {
+ type: "list",
+ listType: "bullet",
+ items: [{ text: "second", value: 1, indent: 1 }],
+ },
+ },
+ ],
+ },
+ ]);
+
+ // Shift+Tab from the middle of "second" dedents back to top level without inserting a tab.
+ harness.editor.update(
+ () => {
+ const selection = $getSelection();
+ if ($isRangeSelection(selection)) {
+ selection.anchor.offset = 3;
+ selection.focus.offset = 3;
+ }
+ },
+ { discrete: true },
+ );
+ const shiftTab1 = harness.pressShiftTab();
+ expect(shiftTab1.defaultPrevented).toBe(true);
+ expect(serializeTree(harness.editor)).toEqual([
+ {
+ type: "list",
+ listType: "bullet",
+ items: [
+ { text: "first", value: 1, indent: 0 },
+ { text: "second", value: 2, indent: 0 },
+ ],
+ },
+ ]);
+
+ // Another Shift+Tab on a top-level list item lifts it out into a paragraph and preserves caret offset.
+ const shiftTab2 = harness.pressShiftTab();
+ expect(shiftTab2.defaultPrevented).toBe(true);
+ expect(serializeTree(harness.editor)).toEqual([
+ {
+ type: "list",
+ listType: "bullet",
+ items: [{ text: "first", value: 1, indent: 0 }],
+ },
+ { type: "paragraph", text: "second" },
+ ]);
+
+ harness.editor.getEditorState().read(() => {
+ const selection = $getSelection();
+ expect($isRangeSelection(selection)).toBe(true);
+ if ($isRangeSelection(selection)) {
+ expect(selection.anchor.offset).toBe(3);
+ }
+ });
+ } finally {
+ harness.cleanup();
+ }
+ });
+
+ it("prevents Tab from inserting a tab character or creating an orphan nested list on the first item", () => {
+ const harness = createRichListEditor("enter");
+ try {
+ seedList(harness.editor, "number", ["only item"], 0, 9);
+
+ const tabEvent = harness.pressTab();
+ expect(tabEvent.defaultPrevented).toBe(true);
+ expect(serializeTree(harness.editor)).toEqual([
+ {
+ type: "list",
+ listType: "number",
+ items: [{ text: "only item", value: 1, indent: 0 }],
+ },
+ ]);
+ } finally {
+ harness.cleanup();
+ }
+ });
+
+ it("indents and dedents multi-item list selections and updates ordered numbering", () => {
+ const harness = createRichListEditor("enter");
+ try {
+ seedList(harness.editor, "number", ["one", "two", "three", "four"]);
+
+ // Select across "two" and "three"
+ harness.editor.update(
+ () => {
+ const list = $getRoot().getFirstChild() as ElementNode;
+ const two = list.getChildAtIndex(1) as ElementNode;
+ const three = list.getChildAtIndex(2) as ElementNode;
+ const range = $createRangeSelection();
+ range.anchor.set(two.getFirstChild()!.getKey(), 0, "text");
+ range.focus.set(three.getFirstChild()!.getKey(), 5, "text");
+ $setSelection(range);
+ },
+ { discrete: true },
+ );
+
+ harness.pressTab();
+ expect(serializeTree(harness.editor)).toEqual([
+ {
+ type: "list",
+ listType: "number",
+ items: [
+ { text: "one", value: 1, indent: 0 },
+ {
+ nested: {
+ type: "list",
+ listType: "number",
+ items: [
+ { text: "two", value: 1, indent: 1 },
+ { text: "three", value: 2, indent: 1 },
+ ],
+ },
+ },
+ { text: "four", value: 2, indent: 0 },
+ ],
+ },
+ ]);
+
+ harness.pressShiftTab();
+ expect(serializeTree(harness.editor)).toEqual([
+ {
+ type: "list",
+ listType: "number",
+ items: [
+ { text: "one", value: 1, indent: 0 },
+ { text: "two", value: 2, indent: 0 },
+ { text: "three", value: 3, indent: 0 },
+ { text: "four", value: 4, indent: 0 },
+ ],
+ },
+ ]);
+ } finally {
+ harness.cleanup();
+ }
+ });
+
+ it("dedents empty nested list items on Shift+Enter and Backspace, and promotes nested children when removing a parent item", () => {
+ const harness = createRichListEditor("enter");
+ try {
+ seedList(harness.editor, "bullet", ["parent", "child"], 1, 5);
+ harness.pressTab();
+
+ // Add an empty nested bullet via Shift+Enter, then Shift+Enter again to dedent to top level.
+ harness.pressShiftEnter();
+ harness.pressShiftEnter();
+ expect(serializeTree(harness.editor)).toEqual([
+ {
+ type: "list",
+ listType: "bullet",
+ items: [
+ { text: "parent", value: 1, indent: 0 },
+ {
+ nested: {
+ type: "list",
+ listType: "bullet",
+ items: [{ text: "child", value: 1, indent: 1 }],
+ },
+ },
+ { text: "", value: 2, indent: 0 },
+ ],
+ },
+ ]);
+
+ // Backspace on the empty top-level bullet converts it to a paragraph.
+ harness.pressBackspace();
+ expect(serializeTree(harness.editor)).toEqual([
+ {
+ type: "list",
+ listType: "bullet",
+ items: [
+ { text: "parent", value: 1, indent: 0 },
+ {
+ nested: {
+ type: "list",
+ listType: "bullet",
+ items: [{ text: "child", value: 1, indent: 1 }],
+ },
+ },
+ ],
+ },
+ { type: "paragraph", text: "" },
+ ]);
+
+ // Now place caret at offset 0 of "parent" and Backspace: "parent" lifts to a paragraph
+ // and its nested "child" promotes cleanly to top-level instead of becoming an orphan nested list.
+ harness.editor.update(
+ () => {
+ const list = $getRoot().getFirstChild() as ElementNode;
+ const parentItem = list.getFirstChild() as ElementNode;
+ const textNode = parentItem.getFirstChild() as ReturnType;
+ textNode.select(0, 0);
+ },
+ { discrete: true },
+ );
+ harness.pressBackspace();
+ expect(serializeTree(harness.editor)).toEqual([
+ { type: "paragraph", text: "parent" },
+ {
+ type: "list",
+ listType: "bullet",
+ items: [{ text: "child", value: 1, indent: 0 }],
+ },
+ { type: "paragraph", text: "" },
+ ]);
+ } finally {
+ harness.cleanup();
+ }
+ });
+
+ it("keeps Shift+Enter as a soft line break when submitKey is mod-enter and reacts dynamically when submitKey switches", () => {
+ const harness = createRichListEditor("mod-enter");
+ try {
+ seedList(harness.editor, "bullet", ["first"], 0, 5);
+
+ // In mod-enter mode, Shift+Enter inserts a soft break inside the same list item.
+ harness.pressShiftEnter();
+ expect(serializeTree(harness.editor)).toEqual([
+ {
+ type: "list",
+ listType: "bullet",
+ items: [{ text: "first\n", value: 1, indent: 0 }],
+ },
+ ]);
+
+ // Plain Enter in mod-enter mode creates a new list item.
+ harness.pressEnter();
+ expect(serializeTree(harness.editor)).toEqual([
+ {
+ type: "list",
+ listType: "bullet",
+ items: [
+ { text: "first\n", value: 1, indent: 0 },
+ { text: "", value: 2, indent: 0 },
+ ],
+ },
+ ]);
+
+ // Switching submitKey dynamically to "enter" makes Shift+Enter exit the empty list item.
+ harness.setSubmitKey("enter");
+ harness.pressShiftEnter();
+ expect(serializeTree(harness.editor)).toEqual([
+ {
+ type: "list",
+ listType: "bullet",
+ items: [{ text: "first\n", value: 1, indent: 0 }],
+ },
+ { type: "paragraph", text: "" },
+ ]);
+ } finally {
+ harness.cleanup();
+ }
+ });
+
+ it("dedents multi-level selections by exactly one level per Shift+Tab without double-dedenting descendants", () => {
+ const harness = createRichListEditor("enter");
+ try {
+ seedList(harness.editor, "bullet", ["parent", "child", "grandchild"], 1, 5);
+ harness.pressTab(); // child -> indent 1
+ harness.editor.update(
+ () => {
+ const rootList = $getRoot().getFirstChild() as ElementNode;
+ const grandchild = rootList.getLastChild() as ElementNode;
+ grandchild.selectEnd();
+ },
+ { discrete: true },
+ );
+ harness.pressTab(); // grandchild -> indent 1
+ harness.pressTab(); // grandchild -> indent 2
+
+ // Select from "parent" through "grandchild".
+ harness.editor.update(
+ () => {
+ const rootList = $getRoot().getFirstChild() as ElementNode;
+ const parentItem = rootList.getFirstChild() as ElementNode;
+ const nested1 = rootList.getChildAtIndex(1) as ElementNode;
+ const list1 = nested1.getFirstChild() as ElementNode;
+ const nested2 = list1.getChildAtIndex(1) as ElementNode;
+ const list2 = nested2.getFirstChild() as ElementNode;
+ const grandchild = list2.getFirstChild() as ElementNode;
+
+ const range = $createRangeSelection();
+ range.anchor.set(parentItem.getFirstChild()!.getKey(), 0, "text");
+ range.focus.set(grandchild.getFirstChild()!.getKey(), 10, "text");
+ $setSelection(range);
+ },
+ { discrete: true },
+ );
+
+ harness.pressShiftTab();
+ expect(serializeTree(harness.editor)).toEqual([
+ { type: "paragraph", text: "parent" },
+ {
+ type: "list",
+ listType: "bullet",
+ items: [
+ { text: "child", value: 1, indent: 0 },
+ {
+ nested: {
+ type: "list",
+ listType: "bullet",
+ items: [{ text: "grandchild", value: 1, indent: 1 }],
+ },
+ },
+ ],
+ },
+ ]);
+ } finally {
+ harness.cleanup();
+ }
+ });
+
+ it("promotes grandchildren when pressing Shift+Enter on an empty nested parent item", () => {
+ const harness = createRichListEditor("enter");
+ try {
+ seedList(harness.editor, "bullet", ["root", "mid", "leaf"], 1, 3);
+ harness.pressTab(); // mid -> indent 1
+ harness.editor.update(
+ () => {
+ const rootList = $getRoot().getFirstChild() as ElementNode;
+ const leaf = rootList.getLastChild() as ElementNode;
+ leaf.selectEnd();
+ },
+ { discrete: true },
+ );
+ harness.pressTab(); // leaf -> indent 1
+ harness.pressTab(); // leaf -> indent 2
+
+ // Clear "mid" so it is an empty indent-1 item owning an indent-2 child, then press Shift+Enter.
+ harness.editor.update(
+ () => {
+ const rootList = $getRoot().getFirstChild() as ElementNode;
+ const nested1 = rootList.getChildAtIndex(1) as ElementNode;
+ const list1 = nested1.getFirstChild() as ElementNode;
+ const mid = list1.getFirstChild() as ElementNode;
+ mid.clear();
+ mid.selectStart();
+ },
+ { discrete: true },
+ );
+ harness.pressShiftEnter();
+ expect(serializeTree(harness.editor)).toEqual([
+ {
+ type: "list",
+ listType: "bullet",
+ items: [
+ { text: "root", value: 1, indent: 0 },
+ { text: "", value: 2, indent: 0 },
+ {
+ nested: {
+ type: "list",
+ listType: "bullet",
+ items: [{ text: "leaf", value: 1, indent: 1 }],
+ },
+ },
+ ],
+ },
+ ]);
+ } finally {
+ harness.cleanup();
+ }
+ });
+
+ it("preserves mixed child list types when removing or outdenting a parent item", () => {
+ const harness = createRichListEditor("enter");
+ try {
+ // Build:
+ // - parent (bullet)
+ // 1. step one (number)
+ // 2. step two (number)
+ // - trailing (bullet)
+ harness.editor.update(
+ () => {
+ const root = $getRoot();
+ root.clear();
+ const outer = lexicalList.$createListNode("bullet");
+ const parentItem = lexicalList.$createListItemNode();
+ const parentText = $createTextNode("parent");
+ parentItem.append(parentText);
+
+ const nestedWrapper = lexicalList.$createListItemNode();
+ const innerOrdered = lexicalList.$createListNode("number");
+ const stepOne = lexicalList.$createListItemNode();
+ stepOne.append($createTextNode("step one"));
+ const stepTwo = lexicalList.$createListItemNode();
+ stepTwo.append($createTextNode("step two"));
+ innerOrdered.append(stepOne, stepTwo);
+ nestedWrapper.append(innerOrdered);
+
+ const trailing = lexicalList.$createListItemNode();
+ trailing.append($createTextNode("trailing"));
+
+ outer.append(parentItem, nestedWrapper, trailing);
+ root.append(outer);
+ parentText.select(0, 0);
+ },
+ { discrete: true },
+ );
+
+ // Backspace at start of "parent" lifts "parent" to a paragraph while keeping
+ // the promoted child list numbered and the trailing sibling bulleted.
+ harness.pressBackspace();
+ expect(serializeTree(harness.editor)).toEqual([
+ { type: "paragraph", text: "parent" },
+ {
+ type: "list",
+ listType: "number",
+ items: [
+ { text: "step one", value: 1, indent: 0 },
+ { text: "step two", value: 2, indent: 0 },
+ ],
+ },
+ {
+ type: "list",
+ listType: "bullet",
+ items: [{ text: "trailing", value: 1, indent: 0 }],
+ },
+ ]);
+
+ // Also verify nested mixed-type promotion when outdenting a bullet child
+ // that owns a numbered grandchild list:
+ // - root (bullet, 0)
+ // - mid (bullet, 1)
+ // 1. sub (number, 2)
+ harness.editor.update(
+ () => {
+ const root = $getRoot();
+ root.clear();
+ const outer = lexicalList.$createListNode("bullet");
+ const rootItem = lexicalList.$createListItemNode();
+ rootItem.append($createTextNode("root"));
+
+ const wrapper1 = lexicalList.$createListItemNode();
+ const midList = lexicalList.$createListNode("bullet");
+ const midItem = lexicalList.$createListItemNode();
+ const midText = $createTextNode("mid");
+ midItem.append(midText);
+
+ const wrapper2 = lexicalList.$createListItemNode();
+ const subOrdered = lexicalList.$createListNode("number");
+ const subItem = lexicalList.$createListItemNode();
+ subItem.append($createTextNode("sub"));
+ subOrdered.append(subItem);
+ wrapper2.append(subOrdered);
+
+ midList.append(midItem, wrapper2);
+ wrapper1.append(midList);
+ outer.append(rootItem, wrapper1);
+ root.append(outer);
+ midText.select(0, 0);
+ },
+ { discrete: true },
+ );
+
+ harness.pressShiftTab();
+ expect(serializeTree(harness.editor)).toEqual([
+ {
+ type: "list",
+ listType: "bullet",
+ items: [
+ { text: "root", value: 1, indent: 0 },
+ { text: "mid", value: 2, indent: 0 },
+ {
+ nested: {
+ type: "list",
+ listType: "number",
+ items: [{ text: "sub", value: 1, indent: 1 }],
+ },
+ },
+ ],
+ },
+ ]);
+ } finally {
+ harness.cleanup();
+ }
+ });
+});
+
+describe("isSelectionInsideList", () => {
+ it("detects selections inside rich DOM list items and textarea markdown list lines", () => {
+ const container = document.createElement("div");
+ container.innerHTML =
+ '';
+ document.body.appendChild(container);
+ try {
+ const pText = container.querySelector("p")!.firstChild!;
+ const liText = container.querySelector("li")!.firstChild!;
+ const editable = container.querySelector('[contenteditable="true"]')!;
+ const selection = window.getSelection()!;
+
+ const pRange = document.createRange();
+ pRange.setStart(pText, 2);
+ pRange.collapse(true);
+ selection.removeAllRanges();
+ selection.addRange(pRange);
+ expect(isSelectionInsideList(editable)).toBe(false);
+
+ const liRange = document.createRange();
+ liRange.setStart(liText, 3);
+ liRange.collapse(true);
+ selection.removeAllRanges();
+ selection.addRange(liRange);
+ expect(isSelectionInsideList(editable)).toBe(true);
+
+ const textarea = document.createElement("textarea");
+ textarea.value = "Intro\n- first\n 1. nested";
+ textarea.setSelectionRange(2, 2);
+ expect(isSelectionInsideList(textarea)).toBe(false);
+ textarea.setSelectionRange(9, 9);
+ expect(isSelectionInsideList(textarea)).toBe(true);
+ textarea.setSelectionRange(18, 18);
+ expect(isSelectionInsideList(textarea)).toBe(true);
+ } finally {
+ window.getSelection()?.removeAllRanges();
+ container.remove();
+ }
+ });
+});
diff --git a/ui/src/lib/list-editing.ts b/ui/src/lib/list-editing.ts
new file mode 100644
index 00000000000..3054083fa0a
--- /dev/null
+++ b/ui/src/lib/list-editing.ts
@@ -0,0 +1,424 @@
+import { createRootEditorSubscription$, realmPlugin } from "@mdxeditor/editor";
+import {
+ $copyNode,
+ $createParagraphNode,
+ $getSelection,
+ $isElementNode,
+ $isRangeSelection,
+ COMMAND_PRIORITY_HIGH,
+ INSERT_PARAGRAPH_COMMAND,
+ KEY_BACKSPACE_COMMAND,
+ KEY_ENTER_COMMAND,
+ KEY_TAB_COMMAND,
+ type ElementNode,
+ type LexicalEditor,
+ type LexicalNode,
+ type RangeSelection,
+} from "lexical";
+import { isTextareaSelectionInList } from "./textarea-list-editing";
+
+export type ComposerSubmitKey = "enter" | "mod-enter";
+
+const MAX_LIST_INDENT_DEPTH = 7;
+
+function isListNode(node: LexicalNode | null | undefined): node is ElementNode {
+ return Boolean(node && $isElementNode(node) && node.getType() === "list");
+}
+
+function isListItemNode(node: LexicalNode | null | undefined): node is ElementNode {
+ return Boolean(node && $isElementNode(node) && node.getType() === "listitem");
+}
+
+/** Lexical wraps nested lists inside a dedicated ListItemNode whose sole child is a ListNode. */
+function isNestedListWrapper(node: LexicalNode | null | undefined): node is ElementNode {
+ if (!isListItemNode(node)) return false;
+ return node.getChildrenSize() === 1 && isListNode(node.getFirstChild());
+}
+
+function findNearestListItem(node: LexicalNode | null | undefined): ElementNode | null {
+ let current: LexicalNode | null | undefined = node;
+ while (current) {
+ if (isListItemNode(current) && !isNestedListWrapper(current)) {
+ return current;
+ }
+ current = current.getParent();
+ }
+ return null;
+}
+
+function getListItemDepth(item: ElementNode): number {
+ let depth = 0;
+ let current: LexicalNode | null = item.getParent();
+ while (current) {
+ if (isListNode(current)) depth += 1;
+ current = current.getParent();
+ }
+ return depth;
+}
+
+function getSelectedListItems(selection: RangeSelection): ElementNode[] {
+ if (selection.isCollapsed()) {
+ const item = findNearestListItem(selection.anchor.getNode());
+ return item ? [item] : [];
+ }
+
+ const items: ElementNode[] = [];
+ const seen = new Set();
+ const addItem = (node: LexicalNode | null | undefined) => {
+ const item = findNearestListItem(node);
+ if (item && !seen.has(item.getKey())) {
+ seen.add(item.getKey());
+ items.push(item);
+ }
+ };
+
+ for (const node of selection.getNodes()) {
+ addItem(node);
+ }
+ if (items.length === 0) {
+ addItem(selection.anchor.getNode());
+ addItem(selection.focus.getNode());
+ }
+ return items;
+}
+
+function getListType(node: ElementNode): string | null {
+ const candidate = node as unknown as { getListType?: () => string };
+ return typeof candidate.getListType === "function" ? candidate.getListType() : null;
+}
+
+/**
+ * Promote any leading nested-list wrapper items up one level so a list never
+ * begins with an orphaned nested list (which Markdown cannot represent), while
+ * preserving the inner list's type when a mixed-type child list is promoted.
+ */
+function unwrapLeadingNestedLists(listNode: ElementNode): void {
+ const outerListType = getListType(listNode);
+ while (listNode.isAttached()) {
+ const firstChild = listNode.getFirstChild();
+ if (!isNestedListWrapper(firstChild)) return;
+ const innerList = firstChild.getFirstChild();
+ if (!isListNode(innerList)) return;
+
+ const innerListType = getListType(innerList);
+ if (innerListType === outerListType) {
+ for (const innerChild of innerList.getChildren()) {
+ firstChild.insertBefore(innerChild);
+ }
+ firstChild.remove();
+ continue;
+ }
+
+ // Mixed list types (e.g., numbered child inside bulleted parent): promote
+ // `innerList` intact so its list type is preserved.
+ const parentWrapper = listNode.getParent();
+ if (isListItemNode(parentWrapper)) {
+ if (listNode.getChildrenSize() === 1) {
+ listNode.replace(innerList);
+ unwrapLeadingNestedLists(innerList);
+ return;
+ }
+ const promotedWrapper = $copyNode(parentWrapper);
+ promotedWrapper.append(innerList);
+ parentWrapper.insertBefore(promotedWrapper);
+ firstChild.remove();
+ unwrapLeadingNestedLists(innerList);
+ } else {
+ listNode.insertBefore(innerList);
+ firstChild.remove();
+ unwrapLeadingNestedLists(innerList);
+ if (listNode.isAttached() && listNode.getChildrenSize() === 0) {
+ listNode.remove();
+ return;
+ }
+ }
+ }
+}
+
+function liftTopLevelListItemToParagraph(
+ item: ElementNode,
+ selection: RangeSelection | null,
+): boolean {
+ const listNode = item.getParent();
+ if (!isListNode(listNode)) return false;
+
+ const anchorWasItem = Boolean(
+ selection && selection.anchor.type === "element" && selection.anchor.getNode().is(item),
+ );
+ const focusWasItem = Boolean(
+ selection && selection.focus.type === "element" && selection.focus.getNode().is(item),
+ );
+ const anchorOffset = selection?.anchor.offset ?? 0;
+ const focusOffset = selection?.focus.offset ?? 0;
+
+ const paragraph = $createParagraphNode();
+ const children = item.getChildren();
+ if (children.length > 0) {
+ paragraph.append(...children);
+ }
+
+ const prevSiblings = item.getPreviousSiblings();
+ const nextSiblings = item.getNextSiblings();
+ item.remove();
+
+ if (prevSiblings.length === 0 && nextSiblings.length === 0) {
+ listNode.replace(paragraph);
+ } else if (prevSiblings.length === 0) {
+ listNode.insertBefore(paragraph);
+ unwrapLeadingNestedLists(listNode);
+ } else {
+ listNode.insertAfter(paragraph);
+ if (nextSiblings.length > 0) {
+ const trailingList = $copyNode(listNode);
+ trailingList.append(...nextSiblings);
+ unwrapLeadingNestedLists(trailingList);
+ paragraph.insertAfter(trailingList);
+ }
+ }
+
+ if (selection) {
+ if (anchorWasItem) {
+ selection.anchor.set(
+ paragraph.getKey(),
+ Math.min(anchorOffset, paragraph.getChildrenSize()),
+ "element",
+ );
+ }
+ if (focusWasItem) {
+ selection.focus.set(
+ paragraph.getKey(),
+ Math.min(focusOffset, paragraph.getChildrenSize()),
+ "element",
+ );
+ }
+ }
+
+ return true;
+}
+
+export function indentSelectedListItems(selection: RangeSelection): boolean {
+ const items = getSelectedListItems(selection);
+ if (items.length === 0) return false;
+
+ for (const item of items) {
+ if (getListItemDepth(item) >= MAX_LIST_INDENT_DEPTH) continue;
+ // Markdown cannot represent a nested list with no preceding parent item.
+ if (item.getPreviousSibling() === null) continue;
+ item.setIndent(item.getIndent() + 1);
+ }
+ return true;
+}
+
+function outdentListItem(item: ElementNode): void {
+ item.setIndent(item.getIndent() - 1);
+ const nextSibling = item.getNextSibling();
+ if (isNestedListWrapper(nextSibling)) {
+ const innerList = nextSibling.getFirstChild();
+ if (isListNode(innerList)) {
+ unwrapLeadingNestedLists(innerList);
+ }
+ }
+}
+
+export function outdentSelectedListItems(selection: RangeSelection): boolean {
+ const items = getSelectedListItems(selection);
+ if (items.length === 0) return false;
+
+ // Snapshot original indents so promoting children when an ancestor lifts or
+ // outdents does not cause selected descendants to be dedented twice.
+ const initialIndents = new Map();
+ for (const item of items) {
+ initialIndents.set(item.getKey(), item.getIndent());
+ }
+
+ for (const item of items) {
+ if (!item.isAttached()) continue;
+ const initialIndent = initialIndents.get(item.getKey()) ?? item.getIndent();
+ if (initialIndent > 0) {
+ if (item.getIndent() < initialIndent) continue;
+ outdentListItem(item);
+ } else {
+ liftTopLevelListItemToParagraph(item, selection);
+ }
+ }
+ return true;
+}
+
+function findListItemAtStart(selection: RangeSelection): ElementNode | null {
+ if (!selection.isCollapsed()) return null;
+ if (selection.anchor.offset !== 0) return null;
+
+ let current: LexicalNode | null = selection.anchor.getNode();
+ while (current && !isListItemNode(current)) {
+ if (current.getPreviousSibling() !== null) return null;
+ current = current.getParent();
+ }
+ if (!isListItemNode(current) || isNestedListWrapper(current)) return null;
+ return current;
+}
+
+function findEmptyListItemWithNestedChildren(selection: RangeSelection): ElementNode | null {
+ if (!selection.isCollapsed()) return null;
+ const item = findNearestListItem(selection.anchor.getNode());
+ if (!item) return null;
+ if (!isNestedListWrapper(item.getNextSibling())) return null;
+ if (item.getTextContent().trim() !== "") return null;
+ return item;
+}
+
+export interface RegisterListEditingOptions {
+ getSubmitKey: () => ComposerSubmitKey;
+}
+
+export function registerListEditingCommands(
+ editor: LexicalEditor,
+ options: RegisterListEditingOptions,
+): () => void {
+ const unregisterEnter = editor.registerCommand(
+ KEY_ENTER_COMMAND,
+ (event: KeyboardEvent | null) => {
+ if (options.getSubmitKey() !== "enter") return false;
+ if (!event || !event.shiftKey || event.metaKey || event.ctrlKey || event.altKey) {
+ return false;
+ }
+ if (event.isComposing || event.keyCode === 229) return false;
+
+ const selection = $getSelection();
+ if (!$isRangeSelection(selection)) return false;
+
+ // In enter-to-submit composers, Shift+Enter is the primary newline key.
+ // Dispatch INSERT_PARAGRAPH_COMMAND instead of Lexical's default soft
+ //
break so markdown list shortcuts work on new lines, list items
+ // continue cleanly, and empty list items dedent/exit naturally.
+ event.preventDefault();
+ return editor.dispatchCommand(INSERT_PARAGRAPH_COMMAND, undefined);
+ },
+ COMMAND_PRIORITY_HIGH,
+ );
+
+ const unregisterTab = editor.registerCommand(
+ KEY_TAB_COMMAND,
+ (event: KeyboardEvent) => {
+ if (event.metaKey || event.ctrlKey || event.altKey) return false;
+ const selection = $getSelection();
+ if (!$isRangeSelection(selection)) return false;
+
+ const handled = event.shiftKey
+ ? outdentSelectedListItems(selection)
+ : indentSelectedListItems(selection);
+ if (!handled) return false;
+
+ event.preventDefault();
+ return true;
+ },
+ COMMAND_PRIORITY_HIGH,
+ );
+
+ const unregisterInsertParagraph = editor.registerCommand(
+ INSERT_PARAGRAPH_COMMAND,
+ () => {
+ const selection = $getSelection();
+ if (!$isRangeSelection(selection)) return false;
+ const emptyParent = findEmptyListItemWithNestedChildren(selection);
+ if (!emptyParent) return false;
+ if (emptyParent.getIndent() > 0) {
+ outdentListItem(emptyParent);
+ return true;
+ }
+ return liftTopLevelListItemToParagraph(emptyParent, selection);
+ },
+ COMMAND_PRIORITY_HIGH,
+ );
+
+ const unregisterBackspace = editor.registerCommand(
+ KEY_BACKSPACE_COMMAND,
+ (event: KeyboardEvent | null) => {
+ const selection = $getSelection();
+ if (!$isRangeSelection(selection)) return false;
+
+ const listItem = findListItemAtStart(selection);
+ if (!listItem || !isNestedListWrapper(listItem.getNextSibling())) {
+ return false;
+ }
+
+ // When backspacing an item that owns nested children, promote its
+ // children up one level instead of leaving an orphaned nested list.
+ if (listItem.getIndent() > 0) {
+ outdentListItem(listItem);
+ event?.preventDefault();
+ return true;
+ }
+ if (!liftTopLevelListItemToParagraph(listItem, selection)) {
+ return false;
+ }
+ event?.preventDefault();
+ return true;
+ },
+ COMMAND_PRIORITY_HIGH,
+ );
+
+ return () => {
+ unregisterEnter();
+ unregisterInsertParagraph();
+ unregisterTab();
+ unregisterBackspace();
+ };
+}
+
+export interface ListEditingPluginParams {
+ submitKeyRef: { readonly current: ComposerSubmitKey };
+}
+
+export const listEditingPlugin = realmPlugin({
+ init(realm, params) {
+ const getSubmitKey = () => params?.submitKeyRef.current ?? "mod-enter";
+ realm.pub(createRootEditorSubscription$, [
+ (editor) => registerListEditingCommands(editor, { getSubmitKey }),
+ ]);
+ },
+});
+
+function nodeClosestList(node: Node | null): Element | null {
+ if (!node) return null;
+ const element = node instanceof Element ? node : node.parentElement;
+ return element?.closest("li, ul, ol") ?? null;
+}
+
+/**
+ * Determine whether the active selection or event target sits inside a rich
+ * list item (or a markdown list line in a plain-text fallback textarea).
+ * Used by composer wrappers so Shift+Tab dedents lists instead of triggering
+ * wrapper-level shortcuts.
+ */
+export function isSelectionInsideList(target: EventTarget | null): boolean {
+ if (target instanceof HTMLTextAreaElement) {
+ return isTextareaSelectionInList(
+ target.value,
+ target.selectionStart ?? 0,
+ target.selectionEnd ?? 0,
+ );
+ }
+
+ if (typeof window !== "undefined") {
+ const selection = window.getSelection();
+ if (selection && selection.rangeCount > 0) {
+ if (nodeClosestList(selection.anchorNode) || nodeClosestList(selection.focusNode)) {
+ return true;
+ }
+ if (!selection.isCollapsed) {
+ const range = selection.getRangeAt(0);
+ const ancestor = range.commonAncestorContainer;
+ const container = ancestor instanceof Element ? ancestor : ancestor.parentElement;
+ if (container) {
+ for (const li of container.querySelectorAll("li")) {
+ if (typeof selection.containsNode === "function" && selection.containsNode(li, true)) {
+ return true;
+ }
+ }
+ }
+ }
+ }
+ }
+
+ return target instanceof Node && Boolean(nodeClosestList(target));
+}
diff --git a/ui/src/lib/textarea-list-editing.test.ts b/ui/src/lib/textarea-list-editing.test.ts
new file mode 100644
index 00000000000..57352535359
--- /dev/null
+++ b/ui/src/lib/textarea-list-editing.test.ts
@@ -0,0 +1,641 @@
+import { describe, expect, it } from "vitest";
+import { fromMarkdown } from "mdast-util-from-markdown";
+import {
+ applyTextareaListKeyDown,
+ isTextareaSelectionInList,
+ type TextareaListKeyEvent,
+} from "./textarea-list-editing";
+
+function keyEvent(
+ key: string,
+ overrides: Partial = {},
+): TextareaListKeyEvent {
+ return {
+ key,
+ shiftKey: false,
+ metaKey: false,
+ ctrlKey: false,
+ altKey: false,
+ isComposing: false,
+ ...overrides,
+ };
+}
+
+describe("textarea list editing", () => {
+ it("continues unordered and ordered lists on Shift+Enter in enter-to-submit mode", () => {
+ const bullet = applyTextareaListKeyDown(
+ { value: "- first", selectionStart: 7, selectionEnd: 7 },
+ keyEvent("Enter", { shiftKey: true }),
+ { submitKey: "enter" },
+ );
+ expect(bullet).toEqual({
+ value: "- first\n- ",
+ selectionStart: 10,
+ selectionEnd: 10,
+ });
+
+ const ordered = applyTextareaListKeyDown(
+ { value: "1. one\n2. three", selectionStart: 6, selectionEnd: 6 },
+ keyEvent("Enter", { shiftKey: true }),
+ { submitKey: "enter" },
+ );
+ expect(ordered).toEqual({
+ value: "1. one\n2. \n3. three",
+ selectionStart: 10,
+ selectionEnd: 10,
+ });
+
+ // Non-list lines pass through untouched so the browser inserts a normal newline.
+ const plain = applyTextareaListKeyDown(
+ { value: "hello", selectionStart: 5, selectionEnd: 5 },
+ keyEvent("Enter", { shiftKey: true }),
+ { submitKey: "enter" },
+ );
+ expect(plain).toBeNull();
+
+ // Newline on a parent item with existing children inserts the new sibling
+ // after the descendant block so children stay attached to the original item.
+ const bulletParentWithChild = applyTextareaListKeyDown(
+ { value: "- parent\n - child", selectionStart: 8, selectionEnd: 8 },
+ keyEvent("Enter", { shiftKey: true }),
+ { submitKey: "enter" },
+ );
+ expect(bulletParentWithChild).toEqual({
+ value: "- parent\n - child\n- ",
+ selectionStart: 21,
+ selectionEnd: 21,
+ });
+
+ const orderedParentWithChild = applyTextareaListKeyDown(
+ { value: "1. parent\n 1. child\n2. next", selectionStart: 9, selectionEnd: 9 },
+ keyEvent("Enter", { shiftKey: true }),
+ { submitKey: "enter" },
+ );
+ expect(orderedParentWithChild).toEqual({
+ value: "1. parent\n 1. child\n2. \n3. next",
+ selectionStart: 25,
+ selectionEnd: 25,
+ });
+
+ // Caret at the start of a parent's content inserts an empty item above and keeps
+ // the parent item and its nested children together below.
+ const bulletStartOfParent = applyTextareaListKeyDown(
+ { value: "- parent\n - child", selectionStart: 2, selectionEnd: 2 },
+ keyEvent("Enter", { shiftKey: true }),
+ { submitKey: "enter" },
+ );
+ expect(bulletStartOfParent).toEqual({
+ value: "- \n- parent\n - child",
+ selectionStart: 5,
+ selectionEnd: 5,
+ });
+
+ const orderedStartOfParent = applyTextareaListKeyDown(
+ { value: "1. parent\n 1. child", selectionStart: 3, selectionEnd: 3 },
+ keyEvent("Enter", { shiftKey: true }),
+ { submitKey: "enter" },
+ );
+ expect(orderedStartOfParent).toEqual({
+ value: "1. \n2. parent\n 1. child",
+ selectionStart: 7,
+ selectionEnd: 7,
+ });
+ });
+
+ it("dedents empty nested list items and exits empty top-level items on newline", () => {
+ const dedented = applyTextareaListKeyDown(
+ { value: "- parent\n - ", selectionStart: 13, selectionEnd: 13 },
+ keyEvent("Enter", { shiftKey: true }),
+ { submitKey: "enter" },
+ );
+ expect(dedented).toEqual({
+ value: "- parent\n- ",
+ selectionStart: 11,
+ selectionEnd: 11,
+ });
+
+ const exited = applyTextareaListKeyDown(
+ { value: "- parent\n- ", selectionStart: 11, selectionEnd: 11 },
+ keyEvent("Enter", { shiftKey: true }),
+ { submitKey: "enter" },
+ );
+ expect(exited).toEqual({
+ value: "- parent\n",
+ selectionStart: 9,
+ selectionEnd: 9,
+ });
+
+ const dedentedOrdered = applyTextareaListKeyDown(
+ { value: "1. one\n2. two\n 1. child\n 2. ", selectionStart: 32, selectionEnd: 32 },
+ keyEvent("Enter", { shiftKey: true }),
+ { submitKey: "enter" },
+ );
+ expect(dedentedOrdered).toEqual({
+ value: "1. one\n2. two\n 1. child\n3. ",
+ selectionStart: 29,
+ selectionEnd: 29,
+ });
+
+ // Exiting an empty top-level parent promotes its nested children instead of leaving orphans.
+ const exitEmptyParent = applyTextareaListKeyDown(
+ { value: "- \n - child", selectionStart: 2, selectionEnd: 2 },
+ keyEvent("Enter", { shiftKey: true }),
+ { submitKey: "enter" },
+ );
+ expect(exitEmptyParent).toEqual({
+ value: "\n- child",
+ selectionStart: 0,
+ selectionEnd: 0,
+ });
+
+ // Dedenting an empty nested ordered parent across a digit-width increase ("1." -> "10.")
+ // shifts its descendants to match the wider parent marker so CommonMark keeps them nested.
+ const dedentOrderedDigitGrowth = applyTextareaListKeyDown(
+ { value: "9. root\n 1. \n - child", selectionStart: 14, selectionEnd: 14 },
+ keyEvent("Enter", { shiftKey: true }),
+ { submitKey: "enter" },
+ );
+ expect(dedentOrderedDigitGrowth).toEqual({
+ value: "9. root\n10. \n - child",
+ selectionStart: 12,
+ selectionEnd: 12,
+ });
+ const growthAst = fromMarkdown(dedentOrderedDigitGrowth!.value);
+ expect(growthAst.children).toHaveLength(1);
+ if (growthAst.children[0]?.type === "list") {
+ expect(growthAst.children[0].children).toHaveLength(2);
+ const tenthItem = growthAst.children[0].children[1]!;
+ expect(tenthItem.children.some((child) => child.type === "list")).toBe(true);
+ }
+
+ // Dedenting an empty nested ordered parent across a digit-width decrease ("10." -> "2.")
+ // shrinks descendant indentation by the same marker-width delta without pulling
+ // same-indent following siblings below the new parent's content column.
+ const dedentOrderedDigitShrink = applyTextareaListKeyDown(
+ { value: "1. root\n 10. \n - child", selectionStart: 15, selectionEnd: 15 },
+ keyEvent("Enter", { shiftKey: true }),
+ { submitKey: "enter" },
+ );
+ expect(dedentOrderedDigitShrink).toEqual({
+ value: "1. root\n2. \n - child",
+ selectionStart: 11,
+ selectionEnd: 11,
+ });
+
+ const dedentOrderedShrinkWithSibling = applyTextareaListKeyDown(
+ { value: "1. root\n 10. \n 11. sibling", selectionStart: 15, selectionEnd: 15 },
+ keyEvent("Enter", { shiftKey: true }),
+ { submitKey: "enter" },
+ );
+ expect(dedentOrderedShrinkWithSibling).toEqual({
+ value: "1. root\n2. \n 1. sibling",
+ selectionStart: 11,
+ selectionEnd: 11,
+ });
+ const shrinkSiblingAst = fromMarkdown(dedentOrderedShrinkWithSibling!.value);
+ expect(shrinkSiblingAst.children).toHaveLength(1);
+ if (shrinkSiblingAst.children[0]?.type === "list") {
+ expect(shrinkSiblingAst.children[0].children).toHaveLength(2);
+ const secondItem = shrinkSiblingAst.children[0].children[1]!;
+ expect(secondItem.children.some((child) => child.type === "list")).toBe(true);
+ }
+
+ const dedentOrderedShrinkWithChildAndSibling = applyTextareaListKeyDown(
+ {
+ value: "1. root\n 10. \n - child\n 11. sibling\n - siblingChild",
+ selectionStart: 15,
+ selectionEnd: 15,
+ },
+ keyEvent("Enter", { shiftKey: true }),
+ { submitKey: "enter" },
+ );
+ expect(dedentOrderedShrinkWithChildAndSibling).toEqual({
+ value: "1. root\n2. \n - child\n 1. sibling\n - siblingChild",
+ selectionStart: 11,
+ selectionEnd: 11,
+ });
+
+ // Following nested ordered siblings shifted by a wider parent marker also renumber from 1,
+ // without renumbering untouched nested lists under later parent items.
+ const dedentOrderedWithSibling = applyTextareaListKeyDown(
+ {
+ value: "9. root\n 1. \n 2. sibling\n11. later\n\n 42. answer",
+ selectionStart: 14,
+ selectionEnd: 14,
+ },
+ keyEvent("Enter", { shiftKey: true }),
+ { submitKey: "enter" },
+ );
+ expect(dedentOrderedWithSibling).toEqual({
+ value: "9. root\n10. \n 1. sibling\n11. later\n\n 42. answer",
+ selectionStart: 12,
+ selectionEnd: 12,
+ });
+ const siblingAst = fromMarkdown(dedentOrderedWithSibling!.value);
+ expect(siblingAst.children).toHaveLength(1);
+ if (siblingAst.children[0]?.type === "list") {
+ expect(siblingAst.children[0].children).toHaveLength(3);
+ const tenthItem = siblingAst.children[0].children[1]!;
+ expect(tenthItem.children.some((child) => child.type === "list")).toBe(true);
+ }
+
+ // When a later parent item itself crosses a digit boundary ("9." -> "10."),
+ // its untouched child list shifts indentation to stay nested without losing its start number.
+ const laterParentDigitGrowth = applyTextareaListKeyDown(
+ {
+ value: "8. root\n 1. \n 2. sibling\n9. later\n 42. answer",
+ selectionStart: 14,
+ selectionEnd: 14,
+ },
+ keyEvent("Enter", { shiftKey: true }),
+ { submitKey: "enter" },
+ );
+ expect(laterParentDigitGrowth).toEqual({
+ value: "8. root\n9. \n 1. sibling\n10. later\n 42. answer",
+ selectionStart: 11,
+ selectionEnd: 11,
+ });
+ });
+
+ it("uses plain Enter for list continuation in mod-enter mode", () => {
+ const next = applyTextareaListKeyDown(
+ { value: "- [x] done", selectionStart: 10, selectionEnd: 10 },
+ keyEvent("Enter"),
+ { submitKey: "mod-enter" },
+ );
+ expect(next).toEqual({
+ value: "- [x] done\n- [ ] ",
+ selectionStart: 17,
+ selectionEnd: 17,
+ });
+
+ const shiftInModEnter = applyTextareaListKeyDown(
+ { value: "- item", selectionStart: 6, selectionEnd: 6 },
+ keyEvent("Enter", { shiftKey: true }),
+ { submitKey: "mod-enter" },
+ );
+ expect(shiftInModEnter).toBeNull();
+ });
+
+ it("indents with Tab and dedents or un-lists with Shift+Tab across single and multi-line selections", () => {
+ const indented = applyTextareaListKeyDown(
+ { value: "- one\n- two", selectionStart: 11, selectionEnd: 11 },
+ keyEvent("Tab"),
+ { submitKey: "enter" },
+ );
+ expect(indented).toEqual({
+ value: "- one\n - two",
+ selectionStart: 13,
+ selectionEnd: 13,
+ });
+
+ const dedented = applyTextareaListKeyDown(
+ indented!,
+ keyEvent("Tab", { shiftKey: true }),
+ { submitKey: "enter" },
+ );
+ expect(dedented).toEqual({
+ value: "- one\n- two",
+ selectionStart: 11,
+ selectionEnd: 11,
+ });
+
+ const unlisted = applyTextareaListKeyDown(
+ dedented!,
+ keyEvent("Tab", { shiftKey: true }),
+ { submitKey: "enter" },
+ );
+ expect(unlisted).toEqual({
+ value: "- one\ntwo",
+ selectionStart: 9,
+ selectionEnd: 9,
+ });
+
+ // Multi-line Tab indent under an ordered parent uses the parent's content column (3 spaces)
+ // and resets nested numbering to `1.` so CommonMark parses it as a nested list.
+ const multiIndent = applyTextareaListKeyDown(
+ { value: "1. one\n2. two\n3. three", selectionStart: 9, selectionEnd: 20 },
+ keyEvent("Tab"),
+ { submitKey: "enter" },
+ );
+ expect(multiIndent).toEqual({
+ value: "1. one\n 1. two\n 2. three",
+ selectionStart: 12,
+ selectionEnd: 26,
+ });
+
+ // Confirm CommonMark actually parses the indented ordered items as a nested list.
+ const ast = fromMarkdown(multiIndent!.value);
+ expect(ast.children).toHaveLength(1);
+ const outerList = ast.children[0]!;
+ expect(outerList.type).toBe("list");
+ if (outerList.type === "list") {
+ expect(outerList.ordered).toBe(true);
+ expect(outerList.children).toHaveLength(1);
+ const firstItem = outerList.children[0]!;
+ expect(firstItem.children.some((child) => child.type === "list")).toBe(true);
+ }
+
+ const multiDedent = applyTextareaListKeyDown(
+ multiIndent!,
+ keyEvent("Tab", { shiftKey: true }),
+ { submitKey: "enter" },
+ );
+ expect(multiDedent).toEqual({
+ value: "1. one\n2. two\n3. three",
+ selectionStart: 9,
+ selectionEnd: 20,
+ });
+
+ // Multi-digit ordered markers (e.g. "10. ") indent children to 4 spaces and reset to "1. ".
+ const twoDigit = applyTextareaListKeyDown(
+ { value: "10. ten\n11. eleven", selectionStart: 12, selectionEnd: 12 },
+ keyEvent("Tab"),
+ { submitKey: "enter" },
+ );
+ expect(twoDigit).toEqual({
+ value: "10. ten\n 1. eleven",
+ selectionStart: 15,
+ selectionEnd: 15,
+ });
+ const twoDigitAst = fromMarkdown(twoDigit!.value);
+ expect(twoDigitAst.children).toHaveLength(1);
+ if (twoDigitAst.children[0]?.type === "list") {
+ expect(twoDigitAst.children[0].children).toHaveLength(1);
+ expect(twoDigitAst.children[0].children[0]!.children.some((c) => c.type === "list")).toBe(true);
+ }
+
+ // Shift+Tab on the nested item restores sequential numbering under "10. ten".
+ const twoDigitDedent = applyTextareaListKeyDown(
+ twoDigit!,
+ keyEvent("Tab", { shiftKey: true }),
+ { submitKey: "enter" },
+ );
+ expect(twoDigitDedent).toEqual({
+ value: "10. ten\n11. eleven",
+ selectionStart: 12,
+ selectionEnd: 12,
+ });
+ });
+
+ it("moves descendant list lines along with their parent on Tab and Shift+Tab without double-moving selected children", () => {
+ // Tab on "parent" also indents its child so child remains nested under parent.
+ const indentParentOnly = applyTextareaListKeyDown(
+ { value: "- root\n- parent\n - child", selectionStart: 10, selectionEnd: 10 },
+ keyEvent("Tab"),
+ { submitKey: "enter" },
+ );
+ expect(indentParentOnly).toEqual({
+ value: "- root\n - parent\n - child",
+ selectionStart: 12,
+ selectionEnd: 12,
+ });
+
+ // Selecting both "parent" and "child" moves each once (no double indent on child).
+ const indentParentAndChild = applyTextareaListKeyDown(
+ { value: "- root\n- parent\n - child", selectionStart: 9, selectionEnd: 25 },
+ keyEvent("Tab"),
+ { submitKey: "enter" },
+ );
+ expect(indentParentAndChild).toEqual({
+ value: "- root\n - parent\n - child",
+ selectionStart: 11,
+ selectionEnd: 29,
+ });
+
+ // Shift+Tab on "parent" brings its child back left by one level too.
+ const dedentParentOnly = applyTextareaListKeyDown(
+ indentParentOnly!,
+ keyEvent("Tab", { shiftKey: true }),
+ { submitKey: "enter" },
+ );
+ expect(dedentParentOnly).toEqual({
+ value: "- root\n- parent\n - child",
+ selectionStart: 10,
+ selectionEnd: 10,
+ });
+
+ // When Shift+Tab renumbers a parent across a digit boundary ("1." -> "10."),
+ // its child's indentation adjusts by +1 space so CommonMark keeps it nested.
+ const digitBoundaryInput = "9. root\n 1. parent\n - child";
+ const digitBoundary = applyTextareaListKeyDown(
+ { value: digitBoundaryInput, selectionStart: 14, selectionEnd: 14 },
+ keyEvent("Tab", { shiftKey: true }),
+ { submitKey: "enter" },
+ );
+ expect(digitBoundary).toEqual({
+ value: "9. root\n10. parent\n - child",
+ selectionStart: 12,
+ selectionEnd: 12,
+ });
+ const digitBoundaryAst = fromMarkdown(digitBoundary!.value);
+ expect(digitBoundaryAst.children).toHaveLength(1);
+ if (digitBoundaryAst.children[0]?.type === "list") {
+ expect(digitBoundaryAst.children[0].children).toHaveLength(2);
+ const tenthItem = digitBoundaryAst.children[0].children[1]!;
+ expect(tenthItem.children.some((child) => child.type === "list")).toBe(true);
+ }
+ });
+
+ it("supports Tab indent and Shift+Tab dedent across loose lists and continuation lines", () => {
+ // Loose list with a blank line between siblings.
+ const looseIndent = applyTextareaListKeyDown(
+ { value: "- a\n\n- b", selectionStart: 8, selectionEnd: 8 },
+ keyEvent("Tab"),
+ { submitKey: "enter" },
+ );
+ expect(looseIndent).toEqual({
+ value: "- a\n\n - b",
+ selectionStart: 10,
+ selectionEnd: 10,
+ });
+ const looseDedent = applyTextareaListKeyDown(
+ looseIndent!,
+ keyEvent("Tab", { shiftKey: true }),
+ { submitKey: "enter" },
+ );
+ expect(looseDedent).toEqual({
+ value: "- a\n\n- b",
+ selectionStart: 8,
+ selectionEnd: 8,
+ });
+
+ // Multi-line item with an indented continuation line.
+ const wrappedIndent = applyTextareaListKeyDown(
+ { value: "- a\n continued\n- b", selectionStart: 19, selectionEnd: 19 },
+ keyEvent("Tab"),
+ { submitKey: "enter" },
+ );
+ expect(wrappedIndent).toEqual({
+ value: "- a\n continued\n - b",
+ selectionStart: 21,
+ selectionEnd: 21,
+ });
+
+ // A dedented paragraph between lists still separates them (no cross-paragraph nesting).
+ const separated = "- a\n\nBetween lists.\n\n- b";
+ const separatedTab = applyTextareaListKeyDown(
+ { value: separated, selectionStart: separated.length, selectionEnd: separated.length },
+ keyEvent("Tab"),
+ { submitKey: "enter" },
+ );
+ expect(separatedTab).toEqual({
+ value: separated,
+ selectionStart: separated.length,
+ selectionEnd: separated.length,
+ });
+ });
+
+ it("skips list shortcuts inside fenced and indented code blocks", () => {
+ const fencedYaml = "```yaml\n- flag\n```";
+ expect(isTextareaSelectionInList(fencedYaml, 14, 14)).toBe(false);
+ expect(
+ applyTextareaListKeyDown(
+ { value: fencedYaml, selectionStart: 14, selectionEnd: 14 },
+ keyEvent("Enter", { shiftKey: true }),
+ { submitKey: "enter" },
+ ),
+ ).toBeNull();
+ expect(
+ applyTextareaListKeyDown(
+ { value: fencedYaml, selectionStart: 10, selectionEnd: 10 },
+ keyEvent("Tab", { shiftKey: true }),
+ { submitKey: "enter" },
+ ),
+ ).toBeNull();
+ expect(
+ applyTextareaListKeyDown(
+ { value: fencedYaml, selectionStart: 10, selectionEnd: 10 },
+ keyEvent("Backspace"),
+ { submitKey: "enter" },
+ ),
+ ).toBeNull();
+
+ const tildeFence = "~~~\n1. code\n~~~";
+ expect(isTextareaSelectionInList(tildeFence, 11, 11)).toBe(false);
+ expect(
+ applyTextareaListKeyDown(
+ { value: tildeFence, selectionStart: 11, selectionEnd: 11 },
+ keyEvent("Enter", { shiftKey: true }),
+ { submitKey: "enter" },
+ ),
+ ).toBeNull();
+
+ const indentedCode = "Example:\n\n - not a list";
+ expect(isTextareaSelectionInList(indentedCode, indentedCode.length, indentedCode.length)).toBe(false);
+ expect(
+ applyTextareaListKeyDown(
+ { value: indentedCode, selectionStart: indentedCode.length, selectionEnd: indentedCode.length },
+ keyEvent("Enter", { shiftKey: true }),
+ { submitKey: "enter" },
+ ),
+ ).toBeNull();
+
+ // An unclosed fence inside a list item ends when the containing list item ends,
+ // so subsequent sibling list items still get list shortcuts.
+ const unclosedNestedFence = "- parent\n ~~~\n - code\n\n- next";
+ expect(isTextareaSelectionInList(unclosedNestedFence, 20, 20)).toBe(false);
+ expect(
+ isTextareaSelectionInList(
+ unclosedNestedFence,
+ unclosedNestedFence.length,
+ unclosedNestedFence.length,
+ ),
+ ).toBe(true);
+ expect(
+ applyTextareaListKeyDown(
+ {
+ value: unclosedNestedFence,
+ selectionStart: unclosedNestedFence.length,
+ selectionEnd: unclosedNestedFence.length,
+ },
+ keyEvent("Enter", { shiftKey: true }),
+ { submitKey: "enter" },
+ ),
+ ).toEqual({
+ value: `${unclosedNestedFence}\n- `,
+ selectionStart: unclosedNestedFence.length + 3,
+ selectionEnd: unclosedNestedFence.length + 3,
+ });
+
+ // Renumbering stops at a separate top-level code block and does not alter
+ // an unrelated later ordered list's starting number.
+ const withSeparateCodeBlock = "1. a\n2. b\n\n~~~\ncode\n~~~\n\n42. answer";
+ const tabBeforeCode = applyTextareaListKeyDown(
+ { value: withSeparateCodeBlock, selectionStart: 9, selectionEnd: 9 },
+ keyEvent("Tab"),
+ { submitKey: "enter" },
+ );
+ expect(tabBeforeCode).toEqual({
+ value: "1. a\n 1. b\n\n~~~\ncode\n~~~\n\n42. answer",
+ selectionStart: 12,
+ selectionEnd: 12,
+ });
+ });
+
+ it("removes or dedents list markers cleanly on Backspace right after the marker", () => {
+ const dedentNested = applyTextareaListKeyDown(
+ { value: "- one\n - two", selectionStart: 10, selectionEnd: 10 },
+ keyEvent("Backspace"),
+ { submitKey: "enter" },
+ );
+ expect(dedentNested).toEqual({
+ value: "- one\n- two",
+ selectionStart: 8,
+ selectionEnd: 8,
+ });
+
+ const removeTopMarker = applyTextareaListKeyDown(
+ dedentNested!,
+ keyEvent("Backspace"),
+ { submitKey: "enter" },
+ );
+ expect(removeTopMarker).toEqual({
+ value: "- one\ntwo",
+ selectionStart: 6,
+ selectionEnd: 6,
+ });
+
+ // Backspace dedenting a nested ordered item renumbers both top-level and
+ // remaining nested siblings so CommonMark keeps the nested list valid.
+ const dedentOrdered = applyTextareaListKeyDown(
+ { value: "1. a\n 1. b\n 2. c", selectionStart: 11, selectionEnd: 11 },
+ keyEvent("Backspace"),
+ { submitKey: "enter" },
+ );
+ expect(dedentOrdered).toEqual({
+ value: "1. a\n2. b\n 1. c",
+ selectionStart: 8,
+ selectionEnd: 8,
+ });
+
+ // Backspace inside text content passes through untouched.
+ const midWord = applyTextareaListKeyDown(
+ { value: "- one", selectionStart: 5, selectionEnd: 5 },
+ keyEvent("Backspace"),
+ { submitKey: "enter" },
+ );
+ expect(midWord).toBeNull();
+ });
+
+ it("does not intercept Tab outside list lines or in singleLine mode", () => {
+ expect(
+ applyTextareaListKeyDown(
+ { value: "plain text", selectionStart: 5, selectionEnd: 5 },
+ keyEvent("Tab"),
+ { submitKey: "enter" },
+ ),
+ ).toBeNull();
+
+ expect(
+ applyTextareaListKeyDown(
+ { value: "- single", selectionStart: 8, selectionEnd: 8 },
+ keyEvent("Tab"),
+ { submitKey: "enter", singleLine: true },
+ ),
+ ).toBeNull();
+
+ expect(isTextareaSelectionInList("plain\n- item", 0, 12)).toBe(false);
+ expect(isTextareaSelectionInList("- one\n2. two", 2, 10)).toBe(true);
+ });
+});
diff --git a/ui/src/lib/textarea-list-editing.ts b/ui/src/lib/textarea-list-editing.ts
new file mode 100644
index 00000000000..4aa001839b8
--- /dev/null
+++ b/ui/src/lib/textarea-list-editing.ts
@@ -0,0 +1,617 @@
+import type { ComposerSubmitKey } from "./list-editing";
+import {
+ INDENT_STEP,
+ dedentDescendantBlock,
+ dedentToAncestorLevel,
+ findLastDescendantLine,
+ findLineIndexForOffset,
+ findPrecedingSiblingToNestUnder,
+ formatListItemPrefix,
+ getCodeBlockLineFlags,
+ getLineSpans,
+ getSelectedLineRange,
+ measureIndentWidth,
+ measureLineIndentWidth,
+ parseListLine,
+ parseNonCodeListLine,
+ removeIndentColumns,
+ type ParsedListLine,
+} from "./textarea-list-markdown";
+
+export interface TextareaSelectionState {
+ value: string;
+ selectionStart: number;
+ selectionEnd: number;
+}
+
+export interface TextareaListKeyEvent {
+ key: string;
+ shiftKey: boolean;
+ metaKey: boolean;
+ ctrlKey: boolean;
+ altKey: boolean;
+ isComposing?: boolean;
+ keyCode?: number;
+}
+
+export interface TextareaListOptions {
+ submitKey: ComposerSubmitKey;
+ singleLine?: boolean;
+}
+
+/**
+ * Shift contiguous non-blank descendant lines under `parentIndex` by `deltaCols`
+ * spaces when an ordered parent's marker width grows or shrinks during renumbering.
+ */
+function shiftFollowingDescendants(
+ lines: string[],
+ codeFlags: readonly boolean[],
+ parentIndex: number,
+ parentIndentWidth: number,
+ oldContentIndentWidth: number,
+ deltaCols: number,
+ affectedIndents?: ReadonlySet,
+ shiftedOrderedLines?: Set,
+): void {
+ if (deltaCols === 0) return;
+ for (let j = parentIndex + 1; j < lines.length; j += 1) {
+ const text = lines[j]!;
+ if (text.trim() === "") continue;
+ const parsed = codeFlags[j] ? null : parseListLine(text);
+ const indentWidth = parsed ? parsed.indentWidth : measureLineIndentWidth(text);
+ if (indentWidth <= parentIndentWidth) break;
+ // When shrinking a parent marker, only lines indented to at least the old
+ // content column belonged to that parent; stop at shallower siblings so we
+ // never pull them below the new parent's content column.
+ if (deltaCols < 0 && indentWidth < oldContentIndentWidth) break;
+ if (deltaCols > 0) {
+ lines[j] = `${" ".repeat(deltaCols)}${text}`;
+ } else {
+ const leadingWs = text.match(/^[ \t]*/)?.[0] ?? "";
+ const { removedChars } = removeIndentColumns(leadingWs, -deltaCols);
+ lines[j] = text.slice(removedChars);
+ }
+ if (
+ shiftedOrderedLines &&
+ affectedIndents &&
+ parsed?.kind === "ordered" &&
+ affectedIndents.has(indentWidth)
+ ) {
+ shiftedOrderedLines.add(j);
+ }
+ }
+}
+
+/** Find the next sequential number for an ordered list item at `indentWidth` above `lineIndex`. */
+function findNextOrderedNumberInLines(
+ lines: readonly string[],
+ codeFlags: readonly boolean[],
+ lineIndex: number,
+ indentWidth: number,
+): number | null {
+ for (let i = lineIndex - 1; i >= 0; i -= 1) {
+ const text = lines[i]!;
+ if (text.trim() === "") continue;
+ if (codeFlags[i]) {
+ if (measureLineIndentWidth(text) > indentWidth) continue;
+ return null;
+ }
+ const parsed = parseListLine(text);
+ if (!parsed) {
+ if (measureLineIndentWidth(text) > indentWidth) continue;
+ return null;
+ }
+ if (parsed.indentWidth < indentWidth) return null;
+ if (parsed.indentWidth > indentWidth) continue;
+ if (parsed.kind === "ordered" && parsed.indentWidth === indentWidth) {
+ return parsed.number + 1;
+ }
+ return null;
+ }
+ return null;
+}
+
+/**
+ * Recompute ordered list numbers starting at `startLine` for lines whose indent
+ * changed (and any following ordered siblings at the affected indent levels) so
+ * nested ordered lists start at `1.` (required by CommonMark to interrupt a
+ * parent item's paragraph) and sibling numbering stays contiguous. Adjusts child
+ * indentation if a parent marker's digit width changes (e.g. `9.` -> `10.`).
+ */
+function renumberOrderedListFrom(
+ lines: string[],
+ codeFlags: readonly boolean[],
+ startLine: number,
+ endLine: number,
+ affectedIndents: ReadonlySet,
+): void {
+ if (affectedIndents.size === 0) return;
+ const activeIndents = new Set(affectedIndents);
+ const shiftedOrderedLines = new Set();
+ const pruneIndents = (threshold: number, inclusive: boolean) => {
+ for (const indent of activeIndents) {
+ if (inclusive ? indent >= threshold : indent > threshold) {
+ activeIndents.delete(indent);
+ }
+ }
+ };
+ const hasPendingTargets = (lineIdx: number) => {
+ if (activeIndents.size > 0) return true;
+ for (const shiftedLine of shiftedOrderedLines) {
+ if (shiftedLine >= lineIdx) return true;
+ }
+ return false;
+ };
+ for (let i = startLine; i < lines.length; i += 1) {
+ const text = lines[i]!;
+ if (text.trim() === "") {
+ continue;
+ }
+ if (codeFlags[i]) {
+ if (i > endLine) {
+ pruneIndents(measureLineIndentWidth(text), true);
+ if (!hasPendingTargets(i + 1)) break;
+ }
+ continue;
+ }
+ const parsed = parseListLine(text);
+ if (!parsed) {
+ if (i > endLine) {
+ pruneIndents(measureLineIndentWidth(text), true);
+ if (!hasPendingTargets(i + 1)) break;
+ }
+ continue;
+ }
+ if (parsed.kind !== "ordered") {
+ if (i > endLine) {
+ pruneIndents(parsed.indentWidth, true);
+ if (!hasPendingTargets(i + 1)) break;
+ }
+ continue;
+ }
+ if (i > endLine) {
+ pruneIndents(parsed.indentWidth, false);
+ if (!hasPendingTargets(i)) break;
+ }
+ if (!activeIndents.has(parsed.indentWidth) && !shiftedOrderedLines.has(i)) continue;
+ const expected = findNextOrderedNumberInLines(lines, codeFlags, i, parsed.indentWidth) ?? 1;
+ if (parsed.number !== expected) {
+ const markerDelta = String(expected).length - String(parsed.number).length;
+ lines[i] = `${parsed.indent}${expected}.${parsed.space}${parsed.content}`;
+ if (markerDelta !== 0) {
+ shiftFollowingDescendants(
+ lines,
+ codeFlags,
+ i,
+ parsed.indentWidth,
+ parsed.contentIndentWidth,
+ markerDelta,
+ activeIndents,
+ shiftedOrderedLines,
+ );
+ }
+ }
+ }
+}
+
+/** Renumber contiguous ordered list siblings starting from `startIndex` at `indentWidth`. */
+function renumberFollowingOrderedSiblings(
+ lines: string[],
+ codeFlags: readonly boolean[],
+ startIndex: number,
+ indentWidth: number,
+ firstNumber: number,
+): void {
+ let nextNumber = firstNumber;
+ for (let i = startIndex; i < lines.length; i += 1) {
+ const text = lines[i]!;
+ if (text.trim() === "") continue;
+ if (codeFlags[i]) {
+ if (measureLineIndentWidth(text) > indentWidth) continue;
+ break;
+ }
+ const parsed = parseListLine(text);
+ if (!parsed) {
+ if (measureLineIndentWidth(text) > indentWidth) continue;
+ break;
+ }
+ if (parsed.indentWidth < indentWidth) break;
+ if (parsed.indentWidth > indentWidth) continue;
+ if (parsed.kind !== "ordered" || parsed.indentWidth !== indentWidth) break;
+ const markerDelta = String(nextNumber).length - String(parsed.number).length;
+ lines[i] = `${parsed.indent}${nextNumber}.${parsed.space}${parsed.content}`;
+ if (markerDelta !== 0) {
+ shiftFollowingDescendants(
+ lines,
+ codeFlags,
+ i,
+ parsed.indentWidth,
+ parsed.contentIndentWidth,
+ markerDelta,
+ );
+ }
+ nextNumber += 1;
+ }
+}
+
+/** Returns true when every line touched by the selection is a non-code markdown list item. */
+export function isTextareaSelectionInList(
+ value: string,
+ selectionStart: number,
+ selectionEnd: number,
+): boolean {
+ const spans = getLineSpans(value);
+ const codeFlags = getCodeBlockLineFlags(spans);
+ const { startLine, endLine } = getSelectedLineRange(spans, selectionStart, selectionEnd);
+ for (let i = startLine; i <= endLine; i += 1) {
+ if (!parseNonCodeListLine(spans, codeFlags, i)) return false;
+ }
+ return startLine <= endLine;
+}
+
+/**
+ * Pure keydown handler for markdown list editing in plain-text `