-
-
Notifications
You must be signed in to change notification settings - Fork 622
/
Copy pathink.tsx
313 lines (259 loc) Β· 7.44 KB
/
ink.tsx
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
import process from 'node:process';
import React, {type ReactNode} from 'react';
import throttle from 'lodash/throttle.js';
import {type DebouncedFunc} from 'lodash';
import ansiEscapes from 'ansi-escapes';
import originalIsCi from 'is-ci';
import autoBind from 'auto-bind';
import signalExit from 'signal-exit';
import patchConsole from 'patch-console';
import {type FiberRoot} from 'react-reconciler';
import reconciler from './reconciler.js';
import render from './renderer.js';
import * as dom from './dom.js';
import logUpdate, {type LogUpdate} from './log-update.js';
import instances from './instances.js';
import App from './components/App.js';
const isCi = process.env['CI'] === 'false' ? false : originalIsCi;
const noop = () => {};
export type Options = {
stdout: NodeJS.WriteStream;
stdin: NodeJS.ReadStream;
stderr: NodeJS.WriteStream;
debug: boolean;
exitOnCtrlC: boolean;
patchConsole: boolean;
waitUntilExit?: () => Promise<void>;
};
export default class Ink {
private readonly options: Options;
private readonly log: LogUpdate;
private readonly throttledLog: LogUpdate | DebouncedFunc<LogUpdate>;
// Ignore last render after unmounting a tree to prevent empty output before exit
private isUnmounted: boolean;
private lastOutput: string;
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 exitPromise?: Promise<void>;
private restoreConsole?: () => void;
private readonly unsubscribeResize?: () => void;
constructor(options: Options) {
autoBind(this);
this.options = options;
this.rootNode = dom.createNode('ink-root');
this.rootNode.onRender = options.debug
? this.onRender
: throttle(this.onRender, 32, {
leading: true,
trailing: true
});
this.rootNode.onImmediateRender = this.onRender;
this.log = logUpdate.create(options.stdout);
this.throttledLog = options.debug
? this.log
: throttle(this.log, undefined, {
leading: true,
trailing: true
});
// Ignore last render after unmounting a tree to prevent empty output before exit
this.isUnmounted = false;
// Store last output to only rerender when needed
this.lastOutput = '';
// 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 = '';
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
this.container = reconciler.createContainer(
this.rootNode,
// Legacy mode
0,
null,
false,
null,
'id',
() => {},
null
);
// Unmount when process exits
this.unsubscribeExit = signalExit(this.unmount, {alwaysLast: false});
if (process.env['DEV'] === 'true') {
reconciler.injectIntoDevTools({
bundleType: 0,
// Reporting React DOM's version, not Ink's
// See https://github.com/facebook/react/issues/16666#issuecomment-532639905
version: '16.13.1',
rendererPackageName: 'ink'
});
}
if (options.patchConsole) {
this.patchConsole();
}
if (!isCi) {
options.stdout.on('resize', this.onRender);
this.unsubscribeResize = () => {
options.stdout.off('resize', this.onRender);
};
}
}
resolveExitPromise: () => void = () => {};
rejectExitPromise: (reason?: Error) => void = () => {};
unsubscribeExit: () => void = () => {};
onRender: () => void = () => {
if (this.isUnmounted) {
return;
}
const {output, outputHeight, staticOutput} = render(
this.rootNode,
// The 'columns' property can be undefined or 0 when not using a TTY.
// In that case we fall back to 80.
this.options.stdout.columns || 80
);
// 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.options.stdout.write(this.fullStaticOutput + output);
return;
}
if (isCi) {
if (hasStaticOutput) {
this.options.stdout.write(staticOutput);
}
this.lastOutput = output;
return;
}
if (hasStaticOutput) {
this.fullStaticOutput += staticOutput;
}
if (outputHeight >= this.options.stdout.rows) {
this.options.stdout.write(
ansiEscapes.clearTerminal + this.fullStaticOutput + output
);
this.lastOutput = output;
return;
}
// To ensure static output is cleanly rendered before main output, clear main output first
if (hasStaticOutput) {
this.log.clear();
this.options.stdout.write(staticOutput);
this.log(output);
}
if (!hasStaticOutput && output !== this.lastOutput) {
this.throttledLog(output);
}
this.lastOutput = output;
};
render(node: ReactNode): void {
const tree = (
<App
stdin={this.options.stdin}
stdout={this.options.stdout}
stderr={this.options.stderr}
writeToStdout={this.writeToStdout}
writeToStderr={this.writeToStderr}
exitOnCtrlC={this.options.exitOnCtrlC}
onExit={this.unmount}
>
{node}
</App>
);
reconciler.updateContainer(tree, this.container, null, noop);
}
writeToStdout(data: string): void {
if (this.isUnmounted) {
return;
}
if (this.options.debug) {
this.options.stdout.write(data + this.fullStaticOutput + this.lastOutput);
return;
}
if (isCi) {
this.options.stdout.write(data);
return;
}
this.log.clear();
this.options.stdout.write(data);
this.log(this.lastOutput);
}
writeToStderr(data: string): void {
if (this.isUnmounted) {
return;
}
if (this.options.debug) {
this.options.stderr.write(data);
this.options.stdout.write(this.fullStaticOutput + this.lastOutput);
return;
}
if (isCi) {
this.options.stderr.write(data);
return;
}
this.log.clear();
this.options.stderr.write(data);
this.log(this.lastOutput);
}
// eslint-disable-next-line @typescript-eslint/ban-types
unmount(error?: Error | number | null): void {
if (this.isUnmounted) {
return;
}
this.onRender();
this.unsubscribeExit();
if (typeof this.restoreConsole === 'function') {
this.restoreConsole();
}
if (typeof this.unsubscribeResize === 'function') {
this.unsubscribeResize();
}
// CIs don't handle erasing ansi escapes well, so it's better to
// only render last frame of non-static output
if (isCi) {
this.options.stdout.write(this.lastOutput + '\n');
} else if (!this.options.debug) {
this.log.done();
}
this.isUnmounted = true;
reconciler.updateContainer(null, this.container, null, noop);
instances.delete(this.options.stdout);
if (error instanceof Error) {
this.rejectExitPromise(error);
} else {
this.resolveExitPromise();
}
}
async waitUntilExit(): Promise<void> {
if (!this.exitPromise) {
this.exitPromise = new Promise((resolve, reject) => {
this.resolveExitPromise = resolve;
this.rejectExitPromise = reject;
});
}
return this.exitPromise;
}
clear(): void {
if (!isCi && !this.options.debug) {
this.log.clear();
}
}
patchConsole(): void {
if (this.options.debug) {
return;
}
this.restoreConsole = patchConsole((stream, data) => {
if (stream === 'stdout') {
this.writeToStdout(data);
}
if (stream === 'stderr') {
const isReactMessage = data.startsWith('The above error occurred');
if (!isReactMessage) {
this.writeToStderr(data);
}
}
});
}
}