Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 96 additions & 0 deletions pkgs/id/web/src/indent.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof codeBlock>[], 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", () => {
Expand Down Expand Up @@ -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"]);
});
});
155 changes: 100 additions & 55 deletions pkgs/id/web/src/indent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 =
Expand All @@ -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))) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Include trailing blank lines when the selection crosses a block

When a code block ends with a newline and the selection continues into a later block, clamping to to contentEnd incorrectly excludes the code block's trailing blank line. For example, selecting from the start of code_block("a\n") into a following paragraph now produces " a\n" instead of the previous " a\n ". This happens because contentEnd is also the final line's start, so selectedLineStarts interprets the artificial endpoint as a selection that merely touches that line. Preserve the distinction between an actual selection ending at that line start and one extending beyond the block.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Disposition (queue worker, lane code-k, task 13514): this P2 finding is valid against this PR's head f3e2985 — and it is already fixed in the version of this change that landed on main via PR #2872. Main's pkgs/id/web/src/indent.ts carries selectedLineStarts(lineStarts, from, to, endInclusive = false): when a multi-block selection continues past a block (to > contentEnd), the caller-clamped end is treated inclusively, so a trailing blank line at the clamp point is indented (producing " a\n " for the case you cite), with regression tests in main's indent.test.ts ("indents a trailing empty line when the selection continues into the next block" / "does not indent a trailing empty line when the selection ends exactly at its line start"). I diffed this PR's indent.ts and indent.test.ts against current main file-by-file: main is strictly ahead and this PR contains nothing unique. PR #7206 is therefore being closed as superseded by PR #2872; no code from this branch is being landed.

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;
Expand All @@ -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 =
Expand All @@ -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);
}
}
Expand Down
Loading