FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
pythonnative/src/pythonnative/layout.py at main · andevsr/pythonnative · GitHub
andevsr
pythonnative
Repository navigation
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
pythonnative
/
src
/
pythonnative
/
layout.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
1297 lines (1116 loc) · 47.9 KB
Breadcrumbs
pythonnative
/
src
/
pythonnative
/
layout.py
Copy path
File metadata and controls
1297 lines (1116 loc) · 47.9 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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-Python flexbox layout engine.
Computes positions and sizes for every node in a layout tree based on
CSS flexbox-inspired style properties. Inspired by Facebook's Yoga and
React Native's layout system, but implemented entirely in Python so
PythonNative does not depend on a native layout library.
The engine is invoked by the reconciler after each commit pass:
1. The reconciler maintains a parallel
[`LayoutNode`][pythonnative.layout.LayoutNode] tree (cached across
passes: clean subtrees keep their nodes, dirty ones are rebuilt).
2. [`calculate_layout`][pythonnative.layout.calculate_layout] is called
with the viewport size; it recursively determines each node's
``(x, y, width, height)`` relative to its parent's coordinate space.
Nodes that are **not dirty** and are measured under the same
constraints as the previous pass return their memoized size without
recursing, which turns full-tree layout into dirty-subtree layout.
3. The reconciler walks the tree again and emits a frame op for each
native view whose frame actually changed.
The algorithm supports:
- **Flex containers**: ``flex_direction`` (``row``/``column`` and their
reverse variants), ``justify_content`` (``flex_start`` / ``center`` /
``flex_end`` / ``space_between`` / ``space_around`` / ``space_evenly``),
``align_items`` (``stretch`` / ``flex_start`` / ``center`` /
``flex_end``), and ``align_self`` overrides per child.
- **Wrapping**: ``flex_wrap`` (``nowrap`` / ``wrap`` / ``wrap_reverse``)
with ``align_content`` controlling how lines share leftover
cross-axis space (``stretch`` default, plus the justify palette).
- **Direction**: ``direction: "rtl"`` flips row layouts, ``start`` /
``end`` edge keys (``margin_start``, ``padding_end``, absolute
``start`` / ``end`` insets) resolve against the inherited direction.
- **Sizing**: explicit ``width`` / ``height`` (numbers or percentages),
``min_width`` / ``max_width`` / ``min_height`` / ``max_height``
constraints, ``aspect_ratio``, and content-based sizing via the
optional ``measure`` callback.
- **Flex distribution**: ``flex`` (RN shorthand for grow factor with
``flex_basis: 0``), ``flex_grow``, ``flex_shrink``, ``flex_basis``.
- **Absolute positioning**: ``position: "absolute"`` with ``top``,
``right``, ``bottom``, ``left`` (and ``start`` / ``end``) insets.
Absolute children are positioned relative to the parent's padding box
and do not participate in flex distribution.
- **Spacing**: ``padding`` / ``margin`` (scalar, dict, or per-edge
keys), inter-child ``spacing`` (aliases: ``gap``, ``column_gap`` /
``row_gap`` per axis).
Example:
```python
from pythonnative.layout import LayoutNode, calculate_layout
root = LayoutNode(
style={"flex_direction": "row", "padding": 8, "spacing": 4},
children=[
LayoutNode(style={"width": 80, "height": 40}),
LayoutNode(style={"flex": 1, "height": 40}),
LayoutNode(style={"width": 60, "height": 40}),
],
)
calculate_layout(root, 320, 200)
# root.children[0].x == 8, .width == 80
# root.children[1].x == 92, .width == 156 (filled by flex: 1)
# root.children[2].x == 252, .width == 60
```
"""
import
math
from
typing
import
Any
,
Callable
,
Dict
,
List
,
Optional
,
Tuple
# ======================================================================
# Public constants
# ======================================================================
LAYOUT_STYLE_KEYS
=
frozenset
(
{
"width"
,
"height"
,
"min_width"
,
"max_width"
,
"min_height"
,
"max_height"
,
"flex"
,
"flex_grow"
,
"flex_shrink"
,
"flex_basis"
,
"flex_wrap"
,
"align_self"
,
"align_content"
,
"position"
,
"top"
,
"right"
,
"bottom"
,
"left"
,
"start"
,
"end"
,
"margin"
,
"margin_top"
,
"margin_bottom"
,
"margin_left"
,
"margin_right"
,
"margin_start"
,
"margin_end"
,
"margin_horizontal"
,
"margin_vertical"
,
"padding"
,
"padding_top"
,
"padding_bottom"
,
"padding_left"
,
"padding_right"
,
"padding_start"
,
"padding_end"
,
"padding_horizontal"
,
"padding_vertical"
,
"flex_direction"
,
"justify_content"
,
"align_items"
,
"spacing"
,
"gap"
,
"row_gap"
,
"column_gap"
,
"aspect_ratio"
,
"direction"
,
}
)
"""Style keys that affect layout (and are consumed by the layout engine)."""
# Flex direction values
FLEX_DIRECTION_COLUMN
=
"column"
FLEX_DIRECTION_COLUMN_REVERSE
=
"column_reverse"
FLEX_DIRECTION_ROW
=
"row"
FLEX_DIRECTION_ROW_REVERSE
=
"row_reverse"
# flex_wrap values
WRAP_NOWRAP
=
"nowrap"
WRAP_WRAP
=
"wrap"
WRAP_REVERSE
=
"wrap_reverse"
# justify_content / align_content values
JUSTIFY_FLEX_START
=
"flex_start"
JUSTIFY_CENTER
=
"center"
JUSTIFY_FLEX_END
=
"flex_end"
JUSTIFY_SPACE_BETWEEN
=
"space_between"
JUSTIFY_SPACE_AROUND
=
"space_around"
JUSTIFY_SPACE_EVENLY
=
"space_evenly"
# align_items / align_self values
ALIGN_AUTO
=
"auto"
ALIGN_FLEX_START
=
"flex_start"
ALIGN_CENTER
=
"center"
ALIGN_FLEX_END
=
"flex_end"
ALIGN_STRETCH
=
"stretch"
# position values
POSITION_RELATIVE
=
"relative"
POSITION_ABSOLUTE
=
"absolute"
# direction values
DIRECTION_LTR
=
"ltr"
DIRECTION_RTL
=
"rtl"
# Friendly aliases on cross-axis alignment props.
_ALIGN_ALIASES
=
{
"start"
:
ALIGN_FLEX_START
,
"leading"
:
ALIGN_FLEX_START
,
"top"
:
ALIGN_FLEX_START
,
"end"
:
ALIGN_FLEX_END
,
"trailing"
:
ALIGN_FLEX_END
,
"bottom"
:
ALIGN_FLEX_END
,
"fill"
:
ALIGN_STRETCH
,
}
_JUSTIFY_ALIASES
=
{
"start"
:
JUSTIFY_FLEX_START
,
"leading"
:
JUSTIFY_FLEX_START
,
"top"
:
JUSTIFY_FLEX_START
,
"end"
:
JUSTIFY_FLEX_END
,
"trailing"
:
JUSTIFY_FLEX_END
,
"bottom"
:
JUSTIFY_FLEX_END
,
}
# A measure callback receives ``(max_width, max_height)`` (either may be
# ``math.inf`` to indicate no constraint) and returns the leaf's natural
# ``(width, height)`` in points.
MeasureFn
=
Callable
[[
float
,
float
],
Tuple
[
float
,
float
]]
# ======================================================================
# Helpers
# ======================================================================
def
_is_row
(
direction
:
str
)
->
bool
:
"""Return whether `direction` lays out children along the horizontal axis."""
return
direction
in
(
FLEX_DIRECTION_ROW
,
FLEX_DIRECTION_ROW_REVERSE
)
def
_is_reverse
(
direction
:
str
)
->
bool
:
"""Return whether `direction` is one of the reverse variants."""
return
direction
in
(
FLEX_DIRECTION_ROW_REVERSE
,
FLEX_DIRECTION_COLUMN_REVERSE
)
def
_to_float
(
value
:
Any
)
->
Optional
[
float
]:
"""Coerce ``value`` to ``float``; return ``None`` if not coercible."""
if
value
is
None
or
isinstance
(
value
,
bool
):
return
None
try
:
return
float
(
value
)
except
(
TypeError
,
ValueError
):
return
None
def
_resolve_value
(
value
:
Any
,
parent_size
:
float
)
->
Optional
[
float
]:
"""Resolve a dimension value to points.
Accepts:
- ``None``: returns ``None``.
- ``int`` / ``float``: returned as-is.
- ``str`` ending in ``"%"``: percentage of ``parent_size``. If
``parent_size`` is not finite (e.g., inside a vertically
unbounded ScrollView), percentages collapse to ``None`` so the
caller can fall back to content-based sizing.
"""
if
value
is
None
:
return
None
if
isinstance
(
value
,
bool
):
return
None
if
isinstance
(
value
, (
int
,
float
)):
return
float
(
value
)
if
isinstance
(
value
,
str
):
s
=
value
.
strip
()
if
s
.
endswith
(
"%"
):
try
:
pct
=
float
(
s
[:
-
1
])
except
ValueError
:
return
None
if
not
math
.
isfinite
(
parent_size
):
return
None
return
parent_size
*
pct
/
100.0
try
:
return
float
(
s
)
except
ValueError
:
return
None
return
None
def
_padding_edges
(
value
:
Any
,
parent_w
:
float
,
parent_h
:
float
)
->
Tuple
[
float
,
float
,
float
,
float
]:
"""Resolve a padding/margin value to ``(left, top, right, bottom)``."""
if
value
is
None
:
return
(
0.0
,
0.0
,
0.0
,
0.0
)
if
isinstance
(
value
, (
int
,
float
))
and
not
isinstance
(
value
,
bool
):
v
=
float
(
value
)
return
(
v
,
v
,
v
,
v
)
if
isinstance
(
value
,
dict
):
all_v
=
_resolve_value
(
value
.
get
(
"all"
),
max
(
parent_w
,
parent_h
))
or
0.0
h_v
=
_resolve_value
(
value
.
get
(
"horizontal"
),
parent_w
)
v_v
=
_resolve_value
(
value
.
get
(
"vertical"
),
parent_h
)
h
=
h_v
if
h_v
is
not
None
else
all_v
v
=
v_v
if
v_v
is
not
None
else
all_v
left
=
_resolve_value
(
value
.
get
(
"left"
),
parent_w
)
right
=
_resolve_value
(
value
.
get
(
"right"
),
parent_w
)
top
=
_resolve_value
(
value
.
get
(
"top"
),
parent_h
)
bottom
=
_resolve_value
(
value
.
get
(
"bottom"
),
parent_h
)
return
(
left
if
left
is
not
None
else
h
,
top
if
top
is
not
None
else
v
,
right
if
right
is
not
None
else
h
,
bottom
if
bottom
is
not
None
else
v
,
)
if
isinstance
(
value
,
str
):
v
=
_resolve_value
(
value
,
max
(
parent_w
,
parent_h
))
if
v
is
None
:
return
(
0.0
,
0.0
,
0.0
,
0.0
)
return
(
v
,
v
,
v
,
v
)
return
(
0.0
,
0.0
,
0.0
,
0.0
)
def
_resolve_padding_for
(
style
:
Dict
[
str
,
Any
],
parent_w
:
float
,
parent_h
:
float
,
prefix
:
str
,
direction
:
str
=
DIRECTION_LTR
,
)
->
Tuple
[
float
,
float
,
float
,
float
]:
"""Resolve padding/margin from `style`, honoring per-edge overrides.
``{prefix}_start`` / ``{prefix}_end`` resolve to the left/right
edge according to ``direction`` and take precedence over the
physical ``left`` / ``right`` keys (matching React Native).
"""
base_l
,
base_t
,
base_r
,
base_b
=
_padding_edges
(
style
.
get
(
prefix
),
parent_w
,
parent_h
)
h_override
=
_resolve_value
(
style
.
get
(
f"
{
prefix
}
_horizontal"
),
parent_w
)
v_override
=
_resolve_value
(
style
.
get
(
f"
{
prefix
}
_vertical"
),
parent_h
)
if
h_override
is
not
None
:
base_l
=
h_override
base_r
=
h_override
if
v_override
is
not
None
:
base_t
=
v_override
base_b
=
v_override
left
=
_resolve_value
(
style
.
get
(
f"
{
prefix
}
_left"
),
parent_w
)
right
=
_resolve_value
(
style
.
get
(
f"
{
prefix
}
_right"
),
parent_w
)
top
=
_resolve_value
(
style
.
get
(
f"
{
prefix
}
_top"
),
parent_h
)
bottom
=
_resolve_value
(
style
.
get
(
f"
{
prefix
}
_bottom"
),
parent_h
)
if
left
is
not
None
:
base_l
=
left
if
right
is
not
None
:
base_r
=
right
if
top
is
not
None
:
base_t
=
top
if
bottom
is
not
None
:
base_b
=
bottom
start
=
_resolve_value
(
style
.
get
(
f"
{
prefix
}
_start"
),
parent_w
)
end
=
_resolve_value
(
style
.
get
(
f"
{
prefix
}
_end"
),
parent_w
)
if
start
is
not
None
:
if
direction
==
DIRECTION_RTL
:
base_r
=
start
else
:
base_l
=
start
if
end
is
not
None
:
if
direction
==
DIRECTION_RTL
:
base_l
=
end
else
:
base_r
=
end
return
(
base_l
,
base_t
,
base_r
,
base_b
)
def
_clamp
(
value
:
Optional
[
float
],
minimum
:
Any
,
maximum
:
Any
,
parent_size
:
float
,
)
->
Optional
[
float
]:
"""Clamp `value` to ``[minimum, maximum]``, resolving percentage limits."""
if
value
is
None
:
return
None
min_v
=
_resolve_value
(
minimum
,
parent_size
)
max_v
=
_resolve_value
(
maximum
,
parent_size
)
if
min_v
is
not
None
and
value
<
min_v
:
value
=
min_v
if
max_v
is
not
None
and
value
>
max_v
:
value
=
max_v
return
value
def
_flex_grow
(
style
:
Dict
[
str
,
Any
])
->
float
:
"""Return the effective `flex_grow` for a child.
Supports the React Native ``flex`` shorthand: a positive ``flex``
value implies ``flex_grow = flex``. ``flex_grow`` overrides the
shorthand if both are set.
"""
fg
=
style
.
get
(
"flex_grow"
)
if
fg
is
not
None
:
v
=
_to_float
(
fg
)
return
max
(
v
,
0.0
)
if
v
is
not
None
else
0.0
f
=
_to_float
(
style
.
get
(
"flex"
))
if
f
is
not
None
and
f
>
0
:
return
f
return
0.0
def
_flex_shrink
(
style
:
Dict
[
str
,
Any
])
->
float
:
"""Return the effective `flex_shrink` for a child.
Defaults to ``0`` for normal children, but a positive React Native
``flex`` shorthand implies ``flex_shrink = 1`` unless explicitly
overridden.
"""
fs
=
style
.
get
(
"flex_shrink"
)
if
fs
is
not
None
:
v
=
_to_float
(
fs
)
return
max
(
v
,
0.0
)
if
v
is
not
None
else
0.0
f
=
_to_float
(
style
.
get
(
"flex"
))
if
f
is
not
None
and
f
>
0
:
return
1.0
return
0.0
def
_flex_basis
(
style
:
Dict
[
str
,
Any
],
main_avail
:
float
)
->
Optional
[
float
]:
"""Return the effective `flex_basis` for a child, or ``None`` for ``"auto"``.
A bare numeric ``flex`` shorthand implies ``flex_basis = 0``
(matches RN), unless ``flex_basis`` is explicitly set.
"""
fb
=
style
.
get
(
"flex_basis"
)
if
fb
is
not
None
:
if
isinstance
(
fb
,
str
)
and
fb
.
strip
().
lower
()
==
"auto"
:
return
None
return
_resolve_value
(
fb
,
main_avail
)
f
=
_to_float
(
style
.
get
(
"flex"
))
if
f
is
not
None
and
f
>
0
:
return
0.0
return
None
def
_resolve_align
(
value
:
Any
,
default
:
str
=
ALIGN_STRETCH
)
->
str
:
"""Normalize an `align_items` / `align_self` value, applying aliases."""
if
value
is
None
:
return
default
s
=
str
(
value
)
return
_ALIGN_ALIASES
.
get
(
s
,
s
)
def
_resolve_justify
(
value
:
Any
)
->
str
:
"""Normalize a `justify_content` / `align_content` value, applying aliases."""
if
value
is
None
:
return
JUSTIFY_FLEX_START
s
=
str
(
value
)
return
_JUSTIFY_ALIASES
.
get
(
s
,
s
)
def
_resolve_gaps
(
style
:
Dict
[
str
,
Any
],
is_row
:
bool
)
->
Tuple
[
float
,
float
]:
"""Return ``(main_gap, cross_gap)`` for a container.
``column_gap`` is the horizontal gap and ``row_gap`` the vertical
gap (CSS semantics); ``spacing`` / ``gap`` set the main-axis gap
when the specific key is absent.
"""
generic
=
_to_float
(
style
.
get
(
"spacing"
))
if
generic
is
None
:
generic
=
_to_float
(
style
.
get
(
"gap"
))
col
=
_to_float
(
style
.
get
(
"column_gap"
))
row
=
_to_float
(
style
.
get
(
"row_gap"
))
if
is_row
:
main
=
col
if
col
is
not
None
else
generic
cross
=
row
else
:
main
=
row
if
row
is
not
None
else
generic
cross
=
col
return
(
main
or
0.0
,
cross
or
0.0
)
def
_wrap_mode
(
style
:
Dict
[
str
,
Any
])
->
str
:
mode
=
style
.
get
(
"flex_wrap"
)
if
mode
in
(
WRAP_WRAP
,
WRAP_REVERSE
):
return
str
(
mode
)
if
mode
==
"wrap-reverse"
:
return
WRAP_REVERSE
return
WRAP_NOWRAP
def
_resolve_direction
(
style
:
Dict
[
str
,
Any
],
inherited
:
str
)
->
str
:
own
=
style
.
get
(
"direction"
)
if
own
in
(
DIRECTION_LTR
,
DIRECTION_RTL
):
return
str
(
own
)
return
inherited
# ======================================================================
# LayoutNode
# ======================================================================
class
LayoutNode
:
"""A node in the layout tree.
Holds the layout-relevant style props, child layout nodes, and the
computed output (``x``, ``y``, ``width``, ``height`` in points
relative to the parent's coordinate space).
Attributes:
style: Dict of layout-relevant style props (a subset of the
element's full props; usually filtered through
[`LAYOUT_STYLE_KEYS`][pythonnative.layout.LAYOUT_STYLE_KEYS]).
children: Ordered list of child `LayoutNode`s.
measure: Optional measure callback for leaf nodes whose natural
size depends on their content (e.g., text). Receives
``(max_width, max_height)`` and returns ``(width, height)``.
Either argument may be ``math.inf``.
user_data: Free-form attribute the caller may use to associate
each layout node with the corresponding native view; the
engine itself does not inspect it.
dirty: When ``False``, the node may serve repeat measurements
from its memo (set by the reconciler's incremental-layout
cache). Fresh nodes start dirty.
x: Computed x-coordinate relative to the parent's coordinate
space.
y: Computed y-coordinate relative to the parent's coordinate
space.
width: Computed width in points.
height: Computed height in points.
"""
__slots__
=
(
"style"
,
"children"
,
"measure"
,
"user_data"
,
"dirty"
,
"x"
,
"y"
,
"width"
,
"height"
,
"_pn_scroll_axis"
,
"_measure_memo"
,
"_lines"
,
"_direction"
,
)
def
__init__
(
self
,
style
:
Optional
[
Dict
[
str
,
Any
]]
=
None
,
children
:
Optional
[
List
[
"LayoutNode"
]]
=
None
,
measure
:
Optional
[
MeasureFn
]
=
None
,
user_data
:
Any
=
None
,
)
->
None
:
self
.
style
=
style
or
{}
self
.
children
=
list
(
children
)
if
children
else
[]
self
.
measure
=
measure
self
.
user_data
=
user_data
self
.
dirty
:
bool
=
True
self
.
x
:
float
=
0.0
self
.
y
:
float
=
0.0
self
.
width
:
float
=
0.0
self
.
height
:
float
=
0.0
# ``"x"``/``"y"`` for scroll containers; ``None`` for everything
# else. Consumed by ``_measure_container`` to clamp the node's
# own main-axis size to the parent's available space while still
# measuring children unbounded on the scroll axis (which is what
# makes the native ``UIScrollView`` / Android ``ScrollView``
# actually scroll). The reconciler stamps this when building the
# layout tree for ``ScrollView`` elements.
self
.
_pn_scroll_axis
:
Optional
[
str
]
=
None
# Measurement memo: ``(avail_w, avail_h, forced_w, forced_h,
# direction, out_w, out_h)`` from the most recent measurement.
# Served when the node is clean (``dirty == False``) and the
# inputs match, skipping the entire subtree's flex math.
self
.
_measure_memo
:
Optional
[
Tuple
[
float
,
float
,
Optional
[
float
],
Optional
[
float
],
str
,
float
,
float
]]
=
None
# Flex lines computed during measurement, consumed by the
# positioning pass (single-line containers store one line).
self
.
_lines
:
Optional
[
List
[
"_FlexLine"
]]
=
None
# Resolved direction ("ltr" / "rtl") inherited at measure time.
self
.
_direction
:
str
=
DIRECTION_LTR
def
__repr__
(
self
)
->
str
:
return
(
f"LayoutNode(x=
{
self
.
x
:g
}
, y=
{
self
.
y
:g
}
, "
f"w=
{
self
.
width
:g
}
, h=
{
self
.
height
:g
}
, "
f"children=
{
len
(
self
.
children
)
}
)"
)
class
_FlexLine
:
"""One row/column of children produced by line partitioning."""
__slots__
=
(
"children"
,
"main_used"
,
"cross_size"
)
def
__init__
(
self
,
children
:
List
[
LayoutNode
])
->
None
:
self
.
children
=
children
self
.
main_used
:
float
=
0.0
self
.
cross_size
:
float
=
0.0
# ======================================================================
# Public entry point
# ======================================================================
def
calculate_layout
(
node
:
LayoutNode
,
available_width
:
float
,
available_height
:
float
,
direction
:
str
=
DIRECTION_LTR
,
)
->
None
:
"""Compute layout for `node` and all descendants, in place.
Sizes the root from its own style and content. Callers that want
the root to fill its viewport should wrap it in a synthetic outer
node with explicit ``width`` / ``height`` (the
[`Reconciler`][pythonnative.reconciler.Reconciler] does this when
running the layout pass after a commit).
Args:
node: Root of the layout tree.
available_width: Available width in points. Pass
``math.inf`` for unbounded (e.g., horizontal scroll).
available_height: Available height in points. Pass
``math.inf`` for unbounded (e.g., vertical scroll).
direction: Base writing direction (``"ltr"`` or ``"rtl"``)
inherited by nodes that don't set their own.
"""
_measure_node
(
node
,
available_width
,
available_height
,
direction
=
direction
)
node
.
x
=
0.0
node
.
y
=
0.0
_position_children
(
node
)
# ======================================================================
# Measurement: top-down sizing
# ======================================================================
def
_measure_node
(
node
:
LayoutNode
,
avail_w
:
float
,
avail_h
:
float
,
forced_w
:
Optional
[
float
]
=
None
,
forced_h
:
Optional
[
float
]
=
None
,
direction
:
str
=
DIRECTION_LTR
,
)
->
None
:
"""Compute ``node.width`` / ``node.height`` and recursively size children.
Args:
node: Node to measure.
avail_w: Available width (constraint, never a forced value).
avail_h: Available height (constraint, never a forced value).
forced_w: If set, overrides any width computed from style or
content. Used by parents to enforce flex distribution or
cross-axis stretch.
forced_h: As ``forced_w`` but for height.
direction: Writing direction inherited from the parent.
"""
style
=
node
.
style
resolved_direction
=
_resolve_direction
(
style
,
direction
)
# Incremental-layout memo: a clean node measured under identical
# inputs reuses its previous result without recursing; its whole
# subtree keeps the sizes from the prior pass.
memo
=
node
.
_measure_memo
if
(
memo
is
not
None
and
not
node
.
dirty
and
memo
[
0
]
==
avail_w
and
memo
[
1
]
==
avail_h
and
memo
[
2
]
==
forced_w
and
memo
[
3
]
==
forced_h
and
memo
[
4
]
==
resolved_direction
):
node
.
width
=
memo
[
5
]
node
.
height
=
memo
[
6
]
return
node
.
_direction
=
resolved_direction
explicit_w
=
forced_w
if
forced_w
is
not
None
else
_resolve_value
(
style
.
get
(
"width"
),
avail_w
)
explicit_h
=
forced_h
if
forced_h
is
not
None
else
_resolve_value
(
style
.
get
(
"height"
),
avail_h
)
aspect
=
_to_float
(
style
.
get
(
"aspect_ratio"
))
if
aspect
is
not
None
and
aspect
>
0
:
if
explicit_w
is
not
None
and
explicit_h
is
None
:
explicit_h
=
explicit_w
/
aspect
elif
explicit_h
is
not
None
and
explicit_w
is
None
:
explicit_w
=
explicit_h
*
aspect
explicit_w
=
_clamp
(
explicit_w
,
style
.
get
(
"min_width"
),
style
.
get
(
"max_width"
),
avail_w
)
explicit_h
=
_clamp
(
explicit_h
,
style
.
get
(
"min_height"
),
style
.
get
(
"max_height"
),
avail_h
)
if
node
.
children
:
width
,
height
=
_measure_container
(
node
,
avail_w
,
avail_h
,
explicit_w
,
explicit_h
)
elif
node
.
measure
is
not
None
:
width
,
height
=
_measure_leaf
(
node
,
avail_w
,
avail_h
,
explicit_w
,
explicit_h
,
aspect
)
else
:
width
=
explicit_w
if
explicit_w
is
not
None
else
0.0
height
=
explicit_h
if
explicit_h
is
not
None
else
0.0
if
aspect
is
not
None
and
aspect
>
0
:
if
explicit_w
is
None
and
explicit_h
is
not
None
and
width
<=
0
:
width
=
height
*
aspect
elif
explicit_h
is
None
and
explicit_w
is
not
None
and
height
<=
0
:
height
=
width
/
aspect
width_clamped
=
_clamp
(
width
,
style
.
get
(
"min_width"
),
style
.
get
(
"max_width"
),
avail_w
)
height_clamped
=
_clamp
(
height
,
style
.
get
(
"min_height"
),
style
.
get
(
"max_height"
),
avail_h
)
width
=
width_clamped
if
width_clamped
is
not
None
else
0.0
height
=
height_clamped
if
height_clamped
is
not
None
else
0.0
node
.
width
=
max
(
width
,
0.0
)
node
.
height
=
max
(
height
,
0.0
)
node
.
_measure_memo
=
(
avail_w
,
avail_h
,
forced_w
,
forced_h
,
resolved_direction
,
node
.
width
,
node
.
height
)
def
_measure_leaf
(
node
:
LayoutNode
,
avail_w
:
float
,
avail_h
:
float
,
explicit_w
:
Optional
[
float
],
explicit_h
:
Optional
[
float
],
aspect
:
Optional
[
float
],
)
->
Tuple
[
float
,
float
]:
"""Measure a leaf node by invoking its `measure` callback."""
assert
node
.
measure
is
not
None
max_w
=
explicit_w
if
explicit_w
is
not
None
else
avail_w
max_h
=
explicit_h
if
explicit_h
is
not
None
else
avail_h
try
:
mw
,
mh
=
node
.
measure
(
max_w
,
max_h
)
except
Exception
:
mw
,
mh
=
0.0
,
0.0
width
=
explicit_w
if
explicit_w
is
not
None
else
float
(
mw
)
height
=
explicit_h
if
explicit_h
is
not
None
else
float
(
mh
)
if
aspect
is
not
None
and
aspect
>
0
:
if
explicit_w
is
None
and
explicit_h
is
None
:
height
=
width
/
aspect
return
width
,
height
def
_measure_container
(
node
:
LayoutNode
,
avail_w
:
float
,
avail_h
:
float
,
explicit_w
:
Optional
[
float
],
explicit_h
:
Optional
[
float
],
)
->
Tuple
[
float
,
float
]:
"""Layout flex children and determine the container's own size."""
style
=
node
.
style
direction
=
node
.
_direction
base_w
=
explicit_w
if
explicit_w
is
not
None
else
avail_w
base_h
=
explicit_h
if
explicit_h
is
not
None
else
avail_h
pad_l
,
pad_t
,
pad_r
,
pad_b
=
_resolve_padding_for
(
style
,
base_w
,
base_h
,
"padding"
,
direction
)
pad_x
=
pad_l
+
pad_r
pad_y
=
pad_t
+
pad_b
content_w
=
(
explicit_w
-
pad_x
)
if
explicit_w
is
not
None
else
max
(
0.0
,
avail_w
-
pad_x
)
content_h
=
(
explicit_h
-
pad_y
)
if
explicit_h
is
not
None
else
max
(
0.0
,
avail_h
-
pad_y
)
is_row
=
_is_row
(
style
.
get
(
"flex_direction"
,
FLEX_DIRECTION_COLUMN
))
main_bounded
=
(
explicit_w
is
not
None
)
if
is_row
else
(
explicit_h
is
not
None
)
cross_bounded
=
(
explicit_h
is
not
None
)
if
is_row
else
(
explicit_w
is
not
None
)
used_main
,
used_cross
=
_layout_flex_children
(
node
,
content_w
,
content_h
,
main_bounded
=
main_bounded
,
cross_bounded
=
cross_bounded
,
)
if
is_row
:
used_w
,
used_h
=
used_main
,
used_cross
else
:
used_w
,
used_h
=
used_cross
,
used_main
width
=
explicit_w
if
explicit_w
is
not
None
else
(
used_w
+
pad_x
)
height
=
explicit_h
if
explicit_h
is
not
None
else
(
used_h
+
pad_y
)
# Scroll containers: clamp the container's own main-axis size to the
# parent's available space when no explicit size was provided. The
# children are still measured against an unbounded main-axis (handled
# via the wrapper inserted in ``Reconciler._build_layout_tree``) so the
# overflow becomes the scrollable region. Without this clamp, the
# container would grow to fit its content and there would be no
# overflow for the native ScrollView to scroll. Skipped when the
# parent is itself unbounded, so nested scroll views still fall back
# to natural sizing (the inner scroll is unscrollable in that case,
# which matches the behavior in React Native).
scroll_axis
=
getattr
(
node
,
"_pn_scroll_axis"
,
None
)
if
scroll_axis
==
"y"
and
explicit_h
is
None
and
math
.
isfinite
(
avail_h
):
height
=
avail_h
elif
scroll_axis
==
"x"
and
explicit_w
is
None
and
math
.
isfinite
(
avail_w
):
width
=
avail_w
return
width
,
height
# ======================================================================
# Flex algorithm
# ======================================================================
def
_child_main_size
(
child
:
LayoutNode
,
is_row
:
bool
)
->
float
:
return
child
.
width
if
is_row
else
child
.
height
def
_child_cross_size
(
child
:
LayoutNode
,
is_row
:
bool
)
->
float
:
return
child
.
height
if
is_row
else
child
.
width
def
_child_margins
(
child
:
LayoutNode
,
parent_w
:
float
,
parent_h
:
float
,
direction
:
str
,
)
->
Tuple
[
float
,
float
,
float
,
float
]:
return
_resolve_padding_for
(
child
.
style
,
parent_w
,
parent_h
,
"margin"
,
direction
)
def
_child_outer_main
(
child
:
LayoutNode
,
is_row
:
bool
,
parent_w
:
float
,
parent_h
:
float
,
direction
:
str
,
)
->
float
:
"""Main-axis extent including margins."""
margins
=
_child_margins
(
child
,
parent_w
,
parent_h
,
direction
)
margin_main
=
(
margins
[
0
]
+
margins
[
2
])
if
is_row
else
(
margins
[
1
]
+
margins
[
3
])
return
_child_main_size
(
child
,
is_row
)
+
margin_main
def
_child_outer_cross
(
child
:
LayoutNode
,
is_row
:
bool
,
parent_w
:
float
,
parent_h
:
float
,
direction
:
str
,
)
->
float
:
margins
=
_child_margins
(
child
,
parent_w
,
parent_h
,
direction
)
margin_cross
=
(
margins
[
1
]
+
margins
[
3
])
if
is_row
else
(
margins
[
0
]
+
margins
[
2
])
return
_child_cross_size
(
child
,
is_row
)
+
margin_cross
def
_measure_child_flexed
(
child
:
LayoutNode
,
main_size
:
Optional
[
float
],
cross_avail
:
float
,
cross_force
:
Optional
[
float
],
is_row
:
bool
,
main_bounded
:
bool
,
direction
:
str
,
)
->
None
:
"""Re-measure a child with optional forced main-axis size and cross hint."""
fallback_main
=
math
.
inf
if
not
main_bounded
else
cross_avail
if
is_row
:
avail_w
=
main_size
if
main_size
is
not
None
else
fallback_main
_measure_node
(
child
,
avail_w
,
cross_avail
,
forced_w
=
main_size
,
forced_h
=
cross_force
,
direction
=
direction
)
else
:
avail_h
=
main_size
if
main_size
is
not
None
else
fallback_main
_measure_node
(
child
,
cross_avail
,
avail_h
,
forced_w
=
cross_force
,
forced_h
=
main_size
,
direction
=
direction
)
def
_resolve_cross_force
(
child
:
LayoutNode
,
parent_align
:
str
,
cross_avail
:
float
,
cross_bounded
:
bool
,
is_row
:
bool
,
direction
:
str
,
)
->
Optional
[
float
]:
"""Compute the cross-axis size to force on a child, or ``None`` to let it size naturally.
Cross-axis stretch only applies when:
1. The child's effective alignment is ``stretch``.
2. The parent's cross axis is bounded (so we have a target size).
3. The child does not have its own explicit cross-axis dimension.
"""
if
not
cross_bounded
or
not
math
.
isfinite
(
cross_avail
):
return
None
align
=
_resolve_align
(
child
.
style
.
get
(
"align_self"
),
default
=
parent_align
)
if
align
!=
ALIGN_STRETCH
:
return
None
cross_key
=
"height"
if
is_row
else
"width"
if
cross_key
in
child
.
style
and
child
.
style
.
get
(
cross_key
)
is
not
None
:
return
None
margins
=
_child_margins
(
child
,
cross_avail
,
cross_avail
,
direction
)
margin_cross
=
(
margins
[
1
]
+
margins
[
3
])
if
is_row
else
(
margins
[
0
]
+
margins
[
2
])
return
max
(
0.0
,
cross_avail
-
margin_cross
)
def
_layout_flex_children
(
parent
:
LayoutNode
,
content_w
:
float
,
content_h
:
float
,
main_bounded
:
bool
,
cross_bounded
:
bool
,
)
->
Tuple
[
float
,
float
]:
"""Layout the in-flow children of `parent` along the flex axes.
Children are measured, partitioned into flex lines (one line unless
``flex_wrap`` is enabled), grown/shrunk per line, and stretched to
their line's cross size. The computed line structure is stored on
``parent._lines`` for the positioning pass.
Returns ``(used_main, used_cross)``, the total content size used
by the in-flow children, including inter-child gaps but excluding
the parent's own padding. The caller adds padding back in for the
container's outer size.
"""
style
=
parent
.
style
flex_direction
=
style
.
get
(
"flex_direction"
,
FLEX_DIRECTION_COLUMN
)
is_row
=
_is_row
(
flex_direction
)
direction
=
parent
.
_direction
main_avail
=
content_w
if
is_row
else
content_h
cross_avail
=
content_h
if
is_row
else
content_w
main_gap
,
cross_gap
=
_resolve_gaps
(
style
,
is_row
)
wrap
=
_wrap_mode
(
style
)
wrapping
=
wrap
!=
WRAP_NOWRAP
and
main_bounded
and
math
.
isfinite
(
main_avail
)
in_flow
:
List
[
LayoutNode
]
=
[]
absolute
:
List
[
LayoutNode
]
=
[]
for
child
in
parent
.
children
:
if
child
.
style
.
get
(
"position"
)
==
POSITION_ABSOLUTE
:
absolute
.
append
(
child
)
else
:
in_flow
.
append
(
child
)
align_items
=
_resolve_align
(
style
.
get
(
"align_items"
),
default
=
ALIGN_STRETCH
)
# ------------------------------------------------------------------
# Pass 1: initial measurement (basis for grow children, natural
# size otherwise). Single-line containers stretch against the full
# cross axis here (matching the nowrap fast path); wrapping
# containers defer stretching until line cross sizes are known.
# ------------------------------------------------------------------
for
child
in
in_flow
:
grow
=
_flex_grow
(
child
.
style
)
basis
=
_flex_basis
(
child
.
style
,
main_avail
)
cross_force
=
(
None
if
wrapping
else
_resolve_cross_force
(
child
,
align_items
,
cross_avail
,
cross_bounded
,
is_row
,
direction
)
)
if
grow
>
0
:
initial_main
=
basis
if
basis
is
not
None
else
0.0
_measure_child_flexed
(
child
,
initial_main
,
cross_avail
,
cross_force
,
is_row
,
main_bounded
,
direction
)
elif
basis
is
not
None
:
_measure_child_flexed
(
child
,
basis
,
cross_avail
,
cross_force
,
is_row
,
main_bounded
,
direction
)
else
:
avail_for_child_main
=
math
.
inf
if
not
main_bounded
else
main_avail
if
is_row
:
_measure_node
(
child
,
avail_for_child_main
,
cross_avail
,
forced_h
=
cross_force
,
direction
=
direction
)
else
:
_measure_node
(
child
,
cross_avail
,
avail_for_child_main
,
forced_w
=
cross_force
,
direction
=
direction
)
# ------------------------------------------------------------------
# Pass 2: partition children into flex lines.
# ------------------------------------------------------------------
lines
:
List
[
_FlexLine
]
=
[]
if
wrapping
:
current
:
List
[
LayoutNode
]
=
[]
current_main
=
0.0
for
child
in
in_flow
:
outer
=
_child_outer_main
(
child
,
is_row
,
content_w
,
content_h
,
direction
)
extra
=
outer
if
not
current
else
outer
+
main_gap
if
current
and
current_main
+
extra
>
main_avail
+
1e-9
:
lines
.
append
(
_FlexLine
(
current
))
current
=
[
child
]
current_main
=
outer
else
:
current
.
append
(
child
)
current_main
+=
extra
if
current
:
lines
.
append
(
_FlexLine
(
current
))
elif
in_flow
:
lines
.
append
(
_FlexLine
(
list
(
in_flow
)))
# ------------------------------------------------------------------
# Pass 3: per-line grow / shrink along the main axis.
# ------------------------------------------------------------------
for
line
in
lines
:
flex_total
=
0.0
fixed_main_total
=
0.0
flex_basis_total
=
0.0
flex_entries
:
List
[
Tuple
[
LayoutNode
,
float
,
Optional
[
float
]]]
=
[]
for
child
in
line
.
children
:
grow
=
_flex_grow
(
child
.
style
)
if
grow
>
0
:
basis
=
_flex_basis
(
child
.
style
,
main_avail
)
or
0.0
margins
=
_child_margins
(
child
,
content_w
,
content_h
,
direction
)
margin_main
=
(
margins
[
0
]
+
margins
[
2
])
if
is_row
else
(
margins
[
1
]
+
margins
[
3
])
flex_total
+=
grow
flex_basis_total
+=
basis
+
margin_main
flex_entries
.
append
((
child
,
grow
,
basis
))
else
:
fixed_main_total
+=
_child_outer_main
(
child
,
is_row
,
content_w
,
content_h
,
direction
)
if
len
(
line
.
children
)
>
1
:
fixed_main_total
+=
main_gap
*
(
len
(
line
.
children
)
-
1
)
if
flex_total
>
0
and
main_bounded
and
math
.
isfinite
(
main_avail
):
remaining
=
max
(
0.0
,
main_avail
-
fixed_main_total
-
flex_basis_total
)
for
child
,
grow
,
basis
in
flex_entries
:
extra
=
(
grow
/
flex_total
)
*
remaining
child_main
=
(
basis
or
0.0
)
+
extra
cross_force
=
(
None
if
wrapping
else
_resolve_cross_force
(
child
,
align_items
,
cross_avail
,
cross_bounded
,
is_row
,
direction
)
)
_measure_child_flexed
(
child
,
child_main
,
cross_avail
,
cross_force
,
is_row
,
main_bounded
,
direction
)
if
main_bounded
and
math
.
isfinite
(
main_avail
):
total_main
=
sum
(
_child_outer_main
(
c
,
is_row
,
content_w
,
content_h
,
direction
)
for
c
in
line
.
children
)
if
len
(
line
.
children
)
>
1
:
total_main
+=
main_gap
*
(
len
(
line
.
children
)
-
1
)
overflow
=
total_main
-
main_avail
if
overflow
>
0
:
shrinks
=
[(
c
,
_flex_shrink
(
c
.
style
))
for
c
in
line
.
children
]
total_shrink
=
sum
(
s
*
_child_main_size
(
c
,
is_row
)
for
c
,
s
in
shrinks
)
if
total_shrink
>
0
:
for
child
,
shrink
in
shrinks
:
if
shrink
<=
0
:
continue
take
=
(
shrink
*
_child_main_size
(
child
,
is_row
)
/
total_shrink
)
*
overflow
new_main
=
max
(
0.0
,
_child_main_size
(
child
,
is_row
)
-
take
)
cross_force
=
(
None
if
wrapping
else
_resolve_cross_force
(
child
,
align_items
,
cross_avail
,
cross_bounded
,
is_row
,
direction
)
)
_measure_child_flexed
(
child
,
new_main
,
cross_avail
,
cross_force
,
is_row
,
main_bounded
,
direction
)
line
.
main_used
=
sum
(
_child_outer_main
(
c
,
is_row
,
content_w
,
content_h
,
direction
)
for
c
in
line
.
children
)
if
len
(
line
.
children
)
>
1
:
line
.
main_used
+=
main_gap
*
(
len
(
line
.
children
)
-
1
)
View remainder of file in raw view
Back
|
FazBrowse Home
|
New Git URL