fret-ui 0.1.0

Mechanism-layer UI engine for Fret with tree, layout, focus, routing, and interaction contracts.
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
use super::super::*;
use super::{OverlayRootOptions, UiLayer, UiLayerId};

impl<H: UiHost> UiTree<H> {
    /// Returns the current UI layer order in paint order (back-to-front).
    ///
    /// This includes the base layer and any overlay layers (even if currently invisible).
    pub fn layer_ids_in_paint_order(&self) -> &[UiLayerId] {
        self.layer_order.as_slice()
    }

    /// Reorders layers in paint order (back-to-front).
    ///
    /// This is a mechanism-only API intended for component-layer overlay orchestration. Policy
    /// code should treat this as "stable z-order correction" rather than a per-component knob.
    ///
    /// Notes:
    /// - The base layer (when present) is always kept at the back (index 0).
    /// - Unknown/missing layer IDs are ignored, and missing existing layers are appended in their
    ///   previous relative order.
    pub fn reorder_layers_in_paint_order(&mut self, desired: Vec<UiLayerId>) {
        if self.layer_order.is_empty() {
            return;
        }

        let mut seen = std::collections::HashSet::<UiLayerId>::new();
        let mut next: Vec<UiLayerId> = Vec::with_capacity(self.layer_order.len());

        for id in desired {
            if !self.layers.contains_key(id) {
                continue;
            }
            if !seen.insert(id) {
                continue;
            }
            next.push(id);
        }

        // Preserve any layers not mentioned by the caller in their existing relative order.
        for &id in &self.layer_order {
            if !self.layers.contains_key(id) {
                continue;
            }
            if seen.insert(id) {
                next.push(id);
            }
        }

        if let Some(base) = self.base_layer {
            next.retain(|&id| id != base);
            next.insert(0, base);
        }

        if next == self.layer_order {
            return;
        }

        self.layer_order = next;
        self.request_post_layout_window_runtime_snapshot_refine_if_layout_active();

        // Layer order changes can move the active modal/focus barriers. Ensure focus/capture do
        // not remain under a barrier after reordering.
        let (active_roots, barrier_root) = self.active_input_layers();
        if barrier_root.is_some() {
            self.enforce_modal_barrier_scope(&active_roots);
        }
        let (active_focus_roots, focus_barrier_root) = self.active_focus_layers();
        if focus_barrier_root.is_some() {
            self.enforce_focus_barrier_scope(&active_focus_roots);
        }
    }

    pub(in crate::tree) fn enforce_modal_barrier_scope(&mut self, active_roots: &[NodeId]) {
        let (focus_roots, focus_barrier_root) = self.active_focus_layers();
        if focus_barrier_root.is_some()
            && self.focus.is_some_and(|n| {
                !self.is_reachable_from_any_root_via_children(n, focus_roots.as_slice())
            })
        {
            self.set_focus_unchecked(None, "layers: enforce modal barrier scope");
        }
        let to_remove: Vec<PointerId> = self
            .captured
            .iter()
            .filter_map(|(p, n)| {
                (!self.is_reachable_from_any_root_via_children(*n, active_roots)).then_some(*p)
            })
            .collect();
        for p in to_remove {
            self.captured.remove(&p);
        }
    }

    pub(in crate::tree) fn enforce_focus_barrier_scope(&mut self, active_roots: &[NodeId]) {
        if self
            .focus
            .is_some_and(|n| !self.is_reachable_from_any_root_via_children(n, active_roots))
        {
            self.set_focus_unchecked(None, "layers: enforce focus barrier scope");
        }
    }

    pub(in crate::tree) fn prune_interaction_state_outside_active_layers(
        &mut self,
        focus_reason: &'static str,
    ) {
        let (active_input_roots, _) = self.active_input_layers();
        let to_remove: Vec<PointerId> = self
            .captured
            .iter()
            .filter_map(|(pointer, node)| {
                (!self
                    .is_reachable_from_any_root_via_children(*node, active_input_roots.as_slice()))
                .then_some(*pointer)
            })
            .collect();
        for pointer in to_remove {
            self.captured.remove(&pointer);
        }

        let (active_focus_roots, _) = self.active_focus_layers();
        if self.focus.is_some_and(|node| {
            !self.is_reachable_from_any_root_via_children(node, active_focus_roots.as_slice())
        }) {
            self.set_focus_unchecked(None, focus_reason);
        }
    }

