TypeScript
fix(web): numbered composer lists nest and lift correctly (#17138)
michal-billtechfec83a18e363
diff --git a/apps/web/src/composer-list-continuation.test.ts b/apps/web/src/composer-list-continuation.test.tsindex e96a3fb5279..12774bae205 100644--- a/apps/web/src/composer-list-continuation.test.ts+++ b/apps/web/src/composer-list-continuation.test.ts@@ -1,6 +1,10 @@import { describe, expect, it } from "vite-plus/test";-import { listContinuationForEnter, nextOrderedMarkerText } from "./composer-list-continuation";+import {+ listContinuationForEnter,+ listIndentForTab,+ nextOrderedMarkerText,+} from "./composer-list-continuation";function applyEdit(value: string, edit: { start: number; end: number; replacement: string }) {return value.slice(0, edit.start) + edit.replacement + value.slice(edit.end);@@ -31,6 +35,25 @@ describe("composer list continuation", () => {expect(applyEdit("- [ ] ", listContinuationForEnter("- [ ] ", 6)!)).toBe("");});+ it("lifts an empty nested item one level per press before leaving the list", () => {+ let value = "1. parent\n 1. child\n 1. ";+ for (const expected of [+ "1. parent\n 1. child\n 2. ",+ "1. parent\n 1. child\n2. ",+ "1. parent\n 1. child\n",+ ]) {+ value = applyEdit(value, listContinuationForEnter(value, value.length)!);+ expect(value).toBe(expected);+ }+ });++ it("renumbers the parent list after lifting an empty nested item", () => {+ const value = "1. a\n 1. \n2. b";+ const edit = listContinuationForEnter(value, value.indexOf("\n2."))!;+ expect(applyEdit(value, edit)).toBe("1. a\n2. \n3. b");+ expect(edit.cursorAfter).toBe("1. a\n2. ".length);+ });+it("refuses to split a supplementary currency skill chip", () => {const value = "1. 𑿝review go";const cursor = value.indexOf(" go") - 1;@@ -44,6 +67,27 @@ describe("composer list continuation", () => {});});+describe("composer list indentation", () => {+ // regression: #17124 Tab must nest a numbered item at its parent's content column+ it.each([+ ["1. parent\n2. child", "1. parent\n 1. child"],+ ["10. parent\n11. child", "10. parent\n 1. child"],+ ["1.\tparent\n2. child", "1.\tparent\n 1. child"],+ ['1. @"file\n 9. name"\n2. child', '1. @"file\n 9. name"\n 1. child'],+ ])("nests %j as a first child and keeps the caret on its text", (value, expected) => {+ const cursor = value.lastIndexOf("child") + 2;+ const edit = listIndentForTab(value, cursor, cursor)!;+ expect(applyEdit(value, edit)).toBe(expected);+ expect(edit.cursorAfter).toBe(expected.lastIndexOf("child") + 2);+ });++ it("continues the numbering of an existing nested sibling", () => {+ const value = "1. parent\n 1. first\n2. second";+ const edit = listIndentForTab(value, value.length, value.length)!;+ expect(applyEdit(value, edit)).toBe("1. parent\n 1. first\n 2. second");+ });+});+describe("nextOrderedMarkerText", () => {it.each([["1.", "2."],diff --git a/apps/web/src/composer-list-continuation.ts b/apps/web/src/composer-list-continuation.tsindex 1c2de5a4824..583cf1bd04a 100644--- a/apps/web/src/composer-list-continuation.ts+++ b/apps/web/src/composer-list-continuation.ts@@ -13,39 +13,60 @@ type ListMarker =| { kind: "task"; indent: string; space: string }| { kind: "bullet"; indent: string; bullet: string; space: string };-function parseListMarker(line: string): { marker: ListMarker; markerEnd: number } | null {+interface ParsedListMarker {+ marker: ListMarker;+ markerEnd: number;+ /** Column a nested item must reach to belong to this item. */+ contentColumn: number;+}++function parseListMarker(line: string): ParsedListMarker | null {const indent = line.match(/^[ \t]*/)?.[0] ?? "";const rest = line.slice(indent.length);const ordered = rest.match(/^(\d+)([.)])((?:[ \t]+)|\s*$)/);if (ordered && ordered[1] !== undefined && ordered[2] !== undefined) {+ const space = ordered[3] ?? "";return {marker: {kind: "ordered",indent,numberText: ordered[1],delimiter: ordered[2] === ")" ? ")" : ".",- space: ordered[3] ?? "",+ space,},markerEnd: indent.length + ordered[0].length,+ contentColumn: contentColumn(indent, ordered[1].length + 1, space),};}- const task = rest.match(/^-\s\[[ xX]\]((?:[ \t]+)|\s*$)/);- if (task) {+ // The checkbox is item content, so a task's content starts after "- ".+ const task = rest.match(/^-(\s)\[[ xX]\]((?:[ \t]+)|\s*$)/);+ if (task && task[1] !== undefined) {return {- marker: { kind: "task", indent, space: task[1] ?? "" },+ marker: { kind: "task", indent, space: task[2] ?? "" },markerEnd: indent.length + task[0].length,+ contentColumn: contentColumn(indent, 1, task[1]),};}const bullet = rest.match(/^([-*+])((?:[ \t]+)|\s*$)/);if (bullet && bullet[1] !== undefined) {+ const space = bullet[2] ?? "";return {- marker: { kind: "bullet", indent, bullet: bullet[1], space: bullet[2] ?? "" },+ marker: { kind: "bullet", indent, bullet: bullet[1], space },markerEnd: indent.length + bullet[0].length,+ contentColumn: contentColumn(indent, 1, space),};}return null;}+// CommonMark content follows 1-4 columns of padding; wider padding is code, so the content+// column sits one column past the marker.+function contentColumn(indent: string, markerWidth: number, padding: string): number {+ const markerEnd = indentWidth(indent) + markerWidth;+ const space = indentWidth(padding, markerEnd);+ return markerEnd + (space >= 1 && space <= 4 ? space : 1);+}+export function nextOrderedMarkerText(marker: string): string {const numberText = marker.slice(0, -1);const delimiter = marker.slice(-1);@@ -67,14 +88,14 @@ function nextMarkerText(marker: ListMarker): string {}// Markdown tabs advance to the next four-column stop.-function indentWidth(line: string): number {- let width = 0;+function indentWidth(line: string, fromColumn = 0): number {+ let column = fromColumn;for (const char of line) {- if (char === " ") width += 1;- else if (char === "\t") width += 4 - (width % 4);+ if (char === " ") column += 1;+ else if (char === "\t") column += 4 - (column % 4);else break;}- return width;+ return column - fromColumn;}function renumberFollowingItems(@@ -149,6 +170,55 @@ function currentLine(value: string, cursor: number): { start: number; end: numbereturn { start, end, text: value.slice(start, end) };}+function* listMarkersAbove(+ value: string,+ lineStart: number,+ tokens: ReturnType<typeof inlineTokenRanges>,+): Generator<ParsedListMarker> {+ let tokenIndex = tokens.length - 1;+ while (lineStart > 0) {+ const lineEnd = lineStart - 1;+ lineStart = value.lastIndexOf("\n", lineEnd - 1) + 1;+ // A newline inside a chip does not start a list item.+ for (let token = tokens[tokenIndex]; token; token = tokens[tokenIndex]) {+ if (token.start >= lineStart) tokenIndex -= 1;+ else if (token.end > lineStart) lineStart = value.lastIndexOf("\n", token.start - 1) + 1;+ else break;+ }+ const parsed = parseListMarker(value.slice(lineStart, lineEnd));+ if (!parsed) return;+ yield parsed;+ }+}++function parentMarker(+ value: string,+ lineStart: number,+ marker: ListMarker,+ tokens: ReturnType<typeof inlineTokenRanges>,+): ListMarker | null {+ const width = indentWidth(marker.indent);+ for (const above of listMarkersAbove(value, lineStart, tokens)) {+ if (indentWidth(above.marker.indent) < width) return above.marker;+ }+ return null;+}++function nestedNumber(+ marker: ListMarker,+ previousChild: ListMarker | undefined,+): { replacedLength: number; text: string } {+ if (marker.kind !== "ordered") return { replacedLength: 0, text: "" };+ const continues =+ previousChild?.kind === "ordered" && previousChild.delimiter === marker.delimiter;+ return {+ replacedLength: marker.numberText.length,+ text: continues+ ? nextOrderedMarkerText(`${previousChild.numberText}${marker.delimiter}`).slice(0, -1)+ : "1",+ };+}+export function listContinuationForEnter(value: string, cursor: number): ComposerListEdit | null {if (!Number.isInteger(cursor) || cursor < 0 || cursor > value.length) return null;const line = currentLine(value, cursor);@@ -159,12 +229,21 @@ export function listContinuationForEnter(value: string, cursor: number): Composeconst tokens = inlineTokenRanges(value);if (isInsideInlineToken(tokens, cursor)) return null;if (value.slice(markerEnd, line.end).trim() === "") {- return {- start: line.start,- end: Math.max(cursor, markerEnd),- replacement: "",- cursorAfter: line.start,- };+ const parent = parentMarker(value, line.start, parsed.marker, tokens);+ const replacement = parent ? nextMarkerText(parent) : "";+ const cursorAfter = line.start + replacement.length;+ const end = Math.max(cursor, markerEnd);+ const renumbered =+ parent?.kind === "ordered" ? renumberFollowingItems(value, line.end, parent, tokens) : null;+ if (renumbered) {+ return {+ start: line.start,+ end: renumbered.end,+ replacement: replacement + value.slice(end, line.end) + renumbered.text,+ cursorAfter,+ };+ }+ return { start: line.start, end, replacement, cursorAfter };}const insertion = `\n${nextMarkerText(parsed.marker)}`;const cursorAfter = cursor + insertion.length;@@ -190,7 +269,36 @@ export function listIndentForTab(): ComposerListEdit | null {if (!Number.isInteger(start) || start !== end || start < 0 || start > value.length) return null;const line = currentLine(value, start);- if (!parseListMarker(line.text)) return null;- if (isInsideInlineToken(inlineTokenRanges(value), start)) return null;+ const parsed = parseListMarker(line.text);+ if (!parsed) return null;+ const tokens = inlineTokenRanges(value);+ if (isInsideInlineToken(tokens, start)) return null;+ const { marker } = parsed;+ const width = indentWidth(marker.indent);+ let previousChild: ListMarker | undefined;+ for (const above of listMarkersAbove(value, line.start, tokens)) {+ const aboveWidth = indentWidth(above.marker.indent);+ if (aboveWidth < width) break;+ if (aboveWidth > width) {+ if (!previousChild || aboveWidth < indentWidth(previousChild.indent)) {+ previousChild = above.marker;+ }+ continue;+ }+ const indent =+ previousChild?.indent ?? above.marker.indent + " ".repeat(above.contentColumn - aboveWidth);+ const number = nestedNumber(marker, previousChild);+ const replacedEnd = line.start + marker.indent.length + number.replacedLength;+ const replacement = indent + number.text;+ return {+ start: line.start,+ end: replacedEnd,+ replacement,+ cursorAfter:+ start < replacedEnd+ ? line.start + indent.length+ : start - replacedEnd + line.start + replacement.length,+ };+ }return { start: line.start, end: line.start, replacement: " ", cursorAfter: start + 2 };}diff --git a/docs/user/composer.md b/docs/user/composer.mdindex e0d1f541851..714572dfd50 100644--- a/docs/user/composer.md+++ b/docs/user/composer.md@@ -22,7 +22,8 @@ block. What you typed is what the agent receives, markers and numberingincluded, and `#1234` without a space still looks up a pull request.Enter sends. In a list or quote, **Shift+Enter** continues it, and Shift+Enter-on an empty line leaves it; **Tab** nests a list item. In a code block, Enter+on an empty line moves out one level, then leaves it; **Tab** nests a list item+under the one above. In a code block, Enterstarts a new line at the current indentation, **Tab** and **Shift+Tab** indentthe selected lines, and a closing ` ``` ` followed by Enter, or two blank linesat the end, leave the block. **Backspace** at the start of a code block turns it