blit-ui 0.1.0

an experimental immediate-mode ui library
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
use crate::*;

pub trait Layout<C: Context>: 'static {
    /// per child data interpreted by this layout
    /// children without explicit items share this type's default value
    type Item: Default + 'static;

    /// smallest and natural content extents along an axis
    fn fit(&self, cx: &mut LayoutCx<'_, C, Self::Item>, axis: Axis) -> Fit<C::Scalar>;

    /// splits this node's final content extent and positions children along an axis
    fn distribute(&self, cx: &mut LayoutCx<'_, C, Self::Item>, axis: Axis, extent: C::Scalar);
}

/// overlaps children at the content origin
impl<C: Context> Layout<C> for () {
    type Item = ();

    fn fit(&self, cx: &mut LayoutCx<'_, C, ()>, axis: Axis) -> Fit<C::Scalar> {
        let mut extent = Fit::ZERO;
        for child in cx.children() {
            extent = extent.max(cx.fit(child, axis));
        }
        extent
    }

    fn distribute(&self, cx: &mut LayoutCx<'_, C, ()>, _axis: Axis, extent: C::Scalar) {
        for child in cx.children() {
            cx.set_extent(child, extent);
            cx.set_offset(child, C::Scalar::ZERO);
        }
    }
}

/// positions a node outside its parent's flow
pub trait Place<C: Context>: 'static {
    /// returns this node's frame position
    fn place(&self, cx: &mut PlaceCx<'_, C>, target: Rect<C::Scalar>) -> Point<C::Scalar>;
}

/// places at the target's origin under unbounded constraints
impl<C: Context> Place<C> for () {
    fn place(&self, cx: &mut PlaceCx<'_, C>, target: Rect<C::Scalar>) -> Point<C::Scalar> {
        cx.resolve(Constraints::loose(Size::uniform(C::Scalar::UNBOUNDED)));
        Point::new(target.x, target.y)
    }
}

/// smallest and natural content extents
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Fit<T> {
    /// smallest extent before content overflows
    pub min: T,
    /// extent the content wants
    pub natural: T,
}

impl<T> Fit<T> {
    #[inline]
    pub const fn new(min: T, natural: T) -> Self {
        Self { min, natural }
    }

    #[inline]
    pub const fn exact(extent: T) -> Self
    where
        T: Copy,
    {
        Self {
            min: extent,
            natural: extent,
        }
    }
}

impl<T: Copy> From<T> for Fit<T> {
    #[inline]
    fn from(extent: T) -> Self {
        Self::exact(extent)
    }
}

impl<T: Scalar> core::ops::Add for Fit<T> {
    type Output = Self;

    #[inline]
    fn add(self, rhs: Self) -> Self {
        Self {
            min: self.min + rhs.min,
            natural: self.natural + rhs.natural,
        }
    }
}

impl<T: Scalar> core::ops::AddAssign for Fit<T> {
    #[inline]
    fn add_assign(&mut self, rhs: Self) {
        self.min += rhs.min;
        self.natural += rhs.natural;
    }
}

impl<T: Scalar> Fit<T> {
    pub const ZERO: Self = Self {
        min: T::ZERO,
        natural: T::ZERO,
    };

    #[inline]
    pub fn max(self, other: Self) -> Self {
        Self {
            min: self.min.max(other.min),
            natural: self.natural.max(other.natural),
        }
    }

    #[inline]
    pub fn clamp(self, min: T, max: T) -> Self {
        Self {
            min: self.min.clamp(min, max),
            natural: self.natural.clamp(min, max),
        }
    }

    #[inline]
    pub fn endpoint(self, offset: T) -> Self {
        Self {
            min: self.min.endpoint(offset),
            natural: self.natural.endpoint(offset),
        }
    }
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Axis {
    Horizontal,
    #[default]
    Vertical,
}

impl Axis {
    #[inline]
    pub const fn other(self) -> Self {
        match self {
            Self::Horizontal => Self::Vertical,
            Self::Vertical => Self::Horizontal,
        }
    }

    #[inline]
    pub fn extent<T: Copy>(self, size: Size<T>) -> T {
        match self {
            Self::Horizontal => size.width,
            Self::Vertical => size.height,
        }
    }

    #[inline]
    pub fn set_extent<T>(self, size: &mut Size<T>, extent: T) {
        match self {
            Self::Horizontal => size.width = extent,
            Self::Vertical => size.height = extent,
        }
    }
}

#[repr(transparent)]
pub struct LayoutCx<'a, C: Context, I = ()> {
    inner: LayoutCxInner<'a, C>,
    item: PhantomData<fn() -> I>,
}

impl<'a, C: Context, I: 'static> LayoutCx<'a, C, I> {
    pub fn node(&self) -> NodeId {
        self.inner.node
    }

    pub fn size(&self, child: NodeId) -> Size<C::Scalar> {
        self.inner.placements[child.index()].size()
    }

    #[inline]
    pub fn fit(&self, child: NodeId, axis: Axis) -> Fit<C::Scalar> {
        axis.extent(self.inner.fits[child.index() - self.inner.root.index()])
    }

    #[inline]
    pub fn children(&self) -> Children<'a> {
        Children {
            nodes: &self.inner.tree.nodes[..=self.inner.tree.nodes[self.inner.node.index()].subtree_end as usize],
            next: NodeId::new(self.inner.node.index() + 1),
        }
    }

    #[inline]
    pub fn item(&self, child: NodeId) -> &'a I {
        let stored = &self.inner.tree.nodes[child.index()];
        // other nodes may store items of another type
        assert_eq!(stored.parent, self.inner.node, "layout items belong to direct children");
        let id = stored.item;
        self.inner.bump.load(if id.offset().is_some() {
            id
        } else {
            self.inner.default_item
        })
    }

    /// the extent a child resolves to regardless of bounds from motion or exact limits
    #[inline(always)]
    pub fn fixed_extent(&self, child: NodeId, axis: Axis) -> Option<C::Scalar> {
        self.inner.fixed_extent(child, axis)
    }

    /// this node's inner extent on the other axis
    ///
    /// in fit(Y) this is the final inner width. in fit(X) this returns the own height limit
    /// when bounded (else unbounded) on round 0 and triggers a relayout round with settled heights
    #[inline(always)]
    pub fn across(&mut self) -> C::Scalar {
        self.inner.across()
    }

    #[inline(always)]
    pub fn set_extent(&mut self, child: NodeId, extent: C::Scalar) -> C::Scalar {
        self.inner.set_extent(child, extent)
    }

    #[inline(always)]
    pub fn set_offset(&mut self, child: NodeId, offset: C::Scalar) {
        self.inner.set_offset(child, offset);
    }

    pub fn request_frame(&mut self) {
        *self.inner.frame_requested = true;
    }

    pub fn context(&self) -> &C {
        self.inner.context
    }

    pub fn context_mut(&mut self) -> &mut C {
        self.inner.context
    }

    pub fn scratch(&self) -> &'a ScratchBuffer {
        &self.inner.bump.storage
    }

    #[inline(always)]
    pub fn set_child_z_index(&mut self, child: NodeId, z_index: i16) {
        self.inner.set_child_z_index(child, z_index);
    }
}

