brep_app/panels/toasts.rs
1//! Transient toast notifications — a small overlay for engine notices (e.g. a
2//! sketch solve that failed after an edit). The engine only QUEUES notices
3//! ([`brep_render::engine_state::EngineState::take_notices`]); this drains them
4//! and shows each as an auto-expiring card anchored bottom-center. Time comes
5//! from egui (`ctx.input().time`) — never `std::time::Instant`, which aborts on
6//! wasm.
7
8use eframe::egui;
9
10/// Seconds a toast stays on screen before it fades out of the list.
11const TTL: f64 = 6.0;
12/// Most toasts kept on screen at once (older ones drop off the top).
13const MAX_ON_SCREEN: usize = 6;
14
15/// A queue of transient messages, each stamped with its egui birth time.
16#[derive(Default)]
17pub struct Toasts {
18 items: Vec<(String, f64)>,
19}
20
21impl Toasts {
22 pub fn new() -> Self {
23 Self::default()
24 }
25
26 /// Queue `messages` (drained from the engine this frame), stamped with `now`
27 /// (`ctx.input().time`).
28 pub fn extend(&mut self, messages: impl IntoIterator<Item = String>, now: f64) {
29 for message in messages {
30 self.items.push((message, now));
31 }
32 let overflow = self.items.len().saturating_sub(MAX_ON_SCREEN);
33 if overflow > 0 {
34 self.items.drain(0..overflow);
35 }
36 }
37
38 /// The queued toast texts, oldest first, as a JSON array — the
39 /// `__brepNotices` global the headed verifier reads to see a refusal the
40 /// app only ever shows as a transient card.
41 pub fn texts_json(&self) -> String {
42 serde_json::Value::Array(
43 self.items
44 .iter()
45 .map(|(text, _)| serde_json::Value::String(text.clone()))
46 .collect(),
47 )
48 .to_string()
49 }
50
51 /// Draw the unexpired toasts. Call once per frame at ctx level (after the
52 /// panels, so the cards float over the shell).
53 pub fn show(&mut self, ctx: &egui::Context) {
54 let now = ctx.input(|i| i.time);
55 self.items.retain(|(_, born)| now - born < TTL);
56 if self.items.is_empty() {
57 return;
58 }
59 // Keep the frame loop alive so a toast expires on time without new input.
60 ctx.request_repaint();
61
62 egui::Area::new(egui::Id::new("brep-toasts"))
63 .anchor(egui::Align2::CENTER_BOTTOM, egui::vec2(0.0, -28.0))
64 .order(egui::Order::Foreground)
65 .interactable(false)
66 .show(ctx, |ui| {
67 for (message, _) in &self.items {
68 egui::Frame::popup(ui.style())
69 .fill(egui::Color32::from_rgb(0x3a, 0x24, 0x24))
70 .stroke(egui::Stroke::new(
71 1.0,
72 egui::Color32::from_rgb(0xff, 0x6b, 0x6b),
73 ))
74 .show(ui, |ui| {
75 ui.set_max_width(460.0);
76 ui.label(
77 egui::RichText::new(message)
78 .color(egui::Color32::from_rgb(0xff, 0x9b, 0x9b)),
79 );
80 });
81 ui.add_space(6.0);
82 }
83 });
84 }
85}