rooter 0.2.0

A window-scoped router for GPUI applications.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
use crate::{Router, config::location_path, resource::IntoCacheFor};
use gpui::{
    AnyElement, App, Div, ElementId, InteractiveElement, IntoElement, ParentElement, RenderOnce,
    SharedString, Stateful, StatefulInteractiveElement, Window, div,
};
use std::marker::PhantomData;
use std::time::Duration;

type ActiveStyle = Box<dyn FnOnce(Stateful<Div>) -> Stateful<Div>>;

/// When a [`NavLink`] starts the target route's loader.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum PrefetchWhen {
    #[default]
    Hover,
    Visible,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct Prefetch {
    when: PrefetchWhen,
    cache_for: Duration,
}

/// How a [`NavLink`] compares the current location to its target.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum ActiveMatch {
    #[default]
    Exact,
    Partial,
}

#[doc(hidden)]
pub struct PathTarget;

#[doc(hidden)]
pub struct NamedTarget;

#[derive(Clone, Debug)]
enum NavTarget {
    Path(SharedString),
    Named {
        name: SharedString,
        params: Vec<(String, String)>,
    },
}

/// A clickable element that navigates the window's [`Router`](crate::Router).
///
/// Use [`NavLink::to`] for a literal path and [`NavLink::named`] for a named
/// route. [`NavLink::param`] is only available on named links.
#[derive(IntoElement)]
pub struct NavLink<Target: 'static = PathTarget> {
    to: NavTarget,
    children: Vec<AnyElement>,
    match_mode: ActiveMatch,
    when_active: Option<ActiveStyle>,
    prefetch: Option<Prefetch>,
    _target: PhantomData<Target>,
}

impl NavLink<PathTarget> {
    pub fn to(to: impl Into<SharedString>) -> Self {
        Self {
            to: NavTarget::Path(to.into()),
            children: Vec::new(),
            match_mode: ActiveMatch::Exact,
            when_active: None,
            prefetch: None,
            _target: PhantomData,
        }
    }

    pub fn named(name: impl Into<SharedString>) -> NavLink<NamedTarget> {
        NavLink {
            to: NavTarget::Named {
                name: name.into(),
                params: Vec::new(),
            },
            children: Vec::new(),
            match_mode: ActiveMatch::Exact,
            when_active: None,
            prefetch: None,
            _target: PhantomData,
        }
    }
}

impl NavLink<NamedTarget> {
    pub fn param(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        if let NavTarget::Named { params, .. } = &mut self.to {
            params.push((key.into(), value.into()));
        }
        self
    }
}

impl<Target> NavLink<Target> {
    pub fn when_active(
        mut self,
        mode: impl Into<Option<ActiveMatch>>,
        style: impl FnOnce(Stateful<Div>) -> Stateful<Div> + 'static,
    ) -> Self {
        self.match_mode = mode.into().unwrap_or_default();
        self.when_active = Some(Box::new(style));
        self
    }

    /// Start the target route loader early.
    ///
    /// `cache_for` is a [`Duration`] or [`None`] ([`crate::DEFAULT_CACHE_FOR`]).
    pub fn prefetch(mut self, when: PrefetchWhen, cache_for: impl IntoCacheFor) -> Self {
        self.prefetch = Some(Prefetch {
            when,
            cache_for: cache_for.into_cache_for(),
        });
        self
    }
}

impl<Target> ParentElement for NavLink<Target> {
    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
        self.children.extend(elements);
    }
}

