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
use crate::*;

/// typestate modes for [`Ui`]
///
/// every mode can query its target and access shared frame services
pub mod state {
    use super::PhantomData;

    /// a node without a layout that may establish one
    pub struct Build;

    /// a child without a layout, with layout item `I`
    pub struct Child<I>(PhantomData<I>);

    /// a laid-out node that may create children
    pub struct Open<L>(PhantomData<L>);

    /// adds content and interactions to an existing node through [`crate::Ui::insert`]
    pub struct Insert;

    /// another node referenced by id through [`crate::Ui::node`], which may be built later
    pub struct Ref;

    /// modes that own their node and may set its properties
    pub trait Owned {}

    impl Owned for Build {}
    impl<I> Owned for Child<I> {}
    impl<L> Owned for Open<L> {}

    /// modes that act on their own node rather than a target
    pub trait Local {}

    impl Local for Build {}
    impl<I> Local for Child<I> {}
    impl<L> Local for Open<L> {}
    impl Local for Insert {}

    /// modes whose node has no layout yet
    pub trait NoLayout: Owned + Local {}

    impl NoLayout for Build {}
    impl<I> NoLayout for Child<I> {}
}

/// scoped handle for building a tree node
///
/// its [`state`] mode determines which operations are available
pub struct Ui<'ui, C: Context, S = state::Build> {
    inner: UiInner<'ui, C>,
    marker: PhantomData<S>,
}

impl<'ui, C: Context, S> Ui<'ui, C, S> {
    /// the target's stable id
    pub fn id(&self) -> Id {
        self.inner.target
    }

    /// the target's area from the previous layout
    #[inline(always)]
    pub fn area(&self) -> Option<Rect<C::Scalar>> {
        self.inner.area()
    }

    /// adds `interaction` to the target and returns its latest response
    ///
    /// one interaction of each kind per target, repeated requests share it
    #[inline(always)]
    pub fn interact<K: Interact<C>>(&mut self, interaction: K) -> K::Response {
        let tree = &mut *self.inner.tree;
        tree.interaction
            .interact::<C, K>(self.inner.target, interaction, tree.time)
    }

    /// animates toward `target`, keyed by the target and call site, then by call order within a frame
    #[inline(always)]
    #[track_caller]
    pub fn animate(&mut self, target: f32, animation: impl Into<Animation>, options: AnimationOptions) -> f32 {
        self.inner
            .animate(target, animation.into(), options, Location::caller())
    }

    #[inline(always)]
    #[track_caller]
    pub fn animate_loop(&mut self, tween: Tween) -> f32 {
        self.inner.animate_loop(tween, Location::caller())
    }

    /// fires once, `duration` after the target first calls it from this site or after a reset
    #[inline(always)]
    #[track_caller]
    pub fn timer(&mut self, duration: Duration) -> Timer<'_> {
        self.inner.timer(duration, false, Location::caller())
    }

    /// fires every `period`, counting from when the target first calls it from this site or from a reset
    #[inline(always)]
    #[track_caller]
    pub fn interval(&mut self, period: Duration) -> Timer<'_> {
        self.inner.timer(period, true, Location::caller())
    }

    /// focuses the target from the next build while it requests an interaction
    pub fn focus(&mut self) {
        self.inner.tree.focus = FocusRequest::Focus(self.inner.target);
    }

    /// whether the target holds focus as this build began
    pub fn focused(&self) -> bool {
        self.inner.tree.interaction.focused == Some(self.inner.target)
    }

    /// whether focus changed from the previous build
    pub fn focus_moved(&self) -> bool {
        let interaction = &self.inner.tree.interaction;
        interaction.focused != interaction.focus_seen
    }

    /// clears focus from the next build
    pub fn clear_focus(&mut self) {
        self.inner.tree.focus = FocusRequest::Clear;
    }

    /// access context during frame construction
    pub fn context(&self) -> &C {
        self.inner.context
    }

    /// access mutable context during frame construction
    pub fn context_mut(&mut self) -> &mut C {
        self.inner.context
    }

    /// the mouse cursor position, independent of touches
    pub fn mouse_position(&self) -> Option<Point<C::Scalar>> {
        self.inner.tree.interaction.mouse_position
    }

    /// the position of a contact in this frame
    ///
    /// ended and cancelled contacts remain available until the next build
    pub fn contact_position(&self, id: ContactId) -> Option<Point<C::Scalar>> {
        self.inner.tree.interaction.contact_position(id)
    }

    /// this frame's input regardless of focus or claims
    ///
    /// handle keyboard shortcuts through an interaction to respect input routing.
    pub fn input(&self) -> &Input<C::Scalar> {
        &self.inner.tree.input
    }

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

    pub fn time(&self) -> Duration {
        self.inner.tree.time
    }

    pub fn request_frame(&mut self) {
        self.inner.tree.request_frame();
    }
}

