xrack-runtime 0.7.0

Runtime types, properties, models, and controls for generated XRack UI
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
use crate::{Component, InputRoute, Node, Property, RoutedEvent};
use std::{
    cell::{Cell, RefCell},
    fmt,
    ops::Range,
    rc::Rc,
    time::{Duration, Instant},
};

/// Identity of a focus target in one component instance.
#[derive(Clone, Default)]
pub struct FocusHandle(Rc<FocusSignals>);

/// Reactive press state for one observed push button.
#[derive(Clone, Default)]
#[doc(hidden)]
pub struct ButtonPressHandle(Rc<ButtonPressState>);

#[derive(Default)]
struct ButtonPressState {
    pressed: Property<bool>,
    physical: Cell<bool>,
    synthetic: Cell<bool>,
    clicking: Cell<bool>,
    animation: Option<Box<Cell<Option<Instant>>>>,
}

struct ButtonClick<'a>(&'a ButtonPressState);

impl ButtonClick<'_> {
    fn release(&self) {
        self.0.synthetic.set(false);
        self.0.pressed.set_if_changed(self.0.physical.get());
    }
}

impl Drop for ButtonClick<'_> {
    fn drop(&mut self) {
        if self
            .0
            .animation
            .as_ref()
            .is_none_or(|deadline| deadline.get().is_none())
        {
            self.release();
        }
        self.0.clicking.set(false);
    }
}

impl fmt::Debug for ButtonPressHandle {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ButtonPressHandle").finish_non_exhaustive()
    }
}

impl PartialEq for ButtonPressHandle {
    fn eq(&self, other: &Self) -> bool {
        Rc::ptr_eq(&self.0, &other.0)
    }
}

impl ButtonPressHandle {
    pub fn animated() -> Self {
        Self(Rc::new(ButtonPressState {
            animation: Some(Box::default()),
            ..ButtonPressState::default()
        }))
    }

    pub fn pressed(&self) -> bool {
        self.0.pressed.get(|| false)
    }

    pub fn publish(&self, pressed: bool) {
        self.0.physical.set(pressed);
        self.0
            .pressed
            .set_if_changed(pressed || self.0.synthetic.get());
    }

    pub fn is_synthetic_pressed(&self) -> bool {
        self.0.synthetic.get()
    }

    pub fn supports_animation(&self) -> bool {
        self.0.animation.is_some()
    }

    fn deadline(&self) -> Option<Instant> {
        self.0.animation.as_ref()?.get()
    }

    pub fn cancel_animation(&self) -> bool {
        if self
            .0
            .animation
            .as_ref()
            .and_then(|deadline| deadline.take())
            .is_none()
        {
            return false;
        }
        self.0.synthetic.set(false);
        self.0.pressed.set_if_changed(self.0.physical.get());
        true
    }