    pub fn base_root(&self) -> Option<NodeId> {
        self.base_layer
            .and_then(|id| self.layers.get(id).map(|l| l.root))
    }

    pub fn set_base_root(&mut self, root: NodeId) -> UiLayerId {
        if let Some(id) = self.base_layer {
            self.update_layer_root(id, root);
            return id;
        }

        let id = self.layers.insert(UiLayer {
            root,
            visible: true,
            blocks_underlay_input: false,
            blocks_underlay_focus: false,
            hit_testable: true,
            pointer_occlusion: PointerOcclusion::None,
            wants_pointer_down_outside_events: false,
            consume_pointer_down_outside_events: false,
            pointer_down_outside_branches: Vec::new(),
            scroll_dismiss_elements: Vec::new(),
            wants_pointer_move_events: false,
            wants_timer_events: true,
        });
        self.root_to_layer.insert(root, id);
        self.layer_order.insert(0, id);
        self.base_layer = Some(id);
        self.request_post_layout_window_runtime_snapshot_refine_if_layout_active();
        id
    }

    pub fn push_overlay_root(&mut self, root: NodeId, blocks_underlay_input: bool) -> UiLayerId {
        self.push_overlay_root_with_options(root, OverlayRootOptions::new(blocks_underlay_input))
    }

    pub fn push_overlay_root_with_options(
        &mut self,
        root: NodeId,
        options: OverlayRootOptions,
    ) -> UiLayerId {
        let id = self.layers.insert(UiLayer {
            root,
            visible: true,
            blocks_underlay_input: options.blocks_underlay_input,
            blocks_underlay_focus: options.blocks_underlay_input,
            hit_testable: options.hit_testable,
            pointer_occlusion: PointerOcclusion::None,
            wants_pointer_down_outside_events: false,
            consume_pointer_down_outside_events: false,
            pointer_down_outside_branches: Vec::new(),
            scroll_dismiss_elements: Vec::new(),
            wants_pointer_move_events: false,
            wants_timer_events: false,
        });
        self.root_to_layer.insert(root, id);
        self.layer_order.push(id);
        self.request_post_layout_window_runtime_snapshot_refine_if_layout_active();

        if options.blocks_underlay_input {
            let (active_roots, _barrier_root) = self.active_input_layers();
            self.enforce_modal_barrier_scope(&active_roots);
        }

        id
    }

    /// Uninstalls an overlay layer and removes its root subtree.
    ///
    /// This is the symmetric operation to `push_overlay_root(...)` /
    /// `push_overlay_root_with_options(...)` and exists to keep the overlay substrate contract
    /// minimal but complete (ADR 0066).
    ///
    /// Notes:
    /// - The base layer cannot be removed (use `set_base_root` instead).
    /// - This removes the layer root node, and recursively removes its children **unless** a child
    ///   subtree is itself a layer root (which is treated as an independent root).
    pub fn remove_layer(
        &mut self,
        services: &mut dyn UiServices,
        layer: UiLayerId,
    ) -> Option<NodeId> {
        if self.base_layer == Some(layer) {
            return None;
        }
        let root = self.layers.get(layer).map(|l| l.root)?;

        // Make the root removable by the existing subtree removal logic (which normally refuses to
        // delete layer roots).
        self.root_to_layer.remove(&root);

        self.layer_order.retain(|&id| id != layer);
        let _ = self.layers.remove(layer);
        self.request_post_layout_window_runtime_snapshot_refine_if_layout_active();

        let mut removed: Vec<NodeId> = Vec::new();
        self.remove_subtree_inner(services, root, &mut removed);

        Some(root)
    }

