Skip to main content

qframe/widgets/
app_shell.rs

1//! The application frame: header, sidebar, body and footer.
2
3use crate::geometry::{Rect, Size};
4use crate::widget::{Axis, Flex, Length, MeasureCx, Node, NodeMut, PaintCx, View, Widget};
5
6type Part<'a, Msg> = Box<dyn FnOnce(&mut View<'_, Msg>) + 'a>;
7
8/// Builds the common application frame: a header on top, a sidebar on the left, the body
9/// beside it and a footer at the bottom.
10///
11/// The parts are separated by surface colour only. Below `collapse_below` columns the sidebar
12/// is hidden to give the body room; while `sidebar_open` is true it is drawn over the body as a
13/// layer instead. Style keys: `shell-header`, `shell-sidebar`, `shell-body`, `shell-footer`
14/// (`bg`).
15pub struct AppShell<'a, Msg> {
16    header: Option<Part<'a, Msg>>,
17    sidebar: Option<Part<'a, Msg>>,
18    body: Option<Part<'a, Msg>>,
19    footer: Option<Part<'a, Msg>>,
20    sidebar_width: u16,
21    collapse_below: u16,
22    sidebar_open: bool,
23}
24
25impl<'a, Msg: 'static> AppShell<'a, Msg> {
26    /// A shell with a 28-column sidebar that collapses below 90 columns.
27    #[must_use]
28    pub fn new() -> Self {
29        Self {
30            header: None,
31            sidebar: None,
32            body: None,
33            footer: None,
34            sidebar_width: 28,
35            collapse_below: 90,
36            sidebar_open: false,
37        }
38    }
39
40    /// The top bar.
41    #[must_use]
42    pub fn header(mut self, build: impl FnOnce(&mut View<'_, Msg>) + 'a) -> Self {
43        self.header = Some(Box::new(build));
44        self
45    }
46
47    /// The navigation column.
48    #[must_use]
49    pub fn sidebar(mut self, build: impl FnOnce(&mut View<'_, Msg>) + 'a) -> Self {
50        self.sidebar = Some(Box::new(build));
51        self
52    }
53
54    /// The main content.
55    #[must_use]
56    pub fn body(mut self, build: impl FnOnce(&mut View<'_, Msg>) + 'a) -> Self {
57        self.body = Some(Box::new(build));
58        self
59    }
60
61    /// The bottom bar, usually [`KeyHints`](crate::widgets::KeyHints).
62    #[must_use]
63    pub fn footer(mut self, build: impl FnOnce(&mut View<'_, Msg>) + 'a) -> Self {
64        self.footer = Some(Box::new(build));
65        self
66    }
67
68    /// Sidebar width in columns.
69    #[must_use]
70    pub fn sidebar_width(mut self, columns: u16) -> Self {
71        self.sidebar_width = columns;
72        self
73    }
74
75    /// Screen width under which the sidebar collapses.
76    #[must_use]
77    pub fn collapse_below(mut self, columns: u16) -> Self {
78        self.collapse_below = columns;
79        self
80    }
81
82    /// Shows the collapsed sidebar as a layer over the body.
83    #[must_use]
84    pub fn sidebar_open(mut self, open: bool) -> Self {
85        self.sidebar_open = open;
86        self
87    }
88
89    /// Adds the shell to `ui`, filling the space it gets.
90    pub fn show<'v>(self, ui: &'v mut View<'_, Msg>) -> NodeMut<'v, Msg> {
91        let build = |part: Option<Part<'a, Msg>>| {
92            let mut children = Vec::new();
93            if let Some(part) = part {
94                part(&mut ui.nested(&mut children));
95            }
96            let mut node = Node::new(Flex::new(Axis::Column, children), 0);
97            node.layout.width = Length::Fill(1);
98            node.layout.height = Length::Fill(1);
99            node
100        };
101        let shell = Shell {
102            parts: vec![build(self.header), build(self.sidebar), build(self.body), build(self.footer)],
103            sidebar_width: self.sidebar_width,
104            collapse_below: self.collapse_below,
105            sidebar_open: self.sidebar_open,
106        };
107        ui.add(shell).fill()
108    }
109}
110
111impl<Msg: 'static> Default for AppShell<'_, Msg> {
112    fn default() -> Self {
113        Self::new()
114    }
115}
116
117const HEADER: usize = 0;
118const SIDEBAR: usize = 1;
119const BODY: usize = 2;
120const FOOTER: usize = 3;
121
122struct Shell<Msg> {
123    parts: Vec<Node<Msg>>,
124    sidebar_width: u16,
125    collapse_below: u16,
126    sidebar_open: bool,
127}
128
129impl<Msg: 'static> Shell<Msg> {
130    fn part_height(&self, cx: &mut PaintCx<'_>, index: usize, area: Rect) -> u16 {
131        if self.parts[index].widget.children().is_empty() {
132            return 0;
133        }
134        cx.measure_child(&self.parts[index], area.size()).height
135    }
136
137    fn collapsed(&self, area: Rect) -> bool {
138        area.width < self.collapse_below
139    }
140
141    /// The heights of the header and the footer in `area`.
142    fn bars(&self, cx: &mut PaintCx<'_>, area: Rect) -> (u16, u16) {
143        (self.part_height(cx, HEADER, area), self.part_height(cx, FOOTER, area))
144    }
145
146    /// The row band between a header `header` rows tall and a footer `footer` rows tall.
147    fn middle(area: Rect, (header, footer): (u16, u16)) -> Rect {
148        Rect::new(
149            area.x,
150            area.y + i32::from(header),
151            area.width,
152            area.height.saturating_sub(header.saturating_add(footer)),
153        )
154    }
155
156    fn has_sidebar(&self) -> bool {
157        !self.parts[SIDEBAR].widget.children().is_empty()
158    }
159}
160
161impl<Msg: 'static> Widget<Msg> for Shell<Msg> {
162    fn measure(&self, _cx: &mut MeasureCx<'_>, available: Size) -> Size {
163        available
164    }
165
166    fn paint(&self, cx: &mut PaintCx<'_>, area: Rect) {
167        let (header, footer) = self.bars(cx, area);
168        let middle = Self::middle(area, (header, footer));
169        if header > 0 {
170            let rect = Rect::new(area.x, area.y, area.width, header);
171            paint_part(cx, &self.parts[HEADER], rect, "shell-header");
172        }
173        let sidebar = self.has_sidebar() && !self.collapsed(area);
174        let sidebar_width = if sidebar { self.sidebar_width.min(area.width) } else { 0 };
175        if sidebar {
176            let rect = Rect::new(middle.x, middle.y, sidebar_width, middle.height);
177            paint_part(cx, &self.parts[SIDEBAR], rect, "shell-sidebar");
178        }
179        let body = Rect::new(
180            middle.x + i32::from(sidebar_width),
181            middle.y,
182            middle.width.saturating_sub(sidebar_width),
183            middle.height,
184        );
185        paint_part(cx, &self.parts[BODY], body, "shell-body");
186        if footer > 0 {
187            let rect = Rect::new(area.x, area.bottom() - i32::from(footer), area.width, footer);
188            paint_part(cx, &self.parts[FOOTER], rect, "shell-footer");
189        }
190        if self.has_sidebar() && self.collapsed(area) && self.sidebar_open {
191            cx.request_overlay(area);
192        }
193    }
194
195    fn paint_overlay(&self, cx: &mut PaintCx<'_>, anchor: Rect) {
196        let middle = Self::middle(anchor, self.bars(cx, anchor));
197        let width = self.sidebar_width.min(middle.width);
198        let rect = Rect::new(middle.x, middle.y, width, middle.height);
199        cx.register_hit(rect);
200        // Drawn over the body, the sidebar floats: it keeps apart from the body and the bars.
201        cx.floating(rect, |cx| paint_part(cx, &self.parts[SIDEBAR], rect, "shell-sidebar"));
202    }
203
204    fn children(&self) -> &[Node<Msg>] {
205        &self.parts
206    }
207
208    fn children_mut(&mut self) -> &mut [Node<Msg>] {
209        &mut self.parts
210    }
211}
212
213fn paint_part<Msg: 'static>(cx: &mut PaintCx<'_>, node: &Node<Msg>, rect: Rect, style: &str) {
214    let background = cx.style(style, None, &[]).text().bg;
215    if let Some(bg) = background {
216        cx.clear(rect, bg);
217    }
218    cx.paint_child(node, rect);
219}
220
221#[cfg(test)]
222mod tests {
223    use super::*;
224    use crate::runtime::{App, Command, Harness};
225    use crate::widgets::Text;
226
227    struct Demo {
228        open: bool,
229    }
230
231    impl App for Demo {
232        type Msg = ();
233        fn update(&mut self, _: ()) -> Command<()> {
234            Command::none()
235        }
236        fn view(&self, ui: &mut View<'_, ()>) {
237            AppShell::new()
238                .sidebar_width(8)
239                .collapse_below(30)
240                .sidebar_open(self.open)
241                .header(|ui| {
242                    ui.add(Text::new("head"));
243                })
244                .sidebar(|ui| {
245                    ui.add(Text::new("menu"));
246                })
247                .body(|ui| {
248                    ui.add(Text::new("body"));
249                })
250                .footer(|ui| {
251                    ui.add(Text::new("foot"));
252                })
253                .show(ui);
254        }
255    }
256
257    #[test]
258    fn lays_out_parts_on_their_surfaces() {
259        let h = Harness::new(Demo { open: false }, 30, 4);
260        assert_eq!(h.screen(), "head\nmenu    body\n\nfoot\n");
261        let theme = h.env().theme();
262        assert_eq!(h.bg(0, 1), theme.color("surface"));
263        assert_eq!(h.bg(10, 1), theme.color("canvas"));
264    }
265
266    #[test]
267    fn collapses_sidebar_and_opens_it_as_a_layer() {
268        let closed = Harness::new(Demo { open: false }, 20, 4);
269        assert_eq!(closed.screen(), "head\nbody\n\nfoot\n");
270        let open = Harness::new(Demo { open: true }, 20, 4);
271        assert_eq!(open.screen(), "head\nmenu\n\nfoot\n");
272    }
273}