/// resolves an out of flow node after all flow layout
pub struct PlaceCx<'a, C: Context> {
    tree: &'a Tree<C>,
    bump: &'a BumpArena,
    placements: &'a mut [Rect<C::Scalar>],
    z_indices: &'a mut Vec<i16>,
    has_custom_order: &'a mut bool,
    context: &'a mut C,
    frame_requested: &'a mut bool,
    animated: &'a [MotionProps],
    node: NodeId,
    parent: Size<C::Scalar>,
}

impl<C: Context> PlaceCx<'_, C> {
    pub fn node(&self) -> NodeId {
        self.node
    }

    /// the visual parent's size
    pub fn parent(&self) -> Size<C::Scalar> {
        self.parent
    }

    pub fn screen(&self) -> Rect<C::Scalar> {
        self.tree.screen
    }

    /// lays out this node and returns its current size
    pub fn resolve(&mut self, bounds: Constraints<C::Scalar>) -> Size<C::Scalar> {
        solve_subtree(
            self.tree,
            self.bump,
            self.placements,
            self.z_indices,
            self.has_custom_order,
            self.context,
            self.frame_requested,
            self.animated,
            self.node,
            bounds,
        )
    }

    pub fn request_frame(&mut self) {
        *self.frame_requested = true;
    }

    pub fn context(&self) -> &C {
        self.context
    }

    pub fn context_mut(&mut self) -> &mut C {
        self.context
    }
}

