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
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
use crate::UiHost;
use fret_core::{
    AppWindowId, Axis, CursorIcon, InternalDragKind, KeyCode, Modifiers, MouseButton, Point,
    PointerId, PointerType, Rect, UiServices,
};
use fret_runtime::{
    ActionId, CommandId, DefaultAction, DragHost, DragKindId, DragSession, Effect, Model,
    ModelStore, PlatformTextInputQuery, PlatformTextInputQueryResult, TickId, TimerToken,
    Utf16Range, WeakModel,
};
use std::any::{Any, TypeId};
use std::sync::Arc;

/// Context passed to component-owned action handlers.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ActionCx {
    pub window: AppWindowId,
    pub target: crate::GlobalElementId,
}

/// Why an element was activated.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ActivateReason {
    Pointer,
    Keyboard,
}

/// Result of a component-owned `Pressable` pointer down hook.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PressablePointerDownResult {
    /// Continue with the default `Pressable` pointer down behavior (focus, capture, pressed state).
    Continue,
    /// Skip the default behavior but allow the event to keep propagating.
    SkipDefault,
    /// Skip the default behavior and stop propagation at this pressable.
    SkipDefaultAndStopPropagation,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PressablePointerUpResult {
    /// Continue with the default `Pressable` pointer-up behavior (activate when pressed+hovered).
    Continue,
    /// Skip the activation step (but still run default cleanup like releasing capture).
    SkipActivate,
}

/// Why an overlay is requesting dismissal.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DismissReason {
    Escape,
    OutsidePress {
        pointer: Option<OutsidePressCx>,
    },
    /// Focus moved outside the dismissable layer subtree (Radix `onFocusOutside` outcome).
    FocusOutside,
    /// The trigger (or another registered subtree) was scrolled.
    ///
    /// This is used for Radix-aligned tooltip semantics: a tooltip should close when its trigger
    /// is inside the scroll target that received a wheel/scroll gesture.
    Scroll,
}

/// Context passed to overlay dismissal handlers.
///
/// This mirrors the DOM/Radix contract where `onInteractOutside` / `onPointerDownOutside` /
/// `onFocusOutside` may "prevent default" to keep the overlay open.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DismissRequestCx {
    pub reason: DismissReason,
    default_prevented: bool,
}

impl DismissRequestCx {
    pub fn new(reason: DismissReason) -> Self {
        Self {
            reason,
            default_prevented: false,
        }
    }

    pub fn prevent_default(&mut self) {
        self.default_prevented = true;
    }

    pub fn default_prevented(&self) -> bool {
        self.default_prevented
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct DismissibleLastDismissRequest {
    pub tick_id: TickId,
    pub reason: Option<DismissReason>,
    pub default_prevented: bool,
}

impl Default for DismissibleLastDismissRequest {
    fn default() -> Self {
        Self {
            tick_id: TickId(0),
            reason: None,
            default_prevented: false,
        }
    }
}

/// Context passed to auto-focus handlers.
///
/// This mirrors the DOM/Radix contract where `onOpenAutoFocus` / `onCloseAutoFocus` may "prevent
/// default" to take full control of focus movement.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AutoFocusRequestCx {
    default_prevented: bool,
}

impl AutoFocusRequestCx {
    pub fn new() -> Self {
        Self {
            default_prevented: false,
        }
    }

    pub fn prevent_default(&mut self) {
        self.default_prevented = true;
    }

