clear-react-router 2.4.9 → 2.5.1
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 +24 -18
- package/dist/components/Router.d.ts +1 -1
- package/dist/config/routerConfig.d.ts +1 -1
- package/dist/hooks/useCacheSnapshot.d.ts +0 -1
- package/dist/index.js +146 -71
- package/dist/runtime/invalidate.d.ts +1 -1
- package/dist/types.d.ts +2 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -33,8 +33,8 @@ It provides first-class support for:
|
|
|
33
33
|
- **Programmatic Redirects** - Redirect from beforeLoad hook
|
|
34
34
|
- **Cache invalidation** - Manual route invalidation
|
|
35
35
|
- **Bounded Cache** - Automatically evicts least recently used entries once `maxCacheSize` is reached, keeping memory usage predictable in long sessions
|
|
36
|
-
- **Cache inspection** - Opt into a live, read-only snapshot of cached loader entries with `
|
|
37
|
-
- **Prefetching** - Preload data on hover for
|
|
36
|
+
- **Cache inspection** - Opt into a live, read-only snapshot of cached loader entries with `enableCacheSnapshot` and `useCacheSnapshot()`
|
|
37
|
+
- **Prefetching** - Preload data on hover; prefetched entries stay fresh for 30 seconds before the first navigation
|
|
38
38
|
- **Lazy Loading** - Code-split your routes with dynamic imports for optimal performance
|
|
39
39
|
- **Scroll Restoration** — Automatically saves and restores scroll position when navigating back to a page (preserves user's scroll position)
|
|
40
40
|
- **Optimistic navigation** — Instantly renders stale cached data while fresh data is loaded in the background.
|
|
@@ -66,7 +66,6 @@ Netlify (`public/_redirects`):
|
|
|
66
66
|
|------|------|---------|-------------|
|
|
67
67
|
| `routes` | `RouteItem[]` | required | Array of route configurations |
|
|
68
68
|
| `maxCacheSize` | `number \| undefined` | 60 for mobile, 150 for desktop | Maximum number of cached loader entries. Once the limit is reached, the least recently used entries are evicted |
|
|
69
|
-
| `logged` | `boolean` | `false` | Enables cache snapshot tracking for [`useCacheSnapshot()`](#usecachesnapshot). Off by default: no snapshot is built and the hook returns an empty list |
|
|
70
69
|
| `isAnimated` | `boolean \| undefined` | `false` | Enable smooth page fade transitions |
|
|
71
70
|
| `animationDuration` | `number \| undefined` | `optional` | Animation duration in milliseconds (browser default is used if not set) |
|
|
72
71
|
| `context` | `object` | `{}` | Initial context (user, theme, etc.) |
|
|
@@ -75,7 +74,7 @@ Netlify (`public/_redirects`):
|
|
|
75
74
|
| `defaultLoaderFallback` | `ReactElement \| () => ReactElement` | `optional` | Default loading fallback for every route loader |
|
|
76
75
|
| `defaultErrorElement` | `ReactElement \| () => ReactElement` | `optional` | Default error fallback for every route |
|
|
77
76
|
| `defaultRetry` | `number \| { count: number; delay: number }` | `optional` | Default cache revalidation retry policy for all routes |
|
|
78
|
-
| `defaultStaleTime` | `number` | `
|
|
77
|
+
| `defaultStaleTime` | `number` | `0` | Default time in milliseconds before cached loader data is considered stale. When unset (or `0`), data is stale immediately and navigation revalidates it |
|
|
79
78
|
| `defaultBeforeLoad` | `({ params, context, redirect, setContext, location }) => Promise<unknown> \| undefined \| void` | `undefined` | Runs before every navigation. Useful for authentication, analytics, or updating shared context. |
|
|
80
79
|
| `defaultAfterLoad` | `({ params, context, searchParams }) => Promise<void>` | `undefined` | Runs after every successful navigation. Useful for analytics, page tracking, or other global side effects. |
|
|
81
80
|
| `defaultPrefetch` | `'hover' \| 'render' \| 'viewport' \| 'none'` | `'hover'` for desktop, `'viewport'` for mobile | Default prefetch strategy for all `<Link>` components |
|
|
@@ -83,6 +82,7 @@ Netlify (`public/_redirects`):
|
|
|
83
82
|
| `defaultScrollRestorationBehavior` | `'auto' \| 'smooth' \| 'instant'` | `auto` | Default scroll restoration behavior |
|
|
84
83
|
| `revalidateOnFocus` | `boolean \| undefined` | `undefined` | Revalidate the current route's `loader` data when the browser tab regains focus |
|
|
85
84
|
| `revalidateOnReconnect` | `boolean \| undefined` | `undefined` | Revalidate the current route's `loader` data when the browser regains an internet connection |
|
|
85
|
+
| `enableCacheSnapshot` | `boolean` | `false` | Enables cache snapshot tracking for [`useCacheSnapshot()`](#usecachesnapshot). Off by default: no snapshot is built and the hook returns an empty list |
|
|
86
86
|
|
|
87
87
|
> **Note:** Global lifecycle hooks wrap every route navigation. The global `defaultBeforeLoad` runs **before** the route-specific beforeLoad, while the global `defaultAfterLoad` runs **after** the route-specific afterLoad.
|
|
88
88
|
|
|
@@ -106,7 +106,7 @@ Normalizes route configuration. Extracts dynamic params, builds nested paths.
|
|
|
106
106
|
| `retry` | `number \| { count: number; delay: number }` | Overrides the global cache revalidation retry policy for this route |
|
|
107
107
|
| `optimistic` | `boolean \| undefined` | Instant navigation using stale data while fresh data is loaded in the background |
|
|
108
108
|
| `errorElement` | `ReactElement \| () => ReactElement \| LazyComponent` | Error fallback for the route. Overrides the global `Router.defaultErrorElement` |
|
|
109
|
-
| `staleTime` | `number \| undefined` | Time in milliseconds before cached loader data is considered stale. Overrides Router.defaultStaleTime. If neither value is provided,
|
|
109
|
+
| `staleTime` | `number \| undefined` | Time in milliseconds before cached loader data is considered stale. Overrides Router.defaultStaleTime. If neither value is provided, data is stale immediately and navigation revalidates it. Use `Infinity` to never consider it stale |
|
|
110
110
|
| `gcTime` | `number \| undefined` | How long, in milliseconds, an unused cache entry is kept in memory after you navigate away, before it's garbage-collected |
|
|
111
111
|
| `actions` | `({ params, context, searchParams, setContext, location }) => Record<string, (data: Record<string, unknown>) => unknown \| Promise<unknown>>` | Defines route actions for data mutations. |
|
|
112
112
|
| `pollingInterval` | `number \| undefined` | Polling interval (in milliseconds) for automatically revalidating data while the route is active. Each tick refetches unconditionally, ignoring `staleTime` |
|
|
@@ -250,6 +250,8 @@ When using a custom element via `as`, these attributes arrive in `props` togethe
|
|
|
250
250
|
| `'viewport'` | Prefetches when the link enters the viewport (using Intersection Observer) |
|
|
251
251
|
| `'none'` | No prefetching |
|
|
252
252
|
|
|
253
|
+
> A prefetched entry is considered fresh for 30 seconds. The first navigation within that window reuses it without running the loader; after that, the route's normal `staleTime` applies (by default `0`, so the next revisit revalidates). A longer route `staleTime` is never shortened by prefetching.
|
|
254
|
+
|
|
253
255
|
### Custom elements via `as`
|
|
254
256
|
|
|
255
257
|
When using `as` to render a custom component instead of the default `<a>`, your component **must spread all received props onto the underlying host element** — including `ref`. If any prop is dropped, the corresponding feature silently stops working (no error is thrown):
|
|
@@ -540,7 +542,7 @@ const routes = createRouter([
|
|
|
540
542
|
|
|
541
543
|
Defines route-specific actions for handling data mutations such as creating, updating, or deleting resources.
|
|
542
544
|
|
|
543
|
-
Actions are available through the `useSubmitAction` and `useAction` hooks. After a successful action, the
|
|
545
|
+
Actions are available through the `useSubmitAction` and `useAction` hooks. After a successful action, the route where the action was triggered is automatically invalidated, causing `loader` to run again in the background.
|
|
544
546
|
|
|
545
547
|
```tsx
|
|
546
548
|
actions?: ({ params, context, searchParams, setContext, location }) => ({
|
|
@@ -644,7 +646,7 @@ const handleClick = async () => await save({ data: 'Hello world!' });
|
|
|
644
646
|
<button onClick={handleClick}>Save</button>
|
|
645
647
|
```
|
|
646
648
|
|
|
647
|
-
`useAction` automatically invalidates the
|
|
649
|
+
`useAction` automatically invalidates the route where the action was triggered after a successful action, causing `loader` to run again in the background. This remains the same route even if the user navigates away while the action is in flight.
|
|
648
650
|
|
|
649
651
|
This hook is useful when the mutation is triggered programmatically, such as from dialogs, context menus, drag-and-drop interactions, keyboard shortcuts, or custom UI components.
|
|
650
652
|
|
|
@@ -825,7 +827,7 @@ beforeLoad: async ({ location, redirect }) => {
|
|
|
825
827
|
|
|
826
828
|
### `useLoaderState<T>()`
|
|
827
829
|
|
|
828
|
-
Returns the cached data loaded by the current route's `loader`, along with any errors from `loader` or `beforeLoad`. Data is
|
|
830
|
+
Returns the cached data loaded by the current route's `loader`, along with any errors from `loader` or `beforeLoad`. Data is cached, but whether a revisit reuses it depends on `staleTime`: by default cached data is stale immediately and the loader runs again.
|
|
829
831
|
|
|
830
832
|
**Returns:**
|
|
831
833
|
|
|
@@ -842,8 +844,7 @@ const UserProfile = () => {
|
|
|
842
844
|
|
|
843
845
|
### Caching behavior:
|
|
844
846
|
|
|
845
|
-
- The loader result is cached
|
|
846
|
-
- Use `staleTime` in route config to control how long cache is considered fresh:
|
|
847
|
+
- The loader result is cached. Without `staleTime` (and without `defaultStaleTime`), the entry is stale immediately, so navigating back to the same route runs the loader again. Set `staleTime` to reuse data within a time window:
|
|
847
848
|
|
|
848
849
|
```tsx
|
|
849
850
|
{
|
|
@@ -853,7 +854,9 @@ const UserProfile = () => {
|
|
|
853
854
|
}
|
|
854
855
|
```
|
|
855
856
|
|
|
856
|
-
-
|
|
857
|
+
- Use `staleTime: Infinity` when data should stay fresh until it is explicitly invalidated, garbage-collected or evicted.
|
|
858
|
+
|
|
859
|
+
- The cache is bounded by `maxCacheSize` — once the limit is reached, the least recently used entry is evicted to make room for a new one, regardless of whether it's still fresh. The currently active route's entry is never evicted. This caps memory usage for apps with many high-cardinality dynamic routes (e.g. `/product/:id` across a large catalog). It defaults to a device-aware value (lower on mobile) and can be overridden on the `Router`:
|
|
857
860
|
|
|
858
861
|
```tsx
|
|
859
862
|
<Router routes={routes} maxCacheSize={200} />
|
|
@@ -863,7 +866,7 @@ const UserProfile = () => {
|
|
|
863
866
|
### `useCacheSnapshot()`
|
|
864
867
|
|
|
865
868
|
Returns a read-only snapshot of the loader cache — intended for devtools panels, debugging, and cache
|
|
866
|
-
monitoring. Requires `<Router
|
|
869
|
+
monitoring. Requires `<Router enableCacheSnapshot>`; while the flag is off the snapshot is empty and nothing is built.
|
|
867
870
|
|
|
868
871
|
```tsx
|
|
869
872
|
import { useCacheSnapshot } from 'clear-react-router';
|
|
@@ -875,14 +878,15 @@ const CachePanel = () => {
|
|
|
875
878
|
<ul>
|
|
876
879
|
{entries.map(entry => (
|
|
877
880
|
<li key={entry.path}>
|
|
878
|
-
{entry.path} — {entry.reason ?? 'unknown'} —
|
|
881
|
+
{entry.path} — {entry.reason ?? 'unknown'} —{' '}
|
|
882
|
+
{entry.isCached ? (entry.isLoading ? 'revalidating' : 'cached') : 'loading'}
|
|
879
883
|
</li>
|
|
880
884
|
))}
|
|
881
885
|
</ul>
|
|
882
886
|
);
|
|
883
887
|
};
|
|
884
888
|
|
|
885
|
-
<Router routes={routes}
|
|
889
|
+
<Router routes={routes} enableCacheSnapshot />
|
|
886
890
|
```
|
|
887
891
|
|
|
888
892
|
```ts
|
|
@@ -892,11 +896,12 @@ type CacheSnapshotEntry = {
|
|
|
892
896
|
path: string; // pathname + search
|
|
893
897
|
data: unknown; // loader result; undefined while the first load is in flight
|
|
894
898
|
timestamp: number; // when the entry was written (ms since epoch)
|
|
895
|
-
staleTime: number | undefined; //
|
|
899
|
+
staleTime: number | undefined; // effective staleTime: route value, default, or 0 when neither is set
|
|
896
900
|
reason?: CacheReason; // what wrote the entry last
|
|
897
901
|
gcExpiresAt: number | undefined; // GC deadline, if a GC timer is pending
|
|
898
902
|
gcDuration: number | undefined; // the route's gcTime, for progress display
|
|
899
|
-
|
|
903
|
+
isCached: boolean; // a loader result exists in memory (fresh or stale)
|
|
904
|
+
isLoading: boolean; // a loader for this path is currently running
|
|
900
905
|
};
|
|
901
906
|
|
|
902
907
|
type CacheSnapshot = CacheSnapshotEntry[];
|
|
@@ -905,9 +910,10 @@ type CacheSnapshot = CacheSnapshotEntry[];
|
|
|
905
910
|
Notes:
|
|
906
911
|
|
|
907
912
|
- The snapshot is a projection, not a second cache — changing it does nothing.
|
|
908
|
-
- Entries appear for in-flight first loads too (`data: undefined`, `isLoading: true`), so a devtool never misses a request.
|
|
913
|
+
- Entries appear for in-flight first loads too (`data: undefined`, `isCached: false`, `isLoading: true`), so a devtool never misses a request.
|
|
914
|
+
- A cached entry being revalidated has `isCached: true` and `isLoading: true`; read `data` to show the previous result while it refreshes.
|
|
909
915
|
- Mounting the hook refreshes the snapshot, so a panel opened after navigation still sees existing entries.
|
|
910
|
-
- `
|
|
916
|
+
- `enableCacheSnapshot` is process-wide (the router is a singleton): if several `<Router>`s render with different values, the last rendered one wins. Enable it only when a consumer is actually mounted.
|
|
911
917
|
|
|
912
918
|
### `useInvalidate()`
|
|
913
919
|
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { type ReactNode } from 'react';
|
|
2
2
|
import { RouterProps } from '../types';
|
|
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,
|
|
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, enableCacheSnapshot, }: 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;
|
|
@@ -13,7 +13,7 @@ declare class RouterConfig {
|
|
|
13
13
|
defaultStaleTime?: RouterProps['defaultStaleTime'];
|
|
14
14
|
defaultMinLoaderDuration?: RouterProps['defaultMinLoaderDuration'];
|
|
15
15
|
defaultScrollRestorationBehavior: RouterProps['defaultScrollRestorationBehavior'];
|
|
16
|
-
|
|
16
|
+
enableCacheSnapshot: boolean;
|
|
17
17
|
configure(config: Partial<RouterConfig>): void;
|
|
18
18
|
}
|
|
19
19
|
export declare const routerConfig: RouterConfig;
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Suspense, lazy as lazy$1, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
|
|
2
2
|
import { jsx } from "react/jsx-runtime";
|
|
3
|
-
|
|
3
|
+
//#region create.ts
|
|
4
4
|
var create = (initialState) => {
|
|
5
5
|
let state = initialState;
|
|
6
6
|
const subscribers = /* @__PURE__ */ new Set();
|
|
@@ -26,7 +26,8 @@ var create = (initialState) => {
|
|
|
26
26
|
var useGlobalState = ({ subscribe, getState, setState }, synchronizer) => {
|
|
27
27
|
return [synchronizer(subscribe, getState), setState];
|
|
28
28
|
};
|
|
29
|
-
|
|
29
|
+
//#endregion
|
|
30
|
+
//#region utils/commitState.ts
|
|
30
31
|
var createCommitState = ({ routeDataState, blockerState }) => ({ routeItem, loaderStateValue, location }) => {
|
|
31
32
|
const isError = loaderStateValue.loaderError || loaderStateValue.beforeLoadError;
|
|
32
33
|
routeDataState.setState({
|
|
@@ -39,11 +40,13 @@ var createCommitState = ({ routeDataState, blockerState }) => ({ routeItem, load
|
|
|
39
40
|
if ((location.search ? `${location.pathname}${location.search}` : location.pathname) === window.location.pathname + window.location.search) return;
|
|
40
41
|
history.pushState(location.state ?? null, "", `${location.pathname}${location.search}`);
|
|
41
42
|
};
|
|
42
|
-
|
|
43
|
+
//#endregion
|
|
44
|
+
//#region constants.ts
|
|
43
45
|
var EMPTY_LOADER_STATE = {};
|
|
44
46
|
var WINDOW_TOP = "__window_top__";
|
|
45
47
|
var WINDOW_LEFT = "__window_left__";
|
|
46
|
-
|
|
48
|
+
//#endregion
|
|
49
|
+
//#region \0@oxc-project+runtime@0.132.0/helpers/typeof.js
|
|
47
50
|
function _typeof(o) {
|
|
48
51
|
"@babel/helpers - typeof";
|
|
49
52
|
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
|
|
@@ -52,7 +55,8 @@ function _typeof(o) {
|
|
|
52
55
|
return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
|
|
53
56
|
}, _typeof(o);
|
|
54
57
|
}
|
|
55
|
-
|
|
58
|
+
//#endregion
|
|
59
|
+
//#region \0@oxc-project+runtime@0.132.0/helpers/toPrimitive.js
|
|
56
60
|
function toPrimitive(t, r) {
|
|
57
61
|
if ("object" != _typeof(t) || !t) return t;
|
|
58
62
|
var e = t[Symbol.toPrimitive];
|
|
@@ -63,12 +67,14 @@ function toPrimitive(t, r) {
|
|
|
63
67
|
}
|
|
64
68
|
return ("string" === r ? String : Number)(t);
|
|
65
69
|
}
|
|
66
|
-
|
|
70
|
+
//#endregion
|
|
71
|
+
//#region \0@oxc-project+runtime@0.132.0/helpers/toPropertyKey.js
|
|
67
72
|
function toPropertyKey(t) {
|
|
68
73
|
var i = toPrimitive(t, "string");
|
|
69
74
|
return "symbol" == _typeof(i) ? i : i + "";
|
|
70
75
|
}
|
|
71
|
-
|
|
76
|
+
//#endregion
|
|
77
|
+
//#region \0@oxc-project+runtime@0.132.0/helpers/defineProperty.js
|
|
72
78
|
function _defineProperty(e, r, t) {
|
|
73
79
|
return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
|
|
74
80
|
value: t,
|
|
@@ -77,7 +83,8 @@ function _defineProperty(e, r, t) {
|
|
|
77
83
|
writable: !0
|
|
78
84
|
}) : e[r] = t, e;
|
|
79
85
|
}
|
|
80
|
-
|
|
86
|
+
//#endregion
|
|
87
|
+
//#region config/routerConfig.ts
|
|
81
88
|
var RouterConfig = class {
|
|
82
89
|
constructor() {
|
|
83
90
|
_defineProperty(this, "routes", []);
|
|
@@ -93,14 +100,15 @@ var RouterConfig = class {
|
|
|
93
100
|
_defineProperty(this, "defaultStaleTime", void 0);
|
|
94
101
|
_defineProperty(this, "defaultMinLoaderDuration", void 0);
|
|
95
102
|
_defineProperty(this, "defaultScrollRestorationBehavior", void 0);
|
|
96
|
-
_defineProperty(this, "
|
|
103
|
+
_defineProperty(this, "enableCacheSnapshot", false);
|
|
97
104
|
}
|
|
98
105
|
configure(config) {
|
|
99
106
|
Object.assign(this, config);
|
|
100
107
|
}
|
|
101
108
|
};
|
|
102
109
|
var routerConfig = new RouterConfig();
|
|
103
|
-
|
|
110
|
+
//#endregion
|
|
111
|
+
//#region utils/commitNavigation.ts
|
|
104
112
|
var commitNavigation = (callback, isCommited) => {
|
|
105
113
|
if (!routerConfig.isAnimated || isCommited) return callback();
|
|
106
114
|
try {
|
|
@@ -111,15 +119,17 @@ var commitNavigation = (callback, isCommited) => {
|
|
|
111
119
|
callback();
|
|
112
120
|
}
|
|
113
121
|
};
|
|
114
|
-
|
|
122
|
+
//#endregion
|
|
123
|
+
//#region utils/isCacheItemFresh.ts
|
|
115
124
|
var createIsCacheItemFresh = (loaderMap) => (path) => {
|
|
116
125
|
const item = loaderMap.get(path);
|
|
117
126
|
if (item === void 0) return false;
|
|
118
|
-
const resolvedStaleTime = item.staleTime ?? routerConfig.defaultStaleTime;
|
|
119
|
-
if (resolvedStaleTime
|
|
127
|
+
const resolvedStaleTime = item.staleTime ?? routerConfig.defaultStaleTime ?? 0;
|
|
128
|
+
if (resolvedStaleTime <= 0) return false;
|
|
120
129
|
return Date.now() - item.timestamp <= resolvedStaleTime;
|
|
121
130
|
};
|
|
122
|
-
|
|
131
|
+
//#endregion
|
|
132
|
+
//#region utils/utils.ts
|
|
123
133
|
var getParams = (location, routeItem) => {
|
|
124
134
|
if (!routeItem) return {};
|
|
125
135
|
const pathnameSegments = location.pathname.split("/");
|
|
@@ -196,7 +206,8 @@ var findRoute = (pathname, includeAll) => {
|
|
|
196
206
|
if (includeAll) return routerConfig.routes.find((el) => el.path === "*" || comparePaths(el, pathname));
|
|
197
207
|
return routerConfig.routes.find((el) => comparePaths(el, pathname));
|
|
198
208
|
};
|
|
199
|
-
|
|
209
|
+
//#endregion
|
|
210
|
+
//#region runtime/navigate.ts
|
|
200
211
|
var createNavigate = (routerState, revalidateCache, syncCacheSnapshot) => {
|
|
201
212
|
let navigationSeq = 0;
|
|
202
213
|
let interval = 0;
|
|
@@ -359,12 +370,13 @@ var createNavigate = (routerState, revalidateCache, syncCacheSnapshot) => {
|
|
|
359
370
|
if (defaultAfterLoad) await defaultAfterLoad(args);
|
|
360
371
|
};
|
|
361
372
|
const checkBlocked = (nextLocation) => {
|
|
362
|
-
|
|
373
|
+
const currentState = blockerState.getState();
|
|
374
|
+
if (currentState === "charged") {
|
|
363
375
|
blockerState.setState("blocked");
|
|
364
376
|
blockedTargetState.setState(nextLocation);
|
|
365
377
|
return true;
|
|
366
378
|
}
|
|
367
|
-
return
|
|
379
|
+
return currentState === "blocked";
|
|
368
380
|
};
|
|
369
381
|
const clearCurrentGcTimeout = (routeItem, location) => {
|
|
370
382
|
const path = `${location.pathname}${location.search}`;
|
|
@@ -413,14 +425,16 @@ var createNavigate = (routerState, revalidateCache, syncCacheSnapshot) => {
|
|
|
413
425
|
};
|
|
414
426
|
return navigate;
|
|
415
427
|
};
|
|
416
|
-
|
|
428
|
+
//#endregion
|
|
429
|
+
//#region runtime/invalidate.ts
|
|
417
430
|
var separatePathname = (text) => text.split("?")[0];
|
|
418
|
-
var createInvalidate = ({ routeDataState, loaderMap }, revalidateCache, syncCacheSnapshot) => {
|
|
431
|
+
var createInvalidate = ({ routeDataState, loaderMap, loadingPromises }, revalidateCache, syncCacheSnapshot) => {
|
|
419
432
|
const invalidatePath = async (routeItem, pathname, options) => {
|
|
420
433
|
const routePathname = routeDataState.getState().location.pathname;
|
|
421
434
|
if (!options?.staleOnly) {
|
|
422
435
|
loaderMap.delete(pathname);
|
|
423
436
|
syncCacheSnapshot();
|
|
437
|
+
await loadingPromises.get(pathname);
|
|
424
438
|
}
|
|
425
439
|
const [path, search = ""] = pathname.split("?");
|
|
426
440
|
const result = await revalidateCache({
|
|
@@ -429,7 +443,8 @@ var createInvalidate = ({ routeDataState, loaderMap }, revalidateCache, syncCach
|
|
|
429
443
|
pathname: path,
|
|
430
444
|
search
|
|
431
445
|
},
|
|
432
|
-
reason: "invalidate"
|
|
446
|
+
reason: "invalidate",
|
|
447
|
+
force: !options?.staleOnly
|
|
433
448
|
});
|
|
434
449
|
if (result && path === routePathname) routeDataState.setState((prevState) => ({
|
|
435
450
|
...prevState,
|
|
@@ -466,7 +481,8 @@ var createInvalidate = ({ routeDataState, loaderMap }, revalidateCache, syncCach
|
|
|
466
481
|
return (await Promise.all(pathnameList.map((pathname) => invalidateItem(pathname, options)))).flat();
|
|
467
482
|
};
|
|
468
483
|
};
|
|
469
|
-
|
|
484
|
+
//#endregion
|
|
485
|
+
//#region runtime/prefetch.ts
|
|
470
486
|
var MOBILE_PREFETCH_CONCURRENCY = 2;
|
|
471
487
|
var DESKTOP_PREFETCH_CONCURRENCY = 4;
|
|
472
488
|
var createPrefetch = ({ routeDataState }, revalidateCache) => {
|
|
@@ -504,7 +520,9 @@ var createPrefetch = ({ routeDataState }, revalidateCache) => {
|
|
|
504
520
|
drain();
|
|
505
521
|
});
|
|
506
522
|
};
|
|
507
|
-
|
|
523
|
+
//#endregion
|
|
524
|
+
//#region runtime/revalidateCache.ts
|
|
525
|
+
var PRELOAD_STALE_TIME = 3e4;
|
|
508
526
|
var isObjectRetry = (arg) => typeof arg === "object";
|
|
509
527
|
var createRetry = (arg) => {
|
|
510
528
|
if (arg === void 0) return null;
|
|
@@ -523,11 +541,13 @@ var getRetry = (routeItem) => {
|
|
|
523
541
|
};
|
|
524
542
|
};
|
|
525
543
|
var createRevalidateCache = (routerState, syncCacheSnapshot) => {
|
|
526
|
-
const { loaderMap, loadingPromises, contextState } = routerState;
|
|
544
|
+
const { loaderMap, loadingPromises, contextState, routeDataState } = routerState;
|
|
527
545
|
const flightOwners = /* @__PURE__ */ new Map();
|
|
528
546
|
const evict = () => {
|
|
529
547
|
if (loaderMap.size <= routerConfig.maxCacheSize) return;
|
|
530
|
-
const
|
|
548
|
+
const { pathname, search = "" } = routeDataState.getState().location;
|
|
549
|
+
const currentPath = `${pathname}${search}`;
|
|
550
|
+
const oldestKey = [...loaderMap.keys()].find((key) => key !== currentPath);
|
|
531
551
|
if (oldestKey) {
|
|
532
552
|
loaderMap.delete(oldestKey);
|
|
533
553
|
syncCacheSnapshot();
|
|
@@ -560,7 +580,12 @@ var createRevalidateCache = (routerState, syncCacheSnapshot) => {
|
|
|
560
580
|
}
|
|
561
581
|
}
|
|
562
582
|
if (!force && isCacheItemFresh(path)) {
|
|
563
|
-
const item =
|
|
583
|
+
const item = loaderMap.get(path);
|
|
584
|
+
if (reason === "navigation" && item?.reason === "prefetch") {
|
|
585
|
+
item.reason = "navigation";
|
|
586
|
+
item.staleTime = routeItem.staleTime;
|
|
587
|
+
}
|
|
588
|
+
moveItemToLastPosition(path);
|
|
564
589
|
if (!item?.state) return void 0;
|
|
565
590
|
return item.state.loaderError ? {
|
|
566
591
|
data: null,
|
|
@@ -583,6 +608,7 @@ var createRevalidateCache = (routerState, syncCacheSnapshot) => {
|
|
|
583
608
|
signal: effectiveSignal,
|
|
584
609
|
attempt: retried + 1
|
|
585
610
|
});
|
|
611
|
+
const resolvedStaleTime = routeItem.staleTime ?? routerConfig.defaultStaleTime ?? 0;
|
|
586
612
|
loaderMap.set(path, {
|
|
587
613
|
state: {
|
|
588
614
|
data: result,
|
|
@@ -590,7 +616,7 @@ var createRevalidateCache = (routerState, syncCacheSnapshot) => {
|
|
|
590
616
|
loaderError: null
|
|
591
617
|
},
|
|
592
618
|
timestamp: Date.now(),
|
|
593
|
-
staleTime: routeItem.staleTime,
|
|
619
|
+
staleTime: reason === "prefetch" ? Math.max(resolvedStaleTime, PRELOAD_STALE_TIME) : routeItem.staleTime,
|
|
594
620
|
reason
|
|
595
621
|
});
|
|
596
622
|
evict();
|
|
@@ -636,17 +662,19 @@ var createRevalidateCache = (routerState, syncCacheSnapshot) => {
|
|
|
636
662
|
};
|
|
637
663
|
return revalidateCache;
|
|
638
664
|
};
|
|
639
|
-
|
|
665
|
+
//#endregion
|
|
666
|
+
//#region runtime/syncCacheSnapshot.ts
|
|
640
667
|
var createCacheSnapshot = (loaderMap, loadingPromises) => {
|
|
641
668
|
const entries = [];
|
|
642
669
|
for (const [path, item] of loaderMap) entries.push({
|
|
643
670
|
path,
|
|
644
671
|
data: item.state?.data,
|
|
645
672
|
timestamp: item.timestamp,
|
|
646
|
-
staleTime: item.staleTime,
|
|
673
|
+
staleTime: item.staleTime ?? routerConfig.defaultStaleTime ?? 0,
|
|
647
674
|
reason: item.reason,
|
|
648
675
|
gcExpiresAt: item.gcExpiresAt,
|
|
649
676
|
gcDuration: item.gcDuration,
|
|
677
|
+
isCached: true,
|
|
650
678
|
isLoading: loadingPromises.has(path)
|
|
651
679
|
});
|
|
652
680
|
for (const path of loadingPromises.keys()) {
|
|
@@ -655,15 +683,17 @@ var createCacheSnapshot = (loaderMap, loadingPromises) => {
|
|
|
655
683
|
path,
|
|
656
684
|
data: void 0,
|
|
657
685
|
timestamp: Date.now(),
|
|
658
|
-
staleTime:
|
|
686
|
+
staleTime: routerConfig.defaultStaleTime ?? 0,
|
|
659
687
|
gcExpiresAt: void 0,
|
|
660
688
|
gcDuration: void 0,
|
|
689
|
+
isCached: false,
|
|
661
690
|
isLoading: true
|
|
662
691
|
});
|
|
663
692
|
}
|
|
664
693
|
return entries;
|
|
665
694
|
};
|
|
666
|
-
|
|
695
|
+
//#endregion
|
|
696
|
+
//#region creators/createRouterInstance.ts
|
|
667
697
|
var createRouterInstance = (synchronizer) => {
|
|
668
698
|
const loaderMap = /* @__PURE__ */ new Map();
|
|
669
699
|
const loadingPromises = /* @__PURE__ */ new Map();
|
|
@@ -684,7 +714,7 @@ var createRouterInstance = (synchronizer) => {
|
|
|
684
714
|
loadingPromises
|
|
685
715
|
};
|
|
686
716
|
const syncCacheSnapshot = () => {
|
|
687
|
-
if (routerConfig.
|
|
717
|
+
if (routerConfig.enableCacheSnapshot) cacheSnapshotState.setState(createCacheSnapshot(loaderMap, loadingPromises));
|
|
688
718
|
};
|
|
689
719
|
const revalidateCache = createRevalidateCache(routerState, syncCacheSnapshot);
|
|
690
720
|
const navigate = createNavigate(routerState, revalidateCache, syncCacheSnapshot);
|
|
@@ -763,8 +793,11 @@ var createRouterInstance = (synchronizer) => {
|
|
|
763
793
|
useAction: (action, options = {}) => {
|
|
764
794
|
return async (input) => {
|
|
765
795
|
try {
|
|
766
|
-
const
|
|
767
|
-
|
|
796
|
+
const currentAction = getCurrentAction(action);
|
|
797
|
+
const { location } = routerState.routeDataState.getState();
|
|
798
|
+
const path = `${location.pathname}${location.search ?? ""}`;
|
|
799
|
+
const data = await currentAction(input);
|
|
800
|
+
await invalidate(path);
|
|
768
801
|
options.onSuccess?.(data);
|
|
769
802
|
return {
|
|
770
803
|
data,
|
|
@@ -817,13 +850,16 @@ var createRouterInstance = (synchronizer) => {
|
|
|
817
850
|
}
|
|
818
851
|
};
|
|
819
852
|
};
|
|
820
|
-
|
|
853
|
+
//#endregion
|
|
854
|
+
//#region instance.ts
|
|
821
855
|
var router = createRouterInstance(useSyncExternalStore);
|
|
822
|
-
|
|
856
|
+
//#endregion
|
|
857
|
+
//#region hooks/useNavigation.ts
|
|
823
858
|
var useNavigation = () => {
|
|
824
859
|
const { navigate } = router.runtime;
|
|
825
860
|
const { useRouteDataSelector, useBlockerState } = router.hooks;
|
|
826
861
|
const location = useRouteDataSelector((state) => state.location);
|
|
862
|
+
const skipForwardPop = useRef(false);
|
|
827
863
|
const [blockerState] = useBlockerState();
|
|
828
864
|
useEffect(() => {
|
|
829
865
|
const handler = async (event) => {
|
|
@@ -832,7 +868,19 @@ var useNavigation = () => {
|
|
|
832
868
|
pathname: location.pathname,
|
|
833
869
|
search: location.search
|
|
834
870
|
};
|
|
835
|
-
if (
|
|
871
|
+
if (skipForwardPop.current) {
|
|
872
|
+
skipForwardPop.current = false;
|
|
873
|
+
if (newLocation.pathname === location.pathname && (newLocation.search ?? "") === (location.search ?? "")) return;
|
|
874
|
+
}
|
|
875
|
+
if (blockerState === "charged" || blockerState === "blocked") {
|
|
876
|
+
skipForwardPop.current = true;
|
|
877
|
+
if (blockerState === "charged") await navigate({
|
|
878
|
+
...newLocation,
|
|
879
|
+
prevLocation
|
|
880
|
+
});
|
|
881
|
+
history.forward();
|
|
882
|
+
return;
|
|
883
|
+
}
|
|
836
884
|
await navigate({
|
|
837
885
|
...newLocation,
|
|
838
886
|
prevLocation
|
|
@@ -851,7 +899,8 @@ var useNavigation = () => {
|
|
|
851
899
|
navigate(parseWindowLocation(window.location));
|
|
852
900
|
}, [navigate]);
|
|
853
901
|
};
|
|
854
|
-
|
|
902
|
+
//#endregion
|
|
903
|
+
//#region hooks/useApplyCustomAnimation.ts
|
|
855
904
|
var useApplyCustomAnimation = (animationDuration) => {
|
|
856
905
|
useEffect(() => {
|
|
857
906
|
if (!animationDuration) return;
|
|
@@ -862,29 +911,34 @@ var useApplyCustomAnimation = (animationDuration) => {
|
|
|
862
911
|
return () => style.remove();
|
|
863
912
|
}, [animationDuration]);
|
|
864
913
|
};
|
|
865
|
-
|
|
914
|
+
//#endregion
|
|
915
|
+
//#region hooks/useRestoreScroll.ts
|
|
866
916
|
var useRestoreScroll = (behavior) => {
|
|
867
917
|
const { useScrollRestoration } = router.hooks;
|
|
868
918
|
const { defaultScrollRestorationBehavior = "auto" } = routerConfig;
|
|
869
919
|
return useScrollRestoration(behavior ?? defaultScrollRestorationBehavior);
|
|
870
920
|
};
|
|
871
|
-
|
|
921
|
+
//#endregion
|
|
922
|
+
//#region hooks/useRestoreRouteScroll.ts
|
|
872
923
|
var useRestoreRouteScroll = (behavior) => {
|
|
873
924
|
const restoreScroll = useRestoreScroll(behavior);
|
|
874
925
|
useEffect(restoreScroll, [restoreScroll]);
|
|
875
926
|
};
|
|
876
|
-
|
|
927
|
+
//#endregion
|
|
928
|
+
//#region hooks/useSetRouterConfig.ts
|
|
877
929
|
var useSetRouterConfig = (routerProps) => {
|
|
878
930
|
useLayoutEffect(() => routerConfig.configure(routerProps), [routerProps]);
|
|
879
931
|
};
|
|
880
|
-
|
|
932
|
+
//#endregion
|
|
933
|
+
//#region hooks/useSetInitialContext.ts
|
|
881
934
|
var useSetInitialContext = (initialContext) => {
|
|
882
935
|
const [, setContext] = router.hooks.useContextState();
|
|
883
936
|
useEffect(() => {
|
|
884
937
|
if (initialContext) setContext(initialContext);
|
|
885
938
|
}, [initialContext, setContext]);
|
|
886
939
|
};
|
|
887
|
-
|
|
940
|
+
//#endregion
|
|
941
|
+
//#region hooks/useReload.ts
|
|
888
942
|
var useReload = () => {
|
|
889
943
|
const { invalidate } = router.runtime;
|
|
890
944
|
useEffect(() => {
|
|
@@ -902,18 +956,20 @@ var useReload = () => {
|
|
|
902
956
|
return () => window.removeEventListener("online", handler);
|
|
903
957
|
}, [invalidate]);
|
|
904
958
|
};
|
|
905
|
-
|
|
959
|
+
//#endregion
|
|
960
|
+
//#region utils/renderElement.tsx
|
|
906
961
|
var renderElement = (Component) => {
|
|
907
962
|
if (!Component) return null;
|
|
908
963
|
if (typeof Component !== "function") return Component;
|
|
909
964
|
return /* @__PURE__ */ jsx(Component, {});
|
|
910
965
|
};
|
|
911
|
-
|
|
966
|
+
//#endregion
|
|
967
|
+
//#region components/Router.tsx
|
|
912
968
|
var EmptyBoundary = ({ children }) => children;
|
|
913
969
|
var IS_MOBILE = isMobile();
|
|
914
970
|
var MOBILE_CACHE_SIZE = 60;
|
|
915
971
|
var DESKTOP_CACHE_SIZE = 150;
|
|
916
|
-
var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration, defaultLoaderFallback, defaultErrorElement, defaultRetry, defaultStaleTime, context: initialContext, isAnimated = false, defaultMinLoaderDuration = 0, revalidateOnFocus = false, revalidateOnReconnect = false, maxCacheSize = IS_MOBILE ? MOBILE_CACHE_SIZE : DESKTOP_CACHE_SIZE, defaultPrefetch = IS_MOBILE ? "viewport" : "hover", defaultHoverPrefetchDelay = 150, defaultScrollRestorationBehavior = "auto", errorBoundary: ErrorBoundary = EmptyBoundary,
|
|
972
|
+
var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration, defaultLoaderFallback, defaultErrorElement, defaultRetry, defaultStaleTime, context: initialContext, isAnimated = false, defaultMinLoaderDuration = 0, revalidateOnFocus = false, revalidateOnReconnect = false, maxCacheSize = IS_MOBILE ? MOBILE_CACHE_SIZE : DESKTOP_CACHE_SIZE, defaultPrefetch = IS_MOBILE ? "viewport" : "hover", defaultHoverPrefetchDelay = 150, defaultScrollRestorationBehavior = "auto", errorBoundary: ErrorBoundary = EmptyBoundary, enableCacheSnapshot = false }) => {
|
|
917
973
|
const { useRouteDataSelector } = router.hooks;
|
|
918
974
|
const routeItem = useRouteDataSelector((state) => state.routeItem);
|
|
919
975
|
const location = useRouteDataSelector((state) => state.location);
|
|
@@ -935,7 +991,7 @@ var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration,
|
|
|
935
991
|
revalidateOnFocus,
|
|
936
992
|
revalidateOnReconnect,
|
|
937
993
|
defaultScrollRestorationBehavior,
|
|
938
|
-
|
|
994
|
+
enableCacheSnapshot
|
|
939
995
|
});
|
|
940
996
|
useApplyCustomAnimation(animationDuration);
|
|
941
997
|
useSetInitialContext(initialContext);
|
|
@@ -951,23 +1007,25 @@ var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration,
|
|
|
951
1007
|
children: content
|
|
952
1008
|
}));
|
|
953
1009
|
};
|
|
954
|
-
|
|
1010
|
+
//#endregion
|
|
1011
|
+
//#region hooks/useNavigate.ts
|
|
955
1012
|
var useNavigate = router.hooks.useNavigate;
|
|
956
|
-
|
|
1013
|
+
//#endregion
|
|
1014
|
+
//#region components/Link.tsx
|
|
957
1015
|
var VIEWPORT_DWELL_MS = 250;
|
|
958
1016
|
var defaultAs = (props) => /* @__PURE__ */ jsx("a", { ...props });
|
|
959
1017
|
var comparator = (to, pathname, exact) => to === "/" ? pathname === "/" : exact ? pathname === to : pathname === to || pathname?.startsWith(`${to}/`);
|
|
960
1018
|
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 }) => {
|
|
961
1019
|
const pathname = path !== void 0 ? interpolatePath(path, params ?? {}) : to ?? "";
|
|
1020
|
+
const searchString = typeof search === "object" ? formatSearchObject(search) : search;
|
|
962
1021
|
const { useRouteDataSelector } = router.hooks;
|
|
963
|
-
const isPending = useRouteDataSelector(({ location: { pathname: currentPathname }, status }) => currentPathname === pathname && status === "pending");
|
|
1022
|
+
const isPending = useRouteDataSelector(({ location: { pathname: currentPathname, search: currentSearch = "" }, status }) => currentPathname === pathname && currentSearch === searchString && status === "pending");
|
|
964
1023
|
const navigate = useNavigate();
|
|
965
1024
|
const isActive = useRouteDataSelector(({ location: { pathname: currentPathname } }) => comparator(pathname, currentPathname, exact));
|
|
966
1025
|
const timeout = useRef(0);
|
|
967
1026
|
const elementRef = useRef(null);
|
|
968
1027
|
const getPrefetchStrategy = useCallback(() => linkPrefetch || routerConfig.defaultPrefetch, [linkPrefetch]);
|
|
969
1028
|
const getPrefetchDelay = useCallback(() => hoverPrefetchDelay ?? routerConfig.defaultHoverPrefetchDelay, [hoverPrefetchDelay]);
|
|
970
|
-
const searchString = typeof search === "object" ? formatSearchObject(search) : search;
|
|
971
1029
|
const location = useMemo(() => ({
|
|
972
1030
|
pathname,
|
|
973
1031
|
search: searchString,
|
|
@@ -1080,7 +1138,8 @@ var Link = ({ children, to, path, params, search = "", state, as = defaultAs, pr
|
|
|
1080
1138
|
isPending
|
|
1081
1139
|
});
|
|
1082
1140
|
};
|
|
1083
|
-
|
|
1141
|
+
//#endregion
|
|
1142
|
+
//#region hooks/useParams.ts
|
|
1084
1143
|
/**
|
|
1085
1144
|
* Route params of the current location.
|
|
1086
1145
|
*
|
|
@@ -1089,16 +1148,20 @@ var Link = ({ children, to, path, params, search = "", state, as = defaultAs, pr
|
|
|
1089
1148
|
* - `useParams<{ ... }>()` — legacy manual shape, kept for compatibility.
|
|
1090
1149
|
*/
|
|
1091
1150
|
var useParams = () => router.hooks.useParams();
|
|
1092
|
-
|
|
1151
|
+
//#endregion
|
|
1152
|
+
//#region hooks/useLocation.ts
|
|
1093
1153
|
var useLocation = () => router.hooks.useRouteDataSelector((state) => state.location);
|
|
1094
|
-
|
|
1154
|
+
//#endregion
|
|
1155
|
+
//#region hooks/useLoaderState.ts
|
|
1095
1156
|
var useLoaderState = () => {
|
|
1096
1157
|
const { useRouteDataSelector } = router.hooks;
|
|
1097
1158
|
return useRouteDataSelector((state) => state.loaderState);
|
|
1098
1159
|
};
|
|
1099
|
-
|
|
1160
|
+
//#endregion
|
|
1161
|
+
//#region hooks/useInvalidate.ts
|
|
1100
1162
|
var useInvalidate = () => router.runtime.invalidate;
|
|
1101
|
-
|
|
1163
|
+
//#endregion
|
|
1164
|
+
//#region hooks/useBlocker.ts
|
|
1102
1165
|
var useBlocker = (blockerFn) => {
|
|
1103
1166
|
const { hooks: { useBlockerState, useContextState, useBlockedTargetState }, runtime: { navigate } } = router;
|
|
1104
1167
|
const [blockerState, setBlockerState] = useBlockerState();
|
|
@@ -1118,11 +1181,15 @@ var useBlocker = (blockerFn) => {
|
|
|
1118
1181
|
return {
|
|
1119
1182
|
state: blockerState,
|
|
1120
1183
|
process: useCallback(async () => {
|
|
1121
|
-
if (nextLocation)
|
|
1184
|
+
if (!nextLocation) return;
|
|
1185
|
+
const target = nextLocation;
|
|
1186
|
+
setBlockerState("unblocked");
|
|
1187
|
+
await navigate(target);
|
|
1122
1188
|
setNextLocation(null);
|
|
1123
1189
|
}, [
|
|
1124
1190
|
navigate,
|
|
1125
1191
|
nextLocation,
|
|
1192
|
+
setBlockerState,
|
|
1126
1193
|
setNextLocation
|
|
1127
1194
|
]),
|
|
1128
1195
|
reset: useCallback(() => {
|
|
@@ -1131,14 +1198,17 @@ var useBlocker = (blockerFn) => {
|
|
|
1131
1198
|
}, [setBlockerState, setNextLocation])
|
|
1132
1199
|
};
|
|
1133
1200
|
};
|
|
1134
|
-
|
|
1201
|
+
//#endregion
|
|
1202
|
+
//#region hooks/useAction.ts
|
|
1135
1203
|
var useAction = router.hooks.useAction;
|
|
1136
|
-
|
|
1204
|
+
//#endregion
|
|
1205
|
+
//#region hooks/useRouteStatus.ts
|
|
1137
1206
|
function useRouteStatus(predicate) {
|
|
1138
1207
|
const { useRouteDataSelector } = router.hooks;
|
|
1139
1208
|
return useRouteDataSelector(({ status }) => predicate ? predicate(status) : status);
|
|
1140
1209
|
}
|
|
1141
|
-
|
|
1210
|
+
//#endregion
|
|
1211
|
+
//#region hooks/useRouterContext.ts
|
|
1142
1212
|
var useRouterContext = () => {
|
|
1143
1213
|
const [context, setContext] = router.hooks.useContextState();
|
|
1144
1214
|
return {
|
|
@@ -1146,7 +1216,8 @@ var useRouterContext = () => {
|
|
|
1146
1216
|
setContext
|
|
1147
1217
|
};
|
|
1148
1218
|
};
|
|
1149
|
-
|
|
1219
|
+
//#endregion
|
|
1220
|
+
//#region hooks/useSearchParams.ts
|
|
1150
1221
|
var useLatest = (value) => {
|
|
1151
1222
|
const ref = useRef(value);
|
|
1152
1223
|
useEffect(() => {
|
|
@@ -1183,14 +1254,13 @@ var useSearchParams = () => {
|
|
|
1183
1254
|
currentParams.delete(param);
|
|
1184
1255
|
(Array.isArray(value) ? value : [value]).forEach((v) => currentParams.append(param, v));
|
|
1185
1256
|
navigateWithSearchParams(currentParams);
|
|
1186
|
-
} else if (typeof param === "function")
|
|
1187
|
-
|
|
1188
|
-
navigateWithSearchParams(newParams);
|
|
1189
|
-
} else throw new Error("useSearchParams first argument must be either function or string");
|
|
1257
|
+
} else if (typeof param === "function") navigateWithSearchParams(param(currentParams));
|
|
1258
|
+
else throw new Error("useSearchParams first argument must be either function or string");
|
|
1190
1259
|
}, [navigateWithSearchParams, searchRef])
|
|
1191
1260
|
};
|
|
1192
1261
|
};
|
|
1193
|
-
|
|
1262
|
+
//#endregion
|
|
1263
|
+
//#region hooks/useSubmitAction.ts
|
|
1194
1264
|
var useSubmitAction = (action, options) => {
|
|
1195
1265
|
const currentAction = router.hooks.useAction(action, options);
|
|
1196
1266
|
const [data, setData] = useState();
|
|
@@ -1217,14 +1287,15 @@ var useSubmitAction = (action, options) => {
|
|
|
1217
1287
|
isSubmitting
|
|
1218
1288
|
};
|
|
1219
1289
|
};
|
|
1220
|
-
|
|
1221
|
-
|
|
1290
|
+
//#endregion
|
|
1291
|
+
//#region hooks/useCacheSnapshot.ts
|
|
1222
1292
|
var useCacheSnapshot = () => {
|
|
1223
1293
|
const snapshot = router.hooks.useCacheSnapshot();
|
|
1224
1294
|
useEffect(() => router.runtime.syncCacheSnapshot(), []);
|
|
1225
1295
|
return snapshot;
|
|
1226
1296
|
};
|
|
1227
|
-
|
|
1297
|
+
//#endregion
|
|
1298
|
+
//#region utils/createLazyComponent.tsx
|
|
1228
1299
|
var createLazyComponent = (importFn, fallback) => {
|
|
1229
1300
|
const load = () => importFn().then((module) => ({ default: module.default || module }));
|
|
1230
1301
|
const LazyComp = lazy$1(load);
|
|
@@ -1237,9 +1308,11 @@ var createLazyComponent = (importFn, fallback) => {
|
|
|
1237
1308
|
preloadElement: load
|
|
1238
1309
|
};
|
|
1239
1310
|
};
|
|
1240
|
-
|
|
1311
|
+
//#endregion
|
|
1312
|
+
//#region types.ts
|
|
1241
1313
|
var LAZY_MARKER = Symbol("clear-router-lazy");
|
|
1242
|
-
|
|
1314
|
+
//#endregion
|
|
1315
|
+
//#region creators/createRouter.ts
|
|
1243
1316
|
var isLazy = (component) => typeof component === "object" && component !== null && LAZY_MARKER in component;
|
|
1244
1317
|
var resolve = (component, fallback) => isLazy(component) ? createLazyComponent(component.importFn, fallback).Component : component;
|
|
1245
1318
|
var parseClientRouteItem = (el, parentPattern = "", inheritedLayouts = []) => {
|
|
@@ -1256,9 +1329,11 @@ var parseClientRouteItem = (el, parentPattern = "", inheritedLayouts = []) => {
|
|
|
1256
1329
|
}, ...el.children?.flatMap((child) => parseClientRouteItem(child, pattern, layouts)) ?? []];
|
|
1257
1330
|
};
|
|
1258
1331
|
var createRouter = (clientList) => clientList.flatMap((el) => parseClientRouteItem(el));
|
|
1259
|
-
|
|
1332
|
+
//#endregion
|
|
1333
|
+
//#region utils/lazy.ts
|
|
1260
1334
|
var lazy = (importFn) => ({
|
|
1261
1335
|
[LAZY_MARKER]: true,
|
|
1262
1336
|
importFn
|
|
1263
1337
|
});
|
|
1338
|
+
//#endregion
|
|
1264
1339
|
export { Link, Router, createRouter, lazy, useAction, useBlocker, useCacheSnapshot, useInvalidate, useLoaderState, useLocation, useNavigate, useParams, useRestoreScroll, useRouteStatus, useRouterContext, useSearchParams, useSubmitAction };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { type InvalidateOptions, InvalidateResult, RevalidateCache, RouterState } from '../types';
|
|
2
|
-
export declare const createInvalidate: ({ routeDataState, loaderMap }: RouterState, revalidateCache: RevalidateCache, syncCacheSnapshot: () => void) => (pathList?: string | string[], options?: InvalidateOptions) => Promise<InvalidateResult[]>;
|
|
2
|
+
export declare const createInvalidate: ({ routeDataState, loaderMap, loadingPromises }: RouterState, revalidateCache: RevalidateCache, syncCacheSnapshot: () => void) => (pathList?: string | string[], options?: InvalidateOptions) => Promise<InvalidateResult[]>;
|
package/dist/types.d.ts
CHANGED
|
@@ -108,7 +108,7 @@ export type RouterProps = {
|
|
|
108
108
|
revalidateOnReconnect?: boolean;
|
|
109
109
|
context?: Record<string, unknown>;
|
|
110
110
|
/** Enables cache snapshot tracking for devtools. `useCacheSnapshot` returns an empty list without it. */
|
|
111
|
-
|
|
111
|
+
enableCacheSnapshot?: boolean;
|
|
112
112
|
};
|
|
113
113
|
export type LoaderStateItem = {
|
|
114
114
|
state: LoaderState;
|
|
@@ -127,6 +127,7 @@ export type CacheSnapshotEntry = {
|
|
|
127
127
|
reason?: CacheReason;
|
|
128
128
|
gcExpiresAt: number | undefined;
|
|
129
129
|
gcDuration: number | undefined;
|
|
130
|
+
isCached: boolean;
|
|
130
131
|
isLoading: boolean;
|
|
131
132
|
};
|
|
132
133
|
export type CacheSnapshot = CacheSnapshotEntry[];
|