/// flow children of a node in build order, skipping nodes positioned with [`Place`]
#[derive(Clone, Copy)]
pub struct Children<'a> {
    nodes: &'a [StoredNode],
    next: NodeId,
}

impl Iterator for Children<'_> {
    type Item = NodeId;

    #[inline]
    fn next(&mut self) -> Option<NodeId> {
        while self.next.index() < self.nodes.len() {
            let node = self.next;
            let stored = &self.nodes[node.index()];
            self.next = NodeId::new(stored.subtree_end as usize + 1);
            if stored.place.index().is_none() {
                return Some(node);
            }
        }
        None
    }
}

//
// internals
//

struct LayoutCxInner<'a, C: Context> {
    tree: &'a Tree<C>,
    bump: &'a BumpArena,
    placements: &'a mut [Rect<C::Scalar>],
    z_indices: &'a mut Vec<i16>,
    has_custom_order: &'a mut bool,
    fits: &'a mut [Size<Fit<C::Scalar>>],
    context: &'a mut C,
    frame_requested: &'a mut bool,
    // size channels a motion animates, by node index
    animated: &'a [MotionProps],
    root: NodeId,
    node: NodeId,
    axis: Axis,
    across: C::Scalar,
    round: u8,
    relayout: bool,
    squeezed: bool,
    content_origin: Point<C::Scalar>,
    default_item: BumpId,
}

impl<'a, C: Context> LayoutCxInner<'a, C> {
    #[inline(always)]
    fn as_cx<J>(&mut self) -> &mut LayoutCx<'a, C, J> {
        // safety: LayoutCx is repr(transparent) over LayoutCxInner
        unsafe { &mut *core::ptr::from_mut(self).cast::<LayoutCx<'a, C, J>>() }
    }

    fn fixed_extent(&self, child: NodeId, axis: Axis) -> Option<C::Scalar> {
        let stored = &self.tree.nodes[child.index()];
        self.size_override(child, axis).or_else(|| {
            let limits = self.tree.aux[stored.aux.index()?].limits;
            let min = axis.extent(limits.min);
            (min == axis.extent(limits.max)).then_some(min)
        })
    }

    fn across(&mut self) -> C::Scalar {
        if self.axis == Axis::Vertical {
            return self.across;
        }
        let pad = self.padding(self.node).size().height;
        if self.round > 0 {
            return (self.placements[self.node.index()].height - pad).max(C::Scalar::ZERO);
        }
        self.relayout = true;
        let max = self.size_override(self.node, Axis::Vertical).or_else(|| {
            let max = self.limits(self.node).max.height;
            max.is_finite().then_some(max)
        });
        max.map_or(C::Scalar::UNBOUNDED, |height| (height - pad).max(C::Scalar::ZERO))
    }

    #[inline]
    fn set_extent(&mut self, child: NodeId, extent: C::Scalar) -> C::Scalar {
        let clamped = self.constrain(child, self.axis, extent.max(C::Scalar::ZERO));
        let area = &mut self.placements[child.index()];
        match self.axis {
            Axis::Horizontal => {
                area.width = clamped;
                if clamped < self.fits[child.index() - self.root.index()].width.natural {
                    self.squeezed = true;
                }
            }
            Axis::Vertical => area.height = clamped,
        }
        clamped
    }

    #[inline]
    fn set_offset(&mut self, child: NodeId, offset: C::Scalar) {
        let area = &mut self.placements[child.index()];
        match self.axis {
            Axis::Horizontal => area.x = offset.endpoint(self.content_origin.x),
            Axis::Vertical => area.y = offset.endpoint(self.content_origin.y),
        }
    }

    fn set_child_z_index(&mut self, child: NodeId, z_index: i16) {
        if z_index != 0 {
            *self.has_custom_order = true;
        } else if self.z_indices.is_empty() {
            return;
        }
        let index = child.index();
        if self.z_indices.len() <= index {
            self.z_indices.resize(index + 1, 0);
        }
        self.z_indices[index] = z_index;
    }