impl<'ui, C: Context, S: state::Local> Ui<'ui, C, S> {
    /// refers to the node with `id`, which may be built later, and keeps its id through this build
    #[inline]
    pub fn node(&mut self, id: Id) -> Ui<'_, C, state::Ref> {
        self.inner.tree.slots.keep(id);
        Ui {
            inner: self.inner.borrow(id),
            marker: PhantomData,
        }
    }

    /// resolves `key` in `scope` to its id, taking a slot if nothing holds it yet
    #[inline]
    pub fn resolve(&mut self, scope: Scope, key: impl Key) -> Id {
        let id = self.inner.tree.slots.name(scope.0, key.value());
        self.inner.tree.slots.keep(id);
        id
    }

    /// a scope for keys of this node and call site, so keys of unrelated code never meet
    ///
    /// scopes made at one call site repeat within a build, told apart by their order
    #[inline(always)]
    #[track_caller]
    pub fn scope(&mut self) -> Scope {
        self.inner.scope(Location::caller())
    }

    /// inserts content into the current node
    #[inline]
    pub fn insert<W: Widget<C, state::Insert>>(&mut self, widget: W) -> W::Response {
        widget.build(Ui {
            inner: self.inner.borrow(self.inner.target),
            marker: PhantomData,
        })
    }

    /// schedules a deferred paint closure on the current node
    #[inline]
    pub fn paint<F>(&mut self, paint: F)
    where
        F: Fn(&mut PaintCx<'_, C>, Rect<C::Scalar>) + 'static,
    {
        paint::insert_paint(self.inner.tree, self.inner.node, paint);
    }

    /// registers a deferred measurement closure on the current node
    ///
    /// measurement may be skipped under tight constraints or when widened past natural width.
    /// painting must not depend on prior measurement.
    #[inline]
    pub fn measure<R, F>(&mut self, measure: F)
    where
        R: Into<Fit<Size<C::Scalar>>>,
        F: Fn(&mut C, Constraints<C::Scalar>) -> R + 'static,
    {
        paint::insert_measure(self.inner.tree, self.inner.node, measure);
    }

    /// the focused node, if it was beneath this one in the previous layout
    #[inline(always)]
    pub fn focus_within(&self) -> Option<Id> {
        self.inner.focus_within()
    }

    /// the id of this node's structural parent, or its own for the root
    pub fn parent_id(&self) -> Id {
        let nodes = &self.inner.tree.nodes;
        nodes[nodes[self.inner.node.index()].parent.index()].id
    }

    /// temporary storage that stays usable while building this node
    pub fn scratch(&self) -> &'ui ScratchBuffer {
        self.inner.scratch
    }
}

impl<'ui, C: Context, S: state::Owned> Ui<'ui, C, S> {
    /// sets this node's size limits
    #[inline(always)]
    pub fn constrain(mut self, limits: Constraints<C::Scalar>) -> Self {
        self.inner.constrain(limits);
        self
    }

    /// creates a child placed against `target` outside its parent's flow
    ///
    /// a target not built before this node places it against its parent
    #[inline]
    #[track_caller]
    pub fn place<P: Place<C>>(&mut self, target: Id, place: P) -> Ui<'_, C, state::Build> {
        let (node, old) = self.inner.child(Location::caller());
        attach_place(self.inner.tree, node, target, place);
        Ui::new(self.inner.tree, self.inner.context, self.inner.scratch, node, old)
    }

    /// creates the child keyed `key` in `scope`, placed against `target` outside its parent's flow
    ///
    /// a target not built before this node places it against its parent
    #[inline]
    #[track_caller]
    pub fn place_in<P: Place<C>>(
        &mut self,
        scope: Scope,
        key: impl Key,
        target: Id,
        place: P,
    ) -> Ui<'_, C, state::Build> {
        let (node, old) = self.inner.child_in(scope.0, key.value(), Location::caller());
        attach_place(self.inner.tree, node, target, place);
        Ui::new(self.inner.tree, self.inner.context, self.inner.scratch, node, old)
    }

    #[inline(always)]
    pub fn motion(mut self, motion: Motion) -> Self {
        self.inner.motion(motion);
        self
    }

    /// selects the parent for stacking, clipping and containing size
    ///
    /// positioning stays with its anchor. a target not built before this node leaves its own parent
    #[inline(always)]
    pub fn parent(mut self, target: Id) -> Self {
        self.inner.parent(target);
        self
    }

    /// clips drawing and hit testing of this node and its visual descendants to its rounded area
    #[inline(always)]
    pub fn clip(mut self, radius: impl Into<Corners<C::Scalar>>) -> Self {
        self.inner.clip(radius.into());
        self
    }

    /// sets this node's paint order among its visual siblings
    #[inline(always)]
    pub fn z_index(mut self, z_index: i16) -> Self {
        self.inner.z_index(z_index);
        self
    }

    #[inline(always)]
    pub fn hit(mut self, hit: Sides<C::Scalar>) -> Self {
        self.inner.hit(hit);
        self
    }
}

