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

/// handle input for your widget
///
/// keep settings on this value and pass it to [`crate::Ui::interact`] each build
///
/// # execution
///
/// interactions run before each build using the last build's settings and layout.
/// children run before parents, siblings in build order, and interactions on the
/// same widget in registration order.
///
/// # keyboard and text
///
/// [`InteractCx::keyboard`] delivers keyboard and text input to the focused widget,
/// then its ancestors. without focus, all mounted handlers are eligible.
/// call [`InteractCx::claim_keyboard`] when handled to stop it from reaching another
/// interaction. ignored events keep bubbling. the route uses focus at the start
/// of the update, so changing focus does not redirect the current event.
///
/// [`InteractCx::input`] bypasses routing and claims.
///
/// # sharing contacts
///
/// - [`Contact::claim`]: keep the press for this update. call it each update,
///   or stop to let a parent take over.
/// - [`Contact::capture`]: keep the press until it ends, even outside your widget.
///   use this when a drag starts.
///
/// both need a [`free`](Contact::free) contact that is not already captured.
/// they return `true` on success. neither can take another widget's claim.
/// interactions on the same widget share captures.
///
/// # following a contact
///
/// save [`Contact::id`] in your state and find it in [`InteractCx::contacts`] on
/// later updates. the handle itself only lasts one update.
/// to start tracking a press with an `Option<ContactId>` state:
///
/// ```
/// # use blit::{ContactId, InteractCx, Phase};
/// # fn begin(state: &mut Option<ContactId>, cx: &mut InteractCx<'_, f32>) {
/// *state = cx.contacts().find_map(|mut contact| {
///     (contact.phase == Phase::Started && contact.claim()).then_some(contact.id)
/// });
/// # }
/// ```
///
/// on later updates:
///
/// - cancel if the contact is missing or [`Contact::free`] is `false`
/// - cancel on [`Phase::Cancelled`]
/// - finish on [`Phase::Ended`]
///
/// after capture, just follow the contact without claiming or capturing it again
pub trait Interact<C: Context>: Copy + 'static {
    /// state kept between updates
    type State: Copy + Default + 'static;
    /// the result returned to your widget
    type Response: Copy + 'static;

    /// update your state for this input and return the result
    ///
    /// the first call has no input or contacts
    fn update(&self, state: &mut Self::State, cx: &mut InteractCx<'_, C::Scalar>) -> Self::Response;
}

/// identifies one press or touch within a [`Tree`]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct ContactId(NonZeroU32);

/// kind of pointer producing a contact
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ContactSource {
    Mouse(MouseButton),
    Touch(u64),
}

/// keyboard and text input routed through focus
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum KeyboardEvent<'a> {
    Key(KeyInput),
    Text(&'a str),
}

/// wheel or trackpad input for this widget
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ScrollEvent {
    pub phase: Phase,
    pub delta: Point<f32>,
    pub continuous: bool,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum Phase {
    /// no new input for this contact
    Held = 0,
    Started = 1,
    Changed = 2,
    Ended = 3,
    /// cancel the gesture without treating it as a release
    Cancelled = 4,
}

/// input and timing for your interaction
///
/// - [`Self::contacts`] for mouse presses and touches
/// - [`Self::scroll`] for wheel and trackpad input
/// - [`Self::keyboard`] for keyboard and text input
/// - [`Self::wake_at`] for timed gestures
pub struct InteractCx<'a, T> {
    id: Id,
    node: u32,
    end: u32,
    contacts: &'a mut [TrackedContact<T>],
    scroll: &'a mut Option<TrackedScroll>,
    focused: &'a mut Option<Id>,
    focus_taken: &'a mut bool,
    hover: Option<u32>,
    deadline: &'a mut Option<Duration>,
    input: &'a Input<T>,
    keyboard_target: Option<u32>,
    keyboard_claimed: &'a mut bool,
    time: Duration,
}

impl<'a, T: Scalar> InteractCx<'a, T> {
    /// the current frame time
    pub fn time(&self) -> Duration {
        self.time
    }