    /// Activate a mounted button using the component's ordinary input route.
    pub fn try_click<E>(
        &self,
        render: impl FnMut() -> Rc<Node>,
        route: impl FnMut(&Node, &[usize], InputRoute<'_>) -> Result<bool, E>,
    ) -> Result<(), E> {
        self.try_click_with_delay(render, route, None)
    }

    /// Press now and let the window scheduler deliver the release.
    pub fn try_animate_click<E>(
        &self,
        render: impl FnMut() -> Rc<Node>,
        route: impl FnMut(&Node, &[usize], InputRoute<'_>) -> Result<bool, E>,
    ) -> Result<(), E> {
        let Some(deadline) = self.0.animation.as_deref() else {
            return Ok(());
        };
        self.try_click_with_delay(render, route, Some(deadline))
    }

    fn try_click_with_delay<E>(
        &self,
        mut render: impl FnMut() -> Rc<Node>,
        mut route: impl FnMut(&Node, &[usize], InputRoute<'_>) -> Result<bool, E>,
        deadline: Option<&Cell<Option<Instant>>>,
    ) -> Result<(), E> {
        if self.0.clicking.get() || self.0.physical.get() {
            return Ok(());
        }
        let next_deadline = || Some(Instant::now() + Duration::from_millis(100));
        if self.deadline().is_some() {
            if let Some(deadline) = deadline {
                let scene = render();
                if self
                    .path_in(&scene)
                    .is_some_and(|path| self.is_available(&scene, &path))
                {
                    deadline.set(next_deadline());
                }
            }
            return Ok(());
        }
        // Retain the guard through clicked(), even after the press has been released.
        self.0.clicking.set(true);
        let click = ButtonClick(&self.0);
        let scene = render();
        let Some(path) = self.path_in(&scene) else {
            return Ok(());
        };
        let Some(node) = scene.interactive_at_path(&path) else {
            return Ok(());
        };
        self.0.synthetic.set(true);
        self.0.pressed.set_if_changed(true);
        if node.boolean("focus-on-click", true)
            && let Some(handle) = &node.focus_handle
        {
            handle.request(FocusAction::Focus);
        }
        let mut send = |scene: &Node, event| {
            if !scene
                .at_path(&path)
                .is_some_and(|node| node.button_press_handle.as_ref() == Some(self))
            {
                return Ok(false);
            }
            RoutedEvent::Dispatch(event)
                .with_input(scene, &path, |input| route(scene, &path, input))
                .unwrap_or(Ok(false))
        };
        send(&scene, "pressed")?;
        if let Some(deadline) = deadline {
            let scene = render();
            if self.is_available(&scene, &path) {
                deadline.set(next_deadline());
            } else {
                click.release();
                send(&scene, "canceled")?;
            }
            return Ok(());
        }
        click.release();
        let scene = render();
        if !self.is_available(&scene, &path) {
            send(&scene, "canceled")?;
        } else {
            send(&scene, "released")?;
            send(&render(), "clicked")?;
        }
        Ok(())
    }

    fn is_available(&self, scene: &Node, path: &[usize]) -> bool {
        scene
            .interactive_at_path(path)
            .is_some_and(|node| node.button_press_handle.as_ref() == Some(self))
    }

    fn path_in(&self, scene: &Node) -> Option<Vec<usize>> {
        fn find(node: &Node, handle: &ButtonPressHandle, path: &mut Vec<usize>) -> bool {
            if node.button_press_handle.as_ref() == Some(handle) {
                return true;
            }
            for (index, child) in node.children.iter().enumerate() {
                path.push(index);
                if find(child, handle, path) {
                    return true;
                }
                path.pop();
            }
            false
        }
        let mut path = Vec::new();
        find(scene, self, &mut path).then_some(path)
    }
}

/// Mounted buttons with animated activations, owned by the window scheduler.
#[doc(hidden)]
#[derive(Default)]
pub struct ButtonAnimations(Vec<(ButtonPressHandle, bool)>);

impl ButtonAnimations {
    pub fn sync<'a>(&mut self, handles: impl IntoIterator<Item = &'a ButtonPressHandle>) {
        let next: Vec<_> = handles
            .into_iter()
            .map(|handle| {
                let was_pressed = self
                    .0
                    .iter()
                    .find(|entry| &entry.0 == handle)
                    .is_some_and(|entry| entry.1);
                (handle.clone(), was_pressed)
            })
            .collect();
        for (old, _) in &self.0 {
            if !next.iter().any(|entry| &entry.0 == old) {
                old.cancel_animation();
            }
        }
        self.0 = next;
    }

    pub fn deadline(&self) -> Option<Instant> {
        self.0.iter().filter_map(|entry| entry.0.deadline()).min()
    }

    pub fn take_redraw(&mut self) -> bool {
        let mut changed = false;
        for (handle, previous) in &mut self.0 {
            changed |= std::mem::replace(previous, handle.is_synthetic_pressed()) != *previous;
        }
        changed
    }

    pub fn next(&self, scene: &Node, now: Instant) -> Option<ButtonAnimationDelivery> {
        for (handle, _) in &self.0 {
            let Some(deadline) = handle.deadline() else {
                continue;
            };
            let Some(path) = handle.path_in(scene) else {
                handle.cancel_animation();
                continue;
            };
            let release = handle.is_available(scene, &path);
            if !release || now >= deadline {
                handle.cancel_animation();
                return Some(ButtonAnimationDelivery {
                    handle: handle.clone(),
                    path,
                    release,
                });
            }
        }
        None
    }
}

impl Drop for ButtonAnimations {
    fn drop(&mut self) {
        for (handle, _) in &self.0 {
            handle.cancel_animation();
        }
    }
}

#[doc(hidden)]
pub struct ButtonAnimationDelivery {
    handle: ButtonPressHandle,
    path: Vec<usize>,
    release: bool,
}

impl ButtonAnimationDelivery {
    pub fn apply(self, ui: &mut impl Component, scene: &Node) {
        self.handle.0.clicking.set(true);
        let _click = ButtonClick(&self.handle.0);
        if self.release {
            RoutedEvent::Dispatch("released").deliver_input(ui, scene, &self.path);
            RoutedEvent::Dispatch("clicked").deliver_input(ui, scene, &self.path);
        } else {
            RoutedEvent::Dispatch("canceled").deliver_input(ui, scene, &self.path);
        }
    }
}

#[derive(Default)]
struct FocusSignals {
    direct: Property<bool>,
    within: Property<bool>,
    text: Option<Box<TextSelectionSignals>>,
    commands: Option<Box<TextCommandSignals>>,
    editing: RefCell<Option<EditorChange>>,
}

struct EditorChange {
    initial: String,
    draft: String,
}

#[derive(Default)]
struct TextSelectionSignals {
    offsets: [Property<i64>; 3],
    selected: Property<Rc<str>>,
}

#[derive(Default)]
struct TextCommandSignals {
    undo: Property<bool>,
    redo: Property<bool>,
    cut: Property<bool>,
    copy: Property<bool>,
}

/// Availability of commands on the active text editor.
#[doc(hidden)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct TextCommandAvailability {
    pub undo: bool,
    pub redo: bool,
    pub cut: bool,
    pub copy: bool,
}

impl fmt::Debug for FocusHandle {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("FocusHandle").finish_non_exhaustive()
    }
}