    pub fn default_prevented(&self) -> bool {
        self.default_prevented
    }
}

impl Default for AutoFocusRequestCx {
    fn default() -> Self {
        Self::new()
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct OutsidePressCx {
    pub pointer_id: PointerId,
    pub pointer_type: PointerType,
    pub button: MouseButton,
    pub modifiers: Modifiers,
    pub click_count: u8,
}

/// Pointer down payload for component-owned pointer handlers.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct PointerDownCx {
    pub pointer_id: PointerId,
    /// Pointer position in the target widget's untransformed layout space (ADR 0238).
    pub position: Point,
    /// Pointer position in the target element's local coordinate space (origin at `(0, 0)`).
    ///
    /// This is derived as `position - host.bounds().origin` (ADR 0238).
    pub position_local: Point,
    /// Pointer position in window-local logical pixels (pre-mapping).
    ///
    /// This is best-effort: events may arrive before the runtime has recorded a window snapshot.
    pub position_window: Option<Point>,
    pub tick_id: TickId,
    /// Pixels-per-point (a.k.a. window scale factor) for `position`.
    ///
    /// This is required for DPI-stable interactions (e.g. viewport tools, gizmos).
    pub pixels_per_point: f32,
    pub button: MouseButton,
    pub modifiers: Modifiers,
    /// See `PointerEvent::{Down,Up}.click_count` for normalization rules.
    pub click_count: u8,
    pub pointer_type: PointerType,
    /// `true` when the pointer-down hit-test target is (or is inside) a text input element subtree
    /// (`TextInput`, `TextArea`, or `TextInputRegion`).
    ///
    /// This is a mechanism-provided classification intended for component policy decisions like
    /// Embla-style "do not arm drag when interacting with focus nodes".
    pub hit_is_text_input: bool,
    /// `true` when the pointer-down hit-test target is (or is inside) a pressable element subtree
    /// (`Pressable`).
    ///
    /// This is a mechanism-provided classification intended for policy-level decisions like
    /// "click-to-focus unless interacting with an embedded button".
    pub hit_is_pressable: bool,
    /// The deepest pressable element in the pointer-down hit-test chain (if any).
    ///
    /// This can be used by composite widgets to implement DOM-style policies like
    /// "click-to-focus unless the event target is inside a button" without requiring selector
    /// mechanisms in the component layer.
    pub hit_pressable_target: Option<crate::GlobalElementId>,
    /// `true` when `hit_pressable_target` is a strict descendant of the current action target.
    ///
    /// This excludes ambient ancestor pressables and the current target itself, so wrapper
    /// policies can suppress forwarding only for genuinely nested interactive descendants.
    pub hit_pressable_target_in_descendant_subtree: bool,
}

/// Pointer move payload for component-owned pointer handlers.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct PointerMoveCx {
    pub pointer_id: PointerId,
    /// Pointer position in the target widget's untransformed layout space (ADR 0238).
    pub position: Point,
    /// Pointer position in the target element's local coordinate space (origin at `(0, 0)`).
    ///
    /// This is derived as `position - host.bounds().origin` (ADR 0238).
    pub position_local: Point,
    /// Pointer position in window-local logical pixels (pre-mapping).
    ///
    /// This is best-effort: events may arrive before the runtime has recorded a window snapshot.
    pub position_window: Option<Point>,
    pub tick_id: TickId,
    /// Pixels-per-point (a.k.a. window scale factor) for `position`.
    pub pixels_per_point: f32,
    /// Best-effort pointer velocity snapshot in window-local logical pixels per second (ADR 0243).
    ///
    /// Notes:
    /// - This is derived from the UI runtime's pointer motion snapshots, not from per-element
    ///   state. It may be `None` when monotonic timestamps are unavailable.
    /// - Components that need deterministic velocity for tests should treat `None` as "unknown"
    ///   and fall back to policy defaults.
    pub velocity_window: Option<Point>,
    pub buttons: fret_core::MouseButtons,
    pub modifiers: Modifiers,
    pub pointer_type: PointerType,
}

/// Wheel payload for component-owned wheel handlers.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct WheelCx {
    pub pointer_id: PointerId,
    /// Pointer position in the target widget's untransformed layout space (ADR 0238).
    pub position: Point,
    /// Pointer position in the target element's local coordinate space (origin at `(0, 0)`).
    ///
    /// This is derived as `position - host.bounds().origin` (ADR 0238).
    pub position_local: Point,
    /// Pointer position in window-local logical pixels (pre-mapping).
    ///
    /// This is best-effort: events may arrive before the runtime has recorded a window snapshot.
    pub position_window: Option<Point>,
    pub tick_id: TickId,
    /// Pixels-per-point (a.k.a. window scale factor) for `position`.
    pub pixels_per_point: f32,
    /// Wheel delta mapped into the target widget's untransformed layout space (ADR 0238).
    pub delta: Point,
    /// Wheel delta in window-local logical pixels (pre-mapping).
    pub delta_window: Option<Point>,
    pub modifiers: Modifiers,
    pub pointer_type: PointerType,
}

/// Pinch (magnify) gesture payload for component-owned pinch handlers.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct PinchGestureCx {
    pub pointer_id: PointerId,
    /// Pointer position in the target widget's untransformed layout space (ADR 0238).
    pub position: Point,
    /// Pointer position in the target element's local coordinate space (origin at `(0, 0)`).
    ///
    /// This is derived as `position - host.bounds().origin` (ADR 0238).
    pub position_local: Point,
    /// Pointer position in window-local logical pixels (pre-mapping).
    ///
    /// This is best-effort: events may arrive before the runtime has recorded a window snapshot.
    pub position_window: Option<Point>,
    pub tick_id: TickId,
    /// Pixels-per-point (a.k.a. window scale factor) for `position`.
    pub pixels_per_point: f32,
    /// Positive for magnification (zoom in) and negative for shrinking (zoom out).
    ///
    /// This may be NaN depending on the platform backend; callers should guard accordingly.
    pub delta: f32,
    pub modifiers: Modifiers,
    pub pointer_type: PointerType,
}