    fn distribute_axis(&mut self, axis: Axis, containers: &[u32], start: usize, bounds: Constraints<C::Scalar>) {
        let root_fit = axis
            .extent(self.fits[0])
            .natural
            .clamp(axis.extent(bounds.min), axis.extent(bounds.max));
        match axis {
            Axis::Horizontal => {
                self.placements[start].width = root_fit;
                if root_fit < self.fits[0].width.natural {
                    self.squeezed = true;
                }
            }
            Axis::Vertical => self.placements[start].height = root_fit,
        }
        // containers are collected in reverse pre-order, so iterating in reverse visits parents first
        for &index in containers.iter().rev() {
            let index = index as usize;
            let stored = &self.tree.nodes[index];
            let node = NodeId::new(index);
            let padding = self.padding(node);
            let pad = padding.size();
            let size = self.placements[index].size();
            let inner_w = (size.width - pad.width).max(C::Scalar::ZERO);
            let inner = (axis.extent(size) - axis.extent(pad)).max(C::Scalar::ZERO);
            let kind = &self.tree.layout_kinds[stored.layout_kind as usize];
            self.node = node;
            self.axis = axis;
            self.across = inner_w;
            self.content_origin = Point::new(padding.left.min(size.width), padding.top.min(size.height));
            self.default_item = kind.default_item;
            (kind.distribute)(self.as_cx(), stored.layout, axis, inner);
        }
    }

    #[inline]
    fn run_fit(&mut self, node: NodeId, axis: Axis, across: C::Scalar) -> Fit<C::Scalar> {
        let stored = &self.tree.nodes[node.index()];
        let kind = &self.tree.layout_kinds[stored.layout_kind as usize];
        self.node = node;
        self.axis = axis;
        self.across = across;
        self.default_item = kind.default_item;
        let fit = (kind.fit)(self.as_cx(), stored.layout, axis);
        Fit {
            min: fit.min.min(fit.natural),
            natural: fit.natural,
        }
    }

    #[inline]
    fn measure(&mut self, node: NodeId, constraints: Constraints<C::Scalar>) -> Size<Fit<C::Scalar>> {
        if constraints.min == constraints.max {
            return Size::new(Fit::exact(constraints.min.width), Fit::exact(constraints.min.height));
        }
        let mut measure = self.tree.nodes[node.index()].first_measure;
        let mut fit = Fit::exact(Size::ZERO);
        while let Some(index) = measure.index() {
            let stored = self.tree.measures[index];
            let next = (stored.run)(self.bump, stored.bump_id, self.context, constraints);
            fit.min = fit.min.max(next.min);
            fit.natural = fit.natural.max(next.natural);
            measure = stored.next;
        }
        let natural = constraints.constrain(fit.natural);
        let min = constraints.constrain(fit.min);
        Size::new(
            Fit::new(min.width.min(natural.width), natural.width),
            Fit::new(min.height.min(natural.height), natural.height),
        )
    }

    #[inline]
    fn constrain(&self, node: NodeId, axis: Axis, value: C::Scalar) -> C::Scalar {
        if let Some(fixed) = self.size_override(node, axis) {
            return fixed;
        }
        let Some(index) = self.tree.nodes[node.index()].aux.index() else {
            return value;
        };
        let limits = self.tree.aux[index].limits;
        value.clamp(axis.extent(limits.min), axis.extent(limits.max))
    }

    #[inline]
    fn size_override(&self, node: NodeId, axis: Axis) -> Option<C::Scalar> {
        let &props = self.animated.get(node.index())?;
        let flag = match axis {
            Axis::Horizontal => MotionProps::WIDTH,
            Axis::Vertical => MotionProps::HEIGHT,
        };
        props
            .intersects(flag)
            .then(|| axis.extent(self.placements[node.index()].size()))
    }

    #[inline]
    fn padding(&self, node: NodeId) -> Sides<C::Scalar> {
        self.tree.nodes[node.index()]
            .aux
            .index()
            .map_or(Sides::all(C::Scalar::ZERO), |index| self.tree.aux[index].padding)
    }

    #[inline]
    fn limits(&self, node: NodeId) -> Constraints<C::Scalar> {
        self.tree.nodes[node.index()]
            .aux
            .index()
            .map_or(Constraints::loose(Size::uniform(C::Scalar::UNBOUNDED)), |index| {
                self.tree.aux[index].limits
            })
    }
}

