1use crate::{Component, InputRoute, Node, Property, RoutedEvent};
2use std::{
3 cell::{Cell, RefCell},
4 fmt,
5 ops::Range,
6 rc::Rc,
7 time::{Duration, Instant},
8};
9
10#[derive(Clone, Default)]
12pub struct FocusHandle(Rc<FocusSignals>);
13
14#[derive(Clone, Default)]
16#[doc(hidden)]
17pub struct ButtonPressHandle(Rc<ButtonPressState>);
18
19#[derive(Default)]
20struct ButtonPressState {
21 pressed: Property<bool>,
22 physical: Cell<bool>,
23 synthetic: Cell<bool>,
24 clicking: Cell<bool>,
25 animation: Option<Box<Cell<Option<Instant>>>>,
26}
27
28struct ButtonClick<'a>(&'a ButtonPressState);
29
30impl ButtonClick<'_> {
31 fn release(&self) {
32 self.0.synthetic.set(false);
33 self.0.pressed.set_if_changed(self.0.physical.get());
34 }
35}
36
37impl Drop for ButtonClick<'_> {
38 fn drop(&mut self) {
39 if self
40 .0
41 .animation
42 .as_ref()
43 .is_none_or(|deadline| deadline.get().is_none())
44 {
45 self.release();
46 }
47 self.0.clicking.set(false);
48 }
49}
50
51impl fmt::Debug for ButtonPressHandle {
52 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
53 f.debug_struct("ButtonPressHandle").finish_non_exhaustive()
54 }
55}
56
57impl PartialEq for ButtonPressHandle {
58 fn eq(&self, other: &Self) -> bool {
59 Rc::ptr_eq(&self.0, &other.0)
60 }
61}
62
63impl ButtonPressHandle {
64 pub fn animated() -> Self {
65 Self(Rc::new(ButtonPressState {
66 animation: Some(Box::default()),
67 ..ButtonPressState::default()
68 }))
69 }
70
71 pub fn pressed(&self) -> bool {
72 self.0.pressed.get(|| false)
73 }
74
75 pub fn publish(&self, pressed: bool) {
76 self.0.physical.set(pressed);
77 self.0
78 .pressed
79 .set_if_changed(pressed || self.0.synthetic.get());
80 }
81
82 pub fn is_synthetic_pressed(&self) -> bool {
83 self.0.synthetic.get()
84 }
85
86 pub fn supports_animation(&self) -> bool {
87 self.0.animation.is_some()
88 }
89
90 fn deadline(&self) -> Option<Instant> {
91 self.0.animation.as_ref()?.get()
92 }
93
94 pub fn cancel_animation(&self) -> bool {
95 if self
96 .0
97 .animation
98 .as_ref()
99 .and_then(|deadline| deadline.take())
100 .is_none()
101 {
102 return false;
103 }
104 self.0.synthetic.set(false);
105 self.0.pressed.set_if_changed(self.0.physical.get());
106 true
107 }
108
109 pub fn try_click<E>(
111 &self,
112 render: impl FnMut() -> Rc<Node>,
113 route: impl FnMut(&Node, &[usize], InputRoute<'_>) -> Result<bool, E>,
114 ) -> Result<(), E> {
115 self.try_click_with_delay(render, route, None)
116 }
117
118 pub fn try_animate_click<E>(
120 &self,
121 render: impl FnMut() -> Rc<Node>,
122 route: impl FnMut(&Node, &[usize], InputRoute<'_>) -> Result<bool, E>,
123 ) -> Result<(), E> {
124 let Some(deadline) = self.0.animation.as_deref() else {
125 return Ok(());
126 };
127 self.try_click_with_delay(render, route, Some(deadline))
128 }
129
130 fn try_click_with_delay<E>(
131 &self,
132 mut render: impl FnMut() -> Rc<Node>,
133 mut route: impl FnMut(&Node, &[usize], InputRoute<'_>) -> Result<bool, E>,
134 deadline: Option<&Cell<Option<Instant>>>,
135 ) -> Result<(), E> {
136 if self.0.clicking.get() || self.0.physical.get() {
137 return Ok(());
138 }
139 let next_deadline = || Some(Instant::now() + Duration::from_millis(100));
140 if self.deadline().is_some() {
141 if let Some(deadline) = deadline {
142 let scene = render();
143 if self
144 .path_in(&scene)
145 .is_some_and(|path| self.is_available(&scene, &path))
146 {
147 deadline.set(next_deadline());
148 }
149 }
150 return Ok(());
151 }
152 self.0.clicking.set(true);
154 let click = ButtonClick(&self.0);
155 let scene = render();
156 let Some(path) = self.path_in(&scene) else {
157 return Ok(());
158 };
159 let Some(node) = scene.interactive_at_path(&path) else {
160 return Ok(());
161 };
162 self.0.synthetic.set(true);
163 self.0.pressed.set_if_changed(true);
164 if node.boolean("focus-on-click", true)
165 && let Some(handle) = &node.focus_handle
166 {
167 handle.request(FocusAction::Focus);
168 }
169 let mut send = |scene: &Node, event| {
170 if !scene
171 .at_path(&path)
172 .is_some_and(|node| node.button_press_handle.as_ref() == Some(self))
173 {
174 return Ok(false);
175 }
176 RoutedEvent::Dispatch(event)
177 .with_input(scene, &path, |input| route(scene, &path, input))
178 .unwrap_or(Ok(false))
179 };
180 send(&scene, "pressed")?;
181 if let Some(deadline) = deadline {
182 let scene = render();
183 if self.is_available(&scene, &path) {
184 deadline.set(next_deadline());
185 } else {
186 click.release();
187 send(&scene, "canceled")?;
188 }
189 return Ok(());
190 }
191 click.release();
192 let scene = render();
193 if !self.is_available(&scene, &path) {
194 send(&scene, "canceled")?;
195 } else {
196 send(&scene, "released")?;
197 send(&render(), "clicked")?;
198 }
199 Ok(())
200 }
201
202 fn is_available(&self, scene: &Node, path: &[usize]) -> bool {
203 scene
204 .interactive_at_path(path)
205 .is_some_and(|node| node.button_press_handle.as_ref() == Some(self))
206 }
207
208 fn path_in(&self, scene: &Node) -> Option<Vec<usize>> {
209 fn find(node: &Node, handle: &ButtonPressHandle, path: &mut Vec<usize>) -> bool {
210 if node.button_press_handle.as_ref() == Some(handle) {
211 return true;
212 }
213 for (index, child) in node.children.iter().enumerate() {
214 path.push(index);
215 if find(child, handle, path) {
216 return true;
217 }
218 path.pop();
219 }
220 false
221 }
222 let mut path = Vec::new();
223 find(scene, self, &mut path).then_some(path)
224 }
225}
226
227#[doc(hidden)]
229#[derive(Default)]
230pub struct ButtonAnimations(Vec<(ButtonPressHandle, bool)>);
231
232impl ButtonAnimations {
233 pub fn sync<'a>(&mut self, handles: impl IntoIterator<Item = &'a ButtonPressHandle>) {
234 let next: Vec<_> = handles
235 .into_iter()
236 .map(|handle| {
237 let was_pressed = self
238 .0
239 .iter()
240 .find(|entry| &entry.0 == handle)
241 .is_some_and(|entry| entry.1);
242 (handle.clone(), was_pressed)
243 })
244 .collect();
245 for (old, _) in &self.0 {
246 if !next.iter().any(|entry| &entry.0 == old) {
247 old.cancel_animation();
248 }
249 }
250 self.0 = next;
251 }
252
253 pub fn deadline(&self) -> Option<Instant> {
254 self.0.iter().filter_map(|entry| entry.0.deadline()).min()
255 }
256
257 pub fn take_redraw(&mut self) -> bool {
258 let mut changed = false;
259 for (handle, previous) in &mut self.0 {
260 changed |= std::mem::replace(previous, handle.is_synthetic_pressed()) != *previous;
261 }
262 changed
263 }
264
265 pub fn next(&self, scene: &Node, now: Instant) -> Option<ButtonAnimationDelivery> {
266 for (handle, _) in &self.0 {
267 let Some(deadline) = handle.deadline() else {
268 continue;
269 };
270 let Some(path) = handle.path_in(scene) else {
271 handle.cancel_animation();
272 continue;
273 };
274 let release = handle.is_available(scene, &path);
275 if !release || now >= deadline {
276 handle.cancel_animation();
277 return Some(ButtonAnimationDelivery {
278 handle: handle.clone(),
279 path,
280 release,
281 });
282 }
283 }
284 None
285 }
286}
287
288impl Drop for ButtonAnimations {
289 fn drop(&mut self) {
290 for (handle, _) in &self.0 {
291 handle.cancel_animation();
292 }
293 }
294}
295
296#[doc(hidden)]
297pub struct ButtonAnimationDelivery {
298 handle: ButtonPressHandle,
299 path: Vec<usize>,
300 release: bool,
301}
302
303impl ButtonAnimationDelivery {
304 pub fn apply(self, ui: &mut impl Component, scene: &Node) {
305 self.handle.0.clicking.set(true);
306 let _click = ButtonClick(&self.handle.0);
307 if self.release {
308 RoutedEvent::Dispatch("released").deliver_input(ui, scene, &self.path);
309 RoutedEvent::Dispatch("clicked").deliver_input(ui, scene, &self.path);
310 } else {
311 RoutedEvent::Dispatch("canceled").deliver_input(ui, scene, &self.path);
312 }
313 }
314}
315
316#[derive(Default)]
317struct FocusSignals {
318 direct: Property<bool>,
319 within: Property<bool>,
320 text: Option<Box<TextSelectionSignals>>,
321 commands: Option<Box<TextCommandSignals>>,
322 editing: RefCell<Option<EditorChange>>,
323}
324
325struct EditorChange {
326 initial: String,
327 draft: String,
328}
329
330#[derive(Default)]
331struct TextSelectionSignals {
332 offsets: [Property<i64>; 3],
333 selected: Property<Rc<str>>,
334}
335
336#[derive(Default)]
337struct TextCommandSignals {
338 undo: Property<bool>,
339 redo: Property<bool>,
340 cut: Property<bool>,
341 copy: Property<bool>,
342}
343
344#[doc(hidden)]
346#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
347pub struct TextCommandAvailability {
348 pub undo: bool,
349 pub redo: bool,
350 pub cut: bool,
351 pub copy: bool,
352}
353
354impl fmt::Debug for FocusHandle {
355 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
356 f.debug_struct("FocusHandle").finish_non_exhaustive()
357 }
358}
359
360impl PartialEq for FocusHandle {
361 fn eq(&self, other: &Self) -> bool {
362 Rc::ptr_eq(&self.0, &other.0)
363 }
364}
365
366#[derive(Clone, Copy, Debug, PartialEq, Eq)]
367pub enum FocusAction {
368 Focus,
369 Clear,
370 OpenChoice,
371 CloseChoice,
372 Text(TextCommand),
373 EditTableCell { row: i64, column: i64 },
374 CancelTableEdit,
375}
376
377#[doc(hidden)]
379#[derive(Clone, Debug, PartialEq, Eq)]
380pub struct TextReplacement {
381 pub start: i64,
382 pub end: i64,
383 pub text: String,
384}
385
386#[derive(Clone, Copy, Debug, PartialEq, Eq)]
388pub enum TextCommand {
389 SelectAll,
390 SelectWord,
391 ClearSelection,
392 SetSelection { anchor: i64, focus: i64 },
393 Undo,
394 Redo,
395 Cut,
396 Copy,
397 Paste,
398}
399
400#[doc(hidden)]
402#[derive(Clone, Copy, Debug)]
403pub enum FocusCommandMethod {
404 Focus,
405 Clear,
406 OpenChoice,
407 CloseChoice,
408 SelectAll,
409 SelectWord,
410 ClearSelection,
411 SetSelection,
412 Undo,
413 Redo,
414 Cut,
415 Copy,
416 Paste,
417 EditTableCell,
418 CancelTableEdit,
419 InsertText,
420 ReplaceText,
421 RemoveText,
422 AppendText,
423 ClearText,
424}
425
426impl FocusCommandMethod {
427 pub fn parse(name: &str) -> Option<Self> {
428 Some(match name {
429 "focus" => Self::Focus,
430 "clear" => Self::Clear,
431 "open-popup" => Self::OpenChoice,
432 "close-popup" => Self::CloseChoice,
433 "select-all" => Self::SelectAll,
434 "select-word" => Self::SelectWord,
435 "clear-selection" => Self::ClearSelection,
436 "set-selection-offsets" => Self::SetSelection,
437 "undo" => Self::Undo,
438 "redo" => Self::Redo,
439 "cut" => Self::Cut,
440 "copy" => Self::Copy,
441 "paste" => Self::Paste,
442 "edit-cell" => Self::EditTableCell,
443 "cancel-edit" => Self::CancelTableEdit,
444 "insert-text" => Self::InsertText,
445 "replace-text" => Self::ReplaceText,
446 "remove-text" => Self::RemoveText,
447 "append-text" => Self::AppendText,
448 "clear-text" => Self::ClearText,
449 _ => return None,
450 })
451 }
452
453 pub fn action(self, operands: &[i64]) -> Option<FocusAction> {
454 let text = match (self, operands) {
455 (Self::Focus, []) => return Some(FocusAction::Focus),
456 (Self::Clear, []) => return Some(FocusAction::Clear),
457 (Self::OpenChoice, []) => return Some(FocusAction::OpenChoice),
458 (Self::CloseChoice, []) => return Some(FocusAction::CloseChoice),
459 (Self::SelectAll, []) => TextCommand::SelectAll,
460 (Self::SelectWord, []) => TextCommand::SelectWord,
461 (Self::ClearSelection, []) => TextCommand::ClearSelection,
462 (Self::SetSelection, &[anchor, focus]) => TextCommand::SetSelection { anchor, focus },
463 (Self::Undo, []) => TextCommand::Undo,
464 (Self::Redo, []) => TextCommand::Redo,
465 (Self::Cut, []) => TextCommand::Cut,
466 (Self::Copy, []) => TextCommand::Copy,
467 (Self::Paste, []) => TextCommand::Paste,
468 (Self::EditTableCell, &[row, column]) => {
469 return Some(FocusAction::EditTableCell { row, column });
470 }
471 (Self::CancelTableEdit, []) => return Some(FocusAction::CancelTableEdit),
472 _ => return None,
473 };
474 Some(FocusAction::Text(text))
475 }
476
477 pub fn uses_text_operand(self) -> bool {
478 matches!(
479 self,
480 Self::InsertText | Self::ReplaceText | Self::AppendText
481 )
482 }
483
484 pub fn edits_text(self) -> bool {
485 self.uses_text_operand() || matches!(self, Self::RemoveText | Self::ClearText)
486 }
487
488 pub fn replacement(self, offsets: &[i64], text: String) -> Option<TextReplacement> {
489 let (start, end) = match (self, offsets) {
490 (Self::InsertText, &[offset]) => (offset, offset),
491 (Self::ReplaceText | Self::RemoveText, &[start, end]) => (start, end),
492 (Self::AppendText, []) => (i64::MAX, i64::MAX),
493 (Self::ClearText, []) => (0, i64::MAX),
494 _ => return None,
495 };
496 Some(TextReplacement { start, end, text })
497 }
498}
499
500#[doc(hidden)]
501pub fn is_focus_handler(name: &str) -> bool {
502 FocusHandler::ALL
503 .iter()
504 .any(|handler| handler.name() == name)
505}
506
507#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
508pub enum FocusReason {
509 #[default]
510 Programmatic,
511 TabNavigation,
512 PointerClick,
513 PopupActivation,
514 WindowActivation,
515 Accessibility,
516 LayoutChange,
517 KeyboardNavigation,
518}
519
520#[derive(Clone, Copy, Debug, PartialEq, Eq)]
521pub enum FocusEvent {
522 Gained(FocusReason),
523 Lost(FocusReason),
524 Within { focused: bool, reason: FocusReason },
525}
526
527#[derive(Clone, Copy, Debug)]
528#[doc(hidden)]
529pub enum FocusHandler {
530 Gained,
531 Lost,
532 Changed,
533 Within,
534}
535
536impl FocusHandler {
537 pub const ALL: [Self; 4] = [Self::Gained, Self::Lost, Self::Changed, Self::Within];
538
539 pub fn name(self) -> &'static str {
540 match self {
541 Self::Gained => "focus-gained",
542 Self::Lost => "focus-lost",
543 Self::Changed => "focus-changed-event",
544 Self::Within => "focus-within-changed",
545 }
546 }
547}
548
549impl FocusEvent {
550 #[doc(hidden)]
551 pub fn is_loss(self) -> bool {
552 matches!(self, Self::Lost(_) | Self::Within { focused: false, .. })
553 }
554
555 #[doc(hidden)]
556 pub fn try_deliver<E>(
557 self,
558 mut notify: impl FnMut(FocusHandler, bool, FocusReason) -> Result<bool, E>,
559 ) -> Result<bool, E> {
560 let (handler, focused, reason) = match self {
561 Self::Gained(reason) => (FocusHandler::Gained, true, reason),
562 Self::Lost(reason) => (FocusHandler::Lost, false, reason),
563 Self::Within { focused, reason } => {
564 return notify(FocusHandler::Within, focused, reason);
565 }
566 };
567 let handled = notify(handler, focused, reason)?;
568 Ok(notify(FocusHandler::Changed, focused, reason)? || handled)
569 }
570
571 #[doc(hidden)]
572 pub fn deliver(self, mut notify: impl FnMut(FocusHandler, bool, FocusReason) -> bool) -> bool {
573 self.try_deliver(|handler, focused, reason| {
574 Ok::<_, std::convert::Infallible>(notify(handler, focused, reason))
575 })
576 .unwrap_or_else(|error| match error {})
577 }
578}
579
580pub struct FocusRequest {
581 pub target: FocusHandle,
582 pub action: FocusAction,
583}
584
585#[doc(hidden)]
586pub enum QueuedFocusRequest {
587 Focus(FocusRequest),
588 ReplaceText {
589 target: FocusHandle,
590 replacement: TextReplacement,
591 },
592}
593
594#[derive(Clone, Default)]
596pub struct FocusRequests(Rc<RefCell<Vec<QueuedFocusRequest>>>);
597
598thread_local! {
599 static ACTIVE: RefCell<Option<FocusRequests>> = const { RefCell::new(None) };
600}
601
602pub struct FocusContext(Option<FocusRequests>);
603
604impl FocusRequests {
605 pub fn enter(&self) -> FocusContext {
606 FocusContext(ACTIVE.with(|active| active.replace(Some(self.clone()))))
607 }
608
609 pub fn drain(&self) -> Vec<FocusRequest> {
610 self.drain_commands()
611 .into_iter()
612 .filter_map(|command| match command {
613 QueuedFocusRequest::Focus(request) => Some(request),
614 QueuedFocusRequest::ReplaceText { .. } => None,
615 })
616 .collect()
617 }
618
619 #[doc(hidden)]
620 pub fn drain_commands(&self) -> Vec<QueuedFocusRequest> {
621 std::mem::take(&mut *self.0.borrow_mut())
622 }
623
624 pub fn is_empty(&self) -> bool {
625 self.0.borrow().is_empty()
626 }
627}
628
629impl Drop for FocusContext {
630 fn drop(&mut self) {
631 ACTIVE.with(|active| active.replace(self.0.take()));
632 }
633}
634
635impl FocusHandle {
636 #[doc(hidden)]
637 pub fn with_text_selection() -> Self {
638 Self::with_text_state(true, false)
639 }
640
641 #[doc(hidden)]
642 pub fn with_text_state(selection: bool, commands: bool) -> Self {
643 Self(Rc::new(FocusSignals {
644 text: selection.then(Box::default),
645 commands: commands.then(Box::default),
646 ..FocusSignals::default()
647 }))
648 }
649
650 #[doc(hidden)]
651 pub fn record_editor_edit(&self, before: &str, after: &str) {
652 if before == after {
653 return;
654 }
655 let mut editing = self.0.editing.borrow_mut();
656 let initial = editing
657 .take()
658 .filter(|editing| editing.draft == before)
659 .map_or_else(|| before.to_owned(), |editing| editing.initial);
660 if initial != after {
661 *editing = Some(EditorChange {
662 initial,
663 draft: after.to_owned(),
664 });
665 }
666 }
667
668 #[doc(hidden)]
669 pub fn has_editor_changes(&self) -> bool {
670 self.0.editing.borrow().is_some()
671 }
672
673 #[doc(hidden)]
674 pub fn take_editor_changes(&self, current: &str) -> bool {
675 self.0
676 .editing
677 .borrow_mut()
678 .take()
679 .is_some_and(|editing| editing.draft == current)
680 }
681
682 #[doc(hidden)]
683 pub fn discard_editor_changes(&self) {
684 self.0.editing.borrow_mut().take();
685 }
686
687 #[doc(hidden)]
688 pub fn observes_text_commands(&self) -> bool {
689 self.0.commands.is_some()
690 }
691
692 #[doc(hidden)]
693 pub fn publish_text_commands(&self, commands: TextCommandAvailability) {
694 if let Some(signals) = &self.0.commands {
695 signals.undo.set_if_changed(commands.undo);
696 signals.redo.set_if_changed(commands.redo);
697 signals.cut.set_if_changed(commands.cut);
698 signals.copy.set_if_changed(commands.copy);
699 }
700 }
701
702 #[doc(hidden)]
703 pub fn clear_text_state(&self) {
704 self.publish_text_selection(0, 0..0, "");
705 self.publish_text_commands(TextCommandAvailability::default());
706 }
707
708 pub fn can_undo(&self) -> bool {
709 self.0
710 .commands
711 .as_ref()
712 .is_some_and(|signals| signals.undo.get(|| false))
713 }
714
715 pub fn can_redo(&self) -> bool {
716 self.0
717 .commands
718 .as_ref()
719 .is_some_and(|signals| signals.redo.get(|| false))
720 }
721
722 pub fn can_cut(&self) -> bool {
723 self.0
724 .commands
725 .as_ref()
726 .is_some_and(|signals| signals.cut.get(|| false))
727 }
728
729 pub fn can_copy(&self) -> bool {
730 self.0
731 .commands
732 .as_ref()
733 .is_some_and(|signals| signals.copy.get(|| false))
734 }
735
736 #[doc(hidden)]
737 pub fn observes_text_selection(&self) -> bool {
738 self.0.text.is_some()
739 }
740
741 #[doc(hidden)]
742 pub fn publish_text_selection(&self, caret: usize, selection: Range<usize>, text: &str) {
743 if let Some(signals) = &self.0.text {
744 for (offset, value) in
745 signals
746 .offsets
747 .iter()
748 .zip([caret, selection.start, selection.end])
749 {
750 offset.set_if_changed(value as i64);
751 }
752 if signals.selected.explicit_value().as_deref() != Some(text) {
753 signals.selected.set(Rc::from(text));
754 }
755 }
756 }
757
758 fn text_offset(&self, index: usize) -> i64 {
759 self.0
760 .text
761 .as_ref()
762 .map_or(0, |signals| signals.offsets[index].get(|| 0))
763 }
764
765 pub fn cursor_offset(&self) -> i64 {
766 self.text_offset(0)
767 }
768
769 pub fn selection_start_offset(&self) -> i64 {
770 self.text_offset(1)
771 }
772
773 pub fn selection_end_offset(&self) -> i64 {
774 self.text_offset(2)
775 }
776
777 pub fn selected_text(&self) -> String {
778 self.0.text.as_ref().map_or_else(String::new, |signals| {
779 signals.selected.get(|| Rc::from("")).to_string()
780 })
781 }
782
783 pub fn has_focus(&self) -> bool {
784 self.0.direct.get(|| false)
785 }
786
787 pub fn focus_within(&self) -> bool {
788 self.0.within.get(|| false)
789 }
790
791 #[doc(hidden)]
792 pub fn publish(&self, direct: bool, within: bool) {
793 self.0.direct.set_if_changed(direct);
794 self.0.within.set_if_changed(within);
795 }
796
797 pub fn request(&self, action: FocusAction) {
798 Self::enqueue(QueuedFocusRequest::Focus(FocusRequest {
799 target: self.clone(),
800 action,
801 }));
802 }
803
804 #[doc(hidden)]
805 pub fn request_text_edit(&self, replacement: TextReplacement) {
806 Self::enqueue(QueuedFocusRequest::ReplaceText {
807 target: self.clone(),
808 replacement,
809 });
810 }
811
812 fn enqueue(request: QueuedFocusRequest) {
813 ACTIVE.with(|active| {
814 if let Some(requests) = &*active.borrow() {
815 requests.0.borrow_mut().push(request);
816 }
817 });
818 }
819}
820
821#[cfg(test)]
822mod tests {
823 use super::*;
824
825 #[test]
826 fn selection_start_and_selected_text_track_independently() {
827 let handle = FocusHandle::with_text_selection();
828 let start = Property::default();
829 let selected = Property::default();
830 handle.publish_text_selection(3, 1..3, "bc");
831 assert_eq!(start.get(|| handle.selection_start_offset()), 1);
832 assert_eq!(selected.get(|| handle.selected_text()), "bc");
833
834 handle.publish_text_selection(4, 1..4, "bcd");
835 assert!(!start.is_dirty());
836 assert!(selected.is_dirty());
837 assert_eq!(selected.get(|| handle.selected_text()), "bcd");
838
839 handle.publish_text_selection(1, 1..4, "bcd");
840 assert!(!start.is_dirty());
841 assert!(!selected.is_dirty());
842 }
843
844 #[test]
845 fn direct_and_within_focus_have_independent_dependencies() {
846 let handle = FocusHandle::default();
847 let direct = Property::default();
848 let within = Property::default();
849 assert!(!direct.get(|| handle.has_focus()));
850 assert!(!within.get(|| handle.focus_within()));
851 handle.publish(false, true);
852 assert!(!direct.is_dirty());
853 assert!(within.is_dirty());
854 assert!(within.get(|| handle.focus_within()));
855 handle.publish(true, true);
856 assert!(direct.is_dirty());
857 assert!(!within.is_dirty());
858 }
859}