impl<Target: 'static> RenderOnce for NavLink<Target> {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let Some(to) = resolve_target(&self.to, window, cx) else {
            return div().children(self.children).into_any_element();
        };
        let active = Router::window_location(window, cx).is_some_and(|location| {
            location_matches(location.as_ref(), to.as_ref(), self.match_mode)
        });
        let prefetch = self.prefetch;
        let mut link = div()
            .id(ElementId::from(to.clone()))
            .on_click({
                let to = to.clone();
                move |_, window, cx| {
                    Router::navigate_window(window, cx, to.clone());
                }
            })
            .children(self.children);
        match prefetch {
            Some(Prefetch {
                when: PrefetchWhen::Hover,
                cache_for,
            }) => {
                let to = to.clone();
                link = link.on_hover(move |hovered, window, cx| {
                    if *hovered {
                        Router::prefetch_window(window, cx, to.clone(), cache_for);
                    }
                });
            }
            Some(Prefetch {
                when: PrefetchWhen::Visible,
                cache_for,
            }) => {
                Router::prefetch_window(window, cx, to.clone(), cache_for);
            }
            None => {}
        }
        if active && let Some(when_active) = self.when_active {
            link = when_active(link);
        }
        link.into_any_element()
    }
}

fn resolve_target(target: &NavTarget, window: &Window, cx: &App) -> Option<SharedString> {
    match target {
        NavTarget::Path(path) => Some(path.clone()),
        NavTarget::Named { name, params } => Router::window_url(window, cx, name, params)
            .and_then(Result::ok)
            .map(Into::into),
    }
}

