Skip to main content

egui_pop_core/
hover_card.rs

1//! Rich hover cards: the tier between a tooltip and a popover. A card
2//! opens after the hover delay on a widget, stays open while the pointer
3//! moves onto it (so its links can be clicked), and closes on leave
4//! after a short grace, on Escape or on a click elsewhere.
5//!
6//! <div class="warning">Experimental: may change in any release
7//! (docs/stability.md).</div>
8//!
9//! Its content is data ([`Card`]): formatted text (a small Markdown
10//! subset: `**bold**`, `` `code` ``, `- ` list lines), rows of key and
11//! value, progress, separators and command links. Being data, an agent
12//! reads it without hovering ([`Card::plain_text`], or the card
13//! serialised), and the same card is the widget's accessible
14//! description. Live values come for free: the owner builds the card
15//! each pass from its state.
16//!
17//! [`HoverCard::show`] draws it next to any widget (a status item, a
18//! toolbar button, a row, a port) and returns the link clicked, which
19//! the owner runs (an egui-pop `App` runs a command with its `when` and
20//! its steps, as anywhere else). [`open`] opens one from the keyboard:
21//! the focus then goes to its first link, and Tab moves through them.
22//!
23//! ```
24//! use egui_pop_core::hover_card::{Card, HoverCard};
25//! use egui_pop_model::ids::CommandId;
26//!
27//! fn vault(ui: &mut egui::Ui, images: u32) {
28//!     let r = ui.button("Vault");
29//!     let card = Card::new()
30//!         .text("**Vault** is open")
31//!         .row("Images", images.to_string())
32//!         .row("Last import", "07:12")
33//!         .separator()
34//!         .link("Show imports", CommandId::from_static("vault.imports"), serde_json::Value::Null);
35//!     if let Some(link) = HoverCard::new("vault").show(ui, &r, &card) {
36//!         let _ = link.command; // run it
37//!     }
38//! }
39//! ```
40
41use egui::text::LayoutJob;
42use egui::{Context, FontId, Id, Key, Modifiers, Response, Role, TextFormat, Ui};
43use egui_pop_model::ids::CommandId;
44use serde::Serialize;
45use serde_json::Value as Json;
46
47use crate::overlay::Closing;
48use crate::placement::{Placement, Side, place};
49
50/// What a card is called for the overlays' watcher ([`crate::overlay::watch`]).
51const LABEL: &str = "hover card";
52
53/// A link in a card: a command run with its arguments.
54#[derive(Clone, Debug, PartialEq, Serialize)]
55pub struct Link {
56    pub label: String,
57    pub command: CommandId,
58    #[serde(skip_serializing_if = "Json::is_null")]
59    pub args: Json,
60}
61
62/// One row of a card's key and value table.
63#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
64pub struct Row {
65    pub key: String,
66    pub value: String,
67}
68
69/// A part of a card, top to bottom.
70#[derive(Clone, Debug, PartialEq, Serialize)]
71#[serde(tag = "kind", rename_all = "snake_case")]
72pub enum Block {
73    /// Formatted text: `**bold**`, `` `code` ``, and lines starting with
74    /// `- ` as list items.
75    Text {
76        text: String,
77    },
78    /// A table of key and value.
79    Rows {
80        rows: Vec<Row>,
81    },
82    /// A progress line, determinate (0 to 1) or not.
83    Progress {
84        label: String,
85        #[serde(skip_serializing_if = "Option::is_none")]
86        fraction: Option<f32>,
87    },
88    Separator,
89    /// Command links, on one line.
90    Links {
91        links: Vec<Link>,
92    },
93}
94
95/// What a hover card shows.
96#[derive(Clone, Debug, Default, PartialEq, Serialize)]
97pub struct Card {
98    pub blocks: Vec<Block>,
99}
100
101impl Card {
102    pub fn new() -> Self {
103        Self::default()
104    }
105
106    /// Formatted text (`**bold**`, `` `code` ``, `- ` list lines).
107    pub fn text(mut self, text: impl Into<String>) -> Self {
108        self.blocks.push(Block::Text { text: text.into() });
109        self
110    }
111
112    /// A row of key and value; rows in a run make one table.
113    pub fn row(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
114        let row = Row {
115            key: key.into(),
116            value: value.into(),
117        };
118        match self.blocks.last_mut() {
119            Some(Block::Rows { rows }) => rows.push(row),
120            _ => self.blocks.push(Block::Rows { rows: vec![row] }),
121        }
122        self
123    }
124
125    /// A progress line (`None`: indeterminate).
126    pub fn progress(mut self, label: impl Into<String>, fraction: Option<f32>) -> Self {
127        self.blocks.push(Block::Progress {
128            label: label.into(),
129            fraction: fraction.map(|f| f.clamp(0.0, 1.0)),
130        });
131        self
132    }
133
134    pub fn separator(mut self) -> Self {
135        self.blocks.push(Block::Separator);
136        self
137    }
138
139    /// A command link; links in a run share a line.
140    pub fn link(mut self, label: impl Into<String>, command: CommandId, args: Json) -> Self {
141        let link = Link {
142            label: label.into(),
143            command,
144            args,
145        };
146        match self.blocks.last_mut() {
147            Some(Block::Links { links }) => links.push(link),
148            _ => self.blocks.push(Block::Links { links: vec![link] }),
149        }
150        self
151    }
152
153    pub fn is_empty(&self) -> bool {
154        self.blocks.is_empty()
155    }
156
157    /// Its links, in order.
158    pub fn links(&self) -> impl Iterator<Item = &Link> {
159        self.blocks.iter().flat_map(|b| match b {
160            Block::Links { links } => links.as_slice(),
161            _ => &[],
162        })
163    }
164
165    /// Its text without formatting, a line per line of text, row or
166    /// progress: the anchor's accessible description, and what an agent
167    /// reads. Links are left out (they are buttons of their own).
168    pub fn plain_text(&self) -> String {
169        let mut out: Vec<String> = Vec::new();
170        for b in &self.blocks {
171            match b {
172                Block::Text { text } => {
173                    for line in lines(text) {
174                        let s: String = line.spans.iter().map(Span::text).collect();
175                        out.push(if line.bullet { format!("• {s}") } else { s });
176                    }
177                }
178                Block::Rows { rows } => {
179                    out.extend(rows.iter().map(|r| format!("{}: {}", r.key, r.value)));
180                }
181                Block::Progress { label, fraction } => out.push(match fraction {
182                    Some(f) => format!("{label} {}%", (f * 100.0).round()),
183                    None => label.clone(),
184                }),
185                Block::Separator | Block::Links { .. } => {}
186            }
187        }
188        out.join("\n")
189    }
190}
191
192/// A run of text in a line, by style.
193#[derive(Clone, Debug, PartialEq, Eq)]
194pub enum Span {
195    Plain(String),
196    Bold(String),
197    Code(String),
198}
199
200impl Span {
201    pub fn text(&self) -> &str {
202        match self {
203            Span::Plain(s) | Span::Bold(s) | Span::Code(s) => s,
204        }
205    }
206}
207
208/// A line of formatted text.
209#[derive(Clone, Debug, PartialEq, Eq)]
210pub struct Line {
211    /// A list item (`- `).
212    pub bullet: bool,
213    pub spans: Vec<Span>,
214}
215
216/// Formatted text's lines: `- ` starts a list item, `**…**` is bold,
217/// `` `…` `` is code (no formatting inside); a mark left open is kept as
218/// text.
219pub fn lines(text: &str) -> Vec<Line> {
220    text.lines()
221        .map(|l| match l.strip_prefix("- ") {
222            Some(rest) => Line {
223                bullet: true,
224                spans: spans(rest),
225            },
226            None => Line {
227                bullet: false,
228                spans: spans(l),
229            },
230        })
231        .collect()
232}
233
234/// A line's spans.
235pub fn spans(text: &str) -> Vec<Span> {
236    let mut out = Vec::new();
237    let mut plain = String::new();
238    let mut rest = text;
239    while !rest.is_empty() {
240        let (mark, make): (&str, fn(String) -> Span) = if rest.starts_with("**") {
241            ("**", Span::Bold)
242        } else if rest.starts_with('`') {
243            ("`", Span::Code)
244        } else {
245            let c = rest.chars().next().unwrap_or_default();
246            plain.push(c);
247            rest = &rest[c.len_utf8()..];
248            continue;
249        };
250        let inner = &rest[mark.len()..];
251        match inner.find(mark) {
252            Some(end) if end > 0 => {
253                if !plain.is_empty() {
254                    out.push(Span::Plain(std::mem::take(&mut plain)));
255                }
256                out.push(make(inner[..end].to_string()));
257                rest = &inner[end + mark.len()..];
258            }
259            _ => {
260                plain.push_str(mark);
261                rest = inner;
262            }
263        }
264    }
265    if !plain.is_empty() {
266        out.push(Span::Plain(plain));
267    }
268    out
269}
270
271/// A card's state, between passes.
272#[derive(Clone, Copy, Debug, Default)]
273struct State {
274    open: bool,
275    /// Opened from the keyboard: stays until Escape or a click elsewhere.
276    by_key: bool,
277    /// The focus goes to the first link next pass.
278    focus: bool,
279    /// Since when the pointer rests on the anchor.
280    hover_since: Option<f64>,
281    /// Since when the pointer left both the anchor and the card.
282    left_at: Option<f64>,
283    /// Clicked: does not open again until the pointer leaves.
284    suppressed: bool,
285}
286
287fn load(ctx: &Context, id: Id) -> State {
288    ctx.data(|d| d.get_temp(id)).unwrap_or_default()
289}
290
291fn store(ctx: &Context, id: Id, s: State) {
292    ctx.data_mut(|d| d.insert_temp(id, s));
293}
294
295/// Opens a card from the keyboard (or for an agent): it stays open until
296/// Escape or a click elsewhere, and its first link takes the focus.
297pub fn open(ctx: &Context, id: Id) {
298    let mut s = load(ctx, id);
299    s.open = true;
300    s.by_key = true;
301    s.focus = true;
302    store(ctx, id, s);
303    ctx.request_repaint();
304}
305
306/// Closes a card.
307pub fn close(ctx: &Context, id: Id) {
308    let mut s = load(ctx, id);
309    s.open = false;
310    s.by_key = false;
311    s.left_at = None;
312    store(ctx, id, s);
313}
314
315/// Whether a card is open.
316pub fn is_open(ctx: &Context, id: Id) -> bool {
317    load(ctx, id).open
318}
319
320/// A hover card next to a widget.
321///
322/// Need (help): a hover card, a rich tooltip with rows and links.
323#[derive(Clone, Copy, Debug)]
324#[must_use = "show it with `show`"]
325pub struct HoverCard {
326    id: Id,
327    side: Side,
328}
329
330impl HoverCard {
331    pub fn new(id: impl std::hash::Hash + std::fmt::Debug) -> Self {
332        Self {
333            id: Id::unique(id),
334            side: Side::Bottom,
335        }
336    }
337
338    /// The card's id, for [`open`], [`close`] and [`is_open`].
339    pub fn id(&self) -> Id {
340        self.id
341    }
342
343    /// Which side of the widget it opens on (below by default; flipped
344    /// when there is no room).
345    pub fn side(mut self, side: Side) -> Self {
346        self.side = side;
347        self
348    }
349
350    /// Follows the pointer over `anchor`, draws the card while it is
351    /// open, and gives the widget the card's text as its accessible
352    /// description. Returns the link clicked, for the owner to run. An
353    /// empty card never opens.
354    pub fn show(self, ui: &Ui, anchor: &Response, card: &Card) -> Option<Link> {
355        let ctx = ui.ctx().clone();
356        let id = self.id;
357        let mut s = load(&ctx, id);
358        if card.is_empty() {
359            if s.open {
360                close(&ctx, id);
361            }
362            crate::overlay::follow_popup(&ctx, id, LABEL, false, Some(Closing::Owner));
363            return None;
364        }
365        let mut how = None;
366        let description = card.plain_text();
367        ctx.accesskit_node_builder(anchor.id, |node| node.set_description(description));
368        let now = ctx.input(|i| i.time);
369        let delay = f64::from(ui.style().interaction.tooltip_delay);
370        let grace = f64::from(ui.style().interaction.tooltip_grace_time.max(0.2));
371        let pointer = ctx.input(|i| i.pointer.hover_pos());
372        let card_rect = ctx.memory(|m| m.area_rect(id));
373        let on_anchor = anchor.contains_pointer();
374        let on_card = s.open
375            && card_rect
376                .zip(pointer)
377                .is_some_and(|(r, p)| r.expand(2.0).contains(p));
378        if anchor.clicked() {
379            how = Some(Closing::Owner);
380            s.open = false;
381            s.by_key = false;
382            s.suppressed = true;
383        }
384        if on_anchor {
385            s.left_at = None;
386            if !s.open && !s.suppressed {
387                let since = *s.hover_since.get_or_insert(now);
388                if now - since >= delay {
389                    s.open = true;
390                    s.by_key = false;
391                } else {
392                    ctx.request_repaint_after_secs((delay - (now - since)) as f32);
393                }
394            }
395        } else {
396            s.hover_since = None;
397            s.suppressed = false;
398        }
399        if s.open && !s.by_key {
400            if on_anchor || on_card {
401                s.left_at = None;
402            } else {
403                let left = *s.left_at.get_or_insert(now);
404                if now - left >= grace {
405                    how = Some(Closing::Outside);
406                    s.open = false;
407                    s.left_at = None;
408                } else {
409                    ctx.request_repaint_after_secs((grace - (now - left)) as f32);
410                }
411            }
412        }
413        if s.open && ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape)) {
414            how = Some(Closing::Escape);
415            s.open = false;
416            s.by_key = false;
417            // Back to the widget it hovers.
418            ctx.memory_mut(|m| m.request_focus(anchor.id));
419        }
420        if s.open && !on_card && !on_anchor && ctx.input(|i| i.pointer.any_pressed()) {
421            how = Some(Closing::Outside);
422            s.open = false;
423            s.by_key = false;
424        }
425        let mut clicked = None;
426        if s.open {
427            let screen = ctx.content_rect();
428            let size = card_rect.map_or(egui::vec2(ui.spacing().tooltip_width, 80.0), |r| r.size());
429            let placed = place(&Placement::new(anchor.rect, size, screen).side(self.side));
430            let focus = std::mem::take(&mut s.focus);
431            // An overlay (ADR 0026): over a lying-over panel it opens
432            // from, above a dialog or a menu it opens from.
433            crate::layers::rank_from(
434                &ctx,
435                egui::LayerId::new(egui::Order::Foreground, id),
436                crate::layers::Rank::Overlay,
437                anchor.layer_id,
438            );
439            egui::Area::new(id)
440                .order(egui::Order::Foreground)
441                .fixed_pos(placed.rect.min)
442                .show(&ctx, |ui| {
443                    let kit = crate::kit::Kit::of(ui.ctx());
444                    let shadow = ui.visuals().popup_shadow;
445                    kit.popover.show(ui, crate::kit::State::REST, shadow, |ui| {
446                        ui.set_max_width(ui.spacing().tooltip_width);
447                        clicked = paint(ui, card, focus);
448                    });
449                });
450        }
451        if clicked.is_some() {
452            how = Some(Closing::Chosen);
453            s.open = false;
454            s.by_key = false;
455        }
456        let open = s.open;
457        store(&ctx, id, s);
458        crate::overlay::follow_popup(&ctx, id, LABEL, open, how.or(Some(Closing::Owner)));
459        clicked
460    }
461}
462
463/// Draws a card's content; the link clicked. `focus` gives the first
464/// link the keyboard focus.
465pub fn paint(ui: &mut Ui, card: &Card, focus: bool) -> Option<Link> {
466    let t = crate::theme::Tokens::of(ui.ctx());
467    let mut clicked = None;
468    let mut first_link = focus;
469    for (k, b) in card.blocks.iter().enumerate() {
470        match b {
471            Block::Text { text } => {
472                for line in lines(text) {
473                    let mut job = LayoutJob::default();
474                    let plain = TextFormat {
475                        font_id: FontId::proportional(t.font.body),
476                        color: t.text.default,
477                        ..Default::default()
478                    };
479                    if line.bullet {
480                        job.append("• ", 0.0, plain.clone());
481                    }
482                    for span in &line.spans {
483                        let format = match span {
484                            Span::Plain(_) => plain.clone(),
485                            Span::Bold(_) => TextFormat {
486                                color: t.text.strong,
487                                ..plain.clone()
488                            },
489                            Span::Code(_) => TextFormat {
490                                font_id: FontId::monospace(t.font.mono),
491                                background: ui.visuals().code_bg_color,
492                                ..plain.clone()
493                            },
494                        };
495                        job.append(span.text(), 0.0, format);
496                    }
497                    job.wrap.max_width = ui.available_width();
498                    ui.label(job);
499                }
500            }
501            Block::Rows { rows } => {
502                egui::Grid::new(("egui_pop_hover_card_rows", k))
503                    .num_columns(2)
504                    .spacing(egui::vec2(t.space.m, t.space.xs))
505                    .show(ui, |ui| {
506                        for r in rows {
507                            ui.label(egui::RichText::new(&r.key).color(t.text.muted));
508                            ui.label(&r.value);
509                            ui.end_row();
510                        }
511                    });
512            }
513            Block::Progress { label, fraction } => {
514                ui.add(
515                    crate::progress::ProgressBar::new(*fraction)
516                        .label(label.clone())
517                        .line(),
518                );
519                let text = match fraction {
520                    Some(f) => format!("{label} {}%", (f * 100.0).round()),
521                    None => label.clone(),
522                };
523                ui.label(egui::RichText::new(text).small().color(t.text.muted));
524            }
525            Block::Separator => {
526                ui.separator();
527            }
528            Block::Links { links } => {
529                ui.horizontal_wrapped(|ui| {
530                    for l in links {
531                        let r = ui.link(&l.label);
532                        crate::a11y::name(&r, Role::Button, &l.label);
533                        if std::mem::take(&mut first_link) {
534                            r.request_focus();
535                        }
536                        if r.clicked() {
537                            clicked = Some(l.clone());
538                        }
539                    }
540                });
541            }
542        }
543    }
544    clicked
545}
546
547#[cfg(test)]
548mod tests {
549    use super::*;
550
551    #[test]
552    fn the_markdown_subset_gives_bold_code_and_list_items() {
553        assert_eq!(
554            spans("a **b** `c` d"),
555            vec![
556                Span::Plain("a ".into()),
557                Span::Bold("b".into()),
558                Span::Plain(" ".into()),
559                Span::Code("c".into()),
560                Span::Plain(" d".into()),
561            ]
562        );
563        // No formatting inside code; a mark left open stays text.
564        assert_eq!(spans("`**x**`"), vec![Span::Code("**x**".into())]);
565        assert_eq!(spans("2 ** 3"), vec![Span::Plain("2 ** 3".into())]);
566        assert_eq!(spans("****"), vec![Span::Plain("****".into())]);
567        let l = lines("Title\n- one\n- **two**");
568        assert!(!l[0].bullet);
569        assert!(l[1].bullet && l[2].bullet);
570        assert_eq!(l[2].spans, vec![Span::Bold("two".into())]);
571    }
572
573    #[test]
574    fn a_card_reads_as_plain_text_without_its_links() {
575        let card = Card::new()
576            .text("**Vault** open\n- `raw` files")
577            .row("Images", "1,204")
578            .row("Stacks", "3")
579            .progress("Import", Some(0.5))
580            .separator()
581            .link("Open", CommandId::from_static("vault.open"), Json::Null)
582            .link("Close", CommandId::from_static("vault.close"), Json::Null);
583        // Rows and links in a run are one block.
584        assert_eq!(card.blocks.len(), 5);
585        assert_eq!(card.links().count(), 2);
586        assert_eq!(
587            card.plain_text(),
588            "Vault open\n• raw files\nImages: 1,204\nStacks: 3\nImport 50%"
589        );
590        let json = serde_json::to_value(&card).unwrap();
591        assert_eq!(json["blocks"][0]["kind"], "text");
592        assert_eq!(json["blocks"][4]["links"][0]["command"], "vault.open");
593    }
594}