    #[track_caller]
    pub fn set_layer_visible(&mut self, layer: UiLayerId, visible: bool) {
        let prev_visible = self.layers.get(layer).map(|l| l.visible);
        let Some(l) = self.layers.get_mut(layer) else {
            return;
        };
        l.visible = visible;

        if !visible {
            let to_remove: Vec<fret_core::PointerId> = self
                .captured
                .iter()
                .filter_map(|(p, n)| {
                    (self.node_layer(*n).is_some_and(|lid| lid == layer)).then_some(*p)
                })
                .collect();
            for p in to_remove {
                self.captured.remove(&p);
            }
            if self
                .focus
                .is_some_and(|n| self.node_layer(n).is_some_and(|lid| lid == layer))
            {
                self.set_focus_unchecked(None, "layers: set_layer_visible(false)");
            }
        }

        // When visibility changes, the active modal barrier can appear/disappear or move. Ensure
        // focus/capture do not remain in layers that are now under the barrier (or otherwise
        // inactive).
        //
        // This is especially important for overlay managers that reuse layer roots and toggle
        // visibility instead of creating/removing roots each time (fearless refactors should keep
        // the behavior consistent).
        if prev_visible != Some(visible) {
            self.request_post_layout_window_runtime_snapshot_refine_if_layout_active();
            let (active_roots, barrier_root) = self.active_input_layers();
            if barrier_root.is_some() {
                self.enforce_modal_barrier_scope(&active_roots);
            }

            #[cfg(feature = "diagnostics")]
            if self.debug_enabled {
                let caller = std::panic::Location::caller();
                self.debug_layer_visible_writes
                    .push(UiDebugSetLayerVisibleWrite {
                        layer,
                        frame_id: self.debug_stats.frame_id,
                        prev_visible,
                        visible,
                        file: caller.file(),
                        line: caller.line(),
                        column: caller.column(),
                    });
            }
        }
    }

    pub fn set_layer_hit_testable(&mut self, layer: UiLayerId, hit_testable: bool) {
        let prev_hit_testable = self.layers.get(layer).map(|l| l.hit_testable);
        let Some(l) = self.layers.get_mut(layer) else {
            return;
        };
        l.hit_testable = hit_testable;

        if !hit_testable {
            let to_remove: Vec<fret_core::PointerId> = self
                .captured
                .iter()
                .filter_map(|(p, n)| {
                    (self.node_layer(*n).is_some_and(|lid| lid == layer)).then_some(*p)
                })
                .collect();
            for p in to_remove {
                self.captured.remove(&p);
            }
            if self
                .focus
                .is_some_and(|n| self.node_layer(n).is_some_and(|lid| lid == layer))
            {
                self.set_focus_unchecked(None, "layers: set_layer_hit_testable(false)");
            }
        }

        if prev_hit_testable != Some(hit_testable) {
            self.request_post_layout_window_runtime_snapshot_refine_if_layout_active();
            let (active_roots, barrier_root) = self.active_input_layers();
            if barrier_root.is_some() {
                self.enforce_modal_barrier_scope(&active_roots);
            }
        }
    }

    pub fn set_layer_pointer_occlusion(&mut self, layer: UiLayerId, occlusion: PointerOcclusion) {
        let Some(l) = self.layers.get_mut(layer) else {
            return;
        };
        if l.pointer_occlusion == occlusion {
            return;
        }
        l.pointer_occlusion = occlusion;
        self.request_post_layout_window_runtime_snapshot_refine_if_layout_active();
    }

    pub fn set_layer_blocks_underlay_focus(&mut self, layer: UiLayerId, blocks: bool) {
        let prev = self.layers.get(layer).map(|l| l.blocks_underlay_focus);
        let Some(l) = self.layers.get_mut(layer) else {
            return;
        };
        l.blocks_underlay_focus = blocks;

        if prev != Some(blocks) {
            self.request_post_layout_window_runtime_snapshot_refine_if_layout_active();
            let (active_roots, barrier_root) = self.active_focus_layers();
            if barrier_root.is_some() {
                self.enforce_focus_barrier_scope(&active_roots);
            }
        }
    }

    pub fn is_layer_visible(&self, layer: UiLayerId) -> bool {
        self.layers.get(layer).is_some_and(|l| l.visible)
    }

    pub fn layer_root(&self, layer: UiLayerId) -> Option<NodeId> {
        self.layers.get(layer).map(|l| l.root)
    }

    pub(crate) fn all_layer_roots(&self) -> Vec<NodeId> {
        self.layer_order
            .iter()
            .filter_map(|layer| self.layers.get(*layer).map(|l| l.root))
            .collect()
    }

