clear-react-router 2.4.6 → 2.4.8

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
@@ -25,6 +25,7 @@ It provides first-class support for:
25
25
  ## Features
26
26
 
27
27
  - **Nested Routes** - Organize your UI with nested layouts and routes
28
+ - **Route Layouts** - A `layout` declared on a route wraps it *and* every descendant (stacking outermost-first), keeping shared chrome and state alive across nested navigation
28
29
  - **Data Loading** - Built-in loaders with TTL-based caching (`staleTime`)
29
30
  - **Navigation Blocking** - Prevent accidental navigation with `useBlocker`
30
31
  - **Smooth Animations** - Page transitions with fade effect (customizable duration)
@@ -93,6 +94,7 @@ Normalizes route configuration. Extracts dynamic params, builds nested paths.
93
94
  |----------|------|-------------|
94
95
  | `path` | `string` | Route path, e.g., `/user/:userId` |
95
96
  | `element` | `ReactElement \| () => ReactElement \| LazyComponent` | Component to render |
97
+ | `layout` | Component that accepts `children` | Wraps this route's element and is inherited by every descendant route. A descendant's own `layout` nests *inside* the inherited ones (see [Layouts](#layouts)) |
96
98
  | `beforeLoad` | `({ params, context, redirect, setContext, location }) => Promise<unknown> \| undefined \| void` | Runs before every route navigation. Auth checks and redirects. Can update context via `setContext`. `redirect` is provided by the router |
97
99
  | `loader` | `({ params, context, setContext, searchParams, signal }) => Promise<unknown>` | Fetch data using route params, search params, abort controller signal and context. Can update context via `setContext` |
98
100
  | `afterLoad` | `({ params, context, searchParams }) => Promise<void> \| void` | Runs after a successful navigation once the route has finished loading. Analytics, side effects after data is loaded. Can update context via `setContext` |
@@ -140,6 +142,54 @@ see [`redirect`](#redirect) for details on programmatic redirects
140
142
  > **Note:** `gcTime` is independent from `staleTime` — `staleTime` controls when cached data is considered outdated (and needs a refetch), while `gcTime` controls how long the cache entry stays in memory at all once you leave that route. Data can be fresh and still get garbage-collected, or stale and still linger in memory, depending on which you set. The timer starts only when you navigate away from the route and is cancelled if you come back before it fires — it isn't affected by prefetching. This is mainly useful for routes with heavy or fast-changing data (large tables, dashboards with charts) that you don't want lingering in memory indefinitely, even when `maxCacheSize` hasn't been reached yet.
141
143
  If a route is both `optimistic` and has `gcTime` set, keep in mind the cached snapshot can disappear while you're relying on it for an instant render — combine the two deliberately, not by default.
142
144
 
145
+ ### Layouts
146
+
147
+ A route can declare a `layout`: a component that wraps the route's element and is **inherited by every descendant route**. Layouts **stack**: a descendant's own `layout` nests *inside* the inherited ones, outermost first. Use it for chrome and state that must survive navigation within a subtree — an app shell, a section navbar, tabs, a scroll container, a wizard.
148
+
149
+ ```tsx
150
+ const AppShell = ({ children }: { children: ReactNode }) => (
151
+ <div className="shell">
152
+ <TopNav />
153
+ {children}
154
+ </div>
155
+ );
156
+
157
+ const SectionLayout = ({ children }: { children: ReactNode }) => (
158
+ <div className="section">
159
+ <SectionNav />
160
+ {children}
161
+ </div>
162
+ );
163
+
164
+ const routes = createRouter([
165
+ {
166
+ path: '/',
167
+ element: <Home />,
168
+ layout: AppShell, // outermost: wraps everything under /
169
+ children: [
170
+ {
171
+ path: '/settings',
172
+ element: <SettingsHome />,
173
+ layout: SectionLayout, // nests inside AppShell
174
+ children: [
175
+ { path: '/profile', element: <Profile /> }, // AppShell ⊃ SectionLayout ⊃ Profile
176
+ { path: '/billing', element: <Billing />, layout: BillingLayout }, // AppShell ⊃ SectionLayout ⊃ BillingLayout ⊃ Billing
177
+ ],
178
+ },
179
+ ],
180
+ },
181
+ ]);
182
+ ```
183
+
184
+ Semantics to know:
185
+
186
+ - **Stacked, outermost first.** A descendant's `layout` is added innermost; it never replaces an inherited one. Moving within a subtree keeps every outer layout mounted — entering `/settings` does not remount `AppShell`.
187
+ - **No opt-out.** A descendant cannot remove an inherited layout. A full-screen page inside a section must render `{children}` outside the section chrome itself, or sit outside that section.
188
+ - **Survives child navigation**, including navigations that run a `loader` (the layouts stay mounted, only the route element below the innermost one swaps). Their state and DOM identity are preserved.
189
+ - **Pass a stable reference.** Define a layout at module scope (or keep it stable with `useCallback`). An inline component recreated on each render changes identity and remounts the layout on every navigation.
190
+ - **It's a component, not an element** — it receives `children`, so pass `SectionLayout`, not `<SectionLayout />`. The `lazy()` wrapper is not resolved for layouts; use a plain component.
191
+ - **First frame.** Until the initial route resolves there is no matched route yet, so layouts are not rendered on the very first loading frame (only the `defaultLoaderFallback` is).
192
+
143
193
  ### `Link`
144
194
 
145
195
  Component for client-side navigation with prefetch support, active state detection, and pending state styling. Prefetch includes lazy route component preload.
@@ -1,2 +1,3 @@
1
+ import { type ReactNode } from 'react';
1
2
  import { RouterProps } from '../types';
2
- export declare const Router: ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration, defaultLoaderFallback, defaultErrorElement, defaultRetry, defaultStaleTime, context: initialContext, isAnimated, defaultMinLoaderDuration, revalidateOnFocus, revalidateOnReconnect, maxCacheSize, defaultPrefetch, defaultHoverPrefetchDelay, defaultScrollRestorationBehavior, errorBoundary: ErrorBoundary, }: RouterProps) => import("react/jsx-runtime").JSX.Element | null;
3
+ export declare const Router: ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration, defaultLoaderFallback, defaultErrorElement, defaultRetry, defaultStaleTime, context: initialContext, isAnimated, defaultMinLoaderDuration, revalidateOnFocus, revalidateOnReconnect, maxCacheSize, defaultPrefetch, defaultHoverPrefetchDelay, defaultScrollRestorationBehavior, errorBoundary: ErrorBoundary, }: RouterProps) => string | number | bigint | boolean | import("react").ReactElement<unknown, string | import("react").JSXElementConstructor<any>> | Iterable<ReactNode> | Promise<string | number | bigint | boolean | import("react").ReactPortal | import("react").ReactElement<unknown, string | import("react").JSXElementConstructor<any>> | Iterable<ReactNode> | null | undefined> | null | undefined;
package/dist/index.js CHANGED
@@ -46,7 +46,7 @@ var EMPTY_LOADER_STATE = {};
46
46
  var WINDOW_TOP = "__window_top__";