    /// request another update at `time`, even without new input
    ///
    /// use this for a long press
    pub fn wake_at(&mut self, time: Duration) {
        *self.deadline = Some(self.deadline.map_or(time, |deadline| deadline.min(time)));
    }

    /// read live mouse presses and touches
    ///
    /// includes contacts your widget cannot use. see
    /// [following a contact](Interact#following-a-contact) to choose and track one.
    pub fn contacts(&mut self) -> Contacts<'_, T> {
        Contacts {
            contacts: self.contacts.iter_mut(),
            id: self.id,
            node: self.node,
            end: self.end,
        }
    }

    pub fn hovered(&self) -> bool {
        self.hover.is_some_and(|node| self.contains(node))
    }

    pub fn focused(&self) -> bool {
        *self.focused == Some(self.id)
    }

    /// focuses this widget unless a deeper widget took focus during this update
    pub fn focus(&mut self) {
        if !*self.focus_taken {
            *self.focused = Some(self.id);
            *self.focus_taken = true;
        }
    }

    /// unclaimed keyboard or text input for this widget
    ///
    /// input starts at the focused widget and bubbles through its ancestors.
    /// without focus, all mounted handlers are eligible.
    pub fn keyboard(&self) -> Option<KeyboardEvent<'a>> {
        if *self.keyboard_claimed
            || self.node == UNRESOLVED
            || self.keyboard_target.is_some_and(|target| !self.contains(target))
        {
            return None;
        }
        match self.input {
            Input::Key(key) => Some(KeyboardEvent::Key(*key)),
            Input::Text(text) => Some(KeyboardEvent::Text(text.as_str())),
            _ => None,
        }
    }

    /// stops this keyboard or text event from reaching another interaction
    pub fn claim_keyboard(&mut self) {
        if self.keyboard().is_some() {
            *self.keyboard_claimed = true;
        }
    }

    /// this frame's input regardless of focus or claims
    pub fn input(&self) -> &'a Input<T> {
        self.input
    }

    /// scrolling over this widget, or the cancellation of a sequence it held
    pub fn scroll(&self) -> Option<ScrollEvent> {
        let scroll = (*self.scroll)?;
        let event = scroll.event.filter(|_| match scroll.owner {
            Some(owner) => owner == self.id,
            None => scroll.target.is_some_and(|target| self.contains(target.node)),
        });
        event.or((scroll.cancelled == Some(self.id)).then_some(ScrollEvent {
            phase: Phase::Cancelled,
            delta: Point::ZERO,
            continuous: true,
        }))
    }

    /// keeps a continuous scroll sequence over this widget until it ends
    pub fn capture_scroll(&mut self) {
        let id = self.id;
        let (node, end) = (self.node, self.end);
        if let Some(scroll) = self.scroll
            && scroll.owner.is_none()
            && scroll
                .target
                .is_some_and(|target| node <= target.node && target.node <= end)
        {
            scroll.owner = Some(id);
        }
    }

    fn contains(&self, node: u32) -> bool {
        self.node <= node && node <= self.end
    }
}

/// a mouse button press or touch, from down to release or cancellation
///
/// see [sharing contacts](Interact#sharing-contacts) for when to claim or capture
#[derive(Debug)]
pub struct Contact<'a, T> {
    pub id: ContactId,
    pub source: ContactSource,
    pub phase: Phase,
    pub origin: Point<T>,
    pub position: Point<T>,
    /// movement since the previous input
    pub delta: Point<T>,
    /// when the press started
    pub started: Duration,
    /// true if the position hits your widget or one of its children
    pub over: bool,
    /// free for this widget to use, including contacts it captured
    pub free: bool,
    pending: Option<&'a mut Route>,
    widget: Id,
}

impl<T> Contact<'_, T> {
    /// reserve this contact for the current update
    pub fn claim(&mut self) -> bool {
        if let Some(Route::Pending { claim, .. }) = self.pending.as_deref_mut() {
            *claim = Some(self.widget);
            return true;
        }
        false
    }

    /// keep this contact until it ends or your widget disappears
    pub fn capture(&mut self) -> bool {
        let Some(route) = self.pending.take() else {
            return false;
        };
        *route = Route::Captured { owner: self.widget };
        true
    }
}