    pub fn set_layer_wants_pointer_move_events(&mut self, layer: UiLayerId, wants: bool) {
        let Some(l) = self.layers.get_mut(layer) else {
            return;
        };
        if l.wants_pointer_move_events == wants {
            return;
        }
        l.wants_pointer_move_events = wants;
        self.request_post_layout_window_runtime_snapshot_refine_if_layout_active();
    }

    pub fn set_layer_wants_pointer_down_outside_events(&mut self, layer: UiLayerId, wants: bool) {
        let Some(l) = self.layers.get_mut(layer) else {
            return;
        };
        if l.wants_pointer_down_outside_events == wants {
            return;
        }
        l.wants_pointer_down_outside_events = wants;
        self.request_post_layout_window_runtime_snapshot_refine_if_layout_active();
    }

    pub fn set_layer_consume_pointer_down_outside_events(
        &mut self,
        layer: UiLayerId,
        consume: bool,
    ) {
        let Some(l) = self.layers.get_mut(layer) else {
            return;
        };
        if l.consume_pointer_down_outside_events == consume {
            return;
        }
        l.consume_pointer_down_outside_events = consume;
        self.request_post_layout_window_runtime_snapshot_refine_if_layout_active();
    }

    pub fn set_layer_pointer_down_outside_branches(
        &mut self,
        layer: UiLayerId,
        branches: Vec<NodeId>,
    ) {
        let Some(l) = self.layers.get_mut(layer) else {
            return;
        };
        if l.pointer_down_outside_branches == branches {
            return;
        }
        l.pointer_down_outside_branches = branches;
        self.request_post_layout_window_runtime_snapshot_refine_if_layout_active();
    }

    /// Register elements that should dismiss this overlay when a scroll event targets an ancestor
    /// of any element's current node.
    ///
    /// This is intended for Radix-aligned tooltip behavior: when the tooltip trigger is scrolled,
    /// the tooltip should close (Radix closes when `event.target.contains(trigger)` on scroll).
    pub fn set_layer_scroll_dismiss_elements(
        &mut self,
        layer: UiLayerId,
        elements: Vec<crate::GlobalElementId>,
    ) {
        let Some(l) = self.layers.get_mut(layer) else {
            return;
        };
        if l.scroll_dismiss_elements == elements {
            return;
        }
        l.scroll_dismiss_elements = elements;
        self.request_post_layout_window_runtime_snapshot_refine_if_layout_active();
    }

    pub fn set_layer_wants_timer_events(&mut self, layer: UiLayerId, wants: bool) {
        let Some(l) = self.layers.get_mut(layer) else {
            return;
        };
        if l.wants_timer_events == wants {
            return;
        }
        l.wants_timer_events = wants;
        self.request_post_layout_window_runtime_snapshot_refine_if_layout_active();
    }

    pub fn node_layer(&self, node: NodeId) -> Option<UiLayerId> {
        let root = self.node_root(node)?;
        self.root_to_layer.get(&root).copied()
    }