impl PartialEq for FocusHandle {
    fn eq(&self, other: &Self) -> bool {
        Rc::ptr_eq(&self.0, &other.0)
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FocusAction {
    Focus,
    Clear,
    OpenChoice,
    CloseChoice,
    Text(TextCommand),
    EditTableCell { row: i64, column: i64 },
    CancelTableEdit,
}

/// Replace the given byte range in a live editor. Positions are clamped by its text layout.
#[doc(hidden)]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TextReplacement {
    pub start: i64,
    pub end: i64,
    pub text: String,
}

/// A programmatic edit using the same selection, validation and history as keyboard input.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TextCommand {
    SelectAll,
    SelectWord,
    ClearSelection,
    SetSelection { anchor: i64, focus: i64 },
    Undo,
    Redo,
    Cut,
    Copy,
    Paste,
}

/// Commands lowered from XR focus and editor methods.
#[doc(hidden)]
#[derive(Clone, Copy, Debug)]
pub enum FocusCommandMethod {
    Focus,
    Clear,
    OpenChoice,
    CloseChoice,
    SelectAll,
    SelectWord,
    ClearSelection,
    SetSelection,
    Undo,
    Redo,
    Cut,
    Copy,
    Paste,
    EditTableCell,
    CancelTableEdit,
    InsertText,
    ReplaceText,
    RemoveText,
    AppendText,
    ClearText,
}

impl FocusCommandMethod {
    pub fn parse(name: &str) -> Option<Self> {
        Some(match name {
            "focus" => Self::Focus,
            "clear" => Self::Clear,
            "open-popup" => Self::OpenChoice,
            "close-popup" => Self::CloseChoice,
            "select-all" => Self::SelectAll,
            "select-word" => Self::SelectWord,
            "clear-selection" => Self::ClearSelection,
            "set-selection-offsets" => Self::SetSelection,
            "undo" => Self::Undo,
            "redo" => Self::Redo,
            "cut" => Self::Cut,
            "copy" => Self::Copy,
            "paste" => Self::Paste,
            "edit-cell" => Self::EditTableCell,
            "cancel-edit" => Self::CancelTableEdit,
            "insert-text" => Self::InsertText,
            "replace-text" => Self::ReplaceText,
            "remove-text" => Self::RemoveText,
            "append-text" => Self::AppendText,
            "clear-text" => Self::ClearText,
            _ => return None,
        })
    }

