frus_widgets/scaffoldinfo.rs
1//! [`ScaffoldInfo`]: **what the shell knows and its slots do not.**
2//!
3//! An [`AppBar`](crate::AppBar) is handed to a [`Scaffold`](crate::Scaffold) already
4//! built, so it cannot see the shell it is about to stand in. The reference's does, through
5//! the context: `Scaffold.of(context)` tells a bar whether the screen has a drawer, which
6//! is how a bar with no `leading` grows a menu button on a screen that has a menu and
7//! stays empty on one that does not (`app_bar.dart:1010`).
8//!
9//! This is that context, in the shape frus already uses twice: an ambient value the walk
10//! installs on the way down, like [`MediaQuery`](crate::MediaQuery) and the theme, and a
11//! [`Widget`] hook — [`Widget::scaffold_override`] — for the node that imposes one.
12//!
13//! It carries **messages**, which is the part that needed care: the shell knows what opens
14//! its drawer and the bar does not, and the two are generic over different type parameters
15//! as far as the ambient is concerned. The message is held as `Rc<dyn Any>` and handed back
16//! only to a caller that names the type it was put in with. A bar whose `Msg` is not the
17//! shell's asks and is told nothing, which is the honest answer: it could not have sent
18//! that message anyway.
19//!
20//! ```ignore
21//! ScaffoldScope::new(ScaffoldInfo::default().with_drawer(Msg::ToggleMenu), shell)
22//! ```
23
24use std::any::Any;
25use std::cell::RefCell;
26use std::hash::{Hash, Hasher};
27use std::rc::Rc;
28
29use crate::widget::Widget;
30
31/// What the [`Scaffold`](crate::Scaffold) around a widget knows about itself.
32///
33/// Empty outside a shell — which is not the same as "a shell with nothing in it", but the
34/// two want the same answers here, and a bar outside a shell has no drawer to open either
35/// way.
36#[derive(Clone, Default)]
37pub struct ScaffoldInfo {
38 /// The message that opens or closes the leading drawer, if the shell has one.
39 drawer: Option<Rc<dyn Any>>,
40 /// The same for the trailing drawer.
41 end_drawer: Option<Rc<dyn Any>>,
42}
43
44impl ScaffoldInfo {
45 /// The one in force here — empty outside every [`ScaffoldInfo::scope`].
46 #[must_use]
47 pub fn of() -> Self {
48 AMBIENT.with(|a| a.borrow().clone())
49 }
50
51 /// Records a leading drawer and the message that toggles it.
52 #[must_use]
53 pub fn with_drawer<Msg: Clone + 'static>(mut self, toggle: Msg) -> Self {
54 self.drawer = Some(Rc::new(toggle));
55 self
56 }
57
58 /// Records a trailing drawer and the message that toggles it.
59 #[must_use]
60 pub fn with_end_drawer<Msg: Clone + 'static>(mut self, toggle: Msg) -> Self {
61 self.end_drawer = Some(Rc::new(toggle));
62 self
63 }
64
65 /// Whether the shell has a drawer on the leading edge.
66 #[must_use]
67 pub fn has_drawer(&self) -> bool {
68 self.drawer.is_some()
69 }
70
71 /// Whether the shell has a drawer on the trailing edge.
72 #[must_use]
73 pub fn has_end_drawer(&self) -> bool {
74 self.end_drawer.is_some()
75 }
76
77 /// The message that toggles the leading drawer, for a widget whose message type it
78 /// **is**. `None` for anyone else: a widget cannot send a message of another tree's
79 /// type, so being told about it would only invite a cast.
80 #[must_use]
81 pub fn drawer_toggle<Msg: Clone + 'static>(&self) -> Option<Msg> {
82 self.drawer.as_ref()?.downcast_ref::<Msg>().cloned()
83 }
84
85 /// The same for the trailing drawer.
86 #[must_use]
87 pub fn end_drawer_toggle<Msg: Clone + 'static>(&self) -> Option<Msg> {
88 self.end_drawer.as_ref()?.downcast_ref::<Msg>().cloned()
89 }
90
91 /// Puts this in force until the guard is dropped.
92 #[must_use]
93 pub fn install(self) -> ScaffoldGuard {
94 ScaffoldGuard(AMBIENT.with(|a| a.replace(self)))
95 }
96
97 /// Runs `body` with this in force, and puts back what was there.
98 pub fn scope<R>(self, body: impl FnOnce() -> R) -> R {
99 let _guard = self.install();
100 body()
101 }
102
103 /// The part of this that changes what a slot **composes**, for the relayout
104 /// fingerprint.
105 ///
106 /// Whether there is a drawer decides whether a bar grows a button, which is a
107 /// different row and a different geometry. *Which* message opens it does not: two
108 /// shells with different messages and the same drawers lay out identically, and
109 /// hashing the message would mean hashing a pointer that moves every frame.
110 pub(crate) fn shape_hash<H: Hasher>(&self, hasher: &mut H) {
111 self.has_drawer().hash(hasher);
112 self.has_end_drawer().hash(hasher);
113 }
114}
115
116/// Puts back the previous ambient shell when dropped — including while a panic unwinds.
117pub struct ScaffoldGuard(ScaffoldInfo);
118
119impl Drop for ScaffoldGuard {
120 fn drop(&mut self) {
121 AMBIENT.with(|a| a.replace(std::mem::take(&mut self.0)));
122 }
123}
124
125thread_local! {
126 /// The shell in force on this thread. A `RefCell` rather than a `Cell` because the
127 /// value is not `Copy`: it holds the messages, and a message is whatever the
128 /// application says it is.
129 static AMBIENT: RefCell<ScaffoldInfo> = const { RefCell::new(ScaffoldInfo {
130 drawer: None,
131 end_drawer: None,
132 }) };
133}
134
135/// A **shell for one subtree**: the counterpart of [`MediaScope`](crate::MediaScope), one
136/// milestone later and for the other thing a shell knows.
137///
138/// A **transparent wrapper**: it lays out, paints and answers exactly
139/// as its child does. The only thing it adds is what the subtree below it reads from
140/// [`ScaffoldInfo::of`] — including a subtree deferred until
141/// [`Widget::build_themed`](crate::Widget::build_themed), which is where an
142/// [`AppBar`](crate::AppBar) is composed and therefore the whole point.
143pub struct ScaffoldScope<Msg = crate::callback::Callback> {
144 info: ScaffoldInfo,
145 inner: Box<dyn Widget<Msg>>,
146}
147
148impl<Msg> ScaffoldScope<Msg> {
149 /// Tells `child`'s subtree what shell it is in.
150 pub fn new(info: ScaffoldInfo, child: impl Widget<Msg> + 'static) -> Self {
151 Self {
152 info,
153 inner: Box::new(child),
154 }
155 }
156
157 /// Transparent: it does not change the box its child is.
158 fn restyle(&self, base: frus_layout::Style) -> frus_layout::Style {
159 base
160 }
161}
162
163crate::transparent::forward_transparent!(ScaffoldScope {
164 fn key(&self) -> Option<u64> {
165 self.inner.key()
166 }
167 fn positioned(&self) -> Option<crate::positioned::Positioning> {
168 self.inner.positioned()
169 }
170 fn theme_override(&self, inherited: &crate::theme::Theme) -> Option<Box<crate::theme::Theme>> {
171 self.inner.theme_override(inherited)
172 }
173 fn media_override(&self, inherited: crate::MediaQuery) -> Option<crate::MediaQuery> {
174 self.inner.media_override(inherited)
175 }
176 /// The shell this scope names — unless the child is itself a scope, in which case the
177 /// **inner** one wins, exactly as a nested `Scaffold` wins in the reference.
178 fn scaffold_override(&self) -> Option<ScaffoldInfo> {
179 Some(
180 self.inner
181 .scaffold_override()
182 .unwrap_or_else(|| self.info.clone()),
183 )
184 }
185 /// Forwarded: a scope around a form is still that form (milestone 512).
186 fn autofill_group(&self) -> bool {
187 self.inner.autofill_group()
188 }
189});
190
191#[cfg(test)]
192mod tests {
193 use super::*;
194 use crate::{build_ui, Container, Runtime, Size, Theme};
195
196 #[derive(Clone, Debug, PartialEq)]
197 enum Msg {
198 Menu,
199 }
200
201 /// Another tree's message type, which the shell's message is not.
202 #[derive(Clone, Debug, PartialEq)]
203 enum Other {
204 #[allow(dead_code)]
205 Menu,
206 }
207
208 /// Outside a shell there is no shell, and the answer says so rather than inventing one.
209 #[test]
210 fn there_is_no_shell_until_one_says_so() {
211 let bare = ScaffoldInfo::of();
212 assert!(!bare.has_drawer() && !bare.has_end_drawer());
213 assert_eq!(bare.drawer_toggle::<Msg>(), None);
214 }
215
216 /// The message comes back to the tree it was put in for, and to nobody else.
217 #[test]
218 fn a_message_is_handed_back_only_to_the_type_it_was_put_in_with() {
219 ScaffoldInfo::default().with_drawer(Msg::Menu).scope(|| {
220 let info = ScaffoldInfo::of();
221 assert!(info.has_drawer());
222 assert_eq!(info.drawer_toggle::<Msg>(), Some(Msg::Menu));
223 // A tree of another message type is told nothing, because it could not
224 // have sent this message anyway.
225 assert_eq!(info.drawer_toggle::<Other>(), None);
226 });
227 // And the scope is closed behind it.
228 assert!(!ScaffoldInfo::of().has_drawer());
229 }
230
231 /// The scope reaches the subtree through the walk, not only the call that installs it —
232 /// which is what an already-built app bar needs.
233 #[test]
234 fn a_scope_reaches_the_subtree_the_walk_visits() {
235 let seen = std::rc::Rc::new(std::cell::Cell::new(false));
236 let probe = {
237 let seen = seen.clone();
238 crate::ThemeBuilder::<Msg>::boxed(move |_| {
239 seen.set(ScaffoldInfo::of().has_drawer());
240 Box::new(Container::new().color(frus_core::Color::WHITE))
241 })
242 };
243 let tree = ScaffoldScope::new(ScaffoldInfo::default().with_drawer(Msg::Menu), probe);
244 build_ui(
245 &tree,
246 Size::new(100.0, 100.0),
247 &Runtime::default(),
248 &Theme::default(),
249 );
250 assert!(seen.get(), "the deferred build did not see the shell");
251 }
252
253 /// Two shells that differ in what they hold must not share a layout: a drawer is a
254 /// button in the bar, and a button is a different row. The cache keys on a fingerprint
255 /// of the walk, so the shell has to be in it — the same trap `theme_override` and
256 /// `media_override` each document beside themselves.
257 #[test]
258 fn the_shell_is_part_of_the_relayout_fingerprint() {
259 // One runtime across both builds, so the second really does consult the first's
260 // cache rather than starting from nothing.
261 let runtime = Runtime::default();
262 let height = |drawer: bool| {
263 let probe = crate::ThemeBuilder::<Msg>::boxed(move |_| {
264 // A shell with a drawer composes a taller box, the way a bar with a menu
265 // button composes a different row.
266 let tall = if ScaffoldInfo::of().has_drawer() {
267 40.0
268 } else {
269 10.0
270 };
271 Box::new(
272 Container::new()
273 .width(10.0)
274 .height(tall)
275 .color(frus_core::Color::rgb8(255, 0, 128)),
276 )
277 });
278 let info = if drawer {
279 ScaffoldInfo::default().with_drawer(Msg::Menu)
280 } else {
281 ScaffoldInfo::default()
282 };
283 let tree = ScaffoldScope::new(info, probe);
284 build_ui(&tree, Size::new(100.0, 100.0), &runtime, &Theme::default())
285 .scene()
286 .primitives()
287 .iter()
288 .find_map(|p| match p {
289 frus_core::Primitive::Rect { rect, .. } => Some(rect.height),
290 _ => None,
291 })
292 };
293 let with = height(true);
294 let without = height(false);
295 assert_ne!(
296 with, without,
297 "a shell with a drawer was served from the cache of one without"
298 );
299 assert_eq!(height(true), with, "and back again");
300 }
301}