/// iterate contact handles from [`InteractCx::contacts`]
pub struct Contacts<'a, T> {
    contacts: core::slice::IterMut<'a, TrackedContact<T>>,
    id: Id,
    node: u32,
    end: u32,
}

impl<'a, T: Scalar> Iterator for Contacts<'a, T> {
    type Item = Contact<'a, T>;

    fn next(&mut self) -> Option<Self::Item> {
        let tracked = self.contacts.next()?;
        let within = |node| self.node <= node && node <= self.end;
        let free = match tracked.route {
            Route::Pending {
                target: Some(target),
                claim,
            } => within(target.node) && claim.is_none_or(|claim| claim == self.id),
            Route::Captured { owner } => owner == self.id,
            Route::Pending { target: None, .. } | Route::Retired => false,
        };
        let pending = free && matches!(tracked.route, Route::Pending { .. });
        Some(Contact {
            id: tracked.id,
            source: tracked.source,
            phase: tracked.phase,
            origin: tracked.origin,
            position: tracked.position,
            delta: tracked.delta,
            started: tracked.started,
            over: tracked.hit.is_some_and(within),
            free,
            pending: pending.then_some(&mut tracked.route),
            widget: self.id,
        })
    }
}

//
// internals
//

// slot node for a named widget missing from the layout
const UNRESOLVED: u32 = u32::MAX;

#[derive(Default)]
pub struct InteractionState<T> {
    pub clips: Vec<ResolvedClip<T>>,
    pub deadline: Option<Duration>,
    pub focused: Option<Id>,
    // focus as the latest build saw it
    pub focus_seen: Option<Id>,
    pub mouse_position: Option<Point<T>>,
    contacts: Vec<TrackedContact<T>>,
    next_contact: u32,
    scroll: Option<TrackedScroll>,
    hits: Vec<HitItem<T>>,
    kinds: Kinds<T>,
}

impl<T: Scalar> InteractionState<T> {
    pub fn interact<C: Context<Scalar = T>, K: Interact<C>>(
        &mut self,
        id: Id,
        config: K,
        time: Duration,
    ) -> K::Response {
        fn update<T: Scalar, C: Context<Scalar = T>, K: Interact<C>>(
            kinds: &mut Kinds<T>,
            index: usize,
            cx: &mut InteractCx<'_, T>,
        ) {
            let (config, state, response) = kinds.get_mut::<C, K>(index);
            *response = config.update(state, cx);
        }

        let kind = self.kinds.register(TypeId::of::<K>(), update::<T, C, K>);
        match self.kinds.find(id, Some(kind)) {
            Ok(index) => {
                self.kinds.mark_requested(index);
                let cell = self.kinds.get_mut::<C, K>(index);
                cell.0 = config;
                cell.2
            }
            Err(bucket) => {
                let mut focused = self.focused;
                let mut state = K::State::default();
                let response = config.update(
                    &mut state,
                    &mut InteractCx {
                        id,
                        node: UNRESOLVED,
                        end: 0,
                        contacts: &mut [],
                        scroll: &mut None,
                        focused: &mut focused,
                        focus_taken: &mut true,
                        hover: None,
                        deadline: &mut self.deadline,
                        input: &Input::None,
                        keyboard_target: None,
                        keyboard_claimed: &mut true,
                        time,
                    },
                );
                let value = (config, state, response);
                // reserve first so a panic cannot lose a reused cell
                self.kinds.slots.reserve(1);
                let free = &mut self.kinds.kinds[kind as usize].free;
                let offset = match *free {
                    Some(offset) => {
                        let offset = offset.get() - 1;
                        // safety: free cells of this kind are dead cells of this layout holding the next link
                        unsafe {
                            let cell = self
                                .kinds
                                .state
                                .get_mut::<Cell<(K, K::State, K::Response)>>(Offset::new(offset));
                            *free = cell.next;
                            *cell = Cell { value };
                        }
                        offset
                    }
                    None => self.kinds.state.push(Cell { value }).byte(),
                };
                self.kinds.insert_requested(bucket, id, kind, offset);
                response
            }
        }
    }