/// Pointer cancel payload for component-owned pointer handlers.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct PointerCancelCx {
    pub pointer_id: PointerId,
    /// When provided by the platform, this is the last known pointer position (logical pixels).
    pub position: Option<Point>,
    /// When provided by the platform, this is the last known pointer position in element-local
    /// logical pixels.
    ///
    /// Derived as `position - host.bounds().origin` (ADR 0238).
    pub position_local: Option<Point>,
    /// When provided by the platform, this is the last known pointer position in window-local
    /// logical pixels (pre-mapping).
    pub position_window: Option<Point>,
    pub tick_id: TickId,
    /// Pixels-per-point (a.k.a. window scale factor) for `position`.
    pub pixels_per_point: f32,
    pub buttons: fret_core::MouseButtons,
    pub modifiers: Modifiers,
    pub pointer_type: PointerType,
    pub reason: fret_core::PointerCancelReason,
}

/// Pointer up payload for component-owned pointer handlers.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct PointerUpCx {
    pub pointer_id: PointerId,
    /// Pointer position in the target widget's untransformed layout space (ADR 0238).
    pub position: Point,
    /// Pointer position in the target element's local coordinate space (origin at `(0, 0)`).
    ///
    /// This is derived as `position - host.bounds().origin` (ADR 0238).
    pub position_local: Point,
    /// Pointer position in window-local logical pixels (pre-mapping).
    ///
    /// This is best-effort: events may arrive before the runtime has recorded a window snapshot.
    pub position_window: Option<Point>,
    pub tick_id: TickId,
    /// Pixels-per-point (a.k.a. window scale factor) for `position`.
    pub pixels_per_point: f32,
    /// Best-effort pointer velocity snapshot in window-local logical pixels per second (ADR 0243).
    pub velocity_window: Option<Point>,
    pub button: MouseButton,
    pub modifiers: Modifiers,
    /// Whether this pointer-up completes a "true click" (press + release without exceeding click
    /// slop).
    ///
    /// See `PointerEvent::Up.is_click` for normalization rules.
    pub is_click: bool,
    /// See `PointerEvent::{Down,Up}.click_count` for normalization rules.
    pub click_count: u8,
    pub pointer_type: PointerType,
    /// The deepest pressable element in the pointer-down hit-test chain (if any).
    ///
    /// This is populated from the pressable/pointer-region state recorded on pointer down, and is
    /// intended for policy decisions like suppressing row selection when the click started inside
    /// a nested button.
    pub down_hit_pressable_target: Option<crate::GlobalElementId>,
    /// `true` when `down_hit_pressable_target` was a strict descendant of the current action
    /// target on pointer down.
    pub down_hit_pressable_target_in_descendant_subtree: bool,
}

/// Key down payload for component-owned key handlers.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct KeyDownCx {
    pub key: KeyCode,
    pub modifiers: Modifiers,
    pub repeat: bool,
    /// Whether the focused text input is currently in an active IME composition session.
    ///
    /// When `true`, components should generally avoid treating key presses as command/selection
    /// navigation shortcuts (see `cmdk`'s `isComposing` guard).
    pub ime_composing: bool,
}

/// Object-safe host surface for action handlers.
///
/// This intentionally exposes only non-generic operations so handlers can be stored in element
/// state and invoked by the runtime without coupling to `H: UiHost` (see ADR 0074).
pub trait UiActionHost {
    fn models_mut(&mut self) -> &mut ModelStore;
    fn push_effect(&mut self, effect: Effect);
    fn request_redraw(&mut self, window: AppWindowId);
    fn next_timer_token(&mut self) -> TimerToken;
    fn next_clipboard_token(&mut self) -> fret_runtime::ClipboardToken;
    fn next_share_sheet_token(&mut self) -> fret_runtime::ShareSheetToken;

    /// Publish router navigation availability for the given window.
    ///
    /// This is an object-safe hook used by ecosystem layers (for example `fret-router-ui`) to
    /// keep cross-surface command gating (menus, command palette, shortcuts) in sync without
    /// requiring generic access to host globals.
    fn set_router_command_availability(
        &mut self,
        _window: AppWindowId,
        _can_back: bool,
        _can_forward: bool,
    ) {
    }

    /// Record a transient, per-element event for the current dispatch cycle.
    ///
    /// This is a mechanism-only escape hatch intended for cases where an action hook needs to
    /// communicate a one-shot signal to the next declarative render pass without allocating a
    /// dedicated model. The event is keyed by `(ActionCx.target, key)` and is typically consumed
    /// by declarative authoring code via an element-scoped "take" API.
    ///
    /// Notes:
    /// - Hosts that are not running inside a UI tree event dispatch may leave this as a no-op.
    /// - Callers should treat `key` as a stable, deterministic identifier (e.g. a const hash).
    fn record_transient_event(&mut self, _cx: ActionCx, _key: u64) {}

