yew-nav-link 0.10.0

Navigation link component for Yew with automatic active state detection
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
// SPDX-FileCopyrightText: 2024-2026 RAprogramm <andrey.rozanov-vl@gmail.com>
// SPDX-License-Identifier: MIT

use std::rc::Rc;

use yew::prelude::*;
use yew_router::prelude::*;

/// A trait for providing custom breadcrumb labels.
pub trait BreadcrumbLabelProvider: Send + Sync {
    /// Returns a human-readable label for the given path.
    fn label_for_path(&self, path: &str) -> String;
}

/// Yew context wrapper around a [`BreadcrumbLabelProvider`].
///
/// Place an instance into the tree with `<ContextProvider<…>>` to override
/// the default path-as-label behaviour of [`use_breadcrumbs`]. Equality is
/// pointer-equality on the inner [`Rc`], so re-renders happen only when the
/// concrete provider value changes.
///
/// The inner `Rc` is **not** publicly accessible — construct via
/// [`BreadcrumbLabelProviderContext::new`] and read with
/// [`BreadcrumbLabelProviderContext::provider`]. Keeping the field private
/// lets future versions evolve the representation (e.g. a provider chain or
/// internal cache) without breaking consumers.
#[derive(Clone)]
pub struct BreadcrumbLabelProviderContext(Rc<dyn BreadcrumbLabelProvider>);

impl BreadcrumbLabelProviderContext {
    /// Wraps the given provider so it can be passed to `ContextProvider`.
    #[must_use]
    pub fn new(provider: Rc<dyn BreadcrumbLabelProvider>) -> Self {
        Self(provider)
    }

    /// Returns a clone of the inner [`Rc`] for callers that need to invoke
    /// the provider directly.
    #[must_use]
    pub fn provider(&self) -> Rc<dyn BreadcrumbLabelProvider> {
        Rc::clone(&self.0)
    }
}

impl PartialEq for BreadcrumbLabelProviderContext {
    fn eq(&self, other: &Self) -> bool {
        Rc::ptr_eq(&self.0, &other.0)
    }
}

/// A single item in a breadcrumb trail.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BreadcrumbItem<R> {
    /// The route this breadcrumb points to.
    pub route:     R,
    /// Human-readable label for the breadcrumb.
    pub label:     String,
    /// Whether this breadcrumb represents the currently active route.
    pub is_active: bool
}