47
47
  var WINDOW_LEFT = "__window_left__";
48
48
  //#endregion
49
- //#region \0@oxc-project+runtime@0.152.0/helpers/esm/typeof.js
49
+ //#region \0@oxc-project+runtime@0.132.0/helpers/typeof.js
50
50
  function _typeof(o) {
51
51
  "@babel/helpers - typeof";
52
52
  return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
@@ -56,7 +56,7 @@ function _typeof(o) {
56
56
  }, _typeof(o);
57
57
  }
58
58
  //#endregion
59
- //#region \0@oxc-project+runtime@0.152.0/helpers/esm/toPrimitive.js
59
+ //#region \0@oxc-project+runtime@0.132.0/helpers/toPrimitive.js
60
60
  function toPrimitive(t, r) {
61
61
  if ("object" != _typeof(t) || !t) return t;
62
62
  var e = t[Symbol.toPrimitive];
@@ -68,13 +68,13 @@ function toPrimitive(t, r) {
68
68
  return ("string" === r ? String : Number)(t);
69
69
  }
70
70
  //#endregion
71
- //#region \0@oxc-project+runtime@0.152.0/helpers/esm/toPropertyKey.js
71
+ //#region \0@oxc-project+runtime@0.132.0/helpers/toPropertyKey.js
72
72
  function toPropertyKey(t) {
73
73
  var i = toPrimitive(t, "string");
74
74
  return "symbol" == _typeof(i) ? i : i + "";
75
75
  }
76
76
  //#endregion
77
- //#region \0@oxc-project+runtime@0.152.0/helpers/esm/defineProperty.js
77
+ //#region \0@oxc-project+runtime@0.132.0/helpers/defineProperty.js
78
78
  function _defineProperty(e, r, t) {
79
79
  return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
80
80
  value: t,
@@ -464,9 +464,15 @@ var createInvalidate = ({ routeDataState, loaderMap }, revalidateCache) => {
464
464
  };
465
465
  //#endregion
466
466
  //#region runtime/prefetch.ts
467
- var createPrefetch = ({ routeDataState }, revalidateCache) => async (location) => {
468
- const item = findRoute(location.pathname);
469
- if (item) {
467
+ var MOBILE_PREFETCH_CONCURRENCY = 2;
468
+ var DESKTOP_PREFETCH_CONCURRENCY = 4;
469
+ var createPrefetch = ({ routeDataState }, revalidateCache) => {
470
+ const maxConcurrent = isMobile() ? MOBILE_PREFETCH_CONCURRENCY : DESKTOP_PREFETCH_CONCURRENCY;
471
+ const queue = [];
472
+ let active = 0;
473
+ const run = async (location) => {
474
+ const item = findRoute(location.pathname);
475
+ if (!item) return;
470
476
  const currentLocation = routeDataState.getState().location;
471
477
  if (location.pathname === currentLocation.pathname && location.search === currentLocation.search) return;
472
478
  await item.preloadElement?.();
@@ -474,7 +480,25 @@ var createPrefetch = ({ routeDataState }, revalidateCache) => async (location) =
474
480
  routeItem: item,
475
481
  location
476
482
  });
477
- }
483
+ };
484
+ const drain = () => {
485
+ while (active < maxConcurrent && queue.length) {
486
+ active++;
487
+ queue.shift()();
488
+ }
489
+ };
490
+ return (location, signal) => new Promise((resolve) => {
491
+ queue.push(async () => {
492
+ try {
493
+ if (!signal?.aborted) await run(location);
494
+ } catch {} finally {
495
+ active--;
496
+ resolve();
497
+ drain();
498
+ }
499
+ });
500
+ drain();
501
+ });
478
502
  };
479
503
  //#endregion
480
504
  //#region runtime/revalidateCache.ts
@@ -878,19 +902,22 @@ var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration,
878
902
  useSetInitialContext(initialContext);
879
903
  useRestoreRouteScroll(defaultScrollRestorationBehavior);
880
904
  useReload();
881
- if (isLoading && !isError) return renderElement(routeItem?.loaderFallback || defaultLoaderFallback);
882
- if (!routeItem) return null;
883
- if (isError) return renderElement(routeItem.errorElement || defaultErrorElement);
884
- return /* @__PURE__ */ jsx("div", {
905
+ const loadingContent = isLoading && !isError;
906
+ if (!routeItem) return renderElement(loadingContent ? defaultLoaderFallback : void 0);
907
+ const content = loadingContent ? renderElement(routeItem.loaderFallback || defaultLoaderFallback) : isError ? renderElement(routeItem.errorElement || defaultErrorElement) : /* @__PURE__ */ jsx(ErrorBoundary, { children: renderElement(routeItem.element) }, location.pathname);
908
+ return routeItem.layouts.reduceRight((acc, Layout) => {
909
+ return /* @__PURE__ */ jsx(Layout, { children: acc });
910
+ }, /* @__PURE__ */ jsx("div", {
885
911
  style: { viewTransitionName: "page" },
886
- children: /* @__PURE__ */ jsx(ErrorBoundary, { children: renderElement(routeItem.element) }, location.pathname)
887
- });
912
+ children: content
913
+ }));
888
914
  };
