forked from vadimdemedes/ink
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathink.tsx
More file actions
1406 lines (1162 loc) Β· 39.7 KB
/
Copy pathink.tsx
File metadata and controls
1406 lines (1162 loc) Β· 39.7 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 React, {type ReactNode} from 'react';
import {throttle, type DebouncedFunc} from 'es-toolkit/compat';
import ansiEscapes from 'ansi-escapes';
import isInCi from 'is-in-ci';
import autoBind from 'auto-bind';
import signalExit from 'signal-exit';
import patchConsole from 'patch-console';
import {LegacyRoot, ConcurrentRoot} from 'react-reconciler/constants.js';
import {type FiberRoot} from 'react-reconciler';
import Yoga from 'yoga-layout';
import wrapAnsi from 'wrap-ansi';
import {getWindowSize} from './utils.js';
import reconciler from './reconciler.js';
import render from './renderer.js';
import * as dom from './dom.js';
import {hideCursorEscape, showCursorEscape} from './cursor-helpers.js';
import logUpdate, {type LogUpdate, type CursorPosition} from './log-update.js';
import {bsu, esu, shouldSynchronize} from './write-synchronized.js';
import instances from './instances.js';
import {
createFrameController,
type FrameController,
} from './frame-controller.js';
import App from './components/App.js';
import {type TerminalSuspension} from './components/AppContext.js';
import {accessibilityContext as AccessibilityContext} from './components/AccessibilityContext.js';
import {
type KittyKeyboardOptions,
type KittyFlagName,
resolveFlags,
} from './kitty-keyboard.js';
const noop = () => {};
const textEncoder = new TextEncoder();
const yieldImmediate = async () =>
new Promise<void>(resolve => {
setImmediate(resolve);
});
const kittyQueryEscapeByte = 0x1b;
const kittyQueryOpenBracketByte = 0x5b;
const kittyQueryQuestionMarkByte = 0x3f;
const kittyQueryLetterByte = 0x75;
const zeroByte = 0x30;
const nineByte = 0x39;
type KittyQueryResponseMatch =
{state: 'complete'; endIndex: number} | {state: 'partial'};
const isDigitByte = (byte: number): boolean =>
byte >= zeroByte && byte <= nineByte;
const matchKittyQueryResponse = (
buffer: number[],
startIndex: number,
): KittyQueryResponseMatch | undefined => {
if (
buffer[startIndex] !== kittyQueryEscapeByte ||
buffer[startIndex + 1] !== kittyQueryOpenBracketByte ||
buffer[startIndex + 2] !== kittyQueryQuestionMarkByte
) {
return undefined;
}
let index = startIndex + 3;
const digitsStartIndex = index;
while (index < buffer.length && isDigitByte(buffer[index]!)) {
index++;
}
if (index === digitsStartIndex) {
return undefined;
}
if (index === buffer.length) {
return {state: 'partial'};
}
if (buffer[index] === kittyQueryLetterByte) {
return {state: 'complete', endIndex: index};
}
return undefined;
};
const hasCompleteKittyQueryResponse = (buffer: number[]): boolean => {
for (let index = 0; index < buffer.length; index++) {
const match = matchKittyQueryResponse(buffer, index);
if (match?.state === 'complete') {
return true;
}
}
return false;
};
const stripKittyQueryResponsesAndTrailingPartial = (
buffer: number[],
): number[] => {
const keptBytes: number[] = [];
let index = 0;
while (index < buffer.length) {
const match = matchKittyQueryResponse(buffer, index);
if (match?.state === 'complete') {
index = match.endIndex + 1;
continue;
}
if (match?.state === 'partial') {
break;
}
keptBytes.push(buffer[index]!);
index++;
}
return keptBytes;
};
// Windows consoles scroll the buffer when the bottom-right cell is written,
// unlike xterm-like terminals which defer the wrap. That extra scroll
// desynchronizes the incremental erase used for frames that exactly fill the
// viewport, leaving stale copies of previous frames behind (#969). Keep the
// pre-7.0 behavior of fully clearing between fullscreen frames there.
const isWindowsConsole = process.platform === 'win32';
const shouldClearTerminalForFrame = ({
isTty,
viewportRows,
previousOutputHeight,
nextOutputHeight,
isUnmounting,
}: {
isTty: boolean;
viewportRows: number;
previousOutputHeight: number;
nextOutputHeight: number;
isUnmounting: boolean;
}): boolean => {
if (!isTty) {
return false;
}
const hadPreviousFrame = previousOutputHeight > 0;
const wasFullscreen = previousOutputHeight >= viewportRows;
const wasOverflowing = previousOutputHeight > viewportRows;
const isOverflowing = nextOutputHeight > viewportRows;
const isFullscreen = nextOutputHeight >= viewportRows;
const isLeavingFullscreen = wasFullscreen && nextOutputHeight < viewportRows;
const shouldClearOnUnmount = isUnmounting && wasFullscreen;
if (isWindowsConsole && (wasFullscreen || isFullscreen)) {
return true;
}
return (
// Overflowing frames still need full clear fallback.
wasOverflowing ||
(isOverflowing && hadPreviousFrame) ||
// Clear when shrinking from fullscreen to non-fullscreen output.
isLeavingFullscreen ||
// Preserve legacy unmount behavior for fullscreen frames: final teardown
// render should clear once to avoid leaving a scrolled viewport state.
shouldClearOnUnmount
);
};
const isErrorInput = (value: unknown): value is Error => {
return (
value instanceof Error ||
Object.prototype.toString.call(value) === '[object Error]'
);
};
type MaybeWritableStream = NodeJS.WriteStream & {
writable?: boolean;
writableEnded?: boolean;
destroyed?: boolean;
writableLength?: number;
_writableState?: unknown;
};
const getWritableStreamState = (stdout: MaybeWritableStream) => {
const canWriteToStdout =
!stdout.destroyed && !stdout.writableEnded && (stdout.writable ?? true);
const hasWritableState =
stdout._writableState !== undefined || stdout.writableLength !== undefined;
return {
canWriteToStdout,
hasWritableState,
};
};
const settleThrottle = (
throttled: unknown,
canWriteToStdout: boolean,
): void => {
if (
!throttled ||
typeof (throttled as {flush?: unknown}).flush !== 'function'
) {
return;
}
const throttledValue = throttled as {
flush: () => void;
cancel?: () => void;
};
if (canWriteToStdout) {
throttledValue.flush();
} else if (typeof throttledValue.cancel === 'function') {
throttledValue.cancel();
}
};
/**
Performance metrics for a render operation.
*/
export type RenderMetrics = {
/**
Time spent rendering in milliseconds.
*/
renderTime: number;
};
export type Options = {
stdout: NodeJS.WriteStream;
stdin: NodeJS.ReadStream;
stderr: NodeJS.WriteStream;
debug: boolean;
exitOnCtrlC: boolean;
patchConsole: boolean;
onRender?: (metrics: RenderMetrics) => void;
isScreenReaderEnabled?: boolean;
waitUntilExit?: () => Promise<unknown>;
maxFps?: number;
incrementalRendering?: boolean;
/**
Enable React Concurrent Rendering mode.
When enabled:
- Suspense boundaries work correctly with async data
- `useTransition` and `useDeferredValue` are fully functional
- Updates can be interrupted for higher priority work
Note: Concurrent mode changes the timing of renders. Some tests may need to use `act()` to properly await updates. Reusing the same stdout across multiple `render()` calls without unmounting is unsupported. Call `unmount()` first if you need to change the rendering mode or create a fresh instance.
@default false
@experimental
*/
concurrent?: boolean;
kittyKeyboard?: KittyKeyboardOptions;
/**
Override automatic interactive mode detection.
By default, Ink detects whether the environment is interactive based on CI detection (via [`is-in-ci`](https://github.com/sindresorhus/is-in-ci)) and `stdout.isTTY`. Most users should not need to set this.
When non-interactive, Ink disables ANSI erase sequences, cursor manipulation, synchronized output, resize handling, and kitty keyboard auto-detection, writing only the final frame at unmount.
Set to `false` to force non-interactive mode or `true` to force interactive mode when the automatic detection doesn't suit your use case.
Note: Reusing the same stdout across multiple `render()` calls without unmounting is unsupported. Call `unmount()` first if you need to change this option or create a fresh instance.
@default true (false if in CI or `stdout.isTTY` is falsy)
@see {@link RenderOptions.interactive}
*/
interactive?: boolean;
/**
Render the app in the terminal's alternate screen buffer. When enabled, the app renders on a separate screen, and the original terminal content is restored when the app exits. This is the same mechanism used by programs like vim, htop, and less.
Note: The terminal's scrollback buffer is not available while in the alternate screen. This is standard terminal behavior; programs like vim use the alternate screen specifically to avoid polluting the user's scrollback history.
Note: Ink intentionally treats alternate-screen teardown output as disposable. It does not preserve or replay teardown-time frames, hook writes, or `console.*` output after restoring the primary screen.
Only works in interactive mode. Ignored when `interactive` is `false` or in a non-interactive environment (CI, piped stdout).
Note: Reusing the same stdout across multiple `render()` calls without unmounting is unsupported. Call `unmount()` first if you need to change this option or create a fresh instance.
@default false
@see {@link RenderOptions.alternateScreen}
*/
alternateScreen?: boolean;
};
export default class Ink {
/**
Whether this instance is using concurrent rendering mode.
*/
readonly isConcurrent: boolean;
readonly frameController: FrameController;
private readonly options: Options;
private readonly log: LogUpdate;
private cursorPosition: CursorPosition | undefined;
private readonly throttledLog:
LogUpdate | DebouncedFunc<(output: string) => void>;
private readonly isScreenReaderEnabled: boolean;
private readonly interactive: boolean;
private readonly renderThrottleMs: number;
private alternateScreen: boolean;
// Ignore last render after unmounting a tree to prevent empty output before exit
private isUnmounted: boolean;
private isUnmounting: boolean;
private lastOutput: string;
private lastOutputToRender: string;
private lastOutputHeight: number;
private lastTerminalWidth: number;
private readonly container: FiberRoot;
private readonly rootNode: dom.DOMElement;
// This variable is used only in debug mode to store full static output
// so that it's rerendered every time, not just new static parts, like in non-debug mode
private fullStaticOutput: string;
private readonly exitPromise!: Promise<unknown>;
private exitResult: unknown;
private beforeExitHandler?: () => void;
private restoreConsole?: () => void;
private readonly unsubscribeResize?: () => void;
private readonly throttledOnRender?: DebouncedFunc<() => void>;
private hasPendingThrottledRender = false;
private kittyProtocolEnabled = false;
private kittyFlags: KittyFlagName[] | undefined;
private cancelKittyDetection?: () => void;
private nextRenderCommit?: {promise: Promise<void>; resolve: () => void};
// Set while suspendTerminal() has handed the terminal to a child process.
private isSuspended = false;
// Input pause/resume hooks registered by the App component, which owns raw
// mode and bracketed paste state.
private pauseInput?: () => void;
private resumeInput?: () => void;
constructor(options: Options) {
autoBind(this);
this.options = options;
this.rootNode = dom.createNode('ink-root');
this.rootNode.onComputeLayout = this.calculateLayout;
this.isScreenReaderEnabled =
options.isScreenReaderEnabled ??
process.env['INK_SCREEN_READER'] === 'true';
// CI detection takes precedence: even a TTY stdout in CI defaults to non-interactive.
// Using Boolean(isTTY) (rather than an 'in' guard) correctly handles piped streams
// where the property is absent (e.g. `node app.js | cat`).
this.interactive = this.resolveInteractiveOption(options.interactive);
this.alternateScreen = false;
const unthrottled = options.debug || this.isScreenReaderEnabled;
const maxFps = options.maxFps ?? 30;
// Treat non-positive maxFps as an internal fallback case, not a supported
// "disable throttling" mode. Keep animation scheduling on a normal cadence
// so future changes don't accidentally reintroduce zero-delay loops.
const renderThrottleMs =
maxFps > 0 ? Math.max(1, Math.ceil(1000 / maxFps)) : 0;
this.renderThrottleMs = unthrottled ? 0 : renderThrottleMs;
if (unthrottled) {
this.rootNode.onRender = this.onRender;
this.throttledOnRender = undefined;
} else {
const throttled = throttle(this.onRender, renderThrottleMs, {
leading: true,
trailing: true,
});
this.rootNode.onRender = () => {
this.hasPendingThrottledRender = true;
throttled();
};
this.throttledOnRender = throttled;
}
this.rootNode.onImmediateRender = this.onRender;
// Bridge for application-level text selection: setSelection schedules a
// throttled repaint via the same path as a normal render, and each frame
// publishes its composited cells (see onRender).
this.frameController = createFrameController(() => {
this.rootNode.onRender?.();
});
this.rootNode.onStaticChange = this.handleStaticChange;
this.log = logUpdate.create(options.stdout, {
incremental: options.incrementalRendering,
});
this.cursorPosition = undefined;
this.throttledLog = unthrottled
? this.log
: throttle(
(output: string) => {
const shouldWrite = this.log.willRender(output);
const sync = this.shouldSync();
if (sync && shouldWrite) {
this.options.stdout.write(bsu);
}
this.log(output);
if (sync && shouldWrite) {
this.options.stdout.write(esu);
}
},
undefined,
{
leading: true,
trailing: true,
},
);
// Ignore last render after unmounting a tree to prevent empty output before exit
this.isUnmounted = false;
this.isUnmounting = false;
// Store concurrent mode setting
this.isConcurrent = options.concurrent ?? false;
// Store last output to only rerender when needed
this.lastOutput = '';
this.lastOutputToRender = '';
this.lastOutputHeight = 0;
this.lastTerminalWidth = getWindowSize(this.options.stdout).columns;
// This variable is used only in debug mode to store full static output
// so that it's rerendered every time, not just new static parts, like in non-debug mode
this.fullStaticOutput = '';
// Use ConcurrentRoot for concurrent mode, LegacyRoot for legacy mode
const rootTag = options.concurrent ? ConcurrentRoot : LegacyRoot;
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
this.container = reconciler.createContainer(
this.rootNode,
rootTag,
null,
false,
null,
'id',
() => {},
() => {},
() => {},
() => {},
);
// Unmount when process exits
this.unsubscribeExit = signalExit(this.unmount, {alwaysLast: false});
this.setAlternateScreen(Boolean(options.alternateScreen));
if (process.env['DEV'] === 'true') {
// @ts-expect-error outdated types
reconciler.injectIntoDevTools();
}
if (options.patchConsole) {
this.patchConsole();
}
if (this.interactive) {
options.stdout.on('resize', this.resized);
this.unsubscribeResize = () => {
options.stdout.off('resize', this.resized);
};
}
this.initKittyKeyboard();
this.exitPromise = new Promise((resolve, reject) => {
this.resolveExitPromise = resolve;
this.rejectExitPromise = reject;
});
// Prevent global unhandled-rejection crashes when app code exits with an
// error but consumers never call waitUntilExit().
void this.exitPromise.catch(noop);
}
resized = () => {
const currentWidth = getWindowSize(this.options.stdout).columns;
if (currentWidth < this.lastTerminalWidth) {
// We clear the screen when decreasing terminal width to prevent duplicate overlapping re-renders.
this.log.clear();
this.lastOutput = '';
this.lastOutputToRender = '';
}
this.calculateLayout();
dom.emitLayoutListeners(this.rootNode);
this.onRender();
this.lastTerminalWidth = currentWidth;
};
resolveExitPromise: (result?: unknown) => void = () => {};
rejectExitPromise: (reason?: Error) => void = () => {};
unsubscribeExit: () => void = () => {};
handleAppExit = (errorOrResult?: unknown): void => {
if (this.isUnmounted || this.isUnmounting) {
return;
}
if (isErrorInput(errorOrResult)) {
this.unmount(errorOrResult);
return;
}
this.exitResult = errorOrResult;
this.unmount();
};
setCursorPosition = (position: CursorPosition | undefined): void => {
this.cursorPosition = position;
this.log.setCursorPosition(position);
};
restoreLastOutput = (): void => {
if (!this.interactive) {
return;
}
// Clear() resets log-update's cursor state, so replay the latest cursor intent
// before restoring output after external stdout/stderr writes.
this.log.setCursorPosition(this.cursorPosition);
this.log(this.lastOutputToRender || this.lastOutput + '\n');
};
calculateLayout = () => {
const terminalWidth = getWindowSize(this.options.stdout).columns;
this.rootNode.yogaNode!.setWidth(terminalWidth);
this.rootNode.yogaNode!.calculateLayout(
undefined,
undefined,
Yoga.DIRECTION_LTR,
);
};
// Resets `fullStaticOutput` when the <Static> identity changes so stale items from a previous instance are not replayed on future rewrites.
handleStaticChange = (): void => {
this.fullStaticOutput = '';
};
onRender: () => void = () => {
this.hasPendingThrottledRender = false;
if (this.isUnmounted) {
return;
}
// While suspended, the terminal belongs to a child process. Discard queued
// renders; resume() forces a full redraw once Ink reclaims the terminal.
// Resolve any awaited render commit so callers don't hang during suspension.
if (this.isSuspended) {
if (this.nextRenderCommit) {
this.nextRenderCommit.resolve();
this.nextRenderCommit = undefined;
}
return;
}
if (this.nextRenderCommit) {
this.nextRenderCommit.resolve();
this.nextRenderCommit = undefined;
}
const startTime = performance.now();
const selection = this.frameController.getSelection();
const {output, outputHeight, staticOutput, cells, boundaries} = render(
this.rootNode,
this.isScreenReaderEnabled,
selection,
);
if (cells) {
let width = 0;
for (const row of cells) {
width = Math.max(width, row.length);
}
this.frameController.publishFrame({
width,
height: cells.length,
cells,
boundaries: boundaries ?? [],
});
}
this.options.onRender?.({renderTime: performance.now() - startTime});
// If <Static> output isn't empty, it means new children have been added to it
const hasStaticOutput = staticOutput && staticOutput !== '\n';
if (this.options.debug) {
if (hasStaticOutput) {
this.fullStaticOutput += staticOutput;
}
this.lastOutput = output;
this.lastOutputToRender = output;
this.lastOutputHeight = outputHeight;
this.options.stdout.write(this.fullStaticOutput + output);
return;
}
if (!this.interactive) {
if (hasStaticOutput) {
this.options.stdout.write(staticOutput);
}
this.lastOutput = output;
this.lastOutputToRender = output + '\n';
this.lastOutputHeight = outputHeight;
return;
}
if (this.isScreenReaderEnabled) {
const sync = this.shouldSync();
if (sync) {
this.options.stdout.write(bsu);
}
if (hasStaticOutput) {
// We need to erase the main output before writing new static output
const erase =
this.lastOutputHeight > 0
? ansiEscapes.eraseLines(this.lastOutputHeight)
: '';
this.options.stdout.write(erase + staticOutput);
// After erasing, the last output is gone, so we should reset its height
this.lastOutputHeight = 0;
}
if (output === this.lastOutput && !hasStaticOutput) {
if (sync) {
this.options.stdout.write(esu);
}
return;
}
const terminalWidth = getWindowSize(this.options.stdout).columns;
const wrappedOutput = wrapAnsi(output, terminalWidth, {
trim: false,
hard: true,
});
// If we haven't erased yet, do it now.
if (hasStaticOutput) {
this.options.stdout.write(wrappedOutput);
} else {
const erase =
this.lastOutputHeight > 0
? ansiEscapes.eraseLines(this.lastOutputHeight)
: '';
this.options.stdout.write(erase + wrappedOutput);
}
this.lastOutput = output;
this.lastOutputToRender = wrappedOutput;
this.lastOutputHeight =
wrappedOutput === '' ? 0 : wrappedOutput.split('\n').length;
if (sync) {
this.options.stdout.write(esu);
}
return;
}
if (hasStaticOutput) {
this.fullStaticOutput += staticOutput;
}
this.renderInteractiveFrame(
output,
outputHeight,
hasStaticOutput ? staticOutput : '',
);
};
render(node: ReactNode): void {
const tree = (
<AccessibilityContext.Provider
value={{isScreenReaderEnabled: this.isScreenReaderEnabled}}
>
<App
stdin={this.options.stdin}
stdout={this.options.stdout}
stderr={this.options.stderr}
exitOnCtrlC={this.options.exitOnCtrlC}
interactive={this.interactive}
renderThrottleMs={this.renderThrottleMs}
writeToStdout={this.writeToStdout}
writeToStderr={this.writeToStderr}
setCursorPosition={this.setCursorPosition}
onExit={this.handleAppExit}
onWaitUntilRenderFlush={this.waitUntilRenderFlush}
onSuspendTerminal={this.suspendTerminal}
onRegisterInputControl={this.registerInputControl}
>
{node}
</App>
</AccessibilityContext.Provider>
);
if (this.options.concurrent) {
// Concurrent mode: use updateContainer (async scheduling)
reconciler.updateContainer(tree, this.container, null, noop);
} else {
// Legacy mode: use updateContainerSync + flushSyncWork (sync)
reconciler.updateContainerSync(tree, this.container, null, noop);
reconciler.flushSyncWork();
}
}
writeToStdout(data: string): void {
if (this.isUnmounted) {
return;
}
// While suspended, the terminal belongs to a child process. Don't erase or
// repaint Ink's frame around console output; the forced redraw on resume
// restores the screen.
if (this.isSuspended) {
return;
}
if (this.options.debug) {
this.options.stdout.write(data + this.fullStaticOutput + this.lastOutput);
return;
}
if (!this.interactive) {
this.options.stdout.write(data);
return;
}
const sync = this.shouldSync();
if (sync) {
this.options.stdout.write(bsu);
}
this.log.clear();
this.options.stdout.write(data);
this.restoreLastOutput();
if (sync) {
this.options.stdout.write(esu);
}
}
writeToStderr(data: string): void {
if (this.isUnmounted) {
return;
}
// See writeToStdout: stay off the terminal while suspended.
if (this.isSuspended) {
return;
}
if (this.options.debug) {
this.options.stderr.write(data);
this.options.stdout.write(this.fullStaticOutput + this.lastOutput);
return;
}
if (!this.interactive) {
this.options.stderr.write(data);
return;
}
const sync = this.shouldSync();
if (sync) {
this.options.stdout.write(bsu);
}
this.log.clear();
this.options.stderr.write(data);
this.restoreLastOutput();
if (sync) {
this.options.stdout.write(esu);
}
}
// eslint-disable-next-line @typescript-eslint/no-restricted-types
unmount(error?: Error | number | null): void {
if (this.isUnmounted || this.isUnmounting) {
return;
}
this.isUnmounting = true;
if (this.beforeExitHandler) {
process.off('beforeExit', this.beforeExitHandler);
this.beforeExitHandler = undefined;
}
const stdout = this.options.stdout as MaybeWritableStream;
const {canWriteToStdout, hasWritableState} = getWritableStreamState(stdout);
// Clear any pending throttled render timer on unmount. When stdout is writable,
// flush so the final frame is emitted; otherwise cancel to avoid delayed callbacks.
settleThrottle(this.throttledOnRender, canWriteToStdout);
if (canWriteToStdout) {
// If throttling is enabled and there is already a pending render, flushing above
// is sufficient. Also avoid calling onRender() again when static output already
// exists, as that can duplicate <Static> children output on exit (see issue #397).
const shouldRenderFinalFrame =
!this.throttledOnRender ||
(!this.hasPendingThrottledRender && this.fullStaticOutput === '');
if (shouldRenderFinalFrame) {
this.calculateLayout();
this.onRender();
}
}
// Mark as unmounted after the final render but before stdout writes
// that could re-enter exit() via synchronous write callbacks.
this.isUnmounted = true;
this.unsubscribeExit();
// Flush any pending throttled log writes if possible, otherwise cancel to
// prevent delayed callbacks from writing to a closed stream.
settleThrottle(this.throttledLog, canWriteToStdout);
if (typeof this.restoreConsole === 'function') {
// Once unmount starts, Ink stops trying to manage teardown-time
// console output. Restoring the native console before React cleanup keeps
// unmount behavior simple and avoids special-case handling for custom
// streams, fullscreen frames, and alternate-screen teardown.
this.restoreConsole();
}
const finishUnmount = (): void => {
if (typeof this.unsubscribeResize === 'function') {
this.unsubscribeResize();
}
// Cancel any in-progress auto-detection before checking protocol state
if (this.cancelKittyDetection) {
this.cancelKittyDetection();
}
if (canWriteToStdout) {
if (this.kittyProtocolEnabled) {
this.writeBestEffort(this.options.stdout, '\u001B[<u');
}
// Alternate-screen content is disposable by design. We intentionally
// leave it active until React cleanup finishes, then restore the
// primary buffer without replaying prior frames, hook writes, or
// diagnostics onto it. Trying to preserve teardown output across the
// buffer switch adds fragile lifecycle-specific behavior, so Ink keeps
// alternate-screen teardown intentionally simple and best-effort.
if (this.alternateScreen) {
this.writeBestEffort(
this.options.stdout,
ansiEscapes.exitAlternativeScreen,
);
this.writeBestEffort(this.options.stdout, showCursorEscape);
this.alternateScreen = false;
}
if (!this.interactive) {
// Non-interactive environments don't handle erasing ansi escapes well.
// In debug mode, each render already writes to stdout, so only a trailing
// newline is needed. In non-debug mode, write the last frame now (it was
// deferred during rendering).
this.options.stdout.write(
this.options.debug ? '\n' : this.lastOutput + '\n',
);
} else if (!this.options.debug) {
this.log.done();
}
}
this.kittyProtocolEnabled = false;
instances.delete(this.options.stdout);
// Ensure all queued writes have been processed before resolving the
// exit promise. For real writable streams, queue an empty write as a
// barrier β its callback fires only after all prior writes complete.
// For non-stream objects (e.g. test spies), resolve on next tick.
//
// When called from signal-exit during process shutdown (error is a
// number or null rather than undefined/Error), resolve synchronously
// because the event loop is draining and async callbacks won't fire.
const {exitResult} = this;
const resolveOrReject = () => {
if (isErrorInput(error)) {
this.rejectExitPromise(error);
} else {
this.resolveExitPromise(exitResult);
}
};
const isProcessExiting = error !== undefined && !isErrorInput(error);
if (isProcessExiting) {
resolveOrReject();
} else if (canWriteToStdout && hasWritableState) {
this.options.stdout.write('', resolveOrReject);
} else {
setImmediate(resolveOrReject);
}
};
const concurrentReconciler = reconciler as {
flushPassiveEffects?: () => boolean;
};
if (this.options.concurrent) {
reconciler.updateContainerSync(null, this.container, null, noop);
reconciler.flushSyncWork();
concurrentReconciler.flushPassiveEffects?.();
finishUnmount();
} else {
// Legacy mode: use updateContainerSync + flushSyncWork (sync)
reconciler.updateContainerSync(null, this.container, null, noop);
reconciler.flushSyncWork();
finishUnmount();
}
}
async waitUntilExit(): Promise<unknown> {
if (!this.beforeExitHandler) {
this.beforeExitHandler = () => {
this.unmount();
};
process.once('beforeExit', this.beforeExitHandler);
}
return this.exitPromise;
}
async waitUntilRenderFlush(): Promise<void> {
if (this.isUnmounted || this.isUnmounting) {
await this.awaitExit();
return;
}
// Yield to the macrotask queue so that React's scheduler has a chance to
// fire passive effects and process any work they enqueued.
await yieldImmediate();
if (this.isUnmounted || this.isUnmounting) {
await this.awaitExit();
return;
}
// In concurrent mode, React's scheduler may still be mid-render after
// the yield. Wait for the next render commit instead of polling.
if (this.isConcurrent && this.hasPendingConcurrentWork()) {
await Promise.race([this.awaitNextRender(), this.awaitExit()]);
if (this.isUnmounted || this.isUnmounting) {
this.nextRenderCommit = undefined;
await this.awaitExit();
return;
}
}
reconciler.flushSyncWork();
const stdout = this.options.stdout as MaybeWritableStream;
const {canWriteToStdout, hasWritableState} = getWritableStreamState(stdout);
// Flush pending throttled render/log timers so their output is included in this wait.
settleThrottle(this.throttledOnRender, canWriteToStdout);
settleThrottle(this.throttledLog, canWriteToStdout);
if (canWriteToStdout && hasWritableState) {
await new Promise<void>(resolve => {
this.options.stdout.write('', () => {
resolve();