clear-react-router 2.2.4 → 2.2.5

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.
Files changed (44) hide show
  1. package/dist/components/Link.d.ts +23 -0
  2. package/dist/components/Router.d.ts +2 -0
  3. package/dist/components/Spinner.d.ts +1 -0
  4. package/dist/config/routerConfig.d.ts +18 -0
  5. package/dist/constants.d.ts +5 -0
  6. package/dist/create.d.ts +10 -0
  7. package/dist/creators/createRouter.d.ts +2 -0
  8. package/dist/creators/createRouterInstance.d.ts +2 -0
  9. package/dist/hooks/useAction.d.ts +4 -0
  10. package/dist/hooks/useApplyCustomAnimation.d.ts +1 -0
  11. package/dist/hooks/useBlocker.d.ts +13 -0
  12. package/dist/hooks/useInvalidate.d.ts +1 -0
  13. package/dist/hooks/useIsDataLoading.d.ts +1 -0
  14. package/dist/hooks/useIsRoutePending.d.ts +1 -0
  15. package/dist/hooks/useLoaderState.d.ts +1 -0
  16. package/dist/hooks/useLocation.d.ts +1 -0
  17. package/dist/hooks/useNavigate.d.ts +1 -0
  18. package/dist/hooks/useNavigation.d.ts +1 -0
  19. package/dist/hooks/useParams.d.ts +1 -0
  20. package/dist/hooks/usePreserveScroll.d.ts +2 -0
  21. package/dist/hooks/useReload.d.ts +1 -0
  22. package/dist/hooks/useRouterContext.d.ts +4 -0
  23. package/dist/hooks/useSearch.d.ts +1 -0
  24. package/dist/hooks/useSearchParams.d.ts +10 -0
  25. package/dist/hooks/useSetInitialContext.d.ts +2 -0
  26. package/dist/hooks/useSetRouterConfig.d.ts +2 -0
  27. package/dist/hooks/useSubmitAction.d.ts +17 -0
  28. package/dist/index.d.ts +16 -0
  29. package/dist/index.js +1168 -0
  30. package/dist/instance.d.ts +1 -0
  31. package/dist/runtime/invalidate.d.ts +2 -0
  32. package/dist/runtime/navigate.d.ts +2 -0
  33. package/dist/runtime/prefetch.d.ts +2 -0
  34. package/dist/runtime/revalidateCache.d.ts +2 -0
  35. package/dist/types.d.ts +180 -0
  36. package/dist/utils/commitNavigation.d.ts +1 -0
  37. package/dist/utils/commitState.d.ts +8 -0
  38. package/dist/utils/createLazyComponent.d.ts +9 -0
  39. package/dist/utils/findRoute.d.ts +2 -0
  40. package/dist/utils/isCacheItemFresh.d.ts +2 -0
  41. package/dist/utils/lazy.d.ts +5 -0
  42. package/dist/utils/renderElement.d.ts +2 -0
  43. package/dist/utils/utils.d.ts +18 -0
  44. package/package.json +1 -1
