@canonical/router-react 0.25.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.
Files changed (102) hide show
  1. package/README.md +452 -0
  2. package/dist/esm/index.js +7 -0
  3. package/dist/esm/index.js.map +1 -0
  4. package/dist/esm/lib/Link/Link.js +68 -0
  5. package/dist/esm/lib/Link/Link.js.map +1 -0
  6. package/dist/esm/lib/Link/index.js +2 -0
  7. package/dist/esm/lib/Link/index.js.map +1 -0
  8. package/dist/esm/lib/Link/types.js +2 -0
  9. package/dist/esm/lib/Link/types.js.map +1 -0
  10. package/dist/esm/lib/Outlet/Outlet.js +40 -0
  11. package/dist/esm/lib/Outlet/Outlet.js.map +1 -0
  12. package/dist/esm/lib/Outlet/index.js +2 -0
  13. package/dist/esm/lib/Outlet/index.js.map +1 -0
  14. package/dist/esm/lib/Outlet/types.js +2 -0
  15. package/dist/esm/lib/Outlet/types.js.map +1 -0
  16. package/dist/esm/lib/RouterProvider/Context.js +9 -0
  17. package/dist/esm/lib/RouterProvider/Context.js.map +1 -0
  18. package/dist/esm/lib/RouterProvider/Provider.js +12 -0
  19. package/dist/esm/lib/RouterProvider/Provider.js.map +1 -0
  20. package/dist/esm/lib/RouterProvider/index.js +2 -0
  21. package/dist/esm/lib/RouterProvider/index.js.map +1 -0
  22. package/dist/esm/lib/RouterProvider/types.js +2 -0
  23. package/dist/esm/lib/RouterProvider/types.js.map +1 -0
  24. package/dist/esm/lib/createHydratedRouter.js +29 -0
  25. package/dist/esm/lib/createHydratedRouter.js.map +1 -0
  26. package/dist/esm/lib/hooks/index.js +9 -0
  27. package/dist/esm/lib/hooks/index.js.map +1 -0
  28. package/dist/esm/lib/hooks/types.js +9 -0
  29. package/dist/esm/lib/hooks/types.js.map +1 -0
  30. package/dist/esm/lib/hooks/useBlocker.js +43 -0
  31. package/dist/esm/lib/hooks/useBlocker.js.map +1 -0
  32. package/dist/esm/lib/hooks/useNavigationState.js +16 -0
  33. package/dist/esm/lib/hooks/useNavigationState.js.map +1 -0
  34. package/dist/esm/lib/hooks/useRoute.js +59 -0
  35. package/dist/esm/lib/hooks/useRoute.js.map +1 -0
  36. package/dist/esm/lib/hooks/useRouter.js +17 -0
  37. package/dist/esm/lib/hooks/useRouter.js.map +1 -0
  38. package/dist/esm/lib/hooks/useRouterState.js +26 -0
  39. package/dist/esm/lib/hooks/useRouterState.js.map +1 -0
  40. package/dist/esm/lib/hooks/useSearchParam.js +18 -0
  41. package/dist/esm/lib/hooks/useSearchParam.js.map +1 -0
  42. package/dist/esm/lib/hooks/useSearchParams.js +46 -0
  43. package/dist/esm/lib/hooks/useSearchParams.js.map +1 -0
  44. package/dist/esm/lib/index.js +9 -0
  45. package/dist/esm/lib/index.js.map +1 -0
  46. package/dist/esm/lib/register.js +2 -0
  47. package/dist/esm/lib/register.js.map +1 -0
  48. package/dist/esm/lib/renderToStream.js +38 -0
  49. package/dist/esm/lib/renderToStream.js.map +1 -0
  50. package/dist/esm/lib/types.js +2 -0
  51. package/dist/esm/lib/types.js.map +1 -0
  52. package/dist/types/index.d.ts +7 -0
  53. package/dist/types/index.d.ts.map +1 -0
  54. package/dist/types/lib/Link/Link.d.ts +17 -0
  55. package/dist/types/lib/Link/Link.d.ts.map +1 -0
  56. package/dist/types/lib/Link/index.d.ts +3 -0
  57. package/dist/types/lib/Link/index.d.ts.map +1 -0
  58. package/dist/types/lib/Link/types.d.ts +33 -0
  59. package/dist/types/lib/Link/types.d.ts.map +1 -0
  60. package/dist/types/lib/Outlet/Outlet.d.ts +17 -0
  61. package/dist/types/lib/Outlet/Outlet.d.ts.map +1 -0
  62. package/dist/types/lib/Outlet/index.d.ts +3 -0
  63. package/dist/types/lib/Outlet/index.d.ts.map +1 -0
  64. package/dist/types/lib/Outlet/types.d.ts +7 -0
  65. package/dist/types/lib/Outlet/types.d.ts.map +1 -0
  66. package/dist/types/lib/RouterProvider/Context.d.ts +9 -0
  67. package/dist/types/lib/RouterProvider/Context.d.ts.map +1 -0
  68. package/dist/types/lib/RouterProvider/Provider.d.ts +11 -0
  69. package/dist/types/lib/RouterProvider/Provider.d.ts.map +1 -0
  70. package/dist/types/lib/RouterProvider/index.d.ts +3 -0
  71. package/dist/types/lib/RouterProvider/index.d.ts.map +1 -0
  72. package/dist/types/lib/RouterProvider/types.d.ts +12 -0
  73. package/dist/types/lib/RouterProvider/types.d.ts.map +1 -0
  74. package/dist/types/lib/createHydratedRouter.d.ts +15 -0
  75. package/dist/types/lib/createHydratedRouter.d.ts.map +1 -0
  76. package/dist/types/lib/hooks/index.d.ts +10 -0
  77. package/dist/types/lib/hooks/index.d.ts.map +1 -0
  78. package/dist/types/lib/hooks/types.d.ts +20 -0
  79. package/dist/types/lib/hooks/types.d.ts.map +1 -0
  80. package/dist/types/lib/hooks/useBlocker.d.ts +25 -0
  81. package/dist/types/lib/hooks/useBlocker.d.ts.map +1 -0
  82. package/dist/types/lib/hooks/useNavigationState.d.ts +11 -0
  83. package/dist/types/lib/hooks/useNavigationState.d.ts.map +1 -0
  84. package/dist/types/lib/hooks/useRoute.d.ts +12 -0
  85. package/dist/types/lib/hooks/useRoute.d.ts.map +1 -0
  86. package/dist/types/lib/hooks/useRouter.d.ts +11 -0
  87. package/dist/types/lib/hooks/useRouter.d.ts.map +1 -0
  88. package/dist/types/lib/hooks/useRouterState.d.ts +14 -0
  89. package/dist/types/lib/hooks/useRouterState.d.ts.map +1 -0
  90. package/dist/types/lib/hooks/useSearchParam.d.ts +13 -0
  91. package/dist/types/lib/hooks/useSearchParam.d.ts.map +1 -0
  92. package/dist/types/lib/hooks/useSearchParams.d.ts +14 -0
  93. package/dist/types/lib/hooks/useSearchParams.d.ts.map +1 -0
  94. package/dist/types/lib/index.d.ts +9 -0
  95. package/dist/types/lib/index.d.ts.map +1 -0
  96. package/dist/types/lib/register.d.ts +29 -0
  97. package/dist/types/lib/register.d.ts.map +1 -0
  98. package/dist/types/lib/renderToStream.d.ts +16 -0
  99. package/dist/types/lib/renderToStream.d.ts.map +1 -0
  100. package/dist/types/lib/types.d.ts +41 -0
  101. package/dist/types/lib/types.d.ts.map +1 -0
  102. package/package.json +67 -0
