mitsuami_core/measure.rs
1//! Measurements: the sizes layout gave, as signals, for views that adapt to
2//! the room they have (media and container queries).
3//!
4//! ```ignore
5//! let viewport = use_viewport();
6//! let sidebar = node_ref();
7//! let width = use_size(sidebar);
8//! view! {
9//! <Row>
10//! <Column node_ref=sidebar grow=1.0>/* … */</Column>
11//! <Show when=move || viewport.get().width >= 600.0>/* … */</Show>
12//! </Row>
13//! }
14//! ```
15//!
16//! Sizes are reported after each layout, in the same run-loop turn, so a
17//! view that changes with them does so before anything is shown.
18
19use mitsuami_reactive::{Computed, Signal, computed, inject, on_cleanup, signal};
20
21use std::ops::Range;
22
23use crate::geometry::Size;
24use crate::task::current_ui;
25use crate::ui::Ui;
26use crate::widget::{CurrentWindow, NodeId};
27
28/// A handle to the node a view builds, set with `.node_ref(…)`. It follows
29/// the node: a view built again (by `Show`, `For`) sets it again, and it's
30/// `None` while nothing is built. It also focuses the node from code
31/// ([`focus`](NodeRef::focus), [`select_text`](NodeRef::select_text)), and
32/// brings a window forward ([`present`](NodeRef::present)).
33#[derive(Clone, Copy, Debug, PartialEq, Eq)]
34pub struct NodeRef {
35 node: Signal<Option<NodeId>>,
36 /// Asked for while nothing was built: done once the node is.
37 waiting: Signal<Option<Request>>,
38}
39
40/// What code asked of the node.
41#[derive(Clone, Debug, PartialEq, Eq)]
42enum Request {
43 Focus,
44 Select(Range<usize>),
45 Present,
46}
47
48/// Creates a [`NodeRef`] owned by the current scope.
49pub fn node_ref() -> NodeRef {
50 NodeRef { node: signal(None), waiting: signal(None) }
51}
52
53impl NodeRef {
54 /// The node, and subscribes the running observer.
55 pub fn get(&self) -> Option<NodeId> {
56 self.node.get()
57 }
58
59 pub fn get_untracked(&self) -> Option<NodeId> {
60 if self.node.is_alive() { self.node.get_untracked() } else { None }
61 }
62
63 /// Gives the control keyboard focus, as a click or Tab would: the
64 /// first field of a dialog, say, where the platform wouldn't focus it
65 /// itself. Asked before the control is built (in a window's
66 /// `on_open`), it's focused once it is.
67 pub fn focus(&self) {
68 self.request(Request::Focus);
69 }
70
71 /// Focuses a text field or text area and selects these characters of
72 /// its text, counted as people see them: grapheme clusters, so an
73 /// accented letter or an emoji made of several code points is one
74 /// (`text.graphemes(true)`, from the re-exported `unicode_segmentation`).
75 /// A file's name without its extension, say, as file managers select
76 /// one to rename. Cut to the text's end; other controls are only
77 /// focused. Asked before the field is built, it's done once it is,
78 /// after its first text.
79 pub fn select_text(&self, range: Range<usize>) {
80 self.request(Request::Select(range));
81 }
82
83 /// Brings the window forward (the one this node is in, or the window
84 /// itself, given `Window::node_ref`), as the platform's apps do when asked to
85 /// show a window that's open already: from a tray menu's Open item, or
86 /// a later launch. The app comes forward with it, a minimized window
87 /// is restored, and it takes the keys. Asked while the window is
88 /// closed, it's done once it opens: `open.set(true)` with this shows
89 /// it whether it was closed or behind other apps' windows.
90 ///
91 /// Platforms may refuse to take the focus from another app: on
92 /// Wayland the compositor only gives it for a user's action it can
93 /// tell (a launch's token), and asks for attention otherwise.
94 pub fn present(&self) {
95 self.request(Request::Present);
96 }
97
98 fn request(&self, request: Request) {
99 match self.get_untracked() {
100 Some(id) => request.send(¤t_ui(), id),
101 None if self.waiting.is_alive() => self.waiting.set(Some(request)),
102 None => {}
103 }
104 }
105
106 /// Points the ref at `id` until the current scope ends, and does what
107 /// was asked while nothing was built. What `.node_ref(…)` does, for
108 /// widgets that build their nodes themselves (`Window`).
109 #[doc(hidden)]
110 pub fn attach(self, ui: &Ui, id: NodeId) {
111 self.node.set(Some(id));
112 if let Some(request) = self.waiting.get_untracked() {
113 self.waiting.set(None);
114 request.send(ui, id);
115 }
116 on_cleanup(move || {
117 if self.get_untracked() == Some(id) {
118 self.node.set(None);
119 }
120 });
121 }
122}
123
124impl Request {
125 fn send(self, ui: &Ui, id: NodeId) {
126 match self {
127 Request::Focus => ui.focus(id),
128 Request::Select(range) => ui.select_text(id, range),
129 Request::Present => ui.present(id),
130 }
131 }
132}
133
134/// The content size of the window the view is in, like a media query.
135/// Zero until its first layout.
136///
137/// # Panics
138/// Outside of a window's content.
139pub fn use_viewport() -> Computed<Size> {
140 let Some(CurrentWindow(window)) = inject::<CurrentWindow>() else {
141 panic!("mitsuami: use_viewport() outside of a window's content");
142 };
143 observe(move || Some(window))
144}
145
146/// The size of the node `node` refers to, like a container query. Zero
147/// while it refers to none, and until its first layout.
148pub fn use_size(node: NodeRef) -> Computed<Size> {
149 observe(move || node.get_untracked())
150}
151
152fn observe(target: impl Fn() -> Option<NodeId> + 'static) -> Computed<Size> {
153 let ui = current_ui();
154 let size = signal(ui.measured_size(target()));
155 let id = ui.observe_size(Box::new(target), size);
156 let weak = ui.downgrade();
157 on_cleanup(move || {
158 if let Some(ui) = weak.upgrade() {
159 ui.unobserve_size(id);
160 }
161 });
162 computed(move || size.get())
163}