    /// Mark the nearest view-cache root for `cx.target` as dirty (GPUI-style `notify`).
    ///
    /// Notes:
    /// - This is intentionally optional: hosts that are not running inside a UI tree event
    ///   dispatch can leave this as a no-op.
    /// - When view caching is enabled, this forces a rerender (skips reuse) for the nearest cache
    ///   root so declarative UI that depends on non-model state can still update deterministically.
    fn notify(&mut self, _cx: ActionCx) {}

    /// Record best-effort diagnostics metadata for an upcoming command dispatch.
    ///
    /// This is a mechanism-only hook intended to help explain pointer-triggered `Effect::Command`
    /// dispatches in `fretboard diag` without changing the effect schema.
    ///
    /// Hosts that do not support diagnostics can leave this as a no-op.
    fn record_pending_command_dispatch_source(
        &mut self,
        _cx: ActionCx,
        _command: &CommandId,
        _reason: ActivateReason,
    ) {
    }

    /// Record a transient payload for a parameterized action dispatch (ADR 0312).
    ///
    /// This is a best-effort, window-scoped pending store with a small tick TTL. Payload is
    /// intentionally *not* embedded into the element tree; it is passed through a separate,
    /// transient channel to keep the IR data-first and to preserve future DSL/frontend options.
    ///
    /// Hosts that do not support payload actions can leave this as a no-op.
    fn record_pending_action_payload(
        &mut self,
        _cx: ActionCx,
        _action: &ActionId,
        _payload: Box<dyn Any + Send + Sync>,
    ) {
    }

    /// Consume the most recent pending payload for a given action, if still available (ADR 0312).
    ///
    /// Recommended handler semantics when `None`:
    /// - treat as "not handled" (payload missing/expired/mismatched),
    /// - keep behavior diagnosable (best-effort) rather than panicking.
    ///
    /// Hosts that do not support payload actions can return `None`.
    fn consume_pending_action_payload(
        &mut self,
        _window: AppWindowId,
        _action: &ActionId,
    ) -> Option<Box<dyn Any + Send + Sync>> {
        None
    }

    fn dispatch_command(&mut self, window: Option<AppWindowId>, command: CommandId) {
        self.push_effect(Effect::Command { window, command });
    }
}

/// Extra runtime-provided operations available to non-pointer action hooks.
///
/// This is used by keyboard hooks and other global hooks that need to move focus as a policy
/// decision (e.g. menu submenu focus transfer).
pub trait UiFocusActionHost: UiActionHost {
    fn request_focus(&mut self, target: crate::GlobalElementId);
}

/// Host operations for internal (app-owned) drag sessions.
///
/// This is intentionally object-safe so drag flows can be authored via stored action hooks.
/// Payload should typically live in models/globals (not in the drag session payload) to avoid
/// generic APIs in this surface.
pub trait UiDragActionHost: UiActionHost {
    fn begin_drag_with_kind(
        &mut self,
        pointer_id: PointerId,
        kind: DragKindId,
        source_window: AppWindowId,
        start: Point,
    );

    fn begin_cross_window_drag_with_kind(
        &mut self,
        pointer_id: PointerId,
        kind: DragKindId,
        source_window: AppWindowId,
        start: Point,
    );

    fn drag(&self, pointer_id: PointerId) -> Option<&DragSession>;
    fn drag_mut(&mut self, pointer_id: PointerId) -> Option<&mut DragSession>;
    fn cancel_drag(&mut self, pointer_id: PointerId);
}

pub trait UiActionHostExt: UiActionHost {
    fn read_weak_model<T: Any, R>(
        &mut self,
        model: &WeakModel<T>,
        f: impl FnOnce(&T) -> R,
    ) -> Option<R> {
        let model = model.upgrade()?;
        self.models_mut().read(&model, f).ok()
    }

    fn update_model<T: Any, R>(
        &mut self,
        model: &Model<T>,
        f: impl FnOnce(&mut T) -> R,
    ) -> Option<R> {
        self.models_mut().update(model, f).ok()
    }

    fn update_weak_model<T: Any, R>(
        &mut self,
        model: &WeakModel<T>,
        f: impl FnOnce(&mut T) -> R,
    ) -> Option<R> {
        let model = model.upgrade()?;
        self.update_model(&model, f)
    }
}

impl<T> UiActionHostExt for T where T: UiActionHost + ?Sized {}

/// Extra runtime-provided operations available during pointer event hooks.
///
/// This is intentionally separate from `UiActionHost` because pointer capture and cursor updates
/// are mediated by the UI runtime (`UiTree`), not by the app host (`UiHost`).
pub trait UiPointerActionHost: UiFocusActionHost + UiDragActionHost {
    fn bounds(&self) -> fret_core::Rect;
    fn capture_pointer(&mut self);
    fn release_pointer_capture(&mut self);
    fn set_cursor_icon(&mut self, icon: CursorIcon);
    /// Suppress a runtime default action for the current event dispatch.
    ///
    /// This is primarily used to prevent "focus on pointer down" while still allowing propagation
    /// and other policies (overlays, global shortcuts, outside-press) to observe the event.
    fn prevent_default(&mut self, action: DefaultAction);

