clear-react-router 2.4.5 → 2.4.7
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 +56 -0
- package/dist/components/Router.d.ts +2 -1
- package/dist/index.js +19 -17
- package/dist/types.d.ts +2 -0
- package/package.json +1 -1
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.
|
|
@@ -294,6 +344,8 @@ screen readers) intact:
|
|
|
294
344
|
Reach for `as` only when the element itself must change (a `<button>`, a UI-kit component)
|
|
295
345
|
— for looks alone, attributes + CSS are simpler and accessible by default.
|
|
296
346
|
|
|
347
|
+
### Prefetch examples
|
|
348
|
+
|
|
297
349
|
```tsx
|
|
298
350
|
// Global prefetch: hover with 100ms delay
|
|
299
351
|
<Router routes={routes} defaultPrefetch="hover" defaultHoverPrefetchDelay={100} />
|
|
@@ -307,7 +359,11 @@ Reach for `as` only when the element itself must change (a `<button>`, a UI-kit
|
|
|
307
359
|
<Link to="/admin" prefetch="none">
|
|
308
360
|
Admin Panel
|
|
309
361
|
</Link>
|
|
362
|
+
```
|
|
310
363
|
|
|
364
|
+
### Appearance and behavior examples
|
|
365
|
+
|
|
366
|
+
```tsx
|
|
311
367
|
// With custom active/pending classes
|
|
312
368
|
<Link to="/settings" activeClassName="active-nav-link" pendingClassName="loading-nav-link">
|
|
313
369
|
Settings
|
|
@@ -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
|
|
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.
|
|
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.
|
|
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.
|
|
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.
|
|
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,
|
|
@@ -878,13 +878,15 @@ var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration,
|
|
|
878
878
|
useSetInitialContext(initialContext);
|
|
879
879
|
useRestoreRouteScroll(defaultScrollRestorationBehavior);
|
|
880
880
|
useReload();
|
|
881
|
-
|
|
882
|
-
if (!routeItem) return
|
|
883
|
-
|
|
884
|
-
return
|
|
881
|
+
const loadingContent = isLoading && !isError;
|
|
882
|
+
if (!routeItem) return renderElement(loadingContent ? defaultLoaderFallback : void 0);
|
|
883
|
+
const content = loadingContent ? renderElement(routeItem.loaderFallback || defaultLoaderFallback) : isError ? renderElement(routeItem.errorElement || defaultErrorElement) : /* @__PURE__ */ jsx(ErrorBoundary, { children: renderElement(routeItem.element) }, location.pathname);
|
|
884
|
+
return routeItem.layouts.reduceRight((acc, Layout) => {
|
|
885
|
+
return /* @__PURE__ */ jsx(Layout, { children: acc });
|
|
886
|
+
}, /* @__PURE__ */ jsx("div", {
|
|
885
887
|
style: { viewTransitionName: "page" },
|
|
886
|
-
children:
|
|
887
|
-
});
|
|
888
|
+
children: content
|
|
889
|
+
}));
|
|
888
890
|
};
|
|
889
891
|
//#endregion
|
|
890
892
|
//#region hooks/useNavigate.ts
|
|
@@ -1099,10 +1101,8 @@ var useSearchParams = () => {
|
|
|
1099
1101
|
currentParams.delete(param);
|
|
1100
1102
|
(Array.isArray(value) ? value : [value]).forEach((v) => currentParams.append(param, v));
|
|
1101
1103
|
navigateWithSearchParams(currentParams);
|
|
1102
|
-
} else if (typeof param === "function")
|
|
1103
|
-
|
|
1104
|
-
navigateWithSearchParams(newParams);
|
|
1105
|
-
} else throw new Error("useSearchParams first argument must be either function or string");
|
|
1104
|
+
} else if (typeof param === "function") navigateWithSearchParams(param(currentParams));
|
|
1105
|
+
else throw new Error("useSearchParams first argument must be either function or string");
|
|
1106
1106
|
}, [navigateWithSearchParams, searchRef])
|
|
1107
1107
|
};
|
|
1108
1108
|
};
|
|
@@ -1155,16 +1155,18 @@ var LAZY_MARKER = Symbol("clear-router-lazy");
|
|
|
1155
1155
|
//#region creators/createRouter.ts
|
|
1156
1156
|
var isLazy = (component) => typeof component === "object" && component !== null && LAZY_MARKER in component;
|
|
1157
1157
|
var resolve = (component, fallback) => isLazy(component) ? createLazyComponent(component.importFn, fallback).Component : component;
|
|
1158
|
-
var parseClientRouteItem = (el, parentPattern = "") => {
|
|
1158
|
+
var parseClientRouteItem = (el, parentPattern = "", inheritedLayouts = []) => {
|
|
1159
1159
|
const pattern = `${parentPattern}/${el.path}`.replace(/\/+/g, "/");
|
|
1160
1160
|
const preloadElement = isLazy(el.element) ? createLazyComponent(el.element.importFn, el.fallback).preloadElement : void 0;
|
|
1161
|
+
const layouts = el.layout ? [...inheritedLayouts, el.layout] : inheritedLayouts;
|
|
1161
1162
|
return [{
|
|
1162
1163
|
...el,
|
|
1163
1164
|
pattern,
|
|
1164
1165
|
element: resolve(el.element, el.fallback),
|
|
1165
1166
|
errorElement: resolve(el.errorElement, el.fallback),
|
|
1166
|
-
preloadElement
|
|
1167
|
-
|
|
1167
|
+
preloadElement,
|
|
1168
|
+
layouts
|
|
1169
|
+
}, ...el.children?.flatMap((child) => parseClientRouteItem(child, pattern, layouts)) ?? []];
|
|
1168
1170
|
};
|
|
1169
1171
|
var createRouter = (clientList) => clientList.flatMap((el) => parseClientRouteItem(el));
|
|
1170
1172
|
//#endregion
|
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;
|