Skip to main content

rooter/
nav_link.rs

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