/// resolves layout motion against a subtree's target layout
///
/// - layout first establishes final areas
/// - size animation updates placements and replays layout
/// - position animation applies after layout without replay
pub fn resolve<C: Context>(
    tree: &mut Tree<C>,
    bump: &BumpArena,
    context: &mut C,
    root: NodeId,
    bounds: Constraints<C::Scalar>,
    commit: bool,
) -> Size<C::Scalar> {
    // placements start here rather than with each node as building never reads them
    tree.placements.resize(tree.nodes.len(), Rect::default());
    let mut size = arrange(tree, bump, context, root, bounds, &[]);
    if tree.node_motions.is_empty() {
        return size;
    }
    let start = root.index();
    let end = tree.nodes[start].subtree_end as usize + 1;
    let nodes = &tree.nodes[..end];
    // size channels by node index, taken once a motion animates a size
    let mut sizes = None;
    let mut index = start;
    while index < end {
        let stored = &nodes[index];
        if !commit && start != 0 && stored.place.index().is_some() {
            index = stored.subtree_end as usize + 1;
            continue;
        }
        index += 1;
        let Some(record) = stored.aux.index().and_then(|aux| tree.aux[aux].motion.index()) else {
            continue;
        };
        let NodeMotion {
            node,
            motion: mut config,
        } = tree.node_motions[record];
        if !commit && !config.properties.intersects(MotionProps::SIZE) {
            continue;
        }
        let id = stored.id;
        if stored.parent == node {
            config.properties = config
                .properties
                .intersection(MotionProps::POSITION | MotionProps::RESIZE);
        }
        let found = tree.motions.binary_search_by_key(&id, |state| state.id);
        let mut initial = MotionState::new(id, node);
        let state = match found {
            Ok(index) => &mut tree.motions[index],
            Err(_) => &mut initial,
        };
        let (values, animated) = state.advance(tree.placements[node.index()], config, tree.time, tree.resized, commit);
        if commit {
            state.node = node;
            state.properties = config.properties;
            state.seen = true;
        }
        let properties = animated.intersection(MotionProps::SIZE);
        if !properties.is_empty() {
            let sizes = sizes.get_or_insert_with(|| {
                let mut sizes = bump.storage.alloc(end);
                sizes.resize(end, MotionProps::NONE);
                sizes
            });
            let area = &mut tree.placements[node.index()];
            if properties.intersects(MotionProps::WIDTH) {
                area.width = values[2];
            }
            if properties.intersects(MotionProps::HEIGHT) {
                area.height = values[3];
            }
            sizes[node.index()] = properties;
        }
        if let Err(index) = found
            && commit
        {
            tree.motions.insert(index, initial);
        }
    }
    if let Some(sizes) = &sizes {
        size = arrange(tree, bump, context, root, bounds, sizes);
    }
    // settled position channels still override reflow from animated sizes
    if commit {
        for state in tree.motions.iter().filter(|state| state.seen) {
            let area = &mut tree.placements[state.node.index()];
            if state.properties.intersects(MotionProps::X) {
                area.x = state.animator.values[0];
            }
            if state.properties.intersects(MotionProps::Y) {
                area.y = state.animator.values[1];
            }
        }
    }
    size
}

