@oomfware/stacker 0.1.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/src/match.ts ADDED
@@ -0,0 +1,180 @@
1
+ import { getDefault, isOptional } from './codec.ts';
2
+ import type { ResolvedLeaf, ResolvedNode, RouteMeta, RouteRegistry, WhenContext } from './routes.ts';
3
+
4
+ /** a node on a matched chain paired with its instance parameters. */
5
+ export interface MatchedNode {
6
+ /** parameters used for instance keying. */
7
+ readonly params: Readonly<Record<string, unknown>>;
8
+ readonly node: ResolvedNode;
9
+ }
10
+
11
+ /** the result of matching a URL, containing the chain, leaf, name, and parameters. */
12
+ export interface RouteMatch {
13
+ readonly chain: readonly MatchedNode[];
14
+ readonly leaf: ResolvedLeaf;
15
+ readonly name: string;
16
+ /** leaf parameters, combining path and query. */
17
+ readonly params: Readonly<Record<string, unknown>>;
18
+ }
19
+
20
+ /**
21
+ * looks up the nearest metadata value for a key on a matched chain, searching leaf-first.
22
+ *
23
+ * @param match the route match chain
24
+ * @param key the metadata key to resolve
25
+ * @returns the nearest metadata value, or undefined if none is found
26
+ */
27
+ export const resolveMeta = <K extends keyof RouteMeta>(
28
+ match: RouteMatch,
29
+ key: K,
30
+ ): RouteMeta[K] | undefined => {
31
+ for (let i = match.chain.length - 1; i >= 0; i--) {
32
+ const value = match.chain[i]?.node.node.meta?.[key];
33
+ if (value !== undefined) {
34
+ return value;
35
+ }
36
+ }
37
+ return undefined;
38
+ };
39
+
40
+ interface CompiledLeaf {
41
+ readonly leaf: ResolvedLeaf;
42
+ readonly paramNames: readonly string[];
43
+ readonly regex: RegExp;
44
+ }
45
+
46
+ const SEGMENT = /:[A-Za-z_]\w*/g;
47
+
48
+ const escapeRegExp = (segment: string): string => segment.replaceAll(/[$()*+.?[\\\]^{|}]/g, '\\$&');
49
+
50
+ const compile = (path: string): { paramNames: string[]; regex: RegExp } => {
51
+ const paramNames: string[] = [];
52
+ let pattern = '';
53
+ let lastIndex = 0;
54
+ for (const match of path.matchAll(SEGMENT)) {
55
+ const whole = match[0];
56
+ const at = match.index;
57
+ if (at === undefined) {
58
+ continue;
59
+ }
60
+ paramNames.push(whole.slice(1));
61
+ pattern += `${escapeRegExp(path.slice(lastIndex, at))}([^/]+)`;
62
+ lastIndex = at + whole.length;
63
+ }
64
+ pattern += escapeRegExp(path.slice(lastIndex));
65
+ const suffix = pattern.endsWith('/') ? '' : '/?';
66
+ return { paramNames, regex: new RegExp(`^${pattern}${suffix}$`) };
67
+ };
68
+
69
+ /** matches URLs in declaration order against a compiled route registry. */
70
+ export class Matcher {
71
+ readonly #compiled: readonly CompiledLeaf[];
72
+
73
+ constructor(registry: RouteRegistry<unknown>) {
74
+ this.#compiled = [...registry.leaves.values()].map((leaf) => {
75
+ const { paramNames, regex } = compile(leaf.path);
76
+ return { leaf, paramNames, regex };
77
+ });
78
+ }
79
+
80
+ match(pathname: string, search = '', hash = ''): RouteMatch | undefined {
81
+ const rawSearch = new URLSearchParams(search);
82
+ const ctx: WhenContext = { hash, pathname, rawSearch, search };
83
+
84
+ for (const { leaf, paramNames, regex } of this.#compiled) {
85
+ const execed = regex.exec(pathname);
86
+ if (execed === null) {
87
+ continue;
88
+ }
89
+
90
+ const raw = this.#rawValues(paramNames, execed);
91
+ if (raw === undefined) {
92
+ continue;
93
+ }
94
+
95
+ const perNode = this.#decodeChain(leaf.chain, raw);
96
+ if (perNode === undefined) {
97
+ continue;
98
+ }
99
+
100
+ const query = this.#decodeQuery(leaf, rawSearch);
101
+ if (query === undefined) {
102
+ continue;
103
+ }
104
+
105
+ if (leaf.leaf.when && !leaf.leaf.when(ctx)) {
106
+ continue;
107
+ }
108
+
109
+ const chain: MatchedNode[] = leaf.chain.map((node) => {
110
+ const own = perNode.get(node.id) ?? {};
111
+ return { node, params: node.kind === 'route' ? { ...own, ...query } : own };
112
+ });
113
+ // the leaf is the last node and always a route, so its chain params are the leaf params.
114
+ return { chain, leaf, name: leaf.name, params: chain.at(-1)?.params ?? {} };
115
+ }
116
+
117
+ return undefined;
118
+ }
119
+
120
+ #rawValues(paramNames: readonly string[], execed: RegExpExecArray): Record<string, string> | undefined {
121
+ const raw: Record<string, string> = {};
122
+ for (const [i, name] of paramNames.entries()) {
123
+ const value = execed[i + 1];
124
+ if (value === undefined) {
125
+ return undefined;
126
+ }
127
+ try {
128
+ raw[name] = decodeURIComponent(value);
129
+ } catch {
130
+ return undefined;
131
+ }
132
+ }
133
+ return raw;
134
+ }
135
+
136
+ #decodeChain(
137
+ chain: readonly ResolvedNode[],
138
+ raw: Record<string, string>,
139
+ ): Map<string, Record<string, unknown>> | undefined {
140
+ const perNode = new Map<string, Record<string, unknown>>();
141
+ for (const node of chain) {
142
+ const decoded: Record<string, unknown> = {};
143
+ for (const [name, codec] of Object.entries(node.params)) {
144
+ const rawValue = raw[name];
145
+ if (rawValue === undefined) {
146
+ return undefined;
147
+ }
148
+ const value = codec.decode(rawValue);
149
+ if (value === undefined) {
150
+ return undefined;
151
+ }
152
+ decoded[name] = value;
153
+ }
154
+ perNode.set(node.id, decoded);
155
+ }
156
+ return perNode;
157
+ }
158
+
159
+ #decodeQuery(leaf: ResolvedLeaf, rawSearch: URLSearchParams): Record<string, unknown> | undefined {
160
+ const out: Record<string, unknown> = {};
161
+ for (const [name, codec] of Object.entries(leaf.query)) {
162
+ const rawValue = rawSearch.get(name);
163
+ if (rawValue !== null) {
164
+ const value = codec.decode(rawValue);
165
+ if (value === undefined) {
166
+ return undefined;
167
+ }
168
+ out[name] = value;
169
+ continue;
170
+ }
171
+ const fallback = getDefault(codec);
172
+ if (fallback !== undefined) {
173
+ out[name] = fallback[0];
174
+ } else if (!isOptional(codec)) {
175
+ return undefined;
176
+ }
177
+ }
178
+ return out;
179
+ }
180
+ }
@@ -0,0 +1,18 @@
1
+ import { createContext } from 'react';
2
+
3
+ import type { Router } from '../router.ts';
4
+ import type { RouteRegistry } from '../routes.ts';
5
+ import type { InstanceNode } from '../view-model.ts';
6
+
7
+ // generated hooks restore the registry type after checking its identity.
8
+ // oxlint-disable-next-line typescript/no-explicit-any -- type-erased context
9
+ export const RouterContext = createContext<Router<RouteRegistry<any>> | null>(null);
10
+
11
+ export const ActiveChainContext = createContext<readonly string[]>([]);
12
+
13
+ export interface CurrentNode {
14
+ readonly node: InstanceNode;
15
+ readonly focused: boolean;
16
+ }
17
+
18
+ export const CurrentNodeContext = createContext<CurrentNode | null>(null);
@@ -0,0 +1,178 @@
1
+ import { useContext, useEffect, useMemo, useSyncExternalStore } from 'react';
2
+ import type { EffectCallback } from 'react';
3
+
4
+ import type { HistoryLocation } from '../history/types.ts';
5
+ import type { RouteMatch } from '../match.ts';
6
+ import type { Router } from '../router.ts';
7
+ import type { ParamsOf, QueryPatchOf, RouteName, RouteRegistry } from '../routes.ts';
8
+
9
+ import { CurrentNodeContext, RouterContext } from './context.ts';
10
+
11
+ // #region loose hooks (no registry type required)
12
+
13
+ /**
14
+ * gets the active router instance.
15
+ *
16
+ * @returns router instance
17
+ * @throws when used outside a router view context
18
+ */
19
+ export const useRouter = (): Router<RouteRegistry<unknown>> => {
20
+ const router = useContext(RouterContext);
21
+ if (router === null) {
22
+ throw new Error('stacker: useRouter must be used within a <RouterView>');
23
+ }
24
+ return router;
25
+ };
26
+
27
+ /**
28
+ * gets the active history location.
29
+ *
30
+ * @returns history location
31
+ */
32
+ export const useLocation = (): HistoryLocation => {
33
+ const router = useRouter();
34
+ return useSyncExternalStore(router.subscribe, () => router.location);
35
+ };
36
+
37
+ /**
38
+ * gets the active route match information.
39
+ *
40
+ * @returns active route match
41
+ */
42
+ export const useRoute = (): RouteMatch => {
43
+ const router = useRouter();
44
+ return useSyncExternalStore(router.subscribe, () => router.route);
45
+ };
46
+
47
+ /**
48
+ * gets the untyped parameter map of the nearest enclosing route node.
49
+ *
50
+ * @returns decoded parameters
51
+ * @throws when used outside a route tree context
52
+ */
53
+ export const useParams = (): Readonly<Record<string, unknown>> => {
54
+ const current = useContext(CurrentNodeContext);
55
+ if (current === null) {
56
+ throw new Error('stacker: useParams must be used within a route component');
57
+ }
58
+ return current.node.params;
59
+ };
60
+
61
+ /**
62
+ * gets whether the enclosing branch is focused (on screen).
63
+ *
64
+ * @returns true if focused
65
+ */
66
+ export const useIsFocused = (): boolean => {
67
+ return useContext(CurrentNodeContext)?.focused ?? false;
68
+ };
69
+
70
+ /**
71
+ * runs an effect callback only while the branch is focused.
72
+ *
73
+ * the effect re-runs whenever its identity changes, the way `useEffect` does, so wrap it in `useCallback` to
74
+ * control when that happens. an effect built fresh on every render re-runs on every render.
75
+ *
76
+ * @param effect effect callback
77
+ */
78
+ export const useFocusEffect = (effect: EffectCallback): void => {
79
+ const focused = useIsFocused();
80
+ useEffect(() => {
81
+ if (!focused) {
82
+ return undefined;
83
+ }
84
+ return effect();
85
+ }, [effect, focused]);
86
+ };
87
+
88
+ // #endregion
89
+
90
+ // #region typed hooks
91
+
92
+ /** typed hooks bound to a specific route registry. */
93
+ export interface RouterHooks<R extends RouteRegistry<unknown>> {
94
+ /** returns a function to build URLs. */
95
+ useBuild(): Router<R>['build'];
96
+ /** gets the current location. */
97
+ useLocation(): HistoryLocation;
98
+ /** returns a function to navigate to routes. */
99
+ useNavigate(): Router<R>['navigate'];
100
+ /** gets a route's parameters and a setter that patches its query in place. */
101
+ useParams<K extends RouteName<R>>(name: K): readonly [ParamsOf<R, K>, (patch: QueryPatchOf<R, K>) => void];
102
+ /** gets the active route match. */
103
+ useRoute(): RouteMatch;
104
+ /** gets the typed router instance. */
105
+ useRouter(): Router<R>;
106
+ }
107
+
108
+ /**
109
+ * generates typed hooks bound to a specific route registry.
110
+ *
111
+ * @param routes the compiled registry the hooks are typed against
112
+ * @returns typed hooks record
113
+ * @throws when used with a router built from a different registry
114
+ */
115
+ export const createRouterHooks = <R extends RouteRegistry<unknown>>(routes: R): RouterHooks<R> => {
116
+ const useTypedRouter = (): Router<R> => {
117
+ const router = useContext(RouterContext);
118
+ if (router === null) {
119
+ throw new Error('stacker: hooks must be used within a <RouterView>');
120
+ }
121
+ // registry identity makes restoring the erased generic a checked assertion.
122
+ if (router.routes !== routes) {
123
+ throw new Error('stacker: these hooks were created for a different route registry');
124
+ }
125
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- guarded by the registry identity check
126
+ return router as Router<R>;
127
+ };
128
+
129
+ return {
130
+ useBuild() {
131
+ const router = useTypedRouter();
132
+
133
+ return useMemo<Router<R>['build']>(() => {
134
+ return (name, ...args) => router.build(name, ...args);
135
+ }, [router]);
136
+ },
137
+
138
+ useLocation: useLocation,
139
+
140
+ useNavigate() {
141
+ const router = useTypedRouter();
142
+
143
+ return useMemo<Router<R>['navigate']>(() => {
144
+ return (name, ...args) => router.navigate(name, ...args);
145
+ }, [router]);
146
+ },
147
+
148
+ useParams<K extends RouteName<R>>(
149
+ name: K,
150
+ ): readonly [ParamsOf<R, K>, (patch: QueryPatchOf<R, K>) => void] {
151
+ const router = useTypedRouter();
152
+
153
+ const current = useContext(CurrentNodeContext);
154
+
155
+ const setParams = useMemo<(patch: QueryPatchOf<R, K>) => void>(() => {
156
+ return (patch) => router.setParams(patch);
157
+ }, [router]);
158
+
159
+ if (current === null) {
160
+ throw new Error('stacker: useParams must be used within a route component');
161
+ }
162
+ if (current.node.node.kind !== 'route' || current.node.node.key !== name) {
163
+ throw new Error(
164
+ `stacker: useParams('${name}') called under ${current.node.node.kind} '${current.node.node.key}'`,
165
+ );
166
+ }
167
+
168
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- guarded by the name check above
169
+ return [current.node.params as ParamsOf<R, K>, setParams];
170
+ },
171
+
172
+ useRoute: useRoute,
173
+
174
+ useRouter: useTypedRouter,
175
+ };
176
+ };
177
+
178
+ // #endregion
@@ -0,0 +1,61 @@
1
+ import type { AnchorHTMLAttributes, MouseEvent, ReactElement } from 'react';
2
+
3
+ import { useRouter } from './hooks.ts';
4
+
5
+ /** properties for the link component. */
6
+ export interface LinkProps extends Omit<AnchorHTMLAttributes<HTMLAnchorElement>, 'href'> {
7
+ /** replace the current history entry. */
8
+ readonly replace?: boolean;
9
+ /** target relative URL path. */
10
+ readonly to: string;
11
+ }
12
+
13
+ const isModifiedClick = (event: MouseEvent): boolean =>
14
+ event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey;
15
+
16
+ // parsing first prevents external URLs from being reduced to local paths.
17
+ const isRoutable = (to: string): boolean => {
18
+ try {
19
+ return new URL(to, window.location.href).origin === window.location.origin;
20
+ } catch {
21
+ return false;
22
+ }
23
+ };
24
+
25
+ /**
26
+ * anchor element that intercepts clicks for in-app navigation.
27
+ *
28
+ * a destination on another origin, or under a scheme like `mailto:`, is left to the browser.
29
+ *
30
+ * @param props link properties
31
+ * @returns rendered anchor element
32
+ */
33
+ export const Link = ({ children, onClick, replace, to, ...rest }: LinkProps): ReactElement => {
34
+ const router = useRouter();
35
+ return (
36
+ <a
37
+ href={to}
38
+ onClick={(event) => {
39
+ onClick?.(event);
40
+ if (
41
+ event.defaultPrevented ||
42
+ isModifiedClick(event) ||
43
+ rest.download !== undefined ||
44
+ (rest.target !== undefined && rest.target !== '' && rest.target !== '_self') ||
45
+ !isRoutable(to)
46
+ ) {
47
+ return;
48
+ }
49
+ event.preventDefault();
50
+ if (replace) {
51
+ router.replace(to);
52
+ } else {
53
+ router.push(to);
54
+ }
55
+ }}
56
+ {...rest}
57
+ >
58
+ {children}
59
+ </a>
60
+ );
61
+ };
@@ -0,0 +1,18 @@
1
+ import { useContext } from 'react';
2
+ import type { ReactElement } from 'react';
3
+
4
+ import { CurrentNodeContext } from './context.ts';
5
+ import { Pool } from './router-view.tsx';
6
+
7
+ /**
8
+ * renders the child branch pool within a layout component.
9
+ *
10
+ * @returns rendered outlet child pool or null if outside a layout
11
+ */
12
+ export const Outlet = (): ReactElement | null => {
13
+ const current = useContext(CurrentNodeContext);
14
+ if (current === null) {
15
+ return null;
16
+ }
17
+ return <Pool nodes={current.node.children} />;
18
+ };
@@ -0,0 +1,79 @@
1
+ import { Suspense, useContext, useLayoutEffect, useSyncExternalStore } from 'react';
2
+ import type { ReactElement } from 'react';
3
+
4
+ import type { Router } from '../router.ts';
5
+ import type { RouteRegistry } from '../routes.ts';
6
+ import type { InstanceNode } from '../view-model.ts';
7
+
8
+ import { ActiveChainContext, CurrentNodeContext, RouterContext } from './context.ts';
9
+
10
+ /**
11
+ * renders the current view tree of the router.
12
+ *
13
+ * off-chain branches stay mounted with their state intact, hidden with `display: none` rather than unmounted,
14
+ * so a back-traversal returns to the instance you left. their effects keep running; a branch that wants to
15
+ * pause background work while stacked can gate it on `useIsFocused`.
16
+ *
17
+ * @param props.router router instance
18
+ * @returns rendered component tree
19
+ */
20
+ export const RouterView = <R extends RouteRegistry<unknown>>({
21
+ router,
22
+ }: {
23
+ readonly router: Router<R>;
24
+ }): ReactElement => {
25
+ const view = useSyncExternalStore(router.subscribe, () => router.view);
26
+
27
+ useLayoutEffect(() => {
28
+ return router.attachView();
29
+ }, [router]);
30
+ useLayoutEffect(() => {
31
+ router.notifyCommit();
32
+ }, [router, view]);
33
+
34
+ return (
35
+ <RouterContext value={router}>
36
+ <ActiveChainContext value={view.activePath}>
37
+ <Pool nodes={view.roots} />
38
+ </ActiveChainContext>
39
+ </RouterContext>
40
+ );
41
+ };
42
+
43
+ export const Pool = ({ nodes }: { readonly nodes: readonly InstanceNode[] }): ReactElement => {
44
+ const activePath = useContext(ActiveChainContext);
45
+ return (
46
+ <>
47
+ {nodes.map((node) => (
48
+ <Branch key={node.instanceKey} focused={activePath.includes(node.instanceKey)} node={node} />
49
+ ))}
50
+ </>
51
+ );
52
+ };
53
+
54
+ const Branch = ({
55
+ focused,
56
+ node,
57
+ }: {
58
+ readonly focused: boolean;
59
+ readonly node: InstanceNode;
60
+ }): ReactElement => {
61
+ const resolved = node.node;
62
+ const Component = resolved.node.component;
63
+ const router = useContext(RouterContext);
64
+ const fallback = resolved.node.fallback ?? router?.defaultFallback;
65
+
66
+ return (
67
+ <div
68
+ className="stacker-branch"
69
+ data-stacker-node={resolved.id}
70
+ style={{ display: focused ? 'contents' : 'none' }}
71
+ >
72
+ <CurrentNodeContext value={{ focused, node }}>
73
+ <Suspense fallback={fallback ?? null}>
74
+ <Component />
75
+ </Suspense>
76
+ </CurrentNodeContext>
77
+ </div>
78
+ );
79
+ };