package/dist/index.js ADDED
@@ -0,0 +1,1168 @@
1
+ import { Suspense, lazy as lazy$1, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
2
+ //#region \0rolldown/runtime.js
3
+ var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
4
+ //#endregion
5
+ //#region create.ts
6
+ var create = (initialState) => {
7
+ let state = initialState;
8
+ const subscribers = /* @__PURE__ */ new Set();
9
+ const getState = () => state;
10
+ const setState = (action) => {
11
+ const prevState = state;
12
+ const nextState = typeof action === "function" ? action(state) : action;
13
+ if (!Object.is(state, nextState)) {
14
+ state = nextState;
15
+ subscribers.forEach((listener) => listener(state, prevState));
16
+ }
17
+ };
18
+ const subscribe = (listener) => {
19
+ subscribers.add(listener);
20
+ return () => subscribers.delete(listener);
21
+ };
22
+ return {
23
+ subscribe,
24
+ getState,
25
+ setState
26
+ };
27
+ };
28
+ var useGlobalState = ({ subscribe, getState, setState }) => {
29
+ return [useSyncExternalStore(subscribe, getState), setState];
30
+ };
31
+ //#endregion
32
+ //#region utils/commitState.ts
33
+ var createCommitState = ({ loaderState, routeItemDataState, blockerState }) => ({ routeItem, loaderStateValue, location }) => {
34
+ const isError = loaderStateValue.loaderError || loaderStateValue.beforeLoadError;
35
+ routeItemDataState.setState({
36
+ routeItem,
37
+ location,
38
+ status: isError ? "error" : "active"
39
+ });
40
+ loaderState.setState(loaderStateValue);
41
+ if (blockerState.getState() === "blocked") blockerState.setState("unblocked");
42
+ if ((location.search ? `${location.pathname}${location.search}` : location.pathname) === window.location.pathname + window.location.search) return;
43
+ history.pushState(null, "", `${location.pathname}${location.search}`);
44
+ };
45
+ //#endregion
46
+ //#region constants.ts
47
+ var EMPTY_LOADER_STATE = {};
48
+ var WINDOW_TOP = "__window_top__";
49
+ var WINDOW_LEFT = "__window_left__";
50
+ //#endregion
51
+ //#region \0@oxc-project+runtime@0.132.0/helpers/typeof.js
52
+ function _typeof(o) {
53
+ "@babel/helpers - typeof";
54
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
55
+ return typeof o;
56
+ } : function(o) {
57
+ return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
58
+ }, _typeof(o);
59
+ }
60
+ //#endregion
61
+ //#region \0@oxc-project+runtime@0.132.0/helpers/toPrimitive.js
62
+ function toPrimitive(t, r) {
63
+ if ("object" != _typeof(t) || !t) return t;
64
+ var e = t[Symbol.toPrimitive];
65
+ if (void 0 !== e) {
66
+ var i = e.call(t, r || "default");
67
+ if ("object" != _typeof(i)) return i;
68
+ throw new TypeError("@@toPrimitive must return a primitive value.");
69
+ }
70
+ return ("string" === r ? String : Number)(t);
71
+ }
72
+ //#endregion
73
+ //#region \0@oxc-project+runtime@0.132.0/helpers/toPropertyKey.js
74
+ function toPropertyKey(t) {
75
+ var i = toPrimitive(t, "string");
76
+ return "symbol" == _typeof(i) ? i : i + "";
77
+ }
78
+ //#endregion
79
+ //#region \0@oxc-project+runtime@0.132.0/helpers/defineProperty.js
80
+ function _defineProperty(e, r, t) {
81
+ return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
82
+ value: t,
83
+ enumerable: !0,
84
+ configurable: !0,
85
+ writable: !0
86
+ }) : e[r] = t, e;
87
+ }
88
+ //#endregion
89
+ //#region config/routerConfig.ts
90
+ var RouterConfig = class {
91
+ constructor() {
92
+ _defineProperty(this, "routes", []);
93
+ _defineProperty(this, "maxCacheSize", 0);
94
+ _defineProperty(this, "defaultPrefetch", "hover");
95
+ _defineProperty(this, "isAnimated", false);
96
+ _defineProperty(this, "revalidateOnFocus", false);
97
+ _defineProperty(this, "revalidateOnReconnect", false);
98
+ _defineProperty(this, "defaultHoverPrefetchDelay", 150);
99
+ _defineProperty(this, "defaultBeforeLoad", void 0);
100
+ _defineProperty(this, "defaultAfterLoad", void 0);
101
+ _defineProperty(this, "defaultRetry", void 0);
102
+ _defineProperty(this, "defaultStaleTime", void 0);
103
+ _defineProperty(this, "defaultMinLoaderDuration", void 0);
104
+ }
105
+ configure(config) {
106
+ Object.assign(this, config);
107
+ }
108
+ };
109
+ var routerConfig = new RouterConfig();
110
+ //#endregion
111
+ //#region utils/commitNavigation.ts
112
+ var commitNavigation = (callback, isCommited) => {
113
+ if (!routerConfig.isAnimated || isCommited) return callback();
114
+ try {
115
+ const transition = document.startViewTransition(callback);
116
+ transition.ready.catch(() => {});
117
+ transition.finished.catch(() => {});
118
+ } catch {
119
+ callback();
120
+ }
121
+ };
122
+ //#endregion
123
+ //#region utils/isCacheItemFresh.ts
124
+ var createIsCacheItemFresh = (loaderMap) => (path) => {
125
+ const item = loaderMap.get(path);
126
+ if (item === void 0) return false;
127
+ const resolvedStaleTime = item.staleTime ?? routerConfig.defaultStaleTime;
128
+ if (resolvedStaleTime === void 0) return true;
129
+ return Date.now() - item.timestamp <= resolvedStaleTime;
130
+ };
131
+ //#endregion
132
+ //#region utils/utils.ts
133
+ var getParams = (location, routeItem) => {
134
+ if (!routeItem) return {};
135
+ const pathnameSegments = location.pathname.split("/");
136
+ return routeItem.pattern.split("/").reduce((acc, segment, index) => {
137
+ if (segment.startsWith(":")) acc[segment.slice(1)] = pathnameSegments[index];
138
+ return acc;
139
+ }, {});
140
+ };
141
+ var parseWindowLocation = (location) => ({
142
+ pathname: location.pathname,
143
+ search: location.search
144
+ });
145
+ var comparePaths = (route, pathname) => {
146
+ const pattern = route.pattern.split("/").filter(Boolean);
147
+ const current = pathname.split("/").filter(Boolean);
148
+ return pattern.length === current.length ? pattern.every((segment, index) => segment.startsWith(":") || segment === current[index]) : false;
149
+ };
150
+ var isMobile = () => {
151
+ const hasCoarsePointer = window.matchMedia("(pointer: coarse)").matches;
152
+ const isSmallScreen = window.matchMedia("(max-width: 768px)").matches;
153
+ return hasCoarsePointer && isSmallScreen;
154
+ };
155
+ var sleep = async (ms) => new Promise((resolve) => setTimeout(resolve, ms));
156
+ var getPartialLoaderArgs = (contextState, location, routeItem) => {
157
+ return {
158
+ params: getParams(location, routeItem),
159
+ context: contextState.getState(),
160
+ setContext: contextState.setState,
161
+ searchParams: Object.fromEntries(new URLSearchParams(location.search).entries()),
162
+ location
163
+ };
164
+ };
165
+ var isVerticalScroll = (el) => !!el && el.scrollHeight > el.clientHeight;
166
+ var updateScrollMap = (routeItemDataState, scrollMapState) => {
167
+ const { routeItem, location: { pathname } } = routeItemDataState.getState();
168
+ scrollMapState.setState((prevState) => {
169
+ if (Array.isArray(routeItem?.scrollRestoration)) return {
170
+ ...prevState,
171
+ [pathname]: routeItem.scrollRestoration.map((key) => {
172
+ const el = document.getElementById(key);
173
+ return [key, isVerticalScroll(el) ? el?.scrollTop || 0 : el?.scrollLeft || 0];
174
+ })
175
+ };
176
+ const scrollingElement = document.scrollingElement;
177
+ const top = scrollingElement?.scrollTop ?? 0;
178
+ const left = scrollingElement?.scrollLeft ?? 0;
179
+ const entries = [];
180
+ if (top) entries.push([WINDOW_TOP, top]);
181
+ if (left) entries.push([WINDOW_LEFT, left]);
182
+ if (!entries.length) return prevState;
183
+ const prevEntries = prevState[pathname];
184
+ if (prevEntries && JSON.stringify(prevEntries) === JSON.stringify(entries)) return prevState;
185
+ return {
186
+ ...prevState,
187
+ [pathname]: entries
188
+ };
189
+ });
190
+ };
191
+ var restoreScroll = (scrollMap, pathname, behavior) => {
192
+ scrollMap[pathname].forEach(([key, scrollPosition]) => {
193
+ if (key === "__window_top__" || key === "__window_left__") {
194
+ requestAnimationFrame(() => {
195
+ window.scrollTo({
196
+ [key === "__window_top__" ? "top" : "left"]: scrollPosition,
197
+ behavior
198
+ });
199
+ });
200
+ return;
201
+ }
202
+ const element = document.getElementById(key);
203
+ if (!element) return;
204
+ const axis = isVerticalScroll(element) ? "top" : "left";
205
+ requestAnimationFrame(() => {
206
+ element.scrollTo({
207
+ [axis]: scrollPosition,
208
+ behavior
209
+ });
210
+ });
211
+ });
212
+ };
213
+ var formatSearchObject = (searchObject) => {
214
+ const params = new URLSearchParams();
215
+ Object.entries(searchObject).forEach(([key, value]) => {
216
+ if (value !== void 0 && value !== null) params.set(key, String(value));
217
+ });
218
+ const result = params.toString();
219
+ return result ? `?${result}` : "";
220
+ };
221
+ var findRoute = (pathname, includeAll) => {
222
+ if (includeAll) return routerConfig.routes.find((el) => el.path === "*" || comparePaths(el, pathname));
223
+ return routerConfig.routes.find((el) => comparePaths(el, pathname));
224
+ };
225
+ //#endregion
226
+ //#region runtime/navigate.ts
227
+ var createNavigate = (routerState, revalidateCache) => {
228
+ let navigationSeq = 0;
229
+ let interval = 0;
230
+ let abortController = null;
231
+ const { loaderState, contextState, loaderMap, routeItemDataState, scrollMapState, blockerState, blockedTargetState } = routerState;
232
+ const commitState = createCommitState(routerState);
233
+ const isCacheItemFresh = createIsCacheItemFresh(loaderMap);
234
+ const createSignal = () => {
235
+ abortController?.abort();
236
+ abortController = new AbortController();
237
+ return abortController.signal;
238
+ };
239
+ const getPath = (nextLocation) => `${nextLocation.pathname}${nextLocation.search}`;
240
+ const routeResolve = (location) => {
241
+ const nextItem = findRoute(location.pathname, true);
242
+ return {
243
+ nextItem,
244
+ params: getParams(location, nextItem)
245
+ };
246
+ };
247
+ const beforeLoad = async (routeItem, nextLocation) => {
248
+ const { defaultBeforeLoad } = routerConfig;
249
+ const runBeforeLoad = async (loaderFn) => {
250
+ const redirect = async (redirected) => {
251
+ const { location } = routeItemDataState.getState();
252
+ const prevLocation = {
253
+ pathname: location.pathname,
254
+ search: location.search
255
+ };
256
+ return await navigate(typeof redirected === "string" ? {
257
+ pathname: redirected,
258
+ prevLocation
259
+ } : {
260
+ ...redirected,
261
+ prevLocation
262
+ });
263
+ };
264
+ try {
265
+ await loaderFn({
266
+ redirect,
267
+ ...getPartialLoaderArgs(contextState, nextLocation, routeItem)
268
+ });
269
+ return null;
270
+ } catch (error) {
271
+ return error;
272
+ }
273
+ };
274
+ let error = null;
275
+ if (defaultBeforeLoad) error = await runBeforeLoad(defaultBeforeLoad);
276
+ if (routeItem?.beforeLoad && !error) error = await runBeforeLoad(routeItem?.beforeLoad);
277
+ return error;
278
+ };
279
+ const createGcTimeout = () => {
280
+ const { routeItem, location } = routeItemDataState.getState();
281
+ if (!routeItem?.gcTime) return;
282
+ const path = `${location.pathname}${location.search}`;
283
+ const currentLoaderEntry = loaderMap.get(path);
284
+ if (!currentLoaderEntry) return;
285
+ if (currentLoaderEntry.gcTimeout) window.clearTimeout(currentLoaderEntry?.gcTimeout);
286
+ const gcTimeout = window.setTimeout(() => loaderMap.delete(path), routeItem.gcTime);
287
+ loaderMap.set(path, {
288
+ ...currentLoaderEntry,
289
+ gcTimeout
290
+ });
291
+ };
292
+ const prepareNavigation = (routeItem, location, hasError) => {
293
+ updateScrollMap(routeItemDataState, scrollMapState);
294
+ createGcTimeout();
295
+ if (hasError) return;
296
+ const path = getPath(location);
297
+ if (routeItem?.optimistic && loaderMap.has(path)) {
298
+ commitNavigation(() => routeItemDataState.setState({
299
+ routeItem,
300
+ location,
301
+ status: "optimistic"
302
+ }));
303
+ const currentLoaderState = loaderMap.get(path)?.state;
304
+ if (currentLoaderState) loaderState.setState(currentLoaderState);
305
+ return;
306
+ }
307
+ if (routeItem?.loader && !isCacheItemFresh(path)) commitNavigation(() => routeItemDataState.setState({
308
+ routeItem,
309
+ location,
310
+ status: "pending"
311
+ }));
312
+ };
313
+ const polling = (routeItem, nextLocation) => {
314
+ if (!routeItem?.pollingInterval) return;
315
+ const signal = createSignal();
316
+ interval = window.setInterval(() => revalidateCache({
317
+ routeItem,
318
+ location: nextLocation,
319
+ signal
320
+ }), routeItem.pollingInterval);
321
+ };
322
+ const getLoaderDurationPromise = (routeItem, nextLocation) => {
323
+ const minLoaderDuration = routeItem?.minLoaderDuration ?? routerConfig.defaultMinLoaderDuration ?? 0;
324
+ return minLoaderDuration && !isCacheItemFresh(getPath(nextLocation)) ? sleep(minLoaderDuration) : Promise.resolve();
325
+ };
326
+ const loader = async (routeItem, nextLocation, seq) => {
327
+ if (!routeItem?.loader) return;
328
+ window.clearInterval(interval);
329
+ const signal = createSignal();
330
+ const [result] = await Promise.all([revalidateCache({
331
+ routeItem,
332
+ location: nextLocation,
333
+ signal
334
+ }), getLoaderDurationPromise(routeItem, nextLocation)]);
335
+ if (seq !== navigationSeq) return;
336
+ polling(routeItem, nextLocation);
337
+ return result;
338
+ };
339
+ const afterLoad = async (routeItem, params) => {
340
+ const { defaultAfterLoad } = routerConfig;
341
+ const searchParams = Object.fromEntries(new URLSearchParams(location.search).entries());
342
+ const args = {
343
+ context: contextState.getState(),
344
+ params,
345
+ searchParams
346
+ };
347
+ if (routeItem?.afterLoad) await routeItem.afterLoad(args);
348
+ if (defaultAfterLoad) await defaultAfterLoad(args);
349
+ };
350
+ const checkBlocked = (nextLocation) => {
351
+ if (blockerState.getState() === "charged") {
352
+ blockerState.setState("blocked");
353
+ blockedTargetState.setState(nextLocation);
354
+ return true;
355
+ }
356
+ return false;
357
+ };
358
+ const clearCurrentGcTimeout = (routeItem, location) => {
359
+ const path = `${location.pathname}${location.search}`;
360
+ if (!routeItem?.gcTime) return;
361
+ const currentLoaderEntry = loaderMap.get(path);
362
+ if (!currentLoaderEntry?.gcTimeout) return;
363
+ window.clearTimeout(currentLoaderEntry.gcTimeout);
364
+ loaderMap.set(path, {
365
+ ...currentLoaderEntry,
366
+ gcTimeout: void 0
367
+ });
368
+ };
369
+ const navigate = async (rawLocation) => {
370
+ const nextLocation = {
371
+ ...rawLocation,
372
+ search: rawLocation.search ?? ""
373
+ };
374
+ if (checkBlocked(nextLocation)) return;
375
+ navigationSeq = navigationSeq + 1;
376
+ const seq = navigationSeq;
377
+ const { nextItem, params } = routeResolve(nextLocation);
378
+ const beforeLoadError = await beforeLoad(nextItem, nextLocation);
379
+ if (seq !== navigationSeq) return;
380
+ prepareNavigation(nextItem, nextLocation, !!beforeLoadError);
381
+ const result = beforeLoadError ? {
382
+ data: null,
383
+ error: null,
384
+ beforeLoadError
385
+ } : await loader(nextItem, nextLocation, seq);
386
+ if (seq !== navigationSeq) return;
387
+ const loaderStateValue = {
388
+ data: result?.data,
389
+ loaderError: result?.error ?? null,
390
+ beforeLoadError
391
+ };
392
+ commitNavigation(() => commitState({
393
+ location: nextLocation,
394
+ routeItem: nextItem,
395
+ loaderStateValue
396
+ }));
397
+ clearCurrentGcTimeout(nextItem, nextLocation);
398
+ afterLoad(nextItem, params);
399
+ };
400
+ return navigate;
401
+ };
402
+ //#endregion
403
+ //#region runtime/invalidate.ts
404
+ var separatePathname = (text) => text.split("?")[0];
405
+ var createInvalidate = ({ routeItemDataState, loaderState, loaderMap }, revalidateCache) => {
406
+ const invalidatePath = async (routeItem, pathname, options) => {
407
+ const routePathname = routeItemDataState.getState().location.pathname;
408
+ if (!options?.staleOnly) loaderMap.delete(pathname);
409
+ const [path, search = ""] = pathname.split("?");
410
+ const result = await revalidateCache({
411
+ routeItem,
412
+ location: {
413
+ pathname: path,
414
+ search
415
+ }
416
+ });
417
+ if (result && path === routePathname) loaderState.setState({
418
+ data: result.data,
419
+ loaderError: result.error,
420
+ beforeLoadError: null
421
+ });
422
+ return {
423
+ path: pathname,
424
+ ...result
425
+ };
426
+ };
427
+ const invalidateItem = async (pathname, options) => {
428
+ const routeItem = findRoute(separatePathname(pathname));
429
+ if (!routeItem) return [];
430
+ const pathnameSet = /* @__PURE__ */ new Set();
431
+ for (const [key] of loaderMap) if (comparePaths(routeItem, separatePathname(key))) pathnameSet.add(key);
432
+ if (options?.force) pathnameSet.add(pathname);
433
+ const currentResults = await Promise.all([...pathnameSet].map((pathname) => invalidatePath(routeItem, pathname, options)));
434
+ if (!options?.withChildren || !routeItem.children?.length) return currentResults;
435
+ const [parentPath] = pathname.split("?");
436
+ const childResults = await Promise.all(routeItem.children.map((child) => invalidateItem(`${parentPath}${child.path}`, options)));
437
+ return [...currentResults, ...childResults.flat()];
438
+ };
439
+ return async (pathList, options) => {
440
+ const { pathname, search } = routeItemDataState.getState().location;
441
+ const routePathname = `${pathname}${search}`;
442
+ const pathnameList = Array.isArray(pathList) ? pathList : pathList ? [pathList] : [routePathname];
443
+ return (await Promise.all(pathnameList.map((pathname) => invalidateItem(pathname, options)))).flat();
444
+ };
445
+ };
446
+ //#endregion
447
+ //#region runtime/prefetch.ts
448
+ var createPrefetch = ({ routeItemDataState }, revalidateCache) => async (location) => {
449
+ const item = findRoute(location.pathname);
450
+ if (item) {
451
+ const currentLocation = routeItemDataState.getState().location;
452
+ if (location.pathname === currentLocation.pathname && location.search === currentLocation.search) return;
453
+ await item.preloadElement?.();
454
+ await revalidateCache({
455
+ routeItem: item,
456
+ location
457
+ });
458
+ }
459
+ };
460
+ //#endregion
461
+ //#region runtime/revalidateCache.ts
462
+ var isObjectRetry = (arg) => typeof arg === "object";
463
+ var createRetry = (arg) => {
464
+ if (arg === void 0) return null;
465
+ return {
466
+ count: isObjectRetry(arg) ? arg.count : arg,
467
+ delay: isObjectRetry(arg) ? arg.delay : 0
468
+ };
469
+ };
470
+ var getRetry = (routeItem) => {
471
+ const routeRetry = createRetry(routeItem?.retry);
472
+ const globalRetry = createRetry(routerConfig.defaultRetry);
473
+ if (!routeRetry && !globalRetry) return null;
474
+ return {
475
+ count: routeRetry ? routeRetry.count : globalRetry?.count || 0,
476
+ delay: routeRetry ? routeRetry.delay : globalRetry?.delay || 0
477
+ };
478
+ };
479
+ var createRevalidateCache = (routerState) => {
480
+ const { loaderMap, loadingPromises, contextState } = routerState;
481
+ const evict = () => {
482
+ if (loaderMap.size <= routerConfig.maxCacheSize) return;
483
+ const oldestKey = loaderMap.keys().next().value;
484
+ if (oldestKey) loaderMap.delete(oldestKey);
485
+ };
486
+ const moveItemToLastPosition = (path) => {
487
+ const item = loaderMap.get(path);
488
+ if (item) {
489
+ loaderMap.delete(path);
490
+ loaderMap.set(path, item);
491
+ }
492
+ return item;
493
+ };
494
+ const revalidateCache = async ({ routeItem, location, signal }, retried = 0) => {
495
+ if (!routeItem?.loader) return;
496
+ const isCacheItemFresh = createIsCacheItemFresh(loaderMap);
497
+ const { pathname, search = "" } = location;
498
+ const path = `${pathname}${search}`;
499
+ if (loadingPromises.has(path)) {
500
+ moveItemToLastPosition(path);
501
+ return loadingPromises.get(path);
502
+ }
503
+ if (isCacheItemFresh(path)) {
504
+ const item = moveItemToLastPosition(path);
505
+ if (!item?.state) return void 0;
506
+ return item.state.loaderError ? {
507
+ data: null,
508
+ error: item.state.loaderError
509
+ } : {
510
+ data: item.state.data,
511
+ error: null
512
+ };
513
+ }
514
+ const promise = (async () => {
515
+ if (!routeItem?.loader) return;
516
+ const effectiveSignal = signal ?? new AbortController().signal;
517
+ try {
518
+ const result = await routeItem?.loader({
519
+ ...getPartialLoaderArgs(contextState, location, routeItem),
520
+ signal: effectiveSignal
521
+ });
522
+ loaderMap.set(path, {
523
+ state: {
524
+ data: result,
525
+ beforeLoadError: null,
526
+ loaderError: null
527
+ },
528
+ timestamp: Date.now(),
529
+ staleTime: routeItem.staleTime
530
+ });
531
+ evict();
532
+ return {
533
+ data: result,
534
+ error: null
535
+ };
536
+ } catch (error) {
537
+ if (effectiveSignal.aborted) return {
538
+ data: null,
539
+ error: null
540
+ };
541
+ const retry = getRetry(routeItem);
542
+ if (retry && retry.count > retried) {
543
+ loadingPromises.delete(path);
544
+ if (retry.delay) await sleep(retry.delay);
545
+ return revalidateCache({
546
+ routeItem,
547
+ location,
548
+ signal
549
+ }, retried + 1);
550
+ } else return {
551
+ data: null,
552
+ error
553
+ };
554
+ } finally {
555
+ loadingPromises.delete(path);
556
+ }
557
+ })();
558
+ loadingPromises.set(path, promise);
559
+ return promise;
560
+ };
561
+ return revalidateCache;
562
+ };
563
+ //#endregion
564
+ //#region creators/createRouterInstance.ts
565
+ var createRouterInstance = () => {
566
+ const routerState = {
567
+ routeItemDataState: create({
568
+ routeItem: void 0,
569
+ location: {},
570
+ status: "idle"
571
+ }),
572
+ scrollMapState: create({}),
573
+ contextState: create({}),
574
+ blockerState: create("unblocked"),
575
+ loaderState: create(EMPTY_LOADER_STATE),
576
+ blockedTargetState: create(null),
577
+ loaderMap: /* @__PURE__ */ new Map(),
578
+ loadingPromises: /* @__PURE__ */ new Map()
579
+ };
580
+ const revalidateCache = createRevalidateCache(routerState);
581
+ const navigate = createNavigate(routerState, revalidateCache);
582
+ const invalidate = createInvalidate(routerState, revalidateCache);
583
+ const prefetch = createPrefetch(routerState, revalidateCache);
584
+ const getCurrentAction = (actionKey) => {
585
+ const { routeItem, location } = routerState.routeItemDataState.getState();
586
+ if (!routeItem) throw new Error("Route not found");
587
+ if (!routeItem.actions) throw new Error("Route action creator not found");
588
+ const context = routerState.contextState.getState();
589
+ const setContext = routerState.contextState.setState;
590
+ const params = getParams(location, routeItem);
591
+ const searchParams = Object.fromEntries(new URLSearchParams(location.search).entries());
592
+ const action = routeItem.actions({
593
+ context,
594
+ setContext,
595
+ params,
596
+ location,
597
+ searchParams
598
+ })[actionKey];
599
+ if (!action) throw new Error(`Action "${actionKey}" not found`);
600
+ return action;
601
+ };
602
+ return {
603
+ runtime: {
604
+ navigate,
605
+ invalidate,
606
+ prefetch
607
+ },
608
+ hooks: {
609
+ useBlockerState: () => useGlobalState(routerState.blockerState),
610
+ useRouteItemData: () => useGlobalState(routerState.routeItemDataState),
611
+ useScrollMap: () => useGlobalState(routerState.scrollMapState),
612
+ useContextState: () => useGlobalState(routerState.contextState),
613
+ useBlockedTargetState: () => useGlobalState(routerState.blockedTargetState),
614
+ useLoaderState: () => useGlobalState(routerState.loaderState)[0],
615
+ useParams: () => {
616
+ const { routeItem, location } = routerState.routeItemDataState.getState();
617
+ return getParams(location, routeItem);
618
+ },
619
+ useNavigate: () => async (arg) => {
620
+ const { location } = routerState.routeItemDataState.getState();
621
+ const prevLocation = {
622
+ pathname: location.pathname,
623
+ search: location.search
624
+ };
625
+ if (arg === -1) return history.go(arg);
626
+ if (typeof arg === "string") {
627
+ const [pathname, search = ""] = arg.split("?");
628
+ if (pathname !== location.pathname || search !== location.search) await navigate({
629
+ pathname,
630
+ search,
631
+ prevLocation
632
+ });
633
+ return;
634
+ }
635
+ const search = typeof arg.search === "object" ? formatSearchObject(arg.search) : arg.search;
636
+ await navigate({
637
+ ...arg,
638
+ search,
639
+ prevLocation
640
+ });
641
+ },
642
+ useAction: (action, options = {}) => {
643
+ const currentAction = getCurrentAction(action);
644
+ return async (input) => {
645
+ try {
646
+ const data = await currentAction(input);
647
+ await invalidate();
648
+ options.onSuccess?.(data);
649
+ return {
650
+ data,
651
+ error: null
652
+ };
653
+ } catch (error) {
654
+ options.onError?.(error);
655
+ return {
656
+ data: null,
657
+ error
658
+ };
659
+ }
660
+ };
661
+ },
662
+ useRestoreScroll: (restorationBehavior) => {
663
+ const { routeItem, location: { pathname } } = routerState.routeItemDataState.getState();
664
+ const scrollMap = routerState.scrollMapState.getState();
665
+ if (!routeItem || routeItem.scrollRestoration === false || !scrollMap[pathname]) return;
666
+ return () => restoreScroll(scrollMap, pathname, routeItem.scrollRestorationBehavior ?? restorationBehavior);
667
+ }
668
+ }
669
+ };
670
+ };
671
+ //#endregion
672
+ //#region instance.ts
673
+ var router = createRouterInstance();
674
+ //#endregion
675
+ //#region hooks/useNavigation.ts
676
+ var useNavigation = () => {
677
+ const { navigate } = router.runtime;
678
+ const { useRouteItemData, useBlockerState } = router.hooks;
679
+ const [{ location }] = useRouteItemData();
680
+ const [blockerState] = useBlockerState();
681
+ useEffect(() => {
682
+ const handler = async (event) => {
683
+ const newLocation = parseWindowLocation(event.target.location);
684
+ const prevLocation = {
685
+ pathname: location.pathname,
686
+ search: location.search
687
+ };
688
+ if (blockerState === "charged") history.pushState(null, "", location.pathname);
689
+ await navigate({
690
+ ...newLocation,
691
+ prevLocation
692
+ });
693
+ };
694
+ window.addEventListener("popstate", handler);
695
+ return () => window.removeEventListener("popstate", handler);
696
+ }, [
697
+ blockerState,
698
+ location.pathname,
699
+ location.search,
700
+ navigate
701
+ ]);
702
+ useEffect(() => {
703
+ navigate(parseWindowLocation(window.location));
704
+ }, [navigate]);
705
+ };
706
+ //#endregion
707
+ //#region hooks/useApplyCustomAnimation.ts
708
+ var useApplyCustomAnimation = (animationDuration) => {
709
+ useEffect(() => {
710
+ const style = document.createElement("style");
711
+ style.id = "spinner-style";
712
+ style.textContent = `
713
+ @keyframes cr-spin {
714
+ 0% { transform: rotate(0deg); }
715
+ 100% { transform: rotate(360deg); }
716
+ }
717
+
718
+ .cr-spinner {
719
+ position: fixed;
720
+ top: 5px;
721
+ left: 5px;
722
+ z-index: 9999;
723
+ width: 1rem;
724
+ height: 1rem;
725
+ border: 2px solid gray;
726
+ border-bottom-color: transparent;
727
+ border-radius: 50%;
728
+ animation: cr-spin 1s linear infinite;
729
+ }
730
+ `;
731
+ document.head.appendChild(style);
732
+ return () => style.remove();
733
+ }, []);
734
+ useEffect(() => {
735
+ if (!animationDuration) return;
736
+ const style = document.createElement("style");
737
+ style.id = "dynamic-view-transition-duration-style";
738
+ style.textContent = `::view-transition-group(page) { animation-duration: ${animationDuration}ms; }`;
739
+ document.head.appendChild(style);
740
+ return () => style.remove();
741
+ }, [animationDuration]);
742
+ };
743
+ //#endregion
744
+ //#region hooks/usePreserveScroll.ts
745
+ var usePreserveScroll = (restorationBehavior) => {
746
+ const { useRestoreScroll } = router.hooks;
747
+ const restoreScroll = useRestoreScroll(restorationBehavior);
748
+ useEffect(() => {
749
+ restoreScroll?.();
750
+ }, [restoreScroll]);
751
+ };
752
+ //#endregion
753
+ //#region hooks/useSetRouterConfig.ts
754
+ var useSetRouterConfig = (routerProps) => {
755
+ useLayoutEffect(() => routerConfig.configure(routerProps), [routerProps]);
756
+ };
757
+ //#endregion
758
+ //#region hooks/useSetInitialContext.ts
759
+ var useSetInitialContext = (initialContext) => {
760
+ const [, setContext] = router.hooks.useContextState();
761
+ useEffect(() => {
762
+ if (initialContext) setContext(initialContext);
763
+ }, [initialContext, setContext]);
764
+ };
765
+ //#endregion
766
+ //#region hooks/useReload.ts
767
+ var useReload = () => {
768
+ const { invalidate } = router.runtime;
769
+ useEffect(() => {
770
+ if (!routerConfig.revalidateOnFocus) return;
771
+ const handler = () => {
772
+ if (document.visibilityState === "visible") invalidate("", { staleOnly: true });
773
+ };
774
+ document.addEventListener("visibilitychange", handler);
775
+ return () => document.removeEventListener("visibilitychange", handler);
776
+ }, [invalidate]);
777
+ useEffect(() => {
778
+ if (!routerConfig.revalidateOnReconnect) return;
779
+ const handler = () => invalidate("", { staleOnly: true });
780
+ window.addEventListener("online", handler);
781
+ return () => window.removeEventListener("online", handler);
782
+ }, [invalidate]);
783
+ };
784
+ //#endregion
785
+ //#region ../../node_modules/react/cjs/react-jsx-runtime.production.js
786
+ /**
787
+ * @license React
788
+ * react-jsx-runtime.production.js
789
+ *
790
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
791
+ *
792
+ * This source code is licensed under the MIT license found in the
793
+ * LICENSE file in the root directory of this source tree.
794
+ */
795
+ var require_react_jsx_runtime_production = /* @__PURE__ */ __commonJSMin(((exports) => {
796
+ var REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element");
797
+ function jsxProd(type, config, maybeKey) {
798
+ var key = null;
799
+ void 0 !== maybeKey && (key = "" + maybeKey);
800
+ void 0 !== config.key && (key = "" + config.key);
801
+ if ("key" in config) {
802
+ maybeKey = {};
803
+ for (var propName in config) "key" !== propName && (maybeKey[propName] = config[propName]);
804
+ } else maybeKey = config;
805
+ config = maybeKey.ref;
806
+ return {
807
+ $$typeof: REACT_ELEMENT_TYPE,
808
+ type,
809
+ key,
810
+ ref: void 0 !== config ? config : null,
811
+ props: maybeKey
812
+ };
813
+ }
814
+ exports.jsx = jsxProd;
815
+ exports.jsxs = jsxProd;
816
+ }));
817
+ //#endregion
818
+ //#region components/Spinner.tsx
819
+ var import_jsx_runtime = (/* @__PURE__ */ __commonJSMin(((exports, module) => {
820
+ module.exports = require_react_jsx_runtime_production();
821
+ })))();
822
+ var Spinner = () => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "cr-spinner" });
823
+ //#endregion
824
+ //#region utils/renderElement.tsx
825
+ var renderElement = (Component) => {
826
+ if (!Component) return null;
827
+ return typeof Component === "function" ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Component, {}) : Component;
828
+ };
829
+ //#endregion
830
+ //#region components/Router.tsx
831
+ var EmptyBoundary = ({ children }) => children;
832
+ var IS_MOBILE = isMobile();
833
+ var MOBILE_CACHE_SIZE = 60;
834
+ var DESKTOP_CACHE_SIZE = 150;
835
+ var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration, defaultLoaderFallback, defaultErrorElement, defaultRetry, defaultStaleTime, context: initialContext, isAnimated = false, optimisticSpinner = true, 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 }) => {
836
+ const { useRouteItemData } = router.hooks;
837
+ const [{ routeItem, status, location }] = useRouteItemData();
838
+ const isError = status === "error";
839
+ const isLoading = status === "pending";
840
+ const isOptimistic = status === "optimistic";
841
+ useNavigation();
842
+ useSetRouterConfig({
843
+ routes,
844
+ isAnimated,
845
+ defaultPrefetch,
846
+ defaultHoverPrefetchDelay,
847
+ defaultBeforeLoad,
848
+ defaultAfterLoad,
849
+ defaultRetry,
850
+ defaultStaleTime,
851
+ defaultMinLoaderDuration,
852
+ maxCacheSize,
853
+ revalidateOnFocus,
854
+ revalidateOnReconnect
855
+ });
856
+ useApplyCustomAnimation(animationDuration);
857
+ useSetInitialContext(initialContext);
858
+ usePreserveScroll(defaultScrollRestorationBehavior);
859
+ useReload();
860
+ if (isLoading && !isError) return renderElement(routeItem?.loaderFallback || defaultLoaderFallback);
861
+ if (!routeItem) return null;
862
+ if (isError) return renderElement(routeItem.errorElement || defaultErrorElement);
863
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
864
+ style: { viewTransitionName: "page" },
865
+ children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(ErrorBoundary, { children: renderElement(routeItem.element) }, location.pathname), optimisticSpinner && isOptimistic && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Spinner, {})]
866
+ });
867
+ };
868
+ //#endregion
869
+ //#region hooks/useIsRoutePending.ts
870
+ var useIsRoutePending = (routePath) => {
871
+ const { useRouteItemData } = router.hooks;
872
+ const [routeItemData] = useRouteItemData();
873
+ return routeItemData.status === "pending" && routeItemData?.location.pathname === routePath;
874
+ };
875
+ //#endregion
876
+ //#region hooks/useNavigate.ts
877
+ var useNavigate = router.hooks.useNavigate;
878
+ //#endregion
879
+ //#region hooks/useLocation.ts
880
+ var useLocation = () => {
881
+ const [routeItemData] = router.hooks.useRouteItemData();
882
+ return routeItemData.location;
883
+ };
884
+ //#endregion
885
+ //#region components/Link.tsx
886
+ var defaultAs = (props) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("a", { ...props });
887
+ var Link = ({ children, to, search = "", state, as = defaultAs, prefetch: linkPrefetch, hoverPrefetchDelay, className, style, beforeNavigate, exact = false, activeClassName = "active-link", pendingClassName = "pending-link" }) => {
888
+ const isPending = useIsRoutePending(to);
889
+ const { pathname } = useLocation();
890
+ const navigate = useNavigate();
891
+ const timeout = useRef(0);
892
+ const elementRef = useRef(null);
893
+ const { defaultPrefetch: configPrefetch, defaultHoverPrefetchDelay: configPrefetchDelay } = routerConfig;
894
+ const prefetch = linkPrefetch || configPrefetch;
895
+ const prefetchDelay = hoverPrefetchDelay ?? configPrefetchDelay;
896
+ const searchString = typeof search === "object" ? formatSearchObject(search) : search;
897
+ const location = useMemo(() => ({
898
+ pathname: to,
899
+ search: searchString,
900
+ state
901
+ }), [
902
+ searchString,
903
+ state,
904
+ to
905
+ ]);
906
+ const onMouseEnter = useCallback(() => {
907
+ if (prefetch !== "hover" || !prefetchDelay) return;
908
+ if (timeout.current) clearTimeout(timeout.current);
909
+ timeout.current = window.setTimeout(() => router.runtime.prefetch(location), prefetchDelay);
910
+ }, [
911
+ prefetch,
912
+ prefetchDelay,
913
+ location
914
+ ]);
915
+ const onMouseLeave = useCallback(() => {
916
+ if (prefetch !== "hover" || !prefetchDelay) return;
917
+ if (timeout.current) {
918
+ clearTimeout(timeout.current);
919
+ timeout.current = 0;
920
+ }
921
+ }, [prefetch, prefetchDelay]);
922
+ useEffect(() => {
923
+ if (prefetch !== "render") return;
924
+ (async () => {
925
+ await router.runtime.prefetch(location);
926
+ })();
927
+ }, [prefetch, location]);
928
+ useEffect(() => {
929
+ if (prefetch !== "viewport") return;
930
+ const element = elementRef.current;
931
+ if (!element) return;
932
+ const observer = new IntersectionObserver(async ([entry]) => {
933
+ if (!entry.isIntersecting) return;
934
+ await router.runtime.prefetch(location);
935
+ observer.disconnect();
936
+ });
937
+ observer.observe(element);
938
+ return () => observer.disconnect();
939
+ }, [prefetch, location]);
940
+ useEffect(() => () => {
941
+ if (timeout.current) clearTimeout(timeout.current);
942
+ }, []);
943
+ const isActive = to === "/" ? pathname === "/" : exact ? pathname === to : pathname === to || pathname?.startsWith(`${to}/`);
944
+ const normalizedClassName = typeof className === "function" ? className({
945
+ isActive,
946
+ isPending
947
+ }) : className;
948
+ const normalizedStyle = typeof style === "function" ? style({
949
+ isActive,
950
+ isPending
951
+ }) : style;
952
+ const resultClassName = [
953
+ isActive && activeClassName,
954
+ isPending && pendingClassName,
955
+ normalizedClassName
956
+ ].filter(Boolean).join(" ");
957
+ const clickHandler = async (event) => {
958
+ if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
959
+ event.preventDefault();
960
+ await beforeNavigate?.();
961
+ await navigate(location);
962
+ };
963
+ return as({
964
+ ref: elementRef,
965
+ style: normalizedStyle,
966
+ className: resultClassName,
967
+ onClick: clickHandler,
968
+ href: `${to}${searchString}`,
969
+ onMouseEnter,
970
+ onMouseLeave,
971
+ children
972
+ }, {
973
+ isActive,
974
+ isPending
975
+ });
976
+ };
977
+ //#endregion
978
+ //#region hooks/useParams.ts
979
+ var useParams = router.hooks.useParams;
980
+ //#endregion
981
+ //#region hooks/useLoaderState.ts
982
+ var useLoaderState = router.hooks.useLoaderState;
983
+ //#endregion
984
+ //#region hooks/useInvalidate.ts
985
+ var useInvalidate = () => router.runtime.invalidate;
986
+ //#endregion
987
+ //#region hooks/useBlocker.ts
988
+ var useBlocker = (blockerFn) => {
989
+ const { hooks: { useBlockerState, useContextState, useBlockedTargetState }, runtime: { navigate } } = router;
990
+ const [blockerState, setBlockerState] = useBlockerState();
991
+ const [nextLocation, setNextLocation] = useBlockedTargetState();
992
+ const [context] = useContextState();
993
+ const location = useLocation();
994
+ const shouldBlock = blockerFn(useMemo(() => ({
995
+ location,
996
+ nextLocation,
997
+ context
998
+ }), [
999
+ context,
1000
+ location,
1001
+ nextLocation
1002
+ ]));
1003
+ useEffect(() => setBlockerState(shouldBlock ? "charged" : "unblocked"), [setBlockerState, shouldBlock]);
1004
+ return {
1005
+ state: blockerState,
1006
+ process: useCallback(async () => {
1007
+ if (nextLocation) await navigate(nextLocation);
1008
+ setNextLocation(null);
1009
+ }, [
1010
+ navigate,
1011
+ nextLocation,
1012
+ setNextLocation
1013
+ ]),
1014
+ reset: useCallback(() => {
1015
+ setBlockerState("charged");
1016
+ setNextLocation(null);
1017
+ }, [setBlockerState, setNextLocation])
1018
+ };
1019
+ };
1020
+ //#endregion
1021
+ //#region hooks/useAction.ts
1022
+ var useAction = router.hooks.useAction;
1023
+ //#endregion
1024
+ //#region hooks/useIsDataLoading.ts
1025
+ var useIsDataLoading = () => {
1026
+ const { useRouteItemData } = router.hooks;
1027
+ const [routeData] = useRouteItemData();
1028
+ return routeData.status === "pending";
1029
+ };
1030
+ //#endregion
1031
+ //#region hooks/useRouterContext.ts
1032
+ var useRouterContext = () => {
1033
+ const [context, setContext] = router.hooks.useContextState();
1034
+ return {
1035
+ context,
1036
+ setContext
1037
+ };
1038
+ };
1039
+ //#endregion
1040
+ //#region hooks/useSearch.ts
1041
+ var isPatched = false;
1042
+ var notify = () => {
1043
+ window.dispatchEvent(new Event("locationChange"));
1044
+ };
1045
+ var patchHistory = () => {
1046
+ if (isPatched) return;
1047
+ isPatched = true;
1048
+ const push = history.pushState;
1049
+ const replace = history.replaceState;
1050
+ history.pushState = function(...args) {
1051
+ const result = push.apply(this, args);
1052
+ notify();
1053
+ return result;
1054
+ };
1055
+ history.replaceState = function(...args) {
1056
+ const result = replace.apply(this, args);
1057
+ notify();
1058
+ return result;
1059
+ };
1060
+ window.addEventListener("popstate", notify);
1061
+ };
1062
+ var subscribe = (onChange) => {
1063
+ window.addEventListener("locationChange", onChange);
1064
+ return () => window.removeEventListener("locationChange", onChange);
1065
+ };
1066
+ var getSnapshot = () => window.location.search;
1067
+ var useSearch = () => {
1068
+ useEffect(patchHistory, []);
1069
+ return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
1070
+ };
1071
+ //#endregion
1072
+ //#region hooks/useSearchParams.ts
1073
+ var useSearchParams = () => {
1074
+ const search = useSearch();
1075
+ const searchString = search ? search.replace("?", "") : window.location.pathname.split("?")?.[1] ?? "";
1076
+ const searchParams = useMemo(() => new URLSearchParams(searchString), [searchString]);
1077
+ const getSearchParams = useCallback((param) => {
1078
+ const allValues = searchParams.getAll(param);
1079
+ return allValues.length > 1 ? allValues : allValues[0] ?? "";
1080
+ }, [searchParams]);
1081
+ const navigateWithSearchParams = useCallback((params) => {
1082
+ const newSearch = params.toString();
1083
+ const { pathname } = window.location;
1084
+ const search = newSearch ? `?${newSearch}` : "";
1085
+ history.replaceState(null, "", pathname + search);
1086
+ }, []);
1087
+ return {
1088
+ searchParams,
1089
+ getSearchParams,
1090
+ setSearchParams: useCallback((param, value) => {
1091
+ const currentParams = new URLSearchParams(search);
1092
+ if (typeof param === "string" && value !== void 0) {
1093
+ currentParams.delete(param);
1094
+ (Array.isArray(value) ? value : [value]).forEach((v) => currentParams.append(param, v));
1095
+ navigateWithSearchParams(currentParams);
1096
+ } else if (typeof param === "function") navigateWithSearchParams(param(currentParams));
1097
+ else throw new Error("useSearchParams first argument must be either function or string");
1098
+ }, [navigateWithSearchParams, search])
1099
+ };
1100
+ };
1101
+ //#endregion
1102
+ //#region hooks/useSubmitAction.ts
1103
+ var useSubmitAction = (action, options) => {
1104
+ const currentAction = router.hooks.useAction(action, options);
1105
+ const [data, setData] = useState();
1106
+ const [error, setError] = useState(null);
1107
+ const [isSubmitting, setIsSubmitting] = useState(false);
1108
+ const submit = useCallback(async (data) => {
1109
+ setIsSubmitting(true);
1110
+ const result = await currentAction(data);
1111
+ setIsSubmitting(false);
1112
+ setData(result.data);
1113
+ setError(result.error);
1114
+ return result;
1115
+ }, [currentAction]);
1116
+ return {
1117
+ submit,
1118
+ onSubmit: useCallback(async (evt) => {
1119
+ evt.preventDefault();
1120
+ const target = evt.target;
1121
+ const { error } = await submit(Object.fromEntries(new FormData(target)));
1122
+ if (!(options?.autoReset === false) && !error) target.reset();
1123
+ }, [options?.autoReset, submit]),
1124
+ data,
1125
+ error,
1126
+ isSubmitting
1127
+ };
1128
+ };
1129
+ //#endregion
1130
+ //#region utils/createLazyComponent.tsx
1131
+ var createLazyComponent = (importFn, fallback) => {
1132
+ const load = () => importFn().then((module) => ({ default: module.default || module }));
1133
+ const LazyComp = lazy$1(load);
1134
+ const Component = () => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Suspense, {
1135
+ fallback: typeof fallback === "function" ? fallback() : fallback || null,
1136
+ children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(LazyComp, {})
1137
+ });
1138
+ return {
1139
+ Component,
1140
+ preloadElement: load
1141
+ };
1142
+ };
1143
+ //#endregion
1144
+ //#region types.ts
1145
+ var LAZY_MARKER = Symbol("clear-router-lazy");
1146
+ //#endregion
1147
+ //#region creators/createRouter.ts
1148
+ var isLazy = (el) => typeof el.element === "object" && el.element !== null && LAZY_MARKER in el.element;
1149
+ var parseClientRouteItem = (el, parentPattern = "") => {
1150
+ const pattern = `${parentPattern}/${el.path}`.replace(/\/+/g, "/");
1151
+ const preloadElement = isLazy(el) ? createLazyComponent(el.element.importFn, el.fallback).preloadElement : void 0;
1152
+ const resolvedElement = isLazy(el) ? createLazyComponent(el.element.importFn, el.fallback).Component : el.element;
1153
+ return [{
1154
+ ...el,
1155
+ pattern,
1156
+ element: resolvedElement,
1157
+ preloadElement
1158
+ }, ...el.children?.flatMap((child) => parseClientRouteItem(child, pattern)) ?? []];
1159
+ };
1160
+ var createRouter = (clientList) => clientList.flatMap((el) => parseClientRouteItem(el));
1161
+ //#endregion
1162
+ //#region utils/lazy.ts
1163
+ var lazy = (importFn) => ({
1164
+ [LAZY_MARKER]: true,
1165
+ importFn
1166
+ });
1167
+ //#endregion
1168
+ export { Link, Router, createRouter, lazy, useAction, useBlocker, useInvalidate, useIsDataLoading, useLoaderState, useLocation, useNavigate, useParams, useRouterContext, useSearchParams, useSubmitAction };