impl<'ui, C: Context, S: state::NoLayout> Ui<'ui, C, S> {
    /// builds a widget in this node
    pub fn build<W: Widget<C>>(self, widget: W) -> W::Response {
        widget.build(Ui {
            inner: self.inner,
            marker: PhantomData,
        })
    }

    /// establishes the current node's layout
    #[inline]
    pub fn layout<L: Layout<C>>(self, layout: L) -> Ui<'ui, C, state::Open<L>> {
        let Ui { mut inner, .. } = self;
        let kind = inner.register_layout_kind(TypeId::of::<L>(), layout::fit::<C, L>, layout::distribute::<C, L>);
        if inner.tree.layout_kinds[kind as usize].default_item.offset().is_none() {
            inner.tree.layout_kinds[kind as usize].default_item = inner.tree.bump.store(L::Item::default());
        }
        let bump_id = inner.tree.bump.store(layout);
        let node = &mut inner.tree.nodes[inner.node.index()];
        node.layout = bump_id;
        node.layout_kind = kind;
        Ui {
            inner,
            marker: PhantomData,
        }
    }
}

impl<'ui, C: Context, I: 'static> Ui<'ui, C, state::Child<I>> {
    /// sets this child's layout item
    #[inline]
    pub fn item(self, item: I) -> Ui<'ui, C, state::Build> {
        let Ui { inner, .. } = self;
        inner.tree.nodes[inner.node.index()].item = inner.tree.bump.store(item);
        Ui {
            inner,
            marker: PhantomData,
        }
    }
}

impl<'ui, C: Context, L: Layout<C>> Ui<'ui, C, state::Open<L>> {
    /// creates a child identified by where it is built
    ///
    /// children built from one place are told apart by the order they are built in
    #[inline]
    #[track_caller]
    pub fn child(&mut self) -> Ui<'_, C, state::Child<L::Item>> {
        let (node, old) = self.inner.child(Location::caller());
        Ui::new(self.inner.tree, self.inner.context, self.inner.scratch, node, old)
    }

    /// creates the child keyed `key` in `scope` rather than one identified by where it is built
    ///
    /// it keeps its state as its siblings change or it moves to another parent, as its key stays.
    /// [`Ui::resolve`] with the same scope and key returns its id before it is built
    #[inline]
    #[track_caller]
    pub fn child_in(&mut self, scope: Scope, key: impl Key) -> Ui<'_, C, state::Child<L::Item>> {
        let (node, old) = self.inner.child_in(scope.0, key.value(), Location::caller());
        Ui::new(self.inner.tree, self.inner.context, self.inner.scratch, node, old)
    }

    /// lays out a built child now and returns its current animated size under `bounds`
    ///
    /// the layout pass lays it out again with whatever bounds this node's layout gives it
    #[inline(always)]
    pub fn layout_child(&mut self, child: Id, bounds: Constraints<C::Scalar>) -> Size<C::Scalar> {
        self.inner.layout_child(child, bounds)
    }

    /// insets this node's children while painted content keeps the full box
    #[inline(always)]
    pub fn pad(mut self, padding: impl Into<Sides<C::Scalar>>) -> Self {
        self.inner.pad(padding.into());
        self
    }
}

//
// internals
//

/// the node with `target`, if it was built before `node`
// keeps target and visual parent chains acyclic and ordered for single pass layout and paint
pub fn resolve_target<C: Context>(tree: &Tree<C>, node: NodeId, target: Id) -> Option<NodeId> {
    let target = tree.slots.node(target)?;
    (target.index() < node.index()).then_some(target)
}

