TypeScript
fix(web): renumber following items when continuing a plain-Markdown numbered list (#14332)
Alex Southwelld407f5443be2
diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsxindex 80b980a76f4..146393fcc8c 100644--- a/apps/web/src/components/chat/ChatComposer.tsx+++ b/apps/web/src/components/chat/ChatComposer.tsx@@ -4216,14 +4216,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps): listIndentForTab(snapshot.value, selection.start, selection.end);if (edit &&- applyPromptReplacement(- edit.start,- edit.end,- edit.replacement,- key === "Tab"- ? { expandedCursorAfterReplace: selection.start + edit.replacement.length }- : undefined,- )+ applyPromptReplacement(edit.start, edit.end, edit.replacement, {+ expandedCursorAfterReplace: edit.cursorAfter,+ })) {return true;}diff --git a/apps/web/src/composer-list-continuation.test.ts b/apps/web/src/composer-list-continuation.test.tsindex a878ed95a12..aeab28a9b36 100644--- a/apps/web/src/composer-list-continuation.test.ts+++ b/apps/web/src/composer-list-continuation.test.ts@@ -83,3 +83,37 @@ describe("nextOrderedMarkerText", () => {expect(nextOrderedMarkerText(marker)).toBe(expected);});});++describe("composer list renumbering", () => {+ it("renumbers following items with their padding and leaves the caret after the inserted marker", () => {+ const value = "1. @README.md go\n2. two\n03. three\n10. four";+ const edit = listContinuationForEnter(value, value.indexOf("go"))!;+ expect(applyEdit(value, edit)).toBe("1. @README.md \n2. go\n3. two\n04. three\n5. four");+ expect(edit.cursorAfter).toBe("1. @README.md \n2. ".length);+ });++ it("renumbers indented paren siblings across tab-indented children and stops at a parent", () => {+ const value = " 1) a\n\t1) child\n 2) b\n1) parent\n 3) untouched";+ const edit = listContinuationForEnter(value, value.indexOf("\n"))!;+ expect(applyEdit(value, edit)).toBe(+ " 1) a\n 2) \n\t1) child\n 3) b\n1) parent\n 3) untouched",+ );+ expect(edit.cursorAfter).toBe(" 1) a\n 2) ".length);+ });++ it.each([+ ["a blank line", ""],+ ["plain text", "text"],+ ["a different delimiter", "1) other list"],+ ])("stops renumbering at %s", (_label, boundary) => {+ const value = `1. a\n2. b\n${boundary}\n3. untouched`;+ const edit = listContinuationForEnter(value, value.indexOf("\n"))!;+ expect(applyEdit(value, edit)).toBe(`1. a\n2. \n3. b\n${boundary}\n3. untouched`);+ });++ it("preserves multiline chip contents while renumbering surrounding items", () => {+ const value = '1. a\n2. @"file\n2. name" \n3. b';+ const edit = listContinuationForEnter(value, value.indexOf("\n"))!;+ expect(applyEdit(value, edit)).toBe('1. a\n2. \n3. @"file\n2. name" \n4. b');+ });+});diff --git a/apps/web/src/composer-list-continuation.ts b/apps/web/src/composer-list-continuation.tsindex 7ebb943ad49..4cbf52aab7f 100644--- a/apps/web/src/composer-list-continuation.ts+++ b/apps/web/src/composer-list-continuation.ts@@ -4,6 +4,8 @@ export interface ComposerListEdit {start: number;end: number;replacement: string;+ /** Expanded caret offset after the edit is applied. */+ cursorAfter: number;}type ListMarker =@@ -64,21 +66,80 @@ function nextMarkerText(marker: ListMarker): string {return `${marker.indent}${marker.bullet} `;}-function segmentSource(- segment: ReturnType<typeof splitPromptIntoComposerSegments>[number],-): string {- if (segment.type === "text") return segment.text;- return segment.source;+// Markdown tabs advance to the next four-column stop.+function indentWidth(line: string): number {+ let width = 0;+ for (const char of line) {+ if (char === " ") width += 1;+ else if (char === "\t") width += 4 - (width % 4);+ else break;+ }+ return width;+}++function renumberFollowingItems(+ value: string,+ afterLineEnd: number,+ marker: Extract<ListMarker, { kind: "ordered" }>,+ tokens: ReturnType<typeof inlineTokenRanges>,+): { end: number; text: string } | null {+ const baseWidth = indentWidth(marker.indent);+ const parts: string[] = [];+ let expected = Number.parseInt(marker.numberText, 10) + 2;+ let position = afterLineEnd;+ let copiedUntil = afterLineEnd;+ let tokenIndex = 0;+ while (position < value.length && Number.isSafeInteger(expected)) {+ const lineStart = position + 1;+ const nextBreak = value.indexOf("\n", lineStart);+ const lineEnd = nextBreak === -1 ? value.length : nextBreak;+ position = lineEnd;+ let token = tokens[tokenIndex];+ while (token && token.end <= lineStart) {+ tokenIndex += 1;+ token = tokens[tokenIndex];+ }+ // A newline inside a chip does not start a list item.+ if (token && token.start < lineStart) continue;++ const line = value.slice(lineStart, lineEnd);+ const width = indentWidth(line);+ if (line.trim() === "" || width < baseWidth) break;+ if (width > baseWidth) continue;+ const parsed = parseListMarker(line);+ if (parsed?.marker.kind !== "ordered" || parsed.marker.delimiter !== marker.delimiter) break;++ const current = parsed.marker;+ const numberStart = lineStart + current.indent.length;+ const numberEnd = numberStart + current.numberText.length;+ const replacement = current.numberText.startsWith("0")+ ? String(expected).padStart(current.numberText.length, "0")+ : String(expected);+ if (replacement !== current.numberText) {+ parts.push(value.slice(copiedUntil, numberStart), replacement);+ copiedUntil = numberEnd;+ }+ expected += 1;+ }+ return parts.length === 0 ? null : { end: copiedUntil, text: parts.join("") };}-function isInsideInlineToken(value: string, cursor: number): boolean {+function inlineTokenRanges(value: string): Array<{ start: number; end: number }> {+ const ranges: Array<{ start: number; end: number }> = [];let offset = 0;for (const segment of splitPromptIntoComposerSegments(value)) {- const end = offset + segmentSource(segment).length;- if (segment.type !== "text" && cursor > offset && cursor < end) return true;+ const end = offset + (segment.type === "text" ? segment.text : segment.source).length;+ if (segment.type !== "text") ranges.push({ start: offset, end });offset = end;}- return false;+ return ranges;+}++function isInsideInlineToken(+ tokens: ReturnType<typeof inlineTokenRanges>,+ cursor: number,+): boolean {+ return tokens.some((range) => cursor > range.start && cursor < range.end);}function currentLine(value: string, cursor: number): { start: number; end: number; text: string } {@@ -95,15 +156,31 @@ export function listContinuationForEnter(value: string, cursor: number): Composeif (!parsed) return null;const markerEnd = line.start + parsed.markerEnd;if (cursor < markerEnd) return null;- if (isInsideInlineToken(value, cursor)) return null;+ const 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: "" };+ return {+ start: line.start,+ end: Math.max(cursor, markerEnd),+ replacement: "",+ cursorAfter: line.start,+ };+ }+ const insertion = `\n${nextMarkerText(parsed.marker)}`;+ const cursorAfter = cursor + insertion.length;+ const { marker } = parsed;+ if (marker.kind === "ordered") {+ const renumbered = renumberFollowingItems(value, line.end, marker, tokens);+ if (renumbered) {+ return {+ start: cursor,+ end: renumbered.end,+ replacement: insertion + value.slice(cursor, line.end) + renumbered.text,+ cursorAfter,+ };+ }}- return {- start: cursor,- end: cursor,- replacement: `\n${nextMarkerText(parsed.marker)}`,- };+ return { start: cursor, end: cursor, replacement: insertion, cursorAfter };}export function listIndentForTab(@@ -114,6 +191,6 @@ export function listIndentForTab(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(value, start)) return null;- return { start: line.start, end: line.start, replacement: " " };+ if (isInsideInlineToken(inlineTokenRanges(value), start)) return null;+ return { start: line.start, end: line.start, replacement: " ", cursorAfter: start + 2 };}