Skip to main content

gpui_component/
link.rs

1use gpui::ColorExt as _;
2use gpui::{
3    AnyElement, ClickEvent, ElementId, InteractiveElement, IntoElement, MouseButton, ParentElement,
4    RenderOnce, SharedString, StatefulInteractiveElement, StyleRefinement, Styled, div,
5};
6
7use crate::{ActiveTheme as _, StyledExt};
8
9/// A Link element like a `<a>` tag in HTML.
10#[derive(IntoElement)]
11pub struct Link {
12    id: ElementId,
13    style: StyleRefinement,
14    href: Option<SharedString>,
15    disabled: bool,
16    on_click: Option<Box<dyn Fn(&ClickEvent, &mut gpui::Window, &mut gpui::App) + 'static>>,
17    children: Vec<AnyElement>,
18}
19
20impl Link {
21    /// Create a new Link element.
22    pub fn new(id: impl Into<ElementId>) -> Self {
23        Self {
24            id: id.into(),
25            style: StyleRefinement::default(),
26            href: None,
27            on_click: None,
28            disabled: false,
29            children: Vec::new(),
30        }
31    }
32
33    /// Set the href of the link.
34    pub fn href(mut self, href: impl Into<SharedString>) -> Self {
35        self.href = Some(href.into());
36        self
37    }
38
39    /// Set the click handler of the link.
40    ///
41    /// If this set, the handler will be called when the link is clicked.
42    /// Otherwise, the link will only open the href if set.
43    pub fn on_click(
44        mut self,
45        handler: impl Fn(&ClickEvent, &mut gpui::Window, &mut gpui::App) + 'static,
46    ) -> Self {
47        self.on_click = Some(Box::new(handler));
48        self
49    }
50
51    /// Set the disabled state, default false.
52    pub fn disabled(mut self, disabled: bool) -> Self {
53        self.disabled = disabled;
54        self
55    }
56}
57
58impl Styled for Link {
59    fn style(&mut self) -> &mut gpui::StyleRefinement {
60        &mut self.style
61    }
62}
63
64impl ParentElement for Link {
65    fn extend(&mut self, elements: impl IntoIterator<Item = gpui::AnyElement>) {
66        self.children.extend(elements)
67    }
68}
69
70impl RenderOnce for Link {
71    fn render(self, _: &mut gpui::Window, cx: &mut gpui::App) -> impl IntoElement {
72        let href = self.href.clone();
73        let on_click = self.on_click;
74
75        div()
76            .id(self.id)
77            .text_color(cx.theme().link)
78            .text_decoration_1()
79            .text_decoration_color(cx.theme().link.opacity(0.5))
80            .hover(|this| {
81                this.text_color(cx.theme().link.opacity(0.8))
82                    .text_decoration_1()
83                    .text_decoration_color(cx.theme().link)
84            })
85            .active(|this| {
86                this.text_color(cx.theme().link.opacity(0.6))
87                    .text_decoration_1()
88                    .text_decoration_color(cx.theme().link)
89            })
90            .cursor_pointer()
91            .refine_style(&self.style)
92            .on_mouse_down(MouseButton::Left, |_, _, cx| {
93                cx.stop_propagation();
94            })
95            .on_click({
96                move |e, window, cx| {
97                    if let Some(href) = &href {
98                        cx.open_url(&href.clone());
99                    }
100                    if let Some(on_click) = &on_click {
101                        on_click(e, window, cx);
102                    }
103                }
104            })
105            .children(self.children)
106    }
107}
108
109#[cfg(test)]
110mod tests {
111    use std::{cell::Cell, rc::Rc};
112
113    use gpui::{Context, Modifiers, Render, TestAppContext, div, point, px};
114
115    use super::*;
116
117    struct LinkHarness {
118        disabled: bool,
119        clicks: Rc<Cell<usize>>,
120    }
121
122    impl Render for LinkHarness {
123        fn render(&mut self, _: &mut gpui::Window, _: &mut Context<Self>) -> impl IntoElement {
124            let clicks = self.clicks.clone();
125            Link::new("legacy-link")
126                .href("https://example.com")
127                .disabled(self.disabled)
128                .size(px(100.))
129                .child(
130                    div()
131                        .debug_selector(|| "legacy-link-child".into())
132                        .child("Visible link"),
133                )
134                .on_click(move |_, _, _| clicks.set(clicks.get() + 1))
135        }
136    }
137
138    #[gpui::test]
139    fn legacy_link_prepaints_children(cx: &mut TestAppContext) {
140        let (cx, _) = harness(cx, false);
141        let bounds = cx
142            .debug_bounds("legacy-link-child")
143            .expect("legacy Link child must participate in layout and prepaint");
144
145        assert!(bounds.size.width > px(0.));
146        assert!(bounds.size.height > px(0.));
147    }
148
149    fn harness(
150        cx: &mut TestAppContext,
151        disabled: bool,
152    ) -> (&mut gpui::VisualTestContext, Rc<Cell<usize>>) {
153        cx.update(crate::init);
154        let clicks = Rc::new(Cell::new(0));
155        let (_, cx) = cx.add_window_view({
156            let clicks = clicks.clone();
157            move |_, _| LinkHarness { disabled, clicks }
158        });
159        cx.update(|window, cx| window.draw(cx).clear(cx));
160        (cx, clicks)
161    }
162
163    #[gpui::test]
164    fn legacy_link_preserves_pointer_open_and_callback(cx: &mut TestAppContext) {
165        let (cx, clicks) = harness(cx, false);
166        cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
167
168        assert_eq!(cx.opened_url().as_deref(), Some("https://example.com"));
169        assert_eq!(clicks.get(), 1);
170    }
171
172    #[gpui::test]
173    fn legacy_link_preserves_disabled_behavior(cx: &mut TestAppContext) {
174        let (cx, clicks) = harness(cx, true);
175        cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
176
177        // `disabled` was historically a stored but behaviorally inert field.
178        assert_eq!(cx.opened_url().as_deref(), Some("https://example.com"));
179        assert_eq!(clicks.get(), 1);
180    }
181
182    #[gpui::test]
183    fn legacy_link_remains_pointer_only(cx: &mut TestAppContext) {
184        let (cx, clicks) = harness(cx, false);
185        cx.simulate_keystrokes("enter space");
186
187        assert_eq!(cx.opened_url(), None);
188        assert_eq!(clicks.get(), 0);
189    }
190}