forked from vadimdemedes/ink
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreconciler.ts
More file actions
460 lines (402 loc) · 11.5 KB
/
Copy pathreconciler.ts
File metadata and controls
460 lines (402 loc) · 11.5 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
import process from 'node:process';
import createReconciler, {type ReactContext} from 'react-reconciler';
import {
DefaultEventPriority,
NoEventPriority,
} from 'react-reconciler/constants.js';
import * as Scheduler from 'scheduler';
import Yoga from 'yoga-layout';
import {createContext, version as reactVersion} from 'react';
import {
createTextNode,
appendChildNode,
insertBeforeNode,
removeChildNode,
freeYogaSubtree,
emitLayoutListeners,
setStyle,
setTextNodeValue,
createNode,
setAttribute,
type DOMNodeAttribute,
type TextNode,
type ElementNames,
type DOMElement,
} from './dom.js';
import applyStyles, {type Styles} from './styles.js';
import {type OutputTransformer} from './render-node-to-output.js';
// We need to conditionally perform devtools connection to avoid
// accidentally breaking other third-party code.
// See https://github.com/vadimdemedes/ink/issues/384
// See https://github.com/vadimdemedes/ink/issues/648
if (process.env['DEV'] === 'true') {
// Intentionally no warning when the package is missing.
// DEV may be set for other reasons; devtools is opt-in via installing the package.
let isDevtoolsInstalled = false;
try {
import.meta.resolve('react-devtools-core');
isDevtoolsInstalled = true;
} catch {}
if (isDevtoolsInstalled) {
await import('./devtools.js');
}
}
type AnyObject = Record<string, unknown>;
const diff = (before: AnyObject, after: AnyObject): AnyObject | undefined => {
if (before === after) {
return;
}
if (!before) {
return after;
}
const changed: AnyObject = {};
let isChanged = false;
for (const key of Object.keys(before)) {
const isDeleted = after ? !Object.hasOwn(after, key) : true;
if (isDeleted) {
changed[key] = undefined;
isChanged = true;
}
}
if (after) {
for (const key of Object.keys(after)) {
if (after[key] !== before[key]) {
changed[key] = after[key];
isChanged = true;
}
}
}
return isChanged ? changed : undefined;
};
const findRootNode = (node: DOMElement): DOMElement | undefined => {
let current: DOMElement | undefined = node;
while (current) {
if (current.nodeName === 'ink-root') {
return current;
}
current = current.parentNode;
}
return undefined;
};
/**
* Clear the root's cached `staticNode` when the node it points at is being
* removed as part of a larger subtree.
*
* The previous identity check (`staticNode === removeNode`) only caught direct
* removal of the `<Static>` element. When an *ancestor* of `<Static>` is
* removed, the stale `staticNode` reference survives and the next render would
* replay stale static output (and, before `freeYogaSubtree`, trap on freed
* WASM memory — see QwenLM/qwen-code#6820).
*
* The owning root is derived from the host parent passed to the removal hook,
* not a module-level global, so instances with separate stdout streams don't
* clobber each other's pointers.
*/
const clearStaticNodeIfContained = (
rootNode: DOMElement | undefined,
removeNode: DOMElement | TextNode,
): void => {
if (!rootNode?.staticNode) {
return;
}
// Walk up from staticNode to see if removeNode is an ancestor.
let current: DOMElement | undefined = rootNode.staticNode;
while (current) {
if (current === removeNode) {
// Only clear staticNode, not previousStaticNode. The inequality
// (undefined !== previousStaticNode) triggers onStaticChange in
// resetAfterCommit, which resets fullStaticOutput.
rootNode.staticNode = undefined;
return;
}
current = current.parentNode;
}
};
type Props = Record<string, unknown>;
type HostContext = {
isInsideText: boolean;
};
let currentUpdatePriority = NoEventPriority;
async function loadPackageJson() {
const fs = await import('node:fs');
const content = fs.readFileSync(
new URL('../package.json', import.meta.url),
'utf8',
);
const parsedContent = JSON.parse(content) as
| {
name?: string;
version?: string;
}
| undefined;
return {
name: parsedContent?.name,
version: parsedContent?.version,
};
}
let packageInfo = {
name: 'ink',
version: reactVersion,
};
if (process.env['DEV'] === 'true') {
try {
const loaded = await loadPackageJson();
packageInfo = {
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
name: loaded.name || packageInfo.name,
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
version: loaded.version || packageInfo.version,
};
} catch (error) {
console.warn(
'Failed to load package.json in development mode. Falling back to default renderer metadata.',
error,
);
}
}
export default createReconciler<
ElementNames,
Props,
DOMElement,
DOMElement,
TextNode,
DOMElement,
unknown,
unknown,
unknown,
HostContext,
unknown,
unknown,
unknown,
unknown
>({
getRootHostContext: () => ({
isInsideText: false,
}),
prepareForCommit: () => null,
preparePortalMount: () => null,
clearContainer: () => false,
resetAfterCommit(rootNode) {
if (typeof rootNode.onComputeLayout === 'function') {
rootNode.onComputeLayout();
}
emitLayoutListeners(rootNode);
/*
Fire `onStaticChange` BEFORE `onImmediateRender` so ink resets accumulated static output before the new instance emits. Without this, items from a replaced/removed <Static> stay in `fullStaticOutput` and get replayed on rewrites.
*/
if (rootNode.staticNode !== rootNode.previousStaticNode) {
rootNode.previousStaticNode = rootNode.staticNode;
if (typeof rootNode.onStaticChange === 'function') {
rootNode.onStaticChange();
}
}
// Since renders are throttled at the instance level and <Static> component children
// are rendered only once and then get deleted, we need an escape hatch to
// trigger an immediate render to ensure <Static> children are written to output before they get erased
if (rootNode.isStaticDirty) {
rootNode.isStaticDirty = false;
if (typeof rootNode.onImmediateRender === 'function') {
rootNode.onImmediateRender();
}
return;
}
if (typeof rootNode.onRender === 'function') {
rootNode.onRender();
}
},
getChildHostContext(parentHostContext, type) {
const previousIsInsideText = parentHostContext.isInsideText;
const isInsideText = type === 'ink-text' || type === 'ink-virtual-text';
if (previousIsInsideText === isInsideText) {
return parentHostContext;
}
return {isInsideText};
},
shouldSetTextContent: () => false,
createInstance(originalType, newProps, rootNode, hostContext) {
if (hostContext.isInsideText && originalType === 'ink-box') {
throw new Error(`<Box> can’t be nested inside <Text> component`);
}
const type =
originalType === 'ink-text' && hostContext.isInsideText
? 'ink-virtual-text'
: originalType;
const node = createNode(type);
for (const [key, value] of Object.entries(newProps)) {
if (key === 'children') {
continue;
}
if (key === 'style') {
setStyle(node, value as Styles);
if (node.yogaNode) {
applyStyles(node.yogaNode, value as Styles);
}
continue;
}
if (key === 'internal_transform') {
node.internal_transform = value as OutputTransformer;
continue;
}
if (key === 'internal_static') {
node.internal_static = true;
rootNode.isStaticDirty = true;
// Save reference to <Static> node to skip traversal of entire
// node tree to find it
rootNode.staticNode = node;
continue;
}
setAttribute(node, key, value as DOMNodeAttribute);
}
return node;
},
createTextInstance(text, _root, hostContext) {
if (!hostContext.isInsideText) {
throw new Error(
`Text string "${text}" must be rendered inside <Text> component`,
);
}
return createTextNode(text);
},
resetTextContent() {},
hideTextInstance(node) {
setTextNodeValue(node, '');
},
unhideTextInstance(node, text) {
setTextNodeValue(node, text);
},
getPublicInstance: instance => instance,
hideInstance(node) {
node.yogaNode?.setDisplay(Yoga.DISPLAY_NONE);
},
unhideInstance(node) {
node.yogaNode?.setDisplay(Yoga.DISPLAY_FLEX);
},
appendInitialChild: appendChildNode,
appendChild: appendChildNode,
insertBefore: insertBeforeNode,
finalizeInitialChildren() {
return false;
},
isPrimaryRenderer: true,
supportsMutation: true,
supportsPersistence: false,
supportsHydration: false,
// Scheduler integration for concurrent mode
supportsMicrotasks: true,
scheduleMicrotask: queueMicrotask,
// @ts-expect-error @types/react-reconciler is outdated and doesn't include scheduleCallback
scheduleCallback: Scheduler.unstable_scheduleCallback,
cancelCallback: Scheduler.unstable_cancelCallback,
shouldYield: Scheduler.unstable_shouldYield,
now: Scheduler.unstable_now,
scheduleTimeout: setTimeout,
cancelTimeout: clearTimeout,
noTimeout: -1,
beforeActiveInstanceBlur() {},
afterActiveInstanceBlur() {},
detachDeletedInstance() {},
getInstanceFromNode: () => null,
prepareScopeUpdate() {},
getInstanceFromScope: () => null,
appendChildToContainer: appendChildNode,
insertInContainerBefore: insertBeforeNode,
removeChildFromContainer(node, removeNode) {
// `node` is the container, i.e. the root itself. Clear before
// removeChildNode breaks the parent chain.
clearStaticNodeIfContained(findRootNode(node), removeNode);
removeChildNode(node, removeNode);
freeYogaSubtree(removeNode);
},
commitUpdate(node, _type, oldProps, newProps) {
if (node.internal_static) {
const rootNode = findRootNode(node);
if (rootNode) {
rootNode.isStaticDirty = true;
}
}
const props = diff(oldProps, newProps);
const style = diff(
oldProps['style'] as Styles,
newProps['style'] as Styles,
);
if (!props && !style) {
return;
}
if (props) {
for (const [key, value] of Object.entries(props)) {
if (key === 'style') {
setStyle(node, value as Styles);
continue;
}
if (key === 'internal_transform') {
node.internal_transform = value as OutputTransformer;
continue;
}
if (key === 'internal_static') {
node.internal_static = true;
continue;
}
setAttribute(node, key, value as DOMNodeAttribute);
}
}
if (style && node.yogaNode) {
applyStyles(
node.yogaNode,
style,
(newProps['style'] as Styles | undefined) ?? {},
);
}
},
commitTextUpdate(node, _oldText, newText) {
setTextNodeValue(node, newText);
},
removeChild(node, removeNode) {
// `node` is the host parent; its chain up to the root is still intact
// here, so derive the owning root from it rather than a global.
clearStaticNodeIfContained(findRootNode(node), removeNode);
removeChildNode(node, removeNode);
freeYogaSubtree(removeNode);
},
setCurrentUpdatePriority(newPriority: number) {
currentUpdatePriority = newPriority;
},
getCurrentUpdatePriority: () => currentUpdatePriority,
resolveUpdatePriority() {
if (currentUpdatePriority !== NoEventPriority) {
return currentUpdatePriority;
}
return DefaultEventPriority;
},
maySuspendCommit() {
// Return true to enable Suspense resource preloading
return true;
},
// eslint-disable-next-line @typescript-eslint/naming-convention
NotPendingTransition: undefined,
// eslint-disable-next-line @typescript-eslint/naming-convention
HostTransitionContext: createContext(
null,
) as unknown as ReactContext<unknown>,
resetFormInstance() {},
requestPostPaintCallback() {},
shouldAttemptEagerTransition() {
return false;
},
trackSchedulerEvent() {},
resolveEventType() {
return null;
},
resolveEventTimeStamp() {
return -1.1;
},
preloadInstance() {
return true;
},
startSuspendingCommit() {},
suspendInstance() {},
waitForCommitToBeReady() {
return null;
},
rendererPackageName: packageInfo.name,
rendererVersion: packageInfo.version,
});