Skip to main content

rooter/
nav_link.rs

1use crate::{Router, config::location_path};
2use gpui::{
3    AnyElement, App, Div, ElementId, InteractiveElement, IntoElement, ParentElement, RenderOnce,
4    SharedString, Stateful, StatefulInteractiveElement, Window, div,
5};
6use std::marker::PhantomData;
7
8type ActiveStyle = Box<dyn FnOnce(Stateful<Div>) -> Stateful<Div>>;
9
10/// How a [`NavLink`] compares the current location to its target.
11#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
12pub enum ActiveMatch {
13    #[default]
14    Exact,
15    Partial,
16}
17
18#[doc(hidden)]
19pub struct PathTarget;
20
21#[doc(hidden)]
22pub struct NamedTarget;
23
24#[derive(Clone, Debug)]
25enum NavTarget {
26    Path(SharedString),
27    Named {
28        name: SharedString,
29        params: Vec<(String, String)>,
30    },
31}
32
33/// A clickable element that navigates the window's [`Router`](crate::Router).
34///
35/// Use [`NavLink::to`] for a literal path and [`NavLink::named`] for a named
36/// route. [`NavLink::param`] is only available on named links.
37#[derive(IntoElement)]
38pub struct NavLink<Target: 'static = PathTarget> {
39    to: NavTarget,
40    children: Vec<AnyElement>,
41    match_mode: ActiveMatch,
42    when_active: Option<ActiveStyle>,
43    _target: PhantomData<Target>,
44}
45
46impl NavLink<PathTarget> {
47    pub fn to(to: impl Into<SharedString>) -> Self {
48        Self {
49            to: NavTarget::Path(to.into()),
50            children: Vec::new(),
51            match_mode: ActiveMatch::Exact,
52            when_active: None,
53            _target: PhantomData,
54        }
55    }
56
57    pub fn named(name: impl Into<SharedString>) -> NavLink<NamedTarget> {
58        NavLink {
59            to: NavTarget::Named {
60                name: name.into(),
61                params: Vec::new(),
62            },
63            children: Vec::new(),
64            match_mode: ActiveMatch::Exact,
65            when_active: None,
66            _target: PhantomData,
67        }
68    }
69}
70
71impl NavLink<NamedTarget> {
72    pub fn param(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
73        if let NavTarget::Named { params, .. } = &mut self.to {
74            params.push((key.into(), value.into()));
75        }
76        self
77    }
78}
79
80impl<Target> NavLink<Target> {
81    pub fn when_active(
82        mut self,
83        mode: impl Into<Option<ActiveMatch>>,
84        style: impl FnOnce(Stateful<Div>) -> Stateful<Div> + 'static,
85    ) -> Self {
86        self.match_mode = mode.into().unwrap_or_default();
87        self.when_active = Some(Box::new(style));
88        self
89    }
90}
91
92impl<Target> ParentElement for NavLink<Target> {
93    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
94        self.children.extend(elements);
95    }
96}
97
98impl<Target: 'static> RenderOnce for NavLink<Target> {
99    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
100        let Some(to) = resolve_target(&self.to, window, cx) else {
101            return div().children(self.children).into_any_element();
102        };
103        let active = Router::window_location(window, cx).is_some_and(|location| {
104            location_matches(location.as_ref(), to.as_ref(), self.match_mode)
105        });
106        let mut link = div()
107            .id(ElementId::from(to.clone()))
108            .on_click(move |_, window, cx| {
109                Router::navigate_window(window, cx, to.clone());
110            })
111            .children(self.children);
112        if active && let Some(when_active) = self.when_active {
113            link = when_active(link);
114        }
115        link.into_any_element()
116    }
117}
118
119fn resolve_target(target: &NavTarget, window: &Window, cx: &App) -> Option<SharedString> {
120    match target {
121        NavTarget::Path(path) => Some(path.clone()),
122        NavTarget::Named { name, params } => Router::window_url(window, cx, name, params)
123            .and_then(Result::ok)
124            .map(Into::into),
125    }
126}
127
128fn location_matches(location: &str, to: &str, mode: ActiveMatch) -> bool {
129    let location = location_path(location);
130    let to = location_path(to);
131    match mode {
132        ActiveMatch::Partial => {
133            to == "/" || location == to || location.starts_with(&format!("{to}/"))
134        }
135        ActiveMatch::Exact => location == to,
136    }
137}
138
139#[cfg(test)]
140mod tests {
141    use super::*;
142    use crate::{Router, RouterConfig};
143    use gpui::{Context, Entity, ParentElement, Render, TestAppContext, point, px, size};
144    use std::sync::{
145        Arc,
146        atomic::{AtomicBool, Ordering},
147    };
148
149    struct Root {
150        router: Entity<Router>,
151    }
152
153    impl Render for Root {
154        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
155            div().child(self.router.clone())
156        }
157    }
158
159    fn config() -> RouterConfig {
160        RouterConfig::new()
161            .route("/", || "home")
162            .route("/about", || "about")
163            .route("/dashboard", || "dashboard")
164            .route("/dashboard/users", || "users")
165    }
166
167    #[test]
168    fn exact_matches_normalize_the_location_and_target() {
169        assert!(location_matches("/about/", "/about", ActiveMatch::Exact));
170        assert!(!location_matches(
171            "/about",
172            "/dashboard",
173            ActiveMatch::Exact
174        ));
175        assert!(!location_matches(
176            "/dashboard/users",
177            "/dashboard",
178            ActiveMatch::Exact
179        ));
180        assert!(!location_matches("/about", "/", ActiveMatch::Exact));
181        assert!(location_matches(
182            "/search?q=rooter",
183            "/search",
184            ActiveMatch::Exact
185        ));
186        assert!(!location_matches(
187            "/search?q=rooter",
188            "/about",
189            ActiveMatch::Exact
190        ));
191    }
192
193    #[test]
194    fn partial_matches_nested_paths_but_not_sibling_paths() {
195        assert!(location_matches(
196            "/dashboard",
197            "/dashboard",
198            ActiveMatch::Partial
199        ));
200        assert!(location_matches(
201            "/dashboard/users",
202            "/dashboard",
203            ActiveMatch::Partial
204        ));
205        assert!(location_matches(
206            "/dashboard/users/42",
207            "/dashboard/users",
208            ActiveMatch::Partial
209        ));
210        assert!(!location_matches(
211            "/dashboard-admin",
212            "/dashboard",
213            ActiveMatch::Partial
214        ));
215        assert!(location_matches("/about", "/", ActiveMatch::Partial));
216    }
217
218    #[gpui::test]
219    async fn applies_active_styles_only_for_the_matching_link(cx: &mut TestAppContext) {
220        let home_active = Arc::new(AtomicBool::new(false));
221        let about_active = Arc::new(AtomicBool::new(false));
222        let window = cx.add_window(|window, cx| Root {
223            router: Router::attach(window, cx, config()),
224        });
225        let router = window
226            .root(cx)
227            .unwrap()
228            .read_with(cx, |root, _| root.router.clone());
229        let mut visual = gpui::VisualTestContext::from_window(window.into(), cx);
230
231        let draw = |visual: &mut gpui::VisualTestContext,
232                    router: Entity<Router>,
233                    home_active: Arc<AtomicBool>,
234                    about_active: Arc<AtomicBool>| {
235            home_active.store(false, Ordering::SeqCst);
236            about_active.store(false, Ordering::SeqCst);
237            visual.draw(point(px(0.), px(0.)), size(px(200.), px(40.)), |_, _| {
238                let home = home_active.clone();
239                let about = about_active.clone();
240                div()
241                    .child(router)
242                    .child(NavLink::to("/").when_active(None, move |link| {
243                        home.store(true, Ordering::SeqCst);
244                        link
245                    }))
246                    .child(NavLink::to("/about").when_active(None, move |link| {
247                        about.store(true, Ordering::SeqCst);
248                        link
249                    }))
250            });
251        };
252
253        draw(
254            &mut visual,
255            router.clone(),
256            home_active.clone(),
257            about_active.clone(),
258        );
259        assert!(home_active.load(Ordering::SeqCst));
260        assert!(!about_active.load(Ordering::SeqCst));
261
262        router.update(&mut visual, |router, cx| router.navigate("/about", cx));
263        draw(
264            &mut visual,
265            router,
266            home_active.clone(),
267            about_active.clone(),
268        );
269        assert!(!home_active.load(Ordering::SeqCst));
270        assert!(about_active.load(Ordering::SeqCst));
271    }
272
273    #[gpui::test]
274    async fn partial_links_stay_active_on_nested_routes(cx: &mut TestAppContext) {
275        let dashboard_active = Arc::new(AtomicBool::new(false));
276        let window = cx.add_window(|window, cx| Root {
277            router: Router::attach(window, cx, config()),
278        });
279        let router = window
280            .root(cx)
281            .unwrap()
282            .read_with(cx, |root, _| root.router.clone());
283        let mut visual = gpui::VisualTestContext::from_window(window.into(), cx);
284
285        router.update(&mut visual, |router, cx| {
286            router.navigate("/dashboard/users", cx)
287        });
288        visual.draw(point(px(0.), px(0.)), size(px(200.), px(40.)), |_, _| {
289            let dashboard = dashboard_active.clone();
290            div().child(
291                NavLink::to("/dashboard").when_active(ActiveMatch::Partial, move |link| {
292                    dashboard.store(true, Ordering::SeqCst);
293                    link
294                }),
295            )
296        });
297
298        assert!(dashboard_active.load(Ordering::SeqCst));
299    }
300
301    #[gpui::test]
302    async fn named_links_resolve_to_generated_paths(cx: &mut TestAppContext) {
303        let user_active = Arc::new(AtomicBool::new(false));
304        let config = RouterConfig::new()
305            .route("/", || "home")
306            .route("/users/{id}", || "user")
307            .name("users.show");
308        let window = cx.add_window(|window, cx| Root {
309            router: Router::attach(window, cx, config),
310        });
311        let router = window
312            .root(cx)
313            .unwrap()
314            .read_with(cx, |root, _| root.router.clone());
315        let mut visual = gpui::VisualTestContext::from_window(window.into(), cx);
316
317        router.update(&mut visual, |router, cx| {
318            let path = router
319                .url("users.show", [("id", "42"), ("tab", "profile")])
320                .unwrap();
321            router.navigate(path, cx);
322        });
323        visual.draw(point(px(0.), px(0.)), size(px(200.), px(40.)), |_, _| {
324            let user = user_active.clone();
325            div().child(
326                NavLink::named("users.show")
327                    .param("id", "42")
328                    .param("tab", "profile")
329                    .when_active(None, move |link| {
330                        user.store(true, Ordering::SeqCst);
331                        link
332                    }),
333            )
334        });
335
336        assert!(user_active.load(Ordering::SeqCst));
337        assert_eq!(
338            router.read_with(&visual, |router, _| router.location().to_owned()),
339            "/users/42?tab=profile"
340        );
341    }
342
343    #[gpui::test]
344    async fn unknown_named_links_do_not_panic(cx: &mut TestAppContext) {
345        let config = RouterConfig::new().route("/", || "home");
346        let window = cx.add_window(|window, cx| Root {
347            router: Router::attach(window, cx, config),
348        });
349        let mut visual = gpui::VisualTestContext::from_window(window.into(), cx);
350
351        visual.draw(point(px(0.), px(0.)), size(px(200.), px(40.)), |_, _| {
352            div().child(NavLink::named("missing").child("Broken"))
353        });
354    }
355}