clear-react-router 2.0.8 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +33 -14
- package/dist/components/Link.d.ts +3 -1
- 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 +225 -174
- package/dist/runtime/invalidate.d.ts +1 -1
- package/dist/runtime/navigate.d.ts +1 -1
- package/dist/runtime/prefetch.d.ts +2 -2
- package/dist/types.d.ts +15 -10
- package/dist/utils/commitState.d.ts +1 -1
- package/dist/utils/createRouter.d.ts +2 -0
- package/dist/utils/revalidateCache.d.ts +1 -1
- package/dist/utils/utils.d.ts +10 -2
- package/package.json +5 -3
package/README.md
CHANGED
|
@@ -1,5 +1,3 @@
|
|
|
1
|
-
[](https://www.npmjs.com/package/clear-react-router)
|
|
2
|
-
|
|
3
1
|
# Clear Router
|
|
4
2
|
|
|
5
3
|
A lightweight, type-safe routing library for client side React applications with nested routes, data loading, navigation blocking, prefetching, and route actions.
|
|
@@ -45,7 +43,7 @@ It provides first-class support for:
|
|
|
45
43
|
| `routes` | `RouteItem[]` | required | Array of route configurations |
|
|
46
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 |
|
|
47
45
|
| `isAnimated` | `boolean \| undefined` | `false` | Enable smooth page fade transitions |
|
|
48
|
-
| `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) |
|
|
49
47
|
| `optimisticSpinner` | `boolean \| undefined` | `true` | Show a small spinner in the corner while optimistic route data revalidates in the background |
|
|
50
48
|
| `context` | `object` | `{}` | Initial context (user, theme, etc.) |
|
|
51
49
|
| `errorBoundary` | `ComponentType<{ children: ReactNode }>` | `undefined` | Custom error boundary component for catching render errors in route components |
|
|
@@ -54,11 +52,12 @@ It provides first-class support for:
|
|
|
54
52
|
| `defaultErrorElement` | `ReactElement \| () => ReactElement` | `optional` | Default error fallback for every route |
|
|
55
53
|
| `defaultRetry` | `number \| { count: number; delay: number }` | `optional` | Default cache revalidation retry policy for all routes |
|
|
56
54
|
| `defaultStaleTime` | `number` | `optional` | Default time in milliseconds before cached loader data is considered stale |
|
|
57
|
-
| `defaultBeforeLoad` | `({ params, context, redirect, setContext }) => Promise<unknown> \| undefined \| void` | `undefined` | Runs before every navigation. Useful for authentication, analytics, or updating shared context. |
|
|
55
|
+
| `defaultBeforeLoad` | `({ params, context, redirect, setContext, location }) => Promise<unknown> \| undefined \| void` | `undefined` | Runs before every navigation. Useful for authentication, analytics, or updating shared context. |
|
|
58
56
|
| `defaultAfterLoad` | `({ params, context, setContext }) => Promise<void>` | `undefined` | Runs after every successful navigation. Useful for analytics, page tracking, or other global side effects. |
|
|
59
57
|
| `defaultPreserveScroll` | `boolean \| undefined` | `true` | Default value for save and restore scroll position when navigating between pages |
|
|
60
58
|
| `defaultPrefetch` | `'hover' \| 'render' \| 'viewport' \| 'none'` | `'hover'` for desktop, `'viewport'` for mobile | Default prefetch strategy for all `<Link>` components |
|
|
61
|
-
| `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 |
|
|
62
61
|
|
|
63
62
|
|
|
64
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.
|
|
@@ -71,7 +70,7 @@ Normalizes route configuration. Extracts dynamic params, builds nested paths.
|
|
|
71
70
|
|----------|------|-------------|
|
|
72
71
|
| `path` | `string` | Route path, e.g., `/user/:userId` |
|
|
73
72
|
| `element` | `ReactElement \| () => ReactElement \| LazyComponent` | Component to render |
|
|
74
|
-
| `beforeLoad` | `({ params, context, redirect, setContext }) => Promise<unknown> \| undefined \| void` | Runs before every route navigation. Auth checks and redirects. Can update context via `setContext`. `redirect` is provided by the router |
|
|
73
|
+
| `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 |
|
|
75
74
|
| `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` |
|
|
76
75
|
| `afterLoad` | `({ params, context, setContext }) => Promise<void>` | Runs after a successful navigation once the route has finished loading. Analytics, side effects after data is loaded. Can update context via `setContext` |
|
|
77
76
|
| `minLoaderDuration` | `number \| undefined` | `undefined` | Minimum time the loader fallback stays visible, to avoid flickering |
|
|
@@ -80,19 +79,37 @@ Normalizes route configuration. Extracts dynamic params, builds nested paths.
|
|
|
80
79
|
| `retry` | `number \| { count: number; delay: number }` | Overrides the global cache revalidation retry policy for this route |
|
|
81
80
|
| `optimistic` | `boolean \| undefined` | Instant navigation using stale data while fresh data is loaded in the background |
|
|
82
81
|
| `errorElement` | `ReactElement \| () => ReactElement` | Error fallback for the route. Overrides the global `defaultErrorElement` set in `Router` |
|
|
83
|
-
| `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 |
|
|
84
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` |
|
|
85
84
|
| `pollingInterval` | `number \| undefined` | Polling interval (in milliseconds) for automatically revalidating data while the route is active |
|
|
86
|
-
| `
|
|
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 |
|
|
87
|
+
|
|
88
|
+
Before load arguments (see [`redirect`](#redirect) for details on programmatic redirects):
|
|
89
|
+
|
|
90
|
+
`beforeLoad` and `loader` both receive:
|
|
91
|
+
|
|
92
|
+
```ts
|
|
93
|
+
{
|
|
94
|
+
params: Record<string, string>; // Route parameters
|
|
95
|
+
context: Record<string, unknown>; // Router context
|
|
96
|
+
setContext: Dispatch<SetStateAction<Record<string, unknown>>>; // Updates the router context
|
|
97
|
+
searchParams: Record<string, string>; // URL search parameters
|
|
98
|
+
location: Location; // Route location
|
|
99
|
+
}
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
`beforeLoad` additionally receives:
|
|
103
|
+
```ts
|
|
104
|
+
{
|
|
105
|
+
redirect: (arg: Location | string) => Promise<void>; // Programmatic redirection, see [redirect](#redirect)
|
|
106
|
+
}
|
|
107
|
+
```
|
|
87
108
|
|
|
88
|
-
|
|
109
|
+
`loader` additionally receives:
|
|
89
110
|
```ts
|
|
90
111
|
{
|
|
91
|
-
|
|
92
|
-
context: Record<string, unknown>; // Router context
|
|
93
|
-
setContext: Dispatch<SetStateAction<Record<string, unknown>>>; // Updates the router context
|
|
94
|
-
searchParams: Record<string, string>; // URL search parameters
|
|
95
|
-
signal: AbortSignal; // AbortController signal
|
|
112
|
+
signal: AbortSignal; // Aborted if a newer navigation supersedes this one — pass to fetch() to cancel in-flight requests
|
|
96
113
|
}
|
|
97
114
|
```
|
|
98
115
|
|
|
@@ -103,6 +120,8 @@ Component for client-side navigation with prefetch support, active state detecti
|
|
|
103
120
|
| Prop | Type | Default | Description |
|
|
104
121
|
|------|------|---------|-------------|
|
|
105
122
|
| `to` | `string` | required | Target path |
|
|
123
|
+
| `search` | `string \| undefined` | `undefined` | Query string appended to the target path |
|
|
124
|
+
| `state` | `unknown` | `undefined` | Arbitrary value attached to the navigation entry |
|
|
106
125
|
| `as` | `(props: ElementProps<T>, state: { isActive: boolean; isPending: boolean }) => ReactElement` | renders `<a>` | Render function for using a custom element/component instead of the default <a>. Receives the props to spread onto your element (href, ref, event handlers, className, style, children) as the first argument, and `{ isActive, isPending }` as a separate second argument — kept separate so these values are never accidentally forwarded to the DOM |
|
|
107
126
|
| `exact` | `boolean` | `false` | When `false`, the link is also considered active if the current URL starts with `to` (useful for nested routes) |
|
|
108
127
|
| `prefetch` | `'hover' \| 'render' \| 'viewport' \| 'none'` | `Router` config | Override the global prefetch strategy |
|
|
@@ -6,6 +6,8 @@ type ElementState = {
|
|
|
6
6
|
};
|
|
7
7
|
type LinkProps<T extends HTMLElement = HTMLAnchorElement> = {
|
|
8
8
|
to: string;
|
|
9
|
+
search?: string;
|
|
10
|
+
state?: unknown;
|
|
9
11
|
children?: ReactNode;
|
|
10
12
|
as?: (props: ElementProps<T>, state: ElementState) => ReactElement;
|
|
11
13
|
prefetch?: RouterProps['defaultPrefetch'];
|
|
@@ -17,5 +19,5 @@ type LinkProps<T extends HTMLElement = HTMLAnchorElement> = {
|
|
|
17
19
|
style?: CSSProperties | ((arg: ElementState) => CSSProperties);
|
|
18
20
|
exact?: boolean;
|
|
19
21
|
};
|
|
20
|
-
export declare const Link: <T extends HTMLElement = HTMLAnchorElement>({ children, to, as, prefetch: linkPrefetch, hoverPrefetchDelay, className, style, beforeNavigate, exact, activeClassName, pendingClassName, }: LinkProps<T>) => ReactElement<unknown, string | import("react").JSXElementConstructor<any>>;
|
|
22
|
+
export declare const Link: <T extends HTMLElement = HTMLAnchorElement>({ children, to, search, state, as, prefetch: linkPrefetch, hoverPrefetchDelay, className, style, beforeNavigate, exact, activeClassName, pendingClassName, }: LinkProps<T>) => ReactElement<unknown, string | import("react").JSXElementConstructor<any>>;
|
|
21
23
|
export {};
|
|
@@ -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
|
@@ -30,21 +30,22 @@ var useGlobalState = ({ subscribe, getState, setState }) => {
|
|
|
30
30
|
};
|
|
31
31
|
//#endregion
|
|
32
32
|
//#region utils/commitState.ts
|
|
33
|
-
var createCommitState = ({ routeItemDataState,
|
|
33
|
+
var createCommitState = ({ routeItemDataState, statusState, isOptimisticLoading, loaderStateRef, loaderState }) => (nextLocation, routeItem) => {
|
|
34
34
|
routeItemDataState.setState({
|
|
35
35
|
routeItem,
|
|
36
36
|
location: nextLocation
|
|
37
37
|
});
|
|
38
|
-
|
|
38
|
+
statusState.setState("active");
|
|
39
39
|
isOptimisticLoading.setState(false);
|
|
40
40
|
loaderState.setState(loaderStateRef.value);
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
history.pushState(null, "", fullPath);
|
|
41
|
+
if ((nextLocation.search ? `${nextLocation.pathname}${nextLocation.search}` : nextLocation.pathname) === window.location.pathname + window.location.search) return;
|
|
42
|
+
history.pushState(null, "", `${nextLocation.pathname}${nextLocation.search}`);
|
|
44
43
|
};
|
|
45
44
|
//#endregion
|
|
46
45
|
//#region constants.ts
|
|
47
|
-
var
|
|
46
|
+
var EMPTY_LOADER_STATE = {};
|
|
47
|
+
var WINDOW_TOP = "__window_top__";
|
|
48
|
+
var WINDOW_LEFT = "__window_left__";
|
|
48
49
|
//#endregion
|
|
49
50
|
//#region \0@oxc-project+runtime@0.133.0/helpers/esm/typeof.js
|
|
50
51
|
function _typeof(o) {
|
|
@@ -96,7 +97,6 @@ var RouterConfig = class {
|
|
|
96
97
|
_defineProperty(this, "defaultAfterLoad", void 0);
|
|
97
98
|
_defineProperty(this, "defaultRetry", void 0);
|
|
98
99
|
_defineProperty(this, "defaultStaleTime", void 0);
|
|
99
|
-
_defineProperty(this, "defaultPreserveScroll", void 0);
|
|
100
100
|
_defineProperty(this, "defaultMinLoaderDuration", void 0);
|
|
101
101
|
}
|
|
102
102
|
configure(config) {
|
|
@@ -109,7 +109,9 @@ var routerConfig = new RouterConfig();
|
|
|
109
109
|
var commitNavigation = (callback) => {
|
|
110
110
|
if (!routerConfig.isAnimated) return callback();
|
|
111
111
|
try {
|
|
112
|
-
document.startViewTransition(callback);
|
|
112
|
+
const transition = document.startViewTransition(callback);
|
|
113
|
+
transition.ready.catch(() => {});
|
|
114
|
+
transition.finished.catch(() => {});
|
|
113
115
|
} catch {
|
|
114
116
|
callback();
|
|
115
117
|
}
|
|
@@ -124,73 +126,7 @@ var createIsCacheItemFresh = (loaderMap) => (path) => {
|
|
|
124
126
|
return Date.now() - item.timestamp <= resolvedStaleTime;
|
|
125
127
|
};
|
|
126
128
|
//#endregion
|
|
127
|
-
//#region ../../node_modules/react/cjs/react-jsx-runtime.production.js
|
|
128
|
-
/**
|
|
129
|
-
* @license React
|
|
130
|
-
* react-jsx-runtime.production.js
|
|
131
|
-
*
|
|
132
|
-
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
133
|
-
*
|
|
134
|
-
* This source code is licensed under the MIT license found in the
|
|
135
|
-
* LICENSE file in the root directory of this source tree.
|
|
136
|
-
*/
|
|
137
|
-
var require_react_jsx_runtime_production = /* @__PURE__ */ __commonJSMin(((exports) => {
|
|
138
|
-
var REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element");
|
|
139
|
-
function jsxProd(type, config, maybeKey) {
|
|
140
|
-
var key = null;
|
|
141
|
-
void 0 !== maybeKey && (key = "" + maybeKey);
|
|
142
|
-
void 0 !== config.key && (key = "" + config.key);
|
|
143
|
-
if ("key" in config) {
|
|
144
|
-
maybeKey = {};
|
|
145
|
-
for (var propName in config) "key" !== propName && (maybeKey[propName] = config[propName]);
|
|
146
|
-
} else maybeKey = config;
|
|
147
|
-
config = maybeKey.ref;
|
|
148
|
-
return {
|
|
149
|
-
$$typeof: REACT_ELEMENT_TYPE,
|
|
150
|
-
type,
|
|
151
|
-
key,
|
|
152
|
-
ref: void 0 !== config ? config : null,
|
|
153
|
-
props: maybeKey
|
|
154
|
-
};
|
|
155
|
-
}
|
|
156
|
-
exports.jsx = jsxProd;
|
|
157
|
-
exports.jsxs = jsxProd;
|
|
158
|
-
}));
|
|
159
|
-
//#endregion
|
|
160
|
-
//#region utils/createLazyComponent.tsx
|
|
161
|
-
var import_jsx_runtime = (/* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
162
|
-
module.exports = require_react_jsx_runtime_production();
|
|
163
|
-
})))();
|
|
164
|
-
var createLazyComponent = (importFn, fallback) => {
|
|
165
|
-
const load = () => importFn().then((module) => ({ default: module.default || module }));
|
|
166
|
-
const LazyComp = lazy$1(load);
|
|
167
|
-
const Component = () => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Suspense, {
|
|
168
|
-
fallback: typeof fallback === "function" ? fallback() : fallback || null,
|
|
169
|
-
children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(LazyComp, {})
|
|
170
|
-
});
|
|
171
|
-
return {
|
|
172
|
-
Component,
|
|
173
|
-
preloadElement: load
|
|
174
|
-
};
|
|
175
|
-
};
|
|
176
|
-
//#endregion
|
|
177
|
-
//#region types.ts
|
|
178
|
-
var LAZY_MARKER = Symbol("clear-router-lazy");
|
|
179
|
-
//#endregion
|
|
180
129
|
//#region utils/utils.ts
|
|
181
|
-
var isLazy = (el) => typeof el.element === "object" && el.element !== null && LAZY_MARKER in el.element;
|
|
182
|
-
var parseClientRouteItem = (el, parentPattern = "") => {
|
|
183
|
-
const pattern = `${parentPattern}/${el.path}`.replace(/\/+/g, "/");
|
|
184
|
-
const preloadElement = isLazy(el) ? createLazyComponent(el.element.importFn, el.fallback).preloadElement : void 0;
|
|
185
|
-
const resolvedElement = isLazy(el) ? createLazyComponent(el.element.importFn, el.fallback).Component : el.element;
|
|
186
|
-
return [{
|
|
187
|
-
...el,
|
|
188
|
-
pattern,
|
|
189
|
-
element: resolvedElement,
|
|
190
|
-
preloadElement
|
|
191
|
-
}, ...el.children?.flatMap((child) => parseClientRouteItem(child, pattern)) ?? []];
|
|
192
|
-
};
|
|
193
|
-
var createRouter = (clientList) => clientList.flatMap((el) => parseClientRouteItem(el));
|
|
194
130
|
var getParamsObject = (nextItem, nextPathname) => {
|
|
195
131
|
const { routeItem: stateItem, location: { pathname: statePathname } } = router.state.routeItemDataState.getState();
|
|
196
132
|
const routeItem = nextItem || stateItem;
|
|
@@ -217,6 +153,44 @@ var isMobile = () => {
|
|
|
217
153
|
return hasCoarsePointer && isSmallScreen;
|
|
218
154
|
};
|
|
219
155
|
var sleep = async (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
156
|
+
var getPartialLoaderArgs = (location) => {
|
|
157
|
+
const params = getParamsObject();
|
|
158
|
+
const { contextState } = router.state;
|
|
159
|
+
return {
|
|
160
|
+
params,
|
|
161
|
+
context: contextState.getState(),
|
|
162
|
+
setContext: contextState.setState,
|
|
163
|
+
searchParams: Object.fromEntries(new URLSearchParams(location.search).entries()),
|
|
164
|
+
location
|
|
165
|
+
};
|
|
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
|
+
};
|
|
220
194
|
var findRoute = (pathname, includeAll) => {
|
|
221
195
|
if (includeAll) return routerConfig.routes.find((el) => el.path === "*" || comparePaths(el, pathname));
|
|
222
196
|
return routerConfig.routes.find((el) => comparePaths(el, pathname));
|
|
@@ -227,7 +201,7 @@ var createNavigate = (routerState, revalidateCache) => {
|
|
|
227
201
|
let navigationSeq = 0;
|
|
228
202
|
let interval = 0;
|
|
229
203
|
let abortController = null;
|
|
230
|
-
const { loaderState, loaderStateRef,
|
|
204
|
+
const { loaderState, loaderStateRef, statusState, contextState, loaderMap, routeItemDataState, isOptimisticLoading } = routerState;
|
|
231
205
|
const navigationExecutor = createCommitState(routerState);
|
|
232
206
|
const isCacheItemFresh = createIsCacheItemFresh(loaderMap);
|
|
233
207
|
const createSignal = () => {
|
|
@@ -235,28 +209,27 @@ var createNavigate = (routerState, revalidateCache) => {
|
|
|
235
209
|
abortController = new AbortController();
|
|
236
210
|
return abortController.signal;
|
|
237
211
|
};
|
|
238
|
-
const getPath = (nextLocation) => `${nextLocation.pathname}${nextLocation.search
|
|
212
|
+
const getPath = (nextLocation) => `${nextLocation.pathname}${nextLocation.search}`;
|
|
239
213
|
const getContext = () => ({
|
|
240
214
|
context: contextState.getState(),
|
|
241
215
|
setContext: contextState.setState
|
|
242
216
|
});
|
|
243
217
|
const routeResolve = (location) => {
|
|
244
|
-
loaderStateRef.set(
|
|
218
|
+
loaderStateRef.set(EMPTY_LOADER_STATE);
|
|
245
219
|
const nextItem = findRoute(location.pathname, true);
|
|
246
220
|
return {
|
|
247
221
|
nextItem,
|
|
248
222
|
params: getParamsObject(nextItem, location.pathname)
|
|
249
223
|
};
|
|
250
224
|
};
|
|
251
|
-
const beforeLoad = async (routeItem,
|
|
225
|
+
const beforeLoad = async (routeItem, nextLocation) => {
|
|
252
226
|
const { defaultBeforeLoad } = routerConfig;
|
|
253
227
|
const runBeforeLoad = async (loaderFn) => {
|
|
254
228
|
const redirect = async (redirected) => await navigate(typeof redirected === "string" ? { pathname: redirected } : redirected);
|
|
255
229
|
try {
|
|
256
230
|
await loaderFn({
|
|
257
|
-
...getContext(),
|
|
258
231
|
redirect,
|
|
259
|
-
|
|
232
|
+
...getPartialLoaderArgs(nextLocation)
|
|
260
233
|
});
|
|
261
234
|
loaderStateRef.set((prev) => ({
|
|
262
235
|
...prev,
|
|
@@ -273,15 +246,7 @@ var createNavigate = (routerState, revalidateCache) => {
|
|
|
273
246
|
if (routeItem?.beforeLoad) await runBeforeLoad(routeItem?.beforeLoad);
|
|
274
247
|
};
|
|
275
248
|
const prepareNavigation = (routeItem, location) => {
|
|
276
|
-
|
|
277
|
-
const scrollPosition = document.scrollingElement?.scrollTop ?? 0;
|
|
278
|
-
const prevPathname = routeItemDataState.getState().location.pathname;
|
|
279
|
-
if (!scrollPosition || prevState[prevPathname] === scrollPosition) return prevState;
|
|
280
|
-
return {
|
|
281
|
-
...prevState,
|
|
282
|
-
[prevPathname]: scrollPosition
|
|
283
|
-
};
|
|
284
|
-
});
|
|
249
|
+
updateScrollMap();
|
|
285
250
|
const path = getPath(location);
|
|
286
251
|
if (routeItem?.optimistic && loaderMap.has(path)) {
|
|
287
252
|
routeItemDataState.setState({
|
|
@@ -291,19 +256,17 @@ var createNavigate = (routerState, revalidateCache) => {
|
|
|
291
256
|
isOptimisticLoading.setState(true);
|
|
292
257
|
const currentLoaderState = loaderMap.get(path)?.state;
|
|
293
258
|
if (currentLoaderState) loaderState.setState(currentLoaderState);
|
|
294
|
-
} else
|
|
295
|
-
routeItem
|
|
296
|
-
|
|
297
|
-
}
|
|
298
|
-
else pendingState.setState(void 0);
|
|
259
|
+
} else {
|
|
260
|
+
const pendingShouldExist = routeItem?.loader && !isCacheItemFresh(path);
|
|
261
|
+
commitNavigation(() => statusState.setState(pendingShouldExist ? "pending" : "active"));
|
|
262
|
+
}
|
|
299
263
|
};
|
|
300
264
|
const polling = (routeItem, nextLocation) => {
|
|
301
265
|
if (!routeItem?.pollingInterval) return;
|
|
302
266
|
const signal = createSignal();
|
|
303
267
|
interval = window.setInterval(() => revalidateCache({
|
|
304
268
|
routeItem,
|
|
305
|
-
|
|
306
|
-
search: nextLocation.search,
|
|
269
|
+
location: nextLocation,
|
|
307
270
|
signal
|
|
308
271
|
}), routeItem.pollingInterval);
|
|
309
272
|
};
|
|
@@ -317,8 +280,7 @@ var createNavigate = (routerState, revalidateCache) => {
|
|
|
317
280
|
const signal = createSignal();
|
|
318
281
|
const [result] = await Promise.all([revalidateCache({
|
|
319
282
|
routeItem,
|
|
320
|
-
|
|
321
|
-
search: nextLocation.search,
|
|
283
|
+
location: nextLocation,
|
|
322
284
|
signal
|
|
323
285
|
}), getLoaderDurationPromise(routeItem, nextLocation)]);
|
|
324
286
|
if (result) loaderStateRef.set((prev) => ({
|
|
@@ -339,11 +301,15 @@ var createNavigate = (routerState, revalidateCache) => {
|
|
|
339
301
|
params
|
|
340
302
|
});
|
|
341
303
|
};
|
|
342
|
-
const navigate = async (
|
|
304
|
+
const navigate = async (rawLocation) => {
|
|
305
|
+
const nextLocation = {
|
|
306
|
+
...rawLocation,
|
|
307
|
+
search: rawLocation.search ?? ""
|
|
308
|
+
};
|
|
343
309
|
navigationSeq = navigationSeq + 1;
|
|
344
310
|
const seq = navigationSeq;
|
|
345
311
|
const { nextItem, params } = routeResolve(nextLocation);
|
|
346
|
-
await beforeLoad(nextItem,
|
|
312
|
+
await beforeLoad(nextItem, nextLocation);
|
|
347
313
|
if (seq !== navigationSeq) return;
|
|
348
314
|
prepareNavigation(nextItem, nextLocation);
|
|
349
315
|
await loader(nextItem, nextLocation, seq);
|
|
@@ -356,22 +322,20 @@ var createNavigate = (routerState, revalidateCache) => {
|
|
|
356
322
|
//#endregion
|
|
357
323
|
//#region runtime/invalidate.ts
|
|
358
324
|
var redirect = Promise.resolve;
|
|
359
|
-
var createInvalidate = ({ routeItemDataState, loaderState, loaderMap
|
|
325
|
+
var createInvalidate = ({ routeItemDataState, loaderState, loaderMap }, revalidateCache) => {
|
|
360
326
|
const invalidatePath = async (routeItem, pathname, options) => {
|
|
361
327
|
const routePathname = routeItemDataState.getState().location.pathname;
|
|
362
328
|
loaderMap.delete(pathname);
|
|
363
|
-
const
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
});
|
|
374
|
-
}
|
|
329
|
+
const [path, search = ""] = pathname.split("?");
|
|
330
|
+
const location = {
|
|
331
|
+
pathname: path,
|
|
332
|
+
search
|
|
333
|
+
};
|
|
334
|
+
if (routeItem?.beforeLoad && options?.withBeforeLoad) try {
|
|
335
|
+
await routeItem.beforeLoad({
|
|
336
|
+
redirect,
|
|
337
|
+
...getPartialLoaderArgs(location)
|
|
338
|
+
});
|
|
375
339
|
loaderState.setState((prev) => ({
|
|
376
340
|
...prev,
|
|
377
341
|
beforeLoadError: null
|
|
@@ -384,7 +348,7 @@ var createInvalidate = ({ routeItemDataState, loaderState, loaderMap, contextSta
|
|
|
384
348
|
}
|
|
385
349
|
const result = await revalidateCache({
|
|
386
350
|
routeItem,
|
|
387
|
-
|
|
351
|
+
location
|
|
388
352
|
});
|
|
389
353
|
if (result && pathname === routePathname) loaderState.setState({
|
|
390
354
|
data: result.data,
|
|
@@ -397,7 +361,7 @@ var createInvalidate = ({ routeItemDataState, loaderState, loaderMap, contextSta
|
|
|
397
361
|
};
|
|
398
362
|
};
|
|
399
363
|
const invalidateItem = async (pathname, options) => {
|
|
400
|
-
const routeItem = findRoute(pathname);
|
|
364
|
+
const routeItem = findRoute(pathname.split("?")[0]);
|
|
401
365
|
if (!routeItem) return [];
|
|
402
366
|
const pathnameSet = /* @__PURE__ */ new Set();
|
|
403
367
|
for (const [key] of loaderMap) if (comparePaths(routeItem, key)) pathnameSet.add(key);
|
|
@@ -415,13 +379,15 @@ var createInvalidate = ({ routeItemDataState, loaderState, loaderMap, contextSta
|
|
|
415
379
|
};
|
|
416
380
|
//#endregion
|
|
417
381
|
//#region runtime/prefetch.ts
|
|
418
|
-
var createPrefetch = (revalidateCache) => async (
|
|
419
|
-
const item = findRoute(pathname);
|
|
382
|
+
var createPrefetch = ({ routeItemDataState }, revalidateCache) => async (location) => {
|
|
383
|
+
const item = findRoute(location.pathname);
|
|
420
384
|
if (item) {
|
|
385
|
+
const currentLocation = routeItemDataState.getState().location;
|
|
386
|
+
if (location.pathname === currentLocation.pathname && location.search === currentLocation.search) return;
|
|
421
387
|
await item.preloadElement?.();
|
|
422
388
|
await revalidateCache({
|
|
423
389
|
routeItem: item,
|
|
424
|
-
|
|
390
|
+
location
|
|
425
391
|
});
|
|
426
392
|
}
|
|
427
393
|
};
|
|
@@ -445,7 +411,7 @@ var getRetry = (routeItem) => {
|
|
|
445
411
|
};
|
|
446
412
|
};
|
|
447
413
|
var createRevalidateCache = (routerState) => {
|
|
448
|
-
const {
|
|
414
|
+
const { loaderMap, loadingPromises } = routerState;
|
|
449
415
|
const evict = () => {
|
|
450
416
|
if (loaderMap.size <= routerConfig.maxCacheSize) return;
|
|
451
417
|
const oldestKey = loaderMap.keys().next().value;
|
|
@@ -459,9 +425,10 @@ var createRevalidateCache = (routerState) => {
|
|
|
459
425
|
}
|
|
460
426
|
return item;
|
|
461
427
|
};
|
|
462
|
-
const revalidateCache = async ({ routeItem,
|
|
428
|
+
const revalidateCache = async ({ routeItem, location, signal }, retried = 0) => {
|
|
463
429
|
if (!routeItem?.loader) return;
|
|
464
430
|
const isCacheItemFresh = createIsCacheItemFresh(loaderMap);
|
|
431
|
+
const { pathname, search = "" } = location;
|
|
465
432
|
const path = `${pathname}${search}`;
|
|
466
433
|
if (loadingPromises.has(path)) {
|
|
467
434
|
moveItemToLastPosition(path);
|
|
@@ -482,15 +449,8 @@ var createRevalidateCache = (routerState) => {
|
|
|
482
449
|
if (!routeItem?.loader) return;
|
|
483
450
|
const effectiveSignal = signal ?? new AbortController().signal;
|
|
484
451
|
try {
|
|
485
|
-
const context = contextState.getState();
|
|
486
|
-
const setContext = contextState.setState;
|
|
487
|
-
const params = getParamsObject(routeItem, pathname);
|
|
488
|
-
const searchParams = Object.fromEntries(new URLSearchParams(search).entries());
|
|
489
452
|
const result = await routeItem?.loader({
|
|
490
|
-
|
|
491
|
-
context,
|
|
492
|
-
setContext,
|
|
493
|
-
searchParams,
|
|
453
|
+
...getPartialLoaderArgs(location),
|
|
494
454
|
signal: effectiveSignal
|
|
495
455
|
});
|
|
496
456
|
loaderMap.set(path, {
|
|
@@ -516,12 +476,15 @@ var createRevalidateCache = (routerState) => {
|
|
|
516
476
|
if (retry && retry.count > retried) {
|
|
517
477
|
loadingPromises.delete(path);
|
|
518
478
|
if (retry.delay) await sleep(retry.delay);
|
|
519
|
-
|
|
479
|
+
await revalidateCache({
|
|
520
480
|
routeItem,
|
|
521
|
-
|
|
522
|
-
search,
|
|
481
|
+
location,
|
|
523
482
|
signal
|
|
524
483
|
}, retried + 1);
|
|
484
|
+
return {
|
|
485
|
+
data: null,
|
|
486
|
+
error
|
|
487
|
+
};
|
|
525
488
|
} else return {
|
|
526
489
|
data: null,
|
|
527
490
|
error
|
|
@@ -557,7 +520,7 @@ var createRouterInstance = () => {
|
|
|
557
520
|
routeItem: void 0,
|
|
558
521
|
location: {}
|
|
559
522
|
}),
|
|
560
|
-
|
|
523
|
+
statusState: create("idle"),
|
|
561
524
|
scrollMapState: create({}),
|
|
562
525
|
contextState: create({}),
|
|
563
526
|
blockedRouteState: create({
|
|
@@ -565,15 +528,15 @@ var createRouterInstance = () => {
|
|
|
565
528
|
to: ""
|
|
566
529
|
}),
|
|
567
530
|
isOptimisticLoading: create(false),
|
|
568
|
-
loaderState: create(
|
|
569
|
-
loaderStateRef: new Cell(
|
|
531
|
+
loaderState: create(EMPTY_LOADER_STATE),
|
|
532
|
+
loaderStateRef: new Cell(EMPTY_LOADER_STATE),
|
|
570
533
|
loaderMap: /* @__PURE__ */ new Map(),
|
|
571
534
|
loadingPromises: /* @__PURE__ */ new Map()
|
|
572
535
|
};
|
|
573
536
|
const revalidateCache = createRevalidateCache(routerState);
|
|
574
537
|
const invalidate = createInvalidate(routerState, revalidateCache);
|
|
575
538
|
const navigate = createNavigate(routerState, revalidateCache);
|
|
576
|
-
const prefetch = createPrefetch(revalidateCache);
|
|
539
|
+
const prefetch = createPrefetch(routerState, revalidateCache);
|
|
577
540
|
const useGetAction = (actionKey) => {
|
|
578
541
|
const { routeItem } = routerState.routeItemDataState.getState();
|
|
579
542
|
const context = routerState.contextState.getState();
|
|
@@ -604,7 +567,7 @@ var createRouterInstance = () => {
|
|
|
604
567
|
useBlockedRoute: () => useGlobalState(routerState.blockedRouteState),
|
|
605
568
|
useRouteItemData: () => useGlobalState(routerState.routeItemDataState),
|
|
606
569
|
useScrollMap: () => useGlobalState(routerState.scrollMapState),
|
|
607
|
-
|
|
570
|
+
useStatus: () => useGlobalState(routerState.statusState),
|
|
608
571
|
useContextState: () => useGlobalState(routerState.contextState),
|
|
609
572
|
useOptimisticLoading: () => useGlobalState(routerState.isOptimisticLoading),
|
|
610
573
|
useLoaderState: () => useGlobalState(routerState.loaderState)[0],
|
|
@@ -627,16 +590,6 @@ var createRouterInstance = () => {
|
|
|
627
590
|
} else if (JSON.stringify(arg) !== JSON.stringify(location)) await navigate(arg);
|
|
628
591
|
};
|
|
629
592
|
},
|
|
630
|
-
useRestoreScroll: () => {
|
|
631
|
-
const { pathname } = routerState.routeItemDataState.getState().location;
|
|
632
|
-
const scrollMap = routerState.scrollMapState.getState();
|
|
633
|
-
return () => {
|
|
634
|
-
if (scrollMap[pathname]) requestAnimationFrame(() => window.scrollTo({
|
|
635
|
-
top: scrollMap[pathname],
|
|
636
|
-
behavior: "smooth"
|
|
637
|
-
}));
|
|
638
|
-
};
|
|
639
|
-
},
|
|
640
593
|
useGetAction,
|
|
641
594
|
useAction: (action, options = {}) => {
|
|
642
595
|
const { currentAction, invalidate } = useGetAction(action);
|
|
@@ -724,15 +677,36 @@ var useApplyCustomAnimation = (animationDuration) => {
|
|
|
724
677
|
};
|
|
725
678
|
//#endregion
|
|
726
679
|
//#region hooks/usePreserveScroll.ts
|
|
727
|
-
var usePreserveScroll = (
|
|
728
|
-
const
|
|
729
|
-
const
|
|
680
|
+
var usePreserveScroll = (restorationBehavior) => {
|
|
681
|
+
const { routeItem, location: { pathname } } = router.state.routeItemDataState.getState();
|
|
682
|
+
const scrollMap = router.state.scrollMapState.getState();
|
|
730
683
|
useEffect(() => {
|
|
731
|
-
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
|
+
});
|
|
732
706
|
}, [
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
707
|
+
pathname,
|
|
708
|
+
routeItem?.scrollRestoration,
|
|
709
|
+
scrollMap
|
|
736
710
|
]);
|
|
737
711
|
};
|
|
738
712
|
//#endregion
|
|
@@ -749,7 +723,43 @@ var useSetInitialContext = (initialContext) => {
|
|
|
749
723
|
}, [initialContext, setContext]);
|
|
750
724
|
};
|
|
751
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
|
|
752
759
|
//#region components/Spinner.tsx
|
|
760
|
+
var import_jsx_runtime = (/* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
761
|
+
module.exports = require_react_jsx_runtime_production();
|
|
762
|
+
})))();
|
|
753
763
|
var Spinner = () => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "cr-spinner" });
|
|
754
764
|
//#endregion
|
|
755
765
|
//#region utils/renderElement.tsx
|
|
@@ -763,13 +773,13 @@ var EmptyBoundary = ({ children }) => children;
|
|
|
763
773
|
var IS_MOBILE = isMobile();
|
|
764
774
|
var MOBILE_CACHE_SIZE = 60;
|
|
765
775
|
var DESKTOP_CACHE_SIZE = 150;
|
|
766
|
-
var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration, defaultLoaderFallback, defaultErrorElement, defaultRetry, defaultStaleTime, context: initialContext, isAnimated = false, optimisticSpinner = true,
|
|
767
|
-
const { useRouteItemData,
|
|
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 }) => {
|
|
777
|
+
const { useRouteItemData, useStatus, useOptimisticLoading } = router.hooks;
|
|
768
778
|
const [routeItemData] = useRouteItemData();
|
|
769
|
-
const [
|
|
779
|
+
const [status] = useStatus();
|
|
770
780
|
const [isOptimisticLoading] = useOptimisticLoading();
|
|
771
781
|
const loaderState = useLoaderState();
|
|
772
|
-
const isLoading =
|
|
782
|
+
const isLoading = status === "pending";
|
|
773
783
|
useNavigation();
|
|
774
784
|
useSetRouterConfig({
|
|
775
785
|
routes,
|
|
@@ -780,16 +790,15 @@ var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration,
|
|
|
780
790
|
defaultAfterLoad,
|
|
781
791
|
defaultRetry,
|
|
782
792
|
defaultStaleTime,
|
|
783
|
-
defaultPreserveScroll,
|
|
784
793
|
defaultMinLoaderDuration,
|
|
785
794
|
maxCacheSize
|
|
786
795
|
});
|
|
787
796
|
useApplyCustomAnimation(animationDuration);
|
|
788
797
|
useSetInitialContext(initialContext);
|
|
789
|
-
usePreserveScroll(
|
|
798
|
+
usePreserveScroll(defaultScrollRestorationBehavior);
|
|
790
799
|
const { routeItem, location } = routeItemData;
|
|
791
800
|
const showErrorElement = !isLoading && Boolean(loaderState.loaderError || loaderState.beforeLoadError);
|
|
792
|
-
if (!showErrorElement && isLoading) return renderElement(
|
|
801
|
+
if (!showErrorElement && isLoading) return renderElement(routeItemData?.routeItem?.loaderFallback || defaultLoaderFallback);
|
|
793
802
|
if (!routeItem) return null;
|
|
794
803
|
if (showErrorElement) return renderElement(routeItem.errorElement || defaultErrorElement);
|
|
795
804
|
return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
|
|
@@ -800,9 +809,10 @@ var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration,
|
|
|
800
809
|
//#endregion
|
|
801
810
|
//#region hooks/useIsRoutePending.ts
|
|
802
811
|
var useIsRoutePending = (routePath) => {
|
|
803
|
-
const {
|
|
804
|
-
const [
|
|
805
|
-
|
|
812
|
+
const { useStatus, useRouteItemData } = router.hooks;
|
|
813
|
+
const [routeItemData] = useRouteItemData();
|
|
814
|
+
const [status] = useStatus();
|
|
815
|
+
return status === "pending" && routeItemData?.location.pathname === routePath;
|
|
806
816
|
};
|
|
807
817
|
//#endregion
|
|
808
818
|
//#region hooks/useNavigate.ts
|
|
@@ -816,7 +826,7 @@ var useLocation = () => {
|
|
|
816
826
|
//#endregion
|
|
817
827
|
//#region components/Link.tsx
|
|
818
828
|
var defaultAs = (props) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("a", { ...props });
|
|
819
|
-
var Link = ({ children, to, as = defaultAs, prefetch: linkPrefetch, hoverPrefetchDelay, className, style, beforeNavigate, exact = false, activeClassName = "active-link", pendingClassName = "pending-link" }) => {
|
|
829
|
+
var Link = ({ children, to, search = "", state, as = defaultAs, prefetch: linkPrefetch, hoverPrefetchDelay, className, style, beforeNavigate, exact = false, activeClassName = "active-link", pendingClassName = "pending-link" }) => {
|
|
820
830
|
const isPending = useIsRoutePending(to);
|
|
821
831
|
const { pathname } = useLocation();
|
|
822
832
|
const navigate = useNavigate();
|
|
@@ -825,14 +835,23 @@ var Link = ({ children, to, as = defaultAs, prefetch: linkPrefetch, hoverPrefetc
|
|
|
825
835
|
const { defaultPrefetch: configPrefetch, defaultHoverPrefetchDelay: configPrefetchDelay } = routerConfig;
|
|
826
836
|
const prefetch = linkPrefetch || configPrefetch;
|
|
827
837
|
const prefetchDelay = hoverPrefetchDelay ?? configPrefetchDelay;
|
|
838
|
+
const location = useMemo(() => ({
|
|
839
|
+
pathname: to,
|
|
840
|
+
search,
|
|
841
|
+
state
|
|
842
|
+
}), [
|
|
843
|
+
search,
|
|
844
|
+
state,
|
|
845
|
+
to
|
|
846
|
+
]);
|
|
828
847
|
const onMouseEnter = useCallback(() => {
|
|
829
848
|
if (prefetch !== "hover" || !prefetchDelay) return;
|
|
830
849
|
if (timeout.current) clearTimeout(timeout.current);
|
|
831
|
-
timeout.current = window.setTimeout(() => router.runtime.prefetch(
|
|
850
|
+
timeout.current = window.setTimeout(() => router.runtime.prefetch(location), prefetchDelay);
|
|
832
851
|
}, [
|
|
833
852
|
prefetch,
|
|
834
853
|
prefetchDelay,
|
|
835
|
-
|
|
854
|
+
location
|
|
836
855
|
]);
|
|
837
856
|
const onMouseLeave = useCallback(() => {
|
|
838
857
|
if (prefetch !== "hover" || !prefetchDelay) return;
|
|
@@ -844,21 +863,21 @@ var Link = ({ children, to, as = defaultAs, prefetch: linkPrefetch, hoverPrefetc
|
|
|
844
863
|
useEffect(() => {
|
|
845
864
|
if (prefetch !== "render") return;
|
|
846
865
|
(async () => {
|
|
847
|
-
await router.runtime.prefetch(
|
|
866
|
+
await router.runtime.prefetch(location);
|
|
848
867
|
})();
|
|
849
|
-
}, [prefetch,
|
|
868
|
+
}, [prefetch, location]);
|
|
850
869
|
useEffect(() => {
|
|
851
870
|
if (prefetch !== "viewport") return;
|
|
852
871
|
const element = elementRef.current;
|
|
853
872
|
if (!element) return;
|
|
854
873
|
const observer = new IntersectionObserver(async ([entry]) => {
|
|
855
874
|
if (!entry.isIntersecting) return;
|
|
856
|
-
await router.runtime.prefetch(
|
|
875
|
+
await router.runtime.prefetch(location);
|
|
857
876
|
observer.disconnect();
|
|
858
877
|
});
|
|
859
878
|
observer.observe(element);
|
|
860
879
|
return () => observer.disconnect();
|
|
861
|
-
}, [prefetch,
|
|
880
|
+
}, [prefetch, location]);
|
|
862
881
|
useEffect(() => () => {
|
|
863
882
|
if (timeout.current) clearTimeout(timeout.current);
|
|
864
883
|
}, []);
|
|
@@ -880,7 +899,7 @@ var Link = ({ children, to, as = defaultAs, prefetch: linkPrefetch, hoverPrefetc
|
|
|
880
899
|
if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
|
|
881
900
|
event.preventDefault();
|
|
882
901
|
await beforeNavigate?.();
|
|
883
|
-
await navigate(
|
|
902
|
+
await navigate(location);
|
|
884
903
|
};
|
|
885
904
|
return as({
|
|
886
905
|
ref: elementRef,
|
|
@@ -988,9 +1007,9 @@ var useAction = router.hooks.useAction;
|
|
|
988
1007
|
//#endregion
|
|
989
1008
|
//#region hooks/useIsDataLoading.ts
|
|
990
1009
|
var useIsDataLoading = () => {
|
|
991
|
-
const {
|
|
992
|
-
const [
|
|
993
|
-
return
|
|
1010
|
+
const { useStatus } = router.hooks;
|
|
1011
|
+
const [status] = useStatus();
|
|
1012
|
+
return status === "pending";
|
|
994
1013
|
};
|
|
995
1014
|
//#endregion
|
|
996
1015
|
//#region hooks/useRouterContext.ts
|
|
@@ -1064,6 +1083,38 @@ var useSearchParams = () => {
|
|
|
1064
1083
|
//#region hooks/useFormContext.ts
|
|
1065
1084
|
var useFormContext = () => useContext(FormContext);
|
|
1066
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
|
|
1067
1118
|
//#region utils/lazy.ts
|
|
1068
1119
|
var lazy = (importFn) => ({
|
|
1069
1120
|
[LAZY_MARKER]: true,
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { type InvalidateOptions, InvalidateResult, RevalidateCache, RouterState } from '../types';
|
|
2
|
-
export declare const createInvalidate: ({ routeItemDataState, loaderState, loaderMap
|
|
2
|
+
export declare const createInvalidate: ({ routeItemDataState, loaderState, loaderMap }: RouterState, revalidateCache: RevalidateCache) => (pathList?: string | string[], options?: InvalidateOptions) => Promise<InvalidateResult[]>;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { Location, RevalidateCache, RouterState } from '../types';
|
|
2
|
-
export declare const createNavigate: (routerState: RouterState, revalidateCache: RevalidateCache) => (
|
|
2
|
+
export declare const createNavigate: (routerState: RouterState, revalidateCache: RevalidateCache) => (rawLocation: Location) => Promise<void>;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { RevalidateCache } from '../types';
|
|
2
|
-
export declare const createPrefetch: (revalidateCache: RevalidateCache) => (
|
|
1
|
+
import { RevalidateCache, RouterState } from '../types';
|
|
2
|
+
export declare const createPrefetch: ({ routeItemDataState }: RouterState, revalidateCache: RevalidateCache) => (location: Location) => Promise<void>;
|
package/dist/types.d.ts
CHANGED
|
@@ -14,7 +14,10 @@ export type BeforeLoad = (arg: {
|
|
|
14
14
|
redirect: (arg: Location | string) => Promise<void>;
|
|
15
15
|
params: Record<string, string>;
|
|
16
16
|
setContext: Dispatch<SetStateAction<Record<string, unknown>>>;
|
|
17
|
+
searchParams: Record<string, string>;
|
|
18
|
+
location: Location;
|
|
17
19
|
}) => Promise<unknown> | undefined | void;
|
|
20
|
+
export type ScrollRestorationBehavior = 'auto' | 'smooth' | 'instant';
|
|
18
21
|
export type ClientRouteItem = {
|
|
19
22
|
path: string;
|
|
20
23
|
element: RenderElement | LazyComponent;
|
|
@@ -24,6 +27,7 @@ export type ClientRouteItem = {
|
|
|
24
27
|
setContext: Dispatch<SetStateAction<Record<string, unknown>>>;
|
|
25
28
|
searchParams: Record<string, string>;
|
|
26
29
|
signal: AbortSignal;
|
|
30
|
+
location: Location;
|
|
27
31
|
}): Promise<unknown>;
|
|
28
32
|
loaderFallback?: RenderElement;
|
|
29
33
|
errorElement?: RenderElement;
|
|
@@ -34,7 +38,8 @@ export type ClientRouteItem = {
|
|
|
34
38
|
pollingInterval?: number;
|
|
35
39
|
retry?: Retry;
|
|
36
40
|
minLoaderDuration?: number;
|
|
37
|
-
|
|
41
|
+
scrollRestoration?: boolean | string[];
|
|
42
|
+
scrollRestorationBehavior?: ScrollRestorationBehavior;
|
|
38
43
|
beforeLoad?: BeforeLoad;
|
|
39
44
|
afterLoad?: (arg: {
|
|
40
45
|
context: Record<string, unknown>;
|
|
@@ -63,9 +68,8 @@ export type Location = {
|
|
|
63
68
|
};
|
|
64
69
|
export type BlockerState = 'blocked' | 'unblocked' | 'charged';
|
|
65
70
|
export type RevalidateCacheArgs = {
|
|
66
|
-
|
|
71
|
+
location: Location;
|
|
67
72
|
routeItem?: RouteItem;
|
|
68
|
-
search?: string;
|
|
69
73
|
signal?: AbortSignal;
|
|
70
74
|
};
|
|
71
75
|
export type LoaderState<T = unknown> = {
|
|
@@ -87,7 +91,6 @@ export type RouterProps = {
|
|
|
87
91
|
isAnimated?: boolean;
|
|
88
92
|
animationDuration?: number;
|
|
89
93
|
optimisticSpinner?: boolean;
|
|
90
|
-
defaultPreserveScroll?: boolean;
|
|
91
94
|
defaultRetry?: Retry;
|
|
92
95
|
defaultStaleTime?: number;
|
|
93
96
|
defaultLoaderFallback?: RenderElement;
|
|
@@ -101,6 +104,7 @@ export type RouterProps = {
|
|
|
101
104
|
}>;
|
|
102
105
|
defaultBeforeLoad?: ClientRouteItem['beforeLoad'];
|
|
103
106
|
defaultAfterLoad?: ClientRouteItem['afterLoad'];
|
|
107
|
+
defaultScrollRestorationBehavior?: ScrollRestorationBehavior;
|
|
104
108
|
context?: Record<string, unknown>;
|
|
105
109
|
};
|
|
106
110
|
export type LoaderStateItem = {
|
|
@@ -115,10 +119,12 @@ export type LoadingPromise = Promise<{
|
|
|
115
119
|
data: null;
|
|
116
120
|
error: unknown;
|
|
117
121
|
} | undefined>;
|
|
122
|
+
export type Status = 'idle' | 'pending' | 'active';
|
|
123
|
+
export type ScrollMap = Record<string, [string, number][]>;
|
|
118
124
|
export type RouterState = {
|
|
119
125
|
routeItemDataState: Store<RouteItemData>;
|
|
120
|
-
|
|
121
|
-
scrollMapState: Store<
|
|
126
|
+
statusState: Store<Status>;
|
|
127
|
+
scrollMapState: Store<ScrollMap>;
|
|
122
128
|
contextState: Store<Record<string, unknown>>;
|
|
123
129
|
blockedRouteState: Store<{
|
|
124
130
|
from: string;
|
|
@@ -135,7 +141,7 @@ export type RouterType = {
|
|
|
135
141
|
runtime: {
|
|
136
142
|
navigate(arg: Location): Promise<void>;
|
|
137
143
|
invalidate(pathList?: string | string[], options?: InvalidateOptions): Promise<InvalidateResult[]>;
|
|
138
|
-
prefetch(
|
|
144
|
+
prefetch(location: Location): Promise<void>;
|
|
139
145
|
};
|
|
140
146
|
hooks: {
|
|
141
147
|
useBlockedRoute: () => ReturnType<typeof useGlobalState<{
|
|
@@ -143,8 +149,8 @@ export type RouterType = {
|
|
|
143
149
|
to: string;
|
|
144
150
|
}>>;
|
|
145
151
|
useRouteItemData: () => ReturnType<typeof useGlobalState<RouteItemData>>;
|
|
146
|
-
useScrollMap: () => ReturnType<typeof useGlobalState<
|
|
147
|
-
|
|
152
|
+
useScrollMap: () => ReturnType<typeof useGlobalState<ScrollMap>>;
|
|
153
|
+
useStatus: () => ReturnType<typeof useGlobalState<Status>>;
|
|
148
154
|
useContextState: () => ReturnType<typeof useGlobalState<Record<string, unknown>>>;
|
|
149
155
|
useOptimisticLoading: () => ReturnType<typeof useGlobalState<boolean>>;
|
|
150
156
|
useLoaderState: <T>() => LoaderState<T>;
|
|
@@ -154,7 +160,6 @@ export type RouterType = {
|
|
|
154
160
|
currentAction: (arg: FormData) => Promise<unknown> | Promise<void> | void | unknown;
|
|
155
161
|
invalidate: (pathList?: string | string[], options?: InvalidateOptions) => Promise<InvalidateResult[]>;
|
|
156
162
|
};
|
|
157
|
-
useRestoreScroll: () => () => void;
|
|
158
163
|
useAction: (action: string, options?: Options) => (arg: FormData) => Promise<void>;
|
|
159
164
|
};
|
|
160
165
|
};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { Location, RouteItem, RouterState } from '../types';
|
|
2
|
-
export declare const createCommitState: ({ routeItemDataState,
|
|
2
|
+
export declare const createCommitState: ({ routeItemDataState, statusState, isOptimisticLoading, loaderStateRef, loaderState }: RouterState) => (nextLocation: Location, routeItem: RouteItem | undefined) => void;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { LoadingPromise, RevalidateCacheArgs, RouterState } from '../types';
|
|
2
|
-
export declare const createRevalidateCache: (routerState: RouterState) => ({ routeItem,
|
|
2
|
+
export declare const createRevalidateCache: (routerState: RouterState) => ({ routeItem, location, signal }: RevalidateCacheArgs, retried?: number) => LoadingPromise;
|
package/dist/utils/utils.d.ts
CHANGED
|
@@ -1,7 +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>;
|
|
7
|
+
export declare const getPartialLoaderArgs: (location: Location) => {
|
|
8
|
+
params: Record<string, string>;
|
|
9
|
+
context: Record<string, unknown>;
|
|
10
|
+
setContext: (action: Record<string, unknown> | ((prevState: Record<string, unknown>) => Record<string, unknown>)) => void;
|
|
11
|
+
searchParams: Record<string, string>;
|
|
12
|
+
location: Location;
|
|
13
|
+
};
|
|
14
|
+
export declare const isVerticalScroll: (el: Element | null) => boolean;
|
|
15
|
+
export declare const updateScrollMap: () => void;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "clear-react-router",
|
|
3
|
-
"version": "2.0
|
|
3
|
+
"version": "2.1.0",
|
|
4
4
|
"description": "A lightweight, type-safe routing library for React applications",
|
|
5
5
|
"author": "Andrew Bubnov",
|
|
6
6
|
"scripts": {
|
|
@@ -16,12 +16,14 @@
|
|
|
16
16
|
"data-loading",
|
|
17
17
|
"navigation-blocker",
|
|
18
18
|
"scroll-restoration",
|
|
19
|
-
"breadcrumbs",
|
|
20
19
|
"search-params",
|
|
21
20
|
"lazy-loading",
|
|
22
21
|
"prefetching",
|
|
23
22
|
"view-transitions",
|
|
24
|
-
"animations"
|
|
23
|
+
"animations",
|
|
24
|
+
"retry",
|
|
25
|
+
"polling",
|
|
26
|
+
"cache-invalidation"
|
|
25
27
|
],
|
|
26
28
|
"repository": {
|
|
27
29
|
"type": "git",
|