-
-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathrender.tsx
More file actions
2207 lines (1819 loc) Β· 52.3 KB
/
Copy pathrender.tsx
File metadata and controls
2207 lines (1819 loc) Β· 52.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import process from 'node:process';
import vm from 'node:vm';
import {spawn as spawnProcess} from 'node:child_process';
import {PassThrough, Writable} from 'node:stream';
import url from 'node:url';
import * as path from 'node:path';
import {createRequire} from 'node:module';
import FakeTimers from '@sinonjs/fake-timers';
import {stub} from 'sinon';
import test, {type ExecutionContext} from 'ava';
import React, {
type ReactElement,
type ReactNode,
PureComponent,
useEffect,
useState,
} from 'react';
import ansiEscapes from 'ansi-escapes';
import stripAnsi from 'strip-ansi';
import boxen from 'boxen';
import delay from 'delay';
import {
render,
Box,
Text,
useApp,
useCursor,
useInput,
type RenderOptions,
type InkOutputStream,
type InkInputStream,
} from '../src/index.js';
import {type RenderMetrics} from '../src/ink.js';
import {bsu, esu} from '../src/write-synchronized.js';
import {createStdin, emitReadable} from './helpers/create-stdin.js';
import createStdout from './helpers/create-stdout.js';
import {reconstructTerminalLines} from './helpers/reconstruct-terminal.js';
const textDecoder = new TextDecoder();
const require = createRequire(import.meta.url);
// eslint-disable-next-line @typescript-eslint/consistent-type-imports
const {spawn} = require('node-pty') as typeof import('node-pty');
const __dirname = url.fileURLToPath(new URL('.', import.meta.url));
const term = (
fixture: string,
args: string[] = [],
options: {rows?: number} = {},
) => {
let resolve: (value?: unknown) => void;
let reject: (error: Error) => void;
const exitPromise = new Promise((resolve2, reject2) => {
resolve = resolve2;
reject = reject2;
});
const env = {
...process.env,
// eslint-disable-next-line @typescript-eslint/naming-convention
NODE_NO_WARNINGS: '1',
};
const ps = spawn(
'node',
[
'--import=tsx',
path.join(__dirname, `./fixtures/${fixture}.tsx`),
...args,
],
{
name: 'xterm-color',
cols: 100,
cwd: __dirname,
env,
...(options.rows === undefined ? {} : {rows: options.rows}),
},
);
const result = {
write(input: string) {
ps.write(input);
},
output: '',
waitForExit: async () => exitPromise,
};
ps.onData(data => {
// Strip Synchronized Update Mode sequences (bsu/esu) so tests
// only see the actual content, not the transport wrapper.
result.output += data
.replaceAll('\u001B[?2026h', '')
.replaceAll('\u001B[?2026l', '');
});
ps.onExit(({exitCode}) => {
if (exitCode === 0) {
resolve();
return;
}
reject(new Error(`Process exited with non-zero exit code: ${exitCode}`));
});
return result;
};
const countOccurrences = (text: string, searchValue: string): number => {
if (searchValue === '') {
return 0;
}
return text.split(searchValue).length - 1;
};
const isWriteBarrierChunk = (chunk: string | Uint8Array): boolean =>
(typeof chunk === 'string' && chunk === '') ||
(chunk instanceof Uint8Array && chunk.length === 0);
const toRenderedChunk = (chunk: string | Uint8Array): string =>
stripAnsi(typeof chunk === 'string' ? chunk : textDecoder.decode(chunk));
const isCursorOrSyncEscape = (chunk: string | Uint8Array): boolean => {
const str = typeof chunk === 'string' ? chunk : textDecoder.decode(chunk);
return str.startsWith('\u001B[?25') || str === bsu || str === esu;
};
const isRenderContent = (chunk: string | Uint8Array): boolean =>
!isWriteBarrierChunk(chunk) && !isCursorOrSyncEscape(chunk);
const getContentWrites = (writeSpy: any): string[] =>
(writeSpy.args as string[][])
.map((args: string[]) => args[0]!)
.filter((w: string) => isRenderContent(w));
const createDelayedWriteCallbackStdout = ({
shouldDelay,
onDelayElapsed,
delayMs = 150,
}: {
readonly shouldDelay: (chunk: string | Uint8Array) => boolean;
readonly onDelayElapsed: () => void;
readonly delayMs?: number;
}): NodeJS.WriteStream => {
let didDelayOnce = false;
const stdout = new Writable({
write(
chunk: string | Uint8Array,
_encoding: BufferEncoding,
callback: (error?: Error) => void,
) {
if (!didDelayOnce && shouldDelay(chunk)) {
didDelayOnce = true;
setTimeout(() => {
onDelayElapsed();
callback();
}, delayMs);
return;
}
callback();
},
}) as unknown as NodeJS.WriteStream;
stdout.columns = 100;
stdout.isTTY = true;
return stdout;
};
type Issue450Fixture =
| 'issue-450-full-height-rerender'
| 'issue-450-full-height-rerender-with-marker'
| 'issue-450-height-minus-one-rerender'
| 'issue-450-full-height-with-static-rerender'
| 'issue-450-initial-overflow'
| 'issue-450-initial-fullscreen'
| 'issue-450-grow-to-fullscreen-rerender'
| 'issue-450-shrink-from-fullscreen-rerender'
| 'issue-450-shrink-from-overflow-rerender'
| 'issue-450-static-shrink-from-fullscreen-rerender'
| 'issue-969-windows-full-height-rerender';
const runIssue450Fixture = async (
fixture: Issue450Fixture,
rows = 6,
): Promise<string> => {
const processResult = term(fixture, [String(rows)]);
await processResult.waitForExit();
return processResult.output;
};
const runNonTtyFixture = async (
fixture: string,
args: string[] = [],
): Promise<string> => {
let output = '';
let errorOutput = '';
const env = {
...process.env,
// eslint-disable-next-line @typescript-eslint/naming-convention
NODE_NO_WARNINGS: '1',
};
// Force non-CI code path while still using a non-TTY stdout stream.
env.CI = 'false';
const fixtureProcess = spawnProcess(
'node',
[
'--import=tsx',
path.join(__dirname, `./fixtures/${fixture}.tsx`),
...args,
],
{
cwd: __dirname,
env,
stdio: ['ignore', 'pipe', 'pipe'],
},
);
fixtureProcess.stdout.on('data', (data: Uint8Array | string) => {
output += typeof data === 'string' ? data : data.toString();
});
fixtureProcess.stderr.on('data', (data: Uint8Array | string) => {
errorOutput += typeof data === 'string' ? data : data.toString();
});
const exitCode = await new Promise<number>((resolve, reject) => {
fixtureProcess.on('error', reject);
fixtureProcess.on('close', code => {
resolve(code ?? 0);
});
});
if (exitCode !== 0) {
throw new Error(
`Non-TTY fixture exited with code ${exitCode}: ${errorOutput}`,
);
}
return output;
};
type Issue450FixtureResult = {
output: string;
clearTerminalCount: number;
eraseLineCount: number;
};
const getIssue450ControlSequenceCounts = (output: string) => ({
clearTerminalCount: countOccurrences(output, ansiEscapes.clearTerminal),
eraseLineCount: countOccurrences(output, ansiEscapes.eraseLines(1)),
});
const runIssue450FixtureWithCounts = async (
fixture: Issue450Fixture,
rows = 6,
): Promise<Issue450FixtureResult> => {
const output = await runIssue450Fixture(fixture, rows);
const {clearTerminalCount, eraseLineCount} =
getIssue450ControlSequenceCounts(output);
return {
output,
clearTerminalCount,
eraseLineCount,
};
};
const getOutputBeforeMarker = (
t: ExecutionContext,
output: string,
marker: string,
): string => {
const markerIndex = output.indexOf(marker);
t.true(markerIndex >= 0, `Fixture marker "${marker}" should be present`);
return markerIndex >= 0 ? output.slice(0, markerIndex) : output;
};
const runIssue450FixtureBeforeMarker = async (
t: ExecutionContext,
fixture: Issue450Fixture,
marker: string,
rows = 6,
): Promise<string> => {
const output = await runIssue450Fixture(fixture, rows);
return getOutputBeforeMarker(t, output, marker);
};
const assertIssue450DynamicFrameOutput = (
t: ExecutionContext,
output: string,
): void => {
t.true(
output.includes('frame 8'),
'Fixture should render multiple dynamic frames',
);
};
class SynchronousErrorBoundary extends PureComponent<
{
onError: (error: Error) => void;
children?: ReactElement;
},
{error?: Error}
> {
static displayName = 'SynchronousErrorBoundary';
static override getDerivedStateFromError(error: Error) {
return {error};
}
override state: {error?: Error} = {
error: undefined,
};
override componentDidCatch(error: Error) {
this.props.onError(error);
}
override render() {
if (this.state.error) {
return null;
}
return this.props.children;
}
}
function SynchronousRenderErrorComponent() {
throw new Error('Synchronous render error');
}
function ThrowingComponentWithBoundary() {
const {exit} = useApp();
return (
<SynchronousErrorBoundary onError={exit}>
<SynchronousRenderErrorComponent />
</SynchronousErrorBoundary>
);
}
test.serial('do not erase screen', async t => {
const ps = term('erase', ['4']);
await ps.waitForExit();
t.false(ps.output.includes(ansiEscapes.clearTerminal));
for (const letter of ['A', 'B', 'C']) {
t.true(ps.output.includes(letter));
}
});
test.serial(
'do not erase screen where <Static> is taller than viewport',
async t => {
const ps = term('erase-with-static', ['4']);
await ps.waitForExit();
t.false(ps.output.includes(ansiEscapes.clearTerminal));
for (const letter of ['A', 'B', 'C', 'D', 'E', 'F']) {
t.true(ps.output.includes(letter));
}
},
);
test.serial(
'last line of <Static> survives a full-clear accounting frame (related to #973)',
async t => {
const rows = 4;
const ps = term('full-clear-static-accounting', [String(rows)], {
rows,
});
await ps.waitForExit();
// The raw stream still contains "F" even when it has been erased on screen,
// so reconstruct the visible buffer (scrollback + viewport) and assert the
// last committed <Static> line is actually still there.
const visibleLines = reconstructTerminalLines(ps.output, rows).filter(
line => line.length > 0,
);
// Positive control: "LIVE-0" only renders on the final live-region update β
// the frame that performs the off-by-one erase. Without this guard, an early
// exit (before that frame) would leave "F" trivially present and the test
// would pass without ever exercising the bug.
t.true(
visibleLines.includes('LIVE-0'),
`Expected the bug-triggering live-region update to have rendered, got ${JSON.stringify(
visibleLines,
)}`,
);
// Distinct-frame guards: if the three phases coalesced into fewer renders,
// the off-by-one would never be planted and the assertions here would pass
// without exercising the bug. Only the inflate frame renders "live-4", and
// its overflow is what first routes a frame through the full clear.
t.true(
ps.output.includes('live-4'),
'Expected the inflate phase to have rendered as its own frame',
);
t.true(
ps.output.includes(ansiEscapes.clearTerminal),
'Expected the overflow to have routed a frame through the full-clear path',
);
// The shrink frame's full clear is the last one; the lowercase "live-0"
// after it proves shrink and nudge rendered as separate frames.
const lastClearIndex = ps.output.lastIndexOf(ansiEscapes.clearTerminal);
t.false(
ps.output.includes('live-4', lastClearIndex),
'Expected the last full clear to be the shrink frame, not the inflate frame',
);
t.true(
ps.output.includes('live-0', lastClearIndex) &&
ps.output.includes('LIVE-0', lastClearIndex),
'Expected the shrink and nudge phases to have rendered as separate frames',
);
t.true(
visibleLines.includes('F'),
`Last static line (F) must remain visible after a live-region update, got ${JSON.stringify(
visibleLines,
)}`,
);
},
);
test.serial('erase screen', async t => {
const ps = term('erase', ['3']);
await ps.waitForExit();
t.true(ps.output.includes(ansiEscapes.clearTerminal));
for (const letter of ['A', 'B', 'C']) {
t.true(ps.output.includes(letter));
}
});
test.serial(
'erase screen where <Static> exists but interactive part is taller than viewport',
async t => {
const ps = term('erase', ['3']);
await ps.waitForExit();
t.true(ps.output.includes(ansiEscapes.clearTerminal));
for (const letter of ['A', 'B', 'C']) {
t.true(ps.output.includes(letter));
}
},
);
test.serial('erase screen where state changes', async t => {
const ps = term('erase-with-state-change', ['4']);
await ps.waitForExit();
// The final frame is between the last eraseLines sequence and cursorShow
// Split on cursorShow to isolate the final rendered content before the cursor is shown
const beforeCursorShow = ps.output.split(ansiEscapes.cursorShow)[0];
if (!beforeCursorShow) {
t.fail('beforeCursorShow is undefined');
return;
}
// Find the last occurrence of an eraseLines sequence
// eraseLines(1) is the minimal erase pattern used by Ink
const eraseLinesPattern = ansiEscapes.eraseLines(1);
const lastEraseIndex = beforeCursorShow.lastIndexOf(eraseLinesPattern);
const lastFrame =
lastEraseIndex === -1
? beforeCursorShow
: beforeCursorShow.slice(lastEraseIndex + eraseLinesPattern.length);
const lastFrameContent = stripAnsi(lastFrame);
for (const letter of ['A', 'B', 'C']) {
t.false(lastFrameContent.includes(letter));
}
});
test.serial('erase screen where state changes in small viewport', async t => {
const ps = term('erase-with-state-change', ['3']);
await ps.waitForExit();
const frames = ps.output.split(ansiEscapes.clearTerminal);
const lastFrame = frames.at(-1);
for (const letter of ['A', 'B', 'C']) {
t.false(lastFrame?.includes(letter));
}
});
test.serial(
'fullscreen mode should not add extra newline at the bottom',
async t => {
const ps = term('fullscreen-no-extra-newline', ['5']);
await ps.waitForExit();
t.true(ps.output.includes('Bottom line'));
const lastFrame = ps.output.split(ansiEscapes.clearTerminal).at(-1) ?? '';
// Check that the bottom line is at the end without extra newlines
// In a 5-line terminal:
// Line 1: Fullscreen: top
// Lines 2-4: empty (from flexGrow)
// Line 5: Bottom line (should be usable)
const lines = lastFrame.split('\n');
t.is(lines.length, 5, 'Should have exactly 5 lines for 5-row terminal');
t.true(
lines[4]?.includes('Bottom line') ?? false,
'Bottom line should be on line 5',
);
},
);
test.serial(
'#442: full terminal-size box should not add an extra scroll line',
async t => {
const rows = 5;
const ps = term('issue-442-full-height', [String(rows)]);
await ps.waitForExit();
const lastFrame = ps.output.split(ansiEscapes.clearTerminal).at(-1) ?? '';
const lastFrameContent = stripAnsi(lastFrame);
const lines = lastFrameContent.split('\n');
t.false(
lastFrameContent.endsWith('\n'),
'Should not end with a trailing newline in fullscreen mode',
);
t.is(
lines.length,
rows,
'Should render exactly terminal row count without an extra line',
);
t.true(lines.at(-1)?.includes('#442 bottom') ?? false);
},
);
test.serial(
'#450: full-height rerenders should not repeatedly clear terminal',
async t => {
const {output, clearTerminalCount, eraseLineCount} =
await runIssue450FixtureWithCounts('issue-450-full-height-rerender');
assertIssue450DynamicFrameOutput(t, output);
t.true(
clearTerminalCount <= 1,
`Expected at most one clearTerminal sequence, received ${clearTerminalCount}`,
);
t.true(
eraseLineCount > 0,
'Expected incremental erase sequences for fullscreen rerenders',
);
},
);
test.serial(
'#969: full-height rerenders on Windows should clear terminal between frames',
async t => {
const output = await runIssue450Fixture(
'issue-969-windows-full-height-rerender',
);
assertIssue450DynamicFrameOutput(t, output);
// Windows consoles scroll when the bottom-right cell is written, which
// breaks incremental erase for fullscreen frames. Each rerender must fall
// back to a full clear there. The fixture process believes it is on
// Windows, so ansi-escapes may emit its legacy clearTerminal variant
// there (the host's os.release() decides), while this process resolves
// the modern one. Count the eraseScreen prefix shared by both variants.
const fullClearCount = countOccurrences(output, ansiEscapes.eraseScreen);
t.true(
fullClearCount >= 2,
`Expected a full clear per fullscreen rerender, received ${fullClearCount}`,
);
},
);
test.serial(
'#450: initial overflowing frame should not clear terminal',
async t => {
const renderedMarker = '__INITIAL_OVERFLOW_FRAME_RENDERED__';
const outputBeforeMarker = await runIssue450FixtureBeforeMarker(
t,
'issue-450-initial-overflow',
renderedMarker,
3,
);
t.false(
outputBeforeMarker.includes(ansiEscapes.clearTerminal),
'Initial overflowing render should not clear terminal',
);
},
);
test.serial(
'#450: initial full-height frame should not clear terminal',
async t => {
const renderedMarker = '__INITIAL_FULLSCREEN_FRAME_RENDERED__';
const outputBeforeMarker = await runIssue450FixtureBeforeMarker(
t,
'issue-450-initial-fullscreen',
renderedMarker,
3,
);
t.false(
outputBeforeMarker.includes(ansiEscapes.clearTerminal),
'Initial full-height render should not clear terminal',
);
},
);
test.serial(
'#450 control: rows - 1 rerenders should avoid clearTerminal',
async t => {
const {output, clearTerminalCount, eraseLineCount} =
await runIssue450FixtureWithCounts('issue-450-height-minus-one-rerender');
assertIssue450DynamicFrameOutput(t, output);
t.is(clearTerminalCount, 0);
t.true(
eraseLineCount > 0,
'Expected incremental erase sequences for non-fullscreen rerenders',
);
},
);
test.serial(
'#450: full-height rerenders should not clear before unmount',
async t => {
const renderedMarker = '__FULL_HEIGHT_RERENDER_COMPLETED__';
const outputBeforeMarker = await runIssue450FixtureBeforeMarker(
t,
'issue-450-full-height-rerender-with-marker',
renderedMarker,
);
const {clearTerminalCount} =
getIssue450ControlSequenceCounts(outputBeforeMarker);
assertIssue450DynamicFrameOutput(t, outputBeforeMarker);
t.is(clearTerminalCount, 0);
},
);
test.serial(
'#450: grow from rows - 1 to full-height should not clear before unmount',
async t => {
const renderedMarker = '__GROW_TO_FULLSCREEN_RERENDER_COMPLETED__';
const outputBeforeMarker = await runIssue450FixtureBeforeMarker(
t,
'issue-450-grow-to-fullscreen-rerender',
renderedMarker,
);
const {clearTerminalCount} =
getIssue450ControlSequenceCounts(outputBeforeMarker);
assertIssue450DynamicFrameOutput(t, outputBeforeMarker);
t.is(clearTerminalCount, 0);
},
);
test.serial(
'#450: shrink from full-height to rows - 1 should clear exactly once',
async t => {
const {output, clearTerminalCount} = await runIssue450FixtureWithCounts(
'issue-450-shrink-from-fullscreen-rerender',
);
assertIssue450DynamicFrameOutput(t, output);
t.is(clearTerminalCount, 1);
},
);
test.serial(
'#450: shrink from overflow to rows - 1 should clear exactly once',
async t => {
const {output, clearTerminalCount} = await runIssue450FixtureWithCounts(
'issue-450-shrink-from-overflow-rerender',
);
assertIssue450DynamicFrameOutput(t, output);
t.is(clearTerminalCount, 1);
},
);
test.serial(
'#450: <Static> with shrink from full-height should clear exactly once',
async t => {
const {output, clearTerminalCount} = await runIssue450FixtureWithCounts(
'issue-450-static-shrink-from-fullscreen-rerender',
);
t.true(output.includes('#450 static line'));
assertIssue450DynamicFrameOutput(t, output);
t.is(clearTerminalCount, 1);
},
);
test.serial(
'#450: non-TTY full-height rerenders should never clear terminal',
t => {
const rows = 6;
const stdout = createStdout();
stdout.rows = rows;
const writes = captureWrites(stdout);
function NonTtyRerenderTestComponent({
frameCount,
}: {
readonly frameCount: number;
}) {
return (
<Box height={rows} flexDirection="column">
<Text>#450 top</Text>
<Box flexGrow={1}>
<Text>{`frame ${frameCount}`}</Text>
</Box>
<Text>#450 bottom</Text>
</Box>
);
}
const {rerender, unmount} = render(
<NonTtyRerenderTestComponent frameCount={0} />,
{stdout},
);
rerender(<NonTtyRerenderTestComponent frameCount={1} />);
rerender(<NonTtyRerenderTestComponent frameCount={2} />);
const {clearTerminalCount} = getIssue450ControlSequenceCounts(
writes.join(''),
);
t.is(clearTerminalCount, 0);
unmount();
},
);
test.serial(
'#450: non-TTY overflow transitions should never clear terminal',
t => {
const rows = 3;
const stdout = createStdout();
stdout.rows = rows;
const writes = captureWrites(stdout);
function NonTtyOverflowTransitionTestComponent({
lineCount,
}: {
readonly lineCount: number;
}) {
const lines = [];
for (let lineNumber = 1; lineNumber <= lineCount; lineNumber++) {
lines.push(<Text key={lineNumber}>{`line ${lineNumber}`}</Text>);
}
return <Box flexDirection="column">{lines}</Box>;
}
const {rerender, unmount} = render(
<NonTtyOverflowTransitionTestComponent lineCount={2} />,
{stdout},
);
rerender(<NonTtyOverflowTransitionTestComponent lineCount={4} />);
const {clearTerminalCount} = getIssue450ControlSequenceCounts(
writes.join(''),
);
t.is(clearTerminalCount, 0);
unmount();
},
);
test.serial(
'#450: viewport shrink into overflow should clear once',
async t => {
const rows = 6;
const stdout = createTtyStdout();
stdout.rows = rows;
const writes = captureWrites(stdout);
function ResizeBoundaryTestComponent() {
return (
<Box height={rows} flexDirection="column">
<Text>#450 top</Text>
<Box flexGrow={1}>
<Text>#450 middle</Text>
</Box>
<Text>#450 bottom</Text>
</Box>
);
}
const {unmount} = render(<ResizeBoundaryTestComponent />, {stdout});
writes.length = 0;
stdout.rows = rows - 1;
stdout.emit('resize');
await delay(0);
const {clearTerminalCount} = getIssue450ControlSequenceCounts(
writes.join(''),
);
t.is(clearTerminalCount, 1);
unmount();
},
);
test.serial(
'#450: non-TTY grow-to-overflow rerender should not clear terminal',
async t => {
const output = await runNonTtyFixture(
'issue-450-grow-to-overflow-rerender',
['3'],
);
t.false(output.includes(ansiEscapes.clearTerminal));
},
);
test.serial('#725: non-TTY child process output is flushed', async t => {
const output = await runNonTtyFixture('issue-725-child-process');
const plainOutput = stripAnsi(output);
t.true(plainOutput.includes('ready-stdin-not-tty'));
t.true(plainOutput.includes('exited'));
});
test.serial('useAnimation can drive non-interactive process exit', async t => {
const output = await runNonTtyFixture('use-animation-non-interactive-exit');
t.true(stripAnsi(output).includes('exited'));
});
test.serial(
'useAnimation can drive explicitly non-interactive process exit',
async t => {
const output = await runNonTtyFixture(
'use-animation-interactive-false-exit',
);
t.true(stripAnsi(output).includes('exited'));
},
);
test.serial(
'#450: full-height rerenders with <Static> should not repeatedly clear terminal',
async t => {
const {output, clearTerminalCount, eraseLineCount} =
await runIssue450FixtureWithCounts(
'issue-450-full-height-with-static-rerender',
);
t.true(
output.includes('#450 static line'),
'Fixture should emit static output',
);
assertIssue450DynamicFrameOutput(t, output);
t.true(
clearTerminalCount <= 1,
`Expected at most one clearTerminal sequence, received ${clearTerminalCount}`,
);
t.true(
eraseLineCount > 0,
'Expected incremental erase sequences for fullscreen rerenders',
);
},
);
test.serial('clear output', async t => {
const ps = term('clear');
await ps.waitForExit();
const secondFrame = ps.output.split(ansiEscapes.eraseLines(4))[1];
for (const letter of ['A', 'B', 'C']) {
t.false(secondFrame?.includes(letter));
}
});
test.serial(
'intercept console methods and display result above output',
async t => {
const ps = term('console');
await ps.waitForExit();
const frames = ps.output.split(ansiEscapes.eraseLines(2)).map(line => {
return stripAnsi(line);
});
t.deepEqual(frames, [
'Hello World\r\n',
'First log\r\nHello World\r\nSecond log\r\n',
]);
},
);
test.serial('rerender on resize', async t => {
const stdout = createStdout(10);
function Test() {
return (
<Box borderStyle="round">
<Text>Test</Text>
</Box>
);
}
const {unmount} = render(<Test />, {stdout});
const contentWrites = getContentWrites(stdout.write);
t.is(
stripAnsi(contentWrites[0]!),
boxen('Test'.padEnd(8), {borderStyle: 'round'}) + '\n',
);
t.is(stdout.listeners('resize').length, 1);
stdout.columns = 8;
stdout.emit('resize');
await delay(100);
const contentWritesAfterResize = getContentWrites(stdout.write);
t.is(
stripAnsi(contentWritesAfterResize.at(-1)!),
boxen('Test'.padEnd(6), {borderStyle: 'round'}) + '\n',
);
unmount();
t.is(stdout.listeners('resize').length, 0);
});
function ThrottleTestComponent({text}: {readonly text: string}) {
return <Text>{text}</Text>;
}
function ThrottleCursorTestComponent({text}: {readonly text: string}) {
const {setCursorPosition} = useCursor();
setCursorPosition({x: 0, y: 0});
return <Text>{text}</Text>;
}
test.serial('throttle renders to maxFps', t => {
const clock = FakeTimers.install(); // Controls timers + Date.now()
try {
const stdout = createStdout();
const {unmount, rerender} = render(<ThrottleTestComponent text="Hello" />, {
stdout,
maxFps: 1, // 1 Hz => ~1000 ms window
});
// Initial render (leading call)
t.is(getContentWrites(stdout.write).length, 1);
t.is(stripAnsi(getContentWrites(stdout.write)[0]!), 'Hello\n');
// Trigger another render inside the throttle window
rerender(<ThrottleTestComponent text="World" />);
t.is(getContentWrites(stdout.write).length, 1);
// Advance 999 ms: still within window, no trailing call yet
clock.tick(999);
t.is(getContentWrites(stdout.write).length, 1);
// Cross the boundary: trailing render fires once
clock.tick(1);
t.is(getContentWrites(stdout.write).length, 2);
t.is(stripAnsi(getContentWrites(stdout.write)[1]!), 'World\n');
unmount();
} finally {
clock.uninstall();
}
});
test.serial('outputs renderTime when onRender is passed', async t => {
const renderTimes: number[] = [];
const funcObj = {
onRender(metrics: RenderMetrics) {
const {renderTime} = metrics;
renderTimes.push(renderTime);
},
};