File size: 14,594 Bytes
064bfd6 | 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 | /* eslint-disable custom-rules/no-top-level-side-effects */
import { appendFileSync } from 'fs'
import createReconciler from 'react-reconciler'
import { getYogaCounters } from 'src/native-ts/yoga-layout/index.js'
import { isEnvTruthy } from '../utils/envUtils.js'
import {
appendChildNode,
clearYogaNodeReferences,
createNode,
createTextNode,
type DOMElement,
type DOMNodeAttribute,
type ElementNames,
insertBeforeNode,
markDirty,
removeChildNode,
setAttribute,
setStyle,
setTextNodeValue,
setTextStyles,
type TextNode,
} from './dom.js'
import { Dispatcher } from './events/dispatcher.js'
import { EVENT_HANDLER_PROPS } from './events/event-handlers.js'
import { getFocusManager, getRootNode } from './focus.js'
import { LayoutDisplay } from './layout/node.js'
import applyStyles, { type Styles, type TextStyles } from './styles.js'
// We need to conditionally perform devtools connection to avoid
// accidentally breaking other third-party code.
// See https://github.com/vadimdemedes/ink/issues/384
if (process.env.NODE_ENV === 'development') {
try {
// eslint-disable-next-line custom-rules/no-top-level-dynamic-import -- dev-only; NODE_ENV check is DCE'd in production
void import('./devtools.js')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (error: any) {
if (error.code === 'ERR_MODULE_NOT_FOUND') {
// biome-ignore lint/suspicious/noConsole: intentional warning
console.warn(
`
The environment variable DEV is set to true, so Ink tried to import \`react-devtools-core\`,
but this failed as it was not installed. Debugging with React Devtools requires it.
To install use this command:
$ npm install --save-dev react-devtools-core
`.trim() + '\n',
)
} else {
// eslint-disable-next-line @typescript-eslint/only-throw-error
throw error
}
}
}
// --
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 cleanupYogaNode = (node: DOMElement | TextNode): void => {
const yogaNode = node.yogaNode
if (yogaNode) {
yogaNode.unsetMeasureFunc()
// Clear all references BEFORE freeing to prevent other code from
// accessing freed WASM memory during concurrent operations
clearYogaNodeReferences(node)
yogaNode.freeRecursive()
}
}
// --
type Props = Record<string, unknown>
type HostContext = {
isInsideText: boolean
}
function setEventHandler(node: DOMElement, key: string, value: unknown): void {
if (!node._eventHandlers) {
node._eventHandlers = {}
}
node._eventHandlers[key] = value
}
function applyProp(node: DOMElement, key: string, value: unknown): void {
if (key === 'children') return
if (key === 'style') {
setStyle(node, value as Styles)
if (node.yogaNode) {
applyStyles(node.yogaNode, value as Styles)
}
return
}
if (key === 'textStyles') {
node.textStyles = value as TextStyles
return
}
if (EVENT_HANDLER_PROPS.has(key)) {
setEventHandler(node, key, value)
return
}
setAttribute(node, key, value as DOMNodeAttribute)
}
// --
// react-reconciler's Fiber shape — only the fields we walk. The 5th arg to
// createInstance is the Fiber (`workInProgress` in react-reconciler.dev.js).
// _debugOwner is the component that rendered this element (dev builds only);
// return is the parent fiber (always present). We prefer _debugOwner since it
// skips past Box/Text wrappers to the actual named component.
type FiberLike = {
elementType?: { displayName?: string; name?: string } | string | null
_debugOwner?: FiberLike | null
return?: FiberLike | null
}
export function getOwnerChain(fiber: unknown): string[] {
const chain: string[] = []
const seen = new Set<unknown>()
let cur = fiber as FiberLike | null | undefined
for (let i = 0; cur && i < 50; i++) {
if (seen.has(cur)) break
seen.add(cur)
const t = cur.elementType
const name =
typeof t === 'function'
? (t as { displayName?: string; name?: string }).displayName ||
(t as { displayName?: string; name?: string }).name
: typeof t === 'string'
? undefined // host element (ink-box etc) — skip
: t?.displayName || t?.name
if (name && name !== chain[chain.length - 1]) chain.push(name)
cur = cur._debugOwner ?? cur.return
}
return chain
}
let debugRepaints: boolean | undefined
export function isDebugRepaintsEnabled(): boolean {
if (debugRepaints === undefined) {
debugRepaints = isEnvTruthy(process.env.CLAUDE_CODE_DEBUG_REPAINTS)
}
return debugRepaints
}
export const dispatcher = new Dispatcher()
// --- COMMIT INSTRUMENTATION (temp debugging) ---
// eslint-disable-next-line custom-rules/no-process-env-top-level -- debug instrumentation, read-once is fine
const COMMIT_LOG = process.env.CLAUDE_CODE_COMMIT_LOG
let _commits = 0
let _lastLog = 0
let _lastCommitAt = 0
let _maxGapMs = 0
let _createCount = 0
let _prepareAt = 0
// --- END ---
// --- SCROLL PROFILING (bench/scroll-e2e.sh reads via getLastYogaMs) ---
// Set by onComputeLayout wrapper in ink.tsx; read by onRender for phases.
let _lastYogaMs = 0
let _lastCommitMs = 0
let _commitStart = 0
export function recordYogaMs(ms: number): void {
_lastYogaMs = ms
}
export function getLastYogaMs(): number {
return _lastYogaMs
}
export function markCommitStart(): void {
_commitStart = performance.now()
}
export function getLastCommitMs(): number {
return _lastCommitMs
}
export function resetProfileCounters(): void {
_lastYogaMs = 0
_lastCommitMs = 0
_commitStart = 0
}
// --- END ---
const reconciler = createReconciler<
ElementNames,
Props,
DOMElement,
DOMElement,
TextNode,
DOMElement,
unknown,
unknown,
DOMElement,
HostContext,
null, // UpdatePayload - not used in React 19
NodeJS.Timeout,
-1,
null
>({
getRootHostContext: () => ({ isInsideText: false }),
prepareForCommit: () => {
if (COMMIT_LOG) _prepareAt = performance.now()
return null
},
preparePortalMount: () => null,
clearContainer: () => false,
resetAfterCommit(rootNode) {
_lastCommitMs = _commitStart > 0 ? performance.now() - _commitStart : 0
_commitStart = 0
if (COMMIT_LOG) {
const now = performance.now()
_commits++
const gap = _lastCommitAt > 0 ? now - _lastCommitAt : 0
if (gap > _maxGapMs) _maxGapMs = gap
_lastCommitAt = now
const reconcileMs = _prepareAt > 0 ? now - _prepareAt : 0
if (gap > 30 || reconcileMs > 20 || _createCount > 50) {
// eslint-disable-next-line custom-rules/no-sync-fs -- debug instrumentation
appendFileSync(
COMMIT_LOG,
`${now.toFixed(1)} gap=${gap.toFixed(1)}ms reconcile=${reconcileMs.toFixed(1)}ms creates=${_createCount}\n`,
)
}
_createCount = 0
if (now - _lastLog > 1000) {
// eslint-disable-next-line custom-rules/no-sync-fs -- debug instrumentation
appendFileSync(
COMMIT_LOG,
`${now.toFixed(1)} commits=${_commits}/s maxGap=${_maxGapMs.toFixed(1)}ms\n`,
)
_commits = 0
_maxGapMs = 0
_lastLog = now
}
}
const _t0 = COMMIT_LOG ? performance.now() : 0
if (typeof rootNode.onComputeLayout === 'function') {
rootNode.onComputeLayout()
}
if (COMMIT_LOG) {
const layoutMs = performance.now() - _t0
if (layoutMs > 20) {
const c = getYogaCounters()
// eslint-disable-next-line custom-rules/no-sync-fs -- debug instrumentation
appendFileSync(
COMMIT_LOG,
`${_t0.toFixed(1)} SLOW_YOGA ${layoutMs.toFixed(1)}ms visited=${c.visited} measured=${c.measured} hits=${c.cacheHits} live=${c.live}\n`,
)
}
}
if (process.env.NODE_ENV === 'test') {
if (rootNode.childNodes.length === 0 && rootNode.hasRenderedContent) {
return
}
if (rootNode.childNodes.length > 0) {
rootNode.hasRenderedContent = true
}
rootNode.onImmediateRender?.()
return
}
const _tr = COMMIT_LOG ? performance.now() : 0
rootNode.onRender?.()
if (COMMIT_LOG) {
const renderMs = performance.now() - _tr
if (renderMs > 10) {
// eslint-disable-next-line custom-rules/no-sync-fs -- debug instrumentation
appendFileSync(
COMMIT_LOG,
`${_tr.toFixed(1)} SLOW_PAINT ${renderMs.toFixed(1)}ms\n`,
)
}
}
},
getChildHostContext(
parentHostContext: HostContext,
type: ElementNames,
): HostContext {
const previousIsInsideText = parentHostContext.isInsideText
const isInsideText =
type === 'ink-text' || type === 'ink-virtual-text' || type === 'ink-link'
if (previousIsInsideText === isInsideText) {
return parentHostContext
}
return { isInsideText }
},
shouldSetTextContent: () => false,
createInstance(
originalType: ElementNames,
newProps: Props,
_root: DOMElement,
hostContext: HostContext,
internalHandle?: unknown,
): DOMElement {
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)
if (COMMIT_LOG) _createCount++
for (const [key, value] of Object.entries(newProps)) {
applyProp(node, key, value)
}
if (isDebugRepaintsEnabled()) {
node.debugOwnerChain = getOwnerChain(internalHandle)
}
return node
},
createTextInstance(
text: string,
_root: DOMElement,
hostContext: HostContext,
): TextNode {
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): DOMElement => instance as DOMElement,
hideInstance(node) {
node.isHidden = true
node.yogaNode?.setDisplay(LayoutDisplay.None)
markDirty(node)
},
unhideInstance(node) {
node.isHidden = false
node.yogaNode?.setDisplay(LayoutDisplay.Flex)
markDirty(node)
},
appendInitialChild: appendChildNode,
appendChild: appendChildNode,
insertBefore: insertBeforeNode,
finalizeInitialChildren(
_node: DOMElement,
_type: ElementNames,
props: Props,
): boolean {
return props['autoFocus'] === true
},
commitMount(node: DOMElement): void {
getFocusManager(node).handleAutoFocus(node)
},
isPrimaryRenderer: true,
supportsMutation: true,
supportsPersistence: false,
supportsHydration: false,
scheduleTimeout: setTimeout,
cancelTimeout: clearTimeout,
noTimeout: -1,
getCurrentUpdatePriority: () => dispatcher.currentUpdatePriority,
beforeActiveInstanceBlur() {},
afterActiveInstanceBlur() {},
detachDeletedInstance() {},
getInstanceFromNode: () => null,
prepareScopeUpdate() {},
getInstanceFromScope: () => null,
appendChildToContainer: appendChildNode,
insertInContainerBefore: insertBeforeNode,
removeChildFromContainer(node: DOMElement, removeNode: DOMElement): void {
removeChildNode(node, removeNode)
cleanupYogaNode(removeNode)
getFocusManager(node).handleNodeRemoved(removeNode, node)
},
// React 19 commitUpdate receives old and new props directly instead of an updatePayload
commitUpdate(
node: DOMElement,
_type: ElementNames,
oldProps: Props,
newProps: Props,
): void {
const props = diff(oldProps, newProps)
const style = diff(oldProps['style'] as Styles, newProps['style'] as Styles)
if (props) {
for (const [key, value] of Object.entries(props)) {
if (key === 'style') {
setStyle(node, value as Styles)
continue
}
if (key === 'textStyles') {
setTextStyles(node, value as TextStyles)
continue
}
if (EVENT_HANDLER_PROPS.has(key)) {
setEventHandler(node, key, value)
continue
}
setAttribute(node, key, value as DOMNodeAttribute)
}
}
if (style && node.yogaNode) {
applyStyles(node.yogaNode, style, newProps['style'] as Styles)
}
},
commitTextUpdate(node: TextNode, _oldText: string, newText: string): void {
setTextNodeValue(node, newText)
},
removeChild(node, removeNode) {
removeChildNode(node, removeNode)
cleanupYogaNode(removeNode)
if (removeNode.nodeName !== '#text') {
const root = getRootNode(node)
root.focusManager!.handleNodeRemoved(removeNode, root)
}
},
// React 19 required methods
maySuspendCommit(): boolean {
return false
},
preloadInstance(): boolean {
return true
},
startSuspendingCommit(): void {},
suspendInstance(): void {},
waitForCommitToBeReady(): null {
return null
},
NotPendingTransition: null,
HostTransitionContext: {
$$typeof: Symbol.for('react.context'),
_currentValue: null,
} as never,
setCurrentUpdatePriority(newPriority: number): void {
dispatcher.currentUpdatePriority = newPriority
},
resolveUpdatePriority(): number {
return dispatcher.resolveEventPriority()
},
resetFormInstance(): void {},
requestPostPaintCallback(): void {},
shouldAttemptEagerTransition(): boolean {
return false
},
trackSchedulerEvent(): void {},
resolveEventType(): string | null {
return dispatcher.currentEvent?.type ?? null
},
resolveEventTimeStamp(): number {
return dispatcher.currentEvent?.timeStamp ?? -1.1
},
})
// Wire the reconciler's discreteUpdates into the dispatcher.
// This breaks the import cycle: dispatcher.ts doesn't import reconciler.ts.
dispatcher.discreteUpdates = reconciler.discreteUpdates.bind(reconciler)
export default reconciler
|