Skip to main content

xrack_layout/
focus_observers.rs

1use crate::{Interaction, LayoutNode, Target};
2use xrack_runtime::{
3    Component, FocusEvent, FocusHandle, FocusReason, Node, combo_editable, is_text_input,
4};
5
6pub(crate) struct FocusEntry {
7    pub target: Target,
8    pub handle: FocusHandle,
9    pub direct: bool,
10}
11
12pub struct FocusDelivery {
13    target: Target,
14    handle: FocusHandle,
15    pub event: FocusEvent,
16}
17
18impl FocusDelivery {
19    pub fn apply(self, component: &mut impl Component, scene: &Node) -> bool {
20        let path = &self.target.path;
21        let same_target = |path| {
22            scene.row_key_at(path) == self.target.row_key
23                && scene
24                    .at_path(path)
25                    .is_some_and(|node| node.focus_handle.as_ref() == Some(&self.handle))
26        };
27        if same_target(path) {
28            let delivered = component.focus_event_at(scene, path, self.event);
29            if matches!(self.event, FocusEvent::Lost(_)) && !delivered {
30                self.handle.discard_editor_changes();
31            }
32            return delivered;
33        }
34        if matches!(self.event, FocusEvent::Lost(_)) && self.handle.has_editor_changes() {
35            if let Some(moved) = editor_path(scene, &self.handle, &mut Vec::new())
36                && same_target(&moved)
37                && component.focus_event_at(scene, &moved, self.event)
38            {
39                return true;
40            }
41            self.handle.discard_editor_changes();
42        }
43        false
44    }
45}
46
47// If a model moved the old editor, match its owning instance before delivering loss.
48fn editor_path(node: &Node, handle: &FocusHandle, path: &mut Vec<usize>) -> Option<Vec<usize>> {
49    if node.focus_handle.as_ref() == Some(handle) {
50        return Some(path.clone());
51    }
52    node.materialized_children().find_map(|(index, child)| {
53        path.push(index);
54        let result = editor_path(child, handle, path);
55        path.pop();
56        result
57    })
58}
59
60/// Publish focus to reactive handles before delivering the corresponding events.
61#[derive(Default)]
62pub struct FocusObservers {
63    active: bool,
64    entries: Vec<FocusEntry>,
65}
66
67impl FocusObservers {
68    pub fn sync(
69        &mut self,
70        input: &Interaction,
71        scene: &Node,
72        layout: &LayoutNode,
73        active: bool,
74    ) -> Vec<FocusDelivery> {
75        let reason = if self.active != active {
76            FocusReason::WindowActivation
77        } else {
78            input.focus_reason()
79        };
80        self.active = active;
81        let next = if active {
82            input.focus_entries(scene, layout)
83        } else {
84            Vec::new()
85        };
86        let previous = std::mem::replace(&mut self.entries, next);
87        let mut events = Vec::new();
88        let mut send = |entry: &FocusEntry, event| {
89            events.push(FocusDelivery {
90                target: entry.target.clone(),
91                handle: entry.handle.clone(),
92                event,
93            })
94        };
95        for old in previous.iter().rev() {
96            let replacement = self.entries.iter().find(|entry| entry.handle == old.handle);
97            if old.direct && !replacement.is_some_and(|entry| entry.direct) {
98                if let Some((editor, node)) =
99                    input.retained_editor_for(scene, &old.target, &old.handle)
100                {
101                    let text = xrack_runtime::text_input_value(node);
102                    let range = editor.selection(text);
103                    let selected = if node.is_password() {
104                        ""
105                    } else {
106                        &text[range.clone()]
107                    };
108                    old.handle
109                        .publish_text_selection(editor.caret(text), range, selected);
110                    old.handle.publish_text_commands(Default::default());
111                } else {
112                    old.handle.clear_text_state();
113                }
114                send(replacement.unwrap_or(old), FocusEvent::Lost(reason));
115            }
116            if replacement.is_none() {
117                old.handle.publish(false, false);
118                send(
119                    old,
120                    FocusEvent::Within {
121                        focused: false,
122                        reason,
123                    },
124                );
125            }
126        }
127        for entry in &self.entries {
128            let old = previous.iter().find(|old| old.handle == entry.handle);
129            entry.handle.publish(entry.direct, true);
130            if old.is_none() {
131                send(
132                    entry,
133                    FocusEvent::Within {
134                        focused: true,
135                        reason,
136                    },
137                );
138            }
139            if entry.direct && !old.is_some_and(|old| old.direct) {
140                send(entry, FocusEvent::Gained(reason));
141            }
142        }
143        self.sync_text_editor(input, scene);
144        events
145    }
146
147    #[doc(hidden)]
148    pub fn sync_text_editor(&self, input: &Interaction, scene: &Node) {
149        let Some(entry) = self.entries.iter().find(|entry| {
150            entry.direct
151                && (entry.handle.observes_text_selection()
152                    || entry.handle.observes_text_commands()
153                    || entry.handle.has_editor_changes())
154        }) else {
155            return;
156        };
157        let Some(node) = entry.target.node_in(scene) else {
158            entry.handle.clear_text_state();
159            return;
160        };
161        if !is_text_input(node.kind) && !combo_editable(node) && !node.selectable_styled_text() {
162            entry.handle.discard_editor_changes();
163            entry.handle.clear_text_state();
164            return;
165        }
166        if !entry.handle.observes_text_commands() && !entry.handle.observes_text_selection() {
167            return;
168        }
169        let text = input.editor_value(node);
170        let (caret, range) = input.editor.as_ref().map_or_else(
171            || (text.len(), text.len()..text.len()),
172            |editor| (editor.caret(&text), editor.selection(&text)),
173        );
174        if entry.handle.observes_text_commands() {
175            entry
176                .handle
177                .publish_text_commands(input.text_command_availability(
178                    scene,
179                    &entry.target,
180                    node,
181                    &text,
182                    !range.is_empty(),
183                ));
184        }
185        if entry.handle.observes_text_selection() {
186            let selected = if node.is_password() {
187                ""
188            } else {
189                &text[range.clone()]
190            };
191            entry.handle.publish_text_selection(caret, range, selected);
192        }
193    }
194
195    pub fn clear(&mut self) {
196        for entry in self.entries.drain(..) {
197            entry.handle.publish(false, false);
198            entry.handle.clear_text_state();
199            entry.handle.discard_editor_changes();
200        }
201        self.active = false;
202    }
203}
204
205#[cfg(test)]
206mod tests {
207    use super::*;
208    use xrack_runtime::VecModel;
209
210    #[derive(Default)]
211    struct Recorder(Vec<Vec<usize>>);
212
213    impl Component for Recorder {
214        fn render(&self) -> Node {
215            Node::new("Window", None)
216        }
217
218        fn dispatch(&mut self, _: &str, _: &str) -> bool {
219            false
220        }
221
222        fn focus_event_at(&mut self, scene: &Node, path: &[usize], event: FocusEvent) -> bool {
223            let Some(editor) = scene.focus_event_target(path, event) else {
224                return false;
225            };
226            if !editor
227                .focus_handle
228                .as_ref()
229                .is_some_and(|handle| handle.take_editor_changes("edited"))
230            {
231                return false;
232            }
233            self.0.push(path.to_vec());
234            true
235        }
236    }
237
238    #[test]
239    fn editing_loss_follows_the_moved_editor_and_discards_a_removed_editor() {
240        let model = VecModel::from(vec![0_i64, 1]);
241        let mut scene = Node::new("Window", None);
242        let handle = FocusHandle::default();
243        for index in 0..2 {
244            let mut row = Node::new("ListRow", None);
245            row.set_row_key(model.row_key(index));
246            let mut editor = Node::new("LineEdit", Some("editor"));
247            editor.focus_handle = Some(if index == 0 {
248                handle.clone()
249            } else {
250                FocusHandle::default()
251            });
252            row.children.push(editor);
253            scene.children.push(row);
254        }
255        let delivery = |scene: &Node, path: Vec<usize>| {
256            let target = Target::from_node(
257                path.clone(),
258                scene.at_path(&path).unwrap(),
259                true,
260                scene.row_key_at(&path),
261            );
262            FocusDelivery {
263                target,
264                handle: handle.clone(),
265                event: FocusEvent::Lost(FocusReason::TabNavigation),
266            }
267        };
268        handle.record_editor_edit("", "edited");
269        let moved = delivery(&scene, vec![0, 0]);
270        scene.children.swap(0, 1);
271        let mut ui = Recorder::default();
272        assert!(moved.apply(&mut ui, &scene));
273        assert_eq!(ui.0, [vec![1, 0]]);
274
275        handle.record_editor_edit("", "edited");
276        let removed = delivery(&scene, vec![1, 0]);
277        scene.children.pop();
278        assert!(!removed.apply(&mut ui, &scene));
279        assert!(!handle.has_editor_changes());
280        assert_eq!(ui.0.len(), 1);
281    }
282}