    pub fn begin(&mut self, input: &Input<T>, time: Duration, nodes: &[StoredNode]) {
        self.contacts
            .retain(|tracked| !matches!(tracked.phase, Phase::Ended | Phase::Cancelled));
        for tracked in &mut self.contacts {
            tracked.phase = Phase::Held;
            tracked.delta = Point::ZERO;
            // claims last one update, claimants renew them
            if let Route::Pending { claim, .. } = &mut tracked.route {
                *claim = None;
            }
        }
        if let Some(scroll) = &mut self.scroll {
            if scroll.active || scroll.cancelled.is_some() {
                scroll.event = None;
            } else {
                self.scroll = None;
            }
        }
        match input {
            Input::MouseDown { position, .. } | Input::MouseMove { position, .. } | Input::MouseUp { position, .. } => {
                let position = *position;
                self.mouse_position = Some(position);
                for index in 0..self.contacts.len() {
                    let ContactSource::Mouse(button) = self.contacts[index].source else {
                        continue;
                    };
                    let released = matches!(input, Input::MouseUp { button: released, .. } if *released == button);
                    self.update(index, position, if released { Phase::Ended } else { Phase::Changed });
                }
                if let Input::MouseDown { button, .. } = input {
                    let button = *button;
                    // a press away from any focusable widget clears focus
                    if button == MouseButton::Primary {
                        self.focused = None;
                    }
                    self.press(ContactSource::Mouse(button), position, time);
                }
                if matches!(input, Input::MouseUp { leave: true, .. }) {
                    self.mouse_position = None;
                }
            }
            &Input::Touch {
                id,
                position,
                phase: TouchPhase::Down,
            } => {
                self.press(ContactSource::Touch(id), position, time);
            }
            &Input::Touch { id, position, phase } => {
                if let Some(index) = self
                    .contacts
                    .iter()
                    .position(|tracked| tracked.source == ContactSource::Touch(id))
                {
                    self.update(
                        index,
                        position,
                        match phase {
                            TouchPhase::Move => Phase::Changed,
                            TouchPhase::Up => Phase::Ended,
                            TouchPhase::Cancel => Phase::Cancelled,
                            TouchPhase::Down => unreachable!(),
                        },
                    );
                    // a release nothing captured clears focus unless a focusable widget takes it
                    if phase == TouchPhase::Up && matches!(self.contacts[index].route, Route::Pending { .. }) {
                        self.focused = None;
                    }
                }
            }
            Input::MouseLeave => self.mouse_position = None,
            &Input::Scroll {
                position,
                delta,
                phase,
                continuous,
                ..
            } => {
                self.mouse_position = Some(position);
                let previous = self.scroll.filter(|scroll| scroll.active);
                let cancelled = self.scroll.and_then(|scroll| scroll.cancelled);
                let continuing = continuous && phase != ScrollPhase::Started && previous.is_some();
                // a continuous ending without a sequence has nothing to end
                let stray = continuous && matches!(phase, ScrollPhase::Ended | ScrollPhase::Cancelled) && !continuing;
                self.scroll = Some(TrackedScroll {
                    target: if continuing {
                        previous.and_then(|scroll| scroll.target)
                    } else {
                        hit(&self.hits, &self.clips, position).map(|hit| HitTarget {
                            id: hit.id,
                            node: hit.node,
                        })
                    },
                    owner: previous.filter(|_| continuing).and_then(|scroll| scroll.owner),
                    event: (!stray).then_some(ScrollEvent {
                        phase: match phase {
                            ScrollPhase::Started => Phase::Started,
                            ScrollPhase::Moved => Phase::Changed,
                            ScrollPhase::Ended => Phase::Ended,
                            ScrollPhase::Cancelled => Phase::Cancelled,
                        },
                        delta: if phase == ScrollPhase::Cancelled {
                            Point::ZERO
                        } else {
                            delta
                        },
                        continuous,
                    }),
                    active: continuous && matches!(phase, ScrollPhase::Started | ScrollPhase::Moved),
                    cancelled: previous
                        .filter(|_| !continuing)
                        .and_then(|scroll| scroll.owner)
                        .or(cancelled),
                });
            }
            Input::Cancel => {
                self.mouse_position = None;
                for index in 0..self.contacts.len() {
                    self.update(index, self.contacts[index].position, Phase::Cancelled);
                }
                if let Some(scroll) = &mut self.scroll {
                    scroll.active = false;
                    scroll.event = Some(ScrollEvent {
                        phase: Phase::Cancelled,
                        delta: Point::ZERO,
                        continuous: true,
                    });
                }
            }
            Input::None | Input::Text(_) | Input::Key(_) => {}
        }
        let hover = self
            .mouse_position
            .and_then(|position| hit(&self.hits, &self.clips, position))
            .map(|hit| hit.node);
        for tracked in &mut self.contacts {
            tracked.hit = hit(&self.hits, &self.clips, tracked.position).map(|hit| hit.node);
        }
        self.deadline = None;
        let mut focus_taken = false;
        let (keyboard_target, mut keyboard_claimed) = match self.focused {
            Some(id) => match self.kinds.find(id, None) {
                Ok(index) => (Some(self.kinds.slots[index].node), false),
                Err(_) => (None, true),
            },
            None => (None, false),
        };
        let kinds = &mut self.kinds;
        for index in 0..kinds.slots.len() {
            let slot = kinds.slots[index];
            (kinds.kinds[slot.kind as usize].update)(
                kinds,
                index,
                &mut InteractCx {
                    id: slot.id,
                    node: slot.node,
                    end: nodes.get(slot.node as usize).map_or(0, |stored| stored.subtree_end),
                    contacts: &mut self.contacts,
                    scroll: &mut self.scroll,
                    focused: &mut self.focused,
                    focus_taken: &mut focus_taken,
                    hover,
                    deadline: &mut self.deadline,
                    input,
                    keyboard_target,
                    keyboard_claimed: &mut keyboard_claimed,
                    time,
                },
            );
        }
        if let Some(scroll) = &mut self.scroll {
            scroll.cancelled = None;
        }
    }