fn attach_place<C: Context, P: Place<C>>(tree: &mut Tree<C>, node: NodeId, target: Id, place: P) {
    let reference = resolve_target(tree, node, target);
    let id = PlaceId::new(tree.places.len());
    tree.places.push(StoredPlace {
        bump_id: tree.bump.store(place),
        run: layout::place::<C, P>,
    });
    let stored = &mut tree.nodes[node.index()];
    stored.target = reference.unwrap_or(stored.target);
    stored.place = id;
    stored.place_scope = node;
}

struct UiInner<'ui, C: Context> {
    tree: &'ui mut Tree<C>,
    context: &'ui mut C,
    scratch: &'ui ScratchBuffer,
    node: NodeId,
    // the node this ui acts on, its own unless made by `node`
    target: Id,
    // where this node's call sites start in the frame's site stack or Slots::NONE when not owning a node
    sites: u32,
    // this node in the previous build, and its child to try next
    cursor: Cursor,
}

// methods are here to avoid monomorphizing to type states
impl<'ui, C: Context> UiInner<'ui, C> {
    fn new(tree: &'ui mut Tree<C>, context: &'ui mut C, scratch: &'ui ScratchBuffer, node: NodeId, old: u32) -> Self {
        Self {
            target: tree.nodes[node.index()].id,
            sites: tree.sites.len() as u32,
            // wraps to zero for a node new to this build, which has no children to try
            cursor: Cursor {
                old,
                next: old.wrapping_add(1),
            },
            tree,
            context,
            scratch,
            node,
        }
    }

