fyrox_ui/
navigation.rs

1// Copyright (c) 2019-present Dmitry Stepanov and Fyrox Engine contributors.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a copy
4// of this software and associated documentation files (the "Software"), to deal
5// in the Software without restriction, including without limitation the rights
6// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7// copies of the Software, and to permit persons to whom the Software is
8// furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in all
11// copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19// SOFTWARE.
20
21//! A widget, that handles keyboard navigation on its descendant widgets using Tab key. See [`NavigationLayer`]
22//! docs for more info and usage examples.
23
24#![warn(missing_docs)]
25
26use crate::{
27    core::{
28        pool::Handle, reflect::prelude::*, type_traits::prelude::*, variable::InheritableVariable,
29        visitor::prelude::*,
30    },
31    message::{KeyCode, MessageDirection, UiMessage},
32    scroll_viewer::{ScrollViewer, ScrollViewerMessage},
33    widget::{Widget, WidgetBuilder, WidgetMessage},
34    BuildContext, Control, UiNode, UserInterface,
35};
36use fyrox_graph::SceneGraph;
37use std::ops::{Deref, DerefMut};
38
39/// A widget, that handles keyboard navigation on its descendant widgets using Tab key. It should
40/// be used as a root widget for an hierarchy, that should support Tab key navigation:
41///
42/// ```rust
43/// use fyrox_ui::{
44///     button::ButtonBuilder, navigation::NavigationLayerBuilder, stack_panel::StackPanelBuilder,
45///     text::TextBuilder, widget::WidgetBuilder, BuildContext,
46/// };
47///
48/// fn create_navigation_layer(ctx: &mut BuildContext) {
49///     NavigationLayerBuilder::new(
50///         WidgetBuilder::new().with_child(
51///             StackPanelBuilder::new(
52///                 WidgetBuilder::new()
53///                     .with_child(
54///                         // This widget won't participate in Tab key navigation.
55///                         TextBuilder::new(WidgetBuilder::new())
56///                             .with_text("Do something?")
57///                             .build(ctx),
58///                     )
59///                     // The keyboard focus for the following two buttons can be cycled using Tab/Shift+Tab.
60///                     .with_child(
61///                         ButtonBuilder::new(WidgetBuilder::new().with_tab_index(Some(0)))
62///                             .with_text("OK")
63///                             .build(ctx),
64///                     )
65///                     .with_child(
66///                         ButtonBuilder::new(WidgetBuilder::new().with_tab_index(Some(1)))
67///                             .with_text("Cancel")
68///                             .build(ctx),
69///                     ),
70///             )
71///             .build(ctx),
72///         ),
73///     )
74///     .build(ctx);
75/// }
76/// ```
77///
78/// This example shows how to create a simple confirmation dialog, that allows a user to use Tab key
79/// to cycle from one button to another. A focused button then can be "clicked" using Enter key.
80#[derive(Default, Clone, Visit, Reflect, Debug, TypeUuidProvider, ComponentProvider)]
81#[type_uuid(id = "135d347b-5019-4743-906c-6df5c295a3be")]
82pub struct NavigationLayer {
83    /// Base widget of the navigation layer.
84    pub widget: Widget,
85    /// A flag, that defines whether the navigation layer should search for a [`crate::scroll_viewer::ScrollViewer`]
86    /// parent widget and send [`crate::scroll_viewer::ScrollViewerMessage::BringIntoView`] message
87    /// to a newly focused widget.
88    pub bring_into_view: InheritableVariable<bool>,
89}
90
91crate::define_widget_deref!(NavigationLayer);
92
93#[derive(Debug)]
94struct OrderedHandle {
95    tab_index: usize,
96    handle: Handle<UiNode>,
97}
98
99impl Control for NavigationLayer {
100    fn handle_routed_message(&mut self, ui: &mut UserInterface, message: &mut UiMessage) {
101        self.widget.handle_routed_message(ui, message);
102
103        if let Some(WidgetMessage::KeyDown(KeyCode::Tab)) = message.data() {
104            // Collect all descendant widgets, that supports Tab navigation.
105            let mut tab_list = Vec::new();
106            for &child in self.children() {
107                for (descendant_handle, descendant_ref) in ui.traverse_iter(child) {
108                    if !*descendant_ref.tab_stop && descendant_ref.is_globally_visible() {
109                        if let Some(tab_index) = *descendant_ref.tab_index {
110                            tab_list.push(OrderedHandle {
111                                tab_index,
112                                handle: descendant_handle,
113                            });
114                        }
115                    }
116                }
117            }
118
119            if !tab_list.is_empty() {
120                tab_list.sort_by_key(|entry| entry.tab_index);
121
122                let focused_index = tab_list
123                    .iter()
124                    .position(|entry| entry.handle == ui.keyboard_focus_node)
125                    .unwrap_or_default();
126
127                let next_focused_node_index = if ui.keyboard_modifiers.shift {
128                    let count = tab_list.len() as isize;
129                    let mut prev = (focused_index as isize).saturating_sub(1);
130                    if prev < 0 {
131                        prev += count;
132                    }
133                    (prev % count) as usize
134                } else {
135                    focused_index.saturating_add(1) % tab_list.len()
136                };
137
138                if let Some(entry) = tab_list.get(next_focused_node_index) {
139                    ui.send_message(WidgetMessage::focus(
140                        entry.handle,
141                        MessageDirection::ToWidget,
142                    ));
143
144                    if *self.bring_into_view {
145                        // Find a parent scroll viewer.
146                        if let Some((scroll_viewer, _)) =
147                            ui.find_component_up::<ScrollViewer>(entry.handle)
148                        {
149                            ui.send_message(ScrollViewerMessage::bring_into_view(
150                                scroll_viewer,
151                                MessageDirection::ToWidget,
152                                entry.handle,
153                            ));
154                        }
155                    }
156                }
157            }
158        }
159    }
160}
161
162/// Navigation layer builder creates new [`NavigationLayer`] widget instances and adds them to the user interface.
163pub struct NavigationLayerBuilder {
164    widget_builder: WidgetBuilder,
165    bring_into_view: bool,
166}
167
168impl NavigationLayerBuilder {
169    /// Creates new builder instance.
170    pub fn new(widget_builder: WidgetBuilder) -> Self {
171        Self {
172            widget_builder,
173            bring_into_view: true,
174        }
175    }
176
177    /// Finishes navigation layer widget building and adds the instance to the user interface and
178    /// returns its handle.
179    pub fn build(self, ctx: &mut BuildContext) -> Handle<UiNode> {
180        let navigation_layer = NavigationLayer {
181            widget: self.widget_builder.build(ctx),
182            bring_into_view: self.bring_into_view.into(),
183        };
184        ctx.add_node(UiNode::new(navigation_layer))
185    }
186}
187
188#[cfg(test)]
189mod test {
190    use crate::navigation::NavigationLayerBuilder;
191    use crate::{test::test_widget_deletion, widget::WidgetBuilder};
192
193    #[test]
194    fn test_deletion() {
195        test_widget_deletion(|ctx| NavigationLayerBuilder::new(WidgetBuilder::new()).build(ctx));
196    }
197}