    pub(in crate::tree) fn visible_layers_in_paint_order(
        &self,
    ) -> impl Iterator<Item = UiLayerId> + '_ {
        self.layer_order
            .iter()
            .copied()
            .filter(|id| self.layers.get(*id).is_some_and(|l| l.visible))
    }

    pub(in crate::tree) fn topmost_pointer_occlusion_layer(
        &self,
        barrier_root: Option<NodeId>,
    ) -> Option<(UiLayerId, PointerOcclusion)> {
        let mut hit_barrier = false;
        for &layer_id in self.layer_order.iter().rev() {
            let Some(layer) = self.layers.get(layer_id) else {
                continue;
            };
            if !layer.visible {
                continue;
            }
            if barrier_root.is_some() && hit_barrier {
                break;
            }

            let occlusion = layer.pointer_occlusion;
            if occlusion != PointerOcclusion::None {
                return Some((layer_id, occlusion));
            }

            if barrier_root == Some(layer.root) {
                hit_barrier = true;
            }
        }
        None
    }

    pub(in crate::tree) fn active_input_layers(&self) -> (Vec<NodeId>, Option<NodeId>) {
        let mut any_visible = false;
        let mut barrier_root: Option<NodeId> = None;
        for &layer_id in &self.layer_order {
            let Some(layer) = self.layers.get(layer_id) else {
                continue;
            };
            if !layer.visible {
                continue;
            }
            any_visible = true;

            // Modal/pointer barriers can be hit-test-inert (e.g. close transitions, pointer-only
            // underlay blocking). A barrier must still gate input even when it isn't hit-testable.
            if layer.blocks_underlay_input {
                barrier_root = Some(layer.root);
            }
        }

        if !any_visible {
            return (Vec::new(), None);
        }

        let mut roots: Vec<NodeId> = Vec::new();
        for &layer_id in self.layer_order.iter().rev() {
            let Some(layer) = self.layers.get(layer_id) else {
                continue;
            };
            if !layer.visible {
                continue;
            }

            // Focus barriers can become active before a layer is hit-testable (e.g. during open/close
            // transitions). Include the barrier root itself so focus can still be moved into the
            // barrier scope; otherwise `set_focus` can reject all targets while the underlay is
            // blocked, leading to spurious focus loss.
            if layer.hit_testable || barrier_root == Some(layer.root) {
                roots.push(layer.root);
            }

            if barrier_root == Some(layer.root) {
                break;
            }
        }
        (roots, barrier_root)
    }

    pub(in crate::tree) fn active_pointer_down_outside_layer_roots(
        &self,
        barrier_root: Option<NodeId>,
    ) -> Vec<NodeId> {
        let mut any_visible = false;
        for &layer_id in &self.layer_order {
            let Some(layer) = self.layers.get(layer_id) else {
                continue;
            };
            if !layer.visible {
                continue;
            }
            any_visible = true;
            if layer.blocks_underlay_input {
                break;
            }
        }

        if !any_visible {
            return Vec::new();
        }

        let mut roots: Vec<NodeId> = Vec::new();
        for &layer_id in self.layer_order.iter().rev() {
            let Some(layer) = self.layers.get(layer_id) else {
                continue;
            };
            if !layer.visible {
                continue;
            }

            roots.push(layer.root);

            if barrier_root == Some(layer.root) {
                break;
            }
        }
        roots
    }

    pub(in crate::tree) fn active_focus_layers(&self) -> (Vec<NodeId>, Option<NodeId>) {
        let mut any_visible = false;
        let mut barrier_root: Option<NodeId> = None;
        let focused_layer = self.focus.and_then(|node| self.node_layer(node));
        for &layer_id in &self.layer_order {
            let Some(layer) = self.layers.get(layer_id) else {
                continue;
            };
            if !layer.visible {
                continue;
            }
            any_visible = true;

            if layer.blocks_underlay_focus {
                barrier_root = Some(layer.root);
            }
        }

        if !any_visible {
            return (Vec::new(), None);
        }

        let mut roots: Vec<NodeId> = Vec::new();
        for &layer_id in self.layer_order.iter().rev() {
            let Some(layer) = self.layers.get(layer_id) else {
                continue;
            };
            if !layer.visible {
                continue;
            }

            // Focus barriers can become active while the barrier layer is hit-test-inert (e.g.
            // open/close transitions or pointer-only underlay blocking). Include the barrier root
            // itself so focus can remain inside (and be moved within) the barrier scope.
            //
            // Likewise, if focus already lives inside a visible layer, keep that layer in the
            // authoritative focus snapshot even when pointer arbitration temporarily makes it
            // hit-test-inert. Otherwise same-frame focus repair can self-invalidate by resolving a
            // live node and then immediately pruning it out of the active focus roots.
            if layer.hit_testable
                || barrier_root == Some(layer.root)
                || focused_layer == Some(layer_id)
            {
                roots.push(layer.root);
            }

            if barrier_root == Some(layer.root) {
                break;
            }
        }
        (roots, barrier_root)
    }

    fn update_layer_root(&mut self, layer: UiLayerId, root: NodeId) {
        let Some(old_root) = self.layers.get(layer).map(|layer| layer.root) else {
            return;
        };
        if old_root == root {
            return;
        }

        self.root_to_layer.remove(&old_root);
        let Some(layer_entry) = self.layers.get_mut(layer) else {
            return;
        };
        layer_entry.root = root;
        self.root_to_layer.insert(root, layer);
        self.prune_interaction_state_outside_active_layers("layers: update_layer_root");
        self.request_post_layout_window_runtime_snapshot_refine_if_layout_active();
    }
}