889
915
  //#endregion
890
916
  //#region hooks/useNavigate.ts
891
917
  var useNavigate = router.hooks.useNavigate;
892
918
  //#endregion
893
919
  //#region components/Link.tsx
920
+ var VIEWPORT_DWELL_MS = 250;
894
921
  var defaultAs = (props) => /* @__PURE__ */ jsx("a", { ...props });
895
922
  var comparator = (to, pathname, exact) => to === "/" ? pathname === "/" : exact ? pathname === to : pathname === to || pathname?.startsWith(`${to}/`);
896
923
  var Link = ({ children, to, path, params, search = "", state, as = defaultAs, prefetch: linkPrefetch, hoverPrefetchDelay, className, style, beforeNavigate, exact = false, activeClassName = "active-link", pendingClassName = "pending-link", ...rest }) => {
@@ -932,22 +959,51 @@ var Link = ({ children, to, path, params, search = "", state, as = defaultAs, pr
932
959
  }, [getPrefetchStrategy, getPrefetchDelay]);
933
960
  useEffect(() => {
934
961
  if (getPrefetchStrategy() !== "render") return;
935
- (async () => {
936
- await router.runtime.prefetch(location);
937
- })();
938
- }, [getPrefetchStrategy, location]);
962
+ const controller = new AbortController();
963
+ router.runtime.prefetch({
964
+ pathname,
965
+ search: searchString
966
+ }, controller.signal);
967
+ return () => controller.abort();
968
+ }, [
969
+ getPrefetchStrategy,
970
+ pathname,
971
+ searchString
972
+ ]);
939
973
  useEffect(() => {
940
974
  if (getPrefetchStrategy() !== "viewport") return;
941
975
  const element = elementRef.current;
942
976
  if (!element) return;
943
- const observer = new IntersectionObserver(async ([entry]) => {
944
- if (!entry.isIntersecting) return;
945
- await router.runtime.prefetch(location);
946
- observer.disconnect();
977
+ let dwellTimer = 0;
978
+ let controller = null;
979
+ const observer = new IntersectionObserver((entries) => {
980
+ const isVisible = entries[entries.length - 1].isIntersecting;
981
+ window.clearTimeout(dwellTimer);
982
+ if (!isVisible) {
983
+ controller?.abort();
984
+ return;
985
+ }
986
+ dwellTimer = window.setTimeout(async () => {
987
+ const attempt = new AbortController();
988
+ controller = attempt;
989
+ await router.runtime.prefetch({
990
+ pathname,
991
+ search: searchString
992
+ }, attempt.signal);
993
+ if (!attempt.signal.aborted) observer.disconnect();
994
+ }, VIEWPORT_DWELL_MS);
947
995
  });
948
996
  observer.observe(element);
949
- return () => observer.disconnect();
950
- }, [getPrefetchStrategy, location]);
997
+ return () => {
998
+ window.clearTimeout(dwellTimer);
999
+ controller?.abort();
1000
+ observer.disconnect();
1001
+ };
1002
+ }, [
1003
+ getPrefetchStrategy,
1004
+ pathname,
1005
+ searchString
1006
+ ]);
951
1007
  useEffect(() => () => {
952
1008
  if (timeout.current) clearTimeout(timeout.current);
953
1009
  }, []);
