clear-react-router 2.0.9 → 2.1.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 +7 -6
- package/dist/components/Router.d.ts +1 -1
- package/dist/config/routerConfig.d.ts +0 -1
- package/dist/constants.d.ts +3 -1
- package/dist/hooks/usePreserveScroll.d.ts +2 -2
- package/dist/index.d.ts +1 -1
- package/dist/index.js +139 -115
- package/dist/types.d.ts +7 -5
- package/dist/utils/createRouter.d.ts +2 -0
- package/dist/utils/utils.d.ts +4 -3
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -43,7 +43,7 @@ It provides first-class support for:
|
|
|
43
43
|
| `routes` | `RouteItem[]` | required | Array of route configurations |
|
|
44
44
|
| `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 |
|
|
45
45
|
| `isAnimated` | `boolean \| undefined` | `false` | Enable smooth page fade transitions |
|
|
46
|
-
| `animationDuration` | `number` | `optional` | Animation duration in milliseconds (browser default is used if not set) |
|
|
46
|
+
| `animationDuration` | `number \| undefined` | `optional` | Animation duration in milliseconds (browser default is used if not set) |
|
|
47
47
|
| `optimisticSpinner` | `boolean \| undefined` | `true` | Show a small spinner in the corner while optimistic route data revalidates in the background |
|
|
48
48
|
| `context` | `object` | `{}` | Initial context (user, theme, etc.) |
|
|
49
49
|
| `errorBoundary` | `ComponentType<{ children: ReactNode }>` | `undefined` | Custom error boundary component for catching render errors in route components |
|
|
@@ -56,7 +56,8 @@ It provides first-class support for:
|
|
|
56
56
|
| `defaultAfterLoad` | `({ params, context, setContext }) => Promise<void>` | `undefined` | Runs after every successful navigation. Useful for analytics, page tracking, or other global side effects. |
|
|
57
57
|
| `defaultPreserveScroll` | `boolean \| undefined` | `true` | Default value for save and restore scroll position when navigating between pages |
|
|
58
58
|
| `defaultPrefetch` | `'hover' \| 'render' \| 'viewport' \| 'none'` | `'hover'` for desktop, `'viewport'` for mobile | Default prefetch strategy for all `<Link>` components |
|
|
59
|
-
| `defaultHoverPrefetchDelay` | `number` | `150` | Default delay in milliseconds before prefetching on hover (only for `'hover'` strategy) |
|
|
59
|
+
| `defaultHoverPrefetchDelay` | `number \| undefined` | `150` | Default delay in milliseconds before prefetching on hover (only for `'hover'` strategy) |
|
|
60
|
+
| `defaultScrollRestorationBehavior` | `'auto' \| 'smooth' \| 'instant'` | `auto` | Default scroll restoration behavior |
|
|
60
61
|
|
|
61
62
|
|
|
62
63
|
> **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.
|
|
@@ -78,10 +79,11 @@ Normalizes route configuration. Extracts dynamic params, builds nested paths.
|
|
|
78
79
|
| `retry` | `number \| { count: number; delay: number }` | Overrides the global cache revalidation retry policy for this route |
|
|
79
80
|
| `optimistic` | `boolean \| undefined` | Instant navigation using stale data while fresh data is loaded in the background |
|
|
80
81
|
| `errorElement` | `ReactElement \| () => ReactElement` | Error fallback for the route. Overrides the global `defaultErrorElement` set in `Router` |
|
|
81
|
-
| `staleTime` | `number` | Time in milliseconds before cached loader data is considered stale. Overrides Router.defaultStaleTime. If neither value is provided, cached data never expires |
|
|
82
|
+
| `staleTime` | `number \| undefined` | Time in milliseconds before cached loader data is considered stale. Overrides Router.defaultStaleTime. If neither value is provided, cached data never expires |
|
|
82
83
|
| `actions` | `({ params, context, invalidate, setContext }) => Record<string, (formData: FormData) => unknown \| Promise<unknown>>` | Defines route actions for data mutations. Actions receive `FormData`, can update context via `setContext`, and can invalidate cached loader data using the router-provided `invalidate` |
|
|
83
84
|
| `pollingInterval` | `number \| undefined` | Polling interval (in milliseconds) for automatically revalidating data while the route is active |
|
|
84
|
-
| `
|
|
85
|
+
| `scrollRestoration` | `boolean \| string[] \| undefined` | Restore scroll position when navigating back to this route. `true` restores the window scroll; a string array restores scroll inside specific scrollable elements, matched by their `id` |
|
|
86
|
+
| `scrollRestorationBehavior` | `'auto' \| 'smooth' \| 'instant'` | Scroll restoration behavior |
|
|
85
87
|
|
|
86
88
|
Before load arguments (see [`redirect`](#redirect) for details on programmatic redirects):
|
|
87
89
|
|
|
@@ -587,8 +589,7 @@ const UserProfile = () => {
|
|
|
587
589
|
}
|
|
588
590
|
```
|
|
589
591
|
|
|
590
|
-
-
|
|
591
|
-
- On top of that, 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. 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`:
|
|
592
|
+
- 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. 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`:
|
|
592
593
|
|
|
593
594
|
```tsx
|
|
594
595
|
<Router routes={routes} maxCacheSize={200} />
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { RouterProps } from '../types';
|
|
2
|
-
export declare const Router: ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration, defaultLoaderFallback, defaultErrorElement, defaultRetry, defaultStaleTime, context: initialContext, isAnimated, optimisticSpinner,
|
|
2
|
+
export declare const Router: ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration, defaultLoaderFallback, defaultErrorElement, defaultRetry, defaultStaleTime, context: initialContext, isAnimated, optimisticSpinner, defaultMinLoaderDuration, maxCacheSize, defaultPrefetch, defaultHoverPrefetchDelay, defaultScrollRestorationBehavior, errorBoundary: ErrorBoundary, }: RouterProps) => import("react/jsx-runtime").JSX.Element | null;
|
|
@@ -9,7 +9,6 @@ declare class RouterConfig {
|
|
|
9
9
|
defaultAfterLoad?: ClientRouteItem['afterLoad'];
|
|
10
10
|
defaultRetry?: RouterProps['defaultRetry'];
|
|
11
11
|
defaultStaleTime?: RouterProps['defaultStaleTime'];
|
|
12
|
-
defaultPreserveScroll?: RouterProps['defaultPreserveScroll'];
|
|
13
12
|
defaultMinLoaderDuration?: RouterProps['defaultMinLoaderDuration'];
|
|
14
13
|
configure(config: Partial<RouterConfig>): void;
|
|
15
14
|
}
|
package/dist/constants.d.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
1
|
import type { LoaderState } from './types';
|
|
2
|
-
export declare const
|
|
2
|
+
export declare const EMPTY_LOADER_STATE: LoaderState;
|
|
3
3
|
export declare const STANDARD_PREFETCH_DELAY = 150;
|
|
4
|
+
export declare const WINDOW_TOP = "__window_top__";
|
|
5
|
+
export declare const WINDOW_LEFT = "__window_left__";
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
2
|
-
export declare const usePreserveScroll: (
|
|
1
|
+
import { ScrollRestorationBehavior } from '../types';
|
|
2
|
+
export declare const usePreserveScroll: (restorationBehavior: ScrollRestorationBehavior) => void;
|
package/dist/index.d.ts
CHANGED
|
@@ -12,6 +12,6 @@ export { useIsDataLoading } from './hooks/useIsDataLoading';
|
|
|
12
12
|
export { useRouterContext } from './hooks/useRouterContext';
|
|
13
13
|
export { useSearchParams } from './hooks/useSearchParams';
|
|
14
14
|
export { useFormContext } from './hooks/useFormContext';
|
|
15
|
+
export { createRouter } from './utils/createRouter';
|
|
15
16
|
export { lazy } from './utils/lazy';
|
|
16
|
-
export { createRouter } from './utils/utils';
|
|
17
17
|
export type { RouteItem, BlockerState, Location, RouterProps, ElementProps } from './types';
|
package/dist/index.js
CHANGED
|
@@ -43,7 +43,9 @@ var createCommitState = ({ routeItemDataState, statusState, isOptimisticLoading,
|
|
|
43
43
|
};
|
|
44
44
|
//#endregion
|
|
45
45
|
//#region constants.ts
|
|
46
|
-
var
|
|
46
|
+
var EMPTY_LOADER_STATE = {};
|
|
47
|
+
var WINDOW_TOP = "__window_top__";
|
|
48
|
+
var WINDOW_LEFT = "__window_left__";
|
|
47
49
|
//#endregion
|
|
48
50
|
//#region \0@oxc-project+runtime@0.133.0/helpers/esm/typeof.js
|
|
49
51
|
function _typeof(o) {
|
|
@@ -95,7 +97,6 @@ var RouterConfig = class {
|
|
|
95
97
|
_defineProperty(this, "defaultAfterLoad", void 0);
|
|
96
98
|
_defineProperty(this, "defaultRetry", void 0);
|
|
97
99
|
_defineProperty(this, "defaultStaleTime", void 0);
|
|
98
|
-
_defineProperty(this, "defaultPreserveScroll", void 0);
|
|
99
100
|
_defineProperty(this, "defaultMinLoaderDuration", void 0);
|
|
100
101
|
}
|
|
101
102
|
configure(config) {
|
|
@@ -125,73 +126,7 @@ var createIsCacheItemFresh = (loaderMap) => (path) => {
|
|
|
125
126
|
return Date.now() - item.timestamp <= resolvedStaleTime;
|
|
126
127
|
};
|
|
127
128
|
//#endregion
|
|
128
|
-
//#region ../../node_modules/react/cjs/react-jsx-runtime.production.js
|
|
129
|
-
/**
|
|
130
|
-
* @license React
|
|
131
|
-
* react-jsx-runtime.production.js
|
|
132
|
-
*
|
|
133
|
-
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
134
|
-
*
|
|
135
|
-
* This source code is licensed under the MIT license found in the
|
|
136
|
-
* LICENSE file in the root directory of this source tree.
|
|
137
|
-
*/
|
|
138
|
-
var require_react_jsx_runtime_production = /* @__PURE__ */ __commonJSMin(((exports) => {
|
|
139
|
-
var REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element");
|
|
140
|
-
function jsxProd(type, config, maybeKey) {
|
|
141
|
-
var key = null;
|
|
142
|
-
void 0 !== maybeKey && (key = "" + maybeKey);
|
|
143
|
-
void 0 !== config.key && (key = "" + config.key);
|
|
144
|
-
if ("key" in config) {
|
|
145
|
-
maybeKey = {};
|
|
146
|
-
for (var propName in config) "key" !== propName && (maybeKey[propName] = config[propName]);
|
|
147
|
-
} else maybeKey = config;
|
|
148
|
-
config = maybeKey.ref;
|
|
149
|
-
return {
|
|
150
|
-
$$typeof: REACT_ELEMENT_TYPE,
|
|
151
|
-
type,
|
|
152
|
-
key,
|
|
153
|
-
ref: void 0 !== config ? config : null,
|
|
154
|
-
props: maybeKey
|
|
155
|
-
};
|
|
156
|
-
}
|
|
157
|
-
exports.jsx = jsxProd;
|
|
158
|
-
exports.jsxs = jsxProd;
|
|
159
|
-
}));
|
|
160
|
-
//#endregion
|
|
161
|
-
//#region utils/createLazyComponent.tsx
|
|
162
|
-
var import_jsx_runtime = (/* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
163
|
-
module.exports = require_react_jsx_runtime_production();
|
|
164
|
-
})))();
|
|
165
|
-
var createLazyComponent = (importFn, fallback) => {
|
|
166
|
-
const load = () => importFn().then((module) => ({ default: module.default || module }));
|
|
167
|
-
const LazyComp = lazy$1(load);
|
|
168
|
-
const Component = () => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Suspense, {
|
|
169
|
-
fallback: typeof fallback === "function" ? fallback() : fallback || null,
|
|
170
|
-
children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(LazyComp, {})
|
|
171
|
-
});
|
|
172
|
-
return {
|
|
173
|
-
Component,
|
|
174
|
-
preloadElement: load
|
|
175
|
-
};
|
|
176
|
-
};
|
|
177
|
-
//#endregion
|
|
178
|
-
//#region types.ts
|
|
179
|
-
var LAZY_MARKER = Symbol("clear-router-lazy");
|
|
180
|
-
//#endregion
|
|
181
129
|
//#region utils/utils.ts
|
|
182
|
-
var isLazy = (el) => typeof el.element === "object" && el.element !== null && LAZY_MARKER in el.element;
|
|
183
|
-
var parseClientRouteItem = (el, parentPattern = "") => {
|
|
184
|
-
const pattern = `${parentPattern}/${el.path}`.replace(/\/+/g, "/");
|
|
185
|
-
const preloadElement = isLazy(el) ? createLazyComponent(el.element.importFn, el.fallback).preloadElement : void 0;
|
|
186
|
-
const resolvedElement = isLazy(el) ? createLazyComponent(el.element.importFn, el.fallback).Component : el.element;
|
|
187
|
-
return [{
|
|
188
|
-
...el,
|
|
189
|
-
pattern,
|
|
190
|
-
element: resolvedElement,
|
|
191
|
-
preloadElement
|
|
192
|
-
}, ...el.children?.flatMap((child) => parseClientRouteItem(child, pattern)) ?? []];
|
|
193
|
-
};
|
|
194
|
-
var createRouter = (clientList) => clientList.flatMap((el) => parseClientRouteItem(el));
|
|
195
130
|
var getParamsObject = (nextItem, nextPathname) => {
|
|
196
131
|
const { routeItem: stateItem, location: { pathname: statePathname } } = router.state.routeItemDataState.getState();
|
|
197
132
|
const routeItem = nextItem || stateItem;
|
|
@@ -218,7 +153,7 @@ var isMobile = () => {
|
|
|
218
153
|
return hasCoarsePointer && isSmallScreen;
|
|
219
154
|
};
|
|
220
155
|
var sleep = async (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
221
|
-
var
|
|
156
|
+
var getPartialLoaderArgs = (location) => {
|
|
222
157
|
const params = getParamsObject();
|
|
223
158
|
const { contextState } = router.state;
|
|
224
159
|
return {
|
|
@@ -229,6 +164,33 @@ var getPartialBeforeLoadArgs = (location) => {
|
|
|
229
164
|
location
|
|
230
165
|
};
|
|
231
166
|
};
|
|
167
|
+
var isVerticalScroll = (el) => !!el && el.scrollHeight > el.clientHeight;
|
|
168
|
+
var updateScrollMap = () => {
|
|
169
|
+
const { routeItemDataState, scrollMapState } = router.state;
|
|
170
|
+
const { routeItem, location: { pathname } } = routeItemDataState.getState();
|
|
171
|
+
scrollMapState.setState((prevState) => {
|
|
172
|
+
if (Array.isArray(routeItem?.scrollRestoration)) return {
|
|
173
|
+
...prevState,
|
|
174
|
+
[pathname]: routeItem.scrollRestoration.map((key) => {
|
|
175
|
+
const el = document.getElementById(key);
|
|
176
|
+
return [key, isVerticalScroll(el) ? el?.scrollTop || 0 : el?.scrollLeft || 0];
|
|
177
|
+
})
|
|
178
|
+
};
|
|
179
|
+
const scrollingElement = document.scrollingElement;
|
|
180
|
+
const top = scrollingElement?.scrollTop ?? 0;
|
|
181
|
+
const left = scrollingElement?.scrollLeft ?? 0;
|
|
182
|
+
const entries = [];
|
|
183
|
+
if (top) entries.push([WINDOW_TOP, top]);
|
|
184
|
+
if (left) entries.push([WINDOW_LEFT, left]);
|
|
185
|
+
if (!entries.length) return prevState;
|
|
186
|
+
const prevEntries = prevState[pathname];
|
|
187
|
+
if (prevEntries && JSON.stringify(prevEntries) === JSON.stringify(entries)) return prevState;
|
|
188
|
+
return {
|
|
189
|
+
...prevState,
|
|
190
|
+
[pathname]: entries
|
|
191
|
+
};
|
|
192
|
+
});
|
|
193
|
+
};
|
|
232
194
|
var findRoute = (pathname, includeAll) => {
|
|
233
195
|
if (includeAll) return routerConfig.routes.find((el) => el.path === "*" || comparePaths(el, pathname));
|
|
234
196
|
return routerConfig.routes.find((el) => comparePaths(el, pathname));
|
|
@@ -239,7 +201,7 @@ var createNavigate = (routerState, revalidateCache) => {
|
|
|
239
201
|
let navigationSeq = 0;
|
|
240
202
|
let interval = 0;
|
|
241
203
|
let abortController = null;
|
|
242
|
-
const { loaderState, loaderStateRef,
|
|
204
|
+
const { loaderState, loaderStateRef, statusState, contextState, loaderMap, routeItemDataState, isOptimisticLoading } = routerState;
|
|
243
205
|
const navigationExecutor = createCommitState(routerState);
|
|
244
206
|
const isCacheItemFresh = createIsCacheItemFresh(loaderMap);
|
|
245
207
|
const createSignal = () => {
|
|
@@ -253,7 +215,7 @@ var createNavigate = (routerState, revalidateCache) => {
|
|
|
253
215
|
setContext: contextState.setState
|
|
254
216
|
});
|
|
255
217
|
const routeResolve = (location) => {
|
|
256
|
-
loaderStateRef.set(
|
|
218
|
+
loaderStateRef.set(EMPTY_LOADER_STATE);
|
|
257
219
|
const nextItem = findRoute(location.pathname, true);
|
|
258
220
|
return {
|
|
259
221
|
nextItem,
|
|
@@ -267,7 +229,7 @@ var createNavigate = (routerState, revalidateCache) => {
|
|
|
267
229
|
try {
|
|
268
230
|
await loaderFn({
|
|
269
231
|
redirect,
|
|
270
|
-
...
|
|
232
|
+
...getPartialLoaderArgs(nextLocation)
|
|
271
233
|
});
|
|
272
234
|
loaderStateRef.set((prev) => ({
|
|
273
235
|
...prev,
|
|
@@ -284,15 +246,7 @@ var createNavigate = (routerState, revalidateCache) => {
|
|
|
284
246
|
if (routeItem?.beforeLoad) await runBeforeLoad(routeItem?.beforeLoad);
|
|
285
247
|
};
|
|
286
248
|
const prepareNavigation = (routeItem, location) => {
|
|
287
|
-
|
|
288
|
-
const scrollPosition = document.scrollingElement?.scrollTop ?? 0;
|
|
289
|
-
const prevPathname = routeItemDataState.getState().location.pathname;
|
|
290
|
-
if (!scrollPosition || prevState[prevPathname] === scrollPosition) return prevState;
|
|
291
|
-
return {
|
|
292
|
-
...prevState,
|
|
293
|
-
[prevPathname]: scrollPosition
|
|
294
|
-
};
|
|
295
|
-
});
|
|
249
|
+
updateScrollMap();
|
|
296
250
|
const path = getPath(location);
|
|
297
251
|
if (routeItem?.optimistic && loaderMap.has(path)) {
|
|
298
252
|
routeItemDataState.setState({
|
|
@@ -380,7 +334,7 @@ var createInvalidate = ({ routeItemDataState, loaderState, loaderMap }, revalida
|
|
|
380
334
|
if (routeItem?.beforeLoad && options?.withBeforeLoad) try {
|
|
381
335
|
await routeItem.beforeLoad({
|
|
382
336
|
redirect,
|
|
383
|
-
...
|
|
337
|
+
...getPartialLoaderArgs(location)
|
|
384
338
|
});
|
|
385
339
|
loaderState.setState((prev) => ({
|
|
386
340
|
...prev,
|
|
@@ -457,7 +411,7 @@ var getRetry = (routeItem) => {
|
|
|
457
411
|
};
|
|
458
412
|
};
|
|
459
413
|
var createRevalidateCache = (routerState) => {
|
|
460
|
-
const {
|
|
414
|
+
const { loaderMap, loadingPromises } = routerState;
|
|
461
415
|
const evict = () => {
|
|
462
416
|
if (loaderMap.size <= routerConfig.maxCacheSize) return;
|
|
463
417
|
const oldestKey = loaderMap.keys().next().value;
|
|
@@ -495,17 +449,9 @@ var createRevalidateCache = (routerState) => {
|
|
|
495
449
|
if (!routeItem?.loader) return;
|
|
496
450
|
const effectiveSignal = signal ?? new AbortController().signal;
|
|
497
451
|
try {
|
|
498
|
-
const context = contextState.getState();
|
|
499
|
-
const setContext = contextState.setState;
|
|
500
|
-
const params = getParamsObject(routeItem, pathname);
|
|
501
|
-
const searchParams = Object.fromEntries(new URLSearchParams(search).entries());
|
|
502
452
|
const result = await routeItem?.loader({
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
setContext,
|
|
506
|
-
searchParams,
|
|
507
|
-
signal: effectiveSignal,
|
|
508
|
-
location
|
|
453
|
+
...getPartialLoaderArgs(location),
|
|
454
|
+
signal: effectiveSignal
|
|
509
455
|
});
|
|
510
456
|
loaderMap.set(path, {
|
|
511
457
|
state: {
|
|
@@ -582,8 +528,8 @@ var createRouterInstance = () => {
|
|
|
582
528
|
to: ""
|
|
583
529
|
}),
|
|
584
530
|
isOptimisticLoading: create(false),
|
|
585
|
-
loaderState: create(
|
|
586
|
-
loaderStateRef: new Cell(
|
|
531
|
+
loaderState: create(EMPTY_LOADER_STATE),
|
|
532
|
+
loaderStateRef: new Cell(EMPTY_LOADER_STATE),
|
|
587
533
|
loaderMap: /* @__PURE__ */ new Map(),
|
|
588
534
|
loadingPromises: /* @__PURE__ */ new Map()
|
|
589
535
|
};
|
|
@@ -644,16 +590,6 @@ var createRouterInstance = () => {
|
|
|
644
590
|
} else if (JSON.stringify(arg) !== JSON.stringify(location)) await navigate(arg);
|
|
645
591
|
};
|
|
646
592
|
},
|
|
647
|
-
useRestoreScroll: () => {
|
|
648
|
-
const { pathname } = routerState.routeItemDataState.getState().location;
|
|
649
|
-
const scrollMap = routerState.scrollMapState.getState();
|
|
650
|
-
return () => {
|
|
651
|
-
if (scrollMap[pathname]) requestAnimationFrame(() => window.scrollTo({
|
|
652
|
-
top: scrollMap[pathname],
|
|
653
|
-
behavior: "smooth"
|
|
654
|
-
}));
|
|
655
|
-
};
|
|
656
|
-
},
|
|
657
593
|
useGetAction,
|
|
658
594
|
useAction: (action, options = {}) => {
|
|
659
595
|
const { currentAction, invalidate } = useGetAction(action);
|
|
@@ -741,15 +677,36 @@ var useApplyCustomAnimation = (animationDuration) => {
|
|
|
741
677
|
};
|
|
742
678
|
//#endregion
|
|
743
679
|
//#region hooks/usePreserveScroll.ts
|
|
744
|
-
var usePreserveScroll = (
|
|
745
|
-
const
|
|
746
|
-
const
|
|
680
|
+
var usePreserveScroll = (restorationBehavior) => {
|
|
681
|
+
const { routeItem, location: { pathname } } = router.state.routeItemDataState.getState();
|
|
682
|
+
const scrollMap = router.state.scrollMapState.getState();
|
|
747
683
|
useEffect(() => {
|
|
748
|
-
if (
|
|
684
|
+
if (!routeItem || routeItem.scrollRestoration === false || !scrollMap[pathname]) return;
|
|
685
|
+
const behavior = routeItem.scrollRestorationBehavior ?? restorationBehavior;
|
|
686
|
+
scrollMap[pathname].forEach(([key, scrollPosition]) => {
|
|
687
|
+
if (key === "__window_top__" || key === "__window_left__") {
|
|
688
|
+
requestAnimationFrame(() => {
|
|
689
|
+
window.scrollTo({
|
|
690
|
+
[key === "__window_top__" ? "top" : "left"]: scrollPosition,
|
|
691
|
+
behavior
|
|
692
|
+
});
|
|
693
|
+
});
|
|
694
|
+
return;
|
|
695
|
+
}
|
|
696
|
+
const element = document.getElementById(key);
|
|
697
|
+
if (!element) return;
|
|
698
|
+
const axis = isVerticalScroll(element) ? "top" : "left";
|
|
699
|
+
requestAnimationFrame(() => {
|
|
700
|
+
element.scrollTo({
|
|
701
|
+
[axis]: scrollPosition,
|
|
702
|
+
behavior
|
|
703
|
+
});
|
|
704
|
+
});
|
|
705
|
+
});
|
|
749
706
|
}, [
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
707
|
+
pathname,
|
|
708
|
+
routeItem?.scrollRestoration,
|
|
709
|
+
scrollMap
|
|
753
710
|
]);
|
|
754
711
|
};
|
|
755
712
|
//#endregion
|
|
@@ -766,7 +723,43 @@ var useSetInitialContext = (initialContext) => {
|
|
|
766
723
|
}, [initialContext, setContext]);
|
|
767
724
|
};
|
|
768
725
|
//#endregion
|
|
726
|
+
//#region ../../node_modules/react/cjs/react-jsx-runtime.production.js
|
|
727
|
+
/**
|
|
728
|
+
* @license React
|
|
729
|
+
* react-jsx-runtime.production.js
|
|
730
|
+
*
|
|
731
|
+
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
732
|
+
*
|
|
733
|
+
* This source code is licensed under the MIT license found in the
|
|
734
|
+
* LICENSE file in the root directory of this source tree.
|
|
735
|
+
*/
|
|
736
|
+
var require_react_jsx_runtime_production = /* @__PURE__ */ __commonJSMin(((exports) => {
|
|
737
|
+
var REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element");
|
|
738
|
+
function jsxProd(type, config, maybeKey) {
|
|
739
|
+
var key = null;
|
|
740
|
+
void 0 !== maybeKey && (key = "" + maybeKey);
|
|
741
|
+
void 0 !== config.key && (key = "" + config.key);
|
|
742
|
+
if ("key" in config) {
|
|
743
|
+
maybeKey = {};
|
|
744
|
+
for (var propName in config) "key" !== propName && (maybeKey[propName] = config[propName]);
|
|
745
|
+
} else maybeKey = config;
|
|
746
|
+
config = maybeKey.ref;
|
|
747
|
+
return {
|
|
748
|
+
$$typeof: REACT_ELEMENT_TYPE,
|
|
749
|
+
type,
|
|
750
|
+
key,
|
|
751
|
+
ref: void 0 !== config ? config : null,
|
|
752
|
+
props: maybeKey
|
|
753
|
+
};
|
|
754
|
+
}
|
|
755
|
+
exports.jsx = jsxProd;
|
|
756
|
+
exports.jsxs = jsxProd;
|
|
757
|
+
}));
|
|
758
|
+
//#endregion
|
|
769
759
|
//#region components/Spinner.tsx
|
|
760
|
+
var import_jsx_runtime = (/* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
761
|
+
module.exports = require_react_jsx_runtime_production();
|
|
762
|
+
})))();
|
|
770
763
|
var Spinner = () => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "cr-spinner" });
|
|
771
764
|
//#endregion
|
|
772
765
|
//#region utils/renderElement.tsx
|
|
@@ -780,7 +773,7 @@ var EmptyBoundary = ({ children }) => children;
|
|
|
780
773
|
var IS_MOBILE = isMobile();
|
|
781
774
|
var MOBILE_CACHE_SIZE = 60;
|
|
782
775
|
var DESKTOP_CACHE_SIZE = 150;
|
|
783
|
-
var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration, defaultLoaderFallback, defaultErrorElement, defaultRetry, defaultStaleTime, context: initialContext, isAnimated = false, optimisticSpinner = true,
|
|
776
|
+
var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration, defaultLoaderFallback, defaultErrorElement, defaultRetry, defaultStaleTime, context: initialContext, isAnimated = false, optimisticSpinner = true, defaultMinLoaderDuration = 0, maxCacheSize = IS_MOBILE ? MOBILE_CACHE_SIZE : DESKTOP_CACHE_SIZE, defaultPrefetch = IS_MOBILE ? "viewport" : "hover", defaultHoverPrefetchDelay = 150, defaultScrollRestorationBehavior = "auto", errorBoundary: ErrorBoundary = EmptyBoundary }) => {
|
|
784
777
|
const { useRouteItemData, useStatus, useOptimisticLoading } = router.hooks;
|
|
785
778
|
const [routeItemData] = useRouteItemData();
|
|
786
779
|
const [status] = useStatus();
|
|
@@ -797,13 +790,12 @@ var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration,
|
|
|
797
790
|
defaultAfterLoad,
|
|
798
791
|
defaultRetry,
|
|
799
792
|
defaultStaleTime,
|
|
800
|
-
defaultPreserveScroll,
|
|
801
793
|
defaultMinLoaderDuration,
|
|
802
794
|
maxCacheSize
|
|
803
795
|
});
|
|
804
796
|
useApplyCustomAnimation(animationDuration);
|
|
805
797
|
useSetInitialContext(initialContext);
|
|
806
|
-
usePreserveScroll(
|
|
798
|
+
usePreserveScroll(defaultScrollRestorationBehavior);
|
|
807
799
|
const { routeItem, location } = routeItemData;
|
|
808
800
|
const showErrorElement = !isLoading && Boolean(loaderState.loaderError || loaderState.beforeLoadError);
|
|
809
801
|
if (!showErrorElement && isLoading) return renderElement(routeItemData?.routeItem?.loaderFallback || defaultLoaderFallback);
|
|
@@ -1091,6 +1083,38 @@ var useSearchParams = () => {
|
|
|
1091
1083
|
//#region hooks/useFormContext.ts
|
|
1092
1084
|
var useFormContext = () => useContext(FormContext);
|
|
1093
1085
|
//#endregion
|
|
1086
|
+
//#region utils/createLazyComponent.tsx
|
|
1087
|
+
var createLazyComponent = (importFn, fallback) => {
|
|
1088
|
+
const load = () => importFn().then((module) => ({ default: module.default || module }));
|
|
1089
|
+
const LazyComp = lazy$1(load);
|
|
1090
|
+
const Component = () => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Suspense, {
|
|
1091
|
+
fallback: typeof fallback === "function" ? fallback() : fallback || null,
|
|
1092
|
+
children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(LazyComp, {})
|
|
1093
|
+
});
|
|
1094
|
+
return {
|
|
1095
|
+
Component,
|
|
1096
|
+
preloadElement: load
|
|
1097
|
+
};
|
|
1098
|
+
};
|
|
1099
|
+
//#endregion
|
|
1100
|
+
//#region types.ts
|
|
1101
|
+
var LAZY_MARKER = Symbol("clear-router-lazy");
|
|
1102
|
+
//#endregion
|
|
1103
|
+
//#region utils/createRouter.ts
|
|
1104
|
+
var isLazy = (el) => typeof el.element === "object" && el.element !== null && LAZY_MARKER in el.element;
|
|
1105
|
+
var parseClientRouteItem = (el, parentPattern = "") => {
|
|
1106
|
+
const pattern = `${parentPattern}/${el.path}`.replace(/\/+/g, "/");
|
|
1107
|
+
const preloadElement = isLazy(el) ? createLazyComponent(el.element.importFn, el.fallback).preloadElement : void 0;
|
|
1108
|
+
const resolvedElement = isLazy(el) ? createLazyComponent(el.element.importFn, el.fallback).Component : el.element;
|
|
1109
|
+
return [{
|
|
1110
|
+
...el,
|
|
1111
|
+
pattern,
|
|
1112
|
+
element: resolvedElement,
|
|
1113
|
+
preloadElement
|
|
1114
|
+
}, ...el.children?.flatMap((child) => parseClientRouteItem(child, pattern)) ?? []];
|
|
1115
|
+
};
|
|
1116
|
+
var createRouter = (clientList) => clientList.flatMap((el) => parseClientRouteItem(el));
|
|
1117
|
+
//#endregion
|
|
1094
1118
|
//#region utils/lazy.ts
|
|
1095
1119
|
var lazy = (importFn) => ({
|
|
1096
1120
|
[LAZY_MARKER]: true,
|
package/dist/types.d.ts
CHANGED
|
@@ -17,6 +17,7 @@ export type BeforeLoad = (arg: {
|
|
|
17
17
|
searchParams: Record<string, string>;
|
|
18
18
|
location: Location;
|
|
19
19
|
}) => Promise<unknown> | undefined | void;
|
|
20
|
+
export type ScrollRestorationBehavior = 'auto' | 'smooth' | 'instant';
|
|
20
21
|
export type ClientRouteItem = {
|
|
21
22
|
path: string;
|
|
22
23
|
element: RenderElement | LazyComponent;
|
|
@@ -37,7 +38,8 @@ export type ClientRouteItem = {
|
|
|
37
38
|
pollingInterval?: number;
|
|
38
39
|
retry?: Retry;
|
|
39
40
|
minLoaderDuration?: number;
|
|
40
|
-
|
|
41
|
+
scrollRestoration?: boolean | string[];
|
|
42
|
+
scrollRestorationBehavior?: ScrollRestorationBehavior;
|
|
41
43
|
beforeLoad?: BeforeLoad;
|
|
42
44
|
afterLoad?: (arg: {
|
|
43
45
|
context: Record<string, unknown>;
|
|
@@ -89,7 +91,6 @@ export type RouterProps = {
|
|
|
89
91
|
isAnimated?: boolean;
|
|
90
92
|
animationDuration?: number;
|
|
91
93
|
optimisticSpinner?: boolean;
|
|
92
|
-
defaultPreserveScroll?: boolean;
|
|
93
94
|
defaultRetry?: Retry;
|
|
94
95
|
defaultStaleTime?: number;
|
|
95
96
|
defaultLoaderFallback?: RenderElement;
|
|
@@ -103,6 +104,7 @@ export type RouterProps = {
|
|
|
103
104
|
}>;
|
|
104
105
|
defaultBeforeLoad?: ClientRouteItem['beforeLoad'];
|
|
105
106
|
defaultAfterLoad?: ClientRouteItem['afterLoad'];
|
|
107
|
+
defaultScrollRestorationBehavior?: ScrollRestorationBehavior;
|
|
106
108
|
context?: Record<string, unknown>;
|
|
107
109
|
};
|
|
108
110
|
export type LoaderStateItem = {
|
|
@@ -118,10 +120,11 @@ export type LoadingPromise = Promise<{
|
|
|
118
120
|
error: unknown;
|
|
119
121
|
} | undefined>;
|
|
120
122
|
export type Status = 'idle' | 'pending' | 'active';
|
|
123
|
+
export type ScrollMap = Record<string, [string, number][]>;
|
|
121
124
|
export type RouterState = {
|
|
122
125
|
routeItemDataState: Store<RouteItemData>;
|
|
123
126
|
statusState: Store<Status>;
|
|
124
|
-
scrollMapState: Store<
|
|
127
|
+
scrollMapState: Store<ScrollMap>;
|
|
125
128
|
contextState: Store<Record<string, unknown>>;
|
|
126
129
|
blockedRouteState: Store<{
|
|
127
130
|
from: string;
|
|
@@ -146,7 +149,7 @@ export type RouterType = {
|
|
|
146
149
|
to: string;
|
|
147
150
|
}>>;
|
|
148
151
|
useRouteItemData: () => ReturnType<typeof useGlobalState<RouteItemData>>;
|
|
149
|
-
useScrollMap: () => ReturnType<typeof useGlobalState<
|
|
152
|
+
useScrollMap: () => ReturnType<typeof useGlobalState<ScrollMap>>;
|
|
150
153
|
useStatus: () => ReturnType<typeof useGlobalState<Status>>;
|
|
151
154
|
useContextState: () => ReturnType<typeof useGlobalState<Record<string, unknown>>>;
|
|
152
155
|
useOptimisticLoading: () => ReturnType<typeof useGlobalState<boolean>>;
|
|
@@ -157,7 +160,6 @@ export type RouterType = {
|
|
|
157
160
|
currentAction: (arg: FormData) => Promise<unknown> | Promise<void> | void | unknown;
|
|
158
161
|
invalidate: (pathList?: string | string[], options?: InvalidateOptions) => Promise<InvalidateResult[]>;
|
|
159
162
|
};
|
|
160
|
-
useRestoreScroll: () => () => void;
|
|
161
163
|
useAction: (action: string, options?: Options) => (arg: FormData) => Promise<void>;
|
|
162
164
|
};
|
|
163
165
|
};
|
package/dist/utils/utils.d.ts
CHANGED
|
@@ -1,14 +1,15 @@
|
|
|
1
|
-
import {
|
|
2
|
-
export declare const createRouter: (clientList: ClientRouteItem[]) => RouteItem[];
|
|
1
|
+
import { Location, RouteItem } from '../types';
|
|
3
2
|
export declare const getParamsObject: (nextItem?: RouteItem, nextPathname?: string) => Record<string, string>;
|
|
4
3
|
export declare const parseWindowLocation: (location: typeof window.location) => Location;
|
|
5
4
|
export declare const comparePaths: (route: RouteItem, pathname: string) => boolean;
|
|
6
5
|
export declare const isMobile: () => boolean;
|
|
7
6
|
export declare const sleep: (ms: number) => Promise<unknown>;
|
|
8
|
-
export declare const
|
|
7
|
+
export declare const getPartialLoaderArgs: (location: Location) => {
|
|
9
8
|
params: Record<string, string>;
|
|
10
9
|
context: Record<string, unknown>;
|
|
11
10
|
setContext: (action: Record<string, unknown> | ((prevState: Record<string, unknown>) => Record<string, unknown>)) => void;
|
|
12
11
|
searchParams: Record<string, string>;
|
|
13
12
|
location: Location;
|
|
14
13
|
};
|
|
14
|
+
export declare const isVerticalScroll: (el: Element | null) => boolean;
|
|
15
|
+
export declare const updateScrollMap: () => void;
|