Skip to main content

gpui_base/
link.rs

1use std::rc::Rc;
2
3use gpui::{
4    AnyElement, App, ClickEvent, Div, ElementId, FocusHandle, InteractiveElement, Interactivity,
5    IntoElement, MouseButton, ParentElement, Refineable as _, RenderOnce, Role, SharedString,
6    Stateful, StatefulInteractiveElement, StyleRefinement, Styled, Window, div,
7    prelude::FluentBuilder as _,
8};
9use smallvec::SmallVec;
10
11use crate::{StateStyle, StyledExt as _};
12
13type ActivationHandler = Rc<dyn Fn(&ClickEvent, &mut Window, &mut App)>;
14type OpenHandler = Rc<dyn Fn(&str, &ClickEvent, &mut Window, &mut App)>;
15
16/// An unstyled link that owns focus, activation, and accessibility semantics.
17///
18/// `href` is target data, not an instruction to launch a browser. Applications
19/// inject navigation through [`Link::open_with`], allowing internal routes,
20/// embedded web views, and external browsers to share the same behavior module.
21/// `href` is also not rendered as text; applications provide visible content
22/// through the element's child slot.
23#[derive(IntoElement)]
24pub struct Link {
25    id: ElementId,
26    base: Stateful<Div>,
27    style: StyleRefinement,
28    semantic_styles: LinkStyles,
29    href: Option<SharedString>,
30    disabled: bool,
31    children: SmallVec<[AnyElement; 2]>,
32    on_activate: Option<ActivationHandler>,
33    open_with: Option<OpenHandler>,
34    accessibility_label: Option<SharedString>,
35    tab_index: isize,
36    tab_stop: bool,
37}
38
39/// Semantic root styles supported by [`Link`].
40#[derive(Default)]
41pub struct LinkStyles {
42    disabled: StyleRefinement,
43}
44
45impl LinkStyles {
46    pub fn disabled(mut self, build: impl FnOnce(StateStyle) -> StateStyle) -> Self {
47        self.disabled
48            .refine(&build(StateStyle::default()).into_refinement());
49        self
50    }
51}
52
53impl Link {
54    pub fn new(id: impl Into<ElementId>) -> Self {
55        let id = id.into();
56        Self {
57            base: div().id(id.clone()),
58            id,
59            style: StyleRefinement::default(),
60            semantic_styles: LinkStyles::default(),
61            href: None,
62            disabled: false,
63            children: SmallVec::new(),
64            on_activate: None,
65            open_with: None,
66            accessibility_label: None,
67            tab_index: 0,
68            tab_stop: true,
69        }
70    }
71
72    /// Sets the application-defined navigation target.
73    pub fn href(mut self, href: impl Into<SharedString>) -> Self {
74        self.href = Some(href.into());
75        self
76    }
77
78    /// Injects the strategy used to open `href` on activation.
79    ///
80    /// Base never calls [`App::open_url`] on its own.
81    pub fn open_with(
82        mut self,
83        open: impl Fn(&str, &ClickEvent, &mut Window, &mut App) + 'static,
84    ) -> Self {
85        self.open_with = Some(Rc::new(open));
86        self
87    }
88
89    /// Observes pointer or keyboard activation after the open strategy runs.
90    pub fn on_activate(
91        mut self,
92        handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
93    ) -> Self {
94        self.on_activate = Some(Rc::new(handler));
95        self
96    }
97
98    /// Sets whether pointer and keyboard activation are ignored.
99    pub fn disabled(mut self, disabled: bool) -> Self {
100        self.disabled = disabled;
101        self
102    }
103
104    /// Configures application-owned styles for the link's semantic states.
105    pub fn styles(mut self, build: impl FnOnce(LinkStyles) -> LinkStyles) -> Self {
106        self.semantic_styles = build(self.semantic_styles);
107        self
108    }
109
110    fn resolved_style(&self) -> StyleRefinement {
111        crate::state_style::resolve_style(
112            &self.style,
113            self.disabled.then_some(&self.semantic_styles.disabled),
114        )
115    }
116
117    /// Sets the name exposed to accessibility clients.
118    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
119        self.accessibility_label = Some(label.into());
120        self
121    }
122
123    /// Sets the focus traversal index. Use this within a GPUI tab group.
124    pub fn tab_index(mut self, tab_index: isize) -> Self {
125        self.tab_index = tab_index;
126        self
127    }
128
129    /// Sets whether the link participates in keyboard focus traversal.
130    pub fn tab_stop(mut self, tab_stop: bool) -> Self {
131        self.tab_stop = tab_stop;
132        self
133    }
134
135    fn focus_handle(&self, window: &mut Window, cx: &mut App) -> FocusHandle {
136        window
137            .use_keyed_state(self.id.clone(), cx, |_, cx| cx.focus_handle())
138            .read(cx)
139            .clone()
140    }
141}
142
143impl Styled for Link {
144    fn style(&mut self) -> &mut StyleRefinement {
145        &mut self.style
146    }
147}
148
149impl ParentElement for Link {
150    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
151        self.children.extend(elements);
152    }
153}
154
155impl InteractiveElement for Link {
156    fn interactivity(&mut self) -> &mut Interactivity {
157        self.base.interactivity()
158    }
159}
160
161impl StatefulInteractiveElement for Link {}
162
163impl RenderOnce for Link {
164    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
165        let focus_handle = self.focus_handle(window, cx);
166        let disabled = self.disabled;
167        let style = self.resolved_style();
168        let href = self.href;
169        let open_with = self.open_with;
170        let on_activate = self.on_activate;
171        let activates = on_activate.is_some() || href.is_some() && open_with.is_some();
172
173        self.base
174            .role(Role::Link)
175            .when_some(self.accessibility_label, |this, label| {
176                this.aria_label(label)
177            })
178            .when(!disabled, |this| {
179                this.track_focus(
180                    &focus_handle
181                        .tab_index(self.tab_index)
182                        .tab_stop(self.tab_stop),
183                )
184            })
185            .when(disabled, |this| {
186                this.on_mouse_down(MouseButton::Left, |_, _, cx| {
187                    cx.stop_propagation();
188                })
189            })
190            .when(!disabled && activates, |this| {
191                this.on_click(move |event, window, cx| {
192                    if let (Some(href), Some(open)) = (&href, &open_with) {
193                        open(href.as_ref(), event, window, cx);
194                    }
195                    if let Some(on_activate) = &on_activate {
196                        on_activate(event, window, cx);
197                    }
198                })
199            })
200            .children(self.children)
201            .refine_style(&style)
202    }
203}
204
205#[cfg(test)]
206mod tests {
207    use super::*;
208    use std::{
209        cell::{Cell, RefCell},
210        rc::Rc,
211        sync::{Arc, Mutex},
212    };
213
214    use gpui::{
215        Context, Element as _, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers, Render,
216        TestAppContext, VisualTestContext, accesskit, canvas, point, px,
217    };
218
219    struct LinkHarness {
220        disabled: bool,
221        activations: Rc<Cell<usize>>,
222        keyboard_events: Rc<Cell<usize>>,
223        opened: Rc<RefCell<Vec<String>>>,
224        parent_clicks: Rc<Cell<usize>>,
225    }
226
227    impl Render for LinkHarness {
228        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
229            let activations = self.activations.clone();
230            let keyboard_events = self.keyboard_events.clone();
231            let opened = self.opened.clone();
232            let parent_clicks = self.parent_clicks.clone();
233
234            div()
235                .id("link-parent")
236                .tab_group()
237                .size(px(100.))
238                .on_click(move |_, _, _| parent_clicks.set(parent_clicks.get() + 1))
239                .child(
240                    Link::new("link")
241                        .href("app://settings")
242                        .disabled(self.disabled)
243                        .size_full()
244                        .open_with(move |href, _, _, _| {
245                            opened.borrow_mut().push(href.to_owned());
246                        })
247                        .on_activate(move |event, _, _| {
248                            activations.set(activations.get() + 1);
249                            if matches!(event, ClickEvent::Keyboard(_)) {
250                                keyboard_events.set(keyboard_events.get() + 1);
251                            }
252                        }),
253                )
254        }
255    }
256
257    fn harness(
258        cx: &mut TestAppContext,
259        disabled: bool,
260    ) -> (
261        &mut VisualTestContext,
262        Rc<Cell<usize>>,
263        Rc<Cell<usize>>,
264        Rc<RefCell<Vec<String>>>,
265        Rc<Cell<usize>>,
266    ) {
267        let activations = Rc::new(Cell::new(0));
268        let keyboard_events = Rc::new(Cell::new(0));
269        let opened = Rc::new(RefCell::new(Vec::new()));
270        let parent_clicks = Rc::new(Cell::new(0));
271        let (_, cx) = cx.add_window_view({
272            let activations = activations.clone();
273            let keyboard_events = keyboard_events.clone();
274            let opened = opened.clone();
275            let parent_clicks = parent_clicks.clone();
276            move |_, _| LinkHarness {
277                disabled,
278                activations,
279                keyboard_events,
280                opened,
281                parent_clicks,
282            }
283        });
284        cx.update(|window, cx| window.draw(cx).clear(cx));
285        (cx, activations, keyboard_events, opened, parent_clicks)
286    }
287
288    fn activate_key(cx: &mut VisualTestContext, key: &str) {
289        let keystroke = Keystroke::parse(key).unwrap();
290        cx.simulate_event(KeyDownEvent {
291            keystroke: keystroke.clone(),
292            is_held: false,
293            prefer_character_input: false,
294        });
295        cx.simulate_event(KeyUpEvent { keystroke });
296    }
297
298    #[gpui::test]
299    fn pointer_runs_injected_open_strategy_and_activation_once(cx: &mut TestAppContext) {
300        let (cx, activations, keyboard_events, opened, _) = harness(cx, false);
301
302        cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
303
304        assert_eq!(activations.get(), 1);
305        assert_eq!(keyboard_events.get(), 0);
306        assert_eq!(&*opened.borrow(), &["app://settings"]);
307        assert_eq!(cx.opened_url(), None);
308    }
309
310    #[gpui::test]
311    fn open_strategy_runs_before_activation_callback(cx: &mut TestAppContext) {
312        struct OrderedLink(Rc<RefCell<Vec<&'static str>>>);
313
314        impl Render for OrderedLink {
315            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
316                let opened = self.0.clone();
317                let activated = self.0.clone();
318                Link::new("ordered-link")
319                    .href("app://ordered")
320                    .size(px(100.))
321                    .open_with(move |_, _, _, _| opened.borrow_mut().push("open"))
322                    .on_activate(move |_, _, _| activated.borrow_mut().push("activate"))
323            }
324        }
325
326        let order = Rc::new(RefCell::new(Vec::new()));
327        let result = order.clone();
328        let (_, cx) = cx.add_window_view(move |_, _| OrderedLink(order));
329        cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
330
331        assert_eq!(result.borrow().as_slice(), &["open", "activate"]);
332    }
333
334    #[gpui::test]
335    fn enter_and_space_each_activate_once(cx: &mut TestAppContext) {
336        let (cx, activations, keyboard_events, opened, _) = harness(cx, false);
337        cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
338        activations.set(0);
339        opened.borrow_mut().clear();
340        cx.update(|window, cx| {
341            assert!(window.focused(cx).is_some());
342            window.draw(cx).clear(cx);
343        });
344
345        activate_key(cx, "enter");
346        activate_key(cx, "space");
347
348        assert_eq!(activations.get(), 2);
349        assert_eq!(keyboard_events.get(), 2);
350        assert_eq!(&*opened.borrow(), &["app://settings", "app://settings"]);
351        assert_eq!(cx.opened_url(), None);
352    }
353
354    #[gpui::test]
355    fn href_without_strategy_never_opens_externally(cx: &mut TestAppContext) {
356        struct TargetOnly;
357
358        impl Render for TargetOnly {
359            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
360                Link::new("target-only")
361                    .href("https://example.com")
362                    .size(px(100.))
363            }
364        }
365
366        let (_, cx) = cx.add_window_view(|_, _| TargetOnly);
367        cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
368        assert_eq!(cx.opened_url(), None);
369    }
370
371    #[gpui::test]
372    fn disabled_link_is_inert_and_blocks_parent_activation(cx: &mut TestAppContext) {
373        let (cx, activations, _, opened, parent_clicks) = harness(cx, true);
374
375        cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
376        activate_key(cx, "enter");
377        activate_key(cx, "space");
378
379        assert_eq!(activations.get(), 0);
380        assert!(opened.borrow().is_empty());
381        assert_eq!(parent_clicks.get(), 0);
382    }
383
384    #[test]
385    fn visual_state_styles_remain_application_owned() {
386        let _ = Link::new("states")
387            .styles(|styles| styles.disabled(|style| style.opacity(0.5)))
388            .hover(|style| style.opacity(0.9))
389            .active(|style| style.opacity(0.8))
390            .focus_visible(|style| style.opacity(0.7));
391    }
392
393    #[test]
394    fn disabled_style_applies_only_while_disabled_and_then_wins() {
395        let enabled = Link::new("enabled")
396            .opacity(0.9)
397            .styles(|styles| styles.disabled(|style| style.opacity(0.5)));
398        assert_eq!(enabled.resolved_style().opacity, Some(0.9));
399
400        let disabled = Link::new("disabled")
401            .styles(|styles| styles.disabled(|style| style.opacity(0.5)))
402            .opacity(0.9)
403            .disabled(true);
404        assert_eq!(disabled.resolved_style().opacity, Some(0.5));
405
406        let semantic_only = Link::new("semantic-only")
407            .styles(|styles| styles.disabled(|style| style.opacity(0.5)))
408            .disabled(true);
409        assert_eq!(semantic_only.resolved_style().opacity, Some(0.5));
410    }
411
412    #[gpui::test]
413    fn accessibility_exposes_link_role_label_and_action_surface(cx: &mut TestAppContext) {
414        type Captured = Arc<Mutex<Option<(accesskit::Node, accesskit::Node)>>>;
415
416        struct A11yProbe {
417            captured: Captured,
418        }
419
420        impl Render for A11yProbe {
421            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
422                let captured = self.captured.clone();
423                canvas(
424                    move |_, window, cx| {
425                        let mut info = |link: Link| {
426                            let mut node = accesskit::Node::new(Role::Link);
427                            link.render(window, cx)
428                                .into_element()
429                                .write_a11y_info(&mut node);
430                            node
431                        };
432                        let enabled = info(
433                            Link::new("enabled")
434                                .href("app://settings")
435                                .accessibility_label("Settings")
436                                .open_with(|_, _, _, _| {}),
437                        );
438                        let disabled = info(
439                            Link::new("disabled")
440                                .disabled(true)
441                                .accessibility_label("Settings")
442                                .on_activate(|_, _, _| {}),
443                        );
444                        *captured.lock().unwrap() = Some((enabled, disabled));
445                    },
446                    |_, _, _, _| {},
447                )
448            }
449        }
450
451        let captured: Captured = Arc::new(Mutex::new(None));
452        let result = captured.clone();
453        let (_, cx) = cx.add_window_view(move |_, _| A11yProbe { captured });
454        cx.update(|window, cx| window.draw(cx).clear(cx));
455        let (enabled, disabled) = result.lock().unwrap().take().unwrap();
456
457        assert_eq!(enabled.role(), Role::Link);
458        assert_eq!(enabled.label(), Some("Settings"));
459        assert!(enabled.supports_action(accesskit::Action::Click));
460        assert_eq!(enabled.url(), None);
461
462        assert_eq!(disabled.role(), Role::Link);
463        assert!(!disabled.supports_action(accesskit::Action::Click));
464        assert!(!disabled.is_disabled());
465    }
466}