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)).
32#[derive(Clone, Copy, Debug, PartialEq, Eq)]
33pub struct NodeRef {
34 node: Signal<Option<NodeId>>,
35 /// Asked for while nothing was built: done once the node is.
36 waiting: Signal<Option<Request>>,
37}
38
39/// What code asked of the node.
40#[derive(Clone, Debug, PartialEq, Eq)]
41enum Request {
42 Focus,
43 Select(Range<usize>),
44}
45
46/// Creates a [`NodeRef`] owned by the current scope.
47pub fn node_ref() -> NodeRef {
48 NodeRef { node: signal(None), waiting: signal(None) }
49}
50
51impl NodeRef {
52 /// The node, and subscribes the running observer.
53 pub fn get(&self) -> Option<NodeId> {
54 self.node.get()
55 }
56
57 pub fn get_untracked(&self) -> Option<NodeId> {
58 if self.node.is_alive() { self.node.get_untracked() } else { None }
59 }
60
61 /// Gives the control keyboard focus, as a click or Tab would: the
62 /// first field of a dialog, say, where the platform wouldn't focus it
63 /// itself. Asked before the control is built (in a window's
64 /// `on_open`), it's focused once it is.
65 pub fn focus(&self) {
66 self.request(Request::Focus);
67 }
68
69 /// Focuses a text field or text area and selects these characters of
70 /// its text, counted as people see them: grapheme clusters, so an
71 /// accented letter or an emoji made of several code points is one
72 /// (`text.graphemes(true)`, from the re-exported `unicode_segmentation`).
73 /// A file's name without its extension, say, as file managers select
74 /// one to rename. Cut to the text's end; other controls are only
75 /// focused. Asked before the field is built, it's done once it is,
76 /// after its first text.
77 pub fn select_text(&self, range: Range<usize>) {
78 self.request(Request::Select(range));
79 }
80
81 fn request(&self, request: Request) {
82 match self.get_untracked() {
83 Some(id) => request.send(¤t_ui(), id),
84 None if self.waiting.is_alive() => self.waiting.set(Some(request)),
85 None => {}
86 }
87 }
88
89 /// Points the ref at `id` until the current scope ends, and does what
90 /// was asked while nothing was built.
91 pub(crate) fn attach(self, ui: &Ui, id: NodeId) {
92 self.node.set(Some(id));
93 if let Some(request) = self.waiting.get_untracked() {
94 self.waiting.set(None);
95 request.send(ui, id);
96 }
97 on_cleanup(move || {
98 if self.get_untracked() == Some(id) {
99 self.node.set(None);
100 }
101 });
102 }
103}
104
105impl Request {
106 fn send(self, ui: &Ui, id: NodeId) {
107 match self {
108 Request::Focus => ui.focus(id),
109 Request::Select(range) => ui.select_text(id, range),
110 }
111 }
112}
113
114/// The content size of the window the view is in, like a media query.
115/// Zero until its first layout.
116///
117/// # Panics
118/// Outside of a window's content.
119pub fn use_viewport() -> Computed<Size> {
120 let Some(CurrentWindow(window)) = inject::<CurrentWindow>() else {
121 panic!("mitsuami: use_viewport() outside of a window's content");
122 };
123 observe(move || Some(window))
124}
125
126/// The size of the node `node` refers to, like a container query. Zero
127/// while it refers to none, and until its first layout.
128pub fn use_size(node: NodeRef) -> Computed<Size> {
129 observe(move || node.get_untracked())
130}
131
132fn observe(target: impl Fn() -> Option<NodeId> + 'static) -> Computed<Size> {
133 let ui = current_ui();
134 let size = signal(ui.measured_size(target()));
135 let id = ui.observe_size(Box::new(target), size);
136 let weak = ui.downgrade();
137 on_cleanup(move || {
138 if let Some(ui) = weak.upgrade() {
139 ui.unobserve_size(id);
140 }
141 });
142 computed(move || size.get())
143}