leptos_forge 0.6.3

Build and test your Leptos components
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
//! Module provides a helpers to create navigation links in the application

use std::fmt::Debug;

use leptos::prelude::*;
use leptos_router::StaticSegment;
use leptos_router::any_nested_route::AnyNestedRoute;
use leptos_router::any_nested_route::IntoAnyNestedRoute;
use leptos_router::components::Route;
use leptos_router::components::RouteProps;
use reactive_stores::Store;
use ui_components::menu::MenuHeader;
use ui_components::menu::MenuState;
use ui_components::menu::Navigate;
use ui_components::primitives::markdown::Markdown;
use utils::prelude::ThreadSafe;

use crate::IntoStory;
use crate::views::story::EmbeddedStory;

use super::Section;
use super::story::Story;
use super::views::section;
use super::views::story::Story;

/// Allows specifying paths of various length (up to 9) and convert it into
/// a [Route] from static iterable tree of [RouteDef]
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum PathSpec {
    /// Just a root of the path, aka "/"
    Root,
    /// Single level path
    ///
    /// For example: `/level1`
    Level1(&'static str),
    /// Path with two levels
    ///
    /// For example `/home/bathroom`
    Level2(&'static str, &'static str),
    /// Path with three levels
    Level3(&'static str, &'static str, &'static str),
    /// Path with four levels
    Level4(&'static str, &'static str, &'static str, &'static str),
    /// Path with five levels
    Level5(
        &'static str,
        &'static str,
        &'static str,
        &'static str,
        &'static str,
    ),
    /// Path with six levels
    Level6(
        &'static str,
        &'static str,
        &'static str,
        &'static str,
        &'static str,
        &'static str,
    ),
    /// Path with seven levels
    Level7(
        &'static str,
        &'static str,
        &'static str,
        &'static str,
        &'static str,
        &'static str,
        &'static str,
    ),
    /// Path with eight levels
    Level8(
        &'static str,
        &'static str,
        &'static str,
        &'static str,
        &'static str,
        &'static str,
        &'static str,
        &'static str,
    ),
    /// Path with nine levels
    Level9(
        &'static str,
        &'static str,
        &'static str,
        &'static str,
        &'static str,
        &'static str,
        &'static str,
        &'static str,
        &'static str,
    ),
}

impl PathSpec {
    /// Converts a path into a route with given view
    ///
    /// # Arguments
    ///
    /// * view - leptos component
    ///
    /// # Returns
    ///
    /// Returns a route with given path and view
    ///
    pub fn as_route<F>(&self, view: F) -> AnyNestedRoute
    where
        F: Fn() -> AnyView + ThreadSafe + Clone,
    {
        use PathSpec::*;

        match self {
            Root => Route(
                RouteProps::builder()
                    .view(view)
                    .path(StaticSegment("/"))
                    .build(),
            )
            .into_any_nested_route(),
            Level1(seg1) => Route(
                RouteProps::builder()
                    .view(view)
                    .path(StaticSegment(*seg1))
                    .build(),
            )
            .into_any_nested_route(),
            Level2(seg1, seg2) => Route(
                RouteProps::builder()
                    .view(view)
                    .path((StaticSegment(*seg1), StaticSegment(*seg2)))
                    .build(),
            )
            .into_any_nested_route(),
            Level3(seg1, seg2, seg3) => Route(
                RouteProps::builder()
                    .view(view)
                    .path((
                        StaticSegment(*seg1),
                        StaticSegment(*seg2),
                        StaticSegment(*seg3),
                    ))
                    .build(),
            )
            .into_any_nested_route(),
            Level4(seg1, seg2, seg3, seg4) => Route(
                RouteProps::builder()
                    .view(view)
                    .path((
                        StaticSegment(*seg1),
                        StaticSegment(*seg2),
                        StaticSegment(*seg3),
                        StaticSegment(*seg4),
                    ))
                    .build(),
            )
            .into_any_nested_route(),
            Level5(seg1, seg2, seg3, seg4, seg5) => Route(
                RouteProps::builder()
                    .view(view)
                    .path((
                        StaticSegment(*seg1),
                        StaticSegment(*seg2),
                        StaticSegment(*seg3),
                        StaticSegment(*seg4),
                        StaticSegment(*seg5),
                    ))
                    .build(),
            )
            .into_any_nested_route(),
            Level6(seg1, seg2, seg3, seg4, seg5, seg6) => Route(
                RouteProps::builder()
                    .view(view)
                    .path((
                        StaticSegment(*seg1),
                        StaticSegment(*seg2),
                        StaticSegment(*seg3),
                        StaticSegment(*seg4),
                        StaticSegment(*seg5),
                        StaticSegment(*seg6),
                    ))
                    .build(),
            )
            .into_any_nested_route(),
            Level7(seg1, seg2, seg3, seg4, seg5, seg6, seg7) => Route(
                RouteProps::builder()
                    .view(view)
                    .path((
                        StaticSegment(*seg1),
                        StaticSegment(*seg2),
                        StaticSegment(*seg3),
                        StaticSegment(*seg4),
                        StaticSegment(*seg5),
                        StaticSegment(*seg6),
                        StaticSegment(*seg7),
                    ))
                    .build(),
            )
            .into_any_nested_route(),
            Level8(seg1, seg2, seg3, seg4, seg5, seg6, seg7, seg8) => Route(
                RouteProps::builder()
                    .view(view)
                    .path((
                        StaticSegment(*seg1),
                        StaticSegment(*seg2),
                        StaticSegment(*seg3),
                        StaticSegment(*seg4),
                        StaticSegment(*seg5),
                        StaticSegment(*seg6),
                        StaticSegment(*seg7),
                        StaticSegment(*seg8),
                    ))
                    .build(),
            )
            .into_any_nested_route(),
            Level9(seg1, seg2, seg3, seg4, seg5, seg6, seg7, seg8, seg9) => Route(
                RouteProps::builder()
                    .view(view)
                    .path((
                        StaticSegment(*seg1),
                        StaticSegment(*seg2),
                        StaticSegment(*seg3),
                        StaticSegment(*seg4),
                        StaticSegment(*seg5),
                        StaticSegment(*seg6),
                        StaticSegment(*seg7),
                        StaticSegment(*seg8),
                        StaticSegment(*seg9),
                    ))
                    .build(),
            )
            .into_any_nested_route(),
        }
    }

    /// Expands the instance of PathSpec with another segment
    ///
    /// For example:
    ///
    /// ```rust
    ///
    /// # use leptos_forge::navigation::PathSpec;
    ///
    /// let root = PathSpec::Root; // root = `/` path in URL
    /// let components = root.extend("components"); // components = `/components` path in URL
    ///
    /// assert_eq!(components, PathSpec::Level1("components"))
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if returned level would need to be above 9
    pub fn extend(&self, next_segment: &'static str) -> Self {
        use PathSpec::*;

        match self {
            Root => Level1(next_segment),
            Level1(seg1) => Level2(seg1, next_segment),
            Level2(seg1, seg2) => Level3(seg1, seg2, next_segment),
            Level3(seg1, seg2, seg3) => Level4(seg1, seg2, seg3, next_segment),
            Level4(seg1, seg2, seg3, seg4) => Level5(seg1, seg2, seg3, seg4, next_segment),
            Level5(seg1, seg2, seg3, seg4, seg5) => {
                Level6(seg1, seg2, seg3, seg4, seg5, next_segment)
            }
            Level6(seg1, seg2, seg3, seg4, seg5, seg6) => {
                Level7(seg1, seg2, seg3, seg4, seg5, seg6, next_segment)
            }
            Level7(seg1, seg2, seg3, seg4, seg5, seg6, seg7) => {
                Level8(seg1, seg2, seg3, seg4, seg5, seg6, seg7, next_segment)
            }
            Level8(seg1, seg2, seg3, seg4, seg5, seg6, seg7, seg8) => {
                Level9(seg1, seg2, seg3, seg4, seg5, seg6, seg7, seg8, next_segment)
            }
            _ => panic!("Nesting above level 9 is not supported"),
        }
    }

    /// Creates a navigation element in the main menu
    pub fn as_navigation_view(
        &self,
        label: &'static str,
        location: &str,
        store: Store<MenuState>,
    ) -> AnyView {
        use PathSpec::*;

        match self {
            // we are using `border-l-0!` as a hack to remove the left border which looks nicely when we use headers, but not so nice when we don't
            Root => view!{ <Navigate to="/" label=label class="ml-6 border-l-0!" location store/> }.into_any(),
            // we are using `border-l-0!` as a hack to remove the left border which looks nicely when we use headers, but not so nice when we don't
            Level1(seg1) => view!{ <Navigate to=format!("/{seg1}") label=label class="ml-6 border-l-0!" location store/> }.into_any(),
            Level2(seg1, seg2) => view!{ <Navigate to=format!("/{seg1}/{seg2}") label=label class="ml-6 pl-6" location store/> }.into_any(),
            Level3(seg1, seg2, seg3) => view!{ <Navigate to=format!("/{seg1}/{seg2}/{seg3}") label=label class="ml-6 pl-9" location store/> }.into_any(),
            Level4(seg1, seg2, seg3, seg4) => view!{ <Navigate to=format!("/{seg1}/{seg2}/{seg3}/{seg4}") label=label class="ml-6 pl-12" location store/> }.into_any(),
            Level5(seg1, seg2, seg3, seg4, seg5) => view!{ <Navigate to=format!("/{seg1}/{seg2}/{seg3}/{seg4}/{seg5}") label=label class="ml-6 pl-15" location store/> }.into_any(),
            Level6(seg1, seg2, seg3, seg4, seg5, seg6) => view!{ <Navigate to=format!("/{seg1}/{seg2}/{seg3}/{seg4}/{seg5}/{seg6}") label=label class="ml-6 pl-18" location store/> }.into_any(),
            Level7(seg1, seg2, seg3, seg4, seg5, seg6, seg7) => view!{ <Navigate to=format!("/{seg1}/{seg2}/{seg3}/{seg4}/{seg5}/{seg6}/{seg7}") label=label class="ml-6 pl-21" location store/> }.into_any(),
            Level8(seg1, seg2, seg3, seg4, seg5, seg6, seg7, seg8) => view!{ <Navigate to=format!("/{seg1}/{seg2}/{seg3}/{seg4}/{seg5}/{seg6}/{seg7}/{seg8}") label=label class="ml-6 pl-24" location store/> }.into_any(),
            Level9(seg1, seg2, seg3, seg4, seg5, seg6, seg7, seg8, seg9) => view!{ <Navigate to=format!("/{seg1}/{seg2}/{seg3}/{seg4}/{seg5}/{seg6}/{seg7}/{seg8}/{seg9}") label=label class="ml-6 pl-27" location store/> }.into_any(),
        }
    }
}

/// Define routes in the application
#[derive(Debug, Clone)]
pub enum RouteDef {
    /// Menu entry which can be navigated
    Route {
        /// path segment in the url
        path: &'static str,
        /// Label in the menu
        label: &'static str,
        /// component to render when the route is matched
        component: fn() -> AnyView,
        /// optional children for nested routes
        subroutes: Vec<RouteDef>,
        /// Returns the view embedded in the section
        ///
        /// # Arguments
        ///
        /// - **view** - wherever we should show the canvas.
        ///   
        ///   Current embedding code hard codes this to true since it wouldn't
        ///   make a lot of sense to do otherwise currently due to the fact that
        ///   every embedding is on it's own.
        ///
        /// - **controls** - wherever we should show controls
        /// - **description** - wherever we should show description of the story
        ///
        ///   Current version of the Markdown parser doesn't allow to set this
        ///   value.
        ///
        /// # Embedding in the section
        ///
        /// Inside the Markdown returned from [Section::description] method
        /// you can add the `<Story />` tag. It has the following boolean attributes
        ///
        /// - **controls**
        ///
        ///
        /// The code below will enable all of the before mentioned attributes
        ///
        /// ```markdown
        ///
        /// <Story of="path/to/the/substory" controls />
        ///
        /// ```
        ///
        ///
        embedded: fn(view: bool, controls: bool, description: bool) -> AnyView,
        /// Wherever this route should be hidden from the menu/router but still
        /// provide to the story embedding resolution
        ///
        /// hidden entry hides it's all children
        private: bool,
    },
    /// Grouping for a set of routes without any path to be taken
    Header {
        /// path part in the url
        path: &'static str,
        /// Header label in the menu
        label: &'static str,
        /// optional children for nested routes
        subroutes: Vec<RouteDef>,
    },
}

impl RouteDef {
    /// Returns the path of the route
    pub fn path(&self) -> &'static str {
        use RouteDef::*;
        match self {
            Route { path, .. } | Header { path, .. } => path,
        }
    }

    /// Returns a list of subroutes for this route
    pub fn subroutes(&self) -> &Vec<RouteDef> {
        use RouteDef::*;
        match self {
            Route { subroutes, .. } | Header { subroutes, .. } => subroutes,
        }
    }

    /// Extends a prefix path while detecting a "root" path
    ///
    /// # For RouteDef::Route
    ///
    /// Patch which only contains the `/` are considered as root paths
    /// and they return the prefix directly.
    ///
    /// You can use this to create a root path for your routes
    ///
    /// # For RouteDef::Header
    ///
    /// It just returns a `PathSpec` since headers do not contribute to
    /// path
    fn extend(&self, prefix: PathSpec) -> PathSpec {
        use RouteDef::*;
        match self {
            Route { path, .. } | Header { path, .. } => {
                if *path == "/" {
                    prefix
                } else {
                    prefix.extend(path)
                }
            }
        }
    }

    /// Converts the route to list of routes that can be used in `leptos_router`
    pub fn as_routes(&self, prefix: PathSpec) -> Vec<AnyNestedRoute> {
        use RouteDef::*;
        match self {
            Route {
                component,
                subroutes,
                ..
            } => {
                let my_path: PathSpec = self.extend(prefix);

                let mut routes: Vec<AnyNestedRoute> = vec![my_path.as_route(*component)];

                routes.extend(
                    subroutes
                        .iter()
                        .filter(|r| {
                            match r {
                                RouteDef::Route { private, .. } => !private,
                                _ => true, // I seriously don't understand what is should mean, but hey
                            }
                        })
                        .flat_map(|r| r.as_routes(my_path)),
                );

                routes
            }
            Header { subroutes, .. } => {
                let my_path: PathSpec = self.extend(prefix);
                let mut routes: Vec<AnyNestedRoute> = vec![];

                routes.extend(
                    subroutes
                        .iter()
                        .filter(|r| {
                            match r {
                                RouteDef::Route { private, .. } => !private,
                                _ => true, // I seriously don't understand what is should mean, but hey
                            }
                        })
                        .flat_map(|r| r.as_routes(my_path)),
                );

                routes
            }
        }
    }

    /// Builds menu items
    pub fn as_menu_items(
        &self,
        prefix: PathSpec,
        location: &str,
        store: Store<MenuState>,
    ) -> Vec<AnyView> {
        use RouteDef::*;
        match self {
            Route {
                label, subroutes, ..
            } => {
                let my_path: PathSpec = self.extend(prefix);

                let mut views = vec![my_path.as_navigation_view(label, location, store)];

                views.extend(
                    subroutes
                        .iter()
                        .filter(|r| {
                            match r {
                                RouteDef::Route { private, .. } => !private,
                                _ => true, // I seriously don't understand what is should mean, but hey
                            }
                        })
                        .flat_map(|r| r.as_menu_items(my_path, location, store)),
                );

                views
            }
            Header {
                label, subroutes, ..
            } => {
                let my_path: PathSpec = self.extend(prefix);

                let mut views = vec![
                    (view! {
                        <MenuHeader label class="" />
                    })
                    .into_any(),
                ];

                views.extend(
                    subroutes
                        .iter()
                        .filter(|r| {
                            match r {
                                RouteDef::Route { private, .. } => !private,
                                _ => true, // I seriously don't understand what is should mean, but hey
                            }
                        })
                        .flat_map(|r| r.as_menu_items(my_path, location, store)),
                );

                views
            }
        }
    }

    /// Creates a new page route with a story and it's related sub-stories
    pub fn story<S: 'static + IntoStory + Default + Copy + ThreadSafe>(
        path: &'static str,
        label: &'static str,
    ) -> RouteDef {
        RouteDef::Route {
            path,
            label,
            component: || view! { <Story<S> /> }.into_any(),
            embedded: |view, controls, description| {
                view! {
                    <EmbeddedStory<S> view  controls description />
                }
                .into_any()
            },
            subroutes: S::default().into_story().subroutes(),
            private: false,
        }
    }

    /// Creates a new private route with a story and it's related sub-stories
    ///
    /// Private story can't be routed into, but still can be embedded into the
    /// section
    ///
    /// It's useful when you need to embed the story in some super generic sections
    /// which needs an interactive example but are not really a story of some
    /// component.
    ///
    /// You can also use it to add custom features for your documentation
    /// which are not supported by the `leptos_forge`.
    pub fn private<S: 'static + IntoStory + Default + Copy + ThreadSafe>(
        path: &'static str,
        label: &'static str,
    ) -> RouteDef {
        RouteDef::Route {
            path,
            label,
            component: || view! { <Story<S> /> }.into_any(),
            embedded: |view, controls, description| {
                view! {
                    <EmbeddedStory<S> view  controls description />
                }
                .into_any()
            },
            subroutes: S::default().into_story().subroutes(),
            private: true,
        }
    }

    /// Creates a new section route
    ///
    /// Section creates a new Markdown only page, It's intended use is
    /// to group a bunch of related [pages][RouteDef::page]
    /// and [story][RouteDef::story]
    /// together
    pub fn section<S: 'static + Section + Default + Copy + Send>(
        path: &'static str,
        label: &'static str,
    ) -> RouteDef {
        //
        // Remember to update when changed
        //
        // - site `usage/sections` - it contains the documentation on calling this function as
        //   as part of adding the section to your site.
        //

        RouteDef::Route {
            path,
            label,
            component: || view! { <section::Section<S> /> }.into_any(),
            embedded: |_, _, _| {
                view! { <Markdown src="> Embedding sections is not allowed"  /> }.into_any()
            },
            subroutes: S::default().subroutes(),
            private: false,
        }
    }

    /// Creates a header in the menu
    ///
    /// Header doesn't contribute to the routing path but provides
    /// a visual named separator and header for parts of the group
    /// of routes in the left hand side menu
    pub fn header(path: &'static str, label: &'static str, subroutes: Vec<RouteDef>) -> RouteDef {
        RouteDef::Header {
            path,
            label,
            subroutes,
        }
    }
}