@tarve/router 0.0.0-stage → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,60 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # @tarve/router
2
+
3
+ Stack and tab navigation for [Tarve](https://github.com/omarcosr/tarve) apps.
4
+
5
+ ```tsx
6
+ import { Button, Text, Window, createApp } from "@tarve/core";
7
+ import { RouterView, Link, createStackRouter, route } from "@tarve/router";
8
+
9
+ const router = createStackRouter({
10
+ transition: "slide", // "none" (default) | "fade" | "slide" | { push, pop?, transition? }
11
+ routes: {
12
+ home: route("/", () => <Link to="/users/42">User 42</Link>),
13
+ user: route("/users/:id", ({ params, router }) => ( // params: { id: string }
14
+ <Button onClick={() => router.pop()}>Back from {params.id}</Button>
15
+ )),
16
+ notFound: route("*", () => <Text>Not found</Text>),
17
+ },
18
+ });
19
+
20
+ const app = createApp(() => (
21
+ <Window title="App" onCloseRequest={router.onCloseRequest}> {/* Android back key pops */}
22
+ <RouterView router={router} /> {/* Escape pops */}
23
+ </Window>
24
+ ), { pointerEvents: true }); // mouse back button
25
+ router.attach(app); // Alt+Left, mouse back, renders after async navigations
26
+ ```
27
+
28
+ ## Stack router
29
+
30
+ `createStackRouter({ routes, initial?, transition?, backOnCloseRequest?, onChange?, id? })`
31
+
32
+ - `push(name, params?, { state?, query? })`, `replace(...)`: params typed from the path (`:id` required, `:tab?` optional, `*` splat).
33
+ - `pop(count = 1)`, `popToRoot()`, `back()`, `canGoBack()`, `reset(path?)`.
34
+ - `navigate("/users/42?tab=posts", { replace? })`: the most specific matching route (static > `:param` > `:param?`, `*` last); `undefined` when nothing matches. Navigating to the screen already on top changes nothing.
35
+ - `route` (top, a union discriminated by `name`), `stack`, `lastChange`, `href(name, params)`, `match(path)`, `title(route?)`, `subscribe(listener)`.
36
+
37
+ ## Tab router
38
+
39
+ `createTabRouter({ tabs: { feed: { title, icon?, routes, initial? }, … }, initialTab?, backBehavior?, reselectToRoot?, transition? })`
40
+
41
+ Every tab keeps its own stack (`stack(name)`, typed per tab; `current` is the active one). `select(tab)` switches (selecting the active tab pops it to its root); `navigate(path)` finds the tab owning the path, active tab first; `back()` pops the active stack, then returns to the initial tab (`backBehavior: "history"` walks visited tabs, `"none"` stops). Render it with `<TabRouterView router={tabs} placement="bottom" />`, or `<RouterView router={tabs} />` plus your own `<TabBar router={tabs} />`.
42
+
43
+ ## Reading the route
44
+
45
+ Screens get `{ route, params, router }`. Deeper components call `useRoute()`, `useParams()`, `useRouter()` (the router given to `RouterView`) or `useStack()` while rendering. Tarve has no component context: `RouterView` brackets each screen's subtree with empty marker components, so these read the screen being rendered; outside a `RouterView` they read the router created last.
46
+
47
+ ## Rendering
48
+
49
+ Navigation inside an event handler renders like any other state change. Outside handlers (a timer, a fetch), `router.attach(app)` makes the router call `app.update()`; without it the router updates the app that last handled an event.
50
+
51
+ ## Back
52
+
53
+ | Input | How |
54
+ | --- | --- |
55
+ | Escape | `RouterView` (`backOnEscape`, default on) while the router can go back; popups keep their own Escape. |
56
+ | Alt+Left | `router.attach(app)` (`hotkeys` option). |
57
+ | Mouse back button | `router.attach(app)` with `createApp(view, { pointerEvents: true })`. |
58
+ | Android back key | `<Window onCloseRequest={router.onCloseRequest}>`: native turns it into a close request. |
59
+
60
+ On Node.js, run apps with `tarve run --runtime node`, which bundles the sources.
package/package.json CHANGED
@@ -1,6 +1,43 @@
1
1
  {
2
2
  "name": "@tarve/router",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.10.0",
4
+ "description": "Stack and tab navigation for Tarve apps: typed path params, <RouterView>, <Link>, back keys and native screen transitions",
5
+ "license": "Apache-2.0",
6
+ "keywords": [
7
+ "tarve",
8
+ "router",
9
+ "navigation",
10
+ "stack",
11
+ "tabs"
12
+ ],
13
+ "homepage": "https://github.com/omarcosr/tarve/tree/main/packages/router#readme",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/omarcosr/tarve.git",
17
+ "directory": "packages/router"
18
+ },
19
+ "bugs": {
20
+ "url": "https://github.com/omarcosr/tarve/issues"
21
+ },
22
+ "publishConfig": {
23
+ "access": "public",
24
+ "provenance": true
25
+ },
26
+ "type": "module",
27
+ "exports": {
28
+ ".": "./src/index.ts"
29
+ },
30
+ "files": [
31
+ "src",
32
+ "!src/**/*.test.ts",
33
+ "!src/**/*.test.tsx",
34
+ "README.md"
35
+ ],
36
+ "peerDependencies": {
37
+ "@tarve/core": "^0.10.0"
38
+ },
39
+ "engines": {
40
+ "bun": ">=1.4.0",
41
+ "node": ">=26.10.0"
42
+ }
43
+ }
package/src/back.ts ADDED
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Back navigation wiring: desktop shortcuts and the mouse back button through an app handle,
3
+ * Android's hardware back through the window's close request. No Tarve runtime import.
4
+ */
5
+
6
+ /** What a router needs from `createApp(...)`'s handle; `AppHandle` satisfies it. */
7
+ export interface RouterApp {
8
+ update(): void;
9
+ registerHotkey?(shortcut: string, handler: () => void): () => void;
10
+ onEvent?(listener: (event: RouterAppEvent) => void): () => void;
11
+ }
12
+
13
+ /** The fields of a native event the router reads (`pointer` events need `createApp(view, { pointerEvents: true })`). */
14
+ export interface RouterAppEvent {
15
+ type: string;
16
+ phase?: string;
17
+ button?: number;
18
+ }
19
+
20
+ export interface BackTarget {
21
+ back(): boolean;
22
+ canGoBack(): boolean;
23
+ }
24
+
25
+ export interface AttachOptions {
26
+ /** Shortcuts that go back. Default `["Alt+Left"]`; `false` registers none. */
27
+ hotkeys?: readonly string[] | false;
28
+ /** The mouse's back button (button 3) goes back. Needs `pointerEvents: true` on the app. Default true. */
29
+ mouseBack?: boolean;
30
+ }
31
+
32
+ /** `<Window onCloseRequest>`'s event. */
33
+ export interface CloseRequestEvent {
34
+ preventDefault(): void;
35
+ }
36
+
37
+ /**
38
+ * When the window's close request means "back": `"android"` (default) only on Android, where the
39
+ * hardware back key asks to close the window; `"always"` also on desktops; `false` never.
40
+ */
41
+ export type BackOnCloseRequest = "android" | "always" | false;
42
+
43
+ /** The mouse button number native reports for the back button (winit `MouseButton::Back`). */
44
+ export const MOUSE_BACK_BUTTON = 3;
45
+
46
+ export function isAndroid(): boolean {
47
+ return typeof process !== "undefined" && (process.platform as string) === "android";
48
+ }
49
+
50
+ /** Registers the back shortcuts and mouse button of `target` on `app`; returns the undo. */
51
+ export function attachBack(app: RouterApp, target: BackTarget, options: AttachOptions = {}): () => void {
52
+ const undo: (() => void)[] = [];
53
+ const hotkeys = options.hotkeys === false ? [] : options.hotkeys ?? ["Alt+Left"];
54
+ if (app.registerHotkey) {
55
+ for (const shortcut of hotkeys) undo.push(app.registerHotkey(shortcut, () => { target.back(); }));
56
+ }
57
+ if (options.mouseBack !== false && app.onEvent) {
58
+ undo.push(app.onEvent(event => {
59
+ if (event.type === "pointer" && event.phase === "up" && event.button === MOUSE_BACK_BUTTON && target.back()) app.update();
60
+ }));
61
+ }
62
+ return () => {
63
+ for (const fn of undo.splice(0)) fn();
64
+ };
65
+ }
66
+
67
+ /** A `<Window onCloseRequest>` handler that goes back instead of closing while the router can. */
68
+ export function closeRequestBack(target: BackTarget, mode: BackOnCloseRequest): (event: CloseRequestEvent) => void {
69
+ return event => {
70
+ const handles = mode === "always" || (mode === "android" && isAndroid());
71
+ if (handles && target.canGoBack() && target.back()) event.preventDefault();
72
+ };
73
+ }
74
+
75
+ const ACTIVE_APP_KEY = Symbol.for("tarve.activeApp");
76
+
77
+ /**
78
+ * Asks for a render after a navigation. Inside an event handler Tarve renders anyway; outside one
79
+ * (a timer, a fetch) the attached apps, else the app that last handled an event, render.
80
+ */
81
+ export function requestRender(apps: ReadonlySet<RouterApp>): void {
82
+ if (apps.size > 0) {
83
+ for (const app of apps) app.update();
84
+ return;
85
+ }
86
+ const active = (globalThis as Record<symbol, { update?(): void } | undefined>)[ACTIVE_APP_KEY];
87
+ active?.update?.();
88
+ }
package/src/context.ts ADDED
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Tarve has no component context: views are plain functions expanded depth-first, in order.
3
+ * `<RouterView>` brackets each screen with two empty marker components, so while a screen's
4
+ * subtree renders, `useRoute()` sees that screen's route. Outside one it falls back to the
5
+ * router created last.
6
+ */
7
+ import type { Navigator, Route } from "./types";
8
+ import type { StackRouter } from "./stack";
9
+
10
+ export interface RouteScope {
11
+ /** The router the `<RouterView>` was given (a tab router for tab screens). */
12
+ navigator: Navigator;
13
+ /** The stack the screen belongs to. */
14
+ stack: StackRouter<any>;
15
+ route: Route;
16
+ }
17
+
18
+ const scopes: RouteScope[] = [];
19
+ let fallback: { navigator: Navigator; stack: () => StackRouter<any> } | undefined;
20
+
21
+ export function setDefaultRouter(navigator: Navigator, stack: () => StackRouter<any>): void {
22
+ fallback = { navigator, stack };
23
+ }
24
+
25
+ /** Opens a scope; `leaveScope` with the returned depth closes it (and any left open by a throw). */
26
+ export function enterScope(scope: RouteScope): number {
27
+ const depth = scopes.length;
28
+ scopes.push(scope);
29
+ return depth;
30
+ }
31
+
32
+ export function leaveScope(depth: number): void {
33
+ if (scopes.length > depth) scopes.length = depth;
34
+ }
35
+
36
+ /** The innermost scope, or the default router's. */
37
+ export function currentScope(): RouteScope | undefined {
38
+ const scope = scopes[scopes.length - 1];
39
+ if (scope) return scope;
40
+ if (!fallback) return undefined;
41
+ const stack = fallback.stack();
42
+ return { navigator: fallback.navigator, stack, route: fallback.navigator.route };
43
+ }
44
+
45
+ function required(): RouteScope {
46
+ const scope = currentScope();
47
+ if (!scope) throw new Error("No router: create one with createStackRouter or createTabRouter first");
48
+ return scope;
49
+ }
50
+
51
+ /**
52
+ * The route of the screen being rendered. Call it while rendering (event handlers should
53
+ * use the value read at render time). Pass the route type for typed params:
54
+ * `useRoute<Route<"user", { id: string }>>()`.
55
+ */
56
+ export function useRoute<R extends Route = Route>(): R {
57
+ return required().route as R;
58
+ }
59
+
60
+ export function useParams<P = Record<string, string>>(): P {
61
+ return required().route.params as P;
62
+ }
63
+
64
+ /** The router given to the enclosing `<RouterView>` (the tab router for tab screens). */
65
+ export function useRouter<N extends Navigator = Navigator>(): N {
66
+ return required().navigator as N;
67
+ }
68
+
69
+ /** The stack router the screen being rendered belongs to. */
70
+ export function useStack<S extends StackRouter<any> = StackRouter<any>>(): S {
71
+ return required().stack as S;
72
+ }
package/src/index.ts ADDED
@@ -0,0 +1,13 @@
1
+ export { createStackRouter, route } from "./stack";
2
+ export type { ParamsArgs, ParamsOf, RouteDefinition, RouteMap, RouteMatch, RouteName, RouteOf, Screen, ScreenProps, StackRouter, StackRouterOptions } from "./stack";
3
+ export { createTabRouter } from "./tabs";
4
+ export type { TabBackBehavior, TabDefinition, TabMap, TabName, TabRouter, TabRouterOptions } from "./tabs";
5
+ export { RouterView, TabRouterView, TabBar, Link, RouterLink } from "./view";
6
+ export type { RouterViewProps, TabRouterViewProps, TabBarProps, LinkProps } from "./view";
7
+ export { useRoute, useParams, useRouter, useStack } from "./context";
8
+ export { attachBack, closeRequestBack, isAndroid, MOUSE_BACK_BUTTON } from "./back";
9
+ export type { AttachOptions, BackOnCloseRequest, BackTarget, CloseRequestEvent, RouterApp, RouterAppEvent } from "./back";
10
+ export { buildPath, compilePath, matchPath, parseLocation } from "./path";
11
+ export type { CompiledPath, Location, PathParams, PathSegment } from "./path";
12
+ export { resolveTransition } from "./types";
13
+ export type { NavigateOptions, Navigator, ResolvedTransition, Route, RouteAction, RouteChange, RouterTransition, TransitionSide } from "./types";
package/src/path.ts ADDED
@@ -0,0 +1,144 @@
1
+ /**
2
+ * Path patterns: `/users/:id`, optional `/:tab?` and a trailing splat `/files/*`.
3
+ * Plain TypeScript with no Tarve import, so it runs on Bun and on Node's type stripping.
4
+ */
5
+
6
+ type Segments<P extends string> = P extends `${infer Head}/${infer Tail}` ? Head | Segments<Tail> : P;
7
+ type RequiredName<S> = S extends `:${infer Name}` ? (Name extends `${string}?` ? never : Name) : S extends "*" ? "*" : never;
8
+ type OptionalName<S> = S extends `:${infer Name}?` ? Name : never;
9
+ type Simplify<T> = { [K in keyof T]: T[K] } & {};
10
+
11
+ /** The params of a path pattern: `PathParams<"/users/:id/:tab?">` is `{ id: string; tab?: string }`. */
12
+ export type PathParams<P extends string> = string extends P
13
+ ? Record<string, string>
14
+ : Simplify<
15
+ { [K in RequiredName<Segments<P>>]: string } &
16
+ { [K in OptionalName<Segments<P>>]?: string }
17
+ >;
18
+
19
+ export type PathSegment =
20
+ | { kind: "static"; value: string }
21
+ | { kind: "param"; name: string; optional: boolean }
22
+ | { kind: "splat" };
23
+
24
+ export interface CompiledPath {
25
+ pattern: string;
26
+ segments: PathSegment[];
27
+ /** Higher is more specific: static segments beat params, params beat optional ones. */
28
+ score: number;
29
+ splat: boolean;
30
+ }
31
+
32
+ export interface Location {
33
+ pathname: string;
34
+ query: Record<string, string>;
35
+ }
36
+
37
+ function parts(path: string): string[] {
38
+ return path.split("/").filter(part => part.length > 0);
39
+ }
40
+
41
+ function decode(value: string): string {
42
+ try {
43
+ return decodeURIComponent(value);
44
+ } catch {
45
+ return value;
46
+ }
47
+ }
48
+
49
+ export function normalizePath(path: string): string {
50
+ const joined = "/" + parts(path).join("/");
51
+ return joined;
52
+ }
53
+
54
+ export function compilePath(pattern: string): CompiledPath {
55
+ if (typeof pattern !== "string") throw new TypeError("A route path must be a string");
56
+ // No query in a pattern: a trailing `?` marks an optional param.
57
+ const raw = parts(pattern);
58
+ const segments: PathSegment[] = [];
59
+ let score = 0;
60
+ raw.forEach((part, index) => {
61
+ if (part === "*") {
62
+ if (index !== raw.length - 1) throw new Error(`"*" must be the last segment of ${pattern}`);
63
+ segments.push({ kind: "splat" });
64
+ } else if (part.startsWith(":")) {
65
+ const optional = part.endsWith("?");
66
+ const name = part.slice(1, optional ? -1 : undefined);
67
+ if (!name) throw new Error(`Empty parameter name in ${pattern}`);
68
+ segments.push({ kind: "param", name, optional });
69
+ score += optional ? 2 : 3;
70
+ } else {
71
+ segments.push({ kind: "static", value: decode(part) });
72
+ score += 4;
73
+ }
74
+ });
75
+ return { pattern: normalizePath(pattern), segments, score, splat: segments.some(segment => segment.kind === "splat") };
76
+ }
77
+
78
+ /** Splits `/users/42?tab=posts#top` into its pathname and query. */
79
+ export function parseLocation(path: string): Location {
80
+ const withoutHash = path.split("#")[0]!;
81
+ const index = withoutHash.indexOf("?");
82
+ const pathname = normalizePath(index < 0 ? withoutHash : withoutHash.slice(0, index));
83
+ const query: Record<string, string> = {};
84
+ if (index >= 0) {
85
+ for (const [key, value] of new URLSearchParams(withoutHash.slice(index + 1))) query[key] = value;
86
+ }
87
+ return { pathname, query };
88
+ }
89
+
90
+ /** The params of `pathname` under `compiled`, or `undefined` when it does not match. */
91
+ export function matchPath(compiled: CompiledPath, pathname: string): Record<string, string> | undefined {
92
+ const actual = parts(pathname);
93
+ const walk = (segment: number, index: number, params: Record<string, string>): Record<string, string> | undefined => {
94
+ if (segment === compiled.segments.length) return index === actual.length ? params : undefined;
95
+ const current = compiled.segments[segment]!;
96
+ if (current.kind === "splat") return { ...params, "*": actual.slice(index).map(decode).join("/") };
97
+ if (current.kind === "static") {
98
+ return index < actual.length && decode(actual[index]!) === current.value ? walk(segment + 1, index + 1, params) : undefined;
99
+ }
100
+ if (index < actual.length) {
101
+ const matched = walk(segment + 1, index + 1, { ...params, [current.name]: decode(actual[index]!) });
102
+ if (matched) return matched;
103
+ }
104
+ return current.optional ? walk(segment + 1, index, params) : undefined;
105
+ };
106
+ return walk(0, 0, {});
107
+ }
108
+
109
+ function encodeQuery(query: Record<string, string> | undefined): string {
110
+ if (!query) return "";
111
+ const search = new URLSearchParams(query).toString();
112
+ return search ? `?${search}` : "";
113
+ }
114
+
115
+ /** Fills a pattern with params: `buildPath("/users/:id", { id: "42" })` is `/users/42`. */
116
+ export function buildPath(compiled: CompiledPath, params: Record<string, string | number | undefined> = {}, query?: Record<string, string>): string {
117
+ const out: string[] = [];
118
+ for (const segment of compiled.segments) {
119
+ if (segment.kind === "static") out.push(encodeURIComponent(segment.value));
120
+ else if (segment.kind === "splat") {
121
+ const rest = params["*"];
122
+ if (rest !== undefined && rest !== "") out.push(...parts(String(rest)).map(encodeURIComponent));
123
+ } else {
124
+ const value = params[segment.name];
125
+ if (value === undefined || value === "") {
126
+ if (segment.optional) continue;
127
+ throw new Error(`Missing parameter "${segment.name}" for ${compiled.pattern}`);
128
+ }
129
+ out.push(encodeURIComponent(String(value)));
130
+ }
131
+ }
132
+ return "/" + out.join("/") + encodeQuery(query);
133
+ }
134
+
135
+ /** Sorts patterns from most to least specific; a splat always comes last. Stable for ties. */
136
+ export function rankPaths<T extends { compiled: CompiledPath }>(entries: readonly T[]): T[] {
137
+ return entries
138
+ .map((entry, index) => ({ entry, index }))
139
+ .sort((a, b) =>
140
+ Number(a.entry.compiled.splat) - Number(b.entry.compiled.splat)
141
+ || b.entry.compiled.score - a.entry.compiled.score
142
+ || a.index - b.index)
143
+ .map(item => item.entry);
144
+ }
package/src/stack.ts ADDED
@@ -0,0 +1,252 @@
1
+ import type { VNode } from "@tarve/core";
2
+ import { attachBack, closeRequestBack, requestRender, type AttachOptions, type BackOnCloseRequest, type CloseRequestEvent, type RouterApp } from "./back";
3
+ import { setDefaultRouter } from "./context";
4
+ import { buildPath, compilePath, matchPath, parseLocation, rankPaths, type CompiledPath, type PathParams } from "./path";
5
+ import { resolveTransition, type NavigateOptions, type Navigator, type ResolvedTransition, type Route, type RouteChange, type RouterTransition } from "./types";
6
+
7
+ export interface ScreenProps<Params = Record<string, string>> {
8
+ route: Route<string, Params>;
9
+ params: Params;
10
+ /** The stack this screen belongs to. */
11
+ router: StackRouter<any>;
12
+ }
13
+
14
+ export type Screen<Params = any> = (props: ScreenProps<Params>) => VNode;
15
+
16
+ export interface RouteDefinition<P extends string = string> {
17
+ path: P;
18
+ screen: Screen<any>;
19
+ /** A title for headers and tab bars. */
20
+ title?: string | ((route: Route) => string);
21
+ /** Overrides the router's transition when this route enters or leaves. */
22
+ transition?: RouterTransition;
23
+ }
24
+
25
+ /** A route definition whose screen props are typed from the path: `route("/users/:id", ({ params }) => …)`. */
26
+ export function route<const P extends string>(
27
+ path: P,
28
+ screen: Screen<PathParams<P>>,
29
+ extra: Omit<RouteDefinition<P>, "path" | "screen"> = {},
30
+ ): RouteDefinition<P> {
31
+ return { ...extra, path, screen };
32
+ }
33
+
34
+ export type RouteMap = Record<string, RouteDefinition<string>>;
35
+ export type RouteName<R extends RouteMap> = keyof R & string;
36
+ export type ParamsOf<R extends RouteMap, K extends RouteName<R>> = PathParams<R[K]["path"]>;
37
+ export type RouteOf<R extends RouteMap> = { [K in RouteName<R>]: Route<K, ParamsOf<R, K>> }[RouteName<R>];
38
+ /** Params are required exactly when the path has a required `:param`. */
39
+ export type ParamsArgs<P> = {} extends P ? [params?: P, options?: NavigateOptions] : [params: P, options?: NavigateOptions];
40
+
41
+ export interface StackRouterOptions<R extends RouteMap> {
42
+ routes: R;
43
+ /** The root screen: a path (`"/"`) or a route name. Default: the first route. */
44
+ initial?: string;
45
+ /** Default `"none"`. */
46
+ transition?: RouterTransition;
47
+ /** See `BackOnCloseRequest`. Default `"android"`. */
48
+ backOnCloseRequest?: BackOnCloseRequest;
49
+ /** Called after every change. */
50
+ onChange?: (change: RouteChange<RouteOf<R>>) => void;
51
+ /** Prefix of route keys and native ids; default `stack<n>`. */
52
+ id?: string;
53
+ }
54
+
55
+ export interface RouteMatch<Name extends string = string> {
56
+ name: Name;
57
+ params: Record<string, string>;
58
+ query: Record<string, string>;
59
+ /** Matched through a `*` catch-all. */
60
+ splat: boolean;
61
+ }
62
+
63
+ export interface StackRouter<R extends RouteMap = RouteMap> extends Navigator {
64
+ readonly kind: "stack";
65
+ readonly routes: R;
66
+ /** The top of the stack: the screen on display. */
67
+ readonly route: RouteOf<R>;
68
+ /** Root first. */
69
+ readonly stack: readonly RouteOf<R>[];
70
+ readonly lastChange: RouteChange<RouteOf<R>> | undefined;
71
+ readonly transition: ResolvedTransition | undefined;
72
+ push<K extends RouteName<R>>(name: K, ...args: ParamsArgs<ParamsOf<R, K>>): Route<K, ParamsOf<R, K>>;
73
+ replace<K extends RouteName<R>>(name: K, ...args: ParamsArgs<ParamsOf<R, K>>): Route<K, ParamsOf<R, K>>;
74
+ /** Pops `count` entries (default 1), never the root; `false` when already at the root. */
75
+ pop(count?: number): boolean;
76
+ popToRoot(): boolean;
77
+ navigate(to: string, options?: NavigateOptions): RouteOf<R> | undefined;
78
+ /** The path of a route: `href("user", { id: 42 })` is `/users/42`. */
79
+ href<K extends RouteName<R>>(name: K, ...args: ParamsArgs<ParamsOf<R, K>>): string;
80
+ match(path: string): RouteMatch<RouteName<R>> | undefined;
81
+ /** Replaces the whole stack with one root entry (default: the initial route). */
82
+ reset(to?: string): void;
83
+ definition(name: RouteName<R>): RouteDefinition;
84
+ title(route?: Route): string | undefined;
85
+ subscribe(listener: (change: RouteChange<RouteOf<R>>) => void): () => void;
86
+ }
87
+
88
+ let routerCount = 0;
89
+
90
+ function sameEntry(a: Route, name: string, path: string): boolean {
91
+ return a.name === name && a.path === path;
92
+ }
93
+
94
+ /** Internal: lets a tab router own stacks without each one becoming the default router. */
95
+ export const OWNED = Symbol("tarve.router.owned");
96
+
97
+ /** A stack navigator: push/replace/pop screens, typed by the route map's paths. */
98
+ export function createStackRouter<const R extends RouteMap>(options: StackRouterOptions<R> & { [OWNED]?: boolean }): StackRouter<R> {
99
+ const { routes } = options;
100
+ const names = Object.keys(routes) as RouteName<R>[];
101
+ if (names.length === 0) throw new Error("createStackRouter needs at least one route");
102
+ const id = options.id ?? `stack${++routerCount}`;
103
+ const compiled = new Map<string, CompiledPath>();
104
+ for (const name of names) compiled.set(name, compilePath(routes[name]!.path));
105
+ const ranked = rankPaths(names.map(name => ({ name, compiled: compiled.get(name)! })));
106
+ const transition = resolveTransition(options.transition);
107
+ const listeners = new Set<(change: RouteChange<RouteOf<R>>) => void>();
108
+ const apps = new Set<RouterApp>();
109
+ let keyCount = 0;
110
+ let entries: RouteOf<R>[] = [];
111
+ let lastChange: RouteChange<RouteOf<R>> | undefined;
112
+
113
+ function definition(name: RouteName<R>): RouteDefinition {
114
+ const found = routes[name];
115
+ if (!found) throw new Error(`Unknown route "${name}" (routes: ${names.join(", ")})`);
116
+ return found;
117
+ }
118
+
119
+ function entry(name: RouteName<R>, params: Record<string, string>, query: Record<string, string>, state: unknown): RouteOf<R> {
120
+ definition(name);
121
+ const path = buildPath(compiled.get(name)!, params, query);
122
+ const made: Route = {
123
+ key: `${id}-${name}-${++keyCount}`,
124
+ name,
125
+ path,
126
+ pattern: compiled.get(name)!.pattern,
127
+ params: { ...params },
128
+ query: { ...query },
129
+ ...(state !== undefined ? { state } : {}),
130
+ };
131
+ return made as RouteOf<R>;
132
+ }
133
+
134
+ function stringParams(params: Record<string, unknown> | undefined): Record<string, string> {
135
+ const out: Record<string, string> = {};
136
+ for (const [key, value] of Object.entries(params ?? {})) if (value !== undefined) out[key] = String(value);
137
+ return out;
138
+ }
139
+
140
+ function match(path: string): RouteMatch<RouteName<R>> | undefined {
141
+ const location = parseLocation(path);
142
+ for (const candidate of ranked) {
143
+ const params = matchPath(candidate.compiled, location.pathname);
144
+ if (params) return { name: candidate.name, params, query: location.query, splat: candidate.compiled.splat };
145
+ }
146
+ return undefined;
147
+ }
148
+
149
+ function commit(action: RouteChange["action"], next: RouteOf<R>[], removed: RouteOf<R>[]): void {
150
+ const from = entries[entries.length - 1];
151
+ entries = next;
152
+ const change: RouteChange<RouteOf<R>> = { action, from, to: next[next.length - 1]!, removed, at: Date.now() };
153
+ lastChange = change;
154
+ options.onChange?.(change);
155
+ for (const listener of [...listeners]) listener(change);
156
+ requestRender(apps);
157
+ }
158
+
159
+ function initialEntry(to: string | undefined): RouteOf<R> {
160
+ const target = to ?? options.initial ?? names[0]!;
161
+ if (!target.startsWith("/") && Object.hasOwn(routes, target)) {
162
+ try {
163
+ return entry(target as RouteName<R>, {}, {}, undefined);
164
+ } catch (error) {
165
+ throw new Error(`The initial route "${target}" needs params: pass \`initial\` as a path (${(error as Error).message})`);
166
+ }
167
+ }
168
+ const found = match(target);
169
+ if (!found) throw new Error(`No route matches the initial path "${target}"`);
170
+ return entry(found.name, found.params, found.query, undefined);
171
+ }
172
+
173
+ function open(action: "push" | "replace", name: RouteName<R>, params: Record<string, string>, navigate: NavigateOptions = {}): RouteOf<R> {
174
+ const made = entry(name, params, navigate.query ?? {}, navigate.state);
175
+ if (action === "replace") {
176
+ const removed = entries.slice(-1);
177
+ commit("replace", [...entries.slice(0, -1), made], removed);
178
+ } else {
179
+ commit("push", [...entries, made], []);
180
+ }
181
+ return made;
182
+ }
183
+
184
+ const back = (): boolean => router.pop();
185
+
186
+ const router: StackRouter<R> = {
187
+ kind: "stack",
188
+ id,
189
+ routes,
190
+ get route() { return entries[entries.length - 1]!; },
191
+ get stack() { return entries; },
192
+ get lastChange() { return lastChange; },
193
+ transition,
194
+ push(name, ...args) {
195
+ return open("push", name, stringParams(args[0] as Record<string, unknown>), args[1]) as never;
196
+ },
197
+ replace(name, ...args) {
198
+ return open("replace", name, stringParams(args[0] as Record<string, unknown>), args[1]) as never;
199
+ },
200
+ pop(count = 1) {
201
+ const keep = Math.max(1, entries.length - Math.max(1, Math.floor(count)));
202
+ if (keep >= entries.length) return false;
203
+ commit("pop", entries.slice(0, keep), entries.slice(keep).reverse());
204
+ return true;
205
+ },
206
+ popToRoot() {
207
+ return router.pop(entries.length - 1);
208
+ },
209
+ canGoBack: () => entries.length > 1,
210
+ back,
211
+ navigate(to, navigate = {}) {
212
+ const found = match(to);
213
+ if (!found) return undefined;
214
+ const query = { ...found.query, ...navigate.query };
215
+ const path = buildPath(compiled.get(found.name)!, found.params, query);
216
+ const top = entries[entries.length - 1]!;
217
+ // Navigating to the screen already on display changes nothing (a tab's root, a double click).
218
+ if (sameEntry(top, found.name, path) && navigate.state === undefined) return top;
219
+ return open(navigate.replace ? "replace" : "push", found.name, found.params, { ...navigate, query });
220
+ },
221
+ href(name, ...args) {
222
+ definition(name);
223
+ return buildPath(compiled.get(name)!, stringParams(args[0] as Record<string, unknown>), args[1]?.query);
224
+ },
225
+ match,
226
+ reset(to) {
227
+ commit("reset", [initialEntry(to)], entries.slice().reverse());
228
+ },
229
+ definition,
230
+ title(target = router.route) {
231
+ const title = definition(target.name as RouteName<R>).title;
232
+ return typeof title === "function" ? title(target) : title;
233
+ },
234
+ subscribe(listener) {
235
+ listeners.add(listener);
236
+ return () => { listeners.delete(listener); };
237
+ },
238
+ attach(app, attachOptions) {
239
+ apps.add(app);
240
+ const detach = attachBack(app, router, attachOptions);
241
+ return () => { detach(); apps.delete(app); };
242
+ },
243
+ onCloseRequest: (event: CloseRequestEvent) => closeRequestBack(router, options.backOnCloseRequest ?? "android")(event),
244
+ invalidate: () => requestRender(apps),
245
+ };
246
+
247
+ entries = [initialEntry(undefined)];
248
+ if (!options[OWNED]) setDefaultRouter(router, () => router as unknown as StackRouter);
249
+ return router;
250
+ }
251
+
252
+ export type { AttachOptions };
package/src/tabs.ts ADDED
@@ -0,0 +1,182 @@
1
+ import { attachBack, closeRequestBack, requestRender, type BackOnCloseRequest, type RouterApp } from "./back";
2
+ import { setDefaultRouter } from "./context";
3
+ import { createStackRouter, OWNED, type RouteMap, type RouteOf, type StackRouter } from "./stack";
4
+ import type { NavigateOptions, Navigator, Route, RouteChange, RouterTransition } from "./types";
5
+
6
+ export interface TabDefinition<R extends RouteMap = RouteMap> {
7
+ /** Label of the tab bar button; default: the tab's name. */
8
+ title?: string;
9
+ /** Drawn before the label (any VNode: an `<Icon>`, an `<Svg>`). */
10
+ icon?: unknown;
11
+ routes: R;
12
+ /** The tab's root: a path or a route name. Default: its first route. */
13
+ initial?: string;
14
+ /** Default: the tab router's. */
15
+ transition?: RouterTransition;
16
+ }
17
+
18
+ export type TabMap = Record<string, TabDefinition<any>>;
19
+ export type TabName<T extends TabMap> = keyof T & string;
20
+
21
+ /**
22
+ * What back does at a tab's root. `"initialTab"` (default) returns to the first tab, as Android
23
+ * apps do; `"history"` walks back through the tabs visited; `"none"` stops.
24
+ */
25
+ export type TabBackBehavior = "initialTab" | "history" | "none";
26
+
27
+ export interface TabRouterOptions<T extends TabMap> {
28
+ tabs: T;
29
+ initialTab?: TabName<T>;
30
+ backBehavior?: TabBackBehavior;
31
+ /** Selecting the active tab again pops its stack to the root. Default true. */
32
+ reselectToRoot?: boolean;
33
+ transition?: RouterTransition;
34
+ backOnCloseRequest?: BackOnCloseRequest;
35
+ onChange?: (change: RouteChange) => void;
36
+ id?: string;
37
+ }
38
+
39
+ export interface TabRouter<T extends TabMap = TabMap> extends Navigator {
40
+ readonly kind: "tabs";
41
+ readonly definitions: T;
42
+ readonly tabs: readonly TabName<T>[];
43
+ readonly active: TabName<T>;
44
+ readonly initialTab: TabName<T>;
45
+ /** The active tab's stack, loosely typed (any tab's); `stack(name)` is typed per tab. */
46
+ readonly current: StackRouter;
47
+ /** The active tab's top route: a union over every tab's routes. */
48
+ readonly route: { [K in TabName<T>]: RouteOf<T[K]["routes"]> }[TabName<T>];
49
+ readonly lastChange: RouteChange | undefined;
50
+ /** Each tab keeps its own stack while another one is shown. */
51
+ stack<K extends TabName<T>>(name: K): StackRouter<T[K]["routes"]>;
52
+ select(name: TabName<T>): void;
53
+ title(name: TabName<T>): string;
54
+ /** Matches `to` in the active tab first, then the others (a `*` catch-all only after every exact match) and switches to that tab. */
55
+ navigate(to: string, options?: NavigateOptions & { tab?: TabName<T> }): Route | undefined;
56
+ }
57
+
58
+ let tabRouterCount = 0;
59
+
60
+ /** Tabs that each keep a stack: switching tabs keeps every tab's history. */
61
+ export function createTabRouter<const T extends TabMap>(options: TabRouterOptions<T>): TabRouter<T> {
62
+ const names = Object.keys(options.tabs) as TabName<T>[];
63
+ if (names.length === 0) throw new Error("createTabRouter needs at least one tab");
64
+ const id = options.id ?? `tabs${++tabRouterCount}`;
65
+ const initialTab = options.initialTab ?? names[0]!;
66
+ if (!names.includes(initialTab)) throw new Error(`Unknown initial tab "${initialTab}"`);
67
+ const backBehavior = options.backBehavior ?? "initialTab";
68
+ const listeners = new Set<(change: RouteChange) => void>();
69
+ const apps = new Set<RouterApp>();
70
+ const stacks = new Map<string, StackRouter>();
71
+ let active = initialTab;
72
+ let visited: TabName<T>[] = [];
73
+ let lastChange: RouteChange | undefined;
74
+
75
+ function emit(change: RouteChange): void {
76
+ lastChange = change;
77
+ options.onChange?.(change);
78
+ for (const listener of [...listeners]) listener(change);
79
+ requestRender(apps);
80
+ }
81
+
82
+ for (const name of names) {
83
+ const tab = options.tabs[name]!;
84
+ const stack = createStackRouter({
85
+ routes: tab.routes,
86
+ ...(tab.initial !== undefined ? { initial: tab.initial } : {}),
87
+ transition: tab.transition ?? options.transition ?? "none",
88
+ id: `${id}-${name}`,
89
+ [OWNED]: true,
90
+ }) as unknown as StackRouter;
91
+ // Only the shown tab's changes reach listeners: hidden tabs change only through `stack(name)`.
92
+ stack.subscribe(change => { if (name === active) emit(change); });
93
+ stacks.set(name, stack);
94
+ }
95
+
96
+ function setActive(name: TabName<T>, remember: boolean): void {
97
+ if (!stacks.has(name)) throw new Error(`Unknown tab "${name}" (tabs: ${names.join(", ")})`);
98
+ if (name === active) return;
99
+ const from = stacks.get(active)!.route;
100
+ if (remember) visited = [...visited.filter(tab => tab !== active && tab !== name), active];
101
+ active = name;
102
+ emit({ action: "tab", from, to: stacks.get(name)!.route, removed: [], at: Date.now() });
103
+ }
104
+
105
+ const router: TabRouter<T> = {
106
+ kind: "tabs",
107
+ id,
108
+ definitions: options.tabs,
109
+ tabs: names,
110
+ initialTab,
111
+ get active() { return active; },
112
+ get current() { return stacks.get(active)! as never; },
113
+ get route() { return stacks.get(active)!.route as never; },
114
+ get lastChange() { return lastChange; },
115
+ stack(name) {
116
+ const stack = stacks.get(name);
117
+ if (!stack) throw new Error(`Unknown tab "${name}" (tabs: ${names.join(", ")})`);
118
+ return stack as never;
119
+ },
120
+ select(name) {
121
+ if (name === active) {
122
+ if (options.reselectToRoot !== false) stacks.get(active)!.popToRoot();
123
+ return;
124
+ }
125
+ setActive(name, true);
126
+ },
127
+ title(name) {
128
+ return options.tabs[name]?.title ?? name;
129
+ },
130
+ canGoBack() {
131
+ if (stacks.get(active)!.canGoBack()) return true;
132
+ if (backBehavior === "history") return visited.length > 0;
133
+ return backBehavior === "initialTab" && active !== initialTab;
134
+ },
135
+ back() {
136
+ if (stacks.get(active)!.back()) return true;
137
+ if (backBehavior === "history" && visited.length > 0) {
138
+ const previous = visited[visited.length - 1]!;
139
+ visited = visited.slice(0, -1);
140
+ setActive(previous, false);
141
+ return true;
142
+ }
143
+ if (backBehavior === "initialTab" && active !== initialTab) {
144
+ visited = [];
145
+ setActive(initialTab, false);
146
+ return true;
147
+ }
148
+ return false;
149
+ },
150
+ navigate(to, navigate = {}) {
151
+ let target: TabName<T> | undefined = navigate.tab;
152
+ if (target === undefined) {
153
+ const order = [active, ...names.filter(name => name !== active)];
154
+ const matches = order.map(name => ({ name, match: stacks.get(name)!.match(to) })).filter(item => item.match);
155
+ target = (matches.find(item => !item.match!.splat) ?? matches[0])?.name;
156
+ }
157
+ if (target === undefined) return undefined;
158
+ const stack = stacks.get(target);
159
+ if (!stack) throw new Error(`Unknown tab "${target}"`);
160
+ const { tab: _tab, ...rest } = navigate;
161
+ if (target === active) return stack.navigate(to, rest);
162
+ // Fill the hidden stack first, then show it: one change for listeners, one render.
163
+ const route = stack.navigate(to, rest);
164
+ if (route) setActive(target, true);
165
+ return route;
166
+ },
167
+ subscribe(listener) {
168
+ listeners.add(listener);
169
+ return () => { listeners.delete(listener); };
170
+ },
171
+ attach(app, attachOptions) {
172
+ apps.add(app);
173
+ const detach = attachBack(app, router, attachOptions);
174
+ return () => { detach(); apps.delete(app); };
175
+ },
176
+ onCloseRequest: event => closeRequestBack(router, options.backOnCloseRequest ?? "android")(event),
177
+ invalidate: () => requestRender(apps),
178
+ };
179
+
180
+ setDefaultRouter(router, () => stacks.get(active)!);
181
+ return router;
182
+ }
package/src/types.ts ADDED
@@ -0,0 +1,111 @@
1
+ import type { MotionTransitions, MotionValues } from "@tarve/core";
2
+ import type { AttachOptions, CloseRequestEvent, RouterApp } from "./back";
3
+
4
+ /** One entry of a stack: a route definition filled with params. */
5
+ export interface Route<Name extends string = string, Params = Record<string, string>> {
6
+ /** Unique per stack entry: two pushes of the same path get two keys. */
7
+ readonly key: string;
8
+ readonly name: Name;
9
+ /** The concrete path, with its query: `/users/42?tab=posts`. */
10
+ readonly path: string;
11
+ /** The definition's pattern: `/users/:id`. */
12
+ readonly pattern: string;
13
+ readonly params: Params;
14
+ readonly query: Readonly<Record<string, string>>;
15
+ /** Anything passed with `{ state }`: not part of the path. */
16
+ readonly state?: unknown;
17
+ }
18
+
19
+ export interface NavigateOptions {
20
+ /** Replace the top entry instead of pushing one. */
21
+ replace?: boolean;
22
+ state?: unknown;
23
+ query?: Record<string, string>;
24
+ }
25
+
26
+ export type RouteAction = "push" | "replace" | "pop" | "reset" | "tab";
27
+
28
+ export interface RouteChange<R extends Route = Route> {
29
+ readonly action: RouteAction;
30
+ readonly from: R | undefined;
31
+ readonly to: R;
32
+ /** Entries that left the stack. */
33
+ readonly removed: readonly R[];
34
+ /** `Date.now()` of the change: RouterView animates only recent ones. */
35
+ readonly at: number;
36
+ }
37
+
38
+ /** What `<RouterView>`, `<Link>` and `useRouter()` share between stack and tab routers. */
39
+ export interface Navigator {
40
+ readonly kind: "stack" | "tabs";
41
+ readonly id: string;
42
+ readonly route: Route;
43
+ canGoBack(): boolean;
44
+ /** Goes back one step; `false` when there is nowhere to go. */
45
+ back(): boolean;
46
+ /** Pushes (or replaces) the route matching `to`; `undefined` when no route matches. */
47
+ navigate(to: string, options?: NavigateOptions): Route | undefined;
48
+ subscribe(listener: (change: RouteChange) => void): () => void;
49
+ /** Alt+Left and the mouse back button on `app`; also renders `app` after navigations outside handlers. */
50
+ attach(app: RouterApp, options?: AttachOptions): () => void;
51
+ /** `<Window onCloseRequest={router.onCloseRequest}>`: Android's back key pops instead of closing. */
52
+ readonly onCloseRequest: (event: CloseRequestEvent) => void;
53
+ /** Asks the attached app (or the active one) to render. */
54
+ invalidate(): void;
55
+ }
56
+
57
+ export interface TransitionSide {
58
+ enter: MotionValues;
59
+ exit: MotionValues;
60
+ }
61
+
62
+ /** Enter/exit motion of screens, run by the native motion engine (`motionFrom` + `AnimatePresence`). */
63
+ export type RouterTransition =
64
+ | "none"
65
+ | "fade"
66
+ | "slide"
67
+ | {
68
+ /** Values a pushed screen starts from and the covered screen leaves to. */
69
+ push: TransitionSide;
70
+ /** Same for `pop`; default: `push` mirrored on `left`/`right`. */
71
+ pop?: TransitionSide;
72
+ /** Default `{ all: { duration: 220, easing: "easeOut" } }`. */
73
+ transition?: MotionTransitions;
74
+ };
75
+
76
+ export interface ResolvedTransition {
77
+ push: TransitionSide;
78
+ pop: TransitionSide;
79
+ transition: MotionTransitions;
80
+ /** Longest duration + delay, ms. */
81
+ span: number;
82
+ }
83
+
84
+ const DEFAULT_MOTION: MotionTransitions = { all: { duration: 220, easing: "easeOut" } };
85
+ const SLIDE = 48;
86
+
87
+ function mirror(values: MotionValues): MotionValues {
88
+ const out: MotionValues = { ...values };
89
+ if (values.left !== undefined) out.left = -values.left;
90
+ if (values.right !== undefined) out.right = -values.right;
91
+ return out;
92
+ }
93
+
94
+ export function resolveTransition(transition: RouterTransition | undefined): ResolvedTransition | undefined {
95
+ if (!transition || transition === "none") return undefined;
96
+ let push: TransitionSide;
97
+ let pop: TransitionSide | undefined;
98
+ let motion = DEFAULT_MOTION;
99
+ if (transition === "fade") {
100
+ push = { enter: { opacity: 0 }, exit: { opacity: 0 } };
101
+ } else if (transition === "slide") {
102
+ push = { enter: { left: SLIDE, right: -SLIDE, opacity: 0 }, exit: { left: -SLIDE, right: SLIDE, opacity: 0 } };
103
+ } else {
104
+ push = transition.push;
105
+ pop = transition.pop;
106
+ motion = transition.transition ?? DEFAULT_MOTION;
107
+ }
108
+ pop ??= { enter: mirror(push.enter), exit: mirror(push.exit) };
109
+ const span = Math.max(0, ...Object.values(motion).map(entry => (entry?.duration ?? 200) + (entry?.delay ?? 0)));
110
+ return { push, pop, transition: motion, span };
111
+ }
package/src/view.ts ADDED
@@ -0,0 +1,219 @@
1
+ import { AnimatePresence, Pressable, Row, Text, View, theme, type PressableProps, type Style, type VNode, type ViewProps } from "@tarve/core";
2
+ import { Fragment, jsx, type Child } from "@tarve/core/jsx-runtime";
3
+ import { currentScope, enterScope, leaveScope, type RouteScope } from "./context";
4
+ import type { StackRouter } from "./stack";
5
+ import type { TabRouter } from "./tabs";
6
+ import { resolveTransition, type Navigator, type Route, type RouterTransition } from "./types";
7
+
8
+ export interface RouterViewProps {
9
+ router: StackRouter<any> | TabRouter<any>;
10
+ /** Escape goes back while the router can (popups and dialogs keep their own Escape). Default true. */
11
+ backOnEscape?: boolean;
12
+ /** Overrides the router's transition. */
13
+ transition?: RouterTransition;
14
+ id?: string;
15
+ style?: Style;
16
+ }
17
+
18
+ interface ScopeMarkerProps {
19
+ scope: RouteScope;
20
+ depth: { value: number };
21
+ }
22
+
23
+ /** Empty: opens the screen's route scope before its subtree renders. */
24
+ function ScopeStart({ scope, depth }: ScopeMarkerProps): VNode {
25
+ depth.value = enterScope(scope);
26
+ return jsx(Fragment, {});
27
+ }
28
+
29
+ /** Empty: closes the scope after the screen's subtree, its last sibling. */
30
+ function ScopeEnd({ depth }: ScopeMarkerProps): VNode {
31
+ leaveScope(depth.value);
32
+ return jsx(Fragment, {});
33
+ }
34
+
35
+ const FRAME: Style = { position: "absolute", top: 0, left: 0, right: 0, bottom: 0, opacity: 1, direction: "column" };
36
+
37
+ function screenFrame(navigator: Navigator, stack: StackRouter<any>, route: Route): VNode {
38
+ const definition = stack.definition(route.name);
39
+ const scope: RouteScope = { navigator, stack, route };
40
+ const depth = { value: 0 };
41
+ return jsx(View, {
42
+ id: `${stack.id}-screen-${route.key}`,
43
+ style: { ...FRAME, background: theme.colors.background },
44
+ children: [
45
+ jsx(ScopeStart, { scope, depth }),
46
+ jsx(definition.screen, { route, params: route.params, router: stack }),
47
+ jsx(ScopeEnd, { scope, depth }),
48
+ ],
49
+ }, route.key);
50
+ }
51
+
52
+ /** Changes older than the transition (plus slack for a busy frame) no longer animate. */
53
+ const SLACK_MS = 1000;
54
+
55
+ function StackView({ stack, navigator, backOnEscape, transition, id, style }: {
56
+ stack: StackRouter<any>;
57
+ navigator: Navigator;
58
+ backOnEscape: boolean;
59
+ transition: RouterTransition | undefined;
60
+ id: string | undefined;
61
+ style: Style | undefined;
62
+ }): VNode {
63
+ const current = stack.route;
64
+ const change = stack.lastChange;
65
+ const motion = transition !== undefined
66
+ ? resolveTransition(transition)
67
+ : resolveTransition(stack.definition(current.name).transition) ?? stack.transition;
68
+ const children: VNode[] = [];
69
+ const presence = (route: Route) => `${stack.id}:${route.key}`;
70
+ if (!motion) {
71
+ children.push(screenFrame(navigator, stack, current));
72
+ } else {
73
+ const recent = !!change && change.to.key === current.key && Date.now() - change.at < motion.span + SLACK_MS;
74
+ const side = change?.action === "pop" ? motion.pop : motion.push;
75
+ const leaving = recent && change!.from && change!.from.key !== current.key ? change!.from : undefined;
76
+ const entering = jsx(AnimatePresence, {
77
+ id: presence(current),
78
+ present: true,
79
+ ...(recent && change!.from ? { enter: side.enter } : {}),
80
+ exit: side.exit,
81
+ transition: motion.transition,
82
+ children: screenFrame(navigator, stack, current),
83
+ }, current.key);
84
+ if (leaving) {
85
+ const exiting = jsx(AnimatePresence, {
86
+ id: presence(leaving),
87
+ present: false,
88
+ exit: side.exit,
89
+ transition: motion.transition,
90
+ children: screenFrame(navigator, stack, leaving),
91
+ }, leaving.key);
92
+ // Lower in the stack first: a pop keeps the order the push rendered.
93
+ children.push(...(change!.action === "pop" ? [entering, exiting] : [exiting, entering]));
94
+ } else {
95
+ children.push(entering);
96
+ }
97
+ }
98
+ const props: ViewProps & { onEscape?: () => void } = {
99
+ ...(id ? { id } : {}),
100
+ style: { flex: 1, position: "relative", overflow: "hidden", minWidth: 0, minHeight: 0, ...style },
101
+ children,
102
+ };
103
+ if (backOnEscape && navigator.canGoBack()) props.onEscape = () => { navigator.back(); };
104
+ return jsx(View, props);
105
+ }
106
+
107
+ /** Renders the router's current screen; pushes and pops animate when the router has a transition. */
108
+ export function RouterView({ router, backOnEscape = true, transition, id, style }: RouterViewProps): VNode {
109
+ const stack = router.kind === "tabs" ? router.current : router;
110
+ return jsx(StackView, {
111
+ stack,
112
+ navigator: router,
113
+ backOnEscape,
114
+ transition,
115
+ id,
116
+ style,
117
+ }, router.kind === "tabs" ? `${router.id}-${router.active}` : router.id);
118
+ }
119
+
120
+ export interface TabBarProps {
121
+ router: TabRouter<any>;
122
+ id?: string;
123
+ style?: Style;
124
+ }
125
+
126
+ /** The buttons of a tab router: one per tab, the active one selected. */
127
+ export function TabBar({ router, id, style }: TabBarProps): VNode {
128
+ const c = theme.colors;
129
+ return jsx(Row, {
130
+ id: id ?? `${router.id}-bar`,
131
+ gap: 4,
132
+ control: { role: "tablist" },
133
+ style: { padding: 4, background: c.muted, ...style },
134
+ children: router.tabs.map((name: string) => {
135
+ const selected = name === router.active;
136
+ const icon = router.definitions[name]?.icon as Child;
137
+ return jsx(Pressable, {
138
+ id: `${router.id}-tab-${name}`,
139
+ control: { role: "tab", label: router.title(name), selected },
140
+ onClick: () => router.select(name),
141
+ flex: 1,
142
+ style: {
143
+ height: 40, gap: 6, direction: "row", align: "center", justify: "center", radius: theme.radius.md,
144
+ background: selected ? c.card : "#00000000",
145
+ hover: { background: selected ? c.card : c.secondaryHover },
146
+ },
147
+ children: [
148
+ icon ?? null,
149
+ jsx(Text, { size: 13, weight: selected ? 600 : 500, color: selected ? c.foreground : c.mutedForeground, children: router.title(name) }),
150
+ ],
151
+ }, name);
152
+ }),
153
+ });
154
+ }
155
+
156
+ export interface TabRouterViewProps extends Omit<RouterViewProps, "router"> {
157
+ router: TabRouter<any>;
158
+ /** Default `"bottom"`. */
159
+ placement?: "top" | "bottom";
160
+ }
161
+
162
+ /** The active tab's stack with a tab bar. */
163
+ export function TabRouterView({ router, placement = "bottom", id, style, ...rest }: TabRouterViewProps): VNode {
164
+ const bar = jsx(TabBar, { router }, "bar");
165
+ const content = jsx(RouterView, { router, ...rest }, "content");
166
+ return jsx(View, {
167
+ ...(id ? { id } : {}),
168
+ style: { flex: 1, direction: "column", minHeight: 0, ...style },
169
+ children: placement === "top" ? [bar, content] : [content, bar],
170
+ });
171
+ }
172
+
173
+ export interface LinkProps extends Omit<PressableProps, "onClick" | "control" | "children"> {
174
+ children?: Child;
175
+ /** A path: `/users/42?tab=posts`. */
176
+ to: string;
177
+ replace?: boolean;
178
+ state?: unknown;
179
+ /** Default: the router of the screen being rendered, else the last router created. */
180
+ router?: Navigator;
181
+ /** Accessible label; default: the text of the children. */
182
+ label?: string;
183
+ onClick?: () => void;
184
+ }
185
+
186
+ function textOf(child: Child): string {
187
+ if (Array.isArray(child)) return child.map(textOf).join("");
188
+ if (child == null || typeof child === "boolean") return "";
189
+ if (typeof child === "string" || typeof child === "number") return String(child);
190
+ return textOf(child.props.children);
191
+ }
192
+
193
+ function plainText(child: Child): boolean {
194
+ if (child == null || typeof child === "boolean" || typeof child === "string" || typeof child === "number") return true;
195
+ return Array.isArray(child) && child.every(plainText);
196
+ }
197
+
198
+ /** An in-app link: navigates the router instead of opening a URL. */
199
+ export function Link({ to, replace, state, router, label, children, style, disabled, onClick, ...props }: LinkProps): VNode {
200
+ const target = router ?? currentScope()?.navigator;
201
+ if (!target) throw new Error("<Link> needs a router: render it inside <RouterView> or pass router");
202
+ const accessible = (label ?? textOf(children)).trim();
203
+ const foreground = disabled ? theme.colors.disabledForeground : theme.colors.primary;
204
+ return jsx(Pressable, {
205
+ ...props,
206
+ disabled,
207
+ control: accessible ? { role: "link", label: accessible } : { role: "link" },
208
+ style: { foreground, ...style },
209
+ children: plainText(children) ? jsx(Text, { style: { textDecoration: "underline" }, color: foreground, children }) : children,
210
+ onClick: () => {
211
+ if (disabled) return;
212
+ onClick?.();
213
+ target.navigate(to, { ...(replace ? { replace } : {}), ...(state !== undefined ? { state } : {}) });
214
+ },
215
+ });
216
+ }
217
+
218
+ /** Same as `Link`, for files that also use core's (external) `Link`. */
219
+ export const RouterLink = Link;