    pub fn contact_position(&self, id: ContactId) -> Option<Point<T>> {
        self.contacts
            .iter()
            .find(|contact| contact.id == id)
            .map(|contact| contact.position)
    }

    fn press(&mut self, source: ContactSource, position: Point<T>, time: Duration) {
        for index in 0..self.contacts.len() {
            if self.contacts[index].source == source {
                self.update(index, self.contacts[index].position, Phase::Cancelled);
            }
        }
        // ids wrap past zero, only live contacts need distinct ids
        let id = NonZeroU32::new(self.next_contact.wrapping_add(1)).unwrap_or(NonZeroU32::MIN);
        self.next_contact = id.get();
        let target = hit(&self.hits, &self.clips, position).map(|hit| HitTarget {
            id: hit.id,
            node: hit.node,
        });
        self.contacts.push(TrackedContact {
            id: ContactId(id),
            source,
            route: Route::Pending { target, claim: None },
            phase: Phase::Started,
            origin: position,
            position,
            delta: Point::ZERO,
            started: time,
            hit: None,
        });
    }

    fn update(&mut self, index: usize, position: Point<T>, phase: Phase) {
        let tracked = &mut self.contacts[index];
        if matches!(tracked.phase, Phase::Ended | Phase::Cancelled) {
            return;
        }
        tracked.delta = if phase == Phase::Cancelled {
            Point::ZERO
        } else {
            Point::new(position.x - tracked.position.x, position.y - tracked.position.y)
        };
        tracked.position = position;
        tracked.phase = phase;
    }
}

