mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-05 06:03:51 +01:00
fix(ui): support rich list editing and keyboard handling in all composers (#23766)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Users write instructions, replies, and chat messages in the UI composers (`TaskChatComposer`, `IssueChatComposer`, `CommentThread`, `ChatComposer`, and `MarkdownEditor`). > - Enter now submits messages by default and Shift+Enter inserts a newline. > - In rich editors, Shift+Enter inserted a soft `<br>` line break instead of a new paragraph or list item, which blocked markdown list shortcuts and stopped bulleted and numbered lists from continuing. > - Inside lists, Tab inserted a literal tab character when the caret was not at column 0, Shift+Tab triggered work-mode cycling in `TaskChatComposer` instead of dedenting, and removing a parent item left orphaned nested lists. > - Plain-text textarea composers (`ChatComposer` and the `MarkdownEditor` raw fallback) also lacked list continuation, Tab indent, Shift+Tab dedent, and Backspace marker removal. > - This pull request adds unified rich and plain-text list keyboard handling and nested list styling across all composers. > - The benefit is smooth creation, continuation, deletion, indentation, and dedentation of bulleted, numbered, and checklist items in every composer. ## Linked Issues or Issue Description No pre-existing public GitHub issue was found after searching open issues and PRs. **What happened?** When a composer uses Enter to submit and Shift+Enter to insert a newline, typing `- ` or `1. ` after a newline does not start a rich list because Shift+Enter inserts a soft `<br>` break inside the same paragraph. Inside an existing list, Shift+Enter inserts a `<br>` inside the same `<li>` instead of adding the next list item. Pressing Tab mid-item inserts a tab character instead of indenting, pressing Shift+Tab inside `TaskChatComposer` cycles work mode instead of dedenting the list item, and plain-text textarea composers provide no list keyboard shortcuts. **Expected behavior** In every composer, users can start bulleted and numbered lists after a newline, add new list items with the active newline shortcut (Shift+Enter in Enter-to-submit mode, Enter in Cmd/Ctrl+Enter mode), indent with Tab, dedent or un-list with Shift+Tab, and delete or exit list items cleanly with Backspace or an empty-item newline. **Steps to reproduce** 1. Open any Enter-to-submit composer (for example, the task composer, new task modal, comment composer, or board chat). 2. Type a line of text, press Shift+Enter, and type `- first item`. 3. Press Shift+Enter to add a second item, Tab to indent, Shift+Tab to dedent, and Backspace to remove the bullet. **Paperclip version or commit** `master` (`62821e8766`) **Deployment mode** Local dev (pnpm dev) ## What Changed - Added `ui/src/lib/list-editing.ts` (`listEditingPlugin`, `registerListEditingCommands`, `isSelectionInsideList`) for MDXEditor/Lexical composers: - Maps Shift+Enter to `INSERT_PARAGRAPH_COMMAND` when `submitKey === "enter"` so markdown list shortcuts work after newlines, list items continue cleanly, and empty list items dedent or exit. - Preserves Shift+Enter as a soft line break when `submitKey === "mod-enter"` and reacts dynamically if the preference changes. - Handles Tab indent and Shift+Tab dedent (or lift to paragraph at top level) from any caret offset inside a list item, snaps original indent depths so multi-level Shift+Tab dedents each selected item by one level, and prevents orphaned nested lists when indenting the first item or removing/exiting a parent item. - Added `ui/src/lib/textarea-list-editing.ts` (`applyTextareaListKeyDown`, `isTextareaSelectionInList`) for plain-text textarea composers: - Continues unordered, ordered (with sibling renumbering), and checklist lines on Shift+Enter (or Enter in `mod-enter` mode), dedents/exits empty list lines, indents with Tab, dedents/un-lists with Shift+Tab, and cleans list markers on Backspace. - Wired `listEditingPlugin` and `applyTextareaListKeyDown` into `ui/src/components/MarkdownEditor.tsx` (rich mode and raw fallback textarea), preserved Shift+Tab for dedent while autocomplete is open, cleared the mount-reset flag on Tab/Shift+Enter, and treated rendered `<li>` nodes as meaningful editor content. - Updated `ui/src/components/task-chat/TaskChatComposer.tsx` so Shift+Tab defers to list dedent when the selection is inside a list and still cycles work modes outside lists. - Wired `applyTextareaListKeyDown` into `ui/src/components/ChatComposer.tsx`. - Added nested bullet (`disc`, `circle`, `square`) and ordered (`decimal`, `lower-alpha`, `lower-roman`) marker styles and suppressed markers on Lexical's nested-list wrapper `<li>` elements in `ui/src/index.css`. - Added real-Lexical, textarea, `ChatComposer`, `MarkdownEditor`, and `TaskChatComposer` tests. ## Verification - Verified post-rebase on commit `62821e8766`: - `pnpm vitest run ui/src/lib/list-editing.test.ts ui/src/lib/textarea-list-editing.test.ts ui/src/components/ChatComposer.test.tsx ui/src/components/MarkdownEditor.test.tsx ui/src/components/task-chat/TaskChatComposer.test.tsx` — 5 test files, 300 tests passed. - `pnpm --filter @paperclipai/ui typecheck` — passed. - `pnpm --filter @paperclipai/ui build` — passed (verified prior to rebase on identical code; CI supplies full typecheck, build, and test coverage on `62821e8766`). - `node scripts/check-forbidden-tokens.mjs` — passed. - `node scripts/local-verify.mjs --explain` — exited 2 because `ui/src/index.css` is a broad input; CI supplies the full suite. ## Risks - Low risk. Changes are scoped to UI composer keyboard handlers and `.paperclip-mdxeditor-content` list CSS rules. - Outside lists, Tab and Shift+Tab retain their existing behavior (including Shift+Tab work-mode cycling in `TaskChatComposer`). - In `mod-enter` mode (document editors and legacy composer submit mode), plain Enter remains the paragraph/list key and Shift+Enter remains a soft break. ## Model Used - Google Gemini (Antigravity agent, high reasoning mode, tool use and code execution) ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [ ] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
5e59737ef3
commit
306437a2a5
12 files changed
+3305
-16
No files matched your search
@@ -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 (
|
||||
<ChatComposer
|
||||
value={value}
|
||||
onChange={setValue}
|
||||
onSubmit={onSubmit}
|
||||
submitKey={submitKey}
|
||||
singleLine={singleLine}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
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(<Harness initialValue="- first" submitKey="enter" onSubmit={onSubmit} />);
|
||||
});
|
||||
|
||||
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(<Harness initialValue="plain text" submitKey="enter" />);
|
||||
});
|
||||
|
||||
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(<Harness initialValue="- single" submitKey="enter" singleLine />);
|
||||
});
|
||||
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());
|
||||
});
|
||||
});
|
||||
@@ -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<ChatComposerHandle, ChatComposerProps>(fu
|
||||
}
|
||||
|
||||
function handleKeyDown(evt: ReactKeyboardEvent<HTMLTextAreaElement>) {
|
||||
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() {
|
||||
|
||||
@@ -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(
|
||||
<MarkdownEditor
|
||||
value={currentValue}
|
||||
onChange={(next) => {
|
||||
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);
|
||||
|
||||
@@ -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<MarkdownEditorRef, MarkdownEditorProps>
|
||||
readOnly = false,
|
||||
}: MarkdownEditorProps, forwardedRef) {
|
||||
const editorValue = useMemo(() => prepareMarkdownForEditor(value), [value]);
|
||||
const submitKeyRef = useRef(submitKey);
|
||||
submitKeyRef.current = submitKey;
|
||||
function isSubmitShortcut(event: KeyboardEvent<HTMLElement>): boolean {
|
||||
return !readOnly
|
||||
&& event.key === "Enter"
|
||||
@@ -1034,6 +1038,7 @@ export const MarkdownEditor = forwardRef<MarkdownEditorRef, MarkdownEditorProps>
|
||||
linkPlugin({ validateUrl: isSafeMarkdownLinkUrl }),
|
||||
linkDialogPlugin(),
|
||||
mentionDeletionPlugin(),
|
||||
listEditingPlugin({ submitKeyRef }),
|
||||
pasteNormalizationPlugin(),
|
||||
thematicBreakPlugin(),
|
||||
codeBlockPlugin({
|
||||
@@ -1416,7 +1421,36 @@ export const MarkdownEditor = forwardRef<MarkdownEditorRef, MarkdownEditorProps>
|
||||
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<MarkdownEditorRef, MarkdownEditorProps>
|
||||
}}
|
||||
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<MarkdownEditorRef, MarkdownEditorProps>
|
||||
return;
|
||||
}
|
||||
if (
|
||||
shouldAcceptAutocompleteKey(
|
||||
!(e.key === "Tab" && e.shiftKey)
|
||||
&& shouldAcceptAutocompleteKey(
|
||||
e.key,
|
||||
mentionStateRef.current?.trigger ?? null,
|
||||
skillEnterArmedRef.current,
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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<LexicalNode>;
|
||||
ListItemNode: Klass<LexicalNode>;
|
||||
$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<typeof $createTextNode>;
|
||||
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 <br>.
|
||||
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<typeof $createTextNode>;
|
||||
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 =
|
||||
'<div contenteditable="true"><p>Plain text</p><ul><li>Bullet item</li></ul></div>';
|
||||
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();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -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<string>();
|
||||
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<string, number>();
|
||||
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
|
||||
// <br> 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<ListEditingPluginParams>({
|
||||
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));
|
||||
}
|
||||
@@ -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> = {},
|
||||
): 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);
|
||||
});
|
||||
});
|
||||
@@ -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<number>,
|
||||
shiftedOrderedLines?: Set<number>,
|
||||
): 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<number>,
|
||||
): void {
|
||||
if (affectedIndents.size === 0) return;
|
||||
const activeIndents = new Set(affectedIndents);
|
||||
const shiftedOrderedLines = new Set<number>();
|
||||
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 `<textarea>`
|
||||
* composers (such as `ChatComposer` and `MarkdownEditor`'s raw fallback).
|
||||
* Returns the next text/selection state when the key was handled, or `null`
|
||||
* to let the browser handle the event normally.
|
||||
*/
|
||||
export function applyTextareaListKeyDown(
|
||||
state: TextareaSelectionState,
|
||||
event: TextareaListKeyEvent,
|
||||
options: TextareaListOptions,
|
||||
): TextareaSelectionState | null {
|
||||
if (options.singleLine) return null;
|
||||
if (event.isComposing || event.keyCode === 229) return null;
|
||||
if (event.metaKey || event.ctrlKey || event.altKey) return null;
|
||||
|
||||
const { value } = state;
|
||||
const selectionStart = Math.min(state.selectionStart, state.selectionEnd);
|
||||
const selectionEnd = Math.max(state.selectionStart, state.selectionEnd);
|
||||
|
||||
// 1. Newline inside a list item (Shift+Enter when Enter submits; Enter when Cmd/Ctrl+Enter submits)
|
||||
if (event.key === "Enter") {
|
||||
const isNewlineShortcut =
|
||||
options.submitKey === "enter" ? event.shiftKey : !event.shiftKey;
|
||||
if (!isNewlineShortcut) return null;
|
||||
|
||||
const spans = getLineSpans(value);
|
||||
const codeFlags = getCodeBlockLineFlags(spans);
|
||||
const startLineIdx = findLineIndexForOffset(spans, selectionStart);
|
||||
const endLineIdx = findLineIndexForOffset(spans, selectionEnd);
|
||||
if (startLineIdx !== endLineIdx) return null;
|
||||
|
||||
const lineSpan = spans[startLineIdx]!;
|
||||
const parsed = parseNonCodeListLine(spans, codeFlags, startLineIdx);
|
||||
if (!parsed) return null;
|
||||
|
||||
const startColumn = selectionStart - lineSpan.start;
|
||||
if (startColumn < parsed.prefixLength) return null;
|
||||
|
||||
// Empty list item: dedent if nested, or exit the list if top-level,
|
||||
// promoting any descendant block cleanly so no orphaned indentation remains.
|
||||
if (selectionStart === selectionEnd && parsed.content.trim() === "") {
|
||||
const lines = spans.map((span) => span.text);
|
||||
const expandedEndLine = findLastDescendantLine(
|
||||
spans,
|
||||
codeFlags,
|
||||
startLineIdx,
|
||||
parsed.indentWidth,
|
||||
);
|
||||
const affectedOrderedIndents = new Set<number>();
|
||||
|
||||
if (parsed.indent.length > 0) {
|
||||
const { nextIndent, removedCols } = dedentToAncestorLevel(spans, codeFlags, startLineIdx, parsed);
|
||||
const nextIndentWidth = measureIndentWidth(nextIndent);
|
||||
// Keep `parsed.number` here so `renumberOrderedListFrom` computes the
|
||||
// marker-width delta (e.g. `1.` -> `10.`) and shifts descendants to match.
|
||||
lines[startLineIdx] = formatListItemPrefix(parsed, { indent: nextIndent });
|
||||
if (parsed.kind === "ordered") {
|
||||
affectedOrderedIndents.add(parsed.indentWidth);
|
||||
affectedOrderedIndents.add(nextIndentWidth);
|
||||
}
|
||||
dedentDescendantBlock(
|
||||
lines,
|
||||
spans,
|
||||
codeFlags,
|
||||
startLineIdx + 1,
|
||||
expandedEndLine,
|
||||
removedCols,
|
||||
affectedOrderedIndents,
|
||||
);
|
||||
renumberOrderedListFrom(lines, codeFlags, startLineIdx, expandedEndLine, affectedOrderedIndents);
|
||||
const nextValue = lines.join("\n");
|
||||
const nextSpans = getLineSpans(nextValue);
|
||||
const nextCursor = nextSpans[startLineIdx]!.end;
|
||||
return {
|
||||
value: nextValue,
|
||||
selectionStart: nextCursor,
|
||||
selectionEnd: nextCursor,
|
||||
};
|
||||
}
|
||||
|
||||
lines[startLineIdx] = "";
|
||||
dedentDescendantBlock(
|
||||
lines,
|
||||
spans,
|
||||
codeFlags,
|
||||
startLineIdx + 1,
|
||||
expandedEndLine,
|
||||
parsed.markerWidth,
|
||||
affectedOrderedIndents,
|
||||
);
|
||||
renumberOrderedListFrom(lines, codeFlags, startLineIdx + 1, expandedEndLine, affectedOrderedIndents);
|
||||
return {
|
||||
value: lines.join("\n"),
|
||||
selectionStart: lineSpan.start,
|
||||
selectionEnd: lineSpan.start,
|
||||
};
|
||||
}
|
||||
|
||||
// Caret at the very start of a non-empty item's content: insert a blank sibling
|
||||
// above so this item and any existing nested children move down together.
|
||||
if (startColumn === parsed.prefixLength) {
|
||||
const endColumn = selectionEnd - lineSpan.start;
|
||||
const remainingContent = lineSpan.text.slice(endColumn);
|
||||
const emptyPrefix = formatListItemPrefix(parsed, { uncheckCheckbox: true });
|
||||
const movedLine = `${formatListItemPrefix(parsed)}${remainingContent}`;
|
||||
|
||||
const lines = spans.map((span) => span.text);
|
||||
const updatedCodeFlags = [...codeFlags];
|
||||
lines.splice(startLineIdx, 1, emptyPrefix, movedLine);
|
||||
updatedCodeFlags.splice(startLineIdx + 1, 0, false);
|
||||
|
||||
if (parsed.kind === "ordered") {
|
||||
renumberFollowingOrderedSiblings(
|
||||
lines,
|
||||
updatedCodeFlags,
|
||||
startLineIdx + 1,
|
||||
parsed.indentWidth,
|
||||
parsed.number + 1,
|
||||
);
|
||||
}
|
||||
|
||||
const nextValue = lines.join("\n");
|
||||
const nextSpans = getLineSpans(nextValue);
|
||||
const movedParsed = parseListLine(nextSpans[startLineIdx + 1]!.text);
|
||||
const nextCursor = nextSpans[startLineIdx + 1]!.start + (movedParsed?.prefixLength ?? 0);
|
||||
return {
|
||||
value: nextValue,
|
||||
selectionStart: nextCursor,
|
||||
selectionEnd: nextCursor,
|
||||
};
|
||||
}
|
||||
|
||||
// Non-empty list item: split at caret and add the next bullet/number after
|
||||
// any existing descendant block so children stay attached to the original item.
|
||||
const beforeCaret = lineSpan.text.slice(0, startColumn);
|
||||
const endColumn = selectionEnd - lineSpan.start;
|
||||
const afterCaret = lineSpan.text.slice(endColumn);
|
||||
const nextPrefix = formatListItemPrefix(parsed, {
|
||||
number: parsed.kind === "ordered" ? parsed.number + 1 : undefined,
|
||||
uncheckCheckbox: true,
|
||||
});
|
||||
|
||||
const insertAfterIdx = findLastDescendantLine(
|
||||
spans,
|
||||
codeFlags,
|
||||
startLineIdx,
|
||||
parsed.indentWidth,
|
||||
);
|
||||
const lines = spans.map((span) => span.text);
|
||||
const updatedCodeFlags = [...codeFlags];
|
||||
lines[startLineIdx] = beforeCaret;
|
||||
lines.splice(insertAfterIdx + 1, 0, `${nextPrefix}${afterCaret}`);
|
||||
updatedCodeFlags.splice(insertAfterIdx + 1, 0, false);
|
||||
|
||||
if (parsed.kind === "ordered") {
|
||||
renumberFollowingOrderedSiblings(
|
||||
lines,
|
||||
updatedCodeFlags,
|
||||
insertAfterIdx + 2,
|
||||
parsed.indentWidth,
|
||||
parsed.number + 2,
|
||||
);
|
||||
}
|
||||
|
||||
const nextValue = lines.join("\n");
|
||||
const nextSpans = getLineSpans(nextValue);
|
||||
const nextCursor = nextSpans[insertAfterIdx + 1]!.start + nextPrefix.length;
|
||||
return {
|
||||
value: nextValue,
|
||||
selectionStart: nextCursor,
|
||||
selectionEnd: nextCursor,
|
||||
};
|
||||
}
|
||||
|
||||
// 2. Tab / Shift+Tab on list line(s)
|
||||
if (event.key === "Tab") {
|
||||
const spans = getLineSpans(value);
|
||||
const codeFlags = getCodeBlockLineFlags(spans);
|
||||
const { startLine, endLine } = getSelectedLineRange(spans, selectionStart, selectionEnd);
|
||||
const parsedLines: ParsedListLine[] = [];
|
||||
for (let i = startLine; i <= endLine; i += 1) {
|
||||
const parsed = parseNonCodeListLine(spans, codeFlags, i);
|
||||
if (!parsed) return null;
|
||||
parsedLines.push(parsed);
|
||||
}
|
||||
|
||||
const lines = spans.map((span) => span.text);
|
||||
const affectedOrderedIndents = new Set<number>();
|
||||
|
||||
if (!event.shiftKey) {
|
||||
const firstParsed = parsedLines[0]!;
|
||||
const parentToNestUnder = findPrecedingSiblingToNestUnder(
|
||||
spans,
|
||||
codeFlags,
|
||||
startLine,
|
||||
firstParsed.indentWidth,
|
||||
);
|
||||
if (!parentToNestUnder) {
|
||||
// Cannot nest without a preceding sibling item; keep focus in the editor.
|
||||
return { value, selectionStart, selectionEnd };
|
||||
}
|
||||
|
||||
const deltaSpaces = Math.max(
|
||||
INDENT_STEP.length,
|
||||
parentToNestUnder.contentIndentWidth - firstParsed.indentWidth,
|
||||
);
|
||||
const indentPrefix = " ".repeat(deltaSpaces);
|
||||
const lastSelectedParsed = parsedLines[parsedLines.length - 1]!;
|
||||
const expandedEndLine = findLastDescendantLine(
|
||||
spans,
|
||||
codeFlags,
|
||||
endLine,
|
||||
lastSelectedParsed.indentWidth,
|
||||
);
|
||||
|
||||
for (let i = startLine; i <= expandedEndLine; i += 1) {
|
||||
const span = spans[i]!;
|
||||
if (span.text.trim() === "") continue;
|
||||
const oldParsed = parseNonCodeListLine(spans, codeFlags, i);
|
||||
lines[i] = `${indentPrefix}${span.text}`;
|
||||
if (oldParsed?.kind === "ordered") {
|
||||
affectedOrderedIndents.add(oldParsed.indentWidth);
|
||||
affectedOrderedIndents.add(oldParsed.indentWidth + deltaSpaces);
|
||||
}
|
||||
}
|
||||
renumberOrderedListFrom(lines, codeFlags, startLine, expandedEndLine, affectedOrderedIndents);
|
||||
} else {
|
||||
const lastSelectedParsed = parsedLines[parsedLines.length - 1]!;
|
||||
const expandedEndLine = findLastDescendantLine(
|
||||
spans,
|
||||
codeFlags,
|
||||
endLine,
|
||||
lastSelectedParsed.indentWidth,
|
||||
);
|
||||
|
||||
let trailingChildDedentCols = 0;
|
||||
for (let i = startLine; i <= endLine; i += 1) {
|
||||
const span = spans[i]!;
|
||||
const parsed = parsedLines[i - startLine]!;
|
||||
let removed = 0;
|
||||
let removedCols = 0;
|
||||
if (parsed.indent.length > 0) {
|
||||
const dedented = dedentToAncestorLevel(spans, codeFlags, i, parsed);
|
||||
removed = dedented.removedChars;
|
||||
removedCols = dedented.removedCols;
|
||||
lines[i] = span.text.slice(removed);
|
||||
if (parsed.kind === "ordered") {
|
||||
affectedOrderedIndents.add(parsed.indentWidth);
|
||||
affectedOrderedIndents.add(Math.max(0, parsed.indentWidth - removedCols));
|
||||
}
|
||||
} else {
|
||||
removed = parsed.prefixLength;
|
||||
removedCols = parsed.markerWidth;
|
||||
lines[i] = span.text.slice(removed);
|
||||
}
|
||||
|
||||
if (i === endLine) {
|
||||
trailingChildDedentCols = removedCols;
|
||||
}
|
||||
}
|
||||
|
||||
// Move un-selected descendants along with the dedented/un-listed parent
|
||||
// so child relationships are preserved and no orphan indentation remains.
|
||||
dedentDescendantBlock(
|
||||
lines,
|
||||
spans,
|
||||
codeFlags,
|
||||
endLine + 1,
|
||||
expandedEndLine,
|
||||
trailingChildDedentCols,
|
||||
affectedOrderedIndents,
|
||||
);
|
||||
renumberOrderedListFrom(lines, codeFlags, startLine, expandedEndLine, affectedOrderedIndents);
|
||||
}
|
||||
|
||||
// Recompute exact selection offsets from per-line length deltas.
|
||||
const nextValue = lines.join("\n");
|
||||
const nextSpans = getLineSpans(nextValue);
|
||||
const startDelta = nextSpans[startLine]!.text.length - spans[startLine]!.text.length;
|
||||
const endDelta = nextSpans[endLine]!.text.length - spans[endLine]!.text.length;
|
||||
const startCol = selectionStart - spans[startLine]!.start;
|
||||
const endCol = selectionEnd - spans[endLine]!.start;
|
||||
const nextStartCol = Math.max(0, Math.min(startCol + startDelta, nextSpans[startLine]!.text.length));
|
||||
const nextEndCol = Math.max(0, Math.min(endCol + endDelta, nextSpans[endLine]!.text.length));
|
||||
|
||||
return {
|
||||
value: nextValue,
|
||||
selectionStart: nextSpans[startLine]!.start + nextStartCol,
|
||||
selectionEnd: nextSpans[endLine]!.start + nextEndCol,
|
||||
};
|
||||
}
|
||||
|
||||
// 3. Backspace right after a list marker: dedent if nested, or remove the marker cleanly.
|
||||
if (event.key === "Backspace" && !event.shiftKey && selectionStart === selectionEnd) {
|
||||
const spans = getLineSpans(value);
|
||||
const codeFlags = getCodeBlockLineFlags(spans);
|
||||
const lineIdx = findLineIndexForOffset(spans, selectionStart);
|
||||
const lineSpan = spans[lineIdx]!;
|
||||
const parsed = parseNonCodeListLine(spans, codeFlags, lineIdx);
|
||||
if (!parsed) return null;
|
||||
|
||||
const column = selectionStart - lineSpan.start;
|
||||
if (column !== parsed.prefixLength) return null;
|
||||
|
||||
const lines = spans.map((span) => span.text);
|
||||
const expandedEndLine = findLastDescendantLine(
|
||||
spans,
|
||||
codeFlags,
|
||||
lineIdx,
|
||||
parsed.indentWidth,
|
||||
);
|
||||
const affectedOrderedIndents = new Set<number>();
|
||||
|
||||
if (parsed.indent.length > 0) {
|
||||
const { removedChars, removedCols } = dedentToAncestorLevel(spans, codeFlags, lineIdx, parsed);
|
||||
lines[lineIdx] = lineSpan.text.slice(removedChars);
|
||||
if (parsed.kind === "ordered") {
|
||||
affectedOrderedIndents.add(parsed.indentWidth);
|
||||
affectedOrderedIndents.add(Math.max(0, parsed.indentWidth - removedCols));
|
||||
}
|
||||
dedentDescendantBlock(
|
||||
lines,
|
||||
spans,
|
||||
codeFlags,
|
||||
lineIdx + 1,
|
||||
expandedEndLine,
|
||||
removedCols,
|
||||
affectedOrderedIndents,
|
||||
);
|
||||
renumberOrderedListFrom(lines, codeFlags, lineIdx, expandedEndLine, affectedOrderedIndents);
|
||||
const nextValue = lines.join("\n");
|
||||
const nextSpans = getLineSpans(nextValue);
|
||||
const nextParsed = parseListLine(nextSpans[lineIdx]!.text);
|
||||
const nextCursor = nextSpans[lineIdx]!.start + (nextParsed?.prefixLength ?? 0);
|
||||
return {
|
||||
value: nextValue,
|
||||
selectionStart: nextCursor,
|
||||
selectionEnd: nextCursor,
|
||||
};
|
||||
}
|
||||
|
||||
lines[lineIdx] = lineSpan.text.slice(parsed.prefixLength);
|
||||
if (parsed.kind === "ordered") {
|
||||
affectedOrderedIndents.add(parsed.indentWidth);
|
||||
}
|
||||
dedentDescendantBlock(
|
||||
lines,
|
||||
spans,
|
||||
codeFlags,
|
||||
lineIdx + 1,
|
||||
expandedEndLine,
|
||||
parsed.markerWidth,
|
||||
affectedOrderedIndents,
|
||||
);
|
||||
renumberOrderedListFrom(lines, codeFlags, lineIdx, expandedEndLine, affectedOrderedIndents);
|
||||
const nextValue = lines.join("\n");
|
||||
const nextSpans = getLineSpans(nextValue);
|
||||
return {
|
||||
value: nextValue,
|
||||
selectionStart: nextSpans[lineIdx]!.start,
|
||||
selectionEnd: nextSpans[lineIdx]!.start,
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,421 @@
|
||||
export interface ParsedListLineBase {
|
||||
indent: string;
|
||||
indentWidth: number;
|
||||
/** Width of the CommonMark list marker + following space (content column offset from indent). */
|
||||
markerWidth: number;
|
||||
/** Column where list item content begins (`indentWidth + markerWidth`). */
|
||||
contentIndentWidth: number;
|
||||
prefixLength: number;
|
||||
content: string;
|
||||
}
|
||||
|
||||
export interface ParsedUnorderedListLine extends ParsedListLineBase {
|
||||
kind: "unordered";
|
||||
marker: string;
|
||||
checkbox: string | null;
|
||||
space: string;
|
||||
}
|
||||
|
||||
export interface ParsedOrderedListLine extends ParsedListLineBase {
|
||||
kind: "ordered";
|
||||
number: number;
|
||||
space: string;
|
||||
}
|
||||
|
||||
export type ParsedListLine = ParsedUnorderedListLine | ParsedOrderedListLine;
|
||||
|
||||
export interface LineSpan {
|
||||
index: number;
|
||||
start: number;
|
||||
end: number;
|
||||
text: string;
|
||||
}
|
||||
|
||||
const UNORDERED_LIST_LINE_RE = /^([ \t]*)([-*+])([ \t]+\[[ xX]\])?([ \t]+)(.*)$/;
|
||||
const ORDERED_LIST_LINE_RE = /^([ \t]*)(\d+)\.([ \t]+)(.*)$/;
|
||||
const FENCE_OPEN_RE = /^([ \t]*)(`{3,}|~{3,})(.*)$/;
|
||||
export const INDENT_STEP = " ";
|
||||
const TAB_WIDTH = 4;
|
||||
|
||||
export function measureIndentWidth(indent: string): number {
|
||||
let width = 0;
|
||||
for (const ch of indent) {
|
||||
if (ch === "\t") {
|
||||
width += TAB_WIDTH - (width % TAB_WIDTH);
|
||||
} else {
|
||||
width += 1;
|
||||
}
|
||||
}
|
||||
return width;
|
||||
}
|
||||
|
||||
export function measureLineIndentWidth(line: string): number {
|
||||
const leadingWs = line.match(/^[ \t]*/)?.[0] ?? "";
|
||||
return measureIndentWidth(leadingWs);
|
||||
}
|
||||
|
||||
export function parseListLine(line: string): ParsedListLine | null {
|
||||
const unordered = UNORDERED_LIST_LINE_RE.exec(line);
|
||||
if (unordered) {
|
||||
const [, indent, marker, checkbox, space, content] = unordered;
|
||||
const indentWidth = measureIndentWidth(indent);
|
||||
const spaceAfterMarker = checkbox
|
||||
? (checkbox.match(/^[ \t]+/)?.[0] ?? " ")
|
||||
: space;
|
||||
const markerWidth = marker.length + measureIndentWidth(spaceAfterMarker);
|
||||
const prefixLength = indent.length + marker.length + (checkbox?.length ?? 0) + space.length;
|
||||
return {
|
||||
kind: "unordered",
|
||||
indent,
|
||||
indentWidth,
|
||||
markerWidth,
|
||||
contentIndentWidth: indentWidth + markerWidth,
|
||||
marker,
|
||||
checkbox: checkbox ?? null,
|
||||
space,
|
||||
prefixLength,
|
||||
content,
|
||||
};
|
||||
}
|
||||
|
||||
const ordered = ORDERED_LIST_LINE_RE.exec(line);
|
||||
if (ordered) {
|
||||
const [, indent, numberText, space, content] = ordered;
|
||||
const indentWidth = measureIndentWidth(indent);
|
||||
const markerWidth = numberText.length + 1 + measureIndentWidth(space);
|
||||
const prefixLength = indent.length + numberText.length + 1 + space.length;
|
||||
return {
|
||||
kind: "ordered",
|
||||
indent,
|
||||
indentWidth,
|
||||
markerWidth,
|
||||
contentIndentWidth: indentWidth + markerWidth,
|
||||
number: Number.parseInt(numberText, 10),
|
||||
space,
|
||||
prefixLength,
|
||||
content,
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export function getLineSpans(value: string): LineSpan[] {
|
||||
const rawLines = value.split("\n");
|
||||
const spans: LineSpan[] = [];
|
||||
let offset = 0;
|
||||
for (let index = 0; index < rawLines.length; index += 1) {
|
||||
const text = rawLines[index]!;
|
||||
const start = offset;
|
||||
const end = start + text.length;
|
||||
spans.push({ index, start, end, text });
|
||||
offset = end + 1;
|
||||
}
|
||||
return spans;
|
||||
}
|
||||
|
||||
export function findLineIndexForOffset(spans: readonly LineSpan[], offset: number): number {
|
||||
for (let i = 0; i < spans.length; i += 1) {
|
||||
const span = spans[i]!;
|
||||
if (offset <= span.end) return i;
|
||||
}
|
||||
return spans.length - 1;
|
||||
}
|
||||
|
||||
export function getSelectedLineRange(
|
||||
spans: readonly LineSpan[],
|
||||
selectionStart: number,
|
||||
selectionEnd: number,
|
||||
): { startLine: number; endLine: number } {
|
||||
const start = Math.min(selectionStart, selectionEnd);
|
||||
const end = Math.max(selectionStart, selectionEnd);
|
||||
const startLine = findLineIndexForOffset(spans, start);
|
||||
// If a non-collapsed selection ends at column 0 of the next line, exclude that trailing line.
|
||||
const effectiveEnd = end > start && spans[findLineIndexForOffset(spans, end)]?.start === end
|
||||
? end - 1
|
||||
: end;
|
||||
const endLine = findLineIndexForOffset(spans, effectiveEnd);
|
||||
return { startLine, endLine };
|
||||
}
|
||||
|
||||
/**
|
||||
* Identify lines that belong to fenced code blocks (``` / ~~~) or CommonMark
|
||||
* indented code blocks (4+ columns beyond the active list content column).
|
||||
*/
|
||||
export function getCodeBlockLineFlags(spans: readonly LineSpan[]): boolean[] {
|
||||
const flags = new Array<boolean>(spans.length).fill(false);
|
||||
let openFence: { char: "`" | "~"; length: number; ownerListBaseCol: number } | null = null;
|
||||
const listContentColumns: number[] = [];
|
||||
let prevWasBlankOrStart = true;
|
||||
let prevWasIndentedCode = false;
|
||||
|
||||
for (let i = 0; i < spans.length; i += 1) {
|
||||
const line = spans[i]!.text;
|
||||
const isBlank = line.trim() === "";
|
||||
const leadingWs = isBlank ? "" : (line.match(/^[ \t]*/)?.[0] ?? "");
|
||||
const indentWidth = isBlank ? 0 : measureIndentWidth(leadingWs);
|
||||
|
||||
if (openFence) {
|
||||
// Per CommonMark, an unclosed fence inside a list item ends as soon as
|
||||
// a non-blank line dedents past the containing list item's content column.
|
||||
if (!isBlank && openFence.ownerListBaseCol > 0 && indentWidth < openFence.ownerListBaseCol) {
|
||||
openFence = null;
|
||||
} else {
|
||||
flags[i] = true;
|
||||
if (!isBlank) {
|
||||
const trimmed = line.slice(leadingWs.length);
|
||||
const closeRe = new RegExp(`^${openFence.char}{${openFence.length},}[ \\t]*$`);
|
||||
if (closeRe.test(trimmed)) {
|
||||
openFence = null;
|
||||
prevWasBlankOrStart = false;
|
||||
prevWasIndentedCode = false;
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (isBlank) {
|
||||
prevWasBlankOrStart = true;
|
||||
prevWasIndentedCode = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
while (
|
||||
listContentColumns.length > 0 &&
|
||||
listContentColumns[listContentColumns.length - 1]! > indentWidth
|
||||
) {
|
||||
listContentColumns.pop();
|
||||
}
|
||||
|
||||
const activeListBaseCol = listContentColumns[listContentColumns.length - 1] ?? 0;
|
||||
const isIndentedCodeCandidate =
|
||||
indentWidth >= activeListBaseCol + TAB_WIDTH &&
|
||||
(prevWasBlankOrStart || prevWasIndentedCode);
|
||||
|
||||
if (isIndentedCodeCandidate) {
|
||||
flags[i] = true;
|
||||
prevWasBlankOrStart = false;
|
||||
prevWasIndentedCode = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
const fenceMatch = FENCE_OPEN_RE.exec(line);
|
||||
if (fenceMatch) {
|
||||
const [, fenceIndent, fenceMarker, info] = fenceMatch;
|
||||
const fenceIndentWidth = measureIndentWidth(fenceIndent);
|
||||
const fenceChar = fenceMarker[0] as "`" | "~";
|
||||
const validBacktickInfo = fenceChar !== "`" || !info.includes("`");
|
||||
if (fenceIndentWidth < activeListBaseCol + TAB_WIDTH && validBacktickInfo) {
|
||||
flags[i] = true;
|
||||
openFence = {
|
||||
char: fenceChar,
|
||||
length: fenceMarker.length,
|
||||
ownerListBaseCol: activeListBaseCol,
|
||||
};
|
||||
prevWasBlankOrStart = false;
|
||||
prevWasIndentedCode = false;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
const parsed = parseListLine(line);
|
||||
if (parsed) {
|
||||
if (parsed.indentWidth >= activeListBaseCol + TAB_WIDTH) {
|
||||
flags[i] = true;
|
||||
prevWasBlankOrStart = false;
|
||||
prevWasIndentedCode = true;
|
||||
continue;
|
||||
}
|
||||
listContentColumns.push(parsed.contentIndentWidth);
|
||||
} else if (indentWidth < activeListBaseCol) {
|
||||
listContentColumns.length = 0;
|
||||
}
|
||||
|
||||
prevWasBlankOrStart = false;
|
||||
prevWasIndentedCode = false;
|
||||
}
|
||||
|
||||
return flags;
|
||||
}
|
||||
|
||||
export function parseNonCodeListLine(
|
||||
spans: readonly LineSpan[],
|
||||
codeFlags: readonly boolean[],
|
||||
lineIndex: number,
|
||||
): ParsedListLine | null {
|
||||
if (lineIndex < 0 || lineIndex >= spans.length) return null;
|
||||
if (codeFlags[lineIndex]) return null;
|
||||
return parseListLine(spans[lineIndex]!.text);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the nearest preceding sibling list item at `targetIndentWidth` that a
|
||||
* list item at `lineIndex` can nest under when indented. Skips blank lines and
|
||||
* indented continuation lines/blocks that belong to the preceding item.
|
||||
*/
|
||||
export function findPrecedingSiblingToNestUnder(
|
||||
spans: readonly LineSpan[],
|
||||
codeFlags: readonly boolean[],
|
||||
lineIndex: number,
|
||||
targetIndentWidth: number,
|
||||
): ParsedListLine | null {
|
||||
for (let i = lineIndex - 1; i >= 0; i -= 1) {
|
||||
const text = spans[i]!.text;
|
||||
if (text.trim() === "") continue;
|
||||
if (codeFlags[i]) {
|
||||
if (measureLineIndentWidth(text) > targetIndentWidth) continue;
|
||||
return null;
|
||||
}
|
||||
const parsed = parseListLine(text);
|
||||
if (!parsed) {
|
||||
if (measureLineIndentWidth(text) > targetIndentWidth) continue;
|
||||
return null;
|
||||
}
|
||||
if (parsed.indentWidth < targetIndentWidth) return null;
|
||||
if (parsed.indentWidth === targetIndentWidth) return parsed;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the nearest enclosing ancestor list item whose indent width is strictly
|
||||
* less than `currentIndentWidth`.
|
||||
*/
|
||||
function findParentListItem(
|
||||
spans: readonly LineSpan[],
|
||||
codeFlags: readonly boolean[],
|
||||
lineIndex: number,
|
||||
currentIndentWidth: number,
|
||||
): ParsedListLine | null {
|
||||
for (let i = lineIndex - 1; i >= 0; i -= 1) {
|
||||
const text = spans[i]!.text;
|
||||
if (text.trim() === "") continue;
|
||||
if (codeFlags[i]) {
|
||||
if (measureLineIndentWidth(text) >= currentIndentWidth) continue;
|
||||
return null;
|
||||
}
|
||||
const parsed = parseListLine(text);
|
||||
if (!parsed) {
|
||||
if (measureLineIndentWidth(text) >= currentIndentWidth) continue;
|
||||
return null;
|
||||
}
|
||||
if (parsed.indentWidth < currentIndentWidth) return parsed;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function removeIndentColumns(
|
||||
indent: string,
|
||||
columnsToRemove: number,
|
||||
): { nextIndent: string; removedChars: number } {
|
||||
if (columnsToRemove <= 0 || indent.length === 0) {
|
||||
return { nextIndent: indent, removedChars: 0 };
|
||||
}
|
||||
let removedCols = 0;
|
||||
let removedChars = 0;
|
||||
for (const ch of indent) {
|
||||
if (removedCols >= columnsToRemove) break;
|
||||
const colWidth = ch === "\t" ? TAB_WIDTH - (removedCols % TAB_WIDTH) : 1;
|
||||
removedCols += colWidth;
|
||||
removedChars += 1;
|
||||
}
|
||||
return {
|
||||
nextIndent: indent.slice(removedChars),
|
||||
removedChars,
|
||||
};
|
||||
}
|
||||
|
||||
export function dedentToAncestorLevel(
|
||||
spans: readonly LineSpan[],
|
||||
codeFlags: readonly boolean[],
|
||||
lineIndex: number,
|
||||
parsed: ParsedListLine,
|
||||
): { nextIndent: string; removedChars: number; removedCols: number } {
|
||||
const parent = findParentListItem(spans, codeFlags, lineIndex, parsed.indentWidth);
|
||||
if (parent) {
|
||||
const targetDelta = parsed.indentWidth - parent.indentWidth;
|
||||
const { nextIndent, removedChars } = removeIndentColumns(parsed.indent, targetDelta);
|
||||
return {
|
||||
nextIndent,
|
||||
removedChars,
|
||||
removedCols: parsed.indentWidth - measureIndentWidth(nextIndent),
|
||||
};
|
||||
}
|
||||
if (parsed.indent.startsWith("\t")) {
|
||||
const nextIndent = parsed.indent.slice(1);
|
||||
return {
|
||||
nextIndent,
|
||||
removedChars: 1,
|
||||
removedCols: parsed.indentWidth - measureIndentWidth(nextIndent),
|
||||
};
|
||||
}
|
||||
const fallbackCols = Math.min(parsed.indentWidth, INDENT_STEP.length);
|
||||
const { nextIndent, removedChars } = removeIndentColumns(parsed.indent, fallbackCols);
|
||||
return {
|
||||
nextIndent,
|
||||
removedChars,
|
||||
removedCols: parsed.indentWidth - measureIndentWidth(nextIndent),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the last contiguous descendant or continuation line strictly following
|
||||
* `afterLine` whose indent width is greater than `parentIndentWidth`.
|
||||
*/
|
||||
export function findLastDescendantLine(
|
||||
spans: readonly LineSpan[],
|
||||
codeFlags: readonly boolean[],
|
||||
afterLine: number,
|
||||
parentIndentWidth: number,
|
||||
): number {
|
||||
let lastDescendant = afterLine;
|
||||
for (let i = afterLine + 1; i < spans.length; i += 1) {
|
||||
const text = spans[i]!.text;
|
||||
if (text.trim() === "") continue;
|
||||
const indentWidth = codeFlags[i]
|
||||
? measureLineIndentWidth(text)
|
||||
: (parseListLine(text)?.indentWidth ?? measureLineIndentWidth(text));
|
||||
if (indentWidth <= parentIndentWidth) break;
|
||||
lastDescendant = i;
|
||||
}
|
||||
return lastDescendant;
|
||||
}
|
||||
|
||||
export function formatListItemPrefix(
|
||||
parsed: ParsedListLine,
|
||||
options?: { indent?: string; number?: number; uncheckCheckbox?: boolean },
|
||||
): string {
|
||||
const indent = options?.indent ?? parsed.indent;
|
||||
if (parsed.kind === "unordered") {
|
||||
const checkbox = options?.uncheckCheckbox
|
||||
? (parsed.checkbox ? " [ ]" : "")
|
||||
: (parsed.checkbox ?? "");
|
||||
return `${indent}${parsed.marker}${checkbox}${parsed.space}`;
|
||||
}
|
||||
const number = options?.number ?? parsed.number;
|
||||
return `${indent}${number}.${parsed.space}`;
|
||||
}
|
||||
|
||||
export function dedentDescendantBlock(
|
||||
lines: string[],
|
||||
spans: readonly LineSpan[],
|
||||
codeFlags: readonly boolean[],
|
||||
startLine: number,
|
||||
endLine: number,
|
||||
removedCols: number,
|
||||
affectedOrderedIndents: Set<number>,
|
||||
): void {
|
||||
for (let i = startLine; i <= endLine; i += 1) {
|
||||
const text = spans[i]!.text;
|
||||
if (text.trim() === "") continue;
|
||||
const childParsed = parseNonCodeListLine(spans, codeFlags, i);
|
||||
const leadingWs = text.match(/^[ \t]*/)?.[0] ?? "";
|
||||
const { removedChars } = removeIndentColumns(leadingWs, removedCols);
|
||||
lines[i] = text.slice(removedChars);
|
||||
if (childParsed?.kind === "ordered") {
|
||||
affectedOrderedIndents.add(childParsed.indentWidth);
|
||||
affectedOrderedIndents.add(measureLineIndentWidth(lines[i]!));
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user