forked from ultraworkers/claw-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
2578 lines (2429 loc) · 81.4 KB
/
Copy pathindex.ts
File metadata and controls
2578 lines (2429 loc) · 81.4 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
/**
* Pure-TypeScript port of yoga-layout (Meta's flexbox engine).
*
* This matches the `yoga-layout/load` API surface used by src/ink/layout/yoga.ts.
* The upstream C++ source is ~2500 lines in CalculateLayout.cpp alone; this port
* is a simplified single-pass flexbox implementation that covers the subset of
* features Ink actually uses:
* - flex-direction (row/column + reverse)
* - flex-grow / flex-shrink / flex-basis
* - align-items / align-self (stretch, flex-start, center, flex-end)
* - justify-content (all six values)
* - margin / padding / border / gap
* - width / height / min / max (point, percent, auto)
* - position: relative / absolute
* - display: flex / none
* - measure functions (for text nodes)
*
* Also implemented for spec parity (not used by Ink):
* - margin: auto (main + cross axis, overrides justify/align)
* - multi-pass flex clamping when children hit min/max constraints
* - flex-grow/shrink against container min/max when size is indefinite
*
* Also implemented for spec parity (not used by Ink):
* - flex-wrap: wrap / wrap-reverse (multi-line flex)
* - align-content (positions wrapped lines on cross axis)
*
* Also implemented for spec parity (not used by Ink):
* - display: contents (children lifted to grandparent, box removed)
*
* Also implemented for spec parity (not used by Ink):
* - baseline alignment (align-items/align-self: baseline)
*
* Not implemented (not used by Ink):
* - aspect-ratio
* - box-sizing: content-box
* - RTL direction (Ink always passes Direction.LTR)
*
* Upstream: https://github.com/facebook/yoga
*/
import {
Align,
BoxSizing,
Dimension,
Direction,
Display,
Edge,
Errata,
ExperimentalFeature,
FlexDirection,
Gutter,
Justify,
MeasureMode,
Overflow,
PositionType,
Unit,
Wrap,
} from './enums.js'
export {
Align,
BoxSizing,
Dimension,
Direction,
Display,
Edge,
Errata,
ExperimentalFeature,
FlexDirection,
Gutter,
Justify,
MeasureMode,
Overflow,
PositionType,
Unit,
Wrap,
}
// --
// Value types
export type Value = {
unit: Unit
value: number
}
const UNDEFINED_VALUE: Value = { unit: Unit.Undefined, value: NaN }
const AUTO_VALUE: Value = { unit: Unit.Auto, value: NaN }
function pointValue(v: number): Value {
return { unit: Unit.Point, value: v }
}
function percentValue(v: number): Value {
return { unit: Unit.Percent, value: v }
}
function resolveValue(v: Value, ownerSize: number): number {
switch (v.unit) {
case Unit.Point:
return v.value
case Unit.Percent:
return isNaN(ownerSize) ? NaN : (v.value * ownerSize) / 100
default:
return NaN
}
}
function isDefined(n: number): boolean {
return !isNaN(n)
}
// NaN-safe equality for layout-cache input comparison
function sameFloat(a: number, b: number): boolean {
return a === b || (a !== a && b !== b)
}
// --
// Layout result (computed values)
type Layout = {
left: number
top: number
width: number
height: number
// Computed per-edge values (resolved to physical edges)
border: [number, number, number, number] // left, top, right, bottom
padding: [number, number, number, number]
margin: [number, number, number, number]
}
// --
// Style (input values)
type Style = {
direction: Direction
flexDirection: FlexDirection
justifyContent: Justify
alignItems: Align
alignSelf: Align
alignContent: Align
flexWrap: Wrap
overflow: Overflow
display: Display
positionType: PositionType
flexGrow: number
flexShrink: number
flexBasis: Value
// 9-edge arrays indexed by Edge enum
margin: Value[]
padding: Value[]
border: Value[]
position: Value[]
// 3-gutter array indexed by Gutter enum
gap: Value[]
width: Value
height: Value
minWidth: Value
minHeight: Value
maxWidth: Value
maxHeight: Value
}
function defaultStyle(): Style {
return {
direction: Direction.Inherit,
flexDirection: FlexDirection.Column,
justifyContent: Justify.FlexStart,
alignItems: Align.Stretch,
alignSelf: Align.Auto,
alignContent: Align.FlexStart,
flexWrap: Wrap.NoWrap,
overflow: Overflow.Visible,
display: Display.Flex,
positionType: PositionType.Relative,
flexGrow: 0,
flexShrink: 0,
flexBasis: AUTO_VALUE,
margin: new Array(9).fill(UNDEFINED_VALUE),
padding: new Array(9).fill(UNDEFINED_VALUE),
border: new Array(9).fill(UNDEFINED_VALUE),
position: new Array(9).fill(UNDEFINED_VALUE),
gap: new Array(3).fill(UNDEFINED_VALUE),
width: AUTO_VALUE,
height: AUTO_VALUE,
minWidth: UNDEFINED_VALUE,
minHeight: UNDEFINED_VALUE,
maxWidth: UNDEFINED_VALUE,
maxHeight: UNDEFINED_VALUE,
}
}
// --
// Edge resolution — yoga's 9-edge model collapsed to 4 physical edges
const EDGE_LEFT = 0
const EDGE_TOP = 1
const EDGE_RIGHT = 2
const EDGE_BOTTOM = 3
function resolveEdge(
edges: Value[],
physicalEdge: number,
ownerSize: number,
// For margin/position we allow auto; for padding/border auto resolves to 0
allowAuto = false,
): number {
// Precedence: specific edge > horizontal/vertical > all
let v = edges[physicalEdge]!
if (v.unit === Unit.Undefined) {
if (physicalEdge === EDGE_LEFT || physicalEdge === EDGE_RIGHT) {
v = edges[Edge.Horizontal]!
} else {
v = edges[Edge.Vertical]!
}
}
if (v.unit === Unit.Undefined) {
v = edges[Edge.All]!
}
// Start/End map to Left/Right for LTR (Ink is always LTR)
if (v.unit === Unit.Undefined) {
if (physicalEdge === EDGE_LEFT) v = edges[Edge.Start]!
if (physicalEdge === EDGE_RIGHT) v = edges[Edge.End]!
}
if (v.unit === Unit.Undefined) return 0
if (v.unit === Unit.Auto) return allowAuto ? NaN : 0
return resolveValue(v, ownerSize)
}
function resolveEdgeRaw(edges: Value[], physicalEdge: number): Value {
let v = edges[physicalEdge]!
if (v.unit === Unit.Undefined) {
if (physicalEdge === EDGE_LEFT || physicalEdge === EDGE_RIGHT) {
v = edges[Edge.Horizontal]!
} else {
v = edges[Edge.Vertical]!
}
}
if (v.unit === Unit.Undefined) v = edges[Edge.All]!
if (v.unit === Unit.Undefined) {
if (physicalEdge === EDGE_LEFT) v = edges[Edge.Start]!
if (physicalEdge === EDGE_RIGHT) v = edges[Edge.End]!
}
return v
}
function isMarginAuto(edges: Value[], physicalEdge: number): boolean {
return resolveEdgeRaw(edges, physicalEdge).unit === Unit.Auto
}
// Setter helpers for the _hasAutoMargin / _hasPosition fast-path flags.
// Unit.Undefined = 0, Unit.Auto = 3.
function hasAnyAutoEdge(edges: Value[]): boolean {
for (let i = 0; i < 9; i++) if (edges[i]!.unit === 3) return true
return false
}
function hasAnyDefinedEdge(edges: Value[]): boolean {
for (let i = 0; i < 9; i++) if (edges[i]!.unit !== 0) return true
return false
}
// Hot path: resolve all 4 physical edges in one pass, writing into `out`.
// Equivalent to calling resolveEdge() 4× with allowAuto=false, but hoists the
// shared fallback lookups (Horizontal/Vertical/All/Start/End) and avoids
// allocating a fresh 4-array on every layoutNode() call.
function resolveEdges4Into(
edges: Value[],
ownerSize: number,
out: [number, number, number, number],
): void {
// Hoist fallbacks once — the 4 per-edge chains share these reads.
const eH = edges[6]! // Edge.Horizontal
const eV = edges[7]! // Edge.Vertical
const eA = edges[8]! // Edge.All
const eS = edges[4]! // Edge.Start
const eE = edges[5]! // Edge.End
const pctDenom = isNaN(ownerSize) ? NaN : ownerSize / 100
// Left: edges[0] → Horizontal → All → Start
let v = edges[0]!
if (v.unit === 0) v = eH
if (v.unit === 0) v = eA
if (v.unit === 0) v = eS
out[0] = v.unit === 1 ? v.value : v.unit === 2 ? v.value * pctDenom : 0
// Top: edges[1] → Vertical → All
v = edges[1]!
if (v.unit === 0) v = eV
if (v.unit === 0) v = eA
out[1] = v.unit === 1 ? v.value : v.unit === 2 ? v.value * pctDenom : 0
// Right: edges[2] → Horizontal → All → End
v = edges[2]!
if (v.unit === 0) v = eH
if (v.unit === 0) v = eA
if (v.unit === 0) v = eE
out[2] = v.unit === 1 ? v.value : v.unit === 2 ? v.value * pctDenom : 0
// Bottom: edges[3] → Vertical → All
v = edges[3]!
if (v.unit === 0) v = eV
if (v.unit === 0) v = eA
out[3] = v.unit === 1 ? v.value : v.unit === 2 ? v.value * pctDenom : 0
}
// --
// Axis helpers
function isRow(dir: FlexDirection): boolean {
return dir === FlexDirection.Row || dir === FlexDirection.RowReverse
}
function isReverse(dir: FlexDirection): boolean {
return dir === FlexDirection.RowReverse || dir === FlexDirection.ColumnReverse
}
function crossAxis(dir: FlexDirection): FlexDirection {
return isRow(dir) ? FlexDirection.Column : FlexDirection.Row
}
function leadingEdge(dir: FlexDirection): number {
switch (dir) {
case FlexDirection.Row:
return EDGE_LEFT
case FlexDirection.RowReverse:
return EDGE_RIGHT
case FlexDirection.Column:
return EDGE_TOP
case FlexDirection.ColumnReverse:
return EDGE_BOTTOM
}
}
function trailingEdge(dir: FlexDirection): number {
switch (dir) {
case FlexDirection.Row:
return EDGE_RIGHT
case FlexDirection.RowReverse:
return EDGE_LEFT
case FlexDirection.Column:
return EDGE_BOTTOM
case FlexDirection.ColumnReverse:
return EDGE_TOP
}
}
// --
// Public types
export type MeasureFunction = (
width: number,
widthMode: MeasureMode,
height: number,
heightMode: MeasureMode,
) => { width: number; height: number }
export type Size = { width: number; height: number }
// --
// Config
export type Config = {
pointScaleFactor: number
errata: Errata
useWebDefaults: boolean
free(): void
isExperimentalFeatureEnabled(_: ExperimentalFeature): boolean
setExperimentalFeatureEnabled(_: ExperimentalFeature, __: boolean): void
setPointScaleFactor(factor: number): void
getErrata(): Errata
setErrata(errata: Errata): void
setUseWebDefaults(v: boolean): void
}
function createConfig(): Config {
const config: Config = {
pointScaleFactor: 1,
errata: Errata.None,
useWebDefaults: false,
free() {},
isExperimentalFeatureEnabled() {
return false
},
setExperimentalFeatureEnabled() {},
setPointScaleFactor(f) {
config.pointScaleFactor = f
},
getErrata() {
return config.errata
},
setErrata(e) {
config.errata = e
},
setUseWebDefaults(v) {
config.useWebDefaults = v
},
}
return config
}
// --
// Node implementation
export class Node {
style: Style
layout: Layout
parent: Node | null
children: Node[]
measureFunc: MeasureFunction | null
config: Config
isDirty_: boolean
isReferenceBaseline_: boolean
// Per-layout scratch (not public API)
_flexBasis = 0
_mainSize = 0
_crossSize = 0
_lineIndex = 0
// Fast-path flags maintained by style setters. Per CPU profile, the
// positioning loop calls isMarginAuto 6× and resolveEdgeRaw(position) 4×
// per child per layout pass — ~11k calls for the 1000-node bench, nearly
// all of which return false/undefined since most nodes have no auto
// margins and no position insets. These flags let us skip straight to
// the common case with a single branch.
_hasAutoMargin = false
_hasPosition = false
// Same pattern for the 3× resolveEdges4Into calls at the top of every
// layoutNode(). In the 1000-node bench ~67% of those calls operate on
// all-undefined edge arrays (most nodes have no border; only cols have
// padding; only leaf cells have margin) — a single-branch skip beats
// ~20 property reads + ~15 compares + 4 writes of zeros.
_hasPadding = false
_hasBorder = false
_hasMargin = false
// -- Dirty-flag layout cache. Mirrors upstream CalculateLayout.cpp's
// layoutNodeInternal: skip a subtree entirely when it's clean and we're
// asking the same question we cached the answer to. Two slots since
// each node typically sees a measure call (performLayout=false, from
// computeFlexBasis) followed by a layout call (performLayout=true) with
// different inputs per parent pass — a single slot thrashes. Re-layout
// bench (dirty one leaf, recompute root) went 2.7x→1.1x with this:
// clean siblings skip straight through, only the dirty chain recomputes.
_lW = NaN
_lH = NaN
_lWM: MeasureMode = 0
_lHM: MeasureMode = 0
_lOW = NaN
_lOH = NaN
_lFW = false
_lFH = false
// _hasL stores INPUTS early (before compute) but layout.width/height are
// mutated by the multi-entry cache and by subsequent compute calls with
// different inputs. Without storing OUTPUTS, a _hasL hit returns whatever
// layout.width/height happened to be left by the last call — the scrollbox
// vpH=33→2624 bug. Store + restore outputs like the multi-entry cache does.
_lOutW = NaN
_lOutH = NaN
_hasL = false
_mW = NaN
_mH = NaN
_mWM: MeasureMode = 0
_mHM: MeasureMode = 0
_mOW = NaN
_mOH = NaN
_mOutW = NaN
_mOutH = NaN
_hasM = false
// Cached computeFlexBasis result. For clean children, basis only depends
// on the container's inner dimensions — if those haven't changed, skip the
// layoutNode(performLayout=false) recursion entirely. This is the hot path
// for scroll: 500-message content container is dirty, its 499 clean
// children each get measured ~20× as the dirty chain's measure/layout
// passes cascade. Basis cache short-circuits at the child boundary.
_fbBasis = NaN
_fbOwnerW = NaN
_fbOwnerH = NaN
_fbAvailMain = NaN
_fbAvailCross = NaN
_fbCrossMode: MeasureMode = 0
// Generation at which _fbBasis was written. Dirty nodes from a PREVIOUS
// generation have stale cache (subtree changed), but within the SAME
// generation the cache is fresh — the dirty chain's measure→layout
// cascade invokes computeFlexBasis ≥2^depth times per calculateLayout on
// fresh-mounted items, and the subtree doesn't change between calls.
// Gating on generation instead of isDirty_ lets fresh mounts (virtual
// scroll) cache-hit after first compute: 105k visits → ~10k.
_fbGen = -1
// Multi-entry layout cache — stores (inputs → computed w,h) so hits with
// different inputs than _hasL can restore the right dimensions. Upstream
// yoga uses 16; 4 covers Ink's dirty-chain depth. Packed as flat arrays
// to avoid per-entry object allocs. Slot i uses indices [i*8, i*8+8) in
// _cIn (aW,aH,wM,hM,oW,oH,fW,fH) and [i*2, i*2+2) in _cOut (w,h).
_cIn: Float64Array | null = null
_cOut: Float64Array | null = null
_cGen = -1
_cN = 0
_cWr = 0
constructor(config?: Config) {
this.style = defaultStyle()
this.layout = {
left: 0,
top: 0,
width: 0,
height: 0,
border: [0, 0, 0, 0],
padding: [0, 0, 0, 0],
margin: [0, 0, 0, 0],
}
this.parent = null
this.children = []
this.measureFunc = null
this.config = config ?? DEFAULT_CONFIG
this.isDirty_ = true
this.isReferenceBaseline_ = false
_yogaLiveNodes++
}
// -- Tree
insertChild(child: Node, index: number): void {
child.parent = this
this.children.splice(index, 0, child)
this.markDirty()
}
removeChild(child: Node): void {
const idx = this.children.indexOf(child)
if (idx >= 0) {
this.children.splice(idx, 1)
child.parent = null
this.markDirty()
}
}
getChild(index: number): Node {
return this.children[index]!
}
getChildCount(): number {
return this.children.length
}
getParent(): Node | null {
return this.parent
}
// -- Lifecycle
free(): void {
this.parent = null
this.children = []
this.measureFunc = null
this._cIn = null
this._cOut = null
_yogaLiveNodes--
}
freeRecursive(): void {
for (const c of this.children) c.freeRecursive()
this.free()
}
reset(): void {
this.style = defaultStyle()
this.children = []
this.parent = null
this.measureFunc = null
this.isDirty_ = true
this._hasAutoMargin = false
this._hasPosition = false
this._hasPadding = false
this._hasBorder = false
this._hasMargin = false
this._hasL = false
this._hasM = false
this._cN = 0
this._cWr = 0
this._fbBasis = NaN
}
// -- Dirty tracking
markDirty(): void {
this.isDirty_ = true
if (this.parent && !this.parent.isDirty_) this.parent.markDirty()
}
isDirty(): boolean {
return this.isDirty_
}
hasNewLayout(): boolean {
return true
}
markLayoutSeen(): void {}
// -- Measure function
setMeasureFunc(fn: MeasureFunction | null): void {
this.measureFunc = fn
this.markDirty()
}
unsetMeasureFunc(): void {
this.measureFunc = null
this.markDirty()
}
// -- Computed layout getters
getComputedLeft(): number {
return this.layout.left
}
getComputedTop(): number {
return this.layout.top
}
getComputedWidth(): number {
return this.layout.width
}
getComputedHeight(): number {
return this.layout.height
}
getComputedRight(): number {
const p = this.parent
return p ? p.layout.width - this.layout.left - this.layout.width : 0
}
getComputedBottom(): number {
const p = this.parent
return p ? p.layout.height - this.layout.top - this.layout.height : 0
}
getComputedLayout(): {
left: number
top: number
right: number
bottom: number
width: number
height: number
} {
return {
left: this.layout.left,
top: this.layout.top,
right: this.getComputedRight(),
bottom: this.getComputedBottom(),
width: this.layout.width,
height: this.layout.height,
}
}
getComputedBorder(edge: Edge): number {
return this.layout.border[physicalEdge(edge)]!
}
getComputedPadding(edge: Edge): number {
return this.layout.padding[physicalEdge(edge)]!
}
getComputedMargin(edge: Edge): number {
return this.layout.margin[physicalEdge(edge)]!
}
// -- Style setters: dimensions
setWidth(v: number | 'auto' | string | undefined): void {
this.style.width = parseDimension(v)
this.markDirty()
}
setWidthPercent(v: number): void {
this.style.width = percentValue(v)
this.markDirty()
}
setWidthAuto(): void {
this.style.width = AUTO_VALUE
this.markDirty()
}
setHeight(v: number | 'auto' | string | undefined): void {
this.style.height = parseDimension(v)
this.markDirty()
}
setHeightPercent(v: number): void {
this.style.height = percentValue(v)
this.markDirty()
}
setHeightAuto(): void {
this.style.height = AUTO_VALUE
this.markDirty()
}
setMinWidth(v: number | string | undefined): void {
this.style.minWidth = parseDimension(v)
this.markDirty()
}
setMinWidthPercent(v: number): void {
this.style.minWidth = percentValue(v)
this.markDirty()
}
setMinHeight(v: number | string | undefined): void {
this.style.minHeight = parseDimension(v)
this.markDirty()
}
setMinHeightPercent(v: number): void {
this.style.minHeight = percentValue(v)
this.markDirty()
}
setMaxWidth(v: number | string | undefined): void {
this.style.maxWidth = parseDimension(v)
this.markDirty()
}
setMaxWidthPercent(v: number): void {
this.style.maxWidth = percentValue(v)
this.markDirty()
}
setMaxHeight(v: number | string | undefined): void {
this.style.maxHeight = parseDimension(v)
this.markDirty()
}
setMaxHeightPercent(v: number): void {
this.style.maxHeight = percentValue(v)
this.markDirty()
}
// -- Style setters: flex
setFlexDirection(dir: FlexDirection): void {
this.style.flexDirection = dir
this.markDirty()
}
setFlexGrow(v: number | undefined): void {
this.style.flexGrow = v ?? 0
this.markDirty()
}
setFlexShrink(v: number | undefined): void {
this.style.flexShrink = v ?? 0
this.markDirty()
}
setFlex(v: number | undefined): void {
if (v === undefined || isNaN(v)) {
this.style.flexGrow = 0
this.style.flexShrink = 0
} else if (v > 0) {
this.style.flexGrow = v
this.style.flexShrink = 1
this.style.flexBasis = pointValue(0)
} else if (v < 0) {
this.style.flexGrow = 0
this.style.flexShrink = -v
} else {
this.style.flexGrow = 0
this.style.flexShrink = 0
}
this.markDirty()
}
setFlexBasis(v: number | 'auto' | string | undefined): void {
this.style.flexBasis = parseDimension(v)
this.markDirty()
}
setFlexBasisPercent(v: number): void {
this.style.flexBasis = percentValue(v)
this.markDirty()
}
setFlexBasisAuto(): void {
this.style.flexBasis = AUTO_VALUE
this.markDirty()
}
setFlexWrap(wrap: Wrap): void {
this.style.flexWrap = wrap
this.markDirty()
}
// -- Style setters: alignment
setAlignItems(a: Align): void {
this.style.alignItems = a
this.markDirty()
}
setAlignSelf(a: Align): void {
this.style.alignSelf = a
this.markDirty()
}
setAlignContent(a: Align): void {
this.style.alignContent = a
this.markDirty()
}
setJustifyContent(j: Justify): void {
this.style.justifyContent = j
this.markDirty()
}
// -- Style setters: display / position / overflow
setDisplay(d: Display): void {
this.style.display = d
this.markDirty()
}
getDisplay(): Display {
return this.style.display
}
setPositionType(t: PositionType): void {
this.style.positionType = t
this.markDirty()
}
setPosition(edge: Edge, v: number | string | undefined): void {
this.style.position[edge] = parseDimension(v)
this._hasPosition = hasAnyDefinedEdge(this.style.position)
this.markDirty()
}
setPositionPercent(edge: Edge, v: number): void {
this.style.position[edge] = percentValue(v)
this._hasPosition = true
this.markDirty()
}
setPositionAuto(edge: Edge): void {
this.style.position[edge] = AUTO_VALUE
this._hasPosition = true
this.markDirty()
}
setOverflow(o: Overflow): void {
this.style.overflow = o
this.markDirty()
}
setDirection(d: Direction): void {
this.style.direction = d
this.markDirty()
}
setBoxSizing(_: BoxSizing): void {
// Not implemented — Ink doesn't use content-box
}
// -- Style setters: spacing
setMargin(edge: Edge, v: number | 'auto' | string | undefined): void {
const val = parseDimension(v)
this.style.margin[edge] = val
if (val.unit === Unit.Auto) this._hasAutoMargin = true
else this._hasAutoMargin = hasAnyAutoEdge(this.style.margin)
this._hasMargin =
this._hasAutoMargin || hasAnyDefinedEdge(this.style.margin)
this.markDirty()
}
setMarginPercent(edge: Edge, v: number): void {
this.style.margin[edge] = percentValue(v)
this._hasAutoMargin = hasAnyAutoEdge(this.style.margin)
this._hasMargin = true
this.markDirty()
}
setMarginAuto(edge: Edge): void {
this.style.margin[edge] = AUTO_VALUE
this._hasAutoMargin = true
this._hasMargin = true
this.markDirty()
}
setPadding(edge: Edge, v: number | string | undefined): void {
this.style.padding[edge] = parseDimension(v)
this._hasPadding = hasAnyDefinedEdge(this.style.padding)
this.markDirty()
}
setPaddingPercent(edge: Edge, v: number): void {
this.style.padding[edge] = percentValue(v)
this._hasPadding = true
this.markDirty()
}
setBorder(edge: Edge, v: number | undefined): void {
this.style.border[edge] = v === undefined ? UNDEFINED_VALUE : pointValue(v)
this._hasBorder = hasAnyDefinedEdge(this.style.border)
this.markDirty()
}
setGap(gutter: Gutter, v: number | string | undefined): void {
this.style.gap[gutter] = parseDimension(v)
this.markDirty()
}
setGapPercent(gutter: Gutter, v: number): void {
this.style.gap[gutter] = percentValue(v)
this.markDirty()
}
// -- Style getters (partial — only what tests need)
getFlexDirection(): FlexDirection {
return this.style.flexDirection
}
getJustifyContent(): Justify {
return this.style.justifyContent
}
getAlignItems(): Align {
return this.style.alignItems
}
getAlignSelf(): Align {
return this.style.alignSelf
}
getAlignContent(): Align {
return this.style.alignContent
}
getFlexGrow(): number {
return this.style.flexGrow
}
getFlexShrink(): number {
return this.style.flexShrink
}
getFlexBasis(): Value {
return this.style.flexBasis
}
getFlexWrap(): Wrap {
return this.style.flexWrap
}
getWidth(): Value {
return this.style.width
}
getHeight(): Value {
return this.style.height
}
getOverflow(): Overflow {
return this.style.overflow
}
getPositionType(): PositionType {
return this.style.positionType
}
getDirection(): Direction {
return this.style.direction
}
// -- Unused API stubs (present for API parity)
copyStyle(_: Node): void {}
setDirtiedFunc(_: unknown): void {}
unsetDirtiedFunc(): void {}
setIsReferenceBaseline(v: boolean): void {
this.isReferenceBaseline_ = v
this.markDirty()
}
isReferenceBaseline(): boolean {
return this.isReferenceBaseline_
}
setAspectRatio(_: number | undefined): void {}
getAspectRatio(): number {
return NaN
}
setAlwaysFormsContainingBlock(_: boolean): void {}
// -- Layout entry point
calculateLayout(
ownerWidth: number | undefined,
ownerHeight: number | undefined,
_direction?: Direction,
): void {
_yogaNodesVisited = 0
_yogaMeasureCalls = 0
_yogaCacheHits = 0
_generation++
const w = ownerWidth === undefined ? NaN : ownerWidth
const h = ownerHeight === undefined ? NaN : ownerHeight
layoutNode(
this,
w,
h,
isDefined(w) ? MeasureMode.Exactly : MeasureMode.Undefined,
isDefined(h) ? MeasureMode.Exactly : MeasureMode.Undefined,
w,
h,
true,
)
// Root's own position = margin + position insets (yoga applies position
// to the root even without a parent container; this matters for rounding
// since the root's abs top/left seeds the pixel-grid walk).
const mar = this.layout.margin
const posL = resolveValue(
resolveEdgeRaw(this.style.position, EDGE_LEFT),
isDefined(w) ? w : 0,
)
const posT = resolveValue(
resolveEdgeRaw(this.style.position, EDGE_TOP),
isDefined(w) ? w : 0,
)
this.layout.left = mar[EDGE_LEFT] + (isDefined(posL) ? posL : 0)
this.layout.top = mar[EDGE_TOP] + (isDefined(posT) ? posT : 0)
roundLayout(this, this.config.pointScaleFactor, 0, 0)
}
}
const DEFAULT_CONFIG = createConfig()
const CACHE_SLOTS = 4
function cacheWrite(
node: Node,
aW: number,
aH: number,
wM: MeasureMode,
hM: MeasureMode,
oW: number,
oH: number,
fW: boolean,
fH: boolean,
wasDirty: boolean,
): void {
if (!node._cIn) {
node._cIn = new Float64Array(CACHE_SLOTS * 8)
node._cOut = new Float64Array(CACHE_SLOTS * 2)
}
// First write after a dirty clears stale entries from before the dirty.
// _cGen < _generation means entries are from a previous calculateLayout;
// if wasDirty, the subtree changed since then → old dimensions invalid.
// Clean nodes' old entries stay — same subtree → same result for same
// inputs, so cross-generation caching works (the scroll hot path where
// 499 clean messages cache-hit while one dirty leaf recomputes).
if (wasDirty && node._cGen !== _generation) {
node._cN = 0
node._cWr = 0
}
// LRU write index wraps; _cN stays at CACHE_SLOTS so the read scan always
// checks all populated slots (not just those since last wrap).
const i = node._cWr++ % CACHE_SLOTS
if (node._cN < CACHE_SLOTS) node._cN = node._cWr
const o = i * 8
const cIn = node._cIn