Skip to main content

cranpose_ui/widgets/
scaffold.rs

1//! Compose-like window scaffold with framework-owned system insets.
2
3#![allow(non_snake_case)]
4
5use std::rc::Rc;
6
7use cranpose_core::{NodeId, SlotId};
8use cranpose_ui_graphics::{Color, EdgeInsets};
9use cranpose_ui_layout::{Constraints, Placement};
10
11use super::SubcomposeLayout;
12use crate::{
13    Modifier, composable,
14    layout_direction::{LayoutDirection, layout_direction},
15    subcompose_layout::{SubcomposeLayoutScope, SubcomposeMeasureScope},
16};
17
18/// Insets supplied to a scaffold's content slot, in reading order.
19///
20/// `start` and `end` are the reading-order edges: in a left-to-right layout
21/// `start` is the left edge, in a right-to-left layout it is the right one.
22#[derive(Clone, Copy, Debug, Default, PartialEq)]
23pub struct PaddingValues {
24    pub start: f32,
25    pub top: f32,
26    pub end: f32,
27    pub bottom: f32,
28}
29
30impl PaddingValues {
31    pub const fn new(start: f32, top: f32, end: f32, bottom: f32) -> Self {
32        Self {
33            start,
34            top,
35            end,
36            bottom,
37        }
38    }
39
40    /// The same padding on every edge.
41    pub const fn all(value: f32) -> Self {
42        Self::new(value, value, value, value)
43    }
44
45    /// Applies these values in the composition's current reading order.
46    pub fn apply_to(self, modifier: Modifier) -> Modifier {
47        self.apply_to_in(modifier, layout_direction())
48    }
49
50    /// Applies these values against an explicit reading order.
51    pub fn apply_to_in(self, modifier: Modifier, direction: LayoutDirection) -> Modifier {
52        modifier.padding_relative_in(direction, self.start, self.top, self.end, self.bottom)
53    }
54
55    /// The physical left/top/right/bottom edges in `direction`.
56    pub fn physical(self, direction: LayoutDirection) -> EdgeInsets {
57        let (left, right) = direction.resolve(self.start, self.end);
58        EdgeInsets::from_components(left, self.top, right, self.bottom)
59    }
60
61    /// The larger of each edge, used to merge bar heights with window insets.
62    pub fn max(self, other: Self) -> Self {
63        Self::new(
64            self.start.max(other.start),
65            self.top.max(other.top),
66            self.end.max(other.end),
67            self.bottom.max(other.bottom),
68        )
69    }
70}
71
72/// The surfaces a scaffold paints behind its slots.
73///
74/// A scaffold that states no colours paints nothing and leaves every surface to
75/// its slots, which is what a full-bleed game or a custom-chrome window wants.
76#[derive(Clone, Copy, Debug, Default, PartialEq)]
77pub struct ScaffoldColors {
78    /// Painted across the whole scaffold, behind every slot.
79    pub background: Option<Color>,
80    /// Painted behind the top bar, including the status-bar area it draws under.
81    pub top_bar: Option<Color>,
82    /// Painted behind the bottom bar, including the navigation-bar area.
83    pub bottom_bar: Option<Color>,
84}
85
86impl ScaffoldColors {
87    /// A scaffold whose background is `background` and whose bars are painted
88    /// with the same colour.
89    pub fn uniform(background: Color) -> Self {
90        Self {
91            background: Some(background),
92            top_bar: Some(background),
93            bottom_bar: Some(background),
94        }
95    }
96
97    /// Sets the whole-scaffold background.
98    pub fn with_background(mut self, color: Color) -> Self {
99        self.background = Some(color);
100        self
101    }
102}
103
104/// Which window insets a scaffold consumes on the application's behalf.
105///
106/// The default consumes every side, which is what an ordinary screen wants. A
107/// screen that draws its own edge-to-edge content — a map, a photo viewer —
108/// turns off the sides it handles itself.
109#[derive(Clone, Copy, Debug, PartialEq, Eq)]
110pub struct ScaffoldContentInsets {
111    /// Consume the top window inset (status bar, notch).
112    pub top: bool,
113    /// Consume the bottom window inset (navigation bar, home indicator, IME).
114    pub bottom: bool,
115    /// Consume the reading-order start inset (a cutout, a curved edge).
116    pub start: bool,
117    /// Consume the reading-order end inset.
118    pub end: bool,
119}
120
121impl Default for ScaffoldContentInsets {
122    fn default() -> Self {
123        Self {
124            top: true,
125            bottom: true,
126            start: true,
127            end: true,
128        }
129    }
130}
131
132impl ScaffoldContentInsets {
133    /// Consume nothing: every slot sees the raw window bounds.
134    pub const fn none() -> Self {
135        Self {
136            top: false,
137            bottom: false,
138            start: false,
139            end: false,
140        }
141    }
142
143    fn filter(self, insets: PaddingValues) -> PaddingValues {
144        PaddingValues::new(
145            if self.start { insets.start } else { 0.0 },
146            if self.top { insets.top } else { 0.0 },
147            if self.end { insets.end } else { 0.0 },
148            if self.bottom { insets.bottom } else { 0.0 },
149        )
150    }
151}
152
153/// Everything a scaffold shows besides its content.
154#[derive(Clone)]
155struct ScaffoldSlots {
156    top_bar: Rc<dyn Fn()>,
157    bottom_bar: Rc<dyn Fn()>,
158    floating_action: Rc<dyn Fn()>,
159    content: Rc<dyn Fn(PaddingValues)>,
160}
161
162impl PartialEq for ScaffoldSlots {
163    fn eq(&self, other: &Self) -> bool {
164        Rc::ptr_eq(&self.top_bar, &other.top_bar)
165            && Rc::ptr_eq(&self.bottom_bar, &other.bottom_bar)
166            && Rc::ptr_eq(&self.floating_action, &other.floating_action)
167            && Rc::ptr_eq(&self.content, &other.content)
168    }
169}
170
171/// How a scaffold is configured beyond its slots.
172#[derive(Clone, Copy, Debug, Default, PartialEq)]
173pub struct ScaffoldSpec {
174    /// Surfaces painted behind the slots.
175    pub colors: ScaffoldColors,
176    /// Which window insets the scaffold consumes.
177    pub content_insets: ScaffoldContentInsets,
178}
179
180impl ScaffoldSpec {
181    /// Sets the surfaces.
182    pub fn with_colors(mut self, colors: ScaffoldColors) -> Self {
183        self.colors = colors;
184        self
185    }
186}
187
188/// Places optional window bars and a floating action over a full-size content
189/// slot, and reports the space occupied by the bars and by platform
190/// obstructions as reading-order inner padding.
191///
192/// Bars receive the full window bounds so they can draw behind system areas; a
193/// bar that places controls there uses [`crate::window_insets`].
194pub fn Scaffold<T, B, C>(modifier: Modifier, top_bar: T, bottom_bar: B, content: C) -> NodeId
195where
196    T: Fn() + 'static,
197    B: Fn() + 'static,
198    C: Fn(PaddingValues) + 'static,
199{
200    ScaffoldWith(
201        modifier,
202        ScaffoldSpec::default(),
203        top_bar,
204        bottom_bar,
205        || {},
206        content,
207    )
208}
209
210/// A scaffold with surfaces, inset policy and a floating-action slot.
211pub fn ScaffoldWith<T, B, F, C>(
212    modifier: Modifier,
213    spec: ScaffoldSpec,
214    top_bar: T,
215    bottom_bar: B,
216    floating_action: F,
217    content: C,
218) -> NodeId
219where
220    T: Fn() + 'static,
221    B: Fn() + 'static,
222    F: Fn() + 'static,
223    C: Fn(PaddingValues) + 'static,
224{
225    ScaffoldImpl(
226        modifier,
227        spec,
228        ScaffoldSlots {
229            top_bar: Rc::new(top_bar),
230            bottom_bar: Rc::new(bottom_bar),
231            floating_action: Rc::new(floating_action),
232            content: Rc::new(content),
233        },
234    )
235}
236
237/// The gap a floating action keeps from the window edges.
238const FLOATING_ACTION_MARGIN: f32 = 16.0;
239
240#[composable]
241fn ScaffoldImpl(modifier: Modifier, spec: ScaffoldSpec, slots: ScaffoldSlots) -> NodeId {
242    let direction = layout_direction();
243    let insets = crate::safe_area::window_insets().combined();
244    let (start_inset, end_inset) = match direction {
245        LayoutDirection::Ltr => (insets.left, insets.right),
246        LayoutDirection::Rtl => (insets.right, insets.left),
247    };
248    let window_padding = spec.content_insets.filter(PaddingValues::new(
249        start_inset,
250        insets.top,
251        end_inset,
252        insets.bottom,
253    ));
254
255    let colors = spec.colors;
256    let modifier = match colors.background {
257        Some(background) => modifier.background(background),
258        None => modifier,
259    };
260
261    let top_bar = slots.top_bar;
262    let bottom_bar = slots.bottom_bar;
263    let floating_action = slots.floating_action;
264    let content = slots.content;
265
266    SubcomposeLayout(modifier, move |scope, constraints| {
267        let width = constraints.max_width.max(constraints.min_width);
268        let height = constraints.max_height.max(constraints.min_height);
269        let loose = Constraints::loose(width, height);
270
271        let top_content = Rc::clone(&top_bar);
272        let top_nodes = scope.subcompose(SlotId::new(0), (), move || top_content());
273        let mut top_height = 0.0_f32;
274        let mut top_placements = Vec::with_capacity(top_nodes.len());
275        for node in top_nodes {
276            let placeable = scope.measure(node, loose);
277            top_height = top_height.max(placeable.height());
278            top_placements.push(Placement::new(placeable.node_id(), 0.0, 0.0, 1));
279        }
280
281        let bottom_content = Rc::clone(&bottom_bar);
282        let bottom_nodes = scope.subcompose(SlotId::new(1), (), move || bottom_content());
283        let mut bottom_height = 0.0_f32;
284        let mut bottom_placeables = Vec::with_capacity(bottom_nodes.len());
285        for node in bottom_nodes {
286            let placeable = scope.measure(node, loose);
287            bottom_height = bottom_height.max(placeable.height());
288            bottom_placeables.push(placeable);
289        }
290
291        let padding = window_padding.max(PaddingValues::new(0.0, top_height, 0.0, bottom_height));
292        let content_slot = Rc::clone(&content);
293        let content_nodes =
294            scope.subcompose(SlotId::new(2), padding, move || content_slot(padding));
295
296        let mut placements = Vec::with_capacity(
297            top_placements.len() + bottom_placeables.len() + content_nodes.len() + 1,
298        );
299        for node in content_nodes {
300            let placeable = scope.measure(node, Constraints::tight(width, height));
301            placements.push(Placement::new(placeable.node_id(), 0.0, 0.0, 0));
302        }
303        placements.extend(top_placements);
304        for placeable in bottom_placeables {
305            placements.push(Placement::new(
306                placeable.node_id(),
307                0.0,
308                (height - placeable.height()).max(0.0),
309                1,
310            ));
311        }
312
313        let floating_content = Rc::clone(&floating_action);
314        let floating_nodes = scope.subcompose(SlotId::new(3), (), move || floating_content());
315        for node in floating_nodes {
316            let placeable = scope.measure(node, loose);
317            let bottom_gap = padding.bottom + FLOATING_ACTION_MARGIN;
318            let end_gap = padding.end + FLOATING_ACTION_MARGIN;
319            let x = match direction {
320                LayoutDirection::Ltr => (width - placeable.width() - end_gap).max(0.0),
321                LayoutDirection::Rtl => end_gap.min((width - placeable.width()).max(0.0)),
322            };
323            let y = (height - placeable.height() - bottom_gap).max(0.0);
324            placements.push(Placement::new(placeable.node_id(), x, y, 2));
325        }
326
327        scope.layout(width, height, placements)
328    })
329}
330
331#[cfg(test)]
332mod tests {
333    use super::*;
334
335    #[test]
336    fn padding_values_preserve_each_edge() {
337        assert_eq!(
338            PaddingValues::new(1.0, 2.0, 3.0, 4.0),
339            PaddingValues {
340                start: 1.0,
341                top: 2.0,
342                end: 3.0,
343                bottom: 4.0,
344            }
345        );
346        assert_eq!(
347            PaddingValues::all(6.0),
348            PaddingValues::new(6.0, 6.0, 6.0, 6.0)
349        );
350    }
351
352    #[test]
353    fn reading_order_padding_swaps_sides_in_a_right_to_left_layout() {
354        let padding = PaddingValues::new(24.0, 2.0, 8.0, 4.0);
355        assert_eq!(
356            padding.physical(LayoutDirection::Ltr),
357            EdgeInsets::from_components(24.0, 2.0, 8.0, 4.0)
358        );
359        assert_eq!(
360            padding.physical(LayoutDirection::Rtl),
361            EdgeInsets::from_components(8.0, 2.0, 24.0, 4.0)
362        );
363    }
364
365    #[test]
366    fn merging_takes_the_larger_of_each_edge() {
367        let bars = PaddingValues::new(0.0, 56.0, 0.0, 0.0);
368        let insets = PaddingValues::new(0.0, 24.0, 0.0, 48.0);
369        assert_eq!(insets.max(bars), PaddingValues::new(0.0, 56.0, 0.0, 48.0));
370    }
371
372    #[test]
373    fn a_screen_can_keep_the_insets_it_draws_under() {
374        let insets = PaddingValues::new(4.0, 24.0, 4.0, 48.0);
375        let consumed = ScaffoldContentInsets {
376            top: false,
377            ..ScaffoldContentInsets::default()
378        }
379        .filter(insets);
380        assert_eq!(consumed, PaddingValues::new(4.0, 0.0, 4.0, 48.0));
381        assert_eq!(
382            ScaffoldContentInsets::none().filter(insets),
383            PaddingValues::default()
384        );
385    }
386
387    #[test]
388    fn a_scaffold_states_no_surfaces_by_default() {
389        assert_eq!(ScaffoldSpec::default().colors, ScaffoldColors::default());
390        let colors = ScaffoldColors::uniform(Color(0.1, 0.1, 0.1, 1.0));
391        assert_eq!(colors.background, colors.top_bar);
392        assert_eq!(colors.background, colors.bottom_bar);
393    }
394}