From f3e29857b6292823347732bdcef0f1727552fe77 Mon Sep 17 00:00:00 2001 From: repo-worker-code Date: Fri, 30 Oct 2026 18:45:02 -0500 Subject: [PATCH] fix(id/web): per-block indent/dedent for multi-block selections (#1399) Tab/Shift-Tab with a selection spanning multiple blocks corrupted a neighbouring paragraph and skipped later code blocks: line math ran on doc.textBetween across block boundaries as one block's text. Iterate every code_block intersecting the selection and do line math per block, clamped to the selection portion; non-code content is never modified. Adds code+paragraph(+code) regression tests for both commands. --- pkgs/id/web/src/indent.test.ts | 96 ++++++++++++++++++++ pkgs/id/web/src/indent.ts | 155 +++++++++++++++++++++------------ 2 files changed, 196 insertions(+), 55 deletions(-) diff --git a/pkgs/id/web/src/indent.test.ts b/pkgs/id/web/src/indent.test.ts index 1f789183cc..ad82e265b2 100644 --- a/pkgs/id/web/src/indent.test.ts +++ b/pkgs/id/web/src/indent.test.ts @@ -55,6 +55,31 @@ function getCodeText(state: EditorState): string { return state.doc.firstChild?.textContent ?? ""; } +/** Build a code_block child node (richSchema) */ +function codeBlock(text: string) { + return richSchema.node("code_block", null, text ? [richSchema.text(text)] : []); +} + +/** Build a paragraph child node (richSchema) */ +function paragraph(text: string) { + return richSchema.node("paragraph", null, text ? [richSchema.text(text)] : []); +} + +/** Create an EditorState with a mixed doc and a text selection range */ +function createMixedState(children: ReturnType[], from: number, to: number): EditorState { + const doc = richSchema.node("doc", null, children); + const state = EditorState.create({ doc, plugins: [createIndentPlugin()] }); + const tr = state.tr.setSelection(TextSelection.create(state.doc, from, to)); + return state.apply(tr); +} + +/** Get the text content of every top-level child in the doc */ +function getChildTexts(state: EditorState): string[] { + const out: string[] = []; + state.doc.forEach((child) => out.push(child.textContent)); + return out; +} + // ── createIndentPlugin ───────────────────────────────────────────── describe("createIndentPlugin", () => { @@ -257,3 +282,74 @@ describe("dedentCommand with selection", () => { expect(getCodeText(newState!)).toBe("line1\nline2\nline3"); }); }); + +// ── multi-block selections (#1399) ────────────────────────────────── + +describe("indentCommand with multi-block selection (#1399)", () => { + it("indents every overlapped code_block and leaves prose untouched", () => { + // doc: code_block("x\ny") + paragraph("mid") + code_block("p\nq") + const children = [codeBlock("x\ny"), paragraph("mid"), codeBlock("p\nq")]; + const doc = richSchema.node("doc", null, children); + // Selection starts inside the first code_block, ends at doc end + const state = createMixedState(children, 1, doc.content.size); + const newState = runCommand(state, indentCommand); + expect(newState).not.toBeNull(); + expect(getChildTexts(newState!)).toEqual([" x\n y", "mid", " p\n q"]); + }); + + it("indents the code_block when the selection runs into a paragraph", () => { + // doc: code_block("a\nb") + paragraph("mid") + const children = [codeBlock("a\nb"), paragraph("mid")]; + const doc = richSchema.node("doc", null, children); + const state = createMixedState(children, 1, doc.content.size); + const newState = runCommand(state, indentCommand); + expect(newState).not.toBeNull(); + expect(getChildTexts(newState!)).toEqual([" a\n b", "mid"]); + }); + + it("returns false when the selection overlaps no code_block", () => { + // Selection entirely inside the paragraph + const children = [codeBlock("x\ny"), paragraph("mid"), codeBlock("p\nq")]; + // paragraph content is "mid" at pos 6-8 + const state = createMixedState(children, 6, 9); + let dispatched = false; + const result = indentCommand(state, (_tr) => { + dispatched = true; + }); + expect(result).toBe(false); + expect(dispatched).toBe(false); + expect(getChildTexts(state)).toEqual(["x\ny", "mid", "p\nq"]); + }); +}); + +describe("dedentCommand with multi-block selection (#1399)", () => { + it("dedents every overlapped code_block and leaves prose untouched", () => { + const children = [codeBlock(" x\n y"), paragraph("mid"), codeBlock(" p\n q")]; + const doc = richSchema.node("doc", null, children); + const state = createMixedState(children, 1, doc.content.size); + const newState = runCommand(state, dedentCommand); + expect(newState).not.toBeNull(); + expect(getChildTexts(newState!)).toEqual(["x\ny", "mid", "p\nq"]); + }); + + it("dedents the code_block when the selection runs into a paragraph", () => { + const children = [codeBlock(" a\n b"), paragraph("mid")]; + const doc = richSchema.node("doc", null, children); + const state = createMixedState(children, 1, doc.content.size); + const newState = runCommand(state, dedentCommand); + expect(newState).not.toBeNull(); + expect(getChildTexts(newState!)).toEqual(["a\nb", "mid"]); + }); + + it("returns false when the selection overlaps no code_block", () => { + const children = [codeBlock(" x"), paragraph("mid")]; + const state = createMixedState(children, 6, 9); + let dispatched = false; + const result = dedentCommand(state, (_tr) => { + dispatched = true; + }); + expect(result).toBe(false); + expect(dispatched).toBe(false); + expect(getChildTexts(state)).toEqual([" x", "mid"]); + }); +}); diff --git a/pkgs/id/web/src/indent.ts b/pkgs/id/web/src/indent.ts index c338ca131f..9a4077369f 100644 --- a/pkgs/id/web/src/indent.ts +++ b/pkgs/id/web/src/indent.ts @@ -59,11 +59,50 @@ export function selectedLineStarts(lineStarts: number[], from: number, to: numbe return lineStarts.slice(firstIdx, lastIdx + 1); } +/** + * Every code_block node intersecting [from, to], with its doc position. + * Used to apply indent/dedent line math per block instead of treating a + * multi-block selection as one block's text (#1399). + */ +function codeBlocksInRange(doc: import("prosemirror-model").Node, from: number, to: number): { pos: number }[] { + const blocks: { pos: number }[] = []; + doc.nodesBetween(from, to, (node, pos) => { + if (node.type.name === "code_block") { + blocks.push({ pos }); + return false; + } + return true; + }); + return blocks; +} + +/** + * Line starts (ascending) of one code_block's own text. + * `pos` is the block node's doc position; content runs + * [pos + 1, pos + nodeSize - 1]. + */ +function blockLineStarts( + doc: import("prosemirror-model").Node, + block: import("prosemirror-model").Node, + pos: number, +): { contentStart: number; contentEnd: number; lineStarts: number[] } { + const contentStart = pos + 1; + const contentEnd = pos + block.nodeSize - 1; + const blockText = doc.textBetween(contentStart, contentEnd); + const lineStarts: number[] = [contentStart]; + for (let i = 0; i < blockText.length; i++) { + if (blockText[i] === "\n") { + lineStarts.push(contentStart + i + 1); + } + } + return { contentStart, contentEnd, lineStarts }; +} + /** * Insert indentation at cursor, or indent all selected lines. */ export const indentCommand: Command = (state, dispatch) => { - const { $from, $to, from, to } = state.selection; + const { $from, from, to } = state.selection; // Check if we're in a code_block const inCode = @@ -80,31 +119,31 @@ export const indentCommand: Command = (state, dispatch) => { return true; } - // Multi-line selection: indent each line + // Multi-line selection: indent each overlapped line of every + // intersected code_block (#1399). Non-code content is untouched. + const blocks = codeBlocksInRange(state.doc, from, to); + if (blocks.length === 0) return false; + if (dispatch) { - // Find all line start positions within the selection - let tr = state.tr; - let offset = 0; - - // Start of the block - const blockStart = $from.start($from.depth); - const blockEnd = $to.end($to.depth); - const blockText = state.doc.textBetween(blockStart, blockEnd); - - // Find newline positions to determine line starts - const lineStarts: number[] = [blockStart]; // first line starts at blockStart - for (let i = 0; i < blockText.length; i++) { - if (blockText[i] === "\n") { - lineStarts.push(blockStart + i + 1); + // Collect insert positions against the original doc, then apply in + // descending order so earlier positions stay valid. + const inserts: number[] = []; + for (const { pos } of blocks) { + const block = state.doc.nodeAt(pos); + if (!block) continue; + const { contentStart, contentEnd, lineStarts } = blockLineStarts(state.doc, block, pos); + // Strict overlap: a selection merely touching the block's edge + // covers none of its characters, so the block is skipped. + if (contentStart >= to || contentEnd <= from) continue; + for (const lineStart of selectedLineStarts(lineStarts, Math.max(from, contentStart), Math.min(to, contentEnd))) { + inserts.push(lineStart); } } - // Only indent lines that overlap with the selection - for (const lineStart of selectedLineStarts(lineStarts, from, to)) { - tr = tr.insertText(INDENT, lineStart + offset); - offset += INDENT.length; + let tr = state.tr; + for (const insertPos of inserts.sort((a, b) => b - a)) { + tr = tr.insertText(INDENT, insertPos); } - dispatch(tr); } return true; @@ -114,7 +153,7 @@ export const indentCommand: Command = (state, dispatch) => { * Remove indentation from cursor line, or dedent all selected lines. */ export const dedentCommand: Command = (state, dispatch) => { - const { $from, $to, from, to } = state.selection; + const { $from, from, to } = state.selection; // Check if we're in a code_block const inCode = @@ -124,44 +163,50 @@ export const dedentCommand: Command = (state, dispatch) => { if (!inCode) return false; if (dispatch) { - const blockStart = $from.start($from.depth); - const blockEnd = $to.end($to.depth); - const blockText = state.doc.textBetween(blockStart, blockEnd); - - // Find all line start positions - const lineStarts: number[] = [blockStart]; - for (let i = 0; i < blockText.length; i++) { - if (blockText[i] === "\n") { - lineStarts.push(blockStart + i + 1); - } - } - - let tr = state.tr; - let offset = 0; - - // Handle selected lines (for single cursor, selectedLineStarts returns just the current line) - const linesToDedent = selectedLineStarts(lineStarts, from, to); - - for (const lineStart of linesToDedent) { - const adjustedPos = lineStart + offset; - // Check how many leading spaces this line has - const lineOffset = lineStart - blockStart; - let spacesToRemove = 0; - for (let i = 0; i < INDENT.length && lineOffset + i < blockText.length; i++) { - if (blockText[lineOffset + i] === " ") { - spacesToRemove++; - } else { - break; + const blocks = codeBlocksInRange(state.doc, from, to); + if (blocks.length === 0) return false; + + // Collect deletions against the original doc, then apply in + // descending order so earlier positions stay valid. + const deletions: { pos: number; count: number }[] = []; + for (const { pos } of blocks) { + const block = state.doc.nodeAt(pos); + if (!block) continue; + const { contentStart, contentEnd, lineStarts } = blockLineStarts(state.doc, block, pos); + // Strict overlap: a non-empty selection merely touching the block's + // edge covers none of its characters, so the block is skipped. (An + // empty selection/cursor at the edge still belongs to its line.) + if (from === to ? contentStart > from || contentEnd < from : contentStart >= to || contentEnd <= from) + continue; + const blockText = state.doc.textBetween(contentStart, contentEnd); + + // Handle selected lines (for single cursor, selectedLineStarts returns just the current line) + const linesToDedent = selectedLineStarts(lineStarts, Math.max(from, contentStart), Math.min(to, contentEnd)); + + for (const lineStart of linesToDedent) { + // Check how many leading spaces this line has, using the + // block's own text (#1399) + const lineOffset = lineStart - contentStart; + let spacesToRemove = 0; + for (let i = 0; i < INDENT.length && lineOffset + i < blockText.length; i++) { + if (blockText[lineOffset + i] === " ") { + spacesToRemove++; + } else { + break; + } } - } - if (spacesToRemove > 0) { - tr = tr.delete(adjustedPos, adjustedPos + spacesToRemove); - offset -= spacesToRemove; + if (spacesToRemove > 0) { + deletions.push({ pos: lineStart, count: spacesToRemove }); + } } } - if (offset !== 0) { + if (deletions.length > 0) { + let tr = state.tr; + for (const { pos: deletePos, count } of deletions.sort((a, b) => b.pos - a.pos)) { + tr = tr.delete(deletePos, deletePos + count); + } dispatch(tr); } }