/// offsets each area by its target
pub fn position<C: Context>(tree: &mut Tree<C>) {
    let count = tree.nodes.len();
    let placements = &mut tree.placements[..count];
    if tree.node_motions.is_empty() {
        for index in 1..count {
            let reference = placements[tree.nodes[index].target.index()];
            let area = &mut placements[index];
            area.x += reference.x;
            area.y += reference.y;
        }
        return;
    }
    for index in 1..count {
        let stored = &tree.nodes[index];
        let reference = placements[stored.target.index()];
        let area = &mut placements[index];
        area.x += reference.x;
        area.y += reference.y;
        let Some(record) = stored.aux.index().and_then(|aux| tree.aux[aux].motion.index()) else {
            continue;
        };
        let motion = tree.node_motions[record].motion;
        // a node that changes reference continues from where it was on screen and its subtree follows
        let id = stored.id;
        let Some(old) = tree.slots.old(id) else {
            continue;
        };
        // previous nodes belong to another build, so their references are read by value
        let old_reference = tree.old_nodes[tree.old_nodes[old].target.index()].id;
        if old_reference == tree.nodes[stored.target.index()].id {
            continue;
        }
        let Ok(state) = tree.motions.binary_search_by_key(&id, |state| state.id) else {
            continue;
        };
        tree.motions[state].flying = true;
        let animator = &mut tree.motions[state].animator;
        let start = tree.old_placements[old];
        if motion.properties.intersects(MotionProps::X) && area.x != start.x {
            animator.displace(0, area.x.delta(start.x), tree.time);
            area.x = start.x;
        }
        if motion.properties.intersects(MotionProps::Y) && area.y != start.y {
            animator.displace(1, area.y.delta(start.y), tree.time);
            area.y = start.y;
        }
    }
}

pub fn fit<'a, C: Context, L: Layout<C>>(cx: &mut LayoutCx<'a, C>, id: BumpId, axis: Axis) -> Fit<C::Scalar> {
    let layout = cx.inner.bump.load::<L>(id);
    layout.fit(cx.inner.as_cx(), axis)
}

pub fn distribute<'a, C: Context, L: Layout<C>>(cx: &mut LayoutCx<'a, C>, id: BumpId, axis: Axis, extent: C::Scalar) {
    let layout = cx.inner.bump.load::<L>(id);
    layout.distribute(cx.inner.as_cx(), axis, extent);
}

pub fn place<C: Context, P: Place<C>>(
    cx: &mut PlaceCx<'_, C>,
    id: BumpId,
    target: Rect<C::Scalar>,
) -> Point<C::Scalar> {
    let bump = cx.bump;
    bump.load::<P>(id).place(cx, target)
}

fn arrange<C: Context>(
    tree: &mut Tree<C>,
    bump: &BumpArena,
    context: &mut C,
    node: NodeId,
    bounds: Constraints<C::Scalar>,
    animated: &[MotionProps],
) -> Size<C::Scalar> {
    let mut placements = core::mem::take(&mut tree.placements);
    let mut z_indices = core::mem::take(&mut tree.z_indices);
    let mut has_custom_order = tree.has_custom_order;
    let mut requested = tree.frame_requested;
    let size = solve_subtree(
        tree,
        bump,
        &mut placements,
        &mut z_indices,
        &mut has_custom_order,
        context,
        &mut requested,
        animated,
        node,
        bounds,
    );
    if node.index() == 0 && !tree.places.is_empty() {
        for index in 1..tree.nodes.len() {
            let stored = &tree.nodes[index];
            let Some(place) = stored.place.index() else {
                continue;
            };
            let place = tree.places[place];
            // earlier areas are resolved and relative to their targets
            let mut reference = stored.target;
            let mut origin = Point::ZERO;
            loop {
                let area = placements[reference.index()];
                origin = Point::new(origin.x + area.x, origin.y + area.y);
                let next = tree.nodes[reference.index()].target;
                if next == reference {
                    break;
                }
                debug_assert!(next.index() < reference.index());
                reference = next;
            }
            let size = placements[stored.target.index()].size();
            let parent = placements[visual_parent(&tree.aux, stored).index()].size();
            let mut place_cx = PlaceCx {
                tree,
                bump,
                placements: &mut placements,
                z_indices: &mut z_indices,
                has_custom_order: &mut has_custom_order,
                context,
                frame_requested: &mut requested,
                animated,
                node: NodeId::new(index),
                parent,
            };
            let target = Rect::new(origin.x, origin.y, size.width, size.height);
            let position = (place.run)(&mut place_cx, place.bump_id, target);
            let area = &mut placements[index];
            area.x = position.x - origin.x;
            area.y = position.y - origin.y;
        }
    }
    tree.placements = placements;
    tree.z_indices = z_indices;
    tree.has_custom_order = has_custom_order;
    tree.frame_requested = requested;
    size
}