    pub fn action(self, operands: &[i64]) -> Option<FocusAction> {
        let text = match (self, operands) {
            (Self::Focus, []) => return Some(FocusAction::Focus),
            (Self::Clear, []) => return Some(FocusAction::Clear),
            (Self::OpenChoice, []) => return Some(FocusAction::OpenChoice),
            (Self::CloseChoice, []) => return Some(FocusAction::CloseChoice),
            (Self::SelectAll, []) => TextCommand::SelectAll,
            (Self::SelectWord, []) => TextCommand::SelectWord,
            (Self::ClearSelection, []) => TextCommand::ClearSelection,
            (Self::SetSelection, &[anchor, focus]) => TextCommand::SetSelection { anchor, focus },
            (Self::Undo, []) => TextCommand::Undo,
            (Self::Redo, []) => TextCommand::Redo,
            (Self::Cut, []) => TextCommand::Cut,
            (Self::Copy, []) => TextCommand::Copy,
            (Self::Paste, []) => TextCommand::Paste,
            (Self::EditTableCell, &[row, column]) => {
                return Some(FocusAction::EditTableCell { row, column });
            }
            (Self::CancelTableEdit, []) => return Some(FocusAction::CancelTableEdit),
            _ => return None,
        };
        Some(FocusAction::Text(text))
    }

    pub fn uses_text_operand(self) -> bool {
        matches!(
            self,
            Self::InsertText | Self::ReplaceText | Self::AppendText
        )
    }

    pub fn edits_text(self) -> bool {
        self.uses_text_operand() || matches!(self, Self::RemoveText | Self::ClearText)
    }

    pub fn replacement(self, offsets: &[i64], text: String) -> Option<TextReplacement> {
        let (start, end) = match (self, offsets) {
            (Self::InsertText, &[offset]) => (offset, offset),
            (Self::ReplaceText | Self::RemoveText, &[start, end]) => (start, end),
            (Self::AppendText, []) => (i64::MAX, i64::MAX),
            (Self::ClearText, []) => (0, i64::MAX),
            _ => return None,
        };
        Some(TextReplacement { start, end, text })
    }
}

