Skip to main content

pax_std/core/
router.rs

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