1use 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#[derive(Clone, Debug, PartialEq, Eq)]
53pub enum Late<T> {
54 Pending,
56 Fresh(T),
58 Refreshing(T),
60 Failed(String),
62}
63
64impl<T> Late<T> {
65 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 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 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
100pub enum Waiting {
101 #[default]
103 Skeleton,
104 Spinner,
107}
108
109#[derive(Debug)]
111pub struct LateResponse {
112 pub response: Response,
114 pub retry: bool,
116}
117
118#[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 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 pub fn sample(mut self, text: impl Into<String>) -> Self {
150 self.sample = Some(text.into());
151 self
152 }
153
154 pub fn size(mut self, size: Vec2) -> Self {
157 self.size = size;
158 self
159 }
160
161 pub fn role(mut self, role: TextRole) -> Self {
164 self.role = role;
165 self
166 }
167
168 pub fn waiting(mut self, waiting: Waiting) -> Self {
170 self.waiting = waiting;
171 self
172 }
173
174 pub fn since(mut self, seconds: f64) -> Self {
178 self.since = Some(seconds);
179 self
180 }
181
182 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 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 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 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 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}