Skip to main content

mitsuami_core/ui/
build.rs

1//! Creating nodes and setting their props, styles and handlers.
2
3use std::rc::Rc;
4
5use crate::a11y::A11yProps;
6use crate::command::{Command, UiEvent};
7use crate::geometry::{Insets, Point, Rect, Size, WindowSize};
8use crate::style::Style;
9use crate::widget::{NodeId, Prop, WidgetKind};
10
11use super::{Fit, Node, Ui};
12
13impl Ui {
14    pub fn create(&self, kind: WidgetKind, props: Vec<Prop>) -> NodeId {
15        let id = {
16            let mut inner = self.inner.borrow_mut();
17            let id = NodeId(inner.next_id);
18            inner.next_id += 1;
19            let taffy = if kind.is_native() {
20                let t = if kind.is_container() {
21                    inner.taffy.new_leaf(taffy::Style::default())
22                } else {
23                    inner.taffy.new_leaf_with_context(taffy::Style::default(), id)
24                };
25                Some(t.expect("taffy: failed to create node"))
26            } else {
27                None
28            };
29            if kind.is_native() {
30                inner.pending.push(Command::Create { id, kind, props: props.clone() });
31                inner.created.insert(id);
32            }
33            inner.nodes.insert(
34                id,
35                Node {
36                    kind,
37                    parent: None,
38                    children: Vec::new(),
39                    native_children: Vec::new(),
40                    native_parent: None,
41                    props,
42                    style: Style::default(),
43                    a11y: A11yProps::default(),
44                    test_id: None,
45                    tab_index: None,
46                    handlers: Vec::new(),
47                    taffy,
48                    frame: Rect::ZERO,
49                    window_size: Size::ZERO,
50                    fit: Fit::None,
51                    heights: Vec::new(),
52                    scroll_offset: Point::ZERO,
53                    row_width: None,
54                    viewport_insets: Insets::ZERO,
55                    column_widths: None,
56                    strip: Size::ZERO,
57                    insets: None,
58                    drawn_at: None,
59                },
60            );
61            inner.styles_dirty = true;
62            id
63        };
64        self.changed();
65        id
66    }
67
68    /// A window fitting its height is sized at its first layout, so give it
69    /// its content before the next commit.
70    pub fn create_window(&self, title: impl Into<String>, size: impl Into<WindowSize>) -> NodeId {
71        let size = size.into();
72        let mut props = vec![Prop::Title(title.into())];
73        if let WindowSize::FollowHeight(_) = size {
74            props.push(Prop::HeightFollowsContent(true));
75        }
76        let id = self.create(WidgetKind::Window, props);
77        let mut inner = self.inner.borrow_mut();
78        let node = inner.nodes.get_mut(&id).expect("just created");
79        let (size, fit) = match size {
80            WindowSize::Fixed(size) => (size, Fit::None),
81            WindowSize::FitHeight(width) => (Size::new(width, 0.0), Fit::Once),
82            WindowSize::FollowHeight(width) => (Size::new(width, 0.0), Fit::Follow { until_resized: false }),
83            WindowSize::FollowHeightUntilResized(width) => (Size::new(width, 0.0), Fit::Follow { until_resized: true }),
84        };
85        node.window_size = size;
86        node.fit = fit;
87        node.frame = Rect { origin: Point::ZERO, size };
88        inner.windows.push(id);
89        // A fitted size is sent with the first frames.
90        if fit == Fit::None {
91            inner.pending.push(Command::SetWindowSize { id, size });
92        }
93        id
94    }
95
96    /// Asks for a window's content size, in points, as the app would resize
97    /// it. The platform may refuse it (a window in full screen keeps the
98    /// screen's), and gives it no smaller than the window's `MinSize`; the
99    /// content is laid out at the size it reports (`WindowResized`). A
100    /// `WindowSize::FollowHeight` window takes only the width: its content
101    /// sets its height. Other windows stop fitting their height.
102    pub fn set_window_size(&self, window: NodeId, size: Size) {
103        {
104            let mut inner = self.inner.borrow_mut();
105            let Some(node) = inner.nodes.get_mut(&window).filter(|n| n.kind == WidgetKind::Window) else { return };
106            let size = match node.fit {
107                Fit::Follow { until_resized: false } => {
108                    Size::new(size.width, node.heights.last().copied().unwrap_or(node.window_size.height))
109                }
110                _ => {
111                    node.fit = Fit::None;
112                    node.heights.clear();
113                    size
114                }
115            };
116            inner.pending.push(Command::SetWindowSize { id: window, size });
117        }
118        self.changed();
119    }
120
121    /// Sets a prop, sending it to the backend only if it changed.
122    pub fn set_prop(&self, id: NodeId, prop: Prop) {
123        {
124            let mut inner = self.inner.borrow_mut();
125            let inner = &mut *inner;
126            let Some(node) = inner.nodes.get_mut(&id) else { return };
127            if node.prop(&prop) == Some(&prop) {
128                return;
129            }
130            node.props.retain(|p| p.key() != prop.key());
131            node.props.push(prop.clone());
132            if matches!(prop, Prop::Custom(_)) {
133                node.drawn_at = None;
134            }
135            if prop.affects_measure(node.kind)
136                && let Some(t) = node.taffy
137            {
138                let _ = inner.taffy.mark_dirty(t);
139            }
140            // A line limit changes a text's minimum width (`resolve_node`).
141            if matches!(prop, Prop::TextStyle(_) | Prop::MaxLines(_)) {
142                inner.styles_dirty = true;
143            }
144            // New titles, icons or another style may make the tab strip wider
145            // (`size_tab_strips`), and a group's heading wider, or give it
146            // the titled insets.
147            if (matches!(prop, Prop::TabTitles(_) | Prop::TabIcons(_) | Prop::TabsStyle(_))
148                || (node.kind == WidgetKind::Group && matches!(prop, Prop::Title(_))))
149                && let Some(t) = node.taffy
150            {
151                let _ = inner.taffy.mark_dirty(t);
152                inner.styles_dirty |= node.kind == WidgetKind::Group;
153            }
154            // A tab view's page shown, and a surface taking input, are in
155            // the Tab order.
156            if matches!(prop, Prop::SelectedIndex(_) | Prop::TakesInput(_)) {
157                inner.focus_dirty = true;
158            }
159            if node.kind.is_native() {
160                inner.queue_prop(id, prop);
161            }
162        }
163        self.changed();
164    }
165
166    pub fn set_style(&self, id: NodeId, style: Style) {
167        {
168            let mut inner = self.inner.borrow_mut();
169            let Some(node) = inner.nodes.get_mut(&id) else { return };
170            if node.style == style {
171                return;
172            }
173            node.style = style;
174            inner.styles_dirty = true;
175        }
176        self.changed();
177    }
178
179    /// Edits a node's style in place (used by reactive style bindings).
180    pub fn update_style(&self, id: NodeId, f: impl FnOnce(&mut Style)) {
181        let style = {
182            let inner = self.inner.borrow();
183            let Some(node) = inner.nodes.get(&id) else { return };
184            let mut style = node.style.clone();
185            f(&mut style);
186            style
187        };
188        self.set_style(id, style);
189    }
190
191    pub fn set_a11y(&self, id: NodeId, a11y: A11yProps) {
192        {
193            let mut inner = self.inner.borrow_mut();
194            let Some(node) = inner.nodes.get_mut(&id) else { return };
195            if node.a11y == a11y {
196                return;
197            }
198            node.a11y = a11y.clone();
199            if node.kind.is_native() {
200                inner.pending.push(Command::SetA11y { id, a11y });
201            }
202        }
203        self.changed();
204    }
205
206    /// Changes part of a node's semantics.
207    pub fn update_a11y(&self, id: NodeId, f: impl FnOnce(&mut A11yProps)) {
208        let Some(mut a11y) = self.inner.borrow().nodes.get(&id).map(|n| n.a11y.clone()) else { return };
209        f(&mut a11y);
210        self.set_a11y(id, a11y);
211    }
212
213    pub fn set_test_id(&self, id: NodeId, test_id: impl Into<String>) {
214        if let Some(node) = self.inner.borrow_mut().nodes.get_mut(&id) {
215            node.test_id = Some(test_id.into());
216        }
217    }
218
219    /// The current owner, or, with none, a scope of its own that goes when
220    /// node `id` is destroyed, so what a view built straight on a `Ui` (a
221    /// `For`, a `List`) hangs off it is freed with its node.
222    pub(crate) fn owner_or_node_scope(&self, id: NodeId) -> mitsuami_reactive::Owner {
223        use mitsuami_reactive::Owner;
224        if let Some(owner) = Owner::current() {
225            return owner;
226        }
227        struct DisposeOnDrop(Owner);
228        impl Drop for DisposeOnDrop {
229            fn drop(&mut self) {
230                self.0.dispose();
231            }
232        }
233        let scope = Owner::new_root();
234        let guard = DisposeOnDrop(scope);
235        // Kept by a handler that does nothing: the node drops its handlers
236        // when it's destroyed (after the tree's borrow, `destroy`).
237        if let Some(node) = self.inner.borrow_mut().nodes.get_mut(&id) {
238            node.handlers.push(Rc::new(move |_: &UiEvent| {
239                let _ = &guard;
240            }));
241        }
242        scope
243    }
244
245    /// Adds an event handler. It runs in the reactive scope that is current
246    /// now (usually the component being built), so `inject`, `spawn_local`
247    /// and friends work inside it.
248    pub fn on_event(&self, id: NodeId, handler: impl Fn(&UiEvent) + 'static) {
249        let owner = mitsuami_reactive::Owner::current();
250        let handler = move |event: &UiEvent| match owner {
251            Some(owner) if owner.is_alive() => owner.with(|| handler(event)),
252            _ => handler(event),
253        };
254        if let Some(node) = self.inner.borrow_mut().nodes.get_mut(&id) {
255            node.handlers.push(Rc::new(handler));
256        }
257    }
258}