pub fn resolve<C: Context>(tree: &mut Tree<C>) {
    let retained = &mut tree.interaction.kinds;
    for slot in &mut retained.slots {
        slot.node = tree.slots.node(slot.id).map_or(UNRESOLVED, |node| node.index() as u32);
    }
    let Kinds {
        slots, kinds, state, ..
    } = retained;
    let before = slots.len();
    slots.retain(|slot| {
        if slot.order != UNRESOLVED {
            return true;
        }
        let free = &mut kinds[slot.kind as usize].free;
        let cell = state.as_ptr().wrapping_add(slot.offset as usize);
        // safety: unrequested cells are dead and every cell starts with room for the link
        unsafe { cell.cast::<Option<NonZeroU32>>().write(*free) };
        *free = NonZeroU32::new(slot.offset + 1);
        false
    });
    let removed = slots.len() != before;
    let nodes = &tree.nodes;
    let key = |slot: &Slot| {
        let end = nodes
            .get(slot.node as usize)
            .map_or(UNRESOLVED, |stored| stored.subtree_end);
        (end, core::cmp::Reverse(slot.node), slot.order)
    };
    // postorder with missing widgets last
    let reordered = !slots.is_sorted_by_key(key);
    if reordered {
        slots.sort_unstable_by_key(key);
    }
    // table indices only shift when slots are removed or reordered
    if removed || reordered {
        retained.rebuild();
    }
    retained.requested = 0;
    for slot in &mut retained.slots {
        slot.order = UNRESOLVED;
        if let Some(stored) = tree.nodes.get_mut(slot.node as usize) {
            stored.interactive = true;
        }
    }
    let retained = &*retained;
    let nodes = &tree.nodes;
    let node = |id| {
        let slot = &retained.slots[retained.find(id, None).ok()?];
        (slot.node != UNRESOLVED).then_some(slot.node as usize)
    };
    // a target that disappears retires its contacts rather than passing them on
    let rebind = |HitTarget { id, .. }| node(id).map(|index| HitTarget { id, node: index as u32 });
    for tracked in &mut tree.interaction.contacts {
        tracked.route = match tracked.route {
            Route::Pending {
                target: Some(target),
                claim,
            } => rebind(target).map_or(Route::Retired, |target| Route::Pending {
                target: Some(target),
                claim,
            }),
            Route::Captured { owner } if node(owner).is_none() => Route::Retired,
            route => route,
        };
    }
    tree.interaction.focus_seen = tree.interaction.focused;
    // focus requested during the build applies once it resolves
    match core::mem::replace(&mut tree.focus, FocusRequest::Keep) {
        FocusRequest::Keep => {}
        FocusRequest::Clear => tree.interaction.focused = None,
        FocusRequest::Focus(id) => tree.interaction.focused = Some(id),
    }
    // focus lasts while its widget requests an interaction
    if tree.interaction.focused.is_some_and(|id| node(id).is_none()) {
        tree.interaction.focused = None;
    }
    if let Some(scroll) = &mut tree.interaction.scroll {
        scroll.target = scroll.target.and_then(rebind);
        if scroll.owner.is_some_and(|id| node(id).is_none()) {
            // cancel the owner while keeping the rest of its sequence from reaching another widget
            scroll.cancelled = scroll.owner.take();
            scroll.event = None;
            scroll.target = None;
        }
    }
    tree.interaction.hits.clear();
    if !tree.interaction.kinds.slots.is_empty() {
        let count = tree.nodes.len();
        let placements = &tree.placements[..count];
        let mut collect = {
            #[inline(always)]
            |index: usize, stored: &StoredNode, area: Rect<C::Scalar>| {
                let id = stored.id;
                if !stored.interactive {
                    return;
                }
                let hit = stored
                    .aux
                    .index()
                    .map_or(Sides::all(C::Scalar::ZERO), |index| tree.aux[index].hit);
                let area = Rect::new(
                    area.x - hit.left,
                    area.y - hit.top,
                    area.width + hit.left + hit.right,
                    area.height + hit.top + hit.bottom,
                );
                let clip = if tree.resolved_clips.is_empty() {
                    ResolvedClipId::NONE
                } else {
                    tree.resolved_clips[index]
                };
                let clip_bounds = clip
                    .index()
                    .map_or(tree.screen, |clip| tree.interaction.clips[clip].bounds);
                tree.interaction.hits.push(HitItem {
                    id,
                    area: area.intersection(clip_bounds).unwrap_or_default(),
                    clip,
                    node: index as u32,
                });
            }
        };
        if tree.paint_order.is_empty() {
            for (index, (stored, &area)) in nodes.iter().zip(placements).enumerate() {
                collect(index, stored, area);
            }
        } else {
            for id in &tree.paint_order[..count] {
                collect(id.index(), &nodes[id.index()], placements[id.index()]);
            }
        }
    }
}

