Skip to content
Open
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
5 changes: 5 additions & 0 deletions .changeset/tidy-resized-prompts.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@clack/core": patch
---

Redraw prompts from their reflowed terminal rows after a resize, preserving preceding output.
22 changes: 11 additions & 11 deletions packages/core/src/prompts/prompt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
getRows,
isAccessible,
isActionKey,
reflowedRows,
setRawMode,
settings,
} from '../utils/index.js';
Expand Down Expand Up @@ -49,6 +50,7 @@ export default class Prompt<TValue> {
private _render: (context: Omit<Prompt<TValue>, 'prompt'>) => string | undefined;
private _track = false;
private _prevFrame = '';
private _prevColumns = 0;
private _subscribers = new Map<string, { cb: (...args: any) => any; once?: boolean }[]>();
protected _cursor = 0;

Expand Down Expand Up @@ -322,15 +324,11 @@ export default class Prompt<TValue> {
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,
});
Expand All @@ -339,10 +337,11 @@ export default class Prompt<TValue> {
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);
Expand Down Expand Up @@ -380,7 +379,8 @@ export default class Prompt<TValue> {
}
}

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);
Expand Down
49 changes: 49 additions & 0 deletions packages/core/src/utils/string.ts
Original file line number Diff line number Diff line change
@@ -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;

Expand Down
78 changes: 78 additions & 0 deletions packages/core/test/prompts/prompt-resize.test.ts
Original file line number Diff line number Diff line change
@@ -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;
}
);
Loading