Skip to main content

egui_pop_api/tips/
screen.rs

1//! The card a tip shows by itself: beside the element it is about (its
2//! target, named where it is drawn), never covering it, with a halo
3//! around the element; in the bottom corner at the start without one.
4//! It never takes the focus and is never modal.
5
6use std::collections::BTreeMap;
7
8use egui::{Color32, Context, Id, LayerId, Order, Rect, Response, Stroke, StrokeKind, Ui};
9use egui_pop_core::icon::{Icon, Size};
10use egui_pop_core::kit::Kit;
11use egui_pop_core::placement::{Placement, Side, place};
12use egui_pop_core::strings;
13use egui_pop_core::theme::Tokens;
14use serde_json::{Value as Json, json};
15
16use super::{TIPS, Tip, Tips, card_in};
17use crate::app::AppHandle;
18use crate::strings as txt;
19
20/// The targets drawn, by name: the pass each was drawn in and where.
21#[derive(Clone, Default)]
22struct Targets(BTreeMap<String, (u64, Rect)>);
23
24fn targets_id() -> Id {
25    Id::unique("egui_pop.tips.targets")
26}
27
28fn card_id() -> Id {
29    Id::unique("egui_pop.tips.card")
30}
31
32/// Names a rectangle a tip may point at (a tip's `target`): call it each
33/// pass the element is drawn. Names are stable ids
34/// (`photos.rating`, `param:exposure`).
35pub fn target(ctx: &Context, name: &str, rect: Rect) {
36    let pass = ctx.cumulative_pass_nr();
37    ctx.data_mut(|d| {
38        d.get_temp_mut_or_default::<Targets>(targets_id())
39            .0
40            .insert(name.to_string(), (pass, rect));
41    });
42}
43
44/// Names a widget a tip may point at; returns the response.
45pub fn mark(response: Response, name: &str) -> Response {
46    target(&response.ctx, name, response.rect);
47    response
48}
49
50/// Where a target is, when it was drawn in this pass or the last.
51pub fn target_rect(ctx: &Context, name: &str) -> Option<Rect> {
52    let pass = ctx.cumulative_pass_nr();
53    ctx.data(|d| {
54        d.get_temp::<Targets>(targets_id())
55            .and_then(|t| t.0.get(name).copied())
56    })
57    .filter(|(p, _)| p + 1 >= pass)
58    .map(|(_, r)| r)
59}
60
61/// Every target named so far in this session (for the lint).
62pub fn targets_seen(ctx: &Context) -> Vec<String> {
63    ctx.data(|d| {
64        d.get_temp::<Targets>(targets_id())
65            .map(|t| t.0.keys().cloned().collect())
66            .unwrap_or_default()
67    })
68}
69
70/// The halo's colour: the theme's `tip-card.halo-color` when it has one,
71/// else the information status colour (the card's icon's).
72pub fn halo_color(t: &Tokens) -> Color32 {
73    t.color("tip-card.halo-color").unwrap_or(t.status.info)
74}
75
76/// Draws a halo around a target, over the interface and under the card.
77fn halo(ctx: &Context, t: &Tokens, rect: Rect) {
78    let color = halo_color(t);
79    let layer = LayerId::new(Order::Foreground, Id::unique("egui_pop.tips.halo"));
80    // At the card's rank, drawn before it: under it.
81    egui_pop_core::layers::rank(ctx, layer, egui_pop_core::layers::Rank::Overlay);
82    let painter = ctx.layer_painter(layer);
83    let r = rect.expand(t.space.s);
84    let radius = t.radius.widget + t.space.s;
85    painter.rect_stroke(
86        r.expand(t.space.s),
87        radius + t.space.s,
88        Stroke::new(t.space.s, color.gamma_multiply(0.35)),
89        StrokeKind::Middle,
90    );
91    painter.rect_stroke(
92        r,
93        radius,
94        Stroke::new(t.space.xs, color),
95        StrokeKind::Middle,
96    );
97}
98
99/// The card's width: the theme's `tip-card.width`, else a toast's.
100fn width(ctx: &Context, t: &Tokens) -> f32 {
101    t.resolved()
102        .dimension("tip-card.width")
103        .unwrap_or_else(|| Kit::of(ctx).toast.data.width)
104}
105
106/// Space between a target and the card.
107fn gap(t: &Tokens) -> f32 {
108    t.space.xl + t.space.m
109}
110
111/// Where the card goes, `size` big, in `bounds`: beside its target
112/// (after it, else where there is room), or at the bottom start.
113fn card_rect(anchor: Option<Rect>, size: egui::Vec2, bounds: Rect, gap: f32) -> Rect {
114    match anchor {
115        Some(a) => place(&Placement::new(a, size, bounds).side(Side::End).gap(gap)).rect,
116        None => Rect::from_min_size(egui::pos2(bounds.left(), bounds.bottom() - size.y), size),
117    }
118}
119
120/// The tip shown, for agents: its fields and where its card and target
121/// are.
122pub(super) fn describe(app: &AppHandle, tip: &Tip) -> Json {
123    let ctx = app.egui();
124    let rect = |r: Rect| json!([r.min.x, r.min.y, r.max.x, r.max.y]);
125    let card = ctx.memory(|m| m.area_rect(card_id()));
126    let target = tip.target.as_deref().and_then(|n| target_rect(&ctx, n));
127    json!({
128        "id": tip.id,
129        "title": tip.title,
130        "text": tip.text_shown(&ctx, app),
131        "target": tip.target,
132        "origin": tip.origin_name(),
133        "card": card.map(rect),
134        "targetRect": target.map(rect),
135    })
136}
137
138/// Draws the card of the tip shown, in the active window.
139pub(super) fn show(ui: &mut Ui, app: &AppHandle) {
140    let Some(tips) = app.service(&TIPS) else {
141        return;
142    };
143    let ctx = ui.ctx().clone();
144    if app.active_window() != ctx.viewport_id() {
145        return;
146    }
147    let Some(tip) = tips.current() else {
148        return;
149    };
150    if !tips.enabled(app) {
151        tips.not_now(app);
152        return;
153    }
154    show_card(&ctx, app, &tips, &tip);
155}
156
157fn show_card(ctx: &Context, app: &AppHandle, tips: &Tips, tip: &Tip) {
158    let t = Tokens::of(ctx);
159    let w = width(ctx, &t);
160    let bounds = ctx.content_rect().shrink(t.space.l);
161    let anchor = tip.target.as_deref().and_then(|n| target_rect(ctx, n));
162    let size = ctx
163        .memory(|m| m.area_rect(card_id()))
164        .map_or(egui::vec2(w, w / 3.0), |r| r.size());
165    let at = card_rect(anchor, size, bounds, gap(&t));
166    if let Some(a) = anchor {
167        halo(ctx, &t, a);
168    }
169    let heading = strings::tr(ctx, &txt::TIPS_DID_YOU_KNOW);
170    let title = tip.title_in(ctx);
171    let text = tip.text_shown(ctx, app);
172    // Over the lying-over panels, under menus and dialogs (ADR 0026).
173    egui_pop_core::layers::rank(
174        ctx,
175        LayerId::new(Order::Foreground, card_id()),
176        egui_pop_core::layers::Rank::Overlay,
177    );
178    egui::Area::new(card_id())
179        .order(Order::Foreground)
180        .fixed_pos(at.min)
181        .interactable(true)
182        .show(ctx, |ui| {
183            ui.set_max_width(w);
184            let shadow = t.shadow.popup;
185            card_in(
186                ui,
187                app,
188                shadow,
189                &heading,
190                &title,
191                &text,
192                Some(|ui: &mut Ui| {
193                    let label = strings::tr(ui.ctx(), &txt::TIPS_NOT_NOW);
194                    // A button: an icon with only a label senses hover,
195                    // and a click on it does nothing.
196                    let cross = Icon::Close.size(Size::Inline).label(&label);
197                    if ui.add(cross.sense_click()).clicked() {
198                        tips.not_now(app);
199                    }
200                }),
201                |ui| {
202                    let got = strings::tr(ui.ctx(), &txt::TIPS_GOT_IT);
203                    let name =
204                        strings::tr_args(ui.ctx(), &txt::TIPS_GOT_IT_NAME, &[("tip", &title)]);
205                    let r = ui.button(&got);
206                    egui_pop_core::a11y::name(&r, egui::Role::Button, &name);
207                    if r.clicked()
208                        && let Err(e) = tips.got_it(app)
209                    {
210                        log::warn!("tips: {e}");
211                    }
212                    if ui.button(strings::tr(ui.ctx(), &txt::TIPS_NEXT)).clicked() {
213                        tips.show_next(app);
214                    }
215                    if ui
216                        .button(strings::tr(ui.ctx(), &txt::TIPS_NO_MORE))
217                        .clicked()
218                        && let Err(e) = tips.turn_off(app)
219                    {
220                        log::warn!("tips: {e}");
221                    }
222                },
223            );
224        });
225}
226
227#[cfg(test)]
228mod tests {
229    use super::*;
230    use egui::{pos2, vec2};
231
232    #[test]
233    fn the_card_goes_beside_its_target_without_covering_it() {
234        let bounds = Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0));
235        let size = vec2(300.0, 120.0);
236        let target = Rect::from_min_size(pos2(100.0, 100.0), vec2(80.0, 24.0));
237        let r = card_rect(Some(target), size, bounds, 24.0);
238        assert!(!r.intersects(target));
239        assert_eq!(r.left(), target.right() + 24.0);
240        // At the end of the window: on the other side.
241        let target = Rect::from_min_size(pos2(700.0, 100.0), vec2(80.0, 24.0));
242        let r = card_rect(Some(target), size, bounds, 24.0);
243        assert!(!r.intersects(target));
244        assert!(bounds.contains_rect(r));
245        // Without a target: the bottom corner at the start.
246        let r = card_rect(None, size, bounds, 24.0);
247        assert_eq!(r.left_bottom(), bounds.left_bottom());
248    }
249}