-
Notifications
You must be signed in to change notification settings - Fork 1
/
yoga.go
3083 lines (2710 loc) · 104 KB
/
yoga.go
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
package flex
import (
"fmt"
"os"
)
// CachedMeasurement describes measurements
type CachedMeasurement struct {
availableWidth float32
availableHeight float32
widthMeasureMode MeasureMode
heightMeasureMode MeasureMode
computedWidth float32
computedHeight float32
}
// This value was chosen based on empiracle data. Even the most complicated
// layouts should not require more than 16 entries to fit within the cache.
const maxCachedResultCount = 16
// Layout describes position information after layout is finished
type Layout struct {
Position [4]float32
Dimensions [2]float32
Margin [6]float32
Border [6]float32
Padding [6]float32
Direction Direction
computedFlexBasisGeneration int
computedFlexBasis float32
HadOverflow bool
// Instead of recomputing the entire layout every single time, we
// cache some information to break early when nothing changed
generationCount int
lastParentDirection Direction
nextCachedMeasurementsIndex int
cachedMeasurements [maxCachedResultCount]CachedMeasurement
measuredDimensions [2]float32
cachedLayout CachedMeasurement
}
// Style describes CSS flexbox style of the node
type Style struct {
Direction Direction
FlexDirection FlexDirection
JustifyContent Justify
AlignContent Align
AlignItems Align
AlignSelf Align
PositionType PositionType
FlexWrap Wrap
Overflow Overflow
Display Display
Flex float32
FlexGrow float32
FlexShrink float32
FlexBasis Value
Margin [EdgeCount]Value
Position [EdgeCount]Value
Padding [EdgeCount]Value
Border [EdgeCount]Value
Dimensions [2]Value
MinDimensions [2]Value
MaxDimensions [2]Value
// Yoga specific properties, not compatible with flexbox specification
AspectRatio float32
}
// Config describes a configuration
type Config struct {
experimentalFeatures [experimentalFeatureCount + 1]bool
UseWebDefaults bool
UseLegacyStretchBehaviour bool
PointScaleFactor float32
Logger Logger
Context interface{}
}
// Node describes a an element
type Node struct {
Style Style
Layout Layout
lineIndex int
Parent *Node
Children []*Node
NextChild *Node
Measure MeasureFunc
Baseline BaselineFunc
Print PrintFunc
Config *Config
Context interface{}
IsDirty bool
hasNewLayout bool
NodeType NodeType
resolvedDimensions [2]*Value
}
var (
undefinedValue = Value{
Value: Undefined,
Unit: UnitUndefined,
}
autoValue = Value{
Value: Undefined,
Unit: UnitAuto,
}
defaultEdgeValuesUnit = [EdgeCount]Value{
undefinedValue,
undefinedValue,
undefinedValue,
undefinedValue,
undefinedValue,
undefinedValue,
undefinedValue,
undefinedValue,
undefinedValue,
}
defaultDimensionValues = [2]float32{
Undefined,
Undefined,
}
defaultDimensionValuesUnit = [2]Value{
undefinedValue,
undefinedValue,
}
defaultDimensionValuesAutoUnit = [2]Value{
autoValue,
autoValue,
}
)
const (
defaultFlexGrow float32 = 0
defaultFlexShrink float32 = 0
webDefaultFlexShrink float32 = 1
)
var (
nodeDefaults = Node{
Parent: nil,
Children: nil,
hasNewLayout: true,
IsDirty: false,
NodeType: NodeTypeDefault,
resolvedDimensions: [2]*Value{&ValueUndefined, &ValueUndefined},
Style: Style{
Flex: Undefined,
FlexGrow: Undefined,
FlexShrink: Undefined,
FlexBasis: autoValue,
JustifyContent: JustifyFlexStart,
AlignItems: AlignStretch,
AlignContent: AlignFlexStart,
Direction: DirectionInherit,
FlexDirection: FlexDirectionColumn,
Overflow: OverflowVisible,
Display: DisplayFlex,
Dimensions: defaultDimensionValuesAutoUnit,
MinDimensions: defaultDimensionValuesUnit,
MaxDimensions: defaultDimensionValuesUnit,
Position: defaultEdgeValuesUnit,
Margin: defaultEdgeValuesUnit,
Padding: defaultEdgeValuesUnit,
Border: defaultEdgeValuesUnit,
AspectRatio: Undefined,
},
Layout: Layout{
Dimensions: defaultDimensionValues,
lastParentDirection: Direction(-1),
nextCachedMeasurementsIndex: 0,
computedFlexBasis: Undefined,
HadOverflow: false,
measuredDimensions: defaultDimensionValues,
cachedLayout: CachedMeasurement{
widthMeasureMode: MeasureMode(-1),
heightMeasureMode: MeasureMode(-1),
computedWidth: -1,
computedHeight: -1,
},
},
}
configDefaults = Config{
experimentalFeatures: [experimentalFeatureCount + 1]bool{
false,
false,
},
UseWebDefaults: false,
PointScaleFactor: 1,
Logger: DefaultLog,
Context: nil,
}
// ValueZero defines a zero value
ValueZero = Value{Value: 0, Unit: UnitPoint}
)
func valueEq(v1, v2 Value) bool {
if v1.Unit != v2.Unit {
return false
}
return feq(v1.Value, v2.Value)
}
// DefaultLog is default logging function
func DefaultLog(config *Config, node *Node, level LogLevel, format string,
args ...interface{}) int {
switch level {
case LogLevelError, LogLevelFatal:
n, _ := fmt.Fprintf(os.Stderr, format, args...)
return n
case LogLevelWarn, LogLevelInfo, LogLevelDebug, LogLevelVerbose:
fallthrough
default:
n, _ := fmt.Printf(format, args...)
return n
}
}
func computedEdgeValue(edges []Value, edge Edge, defaultValue *Value) *Value {
if edges[edge].Unit != UnitUndefined {
return &edges[edge]
}
isVertEdge := edge == EdgeTop || edge == EdgeBottom
if isVertEdge && edges[EdgeVertical].Unit != UnitUndefined {
return &edges[EdgeVertical]
}
isHorizEdge := (edge == EdgeLeft || edge == EdgeRight || edge == EdgeStart || edge == EdgeEnd)
if isHorizEdge && edges[EdgeHorizontal].Unit != UnitUndefined {
return &edges[EdgeHorizontal]
}
if edges[EdgeAll].Unit != UnitUndefined {
return &edges[EdgeAll]
}
if edge == EdgeStart || edge == EdgeEnd {
return &ValueUndefined
}
return defaultValue
}
func resolveValue(value *Value, parentSize float32) float32 {
switch value.Unit {
case UnitUndefined, UnitAuto:
return Undefined
case UnitPoint:
return value.Value
case UnitPercent:
return value.Value * parentSize / 100
}
return Undefined
}
func resolveValueMargin(value *Value, parentSize float32) float32 {
if value.Unit == UnitAuto {
return 0
}
return resolveValue(value, parentSize)
}
// NewNodeWithConfig creates new node with config
func NewNodeWithConfig(config *Config) *Node {
node := nodeDefaults
if config.UseWebDefaults {
node.Style.FlexDirection = FlexDirectionRow
node.Style.AlignContent = AlignStretch
}
node.Config = config
return &node
}
// NewNode creates a new node
func NewNode() *Node {
return NewNodeWithConfig(&configDefaults)
}
// Reset resets a node
func (node *Node) Reset() {
assertWithNode(node, len(node.Children) == 0, "Cannot reset a node which still has children attached")
assertWithNode(node, node.Parent == nil, "Cannot reset a node still attached to a parent")
node.Children = nil
config := node.Config
*node = nodeDefaults
if config.UseWebDefaults {
node.Style.FlexDirection = FlexDirectionRow
node.Style.AlignContent = AlignStretch
}
node.Config = config
}
// ConfigGetDefault returns default config, only for C#
func ConfigGetDefault() *Config {
return &configDefaults
}
// NewConfig creates new config
func NewConfig() *Config {
config := &Config{}
assertCond(config != nil, "Could not allocate memory for config")
*config = configDefaults
return config
}
// ConfigCopy copies a config
func ConfigCopy(dest *Config, src *Config) {
*dest = *src
}
func nodeMarkDirtyInternal(node *Node) {
if !node.IsDirty {
node.IsDirty = true
node.Layout.computedFlexBasis = Undefined
if node.Parent != nil {
nodeMarkDirtyInternal(node.Parent)
}
}
}
// SetMeasureFunc sets measure function
func (node *Node) SetMeasureFunc(measureFunc MeasureFunc) {
if measureFunc == nil {
node.Measure = nil
// TODO: t18095186 Move nodeType to opt-in function and mark appropriate places in Litho
node.NodeType = NodeTypeDefault
} else {
assertWithNode(
node,
len(node.Children) == 0,
"Cannot set measure function: Nodes with measure functions cannot have children.")
node.Measure = measureFunc
// TODO: t18095186 Move nodeType to opt-in function and mark appropriate places in Litho
node.NodeType = NodeTypeText
}
}
// InsertChild inserts a child
func (node *Node) InsertChild(child *Node, idx int) {
assertWithNode(node, child.Parent == nil, "Child already has a parent, it must be removed first.")
assertWithNode(node, node.Measure == nil, "Cannot add child: Nodes with measure functions cannot have children.")
a := node.Children
// https://github.com/golang/go/wiki/SliceTricks
a = append(a[:idx], append([]*Node{child}, a[idx:]...)...)
node.Children = a
child.Parent = node
nodeMarkDirtyInternal(node)
}
func (node *Node) deleteChild(child *Node) *Node {
a := node.Children
n := len(a)
for i := 0; i < n; i++ {
if a[i] == child {
removed := a[i]
copy(a[i:], a[i+1:])
a[len(a)-1] = nil // or the zero value of T
a = a[:len(a)-1]
node.Children = a
return removed
}
}
return nil
}
// RemoveChild removes child node
func (node *Node) RemoveChild(child *Node) {
if node.deleteChild(child) != nil {
child.Layout = nodeDefaults.Layout // layout is no longer valid
child.Parent = nil
nodeMarkDirtyInternal(node)
}
}
// GetChild returns a child at a given index
func (node *Node) GetChild(idx int) *Node {
if idx < len(node.Children) {
return node.Children[idx]
}
return nil
}
// MarkDirty marks node as dirty
func (node *Node) MarkDirty() {
assertWithNode(node, node.Measure != nil,
"Only leaf nodes with custom measure functions should manually mark themselves as dirty")
nodeMarkDirtyInternal(node)
}
func styleEq(s1, s2 *Style) bool {
if s1.Direction != s2.Direction ||
s1.FlexDirection != s2.FlexDirection ||
s1.JustifyContent != s2.JustifyContent ||
s1.AlignContent != s2.AlignContent ||
s1.AlignItems != s2.AlignItems ||
s1.AlignSelf != s2.AlignSelf ||
s1.PositionType != s2.PositionType ||
s1.FlexWrap != s2.FlexWrap ||
s1.Overflow != s2.Overflow ||
s1.Display != s2.Display ||
!feq(s1.Flex, s2.Flex) ||
!feq(s1.FlexGrow, s2.FlexGrow) ||
!feq(s1.FlexShrink, s2.FlexShrink) ||
!valueEq(s1.FlexBasis, s2.FlexBasis) {
return false
}
for i := 0; i < EdgeCount; i++ {
if !valueEq(s1.Margin[i], s2.Margin[i]) ||
!valueEq(s1.Position[i], s2.Position[i]) ||
!valueEq(s1.Padding[i], s2.Padding[i]) ||
!valueEq(s1.Border[i], s2.Border[i]) {
return false
}
}
for i := 0; i < 2; i++ {
if !valueEq(s1.Dimensions[i], s2.Dimensions[i]) ||
!valueEq(s1.MinDimensions[i], s2.MinDimensions[i]) ||
!valueEq(s1.MaxDimensions[i], s2.MaxDimensions[i]) {
return false
}
}
return true
}
// NodeCopyStyle copies style
func NodeCopyStyle(dstNode *Node, srcNode *Node) {
if !styleEq(&dstNode.Style, &srcNode.Style) {
dstNode.Style = srcNode.Style
nodeMarkDirtyInternal(dstNode)
}
}
func resolveFlexGrow(node *Node) float32 {
// Root nodes flexGrow should always be 0
if node.Parent == nil {
return 0
}
if !FloatIsUndefined(node.Style.FlexGrow) {
return node.Style.FlexGrow
}
if !FloatIsUndefined(node.Style.Flex) && node.Style.Flex > 0 {
return node.Style.Flex
}
return defaultFlexGrow
}
// StyleGetFlexGrow gets flex grow
func (node *Node) StyleGetFlexGrow() float32 {
if FloatIsUndefined(node.Style.FlexGrow) {
return defaultFlexGrow
}
return node.Style.FlexGrow
}
// StyleGetFlexShrink gets flex shrink
func (node *Node) StyleGetFlexShrink() float32 {
if FloatIsUndefined(node.Style.FlexShrink) {
if node.Config.UseWebDefaults {
return webDefaultFlexShrink
}
return defaultFlexShrink
}
return node.Style.FlexShrink
}
func nodeResolveFlexShrink(node *Node) float32 {
// Root nodes flexShrink should always be 0
if node.Parent == nil {
return 0
}
if !FloatIsUndefined(node.Style.FlexShrink) {
return node.Style.FlexShrink
}
if !node.Config.UseWebDefaults && !FloatIsUndefined(node.Style.Flex) &&
node.Style.Flex < 0 {
return -node.Style.Flex
}
if node.Config.UseWebDefaults {
return webDefaultFlexShrink
}
return defaultFlexShrink
}
func nodeResolveFlexBasisPtr(node *Node) *Value {
style := &node.Style
if style.FlexBasis.Unit != UnitAuto && style.FlexBasis.Unit != UnitUndefined {
return &style.FlexBasis
}
if !FloatIsUndefined(style.Flex) && style.Flex > 0 {
if node.Config.UseWebDefaults {
return &ValueAuto
}
return &ValueZero
}
return &ValueAuto
}
// see yoga_props.go
var (
currentGenerationCount = 0
)
// FloatIsUndefined returns true if value is undefined
func FloatIsUndefined(value float32) bool {
return IsNaN(value)
}
// ValueEqual returns true if values are equal
func ValueEqual(a Value, b Value) bool {
if a.Unit != b.Unit {
return false
}
if a.Unit == UnitUndefined {
return true
}
return fabs(a.Value-b.Value) < 0.0001
}
func resolveDimensions(node *Node) {
for dim := DimensionWidth; dim <= DimensionHeight; dim++ {
if node.Style.MaxDimensions[dim].Unit != UnitUndefined &&
ValueEqual(node.Style.MaxDimensions[dim], node.Style.MinDimensions[dim]) {
node.resolvedDimensions[dim] = &node.Style.MaxDimensions[dim]
} else {
node.resolvedDimensions[dim] = &node.Style.Dimensions[dim]
}
}
}
// FloatsEqual returns true if floats are approx. equal
func FloatsEqual(a float32, b float32) bool {
if FloatIsUndefined(a) {
return FloatIsUndefined(b)
}
return fabs(a-b) < 0.0001
}
// see print.go
var (
leading = [4]Edge{EdgeTop, EdgeBottom, EdgeLeft, EdgeRight}
trailing = [4]Edge{EdgeBottom, EdgeTop, EdgeRight, EdgeLeft}
pos = [4]Edge{EdgeTop, EdgeBottom, EdgeLeft, EdgeRight}
dim = [4]Dimension{DimensionHeight, DimensionHeight, DimensionWidth, DimensionWidth}
)
func init() {
leading[FlexDirectionColumn] = EdgeTop
leading[FlexDirectionColumnReverse] = EdgeBottom
leading[FlexDirectionRow] = EdgeLeft
leading[FlexDirectionRowReverse] = EdgeRight
trailing[FlexDirectionColumn] = EdgeBottom
trailing[FlexDirectionColumnReverse] = EdgeTop
trailing[FlexDirectionRow] = EdgeRight
trailing[FlexDirectionRowReverse] = EdgeLeft
pos[FlexDirectionColumn] = EdgeTop
pos[FlexDirectionColumnReverse] = EdgeBottom
pos[FlexDirectionRow] = EdgeLeft
pos[FlexDirectionRowReverse] = EdgeRight
dim[FlexDirectionColumn] = DimensionHeight
dim[FlexDirectionColumnReverse] = DimensionHeight
dim[FlexDirectionRow] = DimensionWidth
dim[FlexDirectionRowReverse] = DimensionWidth
}
func flexDirectionIsRow(flexDirection FlexDirection) bool {
return flexDirection == FlexDirectionRow || flexDirection == FlexDirectionRowReverse
}
func flexDirectionIsColumn(flexDirection FlexDirection) bool {
return flexDirection == FlexDirectionColumn || flexDirection == FlexDirectionColumnReverse
}
func nodeLeadingMargin(node *Node, axis FlexDirection, widthSize float32) float32 {
if flexDirectionIsRow(axis) && node.Style.Margin[EdgeStart].Unit != UnitUndefined {
return resolveValueMargin(&node.Style.Margin[EdgeStart], widthSize)
}
v := computedEdgeValue(node.Style.Margin[:], leading[axis], &ValueZero)
return resolveValueMargin(v, widthSize)
}
func nodeTrailingMargin(node *Node, axis FlexDirection, widthSize float32) float32 {
if flexDirectionIsRow(axis) && node.Style.Margin[EdgeEnd].Unit != UnitUndefined {
return resolveValueMargin(&node.Style.Margin[EdgeEnd], widthSize)
}
return resolveValueMargin(computedEdgeValue(node.Style.Margin[:], trailing[axis], &ValueZero),
widthSize)
}
func nodeLeadingPadding(node *Node, axis FlexDirection, widthSize float32) float32 {
if flexDirectionIsRow(axis) && node.Style.Padding[EdgeStart].Unit != UnitUndefined &&
resolveValue(&node.Style.Padding[EdgeStart], widthSize) >= 0 {
return resolveValue(&node.Style.Padding[EdgeStart], widthSize)
}
return fmaxf(resolveValue(computedEdgeValue(node.Style.Padding[:], leading[axis], &ValueZero), widthSize), 0)
}
func nodeTrailingPadding(node *Node, axis FlexDirection, widthSize float32) float32 {
if flexDirectionIsRow(axis) && node.Style.Padding[EdgeEnd].Unit != UnitUndefined &&
resolveValue(&node.Style.Padding[EdgeEnd], widthSize) >= 0 {
return resolveValue(&node.Style.Padding[EdgeEnd], widthSize)
}
return fmaxf(resolveValue(computedEdgeValue(node.Style.Padding[:], trailing[axis], &ValueZero), widthSize), 0)
}
func nodeLeadingBorder(node *Node, axis FlexDirection) float32 {
if flexDirectionIsRow(axis) && node.Style.Border[EdgeStart].Unit != UnitUndefined &&
node.Style.Border[EdgeStart].Value >= 0 {
return node.Style.Border[EdgeStart].Value
}
return fmaxf(computedEdgeValue(node.Style.Border[:], leading[axis], &ValueZero).Value, 0)
}
func nodeTrailingBorder(node *Node, axis FlexDirection) float32 {
if flexDirectionIsRow(axis) && node.Style.Border[EdgeEnd].Unit != UnitUndefined &&
node.Style.Border[EdgeEnd].Value >= 0 {
return node.Style.Border[EdgeEnd].Value
}
return fmaxf(computedEdgeValue(node.Style.Border[:], trailing[axis], &ValueZero).Value, 0)
}
func nodeLeadingPaddingAndBorder(node *Node, axis FlexDirection, widthSize float32) float32 {
return nodeLeadingPadding(node, axis, widthSize) + nodeLeadingBorder(node, axis)
}
func nodeTrailingPaddingAndBorder(node *Node, axis FlexDirection, widthSize float32) float32 {
return nodeTrailingPadding(node, axis, widthSize) + nodeTrailingBorder(node, axis)
}
func nodeMarginForAxis(node *Node, axis FlexDirection, widthSize float32) float32 {
leading := nodeLeadingMargin(node, axis, widthSize)
trailing := nodeTrailingMargin(node, axis, widthSize)
return leading + trailing
}
func nodePaddingAndBorderForAxis(node *Node, axis FlexDirection, widthSize float32) float32 {
return nodeLeadingPaddingAndBorder(node, axis, widthSize) +
nodeTrailingPaddingAndBorder(node, axis, widthSize)
}
func nodeAlignItem(node *Node, child *Node) Align {
align := child.Style.AlignSelf
if child.Style.AlignSelf == AlignAuto {
align = node.Style.AlignItems
}
if align == AlignBaseline && flexDirectionIsColumn(node.Style.FlexDirection) {
return AlignFlexStart
}
return align
}
func nodeResolveDirection(node *Node, parentDirection Direction) Direction {
if node.Style.Direction == DirectionInherit {
if parentDirection > DirectionInherit {
return parentDirection
}
return DirectionLTR
}
return node.Style.Direction
}
// Baseline retuns baseline
func Baseline(node *Node) float32 {
if node.Baseline != nil {
baseline := node.Baseline(node, node.Layout.measuredDimensions[DimensionWidth], node.Layout.measuredDimensions[DimensionHeight])
assertWithNode(node, !FloatIsUndefined(baseline), "Expect custom baseline function to not return NaN")
return baseline
}
var baselineChild *Node
childCount := len(node.Children)
for i := 0; i < childCount; i++ {
child := node.GetChild(i)
if child.lineIndex > 0 {
break
}
if child.Style.PositionType == PositionTypeAbsolute {
continue
}
if nodeAlignItem(node, child) == AlignBaseline {
baselineChild = child
break
}
if baselineChild == nil {
baselineChild = child
}
}
if baselineChild == nil {
return node.Layout.measuredDimensions[DimensionHeight]
}
baseline := Baseline(baselineChild)
return baseline + baselineChild.Layout.Position[EdgeTop]
}
func resolveFlexDirection(flexDirection FlexDirection, direction Direction) FlexDirection {
if direction == DirectionRTL {
if flexDirection == FlexDirectionRow {
return FlexDirectionRowReverse
} else if flexDirection == FlexDirectionRowReverse {
return FlexDirectionRow
}
}
return flexDirection
}
func flexDirectionCross(flexDirection FlexDirection, direction Direction) FlexDirection {
if flexDirectionIsColumn(flexDirection) {
return resolveFlexDirection(FlexDirectionRow, direction)
}
return FlexDirectionColumn
}
func nodeIsFlex(node *Node) bool {
return (node.Style.PositionType == PositionTypeRelative &&
(resolveFlexGrow(node) != 0 || nodeResolveFlexShrink(node) != 0))
}
func isBaselineLayout(node *Node) bool {
if flexDirectionIsColumn(node.Style.FlexDirection) {
return false
}
if node.Style.AlignItems == AlignBaseline {
return true
}
childCount := len(node.Children)
for i := 0; i < childCount; i++ {
child := node.GetChild(i)
if child.Style.PositionType == PositionTypeRelative &&
child.Style.AlignSelf == AlignBaseline {
return true
}
}
return false
}
func nodeDimWithMargin(node *Node, axis FlexDirection, widthSize float32) float32 {
return node.Layout.measuredDimensions[dim[axis]] + nodeLeadingMargin(node, axis, widthSize) +
nodeTrailingMargin(node, axis, widthSize)
}
func nodeIsStyleDimDefined(node *Node, axis FlexDirection, parentSize float32) bool {
v := node.resolvedDimensions[dim[axis]]
isNotDefined := (v.Unit == UnitAuto ||
v.Unit == UnitUndefined ||
(v.Unit == UnitPoint && v.Value < 0) ||
(v.Unit == UnitPercent && (v.Value < 0 || FloatIsUndefined(parentSize))))
return !isNotDefined
}
func nodeIsLayoutDimDefined(node *Node, axis FlexDirection) bool {
value := node.Layout.measuredDimensions[dim[axis]]
return !FloatIsUndefined(value) && value >= 0
}
func nodeIsLeadingPosDefined(node *Node, axis FlexDirection) bool {
return (flexDirectionIsRow(axis) &&
computedEdgeValue(node.Style.Position[:], EdgeStart, &ValueUndefined).Unit !=
UnitUndefined) ||
computedEdgeValue(node.Style.Position[:], leading[axis], &ValueUndefined).Unit !=
UnitUndefined
}
func nodeIsTrailingPosDefined(node *Node, axis FlexDirection) bool {
return (flexDirectionIsRow(axis) &&
computedEdgeValue(node.Style.Position[:], EdgeEnd, &ValueUndefined).Unit !=
UnitUndefined) ||
computedEdgeValue(node.Style.Position[:], trailing[axis], &ValueUndefined).Unit !=
UnitUndefined
}
func nodeLeadingPosition(node *Node, axis FlexDirection, axisSize float32) float32 {
if flexDirectionIsRow(axis) {
leadingPosition := computedEdgeValue(node.Style.Position[:], EdgeStart, &ValueUndefined)
if leadingPosition.Unit != UnitUndefined {
return resolveValue(leadingPosition, axisSize)
}
}
leadingPosition := computedEdgeValue(node.Style.Position[:], leading[axis], &ValueUndefined)
if leadingPosition.Unit == UnitUndefined {
return 0
}
return resolveValue(leadingPosition, axisSize)
}
func nodeTrailingPosition(node *Node, axis FlexDirection, axisSize float32) float32 {
if flexDirectionIsRow(axis) {
trailingPosition := computedEdgeValue(node.Style.Position[:], EdgeEnd, &ValueUndefined)
if trailingPosition.Unit != UnitUndefined {
return resolveValue(trailingPosition, axisSize)
}
}
trailingPosition := computedEdgeValue(node.Style.Position[:], trailing[axis], &ValueUndefined)
if trailingPosition.Unit == UnitUndefined {
return 0
}
return resolveValue(trailingPosition, axisSize)
}
func nodeBoundAxisWithinMinAndMax(node *Node, axis FlexDirection, value float32, axisSize float32) float32 {
min := Undefined
max := Undefined
if flexDirectionIsColumn(axis) {
min = resolveValue(&node.Style.MinDimensions[DimensionHeight], axisSize)
max = resolveValue(&node.Style.MaxDimensions[DimensionHeight], axisSize)
} else if flexDirectionIsRow(axis) {
min = resolveValue(&node.Style.MinDimensions[DimensionWidth], axisSize)
max = resolveValue(&node.Style.MaxDimensions[DimensionWidth], axisSize)
}
boundValue := value
if !FloatIsUndefined(max) && max >= 0 && boundValue > max {
boundValue = max
}
if !FloatIsUndefined(min) && min >= 0 && boundValue < min {
boundValue = min
}
return boundValue
}
func marginLeadingValue(node *Node, axis FlexDirection) *Value {
if flexDirectionIsRow(axis) && node.Style.Margin[EdgeStart].Unit != UnitUndefined {
return &node.Style.Margin[EdgeStart]
}
return &node.Style.Margin[leading[axis]]
}
func marginTrailingValue(node *Node, axis FlexDirection) *Value {
if flexDirectionIsRow(axis) && node.Style.Margin[EdgeEnd].Unit != UnitUndefined {
return &node.Style.Margin[EdgeEnd]
}
return &node.Style.Margin[trailing[axis]]
}
// nodeBoundAxis is like nodeBoundAxisWithinMinAndMax but also ensures that
// the value doesn't go below the padding and border amount.
func nodeBoundAxis(node *Node, axis FlexDirection, value float32, axisSize float32, widthSize float32) float32 {
return fmaxf(nodeBoundAxisWithinMinAndMax(node, axis, value, axisSize),
nodePaddingAndBorderForAxis(node, axis, widthSize))
}
func nodeSetChildTrailingPosition(node *Node, child *Node, axis FlexDirection) {
size := child.Layout.measuredDimensions[dim[axis]]
child.Layout.Position[trailing[axis]] =
node.Layout.measuredDimensions[dim[axis]] - size - child.Layout.Position[pos[axis]]
}
// If both left and right are defined, then use left. Otherwise return
// +left or -right depending on which is defined.
func nodeRelativePosition(node *Node, axis FlexDirection, axisSize float32) float32 {
if nodeIsLeadingPosDefined(node, axis) {
return nodeLeadingPosition(node, axis, axisSize)
}
return -nodeTrailingPosition(node, axis, axisSize)
}
func constrainMaxSizeForMode(node *Node, axis FlexDirection, parentAxisSize float32, parentWidth float32, mode *MeasureMode, size *float32) {
maxSize := resolveValue(&node.Style.MaxDimensions[dim[axis]], parentAxisSize) +
nodeMarginForAxis(node, axis, parentWidth)
switch *mode {
case MeasureModeExactly, MeasureModeAtMost:
if FloatIsUndefined(maxSize) || *size < maxSize {
// TODO: this is redundant, but what is in original code
//*size = *size
} else {
*size = maxSize
}
break
case MeasureModeUndefined:
if !FloatIsUndefined(maxSize) {
*mode = MeasureModeAtMost
*size = maxSize
}
break
}
}
func nodeSetPosition(node *Node, direction Direction, mainSize float32, crossSize float32, parentWidth float32) {
/* Root nodes should be always layouted as LTR, so we don't return negative values. */
directionRespectingRoot := DirectionLTR
if node.Parent != nil {
directionRespectingRoot = direction
}
mainAxis := resolveFlexDirection(node.Style.FlexDirection, directionRespectingRoot)
crossAxis := flexDirectionCross(mainAxis, directionRespectingRoot)
relativePositionMain := nodeRelativePosition(node, mainAxis, mainSize)
relativePositionCross := nodeRelativePosition(node, crossAxis, crossSize)
pos := &node.Layout.Position
pos[leading[mainAxis]] = nodeLeadingMargin(node, mainAxis, parentWidth) + relativePositionMain
pos[trailing[mainAxis]] = nodeTrailingMargin(node, mainAxis, parentWidth) + relativePositionMain
pos[leading[crossAxis]] = nodeLeadingMargin(node, crossAxis, parentWidth) + relativePositionCross
pos[trailing[crossAxis]] = nodeTrailingMargin(node, crossAxis, parentWidth) + relativePositionCross
}
func nodeComputeFlexBasisForChild(node *Node,
child *Node,
width float32,
widthMode MeasureMode,
height float32,
parentWidth float32,
parentHeight float32,
heightMode MeasureMode,
direction Direction,
config *Config) {
mainAxis := resolveFlexDirection(node.Style.FlexDirection, direction)
isMainAxisRow := flexDirectionIsRow(mainAxis)
mainAxisSize := height
mainAxisParentSize := parentHeight
if isMainAxisRow {
mainAxisSize = width
mainAxisParentSize = parentWidth
}
var childWidth float32
var childHeight float32
var childWidthMeasureMode MeasureMode
var childHeightMeasureMode MeasureMode
resolvedFlexBasis := resolveValue(nodeResolveFlexBasisPtr(child), mainAxisParentSize)
isRowStyleDimDefined := nodeIsStyleDimDefined(child, FlexDirectionRow, parentWidth)
isColumnStyleDimDefined := nodeIsStyleDimDefined(child, FlexDirectionColumn, parentHeight)
if !FloatIsUndefined(resolvedFlexBasis) && !FloatIsUndefined(mainAxisSize) {
if FloatIsUndefined(child.Layout.computedFlexBasis) ||
(child.Config.IsExperimentalFeatureEnabled(ExperimentalFeatureWebFlexBasis) &&
child.Layout.computedFlexBasisGeneration != currentGenerationCount) {
child.Layout.computedFlexBasis =
fmaxf(resolvedFlexBasis, nodePaddingAndBorderForAxis(child, mainAxis, parentWidth))
}
} else if isMainAxisRow && isRowStyleDimDefined {
// The width is definite, so use that as the flex basis.
child.Layout.computedFlexBasis =
fmaxf(resolveValue(child.resolvedDimensions[DimensionWidth], parentWidth),
nodePaddingAndBorderForAxis(child, FlexDirectionRow, parentWidth))
} else if !isMainAxisRow && isColumnStyleDimDefined {
// The height is definite, so use that as the flex basis.
child.Layout.computedFlexBasis =
fmaxf(resolveValue(child.resolvedDimensions[DimensionHeight], parentHeight),
nodePaddingAndBorderForAxis(child, FlexDirectionColumn, parentWidth))
} else {
// Compute the flex basis and hypothetical main size (i.e. the clamped
// flex basis).
childWidth = Undefined
childHeight = Undefined
childWidthMeasureMode = MeasureModeUndefined