fn hit<T: Scalar>(hits: &[HitItem<T>], clips: &[ResolvedClip<T>], position: Point<T>) -> Option<HitItem<T>> {
    hits.iter()
        .rev()
        .find(|hit| {
            if !hit.area.contains(position) {
                return false;
            }
            let mut clip = hit.clip;
            while let Some(index) = clip.index() {
                let ResolvedClip {
                    area, radius, parent, ..
                } = clips[index];
                if !area.contains(position) {
                    return false;
                }
                if radius == Corners::all(T::ZERO) {
                    clip = parent;
                    continue;
                }
                let left = (position.x - area.x).to_f32();
                let right = (area.x.endpoint(area.width) - position.x).to_f32();
                let top = (position.y - area.y).to_f32();
                let bottom = (area.y.endpoint(area.height) - position.y).to_f32();
                // the corner of the quadrant holding the position
                let radius = match (left < right, top < bottom) {
                    (true, true) => radius.top_left,
                    (false, true) => radius.top_right,
                    (false, false) => radius.bottom_right,
                    (true, false) => radius.bottom_left,
                };
                let radius = radius.to_f32().min(area.width.min(area.height).to_f32() * 0.5).max(0.0);
                let x = (radius - left.min(right)).max(0.0);
                let y = (radius - top.min(bottom)).max(0.0);
                if x * x + y * y > radius * radius {
                    return false;
                }
                clip = parent;
            }
            true
        })
        .copied()
}

#[derive(Clone, Copy, Debug, PartialEq)]
enum Route {
    Pending {
        target: Option<HitTarget>,
        claim: Option<Id>,
    },
    Captured {
        owner: Id,
    },
    Retired,
}

/// a pending contact's deepest widget and its node in the previous layout
#[derive(Clone, Copy, Debug, PartialEq)]
struct HitTarget {
    id: Id,
    node: u32,
}

#[derive(Clone, Copy)]
struct TrackedContact<T> {
    id: ContactId,
    source: ContactSource,
    route: Route,
    phase: Phase,
    origin: Point<T>,
    position: Point<T>,
    delta: Point<T>,
    started: Duration,
    // node under the position in the previous layout
    hit: Option<u32>,
}

#[derive(Clone, Copy)]
struct TrackedScroll {
    // node under the pointer when the sequence started
    target: Option<HitTarget>,
    owner: Option<Id>,
    event: Option<ScrollEvent>,
    active: bool,
    cancelled: Option<Id>,
}

#[derive(Clone, Copy)]
struct HitItem<T> {
    id: Id,
    area: Rect<T>,
    clip: ResolvedClipId,
    node: u32,
}

/// retained interaction kinds and their state
#[derive(Default)]
struct Kinds<T> {
    // sorted by postorder and request order, then slots added by the current build
    slots: Vec<Slot>,
    // slot indices, at most half full
    table: Vec<u32>,
    requested: u32,
    kinds: Vec<Kind<T>>,
    // cells of every kind, reused through each kind's free list
    state: Bump,
}

