Skip to main content

egui_pop_api/
notices.rs

1//! Notices shown where they happened (`docs/notices.md`).
2//!
3//! A page or a panel draws a notice site for its place
4//! ([`notice_site`]): while it is drawn, the routing policy may send a
5//! notice of that place there (by default, the user's own errors and
6//! warnings: [`Surface::Inline`]), and the site draws each as a
7//! [`Note`], selectable, with Copy and a close
8//! button. Raising, routing and reading notices are on
9//! [`AppHandle`]: [`AppHandle::report`], [`AppHandle::route_notices`],
10//! [`AppHandle::notice_badge`], [`AppHandle::run_reported`].
11//!
12//! <div class="warning">Experimental: may change in any release
13//! (docs/stability.md).</div>
14
15use egui::Ui;
16use egui_pop_core::a11y;
17use egui_pop_core::icon::{Icon, Size};
18use egui_pop_core::indicator::{Anchor, Indicator, IndicatorExt as _, Tone};
19use egui_pop_core::note::Note;
20use egui_pop_core::state::Slot;
21use egui_pop_core::strings;
22use egui_pop_model::ids::{BlockId, CommandId, PanelId, PluginId};
23use egui_pop_model::panels::{Area, PanelSpec};
24
25pub use crate::bus::NoticeBadge;
26pub use egui_pop_model::commands::CommandError;
27pub use egui_pop_model::notice::route::{
28    DefaultRouting, NoticeRouting, Route, RouteCx, Surface, default_route,
29};
30
31use crate::app::AppHandle;
32use crate::strings as txt;
33use crate::zones::{self, Block};
34use crate::{Ctx, Plugin, PluginError};
35
36/// How many notices a site shows at once, the newest.
37pub const SITE_SHOWN: usize = 3;
38
39/// Draws the notice site of `place` (a page, a panel: `settings/storage/
40/// nodes`): registers it, so the routing policy may send it the notices
41/// of that place while it is drawn, and draws the notices routed to it
42/// that were not put away (nor resolved, for a condition), the newest
43/// [`SITE_SHOWN`], newest first. A notice drawn is marked seen; its close
44/// button puts it away (`pop.notice.dismissed`); its actions that name a
45/// command run it.
46///
47/// <div class="warning">Experimental: may change in any release
48/// (docs/stability.md).</div>
49pub fn notice_site(ui: &mut Ui, app: &AppHandle, place: &str) {
50    let ctx = ui.ctx().clone();
51    let hub = &app.0.bus.notices;
52    hub.site_drawn(place, ctx.viewport_id(), ctx.cumulative_pass_nr());
53    let kept: Vec<_> = hub
54        .at(place)
55        .into_iter()
56        .filter(|k| !k.resolved)
57        .rev()
58        .take(SITE_SHOWN)
59        .collect();
60    for k in kept {
61        let n = &k.notice;
62        if !k.seen {
63            app.see_notice(n.id.clone());
64        }
65        let mut close = false;
66        let r = Note::from_notice(n).show_with(ui, |ui| {
67            let name = strings::tr_args(&ctx, &txt::NOTICE_CLOSE, &[("text", &n.headline)]);
68            close = ui
69                .add(Icon::Close.size(Size::Inline).label(&name).sense_click())
70                .clicked();
71        });
72        if let Some(a) = r.action.and_then(|i| n.actions.get(i))
73            && let Ok(command) = CommandId::new(&a.id)
74        {
75            app.run(command, a.args.clone());
76        }
77        if close {
78            app.dismiss_notice(n.id.clone());
79        }
80    }
81}
82
83mod view;
84
85pub use view::{Filter, copy_all_text, listed};
86
87/// The plugin's id.
88pub const PLUGIN: PluginId = PluginId::from_static("egui_pop.notices");
89
90/// The Notices panel: the history of notices, newest first.
91pub const PANEL_NOTICES: PanelId = PanelId::from_static("egui_pop.notices");
92
93/// The status bar's bell.
94pub const BELL: BlockId = BlockId::from_static("egui_pop.notices.bell");
95
96/// The bell's count last drawn, to announce it when it rises.
97const BELL_COUNT: Slot<usize> = Slot::new("egui_pop.notices.bell_count");
98
99/// The history of notices in view: the status bar's bell, counting the
100/// errors and warnings not seen yet ([`AppHandle::notice_badge`]), and
101/// the Notices panel ([`PANEL_NOTICES`], closed until the bell or the
102/// application opens it) listing every notice kept, with its filters,
103/// Copy all, Mark all seen, Clear seen and each notice's details.
104///
105/// <div class="warning">Experimental: may change in any release
106/// (docs/stability.md).</div>
107#[derive(Clone, Debug)]
108pub struct NoticesPlugin {
109    bell: bool,
110    panel: bool,
111}
112
113impl Default for NoticesPlugin {
114    fn default() -> Self {
115        Self {
116            bell: true,
117            panel: true,
118        }
119    }
120}
121
122impl NoticesPlugin {
123    /// Without the status bar's bell (an application drawing [`bell`]
124    /// where it wants).
125    pub fn without_bell(mut self) -> Self {
126        self.bell = false;
127        self
128    }
129
130    /// Without the panel (an application drawing [`panel`] where it
131    /// wants); the bell then opens nothing.
132    pub fn without_panel(mut self) -> Self {
133        self.panel = false;
134        self
135    }
136}
137
138impl Plugin for NoticesPlugin {
139    fn id(&self) -> PluginId {
140        PLUGIN
141    }
142
143    fn title(&self) -> String {
144        "Notices".into()
145    }
146
147    fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
148        if self.bell {
149            ctx.block(zones::STATUS_BAR, Block::add(BELL, 1100, bell));
150        }
151        if self.panel {
152            ctx.panel(
153                PanelSpec::new(PANEL_NOTICES, "Notices", Area::Bottom)
154                    .min_size(120.0)
155                    .default_size(260.0)
156                    .icon("notification")
157                    .closed(),
158                panel,
159            )?;
160        }
161        Ok(())
162    }
163}
164
165/// The bell's tooltip: "3 errors, 1 warning not yet seen", or that
166/// nothing is new.
167pub fn bell_text(ctx: &egui::Context, badge: &NoticeBadge) -> String {
168    let count = |n: usize, one: &strings::StrKey, many: &strings::StrKey| match n {
169        0 => None,
170        1 => Some(strings::tr(ctx, one)),
171        n => Some(strings::tr_with(ctx, many, &[("count", n.into())])),
172    };
173    let parts: Vec<String> = [
174        count(badge.errors, &txt::NOTICES_ERRORS_ONE, &txt::NOTICES_ERRORS),
175        count(
176            badge.warnings,
177            &txt::NOTICES_WARNINGS_ONE,
178            &txt::NOTICES_WARNINGS,
179        ),
180    ]
181    .into_iter()
182    .flatten()
183    .collect();
184    if parts.is_empty() {
185        return strings::tr(ctx, &txt::NOTICES_NONE_UNSEEN);
186    }
187    strings::tr_args(ctx, &txt::NOTICES_UNSEEN, &[("counts", &parts.join(", "))])
188}
189
190/// The status bar's bell: the notification symbol, a count of the errors
191/// and warnings not seen yet coloured by the worst, a tooltip saying
192/// them. A click opens the Notices panel, or gives it the keyboard. For
193/// screen readers, a button named "Notices" with its count, announced
194/// politely when it rises.
195///
196/// <div class="warning">Experimental: may change in any release
197/// (docs/stability.md).</div>
198pub fn bell(ui: &mut Ui, app: &AppHandle) {
199    let ctx = ui.ctx().clone();
200    let badge = app.notice_badge();
201    let count = badge.errors + badge.warnings;
202    let tip = bell_text(&ctx, &badge);
203    if count > BELL_COUNT.get(&ctx).unwrap_or(0) {
204        a11y::announce(&ctx, tip.clone(), a11y::Politeness::Polite);
205    }
206    BELL_COUNT.set(&ctx, count);
207    let tone = if badge.errors > 0 {
208        Tone::Danger
209    } else {
210        Tone::Warning
211    };
212    let name = strings::tr(&ctx, &txt::NOTICES_TITLE);
213    let r = ui
214        .add(Icon::Notification.label(&name).sense_click())
215        .with_indicator(
216            ui,
217            Indicator::count(count as u64).tone(tone).id("notices.bell"),
218            Anchor::TopEnd,
219        )
220        .on_hover_text(&tip);
221    if r.clicked() && app.panels().iter().any(|p| p.id == PANEL_NOTICES) {
222        app.focus_panel(&PANEL_NOTICES);
223    }
224}
225
226/// Draws the Notices panel's content (the panel [`PANEL_NOTICES`] calls
227/// it; an application may draw it anywhere): its filters and actions,
228/// then the notices kept, unresolved first, newest first; a click on a
229/// row shows its notice in full. The notices it lists are marked seen.
230///
231/// <div class="warning">Experimental: may change in any release
232/// (docs/stability.md).</div>
233pub fn panel(ui: &mut Ui, app: &AppHandle) {
234    view::show(ui, app, true);
235}
236
237/// Draws the Notices panel's content as [`panel`] does, without marking
238/// the notices it lists seen: a preview (a gallery, a help page) that
239/// leaves the bell's count as it is.
240///
241/// <div class="warning">Experimental: may change in any release
242/// (docs/stability.md).</div>
243pub fn panel_preview(ui: &mut Ui, app: &AppHandle) {
244    view::show(ui, app, false);
245}