    /// Request a node-level invalidation for the current pointer region / pressable.
    ///
    /// This is intentionally separate from `notify()`: it enables paint-only updates (e.g. hover
    /// chrome) under view-cache reuse without forcing a rerender.
    fn invalidate(&mut self, _invalidation: crate::widget::Invalidation) {}
}

pub struct UiActionHostAdapter<'a, H: UiHost> {
    pub app: &'a mut H,
}

impl<'a, H: UiHost> UiActionHost for UiActionHostAdapter<'a, H> {
    fn models_mut(&mut self) -> &mut ModelStore {
        self.app.models_mut()
    }

    fn push_effect(&mut self, effect: Effect) {
        self.app.push_effect(effect);
    }

    fn request_redraw(&mut self, window: AppWindowId) {
        self.app.request_redraw(window);
    }

    fn next_timer_token(&mut self) -> TimerToken {
        self.app.next_timer_token()
    }

    fn next_clipboard_token(&mut self) -> fret_runtime::ClipboardToken {
        self.app.next_clipboard_token()
    }

    fn next_share_sheet_token(&mut self) -> fret_runtime::ShareSheetToken {
        self.app.next_share_sheet_token()
    }

    fn set_router_command_availability(
        &mut self,
        window: AppWindowId,
        can_back: bool,
        can_forward: bool,
    ) {
        self.app.with_global_mut(
            fret_runtime::WindowCommandAvailabilityService::default,
            |svc, _app| {
                svc.set_router_availability(window, can_back, can_forward);
            },
        );
    }

    fn record_transient_event(&mut self, cx: ActionCx, key: u64) {
        crate::elements::record_transient_event(&mut *self.app, cx.window, cx.target, key);
    }

    fn record_pending_command_dispatch_source(
        &mut self,
        cx: ActionCx,
        command: &CommandId,
        reason: ActivateReason,
    ) {
        let kind = match reason {
            ActivateReason::Pointer => fret_runtime::CommandDispatchSourceKindV1::Pointer,
            ActivateReason::Keyboard => fret_runtime::CommandDispatchSourceKindV1::Keyboard,
        };
        let source = fret_runtime::CommandDispatchSourceV1 {
            kind,
            element: Some(cx.target.0),
            test_id: None,
        };
        self.app.with_global_mut(
            fret_runtime::WindowPendingCommandDispatchSourceService::default,
            |svc, app| {
                svc.record(cx.window, app.tick_id(), command.clone(), source);
            },
        );
    }
}

impl<'a, H: UiHost> UiDragActionHost for UiActionHostAdapter<'a, H> {
    fn begin_drag_with_kind(
        &mut self,
        pointer_id: PointerId,
        kind: DragKindId,
        source_window: AppWindowId,
        start: Point,
    ) {
        DragHost::begin_drag_with_kind(&mut *self.app, pointer_id, kind, source_window, start, ());
    }

    fn begin_cross_window_drag_with_kind(
        &mut self,
        pointer_id: PointerId,
        kind: DragKindId,
        source_window: AppWindowId,
        start: Point,
    ) {
        DragHost::begin_cross_window_drag_with_kind(
            &mut *self.app,
            pointer_id,
            kind,
            source_window,
            start,
            (),
        );
    }

    fn drag(&self, pointer_id: PointerId) -> Option<&DragSession> {
        DragHost::drag(&*self.app, pointer_id)
    }

    fn drag_mut(&mut self, pointer_id: PointerId) -> Option<&mut DragSession> {
        DragHost::drag_mut(&mut *self.app, pointer_id)
    }

    fn cancel_drag(&mut self, pointer_id: PointerId) {
        DragHost::cancel_drag(&mut *self.app, pointer_id);
    }
}

/// Internal drag event payload for component-owned internal drag handlers.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct InternalDragCx {
    pub pointer_id: PointerId,
    pub position: Point,
    /// Pointer position in window-local logical pixels (pre-mapping).
    ///
    /// This is best-effort: events may arrive before the runtime has recorded a window snapshot.
    pub position_window: Option<Point>,
    pub tick_id: TickId,
    pub kind: InternalDragKind,
    pub modifiers: Modifiers,
}

pub type OnInternalDrag =
    Arc<dyn Fn(&mut dyn UiDragActionHost, ActionCx, InternalDragCx) -> bool + 'static>;

#[derive(Default)]
pub(crate) struct InternalDragActionHooks {
    pub on_internal_drag: Option<OnInternalDrag>,
}

pub type OnExternalDrag =
    Arc<dyn Fn(&mut dyn UiActionHost, ActionCx, &fret_core::ExternalDragEvent) -> bool + 'static>;

#[derive(Default)]
pub(crate) struct ExternalDragActionHooks {
    pub on_external_drag: Option<OnExternalDrag>,
}