/// Returns a list of [`BreadcrumbItem`]s representing the current navigation
/// path.
#[hook]
pub fn use_breadcrumbs<R>() -> Vec<BreadcrumbItem<R>>
where
    R: Routable + Clone + PartialEq + 'static
{
    let current = use_route::<R>();
    let provider = use_context::<BreadcrumbLabelProviderContext>();

    current.map_or_else(Vec::new, |route| {
        let path = route.to_path();
        let segments: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
        let mut items = Vec::new();
        let mut built = String::new();
        // Root
        let root_label = provider
            .as_ref()
            .map_or_else(|| "/".to_string(), |p| p.0.label_for_path("/"));
        items.push(BreadcrumbItem {
            route:     route.clone(),
            label:     root_label,
            is_active: segments.is_empty()
        });
        // Segments
        let total = segments.len();
        for (i, segment) in segments.iter().enumerate() {
            built.push('/');
            built.push_str(segment);
            let is_last = i + 1 == total;
            let label = provider
                .as_ref()
                .map_or_else(|| built.clone(), |p| p.0.label_for_path(&built));
            items.push(BreadcrumbItem {
                route: route.clone(),
                label,
                is_active: is_last
            });
        }
        items
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[derive(Clone, PartialEq, Debug, Routable)]
    enum SimpleRoute {
        #[at("/")]
        Home,
        #[at("/about")]
        About,
        #[at("/docs")]
        Docs,
        #[at("/docs/api")]
        Api,
        #[at("/docs/api/v1")]
        ApiV1
    }

    #[derive(Clone, PartialEq, Debug, Routable)]
    enum ParamRoute {
        #[at("/")]
        Home,
        #[at("/users/:id")]
        User { id: String }
    }

    #[derive(Clone, PartialEq, Debug, Routable)]
    enum RootOnlyRoute {
        #[at("/")]
        Root
    }

    struct TestLabelProvider;

    impl BreadcrumbLabelProvider for TestLabelProvider {
        fn label_for_path(&self, path: &str) -> String {
            match path {
                "/" => "Home".to_string(),
                "/about" => "About".to_string(),
                "/docs" => "Docs".to_string(),
                "/docs/api" => "API".to_string(),
                "/docs/api/v1" => "V1".to_string(),
                "/users/42" => "User #42".to_string(),
                _ => path.to_string()
            }
        }
    }

    // ===== BreadcrumbItem tests =====

    #[test]
    fn breadcrumb_item_new() {
        let item = BreadcrumbItem {
            route:     SimpleRoute::Home,
            label:     "Home".to_string(),
            is_active: true
        };
        assert_eq!(item.label, "Home");
        assert!(item.is_active);
        assert_eq!(item.route.to_path(), "/");
    }

    #[test]
    fn breadcrumb_item_inactive() {
        let item = BreadcrumbItem {
            route:     SimpleRoute::About,
            label:     "About".to_string(),
            is_active: false
        };
        assert!(!item.is_active);
        assert_eq!(item.label, "About");
    }

    #[test]
    fn breadcrumb_item_clone_preserves_all_fields() {
        let item1 = BreadcrumbItem {
            route:     SimpleRoute::Api,
            label:     "Root".to_string(),
            is_active: true
        };
        let item2 = item1.clone();
        assert_eq!(item1, item2);
        assert_eq!(item2.label, "Root");
        assert!(item2.is_active);
    }

    #[test]
    fn breadcrumb_item_eq_with_same_values() {
        let item1 = BreadcrumbItem {
            route:     SimpleRoute::Home,
            label:     "Home".to_string(),
            is_active: true
        };
        let item2 = BreadcrumbItem {
            route:     SimpleRoute::Home,
            label:     "Home".to_string(),
            is_active: true
        };
        assert_eq!(item1, item2);
    }

    #[test]
    fn breadcrumb_item_neq_different_label() {
        let item1 = BreadcrumbItem {
            route:     SimpleRoute::Home,
            label:     "Home".to_string(),
            is_active: true
        };
        let item2 = BreadcrumbItem {
            route:     SimpleRoute::Home,
            label:     "Index".to_string(),
            is_active: true
        };
        assert_ne!(item1, item2);
    }

    #[test]
    fn breadcrumb_item_neq_different_state() {
        let item1 = BreadcrumbItem {
            route:     SimpleRoute::Home,
            label:     "Home".to_string(),
            is_active: true
        };
        let item2 = BreadcrumbItem {
            route:     SimpleRoute::Home,
            label:     "Home".to_string(),
            is_active: false
        };
        assert_ne!(item1, item2);
    }

    #[test]
    fn breadcrumb_item_neq_different_route() {
        let item1 = BreadcrumbItem {
            route:     SimpleRoute::Docs,
            label:     "Docs".to_string(),
            is_active: false
        };
        let item2 = BreadcrumbItem {
            route:     SimpleRoute::Api,
            label:     "Docs".to_string(),
            is_active: false
        };
        assert_ne!(item1, item2);
    }

    #[test]
    fn breadcrumb_item_debug_contains_all_fields() {
        let item = BreadcrumbItem {
            route:     SimpleRoute::Home,
            label:     "Home".to_string(),
            is_active: true
        };
        let debug_str = format!("{item:?}");
        assert!(debug_str.contains("BreadcrumbItem"));
        assert!(debug_str.contains("Home"));
        assert!(debug_str.contains("is_active"));
    }

    #[test]
    fn breadcrumb_item_long_label() {
        let label = "Extremely long breadcrumb label to test string handling in various scenarios"
            .to_string();
        let item = BreadcrumbItem {
            route:     SimpleRoute::Home,
            label:     label.clone(),
            is_active: false
        };
        assert_eq!(item.label, label);
        assert!(!item.is_active);
    }

    #[test]
    fn breadcrumb_item_short_label() {
        let item = BreadcrumbItem {
            route:     SimpleRoute::Home,
            label:     "a".to_string(),
            is_active: true
        };
        assert_eq!(item.label, "a");
    }

    #[test]
    fn breadcrumb_item_clone_deep_copy() {
        let item1 = BreadcrumbItem {
            route:     SimpleRoute::ApiV1,
            label:     "Deep".to_string(),
            is_active: true
        };
        let item2 = item1.clone();
        assert_eq!(item1, item2);
    }

    #[test]
    fn breadcrumb_item_root_path() {
        let item = BreadcrumbItem {
            route:     SimpleRoute::Home,
            label:     "/".to_string(),
            is_active: true
        };
        assert_eq!(item.route.to_path(), "/");
    }

    #[test]
    fn breadcrumb_item_nested_path() {
        let item = BreadcrumbItem {
            route:     SimpleRoute::ApiV1,
            label:     "/docs/api/v1".to_string(),
            is_active: true
        };
        assert_eq!(item.route.to_path(), "/docs/api/v1");
    }

    // ===== BreadcrumbLabelProvider tests =====

    #[test]
    fn breadcrumb_label_provider_returns_custom_labels() {
        let provider = TestLabelProvider;
        assert_eq!(provider.label_for_path("/"), "Home");
        assert_eq!(provider.label_for_path("/about"), "About");
        assert_eq!(provider.label_for_path("/docs/api/v1"), "V1");
    }

    #[test]
    fn breadcrumb_label_provider_returns_path_for_unknown() {
        let provider = TestLabelProvider;
        assert_eq!(provider.label_for_path("/unknown/path"), "/unknown/path");
        assert_eq!(provider.label_for_path("/missing"), "/missing");
    }

    #[test]
    fn breadcrumb_label_provider_empty_path_not_root() {
        let provider = TestLabelProvider;
        assert_ne!(provider.label_for_path(""), "Home");
    }

    #[test]
    fn breadcrumb_label_provider_whitespace() {
        let provider = TestLabelProvider;
        assert_eq!(provider.label_for_path("   "), "   ");
    }

    #[test]
    fn breadcrumb_label_provider_special_chars() {
        let provider = TestLabelProvider;
        assert_eq!(provider.label_for_path("@#$%"), "@#$%");
    }

    // ===== BreadcrumbLabelProviderContext tests =====

    #[test]
    fn context_eq_same_rc() {
        let rc = Rc::new(TestLabelProvider);
        let ctx1 = BreadcrumbLabelProviderContext(rc.clone());
        let ctx2 = BreadcrumbLabelProviderContext(rc);
        assert!(ctx1 == ctx2);
    }

    #[test]
    fn context_neq_different_rc() {
        let ctx1 = BreadcrumbLabelProviderContext(Rc::new(TestLabelProvider));
        let ctx2 = BreadcrumbLabelProviderContext(Rc::new(TestLabelProvider));
        assert!(ctx1 != ctx2);
    }

    #[test]
    fn context_clone_preserves_identity() {
        let rc = Rc::new(TestLabelProvider);
        let ctx1 = BreadcrumbLabelProviderContext(rc);
        let ctx2 = ctx1.clone();
        assert!(ctx1 == ctx2);
    }

    // ===== use_breadcrumbs tests =====

    #[test]
    fn use_breadcrumbs_simple_route() {
        let _result = use_breadcrumbs::<SimpleRoute>();
    }

    #[test]
    fn use_breadcrumbs_param_route() {
        let _result = use_breadcrumbs::<ParamRoute>();
    }

    #[test]
    fn use_breadcrumbs_multiple_calls() {
        let _r1 = use_breadcrumbs::<SimpleRoute>();
        let _r2 = use_breadcrumbs::<SimpleRoute>();
        let _r3 = use_breadcrumbs::<SimpleRoute>();
    }

    #[test]
    fn use_breadcrumbs_root_only_route() {
        let _result = use_breadcrumbs::<RootOnlyRoute>();
    }

    #[test]
    fn use_breadcrumbs_all_route_types() {
        let _simple = use_breadcrumbs::<SimpleRoute>();
        let _param = use_breadcrumbs::<ParamRoute>();
        let _root = use_breadcrumbs::<RootOnlyRoute>();
    }

    // ===== Negative tests =====

    #[test]
    fn breadcrumb_item_neq_negatives() {
        let item1 = BreadcrumbItem {
            route:     SimpleRoute::Home,
            label:     "Home".to_string(),
            is_active: true
        };
        let mut item2 = item1.clone();
        item2.label = "Other".to_string();
        assert_ne!(item1, item2);
        item2.is_active = false;
        assert_ne!(item1, item2);
    }
}