fn location_matches(location: &str, to: &str, mode: ActiveMatch) -> bool {
    let location = location_path(location);
    let to = location_path(to);
    match mode {
        ActiveMatch::Partial => {
            to == "/" || location == to || location.starts_with(&format!("{to}/"))
        }
        ActiveMatch::Exact => location == to,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Router, RouterConfig};
    use gpui::{Context, Entity, ParentElement, Render, TestAppContext, point, px, size};
    use std::sync::{
        Arc,
        atomic::{AtomicBool, Ordering},
    };

    struct Root {
        router: Entity<Router>,
    }

    impl Render for Root {
        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
            div().child(self.router.clone())
        }
    }

    fn config() -> RouterConfig {
        RouterConfig::new()
            .route("/", || "home")
            .route("/about", || "about")
            .route("/dashboard", || "dashboard")
            .route("/dashboard/users", || "users")
    }

    #[test]
    fn exact_matches_normalize_the_location_and_target() {
        assert!(location_matches("/about/", "/about", ActiveMatch::Exact));
        assert!(!location_matches(
            "/about",
            "/dashboard",
            ActiveMatch::Exact
        ));
        assert!(!location_matches(
            "/dashboard/users",
            "/dashboard",
            ActiveMatch::Exact
        ));
        assert!(!location_matches("/about", "/", ActiveMatch::Exact));
        assert!(location_matches(
            "/search?q=rooter",
            "/search",
            ActiveMatch::Exact
        ));
        assert!(!location_matches(
            "/search?q=rooter",
            "/about",
            ActiveMatch::Exact
        ));
    }

    #[test]
    fn partial_matches_nested_paths_but_not_sibling_paths() {
        assert!(location_matches(
            "/dashboard",
            "/dashboard",
            ActiveMatch::Partial
        ));
        assert!(location_matches(
            "/dashboard/users",
            "/dashboard",
            ActiveMatch::Partial
        ));
        assert!(location_matches(
            "/dashboard/users/42",
            "/dashboard/users",
            ActiveMatch::Partial
        ));
        assert!(!location_matches(
            "/dashboard-admin",
            "/dashboard",
            ActiveMatch::Partial
        ));
        assert!(location_matches("/about", "/", ActiveMatch::Partial));
    }

    #[gpui::test]
    async fn applies_active_styles_only_for_the_matching_link(cx: &mut TestAppContext) {
        let home_active = Arc::new(AtomicBool::new(false));
        let about_active = Arc::new(AtomicBool::new(false));
        let window = cx.add_window(|window, cx| Root {
            router: Router::attach(window, cx, config()),
        });
        let router = window
            .root(cx)
            .unwrap()
            .read_with(cx, |root, _| root.router.clone());
        let mut visual = gpui::VisualTestContext::from_window(window.into(), cx);

        let draw = |visual: &mut gpui::VisualTestContext,
                    router: Entity<Router>,
                    home_active: Arc<AtomicBool>,
                    about_active: Arc<AtomicBool>| {
            home_active.store(false, Ordering::SeqCst);
            about_active.store(false, Ordering::SeqCst);
            visual.draw(point(px(0.), px(0.)), size(px(200.), px(40.)), |_, _| {
                let home = home_active.clone();
                let about = about_active.clone();
                div()
                    .child(router)
                    .child(NavLink::to("/").when_active(None, move |link| {
                        home.store(true, Ordering::SeqCst);
                        link
                    }))
                    .child(NavLink::to("/about").when_active(None, move |link| {
                        about.store(true, Ordering::SeqCst);
                        link
                    }))
            });
        };

        draw(
            &mut visual,
            router.clone(),
            home_active.clone(),
            about_active.clone(),
        );
        assert!(home_active.load(Ordering::SeqCst));
        assert!(!about_active.load(Ordering::SeqCst));

        router.update(&mut visual, |router, cx| router.navigate("/about", cx));
        draw(
            &mut visual,
            router,
            home_active.clone(),
            about_active.clone(),
        );
        assert!(!home_active.load(Ordering::SeqCst));
        assert!(about_active.load(Ordering::SeqCst));
    }

    #[gpui::test]
    async fn partial_links_stay_active_on_nested_routes(cx: &mut TestAppContext) {
        let dashboard_active = Arc::new(AtomicBool::new(false));
        let window = cx.add_window(|window, cx| Root {
            router: Router::attach(window, cx, config()),
        });
        let router = window
            .root(cx)
            .unwrap()
            .read_with(cx, |root, _| root.router.clone());
        let mut visual = gpui::VisualTestContext::from_window(window.into(), cx);

        router.update(&mut visual, |router, cx| {
            router.navigate("/dashboard/users", cx)
        });
        visual.draw(point(px(0.), px(0.)), size(px(200.), px(40.)), |_, _| {
            let dashboard = dashboard_active.clone();
            div().child(
                NavLink::to("/dashboard").when_active(ActiveMatch::Partial, move |link| {
                    dashboard.store(true, Ordering::SeqCst);
                    link
                }),
            )
        });

        assert!(dashboard_active.load(Ordering::SeqCst));
    }

    #[gpui::test]
    async fn named_links_resolve_to_generated_paths(cx: &mut TestAppContext) {
        let user_active = Arc::new(AtomicBool::new(false));
        let config = RouterConfig::new()
            .route("/", || "home")
            .route("/users/{id}", || "user")
            .name("users.show");
        let window = cx.add_window(|window, cx| Root {
            router: Router::attach(window, cx, config),
        });
        let router = window
            .root(cx)
            .unwrap()
            .read_with(cx, |root, _| root.router.clone());
        let mut visual = gpui::VisualTestContext::from_window(window.into(), cx);

        router.update(&mut visual, |router, cx| {
            let path = router
                .url("users.show", [("id", "42"), ("tab", "profile")])
                .unwrap();
            router.navigate(path, cx);
        });
        visual.draw(point(px(0.), px(0.)), size(px(200.), px(40.)), |_, _| {
            let user = user_active.clone();
            div().child(
                NavLink::named("users.show")
                    .param("id", "42")
                    .param("tab", "profile")
                    .when_active(None, move |link| {
                        user.store(true, Ordering::SeqCst);
                        link
                    }),
            )
        });

        assert!(user_active.load(Ordering::SeqCst));
        assert_eq!(
            router.read_with(&visual, |router, _| router.location().to_owned()),
            "/users/42?tab=profile"
        );
    }

    #[gpui::test]
    async fn unknown_named_links_do_not_panic(cx: &mut TestAppContext) {
        let config = RouterConfig::new().route("/", || "home");
        let window = cx.add_window(|window, cx| Root {
            router: Router::attach(window, cx, config),
        });
        let mut visual = gpui::VisualTestContext::from_window(window.into(), cx);

        visual.draw(point(px(0.), px(0.)), size(px(200.), px(40.)), |_, _| {
            div().child(NavLink::named("missing").child("Broken"))
        });
    }
}