pub type OnActivate = Arc<dyn Fn(&mut dyn UiActionHost, ActionCx, ActivateReason) + 'static>;

/// Span activation payload for `SelectableText` interactive spans.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SelectableTextSpanActivation {
    pub tag: Arc<str>,
    pub range: std::ops::Range<usize>,
}

pub type OnSelectableTextActivateSpan = Arc<
    dyn Fn(&mut dyn UiActionHost, ActionCx, ActivateReason, SelectableTextSpanActivation) + 'static,
>;

#[derive(Default)]
pub(crate) struct SelectableTextActionHooks {
    pub on_activate_span: Option<OnSelectableTextActivateSpan>,
}
pub type OnPressablePointerDown = Arc<
    dyn Fn(&mut dyn UiPointerActionHost, ActionCx, PointerDownCx) -> PressablePointerDownResult
        + 'static,
>;
pub type OnPressablePointerMove =
    Arc<dyn Fn(&mut dyn UiPointerActionHost, ActionCx, PointerMoveCx) -> bool + 'static>;
pub type OnPressablePointerUp = Arc<
    dyn Fn(&mut dyn UiPointerActionHost, ActionCx, PointerUpCx) -> PressablePointerUpResult
        + 'static,
>;
pub type OnPressableClipboardWriteCompleted = Arc<
    dyn Fn(
            &mut dyn UiActionHost,
            ActionCx,
            fret_core::ClipboardToken,
            &fret_core::ClipboardWriteOutcome,
        ) -> bool
        + 'static,
>;

#[derive(Default)]
pub(crate) struct PressableActionHooks {
    pub on_activate: Option<OnActivate>,
    pub on_pointer_down: Option<OnPressablePointerDown>,
    pub on_pointer_move: Option<OnPressablePointerMove>,
    pub on_pointer_up: Option<OnPressablePointerUp>,
    pub on_clipboard_write_completed: Option<OnPressableClipboardWriteCompleted>,
}

pub type OnHoverChange = Arc<dyn Fn(&mut dyn UiActionHost, ActionCx, bool) + 'static>;

#[derive(Default)]
pub(crate) struct PressableHoverActionHooks {
    pub on_hover_change: Option<OnHoverChange>,
}

pub type OnDismissRequest =
    Arc<dyn Fn(&mut dyn UiActionHost, ActionCx, &mut DismissRequestCx) + 'static>;

pub type OnOpenAutoFocus =
    Arc<dyn Fn(&mut dyn UiFocusActionHost, ActionCx, &mut AutoFocusRequestCx) + 'static>;

pub type OnCloseAutoFocus =
    Arc<dyn Fn(&mut dyn UiFocusActionHost, ActionCx, &mut AutoFocusRequestCx) + 'static>;

/// Pointer move observer hook for `DismissibleLayer`.
///
/// This is intentionally `UiActionHost` (not `UiPointerActionHost`) so dismissible roots can
/// observe pointer movement without participating in hit-testing or capture.
pub type OnDismissiblePointerMove =
    Arc<dyn Fn(&mut dyn UiActionHost, ActionCx, PointerMoveCx) -> bool + 'static>;

#[derive(Default)]
pub(crate) struct DismissibleActionHooks {
    pub on_dismiss_request: Option<OnDismissRequest>,
    pub on_pointer_move: Option<OnDismissiblePointerMove>,
}

pub type OnTextInputRegionTextInput =
    Arc<dyn Fn(&mut dyn UiActionHost, ActionCx, &str) -> bool + 'static>;

pub type OnTextInputRegionIme =
    Arc<dyn Fn(&mut dyn UiActionHost, ActionCx, &fret_core::ImeEvent) -> bool + 'static>;

pub type OnTextInputRegionClipboardReadText =
    Arc<dyn Fn(&mut dyn UiActionHost, ActionCx, fret_core::ClipboardToken, &str) -> bool + 'static>;

pub type OnTextInputRegionClipboardReadFailed = Arc<
    dyn Fn(
            &mut dyn UiActionHost,
            ActionCx,
            fret_core::ClipboardToken,
            &fret_core::ClipboardAccessError,
        ) -> bool
        + 'static,
>;

pub type OnTextInputRegionSetSelection =
    Arc<dyn Fn(&mut dyn UiActionHost, ActionCx, u32, u32) -> bool + 'static>;

pub type OnTextInputRegionPlatformTextInputQuery = Arc<
    dyn Fn(
            &mut dyn UiActionHost,
            ActionCx,
            &mut dyn UiServices,
            Rect,
            f32,
            &crate::element::TextInputRegionProps,
            &PlatformTextInputQuery,
        ) -> Option<PlatformTextInputQueryResult>
        + 'static,
>;

