Skip to main content

egui_pop_core/
placeholder.rs

1//! Placeholders: skeletons standing in for content that fills
2//! progressively (a metadata panel, a queue's rows, parameters while
3//! they load), and empty states saying why a place is empty and what to
4//! do about it.
5//!
6//! - [`Skeleton`]: grey shapes in the content's layout (the kit's
7//!   `skeleton`) with a shimmer crossing them (`skeleton-shimmer`, in
8//!   `motion.skeleton.shimmer`); no shimmer under reduced motion, nor
9//!   under a given motion clock (tests). Its region carries AccessKit's
10//!   `busy` flag and the name "Loading", so assistive technologies wait
11//!   for the content rather than read grey boxes. Not for thumbnails:
12//!   use what is known (an embedded preview, an average colour) instead;
13//! - [`EmptyState`]: an icon, a title, a sentence and an optional
14//!   action; [`EmptyState::show`] says whether the action was clicked
15//!   (the application runs its command).
16//!
17//! ```
18//! use egui_pop_core::icon::Icon;
19//! use egui_pop_core::placeholder::{EmptyState, Skeleton};
20//!
21//! fn ui(ui: &mut egui::Ui, loaded: bool, images: usize) {
22//!     if !loaded {
23//!         ui.add(Skeleton::rows(4));
24//!     } else if images == 0 {
25//!         let import = EmptyState::new(Icon::Folder, "No images in this folder")
26//!             .text("Import images to see them here.")
27//!             .action("Import images")
28//!             .show(ui);
29//!         let _ = import;
30//!     }
31//! }
32//! ```
33
34use egui::{Color32, Rect, Response, Role, Sense, Ui, Widget, WidgetInfo, pos2, vec2};
35
36use crate::icon::IconRef;
37use crate::kit::{Kit, KitCx, Part, State, Tone};
38use crate::motion;
39use crate::strings;
40use crate::theme::Tokens;
41
42/// The skeleton colours of the installed kit, for what stands in for
43/// content without being a skeleton (a thumbnail not loaded yet).
44#[derive(Clone, Debug, PartialEq)]
45pub struct SkeletonTokens {
46    /// `skeleton.rest.fill`.
47    pub fill: Color32,
48    /// `skeleton-shimmer.rest.fill`.
49    pub shimmer: Color32,
50}
51
52impl SkeletonTokens {
53    pub fn of(ctx: &egui::Context) -> SkeletonTokens {
54        let kit = Kit::of(ctx);
55        SkeletonTokens {
56            fill: kit.skeleton.style(State::REST).fill,
57            shimmer: kit.skeleton_shimmer.style(State::REST).fill,
58        }
59    }
60}
61
62/// A shape of a skeleton.
63#[derive(Clone, Copy, Debug, PartialEq)]
64enum Shape {
65    /// A line of text, this share of the width.
66    Line(f32),
67    /// A square block (an avatar, an icon).
68    Block,
69}
70
71/// Grey shapes standing in for content.
72///
73/// Need (state): a value or a list still loading.
74/// Need (state): placeholder shapes while content loads.
75#[derive(Clone, Debug, PartialEq)]
76#[must_use = "add it with `ui.add`"]
77pub struct Skeleton {
78    /// Rows of shapes, each row its shapes left to right.
79    rows: Vec<Vec<Shape>>,
80    width: Option<f32>,
81    label: Option<String>,
82}
83
84impl Skeleton {
85    /// A paragraph of `lines` lines, the last one shorter.
86    pub fn text(lines: usize) -> Self {
87        let rows = (0..lines.max(1))
88            .map(|i| vec![Shape::Line(if i + 1 == lines.max(1) { 0.6 } else { 1.0 })])
89            .collect();
90        Self {
91            rows,
92            width: None,
93            label: None,
94        }
95    }
96
97    /// List rows: a block and two lines each.
98    pub fn rows(rows: usize) -> Self {
99        Self {
100            rows: (0..rows.max(1))
101                .map(|_| vec![Shape::Block, Shape::Line(1.0)])
102                .collect(),
103            width: None,
104            label: None,
105        }
106    }
107
108    /// Its width (the available width by default).
109    pub fn width(mut self, width: f32) -> Self {
110        self.width = Some(width);
111        self
112    }
113
114    /// What is loading ("Loading the metadata"); "Loading" by default.
115    pub fn label(mut self, label: impl Into<String>) -> Self {
116        self.label = Some(label.into());
117        self
118    }
119}
120
121impl Widget for Skeleton {
122    fn ui(self, ui: &mut Ui) -> Response {
123        let ctx = ui.ctx().clone();
124        let t = Tokens::of(&ctx);
125        let kit = Kit::of(&ctx);
126        let line = t.font.body;
127        let gap = t.space.s;
128        let block = t.size.control_height;
129        // A row with a block needs room for it; lines alone keep the
130        // width given (a late value's short line).
131        let has_block = self
132            .rows
133            .iter()
134            .flatten()
135            .any(|s| matches!(s, Shape::Block));
136        let width = match self.width {
137            Some(w) if !has_block => w.max(1.0),
138            w => w.unwrap_or_else(|| ui.available_width()).max(block * 2.0),
139        };
140        let row_h = |row: &Vec<Shape>| {
141            if row.iter().any(|s| matches!(s, Shape::Block)) {
142                block
143            } else {
144                line
145            }
146        };
147        let height: f32 = self.rows.iter().map(row_h).sum::<f32>()
148            + gap * (self.rows.len().saturating_sub(1)) as f32;
149        let (rect, response) = ui.allocate_exact_size(vec2(width, height), Sense::hover());
150        if ui.is_rect_visible(rect) {
151            let painter = ui.painter_at(rect);
152            let cx = KitCx {
153                painter: &painter,
154                ppp: ctx.pixels_per_point(),
155            };
156            let part_at = |rect: Rect| Part {
157                rect,
158                room: rect,
159                state: State::REST,
160                label: None,
161            };
162            let mut shapes = Vec::new();
163            let mut y = rect.top();
164            for row in &self.rows {
165                let h = row_h(row);
166                let mut x = rect.left();
167                for shape in row {
168                    match *shape {
169                        Shape::Block => {
170                            shapes.push(Rect::from_min_size(pos2(x, y), vec2(block, block)));
171                            x += block + t.space.m;
172                        }
173                        Shape::Line(share) if h > line => {
174                            // Beside a block: two lines.
175                            let w = (rect.right() - x) * share;
176                            let l = (h - gap) / 2.0;
177                            shapes.push(Rect::from_min_size(pos2(x, y), vec2(w, l * 0.8)));
178                            shapes.push(Rect::from_min_size(
179                                pos2(x, y + l + gap),
180                                vec2(w * 0.6, l * 0.8),
181                            ));
182                        }
183                        Shape::Line(share) => {
184                            let w = (rect.right() - x) * share;
185                            shapes.push(Rect::from_min_size(pos2(x, y), vec2(w, line * 0.8)));
186                        }
187                    }
188                }
189                y += h + gap;
190            }
191            for r in &shapes {
192                kit.skeleton.paint(&cx, &part_at(*r));
193            }
194            // The shimmer: a lighter band crossing, never in tests nor
195            // under reduced motion.
196            if !motion::reduced(&ctx) && !motion::controlled(&ctx) {
197                let p = motion::phase(&ctx, f64::from(t.motion.skeleton_shimmer), 0.0);
198                let band = rect.width() * 0.25;
199                let x = rect.left() - band + p * (rect.width() + band);
200                let shine = Rect::from_min_max(pos2(x, rect.top()), pos2(x + band, rect.bottom()));
201                for r in &shapes {
202                    let part = r.intersect(shine);
203                    if part.is_positive() {
204                        kit.skeleton_shimmer.paint(&cx, &part_at(part));
205                    }
206                }
207                motion::animate(&ctx);
208            }
209        }
210        let label = self
211            .label
212            .unwrap_or_else(|| strings::tr(&ctx, &strings::LOADING));
213        let enabled = ui.is_enabled();
214        response.widget_info(|| WidgetInfo::labeled(Role::Unknown, enabled, &label));
215        ctx.accesskit_node_builder(response.id, |node| node.set_busy());
216        response
217    }
218}
219
220/// An empty place: an icon, a title, a sentence, an action.
221///
222/// Need (state): an empty state, nothing here yet.
223/// Need (state): no results for a search or a filter.
224#[derive(Clone, Debug, PartialEq)]
225#[must_use = "show it with `show`"]
226pub struct EmptyState {
227    icon: IconRef,
228    title: String,
229    text: Option<String>,
230    action: Option<String>,
231    danger: bool,
232}
233
234impl EmptyState {
235    /// An icon by value or by name (`Icon::Folder`, `"phosphor:image"`),
236    /// and a title.
237    pub fn new(icon: impl Into<IconRef>, title: impl Into<String>) -> Self {
238        Self {
239            icon: icon.into(),
240            title: title.into(),
241            text: None,
242            action: None,
243            danger: false,
244        }
245    }
246
247    /// A sentence under the title: why, and what to do.
248    pub fn text(mut self, text: impl Into<String>) -> Self {
249        self.text = Some(text.into());
250        self
251    }
252
253    /// A button under the sentence ("Import images", "Retry").
254    pub fn action(mut self, label: impl Into<String>) -> Self {
255        self.action = Some(label.into());
256        self
257    }
258
259    /// Something went wrong: the icon in the danger colour.
260    pub fn danger(mut self) -> Self {
261        self.danger = true;
262        self
263    }
264
265    /// Draws it centred in the available width; whether its action was
266    /// clicked.
267    pub fn show(self, ui: &mut Ui) -> bool {
268        let t = Tokens::of(ui.ctx());
269        let kit = Kit::of(ui.ctx());
270        let empty = &kit.empty_state;
271        let tone = if self.danger {
272            Tone::Danger
273        } else {
274            Tone::Neutral
275        };
276        let state = State::REST.toned(tone);
277        let pad = empty.data.padding_y;
278        let mut clicked = false;
279        // The box goes under the content, painted once its size is known.
280        let slot = ui.painter().add(egui::Shape::Noop);
281        let r = ui.vertical_centered(|ui| {
282            ui.add_space(pad);
283            let side = t.size.icon_panel * 2.0;
284            let (rect, _) = ui.allocate_exact_size(vec2(side, side), Sense::hover());
285            if ui.is_rect_visible(rect) {
286                self.icon.or_placeholder("empty-state").paint(
287                    ui.painter(),
288                    rect,
289                    empty.style(state).text,
290                );
291            }
292            ui.add_space(t.space.s);
293            ui.label(egui::RichText::new(&self.title).strong());
294            if let Some(text) = &self.text {
295                ui.label(egui::RichText::new(text).color(empty.style(State::REST).text));
296            }
297            if let Some(action) = &self.action {
298                ui.add_space(t.space.s);
299                clicked = ui.button(action).clicked();
300            }
301            ui.add_space(pad);
302        });
303        let rect = r.response.rect;
304        empty.paint_under(
305            ui,
306            slot,
307            &Part {
308                rect,
309                room: rect,
310                state,
311                label: None,
312            },
313            None,
314        );
315        clicked
316    }
317}