Skip to main content

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    fn scroll_behavior_override(&self) -> Option<crate::ScrollBehavior> {
186        self.inner.scroll_behavior_override()
187    }
188    /// Forwarded: a scope around a form is still that form (milestone 512).
189    fn autofill_group(&self) -> bool {
190        self.inner.autofill_group()
191    }
192    /// Forwarded: the area's bar is the area's, whatever wraps it.
193    fn area_toolbar(
194        &self,
195        context: crate::ToolbarContext,
196    ) -> Option<Option<&dyn crate::widget::Widget<Msg>>> {
197        self.inner.area_toolbar(context)
198    }
199});
200
201#[cfg(test)]
202mod tests {
203    use super::*;
204    use crate::{build_ui, Container, Runtime, Size, Theme};
205
206    #[derive(Clone, Debug, PartialEq)]
207    enum Msg {
208        Menu,
209    }
210
211    /// Another tree's message type, which the shell's message is not.
212    #[derive(Clone, Debug, PartialEq)]
213    enum Other {
214        #[allow(dead_code)]
215        Menu,
216    }
217
218    /// Outside a shell there is no shell, and the answer says so rather than inventing one.
219    #[test]
220    fn there_is_no_shell_until_one_says_so() {
221        let bare = ScaffoldInfo::of();
222        assert!(!bare.has_drawer() && !bare.has_end_drawer());
223        assert_eq!(bare.drawer_toggle::<Msg>(), None);
224    }
225
226    /// The message comes back to the tree it was put in for, and to nobody else.
227    #[test]
228    fn a_message_is_handed_back_only_to_the_type_it_was_put_in_with() {
229        ScaffoldInfo::default().with_drawer(Msg::Menu).scope(|| {
230            let info = ScaffoldInfo::of();
231            assert!(info.has_drawer());
232            assert_eq!(info.drawer_toggle::<Msg>(), Some(Msg::Menu));
233            // A tree of another message type is told nothing, because it could not
234            // have sent this message anyway.
235            assert_eq!(info.drawer_toggle::<Other>(), None);
236        });
237        // And the scope is closed behind it.
238        assert!(!ScaffoldInfo::of().has_drawer());
239    }
240
241    /// The scope reaches the subtree through the walk, not only the call that installs it —
242    /// which is what an already-built app bar needs.
243    #[test]
244    fn a_scope_reaches_the_subtree_the_walk_visits() {
245        let seen = std::rc::Rc::new(std::cell::Cell::new(false));
246        let probe = {
247            let seen = seen.clone();
248            crate::ThemeBuilder::<Msg>::boxed(move |_| {
249                seen.set(ScaffoldInfo::of().has_drawer());
250                Box::new(Container::new().color(frus_core::Color::WHITE))
251            })
252        };
253        let tree = ScaffoldScope::new(ScaffoldInfo::default().with_drawer(Msg::Menu), probe);
254        build_ui(
255            &tree,
256            Size::new(100.0, 100.0),
257            &Runtime::default(),
258            &Theme::default(),
259        );
260        assert!(seen.get(), "the deferred build did not see the shell");
261    }
262
263    /// Two shells that differ in what they hold must not share a layout: a drawer is a
264    /// button in the bar, and a button is a different row. The cache keys on a fingerprint
265    /// of the walk, so the shell has to be in it — the same trap `theme_override` and
266    /// `media_override` each document beside themselves.
267    #[test]
268    fn the_shell_is_part_of_the_relayout_fingerprint() {
269        // One runtime across both builds, so the second really does consult the first's
270        // cache rather than starting from nothing.
271        let runtime = Runtime::default();
272        let height = |drawer: bool| {
273            let probe = crate::ThemeBuilder::<Msg>::boxed(move |_| {
274                // A shell with a drawer composes a taller box, the way a bar with a menu
275                // button composes a different row.
276                let tall = if ScaffoldInfo::of().has_drawer() {
277                    40.0
278                } else {
279                    10.0
280                };
281                Box::new(
282                    Container::new()
283                        .width(10.0)
284                        .height(tall)
285                        .color(frus_core::Color::rgb8(255, 0, 128)),
286                )
287            });
288            let info = if drawer {
289                ScaffoldInfo::default().with_drawer(Msg::Menu)
290            } else {
291                ScaffoldInfo::default()
292            };
293            let tree = ScaffoldScope::new(info, probe);
294            build_ui(&tree, Size::new(100.0, 100.0), &runtime, &Theme::default())
295                .scene()
296                .primitives()
297                .iter()
298                .find_map(|p| match p {
299                    frus_core::Primitive::Rect { rect, .. } => Some(rect.height),
300                    _ => None,
301                })
302        };
303        let with = height(true);
304        let without = height(false);
305        assert_ne!(
306            with, without,
307            "a shell with a drawer was served from the cache of one without"
308        );
309        assert_eq!(height(true), with, "and back again");
310    }
311}