pub type OnTextInputRegionPlatformTextInputReplaceTextInRangeUtf16 = Arc<
    dyn Fn(
            &mut dyn UiActionHost,
            ActionCx,
            &mut dyn UiServices,
            Rect,
            f32,
            &crate::element::TextInputRegionProps,
            Utf16Range,
            &str,
        ) -> bool
        + 'static,
>;

pub type OnTextInputRegionPlatformTextInputReplaceAndMarkTextInRangeUtf16 = Arc<
    dyn Fn(
            &mut dyn UiActionHost,
            ActionCx,
            &mut dyn UiServices,
            Rect,
            f32,
            &crate::element::TextInputRegionProps,
            Utf16Range,
            &str,
            Option<Utf16Range>,
            Option<Utf16Range>,
        ) -> bool
        + 'static,
>;

#[derive(Default)]
pub(crate) struct TextInputRegionActionHooks {
    pub on_text_input: Option<OnTextInputRegionTextInput>,
    pub on_ime: Option<OnTextInputRegionIme>,
    pub on_clipboard_read_text: Option<OnTextInputRegionClipboardReadText>,
    pub on_clipboard_read_failed: Option<OnTextInputRegionClipboardReadFailed>,
    pub on_set_selection: Option<OnTextInputRegionSetSelection>,
    pub on_platform_text_input_query: Option<OnTextInputRegionPlatformTextInputQuery>,
    pub on_platform_text_input_replace_text_in_range_utf16:
        Option<OnTextInputRegionPlatformTextInputReplaceTextInRangeUtf16>,
    pub on_platform_text_input_replace_and_mark_text_in_range_utf16:
        Option<OnTextInputRegionPlatformTextInputReplaceAndMarkTextInRangeUtf16>,
}

pub type OnPointerDown =
    Arc<dyn Fn(&mut dyn UiPointerActionHost, ActionCx, PointerDownCx) -> bool + 'static>;

pub type OnPointerMove =
    Arc<dyn Fn(&mut dyn UiPointerActionHost, ActionCx, PointerMoveCx) -> bool + 'static>;

pub type OnWheel = Arc<dyn Fn(&mut dyn UiPointerActionHost, ActionCx, WheelCx) -> bool + 'static>;

pub type OnPinchGesture =
    Arc<dyn Fn(&mut dyn UiPointerActionHost, ActionCx, PinchGestureCx) -> bool + 'static>;

pub type OnPointerUp =
    Arc<dyn Fn(&mut dyn UiPointerActionHost, ActionCx, PointerUpCx) -> bool + 'static>;

pub type OnPointerCancel =
    Arc<dyn Fn(&mut dyn UiPointerActionHost, ActionCx, PointerCancelCx) -> bool + 'static>;

#[derive(Default)]
pub(crate) struct PointerActionHooks {
    pub on_pointer_down: Option<OnPointerDown>,
    pub on_pointer_move: Option<OnPointerMove>,
    pub on_wheel: Option<OnWheel>,
    pub on_pinch_gesture: Option<OnPinchGesture>,
    pub on_pointer_up: Option<OnPointerUp>,
    pub on_pointer_cancel: Option<OnPointerCancel>,
}

pub type OnKeyDown = Arc<dyn Fn(&mut dyn UiFocusActionHost, ActionCx, KeyDownCx) -> bool + 'static>;

#[derive(Default)]
pub(crate) struct KeyActionHooks {
    pub on_key_down_capture: Option<OnKeyDown>,
    pub on_key_down: Option<OnKeyDown>,
    /// Key down hook that only fires when the current node is the focus target.
    ///
    /// Use this for widgets that want to handle navigation keys only when they are focused,
    /// without intercepting keys bubbling from focused descendants.
    pub on_key_down_focused: Option<OnKeyDown>,
}

pub type OnCommand = Arc<dyn Fn(&mut dyn UiFocusActionHost, ActionCx, CommandId) -> bool + 'static>;

#[derive(Default)]
pub(crate) struct CommandActionHooks {
    pub on_command: Option<OnCommand>,
}

#[derive(Clone)]
pub(crate) struct ActionRouteOwnerHooks {
    pub owner: TypeId,
    pub on_command: Option<OnCommand>,
    pub on_command_availability: Option<OnCommandAvailability>,
}

/// Owner-scoped action route hooks.
///
/// This lane is separate from the legacy generic command hook slot so app-facing typed action
/// surfaces can coexist on the same element without overwriting one another.
#[derive(Default, Clone)]
pub(crate) struct ActionRouteHooks {
    owners: Vec<ActionRouteOwnerHooks>,
}

impl ActionRouteHooks {
    fn owner_mut(&mut self, owner: TypeId) -> &mut ActionRouteOwnerHooks {
        if let Some(index) = self.owners.iter().position(|hooks| hooks.owner == owner) {
            return &mut self.owners[index];
        }
        self.owners.push(ActionRouteOwnerHooks {
            owner,
            on_command: None,
            on_command_availability: None,
        });
        self.owners
            .last_mut()
            .expect("action route owner slot must exist after insertion")
    }

