Skip to main content

egui_pop_core/
late.rs

1//! Late values: a cell for a value that arrives after asynchronous work
2//! (a volume's free space, a folder's size, a count from a database),
3//! in four states ([`Late`]):
4//!
5//! <div class="warning">Experimental: may change in any release
6//! (docs/stability.md).</div>
7//!
8//! - **pending**: a [`Skeleton`] line, or a delayed [`Spinner`]
9//!   ([`Waiting::Spinner`]), in a box sized like the expected value
10//!   ([`LateValue::sample`], [`LateValue::size`]), so nothing moves when
11//!   the value lands;
12//! - **fresh**: the value, as text in a [`TextRole`] or drawn by a
13//!   closure ([`LateValue::show_with`]);
14//! - **refreshing**: the last value, a small spinner beside it;
15//! - **failed**: an error icon, the reason and a Retry button;
16//!   [`LateResponse::retry`] says it was clicked (the application runs
17//!   the work again).
18//!
19//! The cell keeps the spinner's room in every state, so its size is the
20//! same pending, fresh and refreshing. Its accessible node (a status) keeps
21//! the value's name; its value says the state (the value, "Loading", the
22//! error) and it is `busy` while the work runs.
23//!
24//! ```
25//! use egui_pop_core::late::{Late, LateValue};
26//!
27//! fn ui(ui: &mut egui::Ui, free: &Late<String>) {
28//!     let cell = LateValue::new("Free space", free.clone())
29//!         .sample("000.0 GB")
30//!         .show(ui);
31//!     if cell.retry {
32//!         // Run the work again.
33//!     }
34//! }
35//! ```
36
37use std::fmt::Display;
38
39use egui::{
40    Align, FontSelection, Id, Layout, Response, Role, Sense, TextWrapMode, Ui, Vec2, WidgetInfo,
41    WidgetText, vec2,
42};
43
44use crate::icon::Icon;
45use crate::placeholder::Skeleton;
46use crate::progress::Spinner;
47use crate::strings::{self, LATE_LOADING, LATE_RETRY, LATE_UPDATING, LOADING};
48use crate::theme::{TextRole, Tokens};
49use crate::ui::role_text;
50
51/// Where a late value stands.
52#[derive(Clone, Debug, PartialEq, Eq)]
53pub enum Late<T> {
54    /// Not known yet: the work runs.
55    Pending,
56    /// Known.
57    Fresh(T),
58    /// Known, and being worked out again: the last value stays.
59    Refreshing(T),
60    /// The work failed, for this reason.
61    Failed(String),
62}
63
64impl<T> Late<T> {
65    /// The value known, fresh or refreshing.
66    pub fn value(&self) -> Option<&T> {
67        match self {
68            Late::Fresh(v) | Late::Refreshing(v) => Some(v),
69            Late::Pending | Late::Failed(_) => None,
70        }
71    }
72
73    /// Whether the work runs (pending or refreshing).
74    pub fn is_busy(&self) -> bool {
75        matches!(self, Late::Pending | Late::Refreshing(_))
76    }
77
78    pub fn as_ref(&self) -> Late<&T> {
79        match self {
80            Late::Pending => Late::Pending,
81            Late::Fresh(v) => Late::Fresh(v),
82            Late::Refreshing(v) => Late::Refreshing(v),
83            Late::Failed(e) => Late::Failed(e.clone()),
84        }
85    }
86
87    /// The same state, the value mapped.
88    pub fn map<U>(self, f: impl FnOnce(T) -> U) -> Late<U> {
89        match self {
90            Late::Pending => Late::Pending,
91            Late::Fresh(v) => Late::Fresh(f(v)),
92            Late::Refreshing(v) => Late::Refreshing(f(v)),
93            Late::Failed(e) => Late::Failed(e),
94        }
95    }
96}
97
98/// What stands in for a pending value.
99#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
100pub enum Waiting {
101    /// A skeleton line, at once.
102    #[default]
103    Skeleton,
104    /// A spinner, delayed when the work's start is known
105    /// ([`LateValue::since`]).
106    Spinner,
107}
108
109/// What [`LateValue::show`] returns.
110#[derive(Debug)]
111pub struct LateResponse {
112    /// The whole cell.
113    pub response: Response,
114    /// Whether Retry was clicked (failed state only).
115    pub retry: bool,
116}
117
118/// A cell showing a value that arrives late, in its four states.
119#[derive(Clone, Debug)]
120#[must_use = "show it with `show` or `show_with`"]
121pub struct LateValue<T> {
122    name: String,
123    late: Late<T>,
124    sample: Option<String>,
125    size: Vec2,
126    role: TextRole,
127    waiting: Waiting,
128    since: Option<f64>,
129    id_salt: Option<Id>,
130}
131
132impl<T> LateValue<T> {
133    /// The value's name ("Free space": its accessible name) and state.
134    pub fn new(name: impl Into<String>, late: Late<T>) -> Self {
135        Self {
136            name: name.into(),
137            late,
138            sample: None,
139            size: Vec2::ZERO,
140            role: TextRole::Body,
141            waiting: Waiting::Skeleton,
142            since: None,
143            id_salt: None,
144        }
145    }
146
147    /// A text as wide as the value is expected to be ("000.0 GB"): the
148    /// cell's room while pending, kept once the value lands.
149    pub fn sample(mut self, text: impl Into<String>) -> Self {
150        self.sample = Some(text.into());
151        self
152    }
153
154    /// The value's room at least (for [`LateValue::show_with`], whose
155    /// drawing the cell cannot measure beforehand).
156    pub fn size(mut self, size: Vec2) -> Self {
157        self.size = size;
158        self
159    }
160
161    /// The text role of the value and of its sample ([`TextRole::Body`]
162    /// by default).
163    pub fn role(mut self, role: TextRole) -> Self {
164        self.role = role;
165        self
166    }
167
168    /// What stands in for a pending value.
169    pub fn waiting(mut self, waiting: Waiting) -> Self {
170        self.waiting = waiting;
171        self
172    }
173
174    /// When the work started (motion clock seconds): the spinners then
175    /// wait `motion.spinner.delay` before showing, and stay
176    /// `motion.spinner.min` once shown ([`Spinner::delayed`]).
177    pub fn since(mut self, seconds: f64) -> Self {
178        self.since = Some(seconds);
179        self
180    }
181
182    /// Tells cells of the same name apart (the delayed spinners' state).
183    pub fn id_salt(mut self, salt: impl std::hash::Hash + std::fmt::Debug) -> Self {
184        self.id_salt = Some(Id::NULL.with(salt));
185        self
186    }
187
188    /// Draws the cell, the value drawn by `add` in the value's room.
189    pub fn show_with(self, ui: &mut Ui, add: impl FnOnce(&mut Ui, &T)) -> LateResponse {
190        self.cell(ui, None, add)
191    }
192
193    fn cell(
194        self,
195        ui: &mut Ui,
196        value_text: Option<String>,
197        add: impl FnOnce(&mut Ui, &T),
198    ) -> LateResponse {
199        let ctx = ui.ctx().clone();
200        let t = Tokens::of(&ctx);
201        let measure = |ui: &Ui, text: &str| {
202            WidgetText::from(role_text(ui, self.role, text))
203                .into_galley(
204                    ui,
205                    Some(TextWrapMode::Extend),
206                    f32::INFINITY,
207                    FontSelection::Default,
208                )
209                .size()
210        };
211        let row = measure(ui, self.sample.as_deref().unwrap_or("0"));
212        let sample_w = if self.sample.is_some() { row.x } else { 0.0 };
213        let text_w = value_text.as_deref().map_or(0.0, |s| measure(ui, s).x);
214        let height = row.y.max(self.size.y);
215        let width = sample_w.max(self.size.x).max(text_w).max(1.0);
216        let side = (height * 0.8).round().max(8.0);
217        let gap = t.space.s;
218        let total = vec2(width + gap + side, height);
219        let id = ui.scope_id().with(("late-value", &self.name, self.id_salt));
220        let name = self.name.clone();
221        let since = self.since;
222        let spinner = |label: String| {
223            let s = Spinner::new().size(side).name(label);
224            match since {
225                Some(at) => s.delayed(id, at, true),
226                None => s,
227            }
228        };
229        let mut retry = false;
230        let inner = ui.allocate_ui_with_layout(total, Layout::left_to_right(Align::Center), |ui| {
231            ui.set_min_size(total);
232            ui.spacing_mut().item_spacing.x = gap;
233            let room = vec2(width, height);
234            let in_room = |ui: &mut Ui, add: &mut dyn FnMut(&mut Ui)| {
235                ui.allocate_ui_with_layout(room, Layout::left_to_right(Align::Center), |ui| {
236                    ui.set_min_size(room);
237                    add(ui);
238                });
239            };
240            let slot = |ui: &mut Ui, busy: Option<String>| {
241                ui.allocate_ui_with_layout(
242                    vec2(side, height),
243                    Layout::left_to_right(Align::Center),
244                    |ui| {
245                        ui.set_min_size(vec2(side, height));
246                        if let Some(label) = busy {
247                            ui.add(spinner(label));
248                        }
249                    },
250                );
251            };
252            let tr = |key: &strings::StrKey| strings::tr_args(&ctx, key, &[("name", &name)]);
253            match &self.late {
254                Late::Pending => {
255                    let label = tr(&LATE_LOADING);
256                    in_room(ui, &mut |ui| match self.waiting {
257                        Waiting::Skeleton => {
258                            ui.add(Skeleton::text(1).width(width).label(label.clone()));
259                        }
260                        Waiting::Spinner => {
261                            ui.add(spinner(label.clone()));
262                        }
263                    });
264                    slot(ui, None);
265                }
266                Late::Fresh(v) => {
267                    let mut add = Some(add);
268                    in_room(ui, &mut |ui| {
269                        if let Some(add) = add.take() {
270                            add(ui, v);
271                        }
272                    });
273                    slot(ui, None);
274                }
275                Late::Refreshing(v) => {
276                    let mut add = Some(add);
277                    in_room(ui, &mut |ui| {
278                        if let Some(add) = add.take() {
279                            add(ui, v);
280                        }
281                    });
282                    slot(ui, Some(tr(&LATE_UPDATING)));
283                }
284                Late::Failed(error) => {
285                    let danger = t.status.danger;
286                    let (icon, _) = ui.allocate_exact_size(vec2(side, side), Sense::hover());
287                    if ui.is_rect_visible(icon) {
288                        Icon::Error.paint(ui.painter(), icon, danger);
289                    }
290                    ui.add(
291                        egui::Label::new(role_text(ui, self.role, error.as_str()).color(danger))
292                            .wrap_mode(TextWrapMode::Extend),
293                    );
294                    let button = ui.small_button(strings::tr(&ctx, &strings::RETRY));
295                    let retry_name = tr(&LATE_RETRY);
296                    ctx.accesskit_node_builder(button.id, |node| node.set_label(retry_name));
297                    retry = button.clicked();
298                }
299            }
300        });
301        let rect = inner.response.rect;
302        let response = ui.interact(rect, id, Sense::hover());
303        let enabled = ui.is_enabled();
304        response.widget_info(|| WidgetInfo::labeled(Role::Status, enabled, &self.name));
305        let value = match &self.late {
306            Late::Pending => Some(strings::tr(&ctx, &LOADING)),
307            Late::Fresh(_) | Late::Refreshing(_) => value_text,
308            Late::Failed(error) => Some(error.clone()),
309        };
310        let busy = self.late.is_busy();
311        if let (Some(at), false) = (since, busy) {
312            // The work ended: the delayed spinners' state lets go, so the
313            // next wait is delayed again.
314            let _ = crate::motion::Busy::new(id, at).visible(&ctx, false);
315        }
316        let label = self.name.clone();
317        ctx.accesskit_node_builder(response.id, |node| {
318            // A status, not a label: a label's name is its value, and here
319            // the name stays while the value says the state.
320            node.set_label(label);
321            match value {
322                Some(v) => node.set_value(v),
323                None => node.clear_value(),
324            }
325            if busy {
326                node.set_busy();
327            } else {
328                node.clear_busy();
329            }
330        });
331        LateResponse { response, retry }
332    }
333}
334
335impl<T: Display> LateValue<T> {
336    /// Draws the cell, the value as text in its role.
337    pub fn show(self, ui: &mut Ui) -> LateResponse {
338        let text = self.late.value().map(ToString::to_string);
339        let role = self.role;
340        let shown = text.clone();
341        self.cell(ui, text, move |ui, _| {
342            let text = shown.unwrap_or_default();
343            ui.add(egui::Label::new(role_text(ui, role, text)).wrap_mode(TextWrapMode::Extend));
344        })
345    }
346}