#[allow(clippy::too_many_arguments)]
fn solve_subtree<C: Context>(
    tree: &Tree<C>,
    bump: &BumpArena,
    placements: &mut [Rect<C::Scalar>],
    z_indices: &mut Vec<i16>,
    has_custom_order: &mut bool,
    context: &mut C,
    frame_requested: &mut bool,
    animated: &[MotionProps],
    root: NodeId,
    mut bounds: Constraints<C::Scalar>,
) -> Size<C::Scalar> {
    let start = root.index();
    let end = tree.nodes[start].subtree_end as usize + 1;
    let len = end - start;
    let root_scope = tree.nodes[start].place_scope;

    let mut fits = bump.storage.alloc(len);
    fits.resize(len, Size::new(Fit::ZERO, Fit::ZERO));
    let mut containers = bump.storage.alloc(0);
    let mut cx = LayoutCxInner {
        tree,
        bump,
        placements,
        z_indices,
        has_custom_order,
        fits: &mut fits,
        context,
        frame_requested,
        animated,
        root,
        node: root,
        axis: Axis::Horizontal,
        across: C::Scalar::ZERO,
        round: 0,
        relayout: false,
        squeezed: false,
        content_origin: Point::ZERO,
        default_item: BumpId::NONE,
    };

    if let Some(index) = tree.nodes[start].aux.index() {
        let limits = tree.aux[index].limits;
        bounds = Constraints {
            min: limits.constrain(bounds.min),
            max: limits.constrain(bounds.max),
        };
    }
    if let Some(width) = cx.size_override(root, Axis::Horizontal) {
        bounds.min.width = width;
        bounds.max.width = width;
    }
    if let Some(height) = cx.size_override(root, Axis::Vertical) {
        bounds.min.height = height;
        bounds.max.height = height;
    }

    let clamp_fit = |fit: Fit<C::Scalar>, aux: Option<&Aux<C::Scalar>>, axis: Axis| {
        let Some(aux) = aux else {
            return fit;
        };
        let fit = if aux.clip.is_some() {
            let pad = axis.extent(aux.padding.size());
            Fit::new(pad.min(fit.min), fit.natural)
        } else {
            fit
        };
        fit.clamp(axis.extent(aux.limits.min), axis.extent(aux.limits.max))
    };

    loop {
        cx.squeezed = false;
        // 1. fit x (reverse)
        for index in (start..end).rev() {
            let stored = &tree.nodes[index];
            if stored.place_scope != root_scope {
                continue;
            }
            let node = NodeId::new(index);
            let local = index - start;
            let has_layout = stored.layout.offset().is_some();
            if has_layout && cx.round == 0 {
                containers.push(index as u32);
            }
            let aux = stored.aux.index().map(|index| &tree.aux[index]);
            let mut fit_x = Fit::ZERO;
            let mut leaf_h = Fit::ZERO;
            if stored.first_measure.index().is_some() {
                let mut limits = aux.map_or(Constraints::loose(Size::uniform(C::Scalar::UNBOUNDED)), |aux| {
                    aux.limits
                });
                if let Some(width) = cx.size_override(node, Axis::Horizontal) {
                    limits.min.width = width;
                    limits.max.width = width;
                }
                if let Some(height) = cx.size_override(node, Axis::Vertical) {
                    limits.min.height = height;
                    limits.max.height = height;
                }
                let measured = cx.measure(node, limits);
                fit_x = measured.width;
                leaf_h = measured.height;
            }
            if has_layout {
                let fixed = cx.size_override(node, Axis::Horizontal).or_else(|| {
                    let limits = aux?.limits;
                    (limits.min.width == limits.max.width).then_some(limits.min.width)
                });
                cx.fits[local].width = if let Some(fixed) = fixed {
                    Fit::exact(fixed)
                } else {
                    let content_x = cx.run_fit(node, Axis::Horizontal, C::Scalar::ZERO);
                    let pad_w = aux.map_or(C::Scalar::ZERO, |aux| aux.padding.size().width);
                    clamp_fit(fit_x.max(content_x.endpoint(pad_w)), aux, Axis::Horizontal)
                };
                if cx.round == 0 {
                    cx.fits[local].height = leaf_h;
                }
            } else {
                cx.fits[local].width = cx
                    .size_override(node, Axis::Horizontal)
                    .map_or_else(|| clamp_fit(fit_x, aux, Axis::Horizontal), Fit::exact);
                cx.fits[local].height = cx
                    .size_override(node, Axis::Vertical)
                    .map_or_else(|| clamp_fit(leaf_h, aux, Axis::Vertical), Fit::exact);
            }
        }

        // 2. distribute x (forward)
        cx.distribute_axis(Axis::Horizontal, &containers, start, bounds);

        // 3. fit y (reverse)
        if cx.squeezed {
            for index in (start..end).rev() {
                let stored = &tree.nodes[index];
                if stored.place_scope != root_scope {
                    continue;
                }
                let node = NodeId::new(index);
                let local = index - start;
                let aux = stored.aux.index().map(|index| &tree.aux[index]);
                let assigned_w = cx.placements[index].width;
                let mut fit_y = Fit::ZERO;
                if stored.first_measure.index().is_some() {
                    fit_y = if assigned_w < cx.fits[local].width.natural
                        || (cx.round > 0 && stored.layout.offset().is_some())
                    {
                        let mut limits = aux.map_or(Constraints::loose(Size::uniform(C::Scalar::UNBOUNDED)), |aux| {
                            aux.limits
                        });
                        limits.min.width = assigned_w;
                        limits.max.width = assigned_w;
                        if let Some(height) = cx.size_override(node, Axis::Vertical) {
                            limits.min.height = height;
                            limits.max.height = height;
                        }
                        cx.measure(node, limits).height
                    } else {
                        cx.fits[local].height
                    };
                }
                if stored.layout.offset().is_some() {
                    let fixed = cx.size_override(node, Axis::Vertical).or_else(|| {
                        let limits = aux?.limits;
                        (limits.min.height == limits.max.height).then_some(limits.min.height)
                    });
                    if let Some(fixed) = fixed {
                        cx.fits[local].height = Fit::exact(fixed);
                        continue;
                    }
                    let pad = aux.map_or(Size::ZERO, |aux| aux.padding.size());
                    let inner_w = (assigned_w - pad.width).max(C::Scalar::ZERO);
                    let content_y = cx.run_fit(node, Axis::Vertical, inner_w);
                    fit_y = fit_y.max(content_y.endpoint(pad.height));
                }
                cx.fits[local].height = cx
                    .size_override(node, Axis::Vertical)
                    .map_or_else(|| clamp_fit(fit_y, aux, Axis::Vertical), Fit::exact);
            }
        } else {
            for &index in containers.iter() {
                let index = index as usize;
                let stored = &tree.nodes[index];
                let node = NodeId::new(index);
                let local = index - start;
                let aux = stored.aux.index().map(|index| &tree.aux[index]);
                let fixed = cx.size_override(node, Axis::Vertical).or_else(|| {
                    let limits = aux?.limits;
                    (limits.min.height == limits.max.height).then_some(limits.min.height)
                });
                if let Some(fixed) = fixed {
                    cx.fits[local].height = Fit::exact(fixed);
                    continue;
                }
                let pad = aux.map_or(Size::ZERO, |aux| aux.padding.size());
                let inner_w = (cx.placements[index].width - pad.width).max(C::Scalar::ZERO);
                let content_y = cx.run_fit(node, Axis::Vertical, inner_w);
                let mut fit_y = content_y.endpoint(pad.height);
                if stored.first_measure.index().is_some() {
                    let leaf_h = if cx.round > 0 {
                        let mut limits = aux.map_or(Constraints::loose(Size::uniform(C::Scalar::UNBOUNDED)), |aux| {
                            aux.limits
                        });
                        if let Some(width) = cx.size_override(node, Axis::Horizontal) {
                            limits.min.width = width;
                            limits.max.width = width;
                        }
                        if let Some(height) = cx.size_override(node, Axis::Vertical) {
                            limits.min.height = height;
                            limits.max.height = height;
                        }
                        cx.measure(node, limits).height
                    } else {
                        cx.fits[local].height
                    };
                    fit_y = fit_y.max(leaf_h);
                }
                cx.fits[local].height = clamp_fit(fit_y, aux, Axis::Vertical);
            }
        }

        // 4. distribute y (forward)
        cx.distribute_axis(Axis::Vertical, &containers, start, bounds);
        if !cx.relayout || cx.round >= 1 {
            break;
        }
        cx.relayout = false;
        cx.round += 1;
    }

    cx.placements[start].size()
}