    pub(crate) fn set_on_command(&mut self, owner: TypeId, handler: OnCommand) {
        self.owner_mut(owner).on_command = Some(handler);
    }

    pub(crate) fn add_on_command(&mut self, owner: TypeId, handler: OnCommand) {
        let hooks = self.owner_mut(owner);
        hooks.on_command = match hooks.on_command.clone() {
            None => Some(handler),
            Some(prev) => {
                let next = handler.clone();
                Some(Arc::new(move |host, cx, command| {
                    prev(host, cx, command.clone()) || next(host, cx, command)
                }))
            }
        };
    }

    pub(crate) fn clear_on_command(&mut self, owner: TypeId) {
        self.owner_mut(owner).on_command = None;
    }

    pub(crate) fn on_command_handlers(&self) -> Vec<OnCommand> {
        self.owners
            .iter()
            .filter_map(|hooks| hooks.on_command.clone())
            .collect()
    }

    pub(crate) fn set_on_command_availability(
        &mut self,
        owner: TypeId,
        handler: OnCommandAvailability,
    ) {
        self.owner_mut(owner).on_command_availability = Some(handler);
    }

    pub(crate) fn add_on_command_availability(
        &mut self,
        owner: TypeId,
        handler: OnCommandAvailability,
    ) {
        let hooks = self.owner_mut(owner);
        hooks.on_command_availability = match hooks.on_command_availability.clone() {
            None => Some(handler),
            Some(prev) => {
                let next = handler.clone();
                Some(Arc::new(move |host, cx, command| {
                    let availability = prev(host, cx.clone(), command.clone());
                    if availability != crate::widget::CommandAvailability::NotHandled {
                        return availability;
                    }
                    next(host, cx, command)
                }))
            }
        };
    }

    pub(crate) fn clear_on_command_availability(&mut self, owner: TypeId) {
        self.owner_mut(owner).on_command_availability = None;
    }

    pub(crate) fn on_command_availability_handlers(&self) -> Vec<OnCommandAvailability> {
        self.owners
            .iter()
            .filter_map(|hooks| hooks.on_command_availability.clone())
            .collect()
    }
}

pub trait UiCommandAvailabilityActionHost {
    fn models_mut(&mut self) -> &mut fret_runtime::ModelStore;
}

#[derive(Debug, Clone)]
pub struct CommandAvailabilityActionCx {
    pub window: fret_core::AppWindowId,
    pub target: crate::GlobalElementId,
    pub node: fret_core::NodeId,
    pub focus: Option<fret_core::NodeId>,
    pub focus_in_subtree: bool,
    pub input_ctx: fret_runtime::InputContext,
}

pub type OnCommandAvailability = Arc<
    dyn Fn(
            &mut dyn UiCommandAvailabilityActionHost,
            CommandAvailabilityActionCx,
            CommandId,
        ) -> crate::widget::CommandAvailability
        + 'static,
>;

#[derive(Default)]
pub(crate) struct CommandAvailabilityActionHooks {
    pub on_command_availability: Option<OnCommandAvailability>,
}

pub type OnTimer = Arc<dyn Fn(&mut dyn UiFocusActionHost, ActionCx, TimerToken) -> bool + 'static>;

#[derive(Default)]
pub(crate) struct TimerActionHooks {
    pub on_timer: Option<OnTimer>,
}

#[derive(Debug, Clone)]
pub struct RovingTypeaheadCx {
    pub input: char,
    pub current: Option<usize>,
    pub len: usize,
    pub disabled: Arc<[bool]>,
    pub wrap: bool,
    pub tick: u64,
}

pub type OnRovingActiveChange = Arc<dyn Fn(&mut dyn UiActionHost, ActionCx, usize) + 'static>;

pub type OnRovingTypeahead =
    Arc<dyn Fn(&mut dyn UiActionHost, ActionCx, RovingTypeaheadCx) -> Option<usize> + 'static>;

#[derive(Debug, Clone)]
pub struct RovingNavigateCx {
    pub key: KeyCode,
    pub modifiers: Modifiers,
    pub repeat: bool,
    pub axis: Axis,
    pub current: Option<usize>,
    pub len: usize,
    pub disabled: Arc<[bool]>,
    pub wrap: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RovingNavigateResult {
    NotHandled,
    Handled { target: Option<usize> },
}

pub type OnRovingNavigate = Arc<
    dyn Fn(&mut dyn UiActionHost, ActionCx, RovingNavigateCx) -> RovingNavigateResult + 'static,
>;

#[derive(Default)]
pub(crate) struct RovingActionHooks {
    pub on_active_change: Option<OnRovingActiveChange>,
    pub on_typeahead: Option<OnRovingTypeahead>,
    pub on_navigate: Option<OnRovingNavigate>,
    pub on_key_down: Vec<OnKeyDown>,
}