ailloli_ui_widgets/controls/
link.rs

1//! Accessible links that open validated external HTTP(S) URLs.
2
3use std::cell::Cell;
4use std::rc::Rc;
5
6use ailloli_ui_core::event::pointer::{MouseButton, PointerEvent};
7use ailloli_ui_core::event::{Event, Key, KeyState, NamedKey};
8use ailloli_ui_core::style::{
9    Border, FlexItemStyle, InteractionState, LayoutSizeHint, LayoutStyle, Radius, StateStyle,
10};
11use ailloli_ui_core::{Color, Constraints, FontId, Offset, Rect, Size, TextStyle, Theme};
12use ailloli_ui_runtime::app::ExternalUrl;
13use ailloli_ui_runtime::component::{Binding, IntoView, Memo, View, Widget};
14use ailloli_ui_runtime::input::{ActivationPolicy, EventCtx, FocusPolicy, HoverCursorRole};
15use ailloli_ui_runtime::layout::{
16    ChildLayout, LayoutArtifact, LayoutChild, LayoutCtx, LayoutResult,
17};
18use ailloli_ui_runtime::scene::PaintCtx;
19use ailloli_ui_runtime::{DrawBorder, DrawCmd, DrawText};
20use ailloli_ui_text::{TextLayoutParams, TextSystem, WrapMode};
21
22use crate::layout::layout_ext::{apply_layout_size, finish_view_sized};
23
24/// Visual states for a text link.
25///
26/// State styles are paint-only: keep the same font and size in every state.
27/// [`LinkStyle::resolve_text`] enforces the normal font and size even if a
28/// state override contains different metrics.
29///
30/// # Examples
31///
32/// ```
33/// use ailloli_ui_core::style::InteractionState;
34/// use ailloli_ui_widgets::controls::LinkStyle;
35/// let style = LinkStyle::default();
36/// let resolved = style.resolve_text(InteractionState::default());
37/// assert_eq!(resolved.px_size, style.text.normal.px_size);
38/// ```
39#[derive(Clone, Debug)]
40pub struct LinkStyle {
41    /// Normal and interaction-state text paint styles.
42    pub text: StateStyle<TextStyle>,
43    /// Border painted outside a focused, enabled link.
44    pub focus_ring: Border,
45    /// Gap between content bounds and focus ring in logical pixels.
46    pub focus_ring_offset: f32,
47}
48
49impl Default for LinkStyle {
50    fn default() -> Self {
51        let theme = Theme::default();
52        let palette = theme.palette();
53        let normal = TextStyle::new(FontId::Ui, 14, palette.accent).underline();
54        Self {
55            text: StateStyle {
56                normal,
57                hovered: Some(TextStyle::new(FontId::Ui, 14, Color::WHITE).underline()),
58                pressed: Some(normal.without_decoration()),
59                focused: None,
60                disabled: Some(
61                    TextStyle::new(FontId::Ui, 14, palette.text_muted.with_alpha(0.65)).underline(),
62                ),
63            },
64            focus_ring: Border::new(1.0, palette.focus),
65            focus_ring_offset: 2.0,
66        }
67    }
68}
69
70impl LinkStyle {
71    /// Resolves the text paint for `state` while preserving normal metrics.
72    ///
73    /// State overrides can change color and decoration, but their `font` and
74    /// `px_size` fields are deliberately ignored to keep layout stable.
75    ///
76    /// # Examples
77    ///
78    /// ```
79    /// use ailloli_ui_core::style::InteractionState;
80    /// use ailloli_ui_widgets::controls::LinkStyle;
81    /// let style = LinkStyle::default();
82    /// let hovered = style.resolve_text(InteractionState {
83    ///     hovered: true,
84    ///     ..InteractionState::default()
85    /// });
86    /// assert_eq!(hovered.px_size, style.text.normal.px_size);
87    /// ```
88    pub fn resolve_text(&self, state: InteractionState) -> TextStyle {
89        let resolved = self.text.resolve(state);
90        TextStyle {
91            font: self.text.normal.font,
92            px_size: self.text.normal.px_size,
93            ..resolved
94        }
95    }
96
97    /// Returns the maximum logical-pixel expansion required by the focus ring.
98    fn visual_inflate(&self) -> f32 {
99        let widths = self.focus_ring.layout_widths();
100        self.focus_ring_offset
101            + widths
102                .left
103                .max(widths.top)
104                .max(widths.right)
105                .max(widths.bottom)
106    }
107}
108
109/// Exactly one content representation owned by a link builder.
110enum LinkContent<A> {
111    /// Zero-sized placeholder used by [`Link::new`].
112    Empty,
113    /// Text rendered through [`LinkStyle`].
114    Label(String),
115    /// Caller-composed child whose own widget controls painting.
116    Child(View<A>),
117}
118
119/// An accessible external HTTP(S) link with a single composable child.
120///
121/// Use [`Link::with_label`] for the common text form, or [`Link::child`] for
122/// icons and composed content. `href` always means an external system URL;
123/// this widget deliberately has no generic action callback.
124/// Invalid, empty, non-HTTP(S), or hostless URL text produces an inert link;
125/// parse errors are intentionally not retained by the builder.
126///
127/// # Examples
128///
129/// ```
130/// use ailloli_ui_widgets::controls::Link;
131/// let link: Link<()> = Link::with_label("Documentation").href("https://example.com/docs");
132/// let _ = link;
133/// ```
134///
135/// # Future routing gate
136///
137/// Internal navigation is intentionally unavailable until the framework owns
138/// a provider-neutral route type, navigation state, history semantics,
139/// deep-link policy, focus/accessibility behavior, and consumer tests. The
140/// intended future syntax is documentation only:
141///
142/// ```text
143/// Link::with_label("Settings").route(Route::Settings)
144/// ```
145pub struct Link<A = ()> {
146    /// Layout configuration applied around the single content child.
147    pub(crate) layout: LayoutStyle,
148    /// Flex-item behavior used by the parent layout.
149    pub(crate) flex_item: FlexItemStyle,
150    /// Empty, styled-label, or composed-child content.
151    content: LinkContent<A>,
152    /// Validated external URL, or `None` for an inert link.
153    href: Option<ExternalUrl>,
154    /// Live disabled state.
155    disabled: Binding<bool>,
156    /// Label paint states and focus-ring style.
157    style: LinkStyle,
158}
159
160crate::impl_layout_builders!(Link);
161
162impl<A: 'static> Default for Link<A> {
163    fn default() -> Self {
164        Self::new()
165    }
166}
167
168impl<A: 'static> Link<A> {
169    /// Creates an empty, enabled link with no destination.
170    ///
171    /// Until content with nonzero layout and a valid URL are supplied, the link
172    /// is not focusable and uses the default cursor.
173    ///
174    /// # Examples
175    ///
176    /// ```
177    /// use ailloli_ui_widgets::controls::Link;
178    /// let link: Link<()> = Link::new();
179    /// let _ = link;
180    /// ```
181    pub fn new() -> Self {
182        Self {
183            layout: LayoutStyle::default(),
184            flex_item: FlexItemStyle::default(),
185            content: LinkContent::Empty,
186            href: None,
187            disabled: Binding::Static(false),
188            style: LinkStyle::default(),
189        }
190    }
191
192    /// Creates a link whose sole child is an owned, unwrapped text label.
193    ///
194    /// Empty text is accepted but normally lays out with zero width, leaving
195    /// the link inert even after a URL is supplied.
196    ///
197    /// # Examples
198    ///
199    /// ```
200    /// use ailloli_ui_widgets::controls::Link;
201    /// let link: Link<()> = Link::with_label("Website");
202    /// let _ = link;
203    /// ```
204    pub fn with_label(label: impl Into<String>) -> Self {
205        Self {
206            content: LinkContent::Label(label.into()),
207            ..Self::new()
208        }
209    }
210
211    /// Replaces empty or label content with one composed child view.
212    ///
213    /// [`LinkStyle::text`] does not affect composed children; the link still
214    /// supplies focus-ring and interaction behavior around their layout bounds.
215    ///
216    /// # Examples
217    ///
218    /// ```
219    /// use ailloli_ui_widgets::controls::Link;
220    /// use ailloli_ui_widgets::text::Text;
221    /// let link = Link::<()>::new().child(Text::new("Website"));
222    /// let _ = link;
223    /// ```
224    pub fn child(mut self, child: impl IntoView<A>) -> Self {
225        self.content = LinkContent::Child(child.into_view());
226        self
227    }
228
229    /// Parses and replaces the external HTTP(S) destination.
230    ///
231    /// Validation performs no network request. Invalid input silently clears
232    /// the destination, so a later invalid call makes a previously valid link
233    /// inert. The host-opening failure, if any, is non-fatal during activation.
234    ///
235    /// # Examples
236    ///
237    /// ```
238    /// use ailloli_ui_widgets::controls::Link;
239    /// let valid: Link<()> = Link::with_label("Web").href("https://example.com");
240    /// let inert: Link<()> = valid.href("file:///tmp/not-allowed");
241    /// let _ = inert;
242    /// ```
243    pub fn href(mut self, href: impl AsRef<str>) -> Self {
244        self.href = ExternalUrl::parse(href).ok();
245        self
246    }
247
248    /// Sets a static or reactive disabled binding.
249    ///
250    /// Disabled links do not activate, receive focus, or show a pointer cursor.
251    /// Label content resolves through the disabled text state.
252    ///
253    /// # Examples
254    ///
255    /// ```
256    /// use ailloli_ui_widgets::controls::Link;
257    /// let link: Link<()> = Link::with_label("Unavailable").disabled(true);
258    /// let _ = link;
259    /// ```
260    pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
261        self.disabled = disabled.into();
262        self
263    }
264
265    /// Convenience alias for [`Self::disabled`] with a reactive memo.
266    ///
267    /// # Examples
268    ///
269    /// ```
270    /// use ailloli_ui_runtime::component::Memo;
271    /// use ailloli_ui_widgets::controls::Link;
272    /// let link: Link<()> = Link::with_label("Website").disabled_signal(Memo::new(|| false));
273    /// let _ = link;
274    /// ```
275    pub fn disabled_signal(self, disabled: Memo<bool>) -> Self {
276        self.disabled(disabled)
277    }
278
279    /// Replaces only the normal label text style.
280    ///
281    /// Existing hover, pressed, and disabled overrides remain unchanged.
282    /// Composed child content ignores this field.
283    ///
284    /// # Examples
285    ///
286    /// ```
287    /// use ailloli_ui_core::{Color, FontId, TextStyle};
288    /// use ailloli_ui_widgets::controls::Link;
289    /// let link: Link<()> = Link::with_label("Docs")
290    ///     .style(TextStyle::new(FontId::Ui, 16, Color::WHITE));
291    /// let _ = link;
292    /// ```
293    pub fn style(mut self, style: TextStyle) -> Self {
294        self.style.text.normal = style;
295        self
296    }
297
298    /// Replaces the complete label-state and focus-ring style.
299    ///
300    /// # Examples
301    ///
302    /// ```
303    /// use ailloli_ui_widgets::controls::{Link, LinkStyle};
304    /// let link: Link<()> = Link::with_label("Docs").link_style(LinkStyle::default());
305    /// let _ = link;
306    /// ```
307    pub fn link_style(mut self, style: LinkStyle) -> Self {
308        self.style = style;
309        self
310    }
311}
312
313/// Retained interaction shell around one laid-out content child.
314struct LinkWidget {
315    /// Outer logical sizing policy.
316    layout: LayoutStyle,
317    /// Optional validated external destination.
318    href: Option<ExternalUrl>,
319    /// Reactive interaction-disable flag.
320    disabled: Binding<bool>,
321    /// Link colors, underline policy, and focus geometry.
322    style: LinkStyle,
323    /// Whether retained child content was assigned layout in the latest pass.
324    laid_out_content: Cell<bool>,
325    /// UI-local hover, press, and focus state shared with the label child.
326    interaction: Rc<Cell<InteractionState>>,
327}
328
329impl<A: 'static> Widget<A> for LinkWidget {
330    fn debug_name(&self) -> &'static str {
331        "Link"
332    }
333
334    fn layout(
335        &self,
336        engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
337        ctx: &mut LayoutCtx<'_>,
338        children: &mut [LayoutChild],
339        constraints: Constraints,
340    ) -> LayoutResult {
341        let mut child_layouts = Vec::new();
342        let mut intrinsic = Size::default();
343        if let Some(child) = children.first_mut() {
344            let result = child.layout(engine, ctx, constraints.loosen());
345            intrinsic = result.size;
346            child_layouts.push(ChildLayout {
347                offset: Offset::default(),
348                size: result.size,
349                paint_bounds: Rect::new(0.0, 0.0, result.size.w, result.size.h),
350                visual_bounds: result.visual_bounds,
351            });
352        }
353        let size = apply_layout_size(intrinsic, self.layout, constraints);
354        self.laid_out_content.set(size.w > 0.0 && size.h > 0.0);
355        let paint_bounds = Rect::new(0.0, 0.0, size.w, size.h);
356        let inflate = self.style.visual_inflate();
357        LayoutResult {
358            size,
359            children: child_layouts,
360            paint_bounds,
361            visual_bounds: paint_bounds.inflate(inflate, inflate),
362            overlay_hit_bounds: Vec::new(),
363            clip: None,
364            is_window_root_clip: false,
365            artifact: None,
366        }
367    }
368
369    fn paint(&self, ctx: &mut PaintCtx<'_>, _bounds: Rect, _layout: &LayoutResult) {
370        let input = ctx.interaction();
371        self.interaction.set(InteractionState {
372            hovered: input.hovered,
373            pressed: input.pressed,
374            focused: input.focused,
375            disabled: self.disabled.read() || self.href.is_none(),
376        });
377    }
378
379    fn paint_overlay(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout: &LayoutResult) {
380        let state = self.interaction.get();
381        if state.focused && !state.disabled && self.style.focus_ring.is_visible() {
382            ctx.push(DrawCmd::Border(DrawBorder {
383                rect: bounds.inflate(self.style.focus_ring_offset, self.style.focus_ring_offset),
384                radius: Radius::uniform(self.style.focus_ring_offset),
385                border: self.style.focus_ring,
386            }));
387        }
388    }
389
390    fn event(&self, ctx: &mut EventCtx<A>, event: &Event, bounds: Rect, _layout: &LayoutResult) {
391        if self.disabled.read() || !self.laid_out_content.get() {
392            return;
393        }
394        let Some(href) = self.href.as_ref() else {
395            return;
396        };
397        let activate = match event {
398            Event::Pointer(PointerEvent::Button {
399                pos,
400                button: MouseButton::Left,
401                pressed: false,
402                ..
403            }) => bounds.contains(pos.x, pos.y),
404            Event::Keyboard(key) => {
405                key.state == KeyState::Pressed
406                    && !key.repeat
407                    && matches!(&key.key, Key::Named(NamedKey::Enter))
408            }
409            _ => false,
410        };
411        if activate {
412            let _ = ctx.open_external_url(href);
413            ctx.stop_propagation();
414        }
415    }
416
417    fn focus_policy(&self) -> FocusPolicy {
418        if self.href.is_some() && !self.disabled.read() && self.laid_out_content.get() {
419            FocusPolicy::Focusable
420        } else {
421            FocusPolicy::NotFocusable
422        }
423    }
424
425    fn activation_policy(&self) -> ActivationPolicy {
426        ActivationPolicy::SuppressOnFocusOnly
427    }
428
429    fn hover_cursor_role(&self) -> HoverCursorRole {
430        if self.href.is_some() && !self.disabled.read() && self.laid_out_content.get() {
431            HoverCursorRole::Pointer
432        } else {
433            HoverCursorRole::Default
434        }
435    }
436}
437
438/// Styled text child sharing its parent's latest interaction snapshot.
439struct LinkLabelWidget {
440    /// User-visible fallback label painted when no custom child is supplied.
441    label: String,
442    /// Text colors and underline policy resolved from interaction state.
443    style: LinkStyle,
444    /// Shared UI-local hover, press, and focus state from the parent link.
445    interaction: Rc<Cell<InteractionState>>,
446}
447
448/// Prepares one unwrapped label with no maximum width.
449fn layout_label(
450    text_system: &mut TextSystem,
451    label: &str,
452    style: TextStyle,
453) -> ailloli_ui_text::TextLayoutHandle {
454    text_system.layout_cached(TextLayoutParams {
455        text: label,
456        style,
457        max_width: None,
458        wrap_mode: WrapMode::NoWrap,
459    })
460}
461
462impl<A: 'static> Widget<A> for LinkLabelWidget {
463    fn debug_name(&self) -> &'static str {
464        "LinkLabel"
465    }
466
467    fn layout(
468        &self,
469        _engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
470        ctx: &mut LayoutCtx<'_>,
471        _children: &mut [LayoutChild],
472        constraints: Constraints,
473    ) -> LayoutResult {
474        let prepared = ctx
475            .text_system
476            .as_deref_mut()
477            .map(|text| layout_label(text, &self.label, self.style.text.normal));
478        let intrinsic = prepared
479            .as_ref()
480            .map(|layout| Size::new(layout.metrics.width, layout.metrics.height))
481            .unwrap_or_else(|| Size::new(0.0, self.style.text.normal.px_size as f32 * 1.2));
482        let size = constraints.constrain(intrinsic);
483        let bounds = Rect::new(0.0, 0.0, size.w, size.h);
484        LayoutResult {
485            size,
486            children: Vec::new(),
487            paint_bounds: bounds,
488            visual_bounds: bounds,
489            overlay_hit_bounds: Vec::new(),
490            clip: None,
491            is_window_root_clip: false,
492            artifact: prepared.map(LayoutArtifact::Text),
493        }
494    }
495
496    fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, layout: &LayoutResult) {
497        let state = self.interaction.get();
498        let style = self.style.resolve_text(state);
499        let prepared = match layout.artifact.as_ref() {
500            Some(LayoutArtifact::Text(prepared)) => prepared.clone(),
501            None => {
502                let Some(text) = ctx.text_system.as_deref_mut() else {
503                    return;
504                };
505                layout_label(text, &self.label, self.style.text.normal)
506            }
507        };
508        let baseline = prepared
509            .lines
510            .first()
511            .map(|line| line.baseline_y)
512            .unwrap_or(0.0);
513        ctx.push(DrawCmd::Text(DrawText {
514            pos: [bounds.x, bounds.y + baseline],
515            color: style.color,
516            decoration: style.decoration,
517            layout: prepared,
518        }));
519    }
520}
521
522impl<A: 'static> IntoView<A> for Link<A> {
523    fn into_view(self) -> View<A> {
524        let interaction = Rc::new(Cell::new(InteractionState::default()));
525        let child = match self.content {
526            LinkContent::Empty => View::empty(),
527            LinkContent::Label(label) => View::leaf(LinkLabelWidget {
528                label,
529                style: self.style.clone(),
530                interaction: interaction.clone(),
531            }),
532            LinkContent::Child(child) => child,
533        };
534        let widget = LinkWidget {
535            layout: self.layout,
536            href: self.href,
537            disabled: self.disabled,
538            style: self.style,
539            laid_out_content: Cell::new(false),
540            interaction,
541        };
542        finish_view_sized(
543            View::node(widget, vec![child]),
544            self.flex_item,
545            LayoutSizeHint::from_layout(self.layout),
546        )
547    }
548}