#[doc(hidden)]
pub fn is_focus_handler(name: &str) -> bool {
    FocusHandler::ALL
        .iter()
        .any(|handler| handler.name() == name)
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum FocusReason {
    #[default]
    Programmatic,
    TabNavigation,
    PointerClick,
    PopupActivation,
    WindowActivation,
    Accessibility,
    LayoutChange,
    KeyboardNavigation,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FocusEvent {
    Gained(FocusReason),
    Lost(FocusReason),
    Within { focused: bool, reason: FocusReason },
}

#[derive(Clone, Copy, Debug)]
#[doc(hidden)]
pub enum FocusHandler {
    Gained,
    Lost,
    Changed,
    Within,
}

impl FocusHandler {
    pub const ALL: [Self; 4] = [Self::Gained, Self::Lost, Self::Changed, Self::Within];

    pub fn name(self) -> &'static str {
        match self {
            Self::Gained => "focus-gained",
            Self::Lost => "focus-lost",
            Self::Changed => "focus-changed-event",
            Self::Within => "focus-within-changed",
        }
    }
}

impl FocusEvent {
    #[doc(hidden)]
    pub fn is_loss(self) -> bool {
        matches!(self, Self::Lost(_) | Self::Within { focused: false, .. })
    }

    #[doc(hidden)]
    pub fn try_deliver<E>(
        self,
        mut notify: impl FnMut(FocusHandler, bool, FocusReason) -> Result<bool, E>,
    ) -> Result<bool, E> {
        let (handler, focused, reason) = match self {
            Self::Gained(reason) => (FocusHandler::Gained, true, reason),
            Self::Lost(reason) => (FocusHandler::Lost, false, reason),
            Self::Within { focused, reason } => {
                return notify(FocusHandler::Within, focused, reason);
            }
        };
        let handled = notify(handler, focused, reason)?;
        Ok(notify(FocusHandler::Changed, focused, reason)? || handled)
    }

    #[doc(hidden)]
    pub fn deliver(self, mut notify: impl FnMut(FocusHandler, bool, FocusReason) -> bool) -> bool {
        self.try_deliver(|handler, focused, reason| {
            Ok::<_, std::convert::Infallible>(notify(handler, focused, reason))
        })
        .unwrap_or_else(|error| match error {})
    }
}

pub struct FocusRequest {
    pub target: FocusHandle,
    pub action: FocusAction,
}

#[doc(hidden)]
pub enum QueuedFocusRequest {
    Focus(FocusRequest),
    ReplaceText {
        target: FocusHandle,
        replacement: TextReplacement,
    },
}

/// A window's commands, drained against the scene prepared after the callback.
#[derive(Clone, Default)]
pub struct FocusRequests(Rc<RefCell<Vec<QueuedFocusRequest>>>);

thread_local! {
    static ACTIVE: RefCell<Option<FocusRequests>> = const { RefCell::new(None) };
}

pub struct FocusContext(Option<FocusRequests>);

impl FocusRequests {
    pub fn enter(&self) -> FocusContext {
        FocusContext(ACTIVE.with(|active| active.replace(Some(self.clone()))))
    }

    pub fn drain(&self) -> Vec<FocusRequest> {
        self.drain_commands()
            .into_iter()
            .filter_map(|command| match command {
                QueuedFocusRequest::Focus(request) => Some(request),
                QueuedFocusRequest::ReplaceText { .. } => None,
            })
            .collect()
    }

    #[doc(hidden)]
    pub fn drain_commands(&self) -> Vec<QueuedFocusRequest> {
        std::mem::take(&mut *self.0.borrow_mut())
    }

    pub fn is_empty(&self) -> bool {
        self.0.borrow().is_empty()
    }
}

impl Drop for FocusContext {
    fn drop(&mut self) {
        ACTIVE.with(|active| active.replace(self.0.take()));
    }
}

impl FocusHandle {
    #[doc(hidden)]
    pub fn with_text_selection() -> Self {
        Self::with_text_state(true, false)
    }

    #[doc(hidden)]
    pub fn with_text_state(selection: bool, commands: bool) -> Self {
        Self(Rc::new(FocusSignals {
            text: selection.then(Box::default),
            commands: commands.then(Box::default),
            ..FocusSignals::default()
        }))
    }

    #[doc(hidden)]
    pub fn record_editor_edit(&self, before: &str, after: &str) {
        if before == after {
            return;
        }
        let mut editing = self.0.editing.borrow_mut();
        let initial = editing
            .take()
            .filter(|editing| editing.draft == before)
            .map_or_else(|| before.to_owned(), |editing| editing.initial);
        if initial != after {
            *editing = Some(EditorChange {
                initial,
                draft: after.to_owned(),
            });
        }
    }

    #[doc(hidden)]
    pub fn has_editor_changes(&self) -> bool {
        self.0.editing.borrow().is_some()
    }

    #[doc(hidden)]
    pub fn take_editor_changes(&self, current: &str) -> bool {
        self.0
            .editing
            .borrow_mut()
            .take()
            .is_some_and(|editing| editing.draft == current)
    }

    #[doc(hidden)]
    pub fn discard_editor_changes(&self) {
        self.0.editing.borrow_mut().take();
    }

    #[doc(hidden)]
    pub fn observes_text_commands(&self) -> bool {
        self.0.commands.is_some()
    }

    #[doc(hidden)]
    pub fn publish_text_commands(&self, commands: TextCommandAvailability) {
        if let Some(signals) = &self.0.commands {
            signals.undo.set_if_changed(commands.undo);
            signals.redo.set_if_changed(commands.redo);
            signals.cut.set_if_changed(commands.cut);
            signals.copy.set_if_changed(commands.copy);
        }
    }

    #[doc(hidden)]
    pub fn clear_text_state(&self) {
        self.publish_text_selection(0, 0..0, "");
        self.publish_text_commands(TextCommandAvailability::default());
    }

    pub fn can_undo(&self) -> bool {
        self.0
            .commands
            .as_ref()
            .is_some_and(|signals| signals.undo.get(|| false))
    }

    pub fn can_redo(&self) -> bool {
        self.0
            .commands
            .as_ref()
            .is_some_and(|signals| signals.redo.get(|| false))
    }

    pub fn can_cut(&self) -> bool {
        self.0
            .commands
            .as_ref()
            .is_some_and(|signals| signals.cut.get(|| false))
    }

    pub fn can_copy(&self) -> bool {
        self.0
            .commands
            .as_ref()
            .is_some_and(|signals| signals.copy.get(|| false))
    }

    #[doc(hidden)]
    pub fn observes_text_selection(&self) -> bool {
        self.0.text.is_some()
    }

    #[doc(hidden)]
    pub fn publish_text_selection(&self, caret: usize, selection: Range<usize>, text: &str) {
        if let Some(signals) = &self.0.text {
            for (offset, value) in
                signals
                    .offsets
                    .iter()
                    .zip([caret, selection.start, selection.end])
            {
                offset.set_if_changed(value as i64);
            }
            if signals.selected.explicit_value().as_deref() != Some(text) {
                signals.selected.set(Rc::from(text));
            }
        }
    }

    fn text_offset(&self, index: usize) -> i64 {
        self.0
            .text
            .as_ref()
            .map_or(0, |signals| signals.offsets[index].get(|| 0))
    }

    pub fn cursor_offset(&self) -> i64 {
        self.text_offset(0)
    }

    pub fn selection_start_offset(&self) -> i64 {
        self.text_offset(1)
    }

    pub fn selection_end_offset(&self) -> i64 {
        self.text_offset(2)
    }

    pub fn selected_text(&self) -> String {
        self.0.text.as_ref().map_or_else(String::new, |signals| {
            signals.selected.get(|| Rc::from("")).to_string()
        })
    }

    pub fn has_focus(&self) -> bool {
        self.0.direct.get(|| false)
    }

    pub fn focus_within(&self) -> bool {
        self.0.within.get(|| false)
    }

    #[doc(hidden)]
    pub fn publish(&self, direct: bool, within: bool) {
        self.0.direct.set_if_changed(direct);
        self.0.within.set_if_changed(within);
    }

    pub fn request(&self, action: FocusAction) {
        Self::enqueue(QueuedFocusRequest::Focus(FocusRequest {
            target: self.clone(),
            action,
        }));
    }

    #[doc(hidden)]
    pub fn request_text_edit(&self, replacement: TextReplacement) {
        Self::enqueue(QueuedFocusRequest::ReplaceText {
            target: self.clone(),
            replacement,
        });
    }

    fn enqueue(request: QueuedFocusRequest) {
        ACTIVE.with(|active| {
            if let Some(requests) = &*active.borrow() {
                requests.0.borrow_mut().push(request);
            }
        });
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn selection_start_and_selected_text_track_independently() {
        let handle = FocusHandle::with_text_selection();
        let start = Property::default();
        let selected = Property::default();
        handle.publish_text_selection(3, 1..3, "bc");
        assert_eq!(start.get(|| handle.selection_start_offset()), 1);
        assert_eq!(selected.get(|| handle.selected_text()), "bc");

        handle.publish_text_selection(4, 1..4, "bcd");
        assert!(!start.is_dirty());
        assert!(selected.is_dirty());
        assert_eq!(selected.get(|| handle.selected_text()), "bcd");

        handle.publish_text_selection(1, 1..4, "bcd");
        assert!(!start.is_dirty());
        assert!(!selected.is_dirty());
    }

    #[test]
    fn direct_and_within_focus_have_independent_dependencies() {
        let handle = FocusHandle::default();
        let direct = Property::default();
        let within = Property::default();
        assert!(!direct.get(|| handle.has_focus()));
        assert!(!within.get(|| handle.focus_within()));
        handle.publish(false, true);
        assert!(!direct.is_dirty());
        assert!(within.is_dirty());
        assert!(within.get(|| handle.focus_within()));
        handle.publish(true, true);
        assert!(direct.is_dirty());
        assert!(!within.is_dirty());
    }
}