impl<T> Kinds<T> {
    #[inline(never)]
    fn register(&mut self, type_id: TypeId, update: fn(&mut Kinds<T>, usize, &mut InteractCx<'_, T>)) -> u16 {
        let kind = self
            .kinds
            .iter()
            .position(|kind| kind.type_id == type_id)
            .unwrap_or_else(|| {
                assert!(self.kinds.len() <= u16::MAX as usize, "too many interaction kinds");
                self.kinds.push(Kind {
                    type_id,
                    update,
                    free: None,
                });
                self.kinds.len() - 1
            });
        kind as u16
    }

    fn mark_requested(&mut self, index: usize) {
        let slot = &mut self.slots[index];
        if slot.order == UNRESOLVED {
            slot.order = self.requested;
            self.requested += 1;
        }
    }

    #[cold]
    #[inline(never)]
    fn insert_requested(&mut self, bucket: usize, id: Id, kind: u16, offset: u32) {
        let order = self.requested;
        self.requested += 1;
        let index = self.slots.len();
        assert!(index < UNRESOLVED as usize, "too many interaction slots");
        self.slots.push(Slot {
            id,
            node: UNRESOLVED,
            offset,
            order,
            kind,
        });
        if self.slots.len() > self.table.len() / 2 {
            self.rebuild();
        } else {
            self.table[bucket] = index as u32;
        }
    }

    fn get_mut<C: Context<Scalar = T>, K: Interact<C>>(&mut self, index: usize) -> &mut (K, K::State, K::Response) {
        let slot = &self.slots[index];
        assert_eq!(
            self.kinds[slot.kind as usize].type_id,
            TypeId::of::<K>(),
            "interaction kind mismatch"
        );
        // safety: the slot is live and its kind was checked above
        unsafe { self.state.get_mut(Offset::new(slot.offset)) }
    }

    // slot index on a hit, insertion bucket on a miss
    fn find(&self, id: Id, kind: Option<u16>) -> Result<usize, usize> {
        if self.table.is_empty() {
            return Err(0);
        }
        let bucket = self.probe(id, kind);
        match self.table[bucket] {
            UNRESOLVED => Err(bucket),
            index => Ok(index as usize),
        }
    }

    fn rebuild(&mut self) {
        let len = self.slots.len();
        if len == 0 {
            self.table.clear();
            return;
        }
        // grow above half full and shrink below one eighth
        // to avoid resizing on small count changes
        if len < self.table.len() / 8 {
            self.table.truncate((len * 2).next_power_of_two());
        }
        self.table.fill(UNRESOLVED);
        if len > self.table.len() / 2 {
            self.table.resize((len * 2).next_power_of_two(), UNRESOLVED);
        }
        for (index, slot) in self.slots.iter().enumerate() {
            let bucket = self.probe(slot.id, Some(slot.kind));
            self.table[bucket] = index as u32;
        }
    }

    fn probe(&self, id: Id, kind: Option<u16>) -> usize {
        let mask = self.table.len() - 1;
        // dense slots with several kinds each would cluster, so the slot is mixed
        let mixed = u64::from(id.slot).wrapping_mul(0x9e37_79b9_7f4a_7c15);
        let mut bucket = (mixed >> (64 - self.table.len().trailing_zeros())) as usize;
        loop {
            let index = self.table[bucket];
            if index == UNRESOLVED {
                return bucket;
            }
            let slot = &self.slots[index as usize];
            if slot.id == id && kind.is_none_or(|kind| slot.kind == kind) {
                return bucket;
            }
            bucket = (bucket + 1) & mask;
        }
    }
}

#[derive(Clone, Copy)]
struct Slot {
    id: Id,
    // in the latest build, or unresolved for a named widget missing from it
    node: u32,
    offset: u32,
    // first request in the current build, or unresolved when unrequested
    order: u32,
    kind: u16,
}

struct Kind<T> {
    type_id: TypeId,
    update: fn(&mut Kinds<T>, usize, &mut InteractCx<'_, T>),
    // dead cells of this kind linked by byte offset plus one
    free: Option<NonZeroU32>,
}

/// a kind with its state and latest response, which holds the free link once it is dead
#[derive(Clone, Copy)]
#[repr(C)]
union Cell<S: Copy> {
    value: S,
    next: Option<NonZeroU32>,
}