package/README.md ADDED
@@ -0,0 +1,452 @@
1
+ # @canonical/router-react
2
+
3
+ React bindings for `@canonical/router-core`. `@canonical/router-react` turns a core router into React context, hooks, links, outlets, and SSR helpers while preserving the flat-route model from the core package.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ bun add @canonical/router-core @canonical/router-react
9
+ ```
10
+
11
+ Requires `react` and `react-dom`.
12
+
13
+ ## Quick start
14
+
15
+ ### 1. Define routes in core
16
+
17
+ ```tsx
18
+ import { createRouter, route } from "@canonical/router-core";
19
+
20
+ export const routes = {
21
+ home: route({
22
+ url: "/",
23
+ content: () => <h1>Home</h1>,
24
+ }),
25
+ docs: route({
26
+ url: "/docs/:slug",
27
+ content: ({ params }) => <h1>{params.slug}</h1>,
28
+ }),
29
+ } as const;
30
+
31
+ export const router = createRouter(routes);
32
+ ```
33
+
34
+ `@canonical/router-core` owns route definitions, matching, and typed navigation. `@canonical/router-react` layers React rendering and subscriptions on top.
35
+
36
+ Route authoring story, in short:
37
+
38
+ - define every route with `route()`
39
+ - give it a `url` pattern such as `/docs/:slug`
40
+ - optionally add `prefetch`, `content`, and `wrappers`
41
+ - create one router from the full flat route map
42
+ - let the router match incoming URLs — React renders the result
43
+
44
+ ### 2. Provide the router and render the current match
45
+
46
+ ```tsx
47
+ import { Outlet, RouterProvider } from "@canonical/router-react";
48
+
49
+ export default function Application() {
50
+ return (
51
+ <RouterProvider router={router}>
52
+ <Outlet />
53
+ </RouterProvider>
54
+ );
55
+ }
56
+ ```
57
+
58
+ `RouterProvider` makes the router instance available to hooks and components. `Outlet` renders the currently matched route subtree.
59
+
60
+ ### 3. Navigate with typed links and observe router state
61
+
62
+ ```tsx
63
+ import {
64
+ Link,
65
+ useNavigationState,
66
+ useRoute,
67
+ useRouterState,
68
+ useSearchParam,
69
+ useSearchParams,
70
+ } from "@canonical/router-react";
71
+
72
+ function Navigation() {
73
+ const navigationState = useNavigationState();
74
+ const location = useRoute();
75
+ const status = useRouterState((state) => state.match?.status ?? 404);
76
+ const tab = useSearchParam("tab");
77
+ const search = useSearchParams();
78
+
79
+ return (
80
+ <nav>
81
+ <Link to="home">Home</Link>
82
+ <Link params={{ slug: "getting-started" }} to="docs">
83
+ Docs
84
+ </Link>
85
+ <span>{navigationState}</span>
86
+ <span>{status}</span>
87
+ <span>{location.pathname}</span>
88
+ <span>{tab ?? "overview"}</span>
89
+ <span>{search.toString()}</span>
90
+ </nav>
91
+ );
92
+ }
93
+ ```
94
+
95
+ All hooks and `Link` default to `RegisteredRouteMap`. Register your route map once in your router file to get full type inference without explicit generics:
96
+
97
+ ```ts
98
+ declare module "@canonical/router-react" {
99
+ interface RouterRegister {
100
+ routes: typeof appRoutes;
101
+ }
102
+ }
103
+ ```
104
+
105
+ Explicit generics (`<typeof routes>`) still work as an escape hatch for multi-router apps or library code.
106
+
107
+ Important distinction:
108
+
109
+ - `useRouterState()` returns the full router state or a selected slice.
110
+ - `useRoute()` returns the current tracked location object.
111
+ - `useSearchParam()` returns the value of one query-string key.
112
+ - `useSearchParams()` returns all search params or a selected subset of keys.
113
+ - `useNavigationState()` returns the router's navigation lifecycle state.
114
+ - `useRouter()` returns the router instance itself.
115
+
116
+ ## Data ownership
117
+
118
+ The router does not own data. `content()` receives `params` and `search` — not data. Components fetch their own data from their cache library (Relay, TanStack Query, SWR, etc.).
119
+
120
+ The optional `prefetch()` on routes is a fire-and-forget navigation-time hook. Use it to warm caches, preload assets, or run side effects before the component renders. It does not pass data to `content()`.
121
+
122
+ ```tsx
123
+ const userRoute = route({
124
+ url: "/users/:id",
125
+ prefetch: async ({ id }) => {
126
+ await queryClient.prefetchQuery(["user", id], () => fetchUser(id));
127
+ },
128
+ content: ({ params }) => <UserProfile id={params.id} />,
129
+ });
130
+
131
+ function UserProfile({ id }: { id: string }) {
132
+ const { data } = useQuery(["user", id], () => fetchUser(id));
133
+ return <h1>{data.name}</h1>;
134
+ }
135
+ ```
136
+
137
+ ## Error handling
138
+
139
+ The router does not ship an error boundary component. When `prefetch()` throws, the error propagates into the React render tree and is caught by the nearest React error boundary.
140
+
141
+ Use `StatusResponse` from `@canonical/router-core` to signal HTTP-like errors:
142
+
143
+ ```tsx
144
+ import { StatusResponse } from "@canonical/router-core";
145
+
146
+ function ErrorFallback({ error }: { error: unknown }) {
147
+ const status = error instanceof StatusResponse ? error.status : 500;
148
+
149
+ if (status === 404) return <NotFound />;
150
+ if (status === 401) return <LoginRedirect />;
151
+ return <ErrorPage status={status} />;
152
+ }
153
+
154
+ function DashboardLayout({ children }: { children: React.ReactNode }) {
155
+ return (
156
+ <div>
157
+ <Sidebar />
158
+ <ErrorBoundary fallbackRender={({ error }) => <ErrorFallback error={error} />}>
159
+ {children}
160
+ </ErrorBoundary>
161
+ </div>
162
+ );
163
+ }
164
+ ```
165
+
166
+ The boilerplate reference app provides a complete `RouteErrorBoundary` implementation to copy and adapt.
167
+
168
+ ## Search param mutation
169
+
170
+ Update search params from any component via the router instance:
171
+
172
+ ```tsx
173
+ function FilterBar() {
174
+ const router = useRouter();
175
+ const sort = useSearchParam("sort");
176
+
177
+ return (
178
+ <select
179
+ value={sort ?? "name"}
180
+ onChange={(event) => {
181
+ router.setSearchParams({ sort: event.target.value }, { replace: true });
182
+ }}
183
+ >
184
+ <option value="name">Name</option>
185
+ <option value="date">Date</option>
186
+ </select>
187
+ );
188
+ }
189
+ ```
190
+
191
+ `setSearchParams` merges into the current URL. Set a key to `null` to remove it. Pass `{ replace: true }` to replace the history entry instead of pushing.
192
+
193
+ ## Navigation blocking
194
+
195
+ `useBlocker()` prevents navigation when the component has unsaved state. The hook returns a state object — the consumer controls the confirmation UI:
196
+
197
+ ```tsx
198
+ import { useBlocker } from "@canonical/router-react";
199
+ import { useState } from "react";
200
+
201
+ function EditForm() {
202
+ const [isDirty, setIsDirty] = useState(false);
203
+ const blocker = useBlocker(isDirty);
204
+
205
+ return (
206
+ <>
207
+ <form onChange={() => setIsDirty(true)}>
208
+ <textarea placeholder="Start typing to mark as dirty..." />
209
+ <button
210
+ type="submit"
211
+ onClick={(event) => {
212
+ event.preventDefault();
213
+ setIsDirty(false);
214
+ }}
215
+ >
216
+ Save
217
+ </button>
218
+ </form>
219
+
220
+ {blocker.state === "blocked" && (
221
+ <div role="alertdialog" aria-modal="true">
222
+ <h2>Unsaved changes</h2>
223
+ <p>You have unsaved changes. Do you want to leave this page?</p>
224
+ <button onClick={blocker.cancel}>Stay on page</button>
225
+ <button onClick={blocker.proceed}>Leave page</button>
226
+ </div>
227
+ )}
228
+ </>
229
+ );
230
+ }
231
+ ```
232
+
233
+ For a quick `window.confirm` approach instead of a custom dialog:
234
+
235
+ ```tsx
236
+ import { useBlocker } from "@canonical/router-react";
237
+ import { useEffect, useState } from "react";
238
+
239
+ function QuickEditForm() {
240
+ const [isDirty, setIsDirty] = useState(false);
241
+ const blocker = useBlocker(isDirty);
242
+
243
+ useEffect(() => {
244
+ if (blocker.state === "blocked") {
245
+ if (window.confirm("You have unsaved changes. Leave anyway?")) {
246
+ blocker.proceed();
247
+ } else {
248
+ blocker.cancel();
249
+ }
250
+ }
251
+ }, [blocker]);
252
+
253
+ return <form onChange={() => setIsDirty(true)}>...</form>;
254
+ }
255
+ ```
256
+
257
+ The blocker registers on mount and unregisters on unmount — when the form is submitted or the component is removed, blocking stops automatically.
258
+
259
+ ## Creating routes and matching URLs
260
+
261
+ ### Route creation
262
+
263
+ Each entry in the route map is a named call to `route()`.
264
+
265
+ ```tsx
266
+ import { createRouter, route } from "@canonical/router-core";
267
+
268
+ const routes = {
269
+ home: route({
270
+ url: "/",
271
+ content: () => <h1>Home</h1>,
272
+ }),
273
+ docs: route({
274
+ url: "/docs/:slug",
275
+ prefetch: async ({ slug }) => {
276
+ await queryClient.prefetchQuery(["doc", slug], () => fetchDoc(slug));
277
+ },
278
+ content: ({ params }) => <DocPage slug={params.slug} />,
279
+ }),
280
+ accountSettings: route({
281
+ url: "/account/settings",
282
+ content: () => <h1>Settings</h1>,
283
+ }),
284
+ } as const;
285
+
286
+ const router = createRouter(routes);
287
+ ```
288
+
289
+ Important parts:
290
+
291
+ - the route-map key such as `docs` is the typed navigation name used by `Link` and `router.navigate()`
292
+ - the `url` string is the matcher used for incoming URLs
293
+ - `:slug` segments become typed route params
294
+ - `prefetch` runs at navigation time as a fire-and-forget hook
295
+ - `content` renders the matched route, receiving `params` and `search`
296
+
297
+ Routes stay flat even when the UI is nested. Shared layout lives in wrappers from the core package, not in a nested route tree.
298
+
299
+ ## SSR
300
+
301
+ ### Server side
302
+
303
+ Wire your own render tree using standard React SSR primitives. Use `createStaticRouter` for server rendering — it matches on construction and fires `prefetch()` eagerly so caches start warming before React renders:
304
+
305
+ ```tsx
306
+ import { createStaticRouter } from "@canonical/router-core";
307
+ import { createHeadCollector, HeadProvider } from "@canonical/react-head";
308
+ import { Outlet, RouterProvider } from "@canonical/router-react";
309
+ import { renderToPipeableStream } from "react-dom/server";
310
+
311
+ app.get("*", (req, res) => {
312
+ const router = createStaticRouter(routes, req.url);
313
+ const headCollector = createHeadCollector();
314
+
315
+ // Check match for status code before rendering
316
+ if (!router.match) {
317
+ res.status(404);
318
+ } else if (router.match.kind === "redirect") {
319
+ return res.redirect(router.match.status, router.match.redirectTo);
320
+ }
321
+
322
+ const { pipe } = renderToPipeableStream(
323
+ <HeadProvider collector={headCollector}>
324
+ <RouterProvider router={router}>
325
+ <Shell>
326
+ <Outlet />
327
+ </Shell>
328
+ </RouterProvider>
329
+ </HeadProvider>,
330
+ {
331
+ onShellReady() {
332
+ const headHtml = headCollector.toHtml();
333
+ res.setHeader("content-type", "text/html");
334
+ res.write(`<!doctype html><html><head>${headHtml}</head><body>`);
335
+ pipe(res);
336
+ },
337
+ },
338
+ );
339
+ });
340
+ ```
341
+
342
+ The router dehydrates navigation state only. Data dehydration is the cache library's responsibility (dual dehydration):
343
+
344
+ ```tsx
345
+ // In onShellReady or after render:
346
+ const routerState = router.dehydrate();
347
+ const cacheState = queryClient.dehydrate(); // TanStack Query, Relay, etc.
348
+
349
+ // Inject both into the HTML template
350
+ res.write(`<script>
351
+ window.__ROUTER_STATE__ = ${JSON.stringify(routerState)};
352
+ window.__QUERY_DATA__ = ${JSON.stringify(cacheState)};
353
+ </script>`);
354
+ ```
355
+
356
+ ### Client side
357
+
358
+ ```tsx
359
+ import { createBrowserRouter } from "@canonical/router-core";
360
+ import { HeadProvider } from "@canonical/react-head";
361
+ import { Outlet, RouterProvider } from "@canonical/router-react";
362
+
363
+ const router = createBrowserRouter(routes, {
364
+ hydratedState: window.__ROUTER_STATE__,
365
+ });
366
+
367
+ hydrateRoot(
368
+ document,
369
+ <HeadProvider>
370
+ <RouterProvider router={router}>
371
+ <Shell>
372
+ <Outlet />
373
+ </Shell>
374
+ </RouterProvider>
375
+ </HeadProvider>,
376
+ );
377
+ ```
378
+
379
+ `createBrowserRouter` uses the Navigation API when available (Baseline Newly Available since January 2026), falling back to the History API.
380
+
381
+ ## Progressive disclosure
382
+
383
+ ### `Link`
384
+
385
+ `Link` builds typed hrefs from route names and optional route params, search data, and hash values. Primary-button clicks are intercepted and routed through the core router. Hover prefetches the destination.
386
+
387
+ ```tsx
388
+ <Link<typeof routes> params={{ slug: "api" }} to="docs">
389
+ API docs
390
+ </Link>
391
+ ```
392
+
393
+ ### `Outlet`
394
+
395
+ `Outlet` subscribes to router state, calls `router.render()`, and wraps the matched subtree in `Suspense`.
396
+
397
+ ```tsx
398
+ <Outlet fallback={<p>Loading route…</p>} />
399
+ ```
400
+
401
+ ### Hooks
402
+
403
+ - `useBlocker(isActive)` blocks navigation when `isActive` is `true`. Returns `{ state, proceed, cancel }`.
404
+ - `useNavigationState()` subscribes to the router loading state.
405
+ - `useRoute()` returns a tracked location proxy and rerenders only when an accessed location key changes.
406
+ - `useRouter()` returns the router instance from context. Use `useRouter().setSearchParams()` for search param mutation.
407
+ - `useRouterState()` is the power-user hook for subscribing to selected slices of `router.getState()`.
408
+ - `useSearchParam()` subscribes to one query-string key.
409
+ - `useSearchParams()` subscribes either to the full query string or to a fixed set of keys.
410
+
411
+ Typical selection strategy:
412
+
413
+ - reach for `useBlocker()` when a form has unsaved state
414
+ - reach for `useNavigationState()` when you only need loading lifecycle
415
+ - reach for `useSearchParam()` for one query-string key
416
+ - reach for `useSearchParams()` for a fixed key set or the full query string
417
+ - reach for `useRoute()` for pathname, hash, or full URL reads
418
+ - reach for `useRouter()` for search param mutation or direct router access
419
+ - reach for `useRouterState()` when you need `match`, `navigation`, or other advanced state in one selector
420
+
421
+ ## Boilerplate reference
422
+
423
+ The reference integration lives in [apps/react/boilerplate-vite](../../../apps/react/boilerplate-vite). It shows:
424
+
425
+ - domain-colocated route modules
426
+ - a shell-as-route-provider layout
427
+ - SSR + hydration
428
+ - hover prefetch
429
+ - auth middleware redirect flow
430
+ - error handling with `StatusResponse` and React error boundaries
431
+
432
+ ## Public API
433
+
434
+ ### Components and helpers
435
+
436
+ - `createHydratedRouter()` — create a browser-backed router that resumes from dehydrated state.
437
+ - `Link` — render a typed anchor that navigates and prefetches through the router.
438
+ - `Outlet` — render the current matched subtree.
439
+ - `RouterProvider` — place a router instance into React context.
440
+ - `useBlocker()` — block navigation when the component has unsaved state.
441
+ - `useNavigationState()` — subscribe to the navigation lifecycle state.
442
+ - `useRoute()` — subscribe to a tracked location object.
443
+ - `useRouter()` — read the router instance from context.
444
+ - `useRouterState()` — subscribe to the full router state or a selected slice.
445
+ - `useSearchParam()` — subscribe to one search-param key.
446
+ - `useSearchParams()` — subscribe to all search params or a selected key set.
447
+
448
+ ### Reference docs
449
+
450
+ - Full API reference: [docs/references/ROUTER_API.md](../../../docs/references/ROUTER_API.md)
451
+ - Migration guide: [docs/how-to-guides/MIGRATE_FROM_TANSTACK_ROUTER.md](../../../docs/how-to-guides/MIGRATE_FROM_TANSTACK_ROUTER.md)
452
+ - Middleware cookbook: [docs/how-to-guides/ROUTER_MIDDLEWARE_COOKBOOK.md](../../../docs/how-to-guides/ROUTER_MIDDLEWARE_COOKBOOK.md)
@@ -0,0 +1,7 @@
1
+ /**
2
+ * @canonical/router-react — React bindings for @canonical/router-core.
3
+ *
4
+ * @packageDocumentation
5
+ */
6
+ export * from "./lib/index.js";
7
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,cAAc,gBAAgB,CAAC"}
@@ -0,0 +1,68 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { forwardRef } from "react";
3
+ import useRoute from "../hooks/useRoute.js";
4
+ import useRouter from "../hooks/useRouter.js";
5
+ function hasModifierKey(event) {
6
+ return event.altKey || event.ctrlKey || event.metaKey || event.shiftKey;
7
+ }
8
+ function buildOptionsObject(options) {
9
+ return Object.fromEntries(Object.entries(options).filter(([, value]) => value !== undefined));
10
+ }
11
+ /**
12
+ * Render an anchor element that integrates with the router.
13
+ *
14
+ * `Link` builds the destination `href` from a typed route name plus optional
15
+ * params, search values, and hash. Primary-button clicks are intercepted and
16
+ * routed through `router.navigate()`, while hover prefetches the destination
17
+ * route data through `router.prefetch()`.
18
+ *
19
+ * Sets `aria-current="page"` when the link target matches the current location.
20
+ */
21
+ const Link = forwardRef(function Link({ children, download, hash, onClick, onMouseEnter, params, replace, search, target, to, ...props }, forwardedRef) {
22
+ const router = useRouter();
23
+ const location = useRoute();
24
+ const buildPath = router.buildPath;
25
+ const navigate = router.navigate;
26
+ const prefetch = router.prefetch;
27
+ const buildOptions = buildOptionsObject({
28
+ hash,
29
+ params,
30
+ replace,
31
+ search,
32
+ });
33
+ const hasOptions = Object.keys(buildOptions).length > 0;
34
+ const href = hasOptions
35
+ ? buildPath(to, buildOptions)
36
+ : buildPath(to);
37
+ const isCurrent = location.pathname === href.split("?")[0].split("#")[0];
38
+ return (_jsx("a", { ...props, "aria-current": isCurrent ? "page" : undefined, download: download, href: href, onClick: (event) => {
39
+ onClick?.(event);
40
+ if (event.defaultPrevented ||
41
+ event.button !== 0 ||
42
+ hasModifierKey(event) ||
43
+ target === "_blank" ||
44
+ download !== undefined) {
45
+ return;
46
+ }
47
+ event.preventDefault();
48
+ if (hasOptions) {
49
+ navigate(to, buildOptions);
50
+ }
51
+ else {
52
+ navigate(to);
53
+ }
54
+ }, onMouseEnter: (event) => {
55
+ onMouseEnter?.(event);
56
+ if (event.defaultPrevented) {
57
+ return;
58
+ }
59
+ if (hasOptions) {
60
+ void prefetch(to, buildOptions);
61
+ }
62
+ else {
63
+ void prefetch(to);
64
+ }
65
+ }, ref: forwardedRef, target: target, children: children }));
66
+ });
67
+ export default Link;
68
+ //# sourceMappingURL=Link.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Link.js","sourceRoot":"","sources":["../../../../src/lib/Link/Link.tsx"],"names":[],"mappings":";AAOA,OAAO,EAAE,UAAU,EAAE,MAAM,OAAO,CAAC;AACnC,OAAO,QAAQ,MAAM,sBAAsB,CAAC;AAC5C,OAAO,SAAS,MAAM,uBAAuB,CAAC;AAI9C,SAAS,cAAc,CAAC,KAAoC;IAC1D,OAAO,KAAK,CAAC,MAAM,IAAI,KAAK,CAAC,OAAO,IAAI,KAAK,CAAC,OAAO,IAAI,KAAK,CAAC,QAAQ,CAAC;AAC1E,CAAC;AAED,SAAS,kBAAkB,CACzB,OAAmC;IAEnC,OAAO,MAAM,CAAC,WAAW,CACvB,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,KAAK,KAAK,SAAS,CAAC,CACnE,CAAC;AACJ,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,IAAI,GAAG,UAAU,CAAC,SAAS,IAAI,CAInC,EACE,QAAQ,EACR,QAAQ,EACR,IAAI,EACJ,OAAO,EACP,YAAY,EACZ,MAAM,EACN,OAAO,EACP,MAAM,EACN,MA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I,UAAU,EAAE,CAAC;gBACf,QAAQ,CACN,EAAE,EACF,YAAyD,CAC1D,CAAC;YACJ,CAAC;iBAAM,CAAC;gBACN,QAAQ,CAAC,EAAE,CAAC,CAAC;YACf,CAAC;QACH,CAAC,EACD,YAAY,EAAE,CAAC,KAAK,EAAE,EAAE;YACtB,YAAY,EAAE,CAAC,KAAK,CAAC,CAAC;YAEtB,IAAI,KAAK,CAAC,gBAAgB,EAAE,CAAC;gBAC3B,OAAO;YACT,CAAC;YAED,IAAI,UAAU,EAAE,CAAC;gBACf,KAAK,QAAQ,CACX,EAAE,EACF,YAAyD,CAC1D,CAAC;YACJ,CAAC;iBAAM,CAAC;gBACN,KAAK,QAAQ,CAAC,EAAE,CAAC,CAAC;YACpB,CAAC;QACH,CAAC,EACD,GAAG,EAAE,YAAY,EACjB,MAAM,EAAE,MAAM,YAEb,QAAQ,GACP,CACL,CAAC;AACJ,CAAC,CAKgB,CAAC;AAElB,eAAe,IAAI,CAAC"}
@@ -0,0 +1,2 @@
1
+ export { default as Link } from "./Link.js";
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/lib/Link/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,IAAI,IAAI,EAAE,MAAM,WAAW,CAAC"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../src/lib/Link/types.ts"],"names":[],"mappings":""}
@@ -0,0 +1,40 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { Suspense, useCallback, useRef, useSyncExternalStore } from "react";
3
+ import useRouter from "../hooks/useRouter.js";
4
+ /**
5
+ * Render the router's currently matched React subtree.
6
+ *
7
+ * `Outlet` subscribes to router state and only rerenders when the location
8
+ * href changes — navigation-state transitions (`idle` → `loading`) do not
9
+ * cause a rerender. The rendered content is keyed by route name so React
10
+ * cleanly unmounts/remounts when the matched route changes.
11
+ *
12
+ * Component-level render errors (e.g. a route's error component itself throws)
13
+ * propagate past `Outlet`. Wrap it in a React `ErrorBoundary` to catch those.
14
+ * The router handles data errors (fetch failures, status codes); React handles
15
+ * render errors.
16
+ */
17
+ export default function Outlet({ fallback = null }) {
18
+ const router = useRouter();
19
+ const hrefRef = useRef(router.getState().location.href);
20
+ const matchRef = useRef(router.getState().match);
21
+ const versionRef = useRef(0);
22
+ const subscribe = useCallback((onStoreChange) => router.subscribe((snapshot) => {
23
+ const nextHref = snapshot.href;
24
+ const nextMatch = snapshot.match;
25
+ if (nextHref !== hrefRef.current || nextMatch !== matchRef.current) {
26
+ hrefRef.current = nextHref;
27
+ matchRef.current = nextMatch;
28
+ versionRef.current += 1;
29
+ onStoreChange();
30
+ }
31
+ }), [router]);
32
+ useSyncExternalStore(subscribe, () => versionRef.current, () => versionRef.current);
33
+ const match = router.getState().match;
34
+ const routeKey = match && "name" in match && typeof match.name === "string"
35
+ ? match.name
36
+ : undefined;
37
+ const rendered = router.render();
38
+ return (_jsx(Suspense, { fallback: fallback, children: rendered }, routeKey));
39
+ }
40
+ //# sourceMappingURL=Outlet.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Outlet.js","sourceRoot":"","sources":["../../../../src/lib/Outlet/Outlet.tsx"],"names":[],"mappings":";AACA,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,EAAE,oBAAoB,EAAE,MAAM,OAAO,CAAC;AAC5E,OAAO,SAAS,MAAM,uBAAuB,CAAC;AAG9C;;;;;;;;;;;;GAYG;AACH,MAAM,CAAC,OAAO,UAAU,MAAM,CAAC,EAAE,QAAQ,GAAG,IAAI,EAAe;IAC7D,MAAM,MAAM,GAAG,SAAS,EAAE,CAAC;IAC3B,MAAM,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,QAAQ,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;IACxD,MAA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Outlet.js";
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/lib/Outlet/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,IAAI,MAAM,EAAE,MAAM,aAAa,CAAC"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../src/lib/Outlet/types.ts"],"names":[],"mappings":""}
@@ -0,0 +1,9 @@
1
+ import { createContext } from "react";
2
+ /**
3
+ * React context that carries the active router instance.
4
+ *
5
+ * `RouterProvider` writes to this context and `useRouter()` reads from it.
6
+ */
7
+ const RouterContext = createContext(null);
8
+ export default RouterContext;
9
+ //# sourceMappingURL=Context.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Context.js","sourceRoot":"","sources":["../../../../src/lib/RouterProvider/Context.tsx"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,OAAO,CAAC;AAGtC;;;;GAIG;AACH,MAAM,aAAa,GAAG,aAAa,CAAwB,IAAI,CAAC,CAAC;AAEjE,eAAe,aAAa,CAAC"}
@@ -0,0 +1,12 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import RouterContext from "./Context.js";
3
+ /**
4
+ * Provide a router instance to router-react hooks and components.
5
+ *
6
+ * Mount this once around the subtree that should be able to call hooks such as
7
+ * `useRouter()`, `useRoute()`, or `useSearchParam()`.
8
+ */
9
+ export default function RouterProvider({ children, router }) {
10
+ return (_jsx(RouterContext.Provider, { value: router, children: children }));
11
+ }
12
+ //# sourceMappingURL=Provider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Provider.js","sourceRoot":"","sources":["../../../../src/lib/RouterProvider/Provider.tsx"],"names":[],"mappings":";AAEA,OAAO,aAAa,MAAM,cAAc,CAAC;AAGzC;;;;;GAKG;AACH,MAAM,CAAC,OAAO,UAAU,cAAc,CAGpC,EAAE,QAAQ,EAAE,MAAM,EAA2C;IAC7D,OAAO,CACL,KAAC,aAAa,CAAC,QAAQ,IAAC,KAAK,EAAE,MAAmC,YAC/D,QAAQ,GACc,CAC1B,CAAC;AACJ,CAAC"}
@@ -0,0 +1,2 @@
1
+ export { default as RouterProvider } from "./Provider.js";
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/lib/RouterProvider/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,IAAI,cAAc,EAAE,MAAM,eAAe,CAAC"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../src/lib/RouterProvider/types.ts"],"names":[],"mappings":""}