@@ -1099,10 +1155,8 @@ var useSearchParams = () => {
1099
1155
  currentParams.delete(param);
1100
1156
  (Array.isArray(value) ? value : [value]).forEach((v) => currentParams.append(param, v));
1101
1157
  navigateWithSearchParams(currentParams);
1102
- } else if (typeof param === "function") {
1103
- const newParams = param(currentParams);
1104
- navigateWithSearchParams(newParams);
1105
- } else throw new Error("useSearchParams first argument must be either function or string");
1158
+ } else if (typeof param === "function") navigateWithSearchParams(param(currentParams));
1159
+ else throw new Error("useSearchParams first argument must be either function or string");
1106
1160
  }, [navigateWithSearchParams, searchRef])
1107
1161
  };
1108
1162
  };
@@ -1155,16 +1209,18 @@ var LAZY_MARKER = Symbol("clear-router-lazy");
1155
1209
  //#region creators/createRouter.ts
1156
1210
  var isLazy = (component) => typeof component === "object" && component !== null && LAZY_MARKER in component;
1157
1211
  var resolve = (component, fallback) => isLazy(component) ? createLazyComponent(component.importFn, fallback).Component : component;
1158
- var parseClientRouteItem = (el, parentPattern = "") => {
1212
+ var parseClientRouteItem = (el, parentPattern = "", inheritedLayouts = []) => {
1159
1213
  const pattern = `${parentPattern}/${el.path}`.replace(/\/+/g, "/");
1160
1214
  const preloadElement = isLazy(el.element) ? createLazyComponent(el.element.importFn, el.fallback).preloadElement : void 0;
1215
+ const layouts = el.layout ? [...inheritedLayouts, el.layout] : inheritedLayouts;
1161
1216
  return [{
1162
1217
  ...el,
1163
1218
  pattern,
1164
1219
  element: resolve(el.element, el.fallback),
1165
1220
  errorElement: resolve(el.errorElement, el.fallback),
1166
- preloadElement
1167
- }, ...el.children?.flatMap((child) => parseClientRouteItem(child, pattern)) ?? []];
1221
+ preloadElement,
1222
+ layouts
1223
+ }, ...el.children?.flatMap((child) => parseClientRouteItem(child, pattern, layouts)) ?? []];
1168
1224
  };
