From f0bbf66d356a14aaddae85f631b4ccc10b7c0aee Mon Sep 17 00:00:00 2001 From: vibhor-aggr Date: Wed, 2 Dec 2026 00:33:37 +0530 Subject: [PATCH] fix(core): repaint reflowed prompt rows after a resize --- .changeset/tidy-resized-prompts.md | 5 ++ packages/core/src/prompts/prompt.ts | 22 +++--- packages/core/src/utils/string.ts | 49 ++++++++++++ .../core/test/prompts/prompt-resize.test.ts | 78 +++++++++++++++++++ 4 files changed, 143 insertions(+), 11 deletions(-) create mode 100644 .changeset/tidy-resized-prompts.md create mode 100644 packages/core/test/prompts/prompt-resize.test.ts diff --git a/.changeset/tidy-resized-prompts.md b/.changeset/tidy-resized-prompts.md new file mode 100644 index 00000000..83a93d06 --- /dev/null +++ b/.changeset/tidy-resized-prompts.md @@ -0,0 +1,5 @@ +--- +"@clack/core": patch +--- + +Redraw prompts from their reflowed terminal rows after a resize, preserving preceding output. diff --git a/packages/core/src/prompts/prompt.ts b/packages/core/src/prompts/prompt.ts index 4b45612c..9f5ab643 100644 --- a/packages/core/src/prompts/prompt.ts +++ b/packages/core/src/prompts/prompt.ts @@ -12,6 +12,7 @@ import { getRows, isAccessible, isActionKey, + reflowedRows, setRawMode, settings, } from '../utils/index.js'; @@ -49,6 +50,7 @@ export default class Prompt { private _render: (context: Omit, 'prompt'>) => string | undefined; private _track = false; private _prevFrame = ''; + private _prevColumns = 0; private _subscribers = new Map any; once?: boolean }[]>(); protected _cursor = 0; @@ -322,15 +324,11 @@ export default class Prompt { this.unsubscribe(); } - private restoreCursor() { - const lines = - wrapAnsi(this._prevFrame, getColumns(this.output), { hard: true, trim: false }).split('\n') - .length - 1; - this.output.write(cursor.move(-999, lines * -1)); - } - private render() { - const frame = wrapAnsi(this._render(this) ?? '', getColumns(this.output), { + const columns = getColumns(this.output); + const previousColumns = this._prevColumns; + this._prevColumns = columns; + const frame = wrapAnsi(this._render(this) ?? '', columns, { hard: true, trim: false, }); @@ -339,10 +337,11 @@ export default class Prompt { if (this.state === 'initial') { this.output.write(cursor.hide); } else { - const diff = diffLines(this._prevFrame, frame); + const reflowed = reflowedRows(this._prevFrame, columns, previousColumns); + const diff = reflowed === 0 ? diffLines(this._prevFrame, frame) : undefined; const rows = getRows(this.output); - this.restoreCursor(); if (diff) { + this.output.write(cursor.move(-999, 1 - diff.numLinesBefore)); const diffOffsetAfter = Math.max(0, diff.numLinesAfter - rows); const diffOffsetBefore = Math.max(0, diff.numLinesBefore - rows); let diffLine = diff.lines.find((line) => line >= diffOffsetAfter); @@ -380,7 +379,8 @@ export default class Prompt { } } - this.output.write(erase.down()); + // Clearing the entire viewport can push its old contents into tmux history. + this.output.write(erase.lines(Math.min(rows, reflowed))); } this.output.write(frame); diff --git a/packages/core/src/utils/string.ts b/packages/core/src/utils/string.ts index a2e59b8b..00adbdbe 100644 --- a/packages/core/src/utils/string.ts +++ b/packages/core/src/utils/string.ts @@ -1,3 +1,52 @@ +import { stripVTControlCharacters } from 'node:util'; +import stringWidth from 'fast-string-width'; + +let graphemes: Intl.Segmenter | undefined; + +function expandPrintedTabs(text: string, previousColumns: number) { + // A tab moves the cursor; only a subsequent printed cell makes that gap part of the line. + const chunks = text.replace(/\t+$/, '').split('\t'); + let column = 0; + return chunks + .map((chunk, i) => { + if (i === chunks.length - 1) return chunk; + column += stringWidth(chunk); + const spaces = Math.max(0, Math.min(8 - (column % 8), previousColumns - 1 - column)); + column += spaces; + return chunk + ' '.repeat(spaces); + }) + .join(''); +} + +function extraRowsOnResize(line: string, columns: number, previousColumns: number) { + if (stringWidth(line) <= columns) return 0; + let text = stripVTControlCharacters(line); + if (text.includes('\t')) text = expandPrintedTabs(text, previousColumns); + let cell = 0; + let rows = 0; + graphemes ??= new Intl.Segmenter(); + for (const { segment } of graphemes.segment(text)) { + const width = stringWidth(segment); + if (cell > 0 && cell + width > columns) { + rows++; + cell = 0; + } + cell += width; + } + return rows; +} + +/** Returns zero if the stored line offsets are still valid at the new width. */ +export function reflowedRows(frame: string, columns: number, previousColumns: number) { + if (columns <= 0 || columns >= previousColumns) return 0; + const lines = frame.split('\n'); + const extra = lines.reduce( + (sum, line) => sum + extraRowsOnResize(line, columns, previousColumns), + 0 + ); + return extra === 0 ? 0 : lines.length + extra; +} + export function diffLines(a: string, b: string) { if (a === b) return; diff --git a/packages/core/test/prompts/prompt-resize.test.ts b/packages/core/test/prompts/prompt-resize.test.ts new file mode 100644 index 00000000..aa9111df --- /dev/null +++ b/packages/core/test/prompts/prompt-resize.test.ts @@ -0,0 +1,78 @@ +import { erase } from 'sisteransi'; +import { expect, test } from 'vitest'; +import Prompt from '../../src/prompts/prompt.js'; +import { MockReadable } from '../mock-readable.js'; +import { MockWritable } from '../mock-writable.js'; + +test.each([ + { + before: 'Title\nabcdefghijklmn\nstatus', + after: 'Title\nselected', + rows: 3, + clearRows: 3, + }, + { + before: 'aaaaa bbbbb cccc', + after: 'selected', + rows: 10, + clearRows: 2, + }, + { + before: 'a 👩‍💻👩‍💻aaaa', + after: 'selected', + rows: 10, + clearRows: 2, + }, + { + before: '1234567\u001b[32m界\u001b[39m1234567', + after: 'selected', + rows: 10, + clearRows: 3, + }, + { + before: 'Title\na\tbc\nstatus', + after: 'Title\nselected', + rows: 10, + clearRows: 4, + }, +])('redraws from the reflowed frame: $before', async ({ before, after, rows, clearRows }) => { + const input = new MockReadable(); + const output = Object.assign(new MockWritable(), { columns: 16, rows }); + const prompt = new Prompt({ + input, + output, + render: () => (output.columns === 16 ? before : after), + }); + const result = prompt.prompt(); + output.buffer = []; + + output.columns = 8; + output.emit('resize'); + + expect(output.buffer).toEqual([erase.lines(clearRows), after]); + input.emit('keypress', '\x03', { name: 'c' }); + await result; +}); + +test.each(['Title\nfirst', 'Title\nabcdefg\t\nstatus'])( + 'keeps the line diff when printed cells still fit: %s', + async (before) => { + const input = new MockReadable(); + const output = Object.assign(new MockWritable(), { columns: 16, rows: 10 }); + const prompt = new Prompt({ + input, + output, + render: () => (output.columns === 16 ? before : 'Title\nnext'), + }); + const result = prompt.prompt(); + output.buffer = []; + + output.columns = 8; + output.emit('resize'); + + expect(output.buffer).toContain('next'); + expect(output.buffer.join('')).not.toContain('Title'); + input.emit('keypress', '\x03', { name: 'c' }); + await result; + } +);