@luwiostack/router 0.2.0 → 0.4.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
@@ -297,6 +297,7 @@ TanStack route option is accepted and forwarded untouched**.
297
297
  | `validateSearch` | `(search) => T` | Parse/validate the query string into typed `search`. |
298
298
  | `title` / `description` | `(ctx) => string` | **Required** for URL routes (SEO). The router emits them (plus canonical, hreflang, og) into the head. `ctx.context.locale` is the active locale. See below. |
299
299
  | `head` | `(ctx) => RouteHead` | **Optional** extra head tags beyond the SEO essentials the router already emits. See below. |
300
+ | `onPageView` | `(ctx) => void` | **Optional.** Runs for each page view of this route (not inherited; URL routes only). See [Page views](#page-views). |
300
301
  | `component` | component | The page (or a layout shell around `<Outlet />`). |
301
302
  | `pendingComponent` | component | Shown while the loader is pending. |
302
303
  | `errorComponent` | component | Shown when the route (or a child) throws. |
@@ -305,6 +306,7 @@ TanStack route option is accepted and forwarded untouched**.
305
306
  | `shouldReload` | `boolean \| (ctx) => boolean` | Whether the loader re-runs on navigation. |
306
307
  | `caseSensitive` | `boolean` | Case-sensitive path matching. |
307
308
  | `wrapInSuspense` | `boolean` | Wrap the component in `<Suspense>`. |
309
+ | `staticData` | `RouteStaticData` | Static flags for this route and its children, read with `useRouteStaticData()`. See [Route flags](#route-flags-staticdata). |
308
310
  | _…anything else_ | | Forwarded to TanStack's `createRoute` untouched. |
309
311
 
310
312
  \* required. `path` and `getParentRoute` are **not** accepted — the URL segment comes from
@@ -485,6 +487,38 @@ Resulting tree — `auth` and `app` never appear in the URL, but run on every re
485
487
  | `en-BE` | `/en-BE/account` |
486
488
  | `fr-BE` | `/fr-BE/compte` |
487
489
 
490
+ ## Route flags (`staticData`)
491
+
492
+ Some app chrome depends on the page: no cookie banner over the privacy policy, a full-bleed layout,
493
+ a hidden footer. Put that decision on the route itself with `staticData`, and read it back anywhere
494
+ under the router with `useRouteStaticData()` — also in a shell or banner outside the page component.
495
+ No path checks needed, so it keeps working across locales and translated aliases.
496
+
497
+ ```tsx
498
+ // Type your flags once.
499
+ declare module '@luwiostack/router' {
500
+ interface RouteStaticData {
501
+ hideCookieBanner?: boolean
502
+ }
503
+ }
504
+
505
+ // privacy.route.tsx
506
+ export default createRoute({
507
+ id: 'privacy',
508
+ staticData: { hideCookieBanner: true },
509
+ title, description, component: Privacy,
510
+ })
511
+
512
+ // CookieBanner.tsx (rendered by the app shell, on every page)
513
+ const hideBanner = useRouteStaticData((d) => d.hideCookieBanner === true)
514
+ ```
515
+
516
+ The flags **merge down the matched tree**: a layout route's flags apply to every child, and the
517
+ deepest route that sets a key wins — put `hideCookieBanner` on a `legal` layout and every legal page
518
+ gets it. Without a `select`, `useRouteStaticData()` returns the whole merged object (`{}` when no
519
+ route sets any). The flags are static: anything that depends on params or loaded data belongs in
520
+ `beforeLoad` / `loader` instead.
521
+
488
522
  ## Config-driven availability
489
523
 
490
524
  `createRouter`'s config decides what actually mounts, so one build can serve different route/locale
@@ -813,6 +847,42 @@ On an unprefixed route the active locale is the default locale — `useRouter().
813
847
  the default locale: `router.href({ id: 'home' })` returns `/home`, not `/nl-BE/home` — so `navigate`
814
848
  and every generated link stay unprefixed while you're in the default locale.
815
849
 
850
+ ## Page views
851
+
852
+ A route's `onPageView` runs for each page view of that route: once for the first load, then once per
853
+ navigation that resolves to a different path or query string. Track it there, next to `title()` and
854
+ `head()` — the router knows nothing about analytics.
855
+
856
+ ```ts
857
+ const about = createRoute({
858
+ id: 'about',
859
+ parent: 'shell',
860
+ title: ({ context }) => context.t('about.title'),
861
+ description: ({ context }) => context.t('about.body'),
862
+ // { context: { routeId: 'about', locale, … }, title: 'Over ons', path: '/nl-BE/over-ons',
863
+ // href: '/nl-BE/over-ons?ref=mail', params: {}, search: { ref: 'mail' } }
864
+ onPageView: ({ context, title }) =>
865
+ context.analytics.pageView({ title, route_id: context.routeId }),
866
+ })
867
+ ```
868
+
869
+ Put what it needs on context: an ancestor's `beforeLoad` (`return { analytics }`) or the router's
870
+ own context (`createRouter(registry, { …, router: { context: { analytics } } })`), typed by augmenting
871
+ `RouteContext`.
872
+
873
+ - **Only the page's own.** It runs for the route that is the page and isn't inherited: a child's page
874
+ view never runs its parent's `onPageView`. A layout route can't set one (`createRouter` throws).
875
+ - **One per page.** A hash-only change isn't a new page, and neither is a re-resolve of the same URL
876
+ (`router.invalidate()`); a new query string is.
877
+ - **Route id, not path.** `context.routeId` is the same in every locale, so `/en-BE/about` and
878
+ `/nl-BE/over-ons` report as one page in two locales.
879
+ - **The route's own title.** `title` is the route's resolved `title()`, the value the router puts in
880
+ `<title>`. Read it here rather than from `document.title`, which `<HeadContent>` only updates after
881
+ render, so on a navigation it can still be the previous page's.
882
+ - **Synthetic routes are skipped.** The 404 catch-all, a forbidden guard and a legacy redirect aren't
883
+ pages: the page they redirect to runs its `onPageView` instead.
884
+ - **Browser only.** It never runs during server rendering; the client's first load reports the page.
885
+
816
886
  ## API
817
887
 
818
888
  | Export | Description |
@@ -828,7 +898,9 @@ and every generated link stay unprefixed while you're in the default locale.
828
898
  | `referrer: true` | On `href` / `navigate` / `redirect`: add the current page (in a guard, the page being loaded) as `?referrer=`. `forbidden()` adds it by default; `referrer: false` leaves it out. See [Back to the referrer](#back-to-the-referrer). |
829
899
  | `router.canGoToReferrer({ from? })` / `router.goToReferrer({ from?, replace? })` | Like `canGoBack()` / `goBack()`, but for `?referrer=` instead of history: whether there's a safe page to go back to, and go there (a no-op when there isn't). |
830
900
  | `router.referrer({ from? })` | The referrer as `{ id, params, query?, hash?, locale? }` in the active locale, or `undefined` unless it's a page on this site the router serves (and not the current route or a status page). `from` checks a value that arrived another way, like an OAuth `state`. See [Through an OAuth round trip](#through-an-oauth-round-trip). |
901
+ | `RoutePageViewCtx` | What a route's `onPageView` receives: `{ context, params, search, title, path, href }`. See [Page views](#page-views). |
831
902
  | `useRouteFailure()` | `{ status, error? } \| undefined` — the failure that redirected to the current `statusPages` page. See [Not found, forbidden & error](#not-found-forbidden--error-404--403--5xx). |
903
+ | `useRouteStaticData(select?)` | The active route's `staticData`, merged down the matched tree (deepest wins). See [Route flags](#route-flags-staticdata). |
832
904
  | `RouterProvider` / `Outlet` | Re-exported from the bundled TanStack Router. Mount the tree / render children. |
833
905
  | `HeadContent` / `Scripts` | Re-exported from the bundled TanStack Router. Render a route's `head()` tags / body scripts. |
834
906
  | `Await` / `useAwaited` / `defer` | Re-exported from the bundled TanStack Router. Stream deferred loader data (skeletons). |
@@ -836,6 +908,7 @@ and every generated link stay unprefixed while you're in the default locale.
836
908
  | `RouteConfig` / `RouterConfig` | Config types. `createRoute<TParams, TSearch>` types the handler `ctx`. |
837
909
  | `StatusPages` | The `statusPages` config type — `Record<number, string> & { default: string }`. |
838
910
  | `RouteRegister` | Augment to map `id` → `{ params?; search? }` for typed `href` / `navigate` (see below). |
911
+ | `RouteStaticData` | Augment to type the keys of `staticData` / `useRouteStaticData()`. |
839
912
 
840
913
  ## Type safety
841
914
 
package/dist/index.cjs CHANGED
@@ -7058,6 +7058,41 @@ function getRouteTag(route) {
7058
7058
  return route ? tags.get(route) : void 0;
7059
7059
  }
7060
7060
  //#endregion
7061
+ //#region src/page-view.ts
7062
+ /**
7063
+ * Call the leaf route's own `onPageView` for each page the visitor lands on: once for the first load,
7064
+ * then once per navigation that resolves to a different path or query string. A hash-only change
7065
+ * isn't a new page, and neither is a re-resolve of the same URL. Synthetic routes (the 404 catch-all,
7066
+ * a forbidden guard, a legacy redirect) are skipped; the page they redirect to is reported instead.
7067
+ * The title is the route's resolved `title()`, ready before `<HeadContent>` updates `document.title`.
7068
+ *
7069
+ * Subscribed by `createRouter` itself, before the router first loads, so the first page counts.
7070
+ */
7071
+ function reportPageViews(router, registry) {
7072
+ let lastKey;
7073
+ router.subscribe("onResolved", ({ toLocation }) => {
7074
+ const key = `${toLocation.pathname}?${toLocation.searchStr}`;
7075
+ if (key === lastKey) return;
7076
+ const leaf = router.state.matches.at(-1);
7077
+ const tag = leaf ? getRouteTag(router.routesById[leaf.routeId]) : void 0;
7078
+ if (!leaf || !tag) return;
7079
+ lastKey = key;
7080
+ const onPageView = registry.get(tag.id)?.options.onPageView;
7081
+ onPageView?.({
7082
+ context: {
7083
+ routeId: tag.id,
7084
+ locale: tag.locale,
7085
+ ...leaf.context ?? {}
7086
+ },
7087
+ params: { ...leaf.params ?? {} },
7088
+ search: { ...leaf.search ?? {} },
7089
+ title: (leaf.meta ?? []).find((m) => m?.title !== void 0)?.title ?? "",
7090
+ path: toLocation.pathname,
7091
+ href: toLocation.href
7092
+ });
7093
+ });
7094
+ }
7095
+ //#endregion
7061
7096
  //#region src/use-router.ts
7062
7097
  /** The query param the referrer travels in. */
7063
7098
  const REFERRER = "referrer";
@@ -7438,6 +7473,7 @@ function createRouter(registry, config) {
7438
7473
  }
7439
7474
  const { kept: builders, tombstones } = planRoutes(registry.all(), config);
7440
7475
  for (const b of builders) {
7476
+ if (b.layout && b.options.onPageView !== void 0) throw new Error(`Route "${b.id}" is a layout route — onPageView is only for URL routes (it isn't inherited).`);
7441
7477
  if (b.layout) continue;
7442
7478
  if (b.aliasCount === 0) throw new Error(`Route "${b.id}" has no alias — call .alias(locale, slug) at least once (only layout routes may omit it).`);
7443
7479
  if (typeof b.options.title !== "function") throw new Error(`Route "${b.id}" has no title() — it's required for SEO (layout routes exempt).`);
@@ -7478,7 +7514,7 @@ function createRouter(registry, config) {
7478
7514
  const build = (parentId, parent) => {
7479
7515
  const routes = (byParent.get(parentId) ?? []).filter((b) => b.layout || b.hasAlias(locale)).map((b) => {
7480
7516
  const head = withHead(b, locale, apiCtx);
7481
- const { title: _t, description: _d, head: _h, loader: userLoader, ...tanstackOptions } = b.options;
7517
+ const { title: _t, description: _d, head: _h, onPageView: _pv, loader: userLoader, ...tanstackOptions } = b.options;
7482
7518
  const route = buildRoute({
7483
7519
  ...tanstackOptions,
7484
7520
  getParentRoute: () => parent,
@@ -7556,6 +7592,7 @@ function createRouter(registry, config) {
7556
7592
  config,
7557
7593
  mounted
7558
7594
  });
7595
+ if (typeof document !== "undefined" && builders.some((b) => b.options.onPageView)) reportPageViews(router, registry);
7559
7596
  return router;
7560
7597
  }
7561
7598
  /** Group builders by their parent id for tree assembly. */
@@ -7865,6 +7902,7 @@ const KNOWN_KEYS = /* @__PURE__ */ new Set([
7865
7902
  "title",
7866
7903
  "description",
7867
7904
  "head",
7905
+ "onPageView",
7868
7906
  "beforeLoad",
7869
7907
  "loader",
7870
7908
  "loaderDeps",
@@ -7886,6 +7924,7 @@ const KNOWN_KEYS = /* @__PURE__ */ new Set([
7886
7924
  "preloadGcTime",
7887
7925
  "caseSensitive",
7888
7926
  "wrapInSuspense",
7927
+ "staticData",
7889
7928
  "preload",
7890
7929
  "ssr",
7891
7930
  "pendingMs",
@@ -8132,6 +8171,12 @@ function useRouteLoaderData() {
8132
8171
  function useRouteContext() {
8133
8172
  return useRouteContext$1({ strict: false });
8134
8173
  }
8174
+ function useRouteStaticData(select) {
8175
+ return useRouterState({ select: (s) => {
8176
+ const merged = Object.assign({}, ...s.matches.map((m) => m.staticData));
8177
+ return select ? select(merged) : merged;
8178
+ } });
8179
+ }
8135
8180
  /**
8136
8181
  * The failure that redirected here, for a page configured in `createRouter`'s `statusPages` (404,
8137
8182
  * 403, a dedicated status like 503, or the `default` catch-all). The router attaches this as history
@@ -8179,6 +8224,7 @@ exports.useRouteLoaderData = useRouteLoaderData;
8179
8224
  exports.useRouteLocale = useRouteLocale;
8180
8225
  exports.useRouteParams = useRouteParams;
8181
8226
  exports.useRouteQuery = useRouteQuery;
8227
+ exports.useRouteStaticData = useRouteStaticData;
8182
8228
  exports.useRouter = useRouter;
8183
8229
 
8184
8230
  //# sourceMappingURL=index.cjs.map