    #[inline]
    fn borrow(&mut self, target: Id) -> UiInner<'_, C> {
        UiInner {
            tree: self.tree,
            context: self.context,
            scratch: self.scratch,
            node: self.node,
            target,
            sites: Slots::NONE,
            cursor: Cursor {
                old: Slots::NONE,
                next: 0,
            },
        }
    }

    fn area(&self) -> Option<Rect<C::Scalar>> {
        let tree = &*self.tree;
        let old = tree.slots.old(self.target)?;
        tree.old_placements.get(old).copied()
    }

    #[inline(never)]
    fn animate(
        &mut self,
        target: f32,
        animation: Animation,
        mut options: AnimationOptions,
        location: &'static Location<'static>,
    ) -> f32 {
        let call = Call::new(self.target, location);
        let tree = &mut *self.tree;
        // cleared so stored options stay equal across frames and do not retarget
        let initial = options.initial.take().unwrap_or(target);
        let state = AnimationState::update(&mut tree.animations, call, initial);
        match &mut state.playback {
            Playback::Target(animator) => {
                animator
                    .advance([target], [true], animation, options, tree.time, true)
                    .0[0]
            }
            Playback::Loop { value, .. } => {
                let mut animator = Animator::new([*value], Animation::default());
                let value = animator
                    .advance([target], [true], animation, options, tree.time, true)
                    .0[0];
                state.playback = Playback::Target(animator);
                value
            }
        }
    }

    #[inline(never)]
    fn animate_loop(&mut self, mut tween: Tween, location: &'static Location<'static>) -> f32 {
        tween.duration = tween.duration.max(0.0);
        if tween.duration == 0.0 {
            return self.animate(0.0, Animation::default(), AnimationOptions::default(), location);
        }
        let call = Call::new(self.target, location);
        let tree = &mut *self.tree;
        let state = AnimationState::update(&mut tree.animations, call, 0.0);
        let now = tree.time.as_secs_f64();
        let time = match state.playback {
            Playback::Loop {
                tween: previous, time, ..
            } if previous == tween => time,
            _ => now,
        };
        let progress = (now - time).max(0.0) as f32 / tween.duration;
        let value = tween.easing.sample(progress % 1.0).0;
        state.playback = Playback::Loop { tween, time, value };
        value
    }

    #[inline(never)]
    fn timer(&mut self, period: Duration, repeat: bool, location: &'static Location<'static>) -> Timer<'_> {
        if repeat {
            assert!(!period.is_zero(), "an interval must be nonzero");
        }
        let call = Call::new(self.target, location);
        let tree = &mut *self.tree;
        TimerState::update(&mut tree.timers, call, period, repeat, tree.time)
    }

    #[inline(never)]
    fn scope(&mut self, location: &'static Location<'static>) -> Scope {
        let tree = &mut *self.tree;
        let mut call = Call::new(self.target, location);
        let index = loop {
            match tree.scopes.binary_search_by_key(&call, |scope| scope.call) {
                Ok(index) if tree.slots.is_kept(tree.scopes[index].id) => call.repeat += 1,
                Ok(index) => break index,
                Err(index) => {
                    let id = tree.slots.alloc();
                    tree.scopes.insert(index, CallScope { call, id });
                    break index;
                }
            }
        };
        let id = tree.scopes[index].id;
        tree.slots.keep(id);
        Scope(id)
    }

    fn focus_within(&self) -> Option<Id> {
        let tree = &*self.tree;
        let focused = tree.interaction.focused?;
        let node = tree.slots.old(self.target)?;
        let inside = tree.slots.old(focused)?;
        (node < inside && inside <= tree.old_nodes[node].subtree_end as usize).then_some(focused)
    }

    #[inline(never)]
    fn constrain(&mut self, limits: Constraints<C::Scalar>) {
        assert!(
            limits.min.width >= C::Scalar::ZERO
                && limits.min.height >= C::Scalar::ZERO
                && limits.min.width.is_finite()
                && limits.min.height.is_finite()
                && limits.max.width >= limits.min.width
                && limits.max.height >= limits.min.height,
            "invalid local bounds"
        );
        self.tree.aux_mut(self.node).limits = limits;
    }

    fn motion(&mut self, motion: Motion) {
        let tree = &mut *self.tree;
        match tree.aux_mut(self.node).motion.index() {
            Some(index) => tree.node_motions[index].motion = motion,
            None => {
                tree.aux_mut(self.node).motion = NodeMotionId::new(tree.node_motions.len());
                tree.node_motions.push(NodeMotion {
                    node: self.node,
                    motion,
                });
            }
        }
    }

    fn parent(&mut self, target: Id) {
        if let Some(parent) = resolve_target(self.tree, self.node, target) {
            self.tree.aux_mut(self.node).visual_parent = parent;
            if parent != self.tree.nodes[self.node.index()].parent {
                self.tree.has_custom_order = true;
            }
        }
    }

    fn clip(&mut self, radius: Corners<C::Scalar>) {
        self.tree.aux_mut(self.node).clip = Some(radius);
        self.tree.has_clips = true;
    }

    fn z_index(&mut self, z_index: i16) {
        self.tree.set_z_index(self.node, z_index);
    }

    fn hit(&mut self, hit: Sides<C::Scalar>) {
        self.tree.aux_mut(self.node).hit = hit;
    }

    #[inline(never)]
    fn pad(&mut self, padding: Sides<C::Scalar>) {
        assert!(
            [padding.top, padding.right, padding.bottom, padding.left]
                .iter()
                .all(|side| *side >= C::Scalar::ZERO && side.is_finite()),
            "invalid padding"
        );
        self.tree.aux_mut(self.node).padding = padding;
    }

    fn layout_child(&mut self, child: Id, bounds: Constraints<C::Scalar>) -> Size<C::Scalar> {
        let tree = &mut *self.tree;
        let child = tree.slots.node(child).expect("a laid out child must be built first");
        assert!(
            tree.nodes[child.index()].place.index().is_none(),
            "measured widgets must stay in flow"
        );
        let mut bump = core::mem::take(&mut tree.bump);
        bump.storage.prepare();
        let size = layout::resolve(tree, &bump, self.context, child, bounds, false);
        tree.bump = bump;
        size
    }

    #[inline(never)]
    fn register_layout_kind(
        &mut self,
        type_id: TypeId,
        fit: fn(&mut LayoutCx<'_, C>, BumpId, Axis) -> Fit<C::Scalar>,
        distribute: fn(&mut LayoutCx<'_, C>, BumpId, Axis, C::Scalar),
    ) -> u16 {
        let tree = &mut *self.tree;
        let kind = tree
            .layout_kinds
            .iter()
            .position(|kind| kind.type_id == type_id)
            .unwrap_or_else(|| {
                tree.layout_kinds.push(LayoutKind {
                    type_id,
                    fit,
                    distribute,
                    default_item: BumpId::NONE,
                });
                tree.layout_kinds.len() - 1
            });
        u16::try_from(kind).expect("too many layout kinds")
    }

    // children return their node and its match in the previous build, which fit in one register
    fn child(&mut self, location: &'static Location<'static>) -> (NodeId, u32) {
        // out of line so the usual match stays small
        #[cold]
        fn search(
            old_nodes: &[StoredNode],
            old_marks: &[Mark],
            cursor: Cursor,
            end: u32,
            location: &Location<'_>,
            ordinal: u32,
        ) -> Option<u32> {
            // scan past the cursor first so skipped siblings stay linear, then wrap around
            let mut index = if cursor.next <= end {
                old_nodes[cursor.next as usize].subtree_end + 1
            } else {
                end + 1
            };
            while index <= end {
                if old_marks[index as usize].is_site(location, ordinal) {
                    return Some(index);
                }
                index = old_nodes[index as usize].subtree_end + 1;
            }
            let mut index = cursor.old + 1;
            while index < cursor.next {
                if old_marks[index as usize].is_site(location, ordinal) {
                    return Some(index);
                }
                index = old_nodes[index as usize].subtree_end + 1;
            }
            None
        }

        let tree = &mut *self.tree;
        let start = self.sites as usize;
        let (site, ordinal, scan) = match tree.sites[start..]
            .iter()
            .rposition(|site| same_place(site.location, location))
        {
            Some(index) => {
                let site = &mut tree.sites[start + index];
                site.ordinal = site.ordinal.checked_add(1).expect("too many children from one place");
                (start + index, site.ordinal, site.scan)
            }
            None => {
                tree.sites.push(Site {
                    location,
                    ordinal: 0,
                    scan: true,
                });
                (tree.sites.len() - 1, 0, true)
            }
        };
        let mut found = None;
        if scan && self.cursor.old != Slots::NONE {
            let end = tree.old_nodes[self.cursor.old as usize].subtree_end;
            if self.cursor.next <= end && tree.old_marks[self.cursor.next as usize].is_site(location, ordinal) {
                found = Some(self.cursor.next);
            } else {
                found = search(&tree.old_nodes, &tree.old_marks, self.cursor, end, location, ordinal);
                tree.sites[site].scan = found.is_some();
            }
        }
        let (id, old) = match found {
            Some(index) => {
                let stored = &tree.old_nodes[index as usize];
                self.cursor.next = stored.subtree_end + 1;
                (stored.id, index)
            }
            None => (tree.slots.alloc(), Slots::NONE),
        };
        (tree.push_node(Some(self.node), id, Mark::Site(location, ordinal)), old)
    }

    fn child_in(&mut self, scope: Id, key: u64, location: &'static Location<'static>) -> (NodeId, u32) {
        let tree = &mut *self.tree;
        // a scope is kept by the build that made it, while one held from an older build names alone
        let keyed = tree.slots.is_kept(scope);
        let mut mark = if keyed { Mark::Key(scope.slot, key) } else { Mark::Named };
        let (mut id, mut old) = if keyed
            && self.cursor.old != Slots::NONE
            && self.cursor.next <= tree.old_nodes[self.cursor.old as usize].subtree_end
            && matches!(tree.old_marks[self.cursor.next as usize], Mark::Key(slot, other) if slot == scope.slot && other == key)
        {
            let index = self.cursor.next;
            let stored = &tree.old_nodes[index as usize];
            self.cursor.next = stored.subtree_end + 1;
            (stored.id, index)
        } else {
            let id = tree.slots.name(scope, key);
            let old = tree.slots.old(id).map_or(Slots::NONE, |node| node as u32);
            // a moved key among these siblings keeps the ones after it on the cursor
            if old != Slots::NONE && tree.old_nodes[old as usize].parent.index() as u32 == self.cursor.old {
                self.cursor.next = tree.old_nodes[old as usize].subtree_end + 1;
            }
            (id, old)
        };
        if tree.slots.claimed(id) {
            // the repeat is named alone so the next build finds the first holder
            self.context.duplicate_key(Scope(scope), key, location);
            id = tree.slots.alloc();
            old = Slots::NONE;
            mark = Mark::Named;
        }
        (tree.push_node(Some(self.node), id, mark), old)
    }
}

impl<'ui, C: Context, S> Ui<'ui, C, S> {
    pub(crate) fn new(
        tree: &'ui mut Tree<C>,
        context: &'ui mut C,
        scratch: &'ui ScratchBuffer,
        node: NodeId,
        old: u32,
    ) -> Self {
        Self {
            inner: UiInner::new(tree, context, scratch, node, old),
            marker: PhantomData,
        }
    }
}

impl<C: Context> Drop for UiInner<'_, C> {
    fn drop(&mut self) {
        if self.sites == Slots::NONE {
            return;
        }
        self.tree.nodes[self.node.index()].subtree_end = (self.tree.nodes.len() - 1) as u32;
        // sites nest like open nodes so this node's are always last
        self.tree.sites.truncate(self.sites as usize);
    }
}