Skip to main content

agg_gui/widgets/
hyperlink.rs

1//! `Hyperlink` — a clickable label rendered in link style (blue, underlined).
2//!
3//! Unlike a full URL-opening widget, `Hyperlink` fires a plain `on_click`
4//! callback so callers can open URLs via whatever platform mechanism is
5//! available (`web_sys::window().open()` on WASM, `open::open()` on native).
6
7use std::sync::Arc;
8
9use crate::draw_ctx::DrawCtx;
10use crate::event::{Event, EventResult, MouseButton};
11use crate::geometry::{Rect, Size};
12use crate::layout_props::{HAnchor, Insets, VAnchor, WidgetBase};
13use crate::text::{measure_text_metrics, Font};
14use crate::widget::Widget;
15
16// Colors are resolved from ctx.visuals() at paint time.
17
18/// A text label that looks like a hyperlink (blue, underlined) and fires a
19/// callback when clicked.
20pub struct Hyperlink {
21    bounds: Rect,
22    children: Vec<Box<dyn Widget>>,
23    base: WidgetBase,
24
25    text: String,
26    font: Arc<Font>,
27    font_size: f64,
28
29    hovered: bool,
30    on_click: Option<Box<dyn FnMut()>>,
31
32    cache: crate::widget::BackbufferCache,
33    last_sig: Option<(bool, u64, u64)>, // (hovered, w_bits, h_bits)
34}
35
36impl Hyperlink {
37    pub fn new(text: impl Into<String>, font: Arc<Font>) -> Self {
38        Self {
39            bounds: Rect::default(),
40            children: Vec::new(),
41            base: WidgetBase::new(),
42            text: text.into(),
43            font,
44            font_size: 14.0,
45            hovered: false,
46            on_click: None,
47            cache: crate::widget::BackbufferCache::default(),
48            last_sig: None,
49        }
50    }
51
52    pub fn with_font_size(mut self, size: f64) -> Self {
53        self.font_size = size;
54        self
55    }
56    pub fn on_click(mut self, cb: impl FnMut() + 'static) -> Self {
57        self.on_click = Some(Box::new(cb));
58        self
59    }
60
61    pub fn with_margin(mut self, m: Insets) -> Self {
62        self.base.margin = m;
63        self
64    }
65    pub fn with_h_anchor(mut self, h: HAnchor) -> Self {
66        self.base.h_anchor = h;
67        self
68    }
69    pub fn with_v_anchor(mut self, v: VAnchor) -> Self {
70        self.base.v_anchor = v;
71        self
72    }
73    pub fn with_min_size(mut self, s: Size) -> Self {
74        self.base.min_size = s;
75        self
76    }
77    pub fn with_max_size(mut self, s: Size) -> Self {
78        self.base.max_size = s;
79        self
80    }
81}
82
83impl Widget for Hyperlink {
84    fn type_name(&self) -> &'static str {
85        "Hyperlink"
86    }
87    fn bounds(&self) -> Rect {
88        self.bounds
89    }
90    fn set_bounds(&mut self, b: Rect) {
91        self.bounds = b;
92    }
93    fn children(&self) -> &[Box<dyn Widget>] {
94        &self.children
95    }
96    fn children_mut(&mut self) -> &mut Vec<Box<dyn Widget>> {
97        &mut self.children
98    }
99
100    fn margin(&self) -> Insets {
101        self.base.margin
102    }
103    fn h_anchor(&self) -> HAnchor {
104        self.base.h_anchor
105    }
106    fn v_anchor(&self) -> VAnchor {
107        self.base.v_anchor
108    }
109    fn min_size(&self) -> Size {
110        self.base.min_size
111    }
112    fn max_size(&self) -> Size {
113        self.base.max_size
114    }
115
116    fn is_focusable(&self) -> bool {
117        true
118    }
119
120    fn backbuffer_cache_mut(&mut self) -> Option<&mut crate::widget::BackbufferCache> {
121        Some(&mut self.cache)
122    }
123
124    fn backbuffer_mode(&self) -> crate::widget::BackbufferMode {
125        if crate::font_settings::lcd_enabled() {
126            crate::widget::BackbufferMode::LcdCoverage
127        } else {
128            crate::widget::BackbufferMode::Rgba
129        }
130    }
131
132    fn layout(&mut self, _available: Size) -> Size {
133        let sig = (
134            self.hovered,
135            self.bounds.width.to_bits(),
136            self.bounds.height.to_bits(),
137        );
138        if self.last_sig != Some(sig) {
139            self.last_sig = Some(sig);
140            self.cache.invalidate();
141        }
142        let h = self.font_size * 1.5;
143        let w = measure_text_metrics(&self.font, &self.text, self.font_size).width;
144        Size::new(w, h)
145    }
146
147    fn paint(&mut self, ctx: &mut dyn DrawCtx) {
148        let v = ctx.visuals();
149        let color = if self.hovered {
150            v.text_link_hovered
151        } else {
152            v.text_link
153        };
154        ctx.set_font(Arc::clone(&self.font));
155        ctx.set_font_size(self.font_size);
156        ctx.set_fill_color(color);
157
158        let h = self.bounds.height;
159        let m = ctx.measure_text(&self.text).unwrap_or_default();
160        let ty = h * 0.5 - (m.ascent - m.descent) * 0.5;
161        ctx.fill_text(&self.text, 0.0, ty);
162
163        // Underline — drawn at the text baseline.
164        let uw = m.width;
165        let uy = ty - m.descent - 1.0; // 1 px below baseline
166        ctx.set_stroke_color(color);
167        ctx.set_line_width(1.0);
168        ctx.begin_path();
169        ctx.move_to(0.0, uy);
170        ctx.line_to(uw, uy);
171        ctx.stroke();
172    }
173
174    fn on_event(&mut self, event: &Event) -> EventResult {
175        match event {
176            Event::MouseMove { pos } => {
177                let was = self.hovered;
178                self.hovered = self.hit_test(*pos);
179                if was != self.hovered {
180                    crate::animation::request_draw();
181                    return EventResult::Consumed;
182                }
183                EventResult::Ignored
184            }
185            Event::MouseDown {
186                button: MouseButton::Left,
187                ..
188            } => EventResult::Consumed,
189            Event::MouseUp {
190                button: MouseButton::Left,
191                pos,
192                ..
193            } => {
194                if self.hit_test(*pos) {
195                    if let Some(cb) = self.on_click.as_mut() {
196                        cb();
197                    }
198                    // Click handler typically mutates app state.
199                    crate::animation::request_draw();
200                }
201                EventResult::Consumed
202            }
203            _ => EventResult::Ignored,
204        }
205    }
206}