Skip to main content

pax_std/core/
router.rs

1#[allow(unused)]
2use crate::*;
3use pax_engine::api::{Duration, Opacity, Property};
4use pax_engine::pax;
5use pax_runtime::api::NodeContext;
6
7/// Declarative route reader that selects one active [`Route`] child subtree.
8///
9/// `Router` is a control-flow primitive: it does not render by itself.
10/// Instead, it matches the current location against its child `Route` branches
11/// and mounts only the winning subtree.
12///
13/// The active subtree receives an implicit `route` binding with:
14///
15/// - `route.location`: the location scoped to this router
16/// - `route.global_location`: the full browser/native location
17/// - `route.params`: named captures from `:param` segments
18/// - `route.remainder`: the unmatched tail after this branch
19/// - `route.is_exact` and `route.consumed_segments`: match metadata
20///
21/// Nested routers match against the nearest ancestor `route.remainder` by
22/// default, which keeps route trees composable without manual string slicing.
23#[pax]
24#[engine_import_path("pax_engine")]
25#[inlined(<Group/>)]
26pub struct Router {}
27
28/// Default route branch shell consumed by a parent [`Router`].
29///
30/// Use `path` for explicit path matching, `:param` for single-segment capture,
31/// and a terminal `*` to consume the remaining tail. Use `default=true` to
32/// provide the fallback branch when no explicit path matches.
33#[pax]
34#[engine_import_path("pax_engine")]
35#[route_branch(path = "path", default = "default")]
36#[inlined(
37    <Group width=100% height=100% anchor_x=0% anchor_y=0%>
38        for i in 0..self._projected_children_count {
39            slot(i)
40        }
41    </Group>
42
43    @settings {
44        @mount: on_mount
45    }
46)]
47pub struct Route {
48    /// Static route pattern, e.g. `/docs/:slug` or `/settings/*`.
49    ///
50    /// Patterns are matched against the current router scope, not always the
51    /// full global path. At the root router, that scope is the full location.
52    pub path: Property<String>,
53    /// Fallback branch used when no `path` branch matches.
54    pub r#default: Property<bool>,
55    // Number of slotted children rendered by the route shell.
56    pub _projected_children_count: Property<usize>,
57}
58
59/// Stacked route branch consumed by a parent [`Router`].
60///
61/// `RouteModal` matches like [`Route`], but it keeps the previously mounted
62/// branch active underneath while the modal branch is active. The shell fades a
63/// black scrim over the retained branch; the route's own contents are
64/// responsible for any modal-specific enter/exit transition.
65#[pax]
66#[engine_import_path("pax_engine")]
67#[custom(Default)]
68#[route_branch(path = "path", default = "default", modal = true)]
69#[inlined(
70    <Group width=100% height=100% anchor_x=0% anchor_y=0%>
71        <Group width=100% height=100% anchor_x=0% anchor_y=0%>
72            for i in 0..self._projected_children_count {
73                slot(i)
74            }
75        </Group>
76        <EventBlocker
77            width=100%
78            height=100%
79            background=rgba(0, 0, 0, 255)
80            opacity={self.scrim_opacity}
81            @in=@timeline {
82                duration: {self.duration},
83                opacity: {
84                    0: 0, Linear,
85                    100%: {$base},
86                },
87            }
88            @out=@timeline {
89                duration: {self.duration},
90                opacity: {
91                    0: {$base}, Linear,
92                    100%: 0,
93                },
94            }
95        />
96    </Group>
97
98    @settings {
99        @mount: on_mount
100    }
101)]
102pub struct RouteModal {
103    /// Static route pattern, e.g. `/tools`.
104    pub path: Property<String>,
105    /// Fallback modal branch used when no `path` branch matches.
106    pub r#default: Property<bool>,
107    /// Duration for the generated modal scrim enter/exit transition.
108    pub duration: Property<Duration>,
109    /// Maximum opacity for the black scrim over the retained background.
110    /// Unitless values are normalized alpha (`0.3` is 30%); percentages such
111    /// as `30%` are also supported.
112    pub scrim_opacity: Property<Opacity>,
113    // Number of slotted children rendered by the modal route shell.
114    pub _projected_children_count: Property<usize>,
115}
116
117/// Declarative route branch presented as a card over the current route.
118///
119/// `RouteCard` is consumed by a parent [`Router`] like [`Route`], but the
120/// presentation behavior is owned by this component shell. It retains the
121/// previously mounted branch underneath so the incoming or outgoing card slides
122/// over stable content while a black scrim fades over the retained branch. The
123/// route's own contents may still declare additional element or component
124/// lifecycle transitions.
125#[pax]
126#[engine_import_path("pax_engine")]
127#[custom(Default)]
128#[route_branch(path = "path", default = "default", modal = true)]
129#[inlined(
130    <Group width=100% height=100% anchor_x=0% anchor_y=0%>
131        <Group
132            id=card_shell
133            width=100%
134            height=100%
135            anchor_x=0%
136            anchor_y=0%
137            @in=@timeline {
138                duration: {self.duration},
139                x: {
140                    0: {self.edge == RouteCardEdge::Leading ? $base - 100% : self.edge == RouteCardEdge::Trailing ? $base + 100% : $base}, OutQuad,
141                    100%: {$base},
142                },
143                y: {
144                    0: {self.edge == RouteCardEdge::Top ? $base - 100% : self.edge == RouteCardEdge::Bottom ? $base + 100% : $base}, OutQuad,
145                    100%: {$base},
146                },
147            }
148            @out=@timeline {
149                duration: {self.duration},
150                x: {
151                    0: {$base}, OutQuad,
152                    100%: {self.edge == RouteCardEdge::Leading ? $base - 100% : self.edge == RouteCardEdge::Trailing ? $base + 100% : $base},
153                },
154                y: {
155                    0: {$base}, OutQuad,
156                    100%: {self.edge == RouteCardEdge::Top ? $base - 100% : self.edge == RouteCardEdge::Bottom ? $base + 100% : $base},
157                },
158            }
159        >
160            for i in 0..self._projected_children_count {
161                slot(i)
162            }
163        </Group>
164        <EventBlocker
165            width=100%
166            height=100%
167            background=rgba(0, 0, 0, 255)
168            opacity={self.scrim_opacity}
169            @in=@timeline {
170                duration: {self.duration},
171                opacity: {
172                    0: 0, Linear,
173                    100%: {$base},
174                },
175            }
176            @out=@timeline {
177                duration: {self.duration},
178                opacity: {
179                    0: {$base}, Linear,
180                    100%: 0,
181                },
182            }
183        />
184    </Group>
185
186    @settings {
187        @mount: on_mount
188    }
189)]
190pub struct RouteCard {
191    /// Static route pattern, e.g. `/details/:id`.
192    pub path: Property<String>,
193    /// Fallback card branch used when no `path` branch matches.
194    pub r#default: Property<bool>,
195    /// Edge used by the generated card enter/exit transition.
196    pub edge: Property<RouteCardEdge>,
197    /// Duration for the generated card enter/exit transition.
198    pub duration: Property<Duration>,
199    /// Maximum opacity for the black scrim over the retained background.
200    /// Unitless values are normalized alpha (`0.3` is 30%); percentages such
201    /// as `30%` are also supported.
202    pub scrim_opacity: Property<Opacity>,
203    /// Reserved easing tuning for the card enter/exit transition.
204    pub curve: Property<RouteCardCurve>,
205    // Number of slotted children rendered by the card shell.
206    pub _projected_children_count: Property<usize>,
207}
208
209/// Edge used by [`RouteCard`] transitions.
210#[pax]
211#[engine_import_path("pax_engine")]
212pub enum RouteCardEdge {
213    Leading,
214    #[default]
215    Trailing,
216    Top,
217    Bottom,
218}
219
220/// Reserved easing curve values for [`RouteCard`] transition tuning.
221#[pax]
222#[engine_import_path("pax_engine")]
223pub enum RouteCardCurve {
224    Linear,
225    Hold,
226    InQuad,
227    #[default]
228    OutQuad,
229    InOutQuad,
230    InBack,
231    OutBack,
232    InOutBack,
233}
234
235impl Route {
236    pub fn on_mount(&mut self, ctx: &NodeContext) {
237        let projected_children_count = ctx.projected_children_count.clone();
238        let deps = [projected_children_count.untyped()];
239        self._projected_children_count
240            .replace_with(Property::computed(
241                move || projected_children_count.get(),
242                &deps,
243            ));
244    }
245}
246
247impl Default for RouteModal {
248    fn default() -> Self {
249        Self {
250            path: Property::default(),
251            r#default: Property::new(false),
252            duration: Property::new(Duration::Frames(18.into())),
253            scrim_opacity: Property::new(Opacity::Alpha(0.3.into())),
254            _projected_children_count: Property::new(0),
255        }
256    }
257}
258
259impl RouteModal {
260    pub fn on_mount(&mut self, ctx: &NodeContext) {
261        let projected_children_count = ctx.projected_children_count.clone();
262        let deps = [projected_children_count.untyped()];
263        self._projected_children_count
264            .replace_with(Property::computed(
265                move || projected_children_count.get(),
266                &deps,
267            ));
268    }
269}
270
271impl Default for RouteCard {
272    fn default() -> Self {
273        Self {
274            path: Property::default(),
275            r#default: Property::new(false),
276            edge: Property::new(RouteCardEdge::Trailing),
277            duration: Property::new(Duration::Frames(18.into())),
278            scrim_opacity: Property::new(Opacity::Alpha(0.3.into())),
279            curve: Property::new(RouteCardCurve::OutQuad),
280            _projected_children_count: Property::new(0),
281        }
282    }
283}
284
285impl RouteCard {
286    pub fn on_mount(&mut self, ctx: &NodeContext) {
287        let projected_children_count = ctx.projected_children_count.clone();
288        let deps = [projected_children_count.untyped()];
289        self._projected_children_count
290            .replace_with(Property::computed(
291                move || projected_children_count.get(),
292                &deps,
293            ));
294    }
295}