1169
1225
  var createRouter = (clientList) => clientList.flatMap((el) => parseClientRouteItem(el));
1170
1226
  //#endregion
@@ -1,2 +1,2 @@
1
1
  import { RevalidateCache, RouterState, Location } from '../types';
2
- export declare const createPrefetch: ({ routeDataState }: RouterState, revalidateCache: RevalidateCache) => (location: Location) => Promise<void>;
2
+ export declare const createPrefetch: ({ routeDataState }: RouterState, revalidateCache: RevalidateCache) => (location: Location, signal?: AbortSignal) => Promise<void>;
package/dist/types.d.ts CHANGED
@@ -29,6 +29,7 @@ export type ClientRouteItem = {
29
29
  loaderFallback?: RenderElement;
30
30
  errorElement?: RenderElement | LazyComponent;
31
31
  fallback?: RenderElement;
32
+ layout?: RenderElement;
32
33
  children?: ClientRouteItem[];
33
34
  staleTime?: number;
34
35
  gcTime?: number;
@@ -49,6 +50,7 @@ export type ClientRouteItem = {
49
50
  export type RouteItem = ClientRouteItem & {
50
51
  element: RenderElement;
51
52
  pattern: string;
53
+ layouts: RenderElement[];
52
54
  cacheTimestamp?: number;
53
55
  preloadElement?(): Promise<{
54
56
  default: unknown;
@@ -131,7 +133,7 @@ export type RouterType = {
131
133
  runtime: {
132
134
  navigate(arg: Location): Promise<void>;
133
135
  invalidate(pathList?: string | string[], options?: InvalidateOptions): Promise<InvalidateResult[]>;
134
- prefetch(location: Location): Promise<void>;
136
+ prefetch(location: Location, signal?: AbortSignal): Promise<void>;
135
137
  };
136
138
  hooks: {
137
139
  useBlockerState(): ReturnType<typeof useGlobalState<BlockerState>>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clear-react-router",
3
- "version": "2.4.6",
3
+ "version": "2.4.8",
4
4
  "description": "A lightweight routing library for React applications",
5
5
  "author": "Andrew Bubnov",
6
6
  "scripts": {