egui_pop_model/notice/route.rs
1//! Routing: which views show a notice.
2//!
3//! egui-pop gives the mechanism, the application the policy. A policy
4//! ([`NoticeRouting`]) is given each notice raised and answers a
5//! [`Route`]: the [`Surface`]s that show it (inline at its place, a
6//! toast, the status bar's badge, the history, the Decisions surface).
7//! [`default_route`] is egui-pop's own policy, the table below; an
8//! application installs its own in its place.
9//!
10//! | Notice | Surfaces |
11//! |---|---|
12//! | an ask (any origin) | Decisions, history |
13//! | a condition (any origin) | inline at its place when a site shows it, history; badge when a warning or an error |
14//! | a user's error or warning | inline at its place when a site shows it, else a toast; history |
15//! | a user's information or success | toast, history |
16//! | a background, node or system error or warning | badge, history (never a toast) |
17//! | a background, node or system information or success | history |
18//!
19//! ```
20//! use egui_pop_model::notice::Notice;
21//! use egui_pop_model::notice::route::{RouteCx, Surface, default_route};
22//!
23//! let cx = RouteCx::new(["settings/storage/nodes"]);
24//! let failed = Notice::error("cloudy was not added").place("settings/storage/nodes");
25//! assert_eq!(
26//! default_route(&failed, &cx).surfaces,
27//! [Surface::Inline("settings/storage/nodes".into()), Surface::History]
28//! );
29//! ```
30//!
31//! <div class="warning">Experimental: may change in any release
32//! (docs/stability.md).</div>
33
34use std::collections::BTreeSet;
35
36use serde::{Deserialize, Serialize};
37
38use super::{Kind, Notice, Origin, Severity};
39
40/// A view that shows a notice.
41#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
42#[serde(rename_all = "snake_case", tag = "surface", content = "place")]
43#[non_exhaustive]
44pub enum Surface {
45 /// A note inside the page or panel that registered this place (a
46 /// notice site).
47 Inline(String),
48 /// A toast: transient for information, success and warnings, until
49 /// closed for errors.
50 Toast,
51 /// The status bar's badge: counted until seen (or resolved).
52 StatusBadge,
53 /// The history of notices.
54 History,
55 /// The Decisions surface: a question for the user, which the
56 /// application's panel shows.
57 Decisions,
58}
59
60/// The surfaces a policy picked for one notice, in order.
61#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
62#[non_exhaustive]
63#[must_use]
64pub struct Route {
65 pub surfaces: Vec<Surface>,
66}
67
68impl Route {
69 /// No surface: the notice is kept, shown nowhere.
70 pub fn none() -> Self {
71 Self::default()
72 }
73
74 /// Adds a surface (once).
75 pub fn with(mut self, surface: Surface) -> Self {
76 if !self.surfaces.contains(&surface) {
77 self.surfaces.push(surface);
78 }
79 self
80 }
81
82 /// Inline at `place`.
83 pub fn inline(self, place: impl Into<String>) -> Self {
84 self.with(Surface::Inline(place.into()))
85 }
86
87 pub fn toast(self) -> Self {
88 self.with(Surface::Toast)
89 }
90
91 pub fn badge(self) -> Self {
92 self.with(Surface::StatusBadge)
93 }
94
95 pub fn history(self) -> Self {
96 self.with(Surface::History)
97 }
98
99 pub fn decisions(self) -> Self {
100 self.with(Surface::Decisions)
101 }
102
103 pub fn has(&self, surface: &Surface) -> bool {
104 self.surfaces.contains(surface)
105 }
106
107 /// The place it shows inline at, if it does.
108 pub fn inline_place(&self) -> Option<&str> {
109 self.surfaces.iter().find_map(|s| match s {
110 Surface::Inline(p) => Some(p.as_str()),
111 _ => None,
112 })
113 }
114}
115
116impl FromIterator<Surface> for Route {
117 fn from_iter<T: IntoIterator<Item = Surface>>(iter: T) -> Self {
118 iter.into_iter().fold(Route::none(), Route::with)
119 }
120}
121
122/// What a policy knows besides the notice: the places a notice site
123/// shows now.
124#[derive(Clone, Debug, Default, PartialEq, Eq)]
125#[non_exhaustive]
126pub struct RouteCx {
127 pub sites: BTreeSet<String>,
128}
129
130impl RouteCx {
131 pub fn new<S: Into<String>>(sites: impl IntoIterator<Item = S>) -> Self {
132 Self {
133 sites: sites.into_iter().map(Into::into).collect(),
134 }
135 }
136
137 /// Whether a notice site shows `place` now.
138 pub fn has_site(&self, place: &str) -> bool {
139 self.sites.contains(place)
140 }
141
142 /// The notice's place, when a site shows it now.
143 pub fn site_of<'n>(&self, notice: &'n Notice) -> Option<&'n str> {
144 notice.place.as_deref().filter(|p| self.has_site(p))
145 }
146}
147
148/// An application's routing policy. A closure
149/// `Fn(&Notice, &RouteCx) -> Route` is one.
150///
151/// It is asked on the thread that raised the notice: it must be quick and
152/// must not raise notices itself.
153pub trait NoticeRouting: Send + Sync {
154 /// The surfaces that show `notice`.
155 fn route(&self, notice: &Notice, cx: &RouteCx) -> Route;
156
157 /// Hands a notice routed to [`Surface::Decisions`] to the
158 /// application's Decisions surface. egui-pop has none: by default it
159 /// is only kept (and in the history when routed there).
160 fn ask(&self, notice: &Notice) {
161 let _ = notice;
162 }
163}
164
165impl<F> NoticeRouting for F
166where
167 F: Fn(&Notice, &RouteCx) -> Route + Send + Sync,
168{
169 fn route(&self, notice: &Notice, cx: &RouteCx) -> Route {
170 self(notice, cx)
171 }
172}
173
174/// egui-pop's own policy: [`default_route`].
175#[derive(Clone, Copy, Debug, Default)]
176pub struct DefaultRouting;
177
178impl NoticeRouting for DefaultRouting {
179 fn route(&self, notice: &Notice, cx: &RouteCx) -> Route {
180 default_route(notice, cx)
181 }
182}
183
184/// egui-pop's default routing table (the [module](self)'s): background
185/// work never pops up, a user's own failure shows where it happened.
186pub fn default_route(notice: &Notice, cx: &RouteCx) -> Route {
187 let serious = matches!(notice.severity, Severity::Warning | Severity::Error);
188 let site = cx.site_of(notice);
189 match notice.kind {
190 Kind::Ask => Route::none().decisions().history(),
191 Kind::Condition => {
192 let mut r = Route::none();
193 if let Some(p) = site {
194 r = r.inline(p);
195 }
196 r = r.history();
197 if serious { r.badge() } else { r }
198 }
199 Kind::Event => match (notice.origin, serious) {
200 (Origin::User, true) => match site {
201 Some(p) => Route::none().inline(p).history(),
202 None => Route::none().toast().history(),
203 },
204 (Origin::User, false) => Route::none().toast().history(),
205 (_, true) => Route::none().badge().history(),
206 (_, false) => Route::none().history(),
207 },
208 }
209}