@weaverse/react 5.5.0-beta.0 → 5.5.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -9,2108 +9,7 @@ var WeaverseItemContext = createContext({ id: "", parentId: "" });
9
9
 
10
10
  // src/hooks.ts
11
11
  import { Weaverse } from "@weaverse/core";
12
- import { useContext as useContext6 } from "react";
13
-
14
- // ../../node_modules/react-router/dist/development/chunk-B7RQU5TL.mjs
15
- import * as React from "react";
16
- import * as React2 from "react";
17
- import * as React3 from "react";
18
- import * as React4 from "react";
19
- import * as React9 from "react";
20
- import * as React8 from "react";
21
- import * as React7 from "react";
22
- import * as React6 from "react";
23
- import * as React5 from "react";
24
- import * as React10 from "react";
25
- import * as React11 from "react";
26
- function invariant(value, message) {
27
- if (value === false || value === null || typeof value === "undefined") {
28
- throw new Error(message);
29
- }
30
- }
31
- function warning(cond, message) {
32
- if (!cond) {
33
- if (typeof console !== "undefined") console.warn(message);
34
- try {
35
- throw new Error(message);
36
- } catch (e) {
37
- }
38
- }
39
- }
40
- function createPath({
41
- pathname = "/",
42
- search = "",
43
- hash = ""
44
- }) {
45
- if (search && search !== "?")
46
- pathname += search.charAt(0) === "?" ? search : "?" + search;
47
- if (hash && hash !== "#")
48
- pathname += hash.charAt(0) === "#" ? hash : "#" + hash;
49
- return pathname;
50
- }
51
- function parsePath(path) {
52
- let parsedPath = {};
53
- if (path) {
54
- let hashIndex = path.indexOf("#");
55
- if (hashIndex >= 0) {
56
- parsedPath.hash = path.substring(hashIndex);
57
- path = path.substring(0, hashIndex);
58
- }
59
- let searchIndex = path.indexOf("?");
60
- if (searchIndex >= 0) {
61
- parsedPath.search = path.substring(searchIndex);
62
- path = path.substring(0, searchIndex);
63
- }
64
- if (path) {
65
- parsedPath.pathname = path;
66
- }
67
- }
68
- return parsedPath;
69
- }
70
- var _map;
71
- _map = /* @__PURE__ */ new WeakMap();
72
- function matchRoutes(routes, locationArg, basename = "/") {
73
- return matchRoutesImpl(routes, locationArg, basename, false);
74
- }
75
- function matchRoutesImpl(routes, locationArg, basename, allowPartial) {
76
- let location = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
77
- let pathname = stripBasename(location.pathname || "/", basename);
78
- if (pathname == null) {
79
- return null;
80
- }
81
- let branches = flattenRoutes(routes);
82
- rankRouteBranches(branches);
83
- let matches = null;
84
- for (let i = 0; matches == null && i < branches.length; ++i) {
85
- let decoded = decodePath(pathname);
86
- matches = matchRouteBranch(
87
- branches[i],
88
- decoded,
89
- allowPartial
90
- );
91
- }
92
- return matches;
93
- }
94
- function convertRouteMatchToUiMatch(match, loaderData) {
95
- let { route, pathname, params } = match;
96
- return {
97
- id: route.id,
98
- pathname,
99
- params,
100
- data: loaderData[route.id],
101
- loaderData: loaderData[route.id],
102
- handle: route.handle
103
- };
104
- }
105
- function flattenRoutes(routes, branches = [], parentsMeta = [], parentPath = "", _hasParentOptionalSegments = false) {
106
- let flattenRoute = (route, index, hasParentOptionalSegments = _hasParentOptionalSegments, relativePath) => {
107
- let meta = {
108
- relativePath: relativePath === void 0 ? route.path || "" : relativePath,
109
- caseSensitive: route.caseSensitive === true,
110
- childrenIndex: index,
111
- route
112
- };
113
- if (meta.relativePath.startsWith("/")) {
114
- if (!meta.relativePath.startsWith(parentPath) && hasParentOptionalSegments) {
115
- return;
116
- }
117
- invariant(
118
- meta.relativePath.startsWith(parentPath),
119
- `Absolute route path "${meta.relativePath}" nested under path "${parentPath}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`
120
- );
121
- meta.relativePath = meta.relativePath.slice(parentPath.length);
122
- }
123
- let path = joinPaths([parentPath, meta.relativePath]);
124
- let routesMeta = parentsMeta.concat(meta);
125
- if (route.children && route.children.length > 0) {
126
- invariant(
127
- // Our types know better, but runtime JS may not!
128
- // @ts-expect-error
129
- route.index !== true,
130
- `Index routes must not have child routes. Please remove all child routes from route path "${path}".`
131
- );
132
- flattenRoutes(
133
- route.children,
134
- branches,
135
- routesMeta,
136
- path,
137
- hasParentOptionalSegments
138
- );
139
- }
140
- if (route.path == null && !route.index) {
141
- return;
142
- }
143
- branches.push({
144
- path,
145
- score: computeScore(path, route.index),
146
- routesMeta
147
- });
148
- };
149
- routes.forEach((route, index) => {
150
- if (route.path === "" || !route.path?.includes("?")) {
151
- flattenRoute(route, index);
152
- } else {
153
- for (let exploded of explodeOptionalSegments(route.path)) {
154
- flattenRoute(route, index, true, exploded);
155
- }
156
- }
157
- });
158
- return branches;
159
- }
160
- function explodeOptionalSegments(path) {
161
- let segments = path.split("/");
162
- if (segments.length === 0) return [];
163
- let [first, ...rest] = segments;
164
- let isOptional = first.endsWith("?");
165
- let required = first.replace(/\?$/, "");
166
- if (rest.length === 0) {
167
- return isOptional ? [required, ""] : [required];
168
- }
169
- let restExploded = explodeOptionalSegments(rest.join("/"));
170
- let result = [];
171
- result.push(
172
- ...restExploded.map(
173
- (subpath) => subpath === "" ? required : [required, subpath].join("/")
174
- )
175
- );
176
- if (isOptional) {
177
- result.push(...restExploded);
178
- }
179
- return result.map(
180
- (exploded) => path.startsWith("/") && exploded === "" ? "/" : exploded
181
- );
182
- }
183
- function rankRouteBranches(branches) {
184
- branches.sort(
185
- (a, b) => a.score !== b.score ? b.score - a.score : compareIndexes(
186
- a.routesMeta.map((meta) => meta.childrenIndex),
187
- b.routesMeta.map((meta) => meta.childrenIndex)
188
- )
189
- );
190
- }
191
- var paramRe = /^:[\w-]+$/;
192
- var dynamicSegmentValue = 3;
193
- var indexRouteValue = 2;
194
- var emptySegmentValue = 1;
195
- var staticSegmentValue = 10;
196
- var splatPenalty = -2;
197
- var isSplat = (s) => s === "*";
198
- function computeScore(path, index) {
199
- let segments = path.split("/");
200
- let initialScore = segments.length;
201
- if (segments.some(isSplat)) {
202
- initialScore += splatPenalty;
203
- }
204
- if (index) {
205
- initialScore += indexRouteValue;
206
- }
207
- return segments.filter((s) => !isSplat(s)).reduce(
208
- (score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : segment === "" ? emptySegmentValue : staticSegmentValue),
209
- initialScore
210
- );
211
- }
212
- function compareIndexes(a, b) {
213
- let siblings = a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);
214
- return siblings ? (
215
- // If two routes are siblings, we should try to match the earlier sibling
216
- // first. This allows people to have fine-grained control over the matching
217
- // behavior by simply putting routes with identical paths in the order they
218
- // want them tried.
219
- a[a.length - 1] - b[b.length - 1]
220
- ) : (
221
- // Otherwise, it doesn't really make sense to rank non-siblings by index,
222
- // so they sort equally.
223
- 0
224
- );
225
- }
226
- function matchRouteBranch(branch, pathname, allowPartial = false) {
227
- let { routesMeta } = branch;
228
- let matchedParams = {};
229
- let matchedPathname = "/";
230
- let matches = [];
231
- for (let i = 0; i < routesMeta.length; ++i) {
232
- let meta = routesMeta[i];
233
- let end = i === routesMeta.length - 1;
234
- let remainingPathname = matchedPathname === "/" ? pathname : pathname.slice(matchedPathname.length) || "/";
235
- let match = matchPath(
236
- { path: meta.relativePath, caseSensitive: meta.caseSensitive, end },
237
- remainingPathname
238
- );
239
- let route = meta.route;
240
- if (!match && end && allowPartial && !routesMeta[routesMeta.length - 1].route.index) {
241
- match = matchPath(
242
- {
243
- path: meta.relativePath,
244
- caseSensitive: meta.caseSensitive,
245
- end: false
246
- },
247
- remainingPathname
248
- );
249
- }
250
- if (!match) {
251
- return null;
252
- }
253
- Object.assign(matchedParams, match.params);
254
- matches.push({
255
- // TODO: Can this as be avoided?
256
- params: matchedParams,
257
- pathname: joinPaths([matchedPathname, match.pathname]),
258
- pathnameBase: normalizePathname(
259
- joinPaths([matchedPathname, match.pathnameBase])
260
- ),
261
- route
262
- });
263
- if (match.pathnameBase !== "/") {
264
- matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);
265
- }
266
- }
267
- return matches;
268
- }
269
- function matchPath(pattern, pathname) {
270
- if (typeof pattern === "string") {
271
- pattern = { path: pattern, caseSensitive: false, end: true };
272
- }
273
- let [matcher, compiledParams] = compilePath(
274
- pattern.path,
275
- pattern.caseSensitive,
276
- pattern.end
277
- );
278
- let match = pathname.match(matcher);
279
- if (!match) return null;
280
- let matchedPathname = match[0];
281
- let pathnameBase = matchedPathname.replace(/(.)\/+$/, "$1");
282
- let captureGroups = match.slice(1);
283
- let params = compiledParams.reduce(
284
- (memo22, { paramName, isOptional }, index) => {
285
- if (paramName === "*") {
286
- let splatValue = captureGroups[index] || "";
287
- pathnameBase = matchedPathname.slice(0, matchedPathname.length - splatValue.length).replace(/(.)\/+$/, "$1");
288
- }
289
- const value = captureGroups[index];
290
- if (isOptional && !value) {
291
- memo22[paramName] = void 0;
292
- } else {
293
- memo22[paramName] = (value || "").replace(/%2F/g, "/");
294
- }
295
- return memo22;
296
- },
297
- {}
298
- );
299
- return {
300
- params,
301
- pathname: matchedPathname,
302
- pathnameBase,
303
- pattern
304
- };
305
- }
306
- function compilePath(path, caseSensitive = false, end = true) {
307
- warning(
308
- path === "*" || !path.endsWith("*") || path.endsWith("/*"),
309
- `Route path "${path}" will be treated as if it were "${path.replace(/\*$/, "/*")}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${path.replace(/\*$/, "/*")}".`
310
- );
311
- let params = [];
312
- let regexpSource = "^" + path.replace(/\/*\*?$/, "").replace(/^\/*/, "/").replace(/[\\.*+^${}|()[\]]/g, "\\$&").replace(
313
- /\/:([\w-]+)(\?)?/g,
314
- (_, paramName, isOptional) => {
315
- params.push({ paramName, isOptional: isOptional != null });
316
- return isOptional ? "/?([^\\/]+)?" : "/([^\\/]+)";
317
- }
318
- ).replace(/\/([\w-]+)\?(\/|$)/g, "(/$1)?$2");
319
- if (path.endsWith("*")) {
320
- params.push({ paramName: "*" });
321
- regexpSource += path === "*" || path === "/*" ? "(.*)$" : "(?:\\/(.+)|\\/*)$";
322
- } else if (end) {
323
- regexpSource += "\\/*$";
324
- } else if (path !== "" && path !== "/") {
325
- regexpSource += "(?:(?=\\/|$))";
326
- } else {
327
- }
328
- let matcher = new RegExp(regexpSource, caseSensitive ? void 0 : "i");
329
- return [matcher, params];
330
- }
331
- function decodePath(value) {
332
- try {
333
- return value.split("/").map((v) => decodeURIComponent(v).replace(/\//g, "%2F")).join("/");
334
- } catch (error) {
335
- warning(
336
- false,
337
- `The URL path "${value}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${error}).`
338
- );
339
- return value;
340
- }
341
- }
342
- function stripBasename(pathname, basename) {
343
- if (basename === "/") return pathname;
344
- if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {
345
- return null;
346
- }
347
- let startIndex = basename.endsWith("/") ? basename.length - 1 : basename.length;
348
- let nextChar = pathname.charAt(startIndex);
349
- if (nextChar && nextChar !== "/") {
350
- return null;
351
- }
352
- return pathname.slice(startIndex) || "/";
353
- }
354
- function resolvePath(to, fromPathname = "/") {
355
- let {
356
- pathname: toPathname,
357
- search = "",
358
- hash = ""
359
- } = typeof to === "string" ? parsePath(to) : to;
360
- let pathname = toPathname ? toPathname.startsWith("/") ? toPathname : resolvePathname(toPathname, fromPathname) : fromPathname;
361
- return {
362
- pathname,
363
- search: normalizeSearch(search),
364
- hash: normalizeHash(hash)
365
- };
366
- }
367
- function resolvePathname(relativePath, fromPathname) {
368
- let segments = fromPathname.replace(/\/+$/, "").split("/");
369
- let relativeSegments = relativePath.split("/");
370
- relativeSegments.forEach((segment) => {
371
- if (segment === "..") {
372
- if (segments.length > 1) segments.pop();
373
- } else if (segment !== ".") {
374
- segments.push(segment);
375
- }
376
- });
377
- return segments.length > 1 ? segments.join("/") : "/";
378
- }
379
- function getInvalidPathError(char, field, dest, path) {
380
- return `Cannot include a '${char}' character in a manually specified \`to.${field}\` field [${JSON.stringify(
381
- path
382
- )}]. Please separate it out to the \`to.${dest}\` field. Alternatively you may provide the full path as a string in <Link to="..."> and the router will parse it for you.`;
383
- }
384
- function getPathContributingMatches(matches) {
385
- return matches.filter(
386
- (match, index) => index === 0 || match.route.path && match.route.path.length > 0
387
- );
388
- }
389
- function getResolveToMatches(matches) {
390
- let pathMatches = getPathContributingMatches(matches);
391
- return pathMatches.map(
392
- (match, idx) => idx === pathMatches.length - 1 ? match.pathname : match.pathnameBase
393
- );
394
- }
395
- function resolveTo(toArg, routePathnames, locationPathname, isPathRelative = false) {
396
- let to;
397
- if (typeof toArg === "string") {
398
- to = parsePath(toArg);
399
- } else {
400
- to = { ...toArg };
401
- invariant(
402
- !to.pathname || !to.pathname.includes("?"),
403
- getInvalidPathError("?", "pathname", "search", to)
404
- );
405
- invariant(
406
- !to.pathname || !to.pathname.includes("#"),
407
- getInvalidPathError("#", "pathname", "hash", to)
408
- );
409
- invariant(
410
- !to.search || !to.search.includes("#"),
411
- getInvalidPathError("#", "search", "hash", to)
412
- );
413
- }
414
- let isEmptyPath = toArg === "" || to.pathname === "";
415
- let toPathname = isEmptyPath ? "/" : to.pathname;
416
- let from;
417
- if (toPathname == null) {
418
- from = locationPathname;
419
- } else {
420
- let routePathnameIndex = routePathnames.length - 1;
421
- if (!isPathRelative && toPathname.startsWith("..")) {
422
- let toSegments = toPathname.split("/");
423
- while (toSegments[0] === "..") {
424
- toSegments.shift();
425
- routePathnameIndex -= 1;
426
- }
427
- to.pathname = toSegments.join("/");
428
- }
429
- from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : "/";
430
- }
431
- let path = resolvePath(to, from);
432
- let hasExplicitTrailingSlash = toPathname && toPathname !== "/" && toPathname.endsWith("/");
433
- let hasCurrentTrailingSlash = (isEmptyPath || toPathname === ".") && locationPathname.endsWith("/");
434
- if (!path.pathname.endsWith("/") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) {
435
- path.pathname += "/";
436
- }
437
- return path;
438
- }
439
- var joinPaths = (paths) => paths.join("/").replace(/\/\/+/g, "/");
440
- var normalizePathname = (pathname) => pathname.replace(/\/+$/, "").replace(/^\/*/, "/");
441
- var normalizeSearch = (search) => !search || search === "?" ? "" : search.startsWith("?") ? search : "?" + search;
442
- var normalizeHash = (hash) => !hash || hash === "#" ? "" : hash.startsWith("#") ? hash : "#" + hash;
443
- function isRouteErrorResponse(error) {
444
- return error != null && typeof error.status === "number" && typeof error.statusText === "string" && typeof error.internal === "boolean" && "data" in error;
445
- }
446
- var validMutationMethodsArr = [
447
- "POST",
448
- "PUT",
449
- "PATCH",
450
- "DELETE"
451
- ];
452
- var validMutationMethods = new Set(
453
- validMutationMethodsArr
454
- );
455
- var validRequestMethodsArr = [
456
- "GET",
457
- ...validMutationMethodsArr
458
- ];
459
- var validRequestMethods = new Set(validRequestMethodsArr);
460
- var ResetLoaderDataSymbol = Symbol("ResetLoaderData");
461
- var DataRouterContext = React.createContext(null);
462
- DataRouterContext.displayName = "DataRouter";
463
- var DataRouterStateContext = React.createContext(null);
464
- DataRouterStateContext.displayName = "DataRouterState";
465
- var RSCRouterContext = React.createContext(false);
466
- var ViewTransitionContext = React.createContext({
467
- isTransitioning: false
468
- });
469
- ViewTransitionContext.displayName = "ViewTransition";
470
- var FetchersContext = React.createContext(
471
- /* @__PURE__ */ new Map()
472
- );
473
- FetchersContext.displayName = "Fetchers";
474
- var AwaitContext = React.createContext(null);
475
- AwaitContext.displayName = "Await";
476
- var NavigationContext = React.createContext(
477
- null
478
- );
479
- NavigationContext.displayName = "Navigation";
480
- var LocationContext = React.createContext(
481
- null
482
- );
483
- LocationContext.displayName = "Location";
484
- var RouteContext = React.createContext({
485
- outlet: null,
486
- matches: [],
487
- isDataRoute: false
488
- });
489
- RouteContext.displayName = "Route";
490
- var RouteErrorContext = React.createContext(null);
491
- RouteErrorContext.displayName = "RouteError";
492
- var ENABLE_DEV_WARNINGS = true;
493
- function useHref(to, { relative } = {}) {
494
- invariant(
495
- useInRouterContext(),
496
- // TODO: This error is probably because they somehow have 2 versions of the
497
- // router loaded. We can help them understand how to avoid that.
498
- `useHref() may be used only in the context of a <Router> component.`
499
- );
500
- let { basename, navigator } = React2.useContext(NavigationContext);
501
- let { hash, pathname, search } = useResolvedPath(to, { relative });
502
- let joinedPathname = pathname;
503
- if (basename !== "/") {
504
- joinedPathname = pathname === "/" ? basename : joinPaths([basename, pathname]);
505
- }
506
- return navigator.createHref({ pathname: joinedPathname, search, hash });
507
- }
508
- function useInRouterContext() {
509
- return React2.useContext(LocationContext) != null;
510
- }
511
- function useLocation() {
512
- invariant(
513
- useInRouterContext(),
514
- // TODO: This error is probably because they somehow have 2 versions of the
515
- // router loaded. We can help them understand how to avoid that.
516
- `useLocation() may be used only in the context of a <Router> component.`
517
- );
518
- return React2.useContext(LocationContext).location;
519
- }
520
- var navigateEffectWarning = `You should call navigate() in a React.useEffect(), not when your component is first rendered.`;
521
- function useIsomorphicLayoutEffect(cb) {
522
- let isStatic = React2.useContext(NavigationContext).static;
523
- if (!isStatic) {
524
- React2.useLayoutEffect(cb);
525
- }
526
- }
527
- function useNavigate() {
528
- let { isDataRoute } = React2.useContext(RouteContext);
529
- return isDataRoute ? useNavigateStable() : useNavigateUnstable();
530
- }
531
- function useNavigateUnstable() {
532
- invariant(
533
- useInRouterContext(),
534
- // TODO: This error is probably because they somehow have 2 versions of the
535
- // router loaded. We can help them understand how to avoid that.
536
- `useNavigate() may be used only in the context of a <Router> component.`
537
- );
538
- let dataRouterContext = React2.useContext(DataRouterContext);
539
- let { basename, navigator } = React2.useContext(NavigationContext);
540
- let { matches } = React2.useContext(RouteContext);
541
- let { pathname: locationPathname } = useLocation();
542
- let routePathnamesJson = JSON.stringify(getResolveToMatches(matches));
543
- let activeRef = React2.useRef(false);
544
- useIsomorphicLayoutEffect(() => {
545
- activeRef.current = true;
546
- });
547
- let navigate = React2.useCallback(
548
- (to, options = {}) => {
549
- warning(activeRef.current, navigateEffectWarning);
550
- if (!activeRef.current) return;
551
- if (typeof to === "number") {
552
- navigator.go(to);
553
- return;
554
- }
555
- let path = resolveTo(
556
- to,
557
- JSON.parse(routePathnamesJson),
558
- locationPathname,
559
- options.relative === "path"
560
- );
561
- if (dataRouterContext == null && basename !== "/") {
562
- path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
563
- }
564
- (!!options.replace ? navigator.replace : navigator.push)(
565
- path,
566
- options.state,
567
- options
568
- );
569
- },
570
- [
571
- basename,
572
- navigator,
573
- routePathnamesJson,
574
- locationPathname,
575
- dataRouterContext
576
- ]
577
- );
578
- return navigate;
579
- }
580
- var OutletContext = React2.createContext(null);
581
- function useResolvedPath(to, { relative } = {}) {
582
- let { matches } = React2.useContext(RouteContext);
583
- let { pathname: locationPathname } = useLocation();
584
- let routePathnamesJson = JSON.stringify(getResolveToMatches(matches));
585
- return React2.useMemo(
586
- () => resolveTo(
587
- to,
588
- JSON.parse(routePathnamesJson),
589
- locationPathname,
590
- relative === "path"
591
- ),
592
- [to, routePathnamesJson, locationPathname, relative]
593
- );
594
- }
595
- function useRoutesImpl(routes, locationArg, dataRouterState, unstable_onError, future) {
596
- invariant(
597
- useInRouterContext(),
598
- // TODO: This error is probably because they somehow have 2 versions of the
599
- // router loaded. We can help them understand how to avoid that.
600
- `useRoutes() may be used only in the context of a <Router> component.`
601
- );
602
- let { navigator } = React2.useContext(NavigationContext);
603
- let { matches: parentMatches } = React2.useContext(RouteContext);
604
- let routeMatch = parentMatches[parentMatches.length - 1];
605
- let parentParams = routeMatch ? routeMatch.params : {};
606
- let parentPathname = routeMatch ? routeMatch.pathname : "/";
607
- let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : "/";
608
- let parentRoute = routeMatch && routeMatch.route;
609
- if (ENABLE_DEV_WARNINGS) {
610
- let parentPath = parentRoute && parentRoute.path || "";
611
- warningOnce(
612
- parentPathname,
613
- !parentRoute || parentPath.endsWith("*") || parentPath.endsWith("*?"),
614
- `You rendered descendant <Routes> (or called \`useRoutes()\`) at "${parentPathname}" (under <Route path="${parentPath}">) but the parent route path has no trailing "*". This means if you navigate deeper, the parent won't match anymore and therefore the child routes will never render.
615
-
616
- Please change the parent <Route path="${parentPath}"> to <Route path="${parentPath === "/" ? "*" : `${parentPath}/*`}">.`
617
- );
618
- }
619
- let locationFromContext = useLocation();
620
- let location;
621
- if (locationArg) {
622
- let parsedLocationArg = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
623
- invariant(
624
- parentPathnameBase === "/" || parsedLocationArg.pathname?.startsWith(parentPathnameBase),
625
- `When overriding the location using \`<Routes location>\` or \`useRoutes(routes, location)\`, the location pathname must begin with the portion of the URL pathname that was matched by all parent routes. The current pathname base is "${parentPathnameBase}" but pathname "${parsedLocationArg.pathname}" was given in the \`location\` prop.`
626
- );
627
- location = parsedLocationArg;
628
- } else {
629
- location = locationFromContext;
630
- }
631
- let pathname = location.pathname || "/";
632
- let remainingPathname = pathname;
633
- if (parentPathnameBase !== "/") {
634
- let parentSegments = parentPathnameBase.replace(/^\//, "").split("/");
635
- let segments = pathname.replace(/^\//, "").split("/");
636
- remainingPathname = "/" + segments.slice(parentSegments.length).join("/");
637
- }
638
- let matches = matchRoutes(routes, { pathname: remainingPathname });
639
- if (ENABLE_DEV_WARNINGS) {
640
- warning(
641
- parentRoute || matches != null,
642
- `No routes matched location "${location.pathname}${location.search}${location.hash}" `
643
- );
644
- warning(
645
- matches == null || matches[matches.length - 1].route.element !== void 0 || matches[matches.length - 1].route.Component !== void 0 || matches[matches.length - 1].route.lazy !== void 0,
646
- `Matched leaf route at location "${location.pathname}${location.search}${location.hash}" does not have an element or Component. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.`
647
- );
648
- }
649
- let renderedMatches = _renderMatches(
650
- matches && matches.map(
651
- (match) => Object.assign({}, match, {
652
- params: Object.assign({}, parentParams, match.params),
653
- pathname: joinPaths([
654
- parentPathnameBase,
655
- // Re-encode pathnames that were decoded inside matchRoutes
656
- navigator.encodeLocation ? navigator.encodeLocation(match.pathname).pathname : match.pathname
657
- ]),
658
- pathnameBase: match.pathnameBase === "/" ? parentPathnameBase : joinPaths([
659
- parentPathnameBase,
660
- // Re-encode pathnames that were decoded inside matchRoutes
661
- navigator.encodeLocation ? navigator.encodeLocation(match.pathnameBase).pathname : match.pathnameBase
662
- ])
663
- })
664
- ),
665
- parentMatches,
666
- dataRouterState,
667
- unstable_onError,
668
- future
669
- );
670
- if (locationArg && renderedMatches) {
671
- return /* @__PURE__ */ React2.createElement(
672
- LocationContext.Provider,
673
- {
674
- value: {
675
- location: {
676
- pathname: "/",
677
- search: "",
678
- hash: "",
679
- state: null,
680
- key: "default",
681
- ...location
682
- },
683
- navigationType: "POP"
684
- /* Pop */
685
- }
686
- },
687
- renderedMatches
688
- );
689
- }
690
- return renderedMatches;
691
- }
692
- function DefaultErrorComponent() {
693
- let error = useRouteError();
694
- let message = isRouteErrorResponse(error) ? `${error.status} ${error.statusText}` : error instanceof Error ? error.message : JSON.stringify(error);
695
- let stack = error instanceof Error ? error.stack : null;
696
- let lightgrey = "rgba(200,200,200, 0.5)";
697
- let preStyles = { padding: "0.5rem", backgroundColor: lightgrey };
698
- let codeStyles = { padding: "2px 4px", backgroundColor: lightgrey };
699
- let devInfo = null;
700
- if (ENABLE_DEV_WARNINGS) {
701
- console.error(
702
- "Error handled by React Router default ErrorBoundary:",
703
- error
704
- );
705
- devInfo = /* @__PURE__ */ React2.createElement(React2.Fragment, null, /* @__PURE__ */ React2.createElement("p", null, "\u{1F4BF} Hey developer \u{1F44B}"), /* @__PURE__ */ React2.createElement("p", null, "You can provide a way better UX than this when your app throws errors by providing your own ", /* @__PURE__ */ React2.createElement("code", { style: codeStyles }, "ErrorBoundary"), " or", " ", /* @__PURE__ */ React2.createElement("code", { style: codeStyles }, "errorElement"), " prop on your route."));
706
- }
707
- return /* @__PURE__ */ React2.createElement(React2.Fragment, null, /* @__PURE__ */ React2.createElement("h2", null, "Unexpected Application Error!"), /* @__PURE__ */ React2.createElement("h3", { style: { fontStyle: "italic" } }, message), stack ? /* @__PURE__ */ React2.createElement("pre", { style: preStyles }, stack) : null, devInfo);
708
- }
709
- var defaultErrorElement = /* @__PURE__ */ React2.createElement(DefaultErrorComponent, null);
710
- var RenderErrorBoundary = class extends React2.Component {
711
- constructor(props) {
712
- super(props);
713
- this.state = {
714
- location: props.location,
715
- revalidation: props.revalidation,
716
- error: props.error
717
- };
718
- }
719
- static getDerivedStateFromError(error) {
720
- return { error };
721
- }
722
- static getDerivedStateFromProps(props, state) {
723
- if (state.location !== props.location || state.revalidation !== "idle" && props.revalidation === "idle") {
724
- return {
725
- error: props.error,
726
- location: props.location,
727
- revalidation: props.revalidation
728
- };
729
- }
730
- return {
731
- error: props.error !== void 0 ? props.error : state.error,
732
- location: state.location,
733
- revalidation: props.revalidation || state.revalidation
734
- };
735
- }
736
- componentDidCatch(error, errorInfo) {
737
- if (this.props.unstable_onError) {
738
- this.props.unstable_onError(error, errorInfo);
739
- } else {
740
- console.error(
741
- "React Router caught the following error during render",
742
- error
743
- );
744
- }
745
- }
746
- render() {
747
- return this.state.error !== void 0 ? /* @__PURE__ */ React2.createElement(RouteContext.Provider, { value: this.props.routeContext }, /* @__PURE__ */ React2.createElement(
748
- RouteErrorContext.Provider,
749
- {
750
- value: this.state.error,
751
- children: this.props.component
752
- }
753
- )) : this.props.children;
754
- }
755
- };
756
- function RenderedRoute({ routeContext, match, children }) {
757
- let dataRouterContext = React2.useContext(DataRouterContext);
758
- if (dataRouterContext && dataRouterContext.static && dataRouterContext.staticContext && (match.route.errorElement || match.route.ErrorBoundary)) {
759
- dataRouterContext.staticContext._deepestRenderedBoundaryId = match.route.id;
760
- }
761
- return /* @__PURE__ */ React2.createElement(RouteContext.Provider, { value: routeContext }, children);
762
- }
763
- function _renderMatches(matches, parentMatches = [], dataRouterState = null, unstable_onError = null, future = null) {
764
- if (matches == null) {
765
- if (!dataRouterState) {
766
- return null;
767
- }
768
- if (dataRouterState.errors) {
769
- matches = dataRouterState.matches;
770
- } else if (parentMatches.length === 0 && !dataRouterState.initialized && dataRouterState.matches.length > 0) {
771
- matches = dataRouterState.matches;
772
- } else {
773
- return null;
774
- }
775
- }
776
- let renderedMatches = matches;
777
- let errors = dataRouterState?.errors;
778
- if (errors != null) {
779
- let errorIndex = renderedMatches.findIndex(
780
- (m) => m.route.id && errors?.[m.route.id] !== void 0
781
- );
782
- invariant(
783
- errorIndex >= 0,
784
- `Could not find a matching route for errors on route IDs: ${Object.keys(
785
- errors
786
- ).join(",")}`
787
- );
788
- renderedMatches = renderedMatches.slice(
789
- 0,
790
- Math.min(renderedMatches.length, errorIndex + 1)
791
- );
792
- }
793
- let renderFallback = false;
794
- let fallbackIndex = -1;
795
- if (dataRouterState) {
796
- for (let i = 0; i < renderedMatches.length; i++) {
797
- let match = renderedMatches[i];
798
- if (match.route.HydrateFallback || match.route.hydrateFallbackElement) {
799
- fallbackIndex = i;
800
- }
801
- if (match.route.id) {
802
- let { loaderData, errors: errors2 } = dataRouterState;
803
- let needsToRunLoader = match.route.loader && !loaderData.hasOwnProperty(match.route.id) && (!errors2 || errors2[match.route.id] === void 0);
804
- if (match.route.lazy || needsToRunLoader) {
805
- renderFallback = true;
806
- if (fallbackIndex >= 0) {
807
- renderedMatches = renderedMatches.slice(0, fallbackIndex + 1);
808
- } else {
809
- renderedMatches = [renderedMatches[0]];
810
- }
811
- break;
812
- }
813
- }
814
- }
815
- }
816
- return renderedMatches.reduceRight(
817
- (outlet, match, index) => {
818
- let error;
819
- let shouldRenderHydrateFallback = false;
820
- let errorElement = null;
821
- let hydrateFallbackElement = null;
822
- if (dataRouterState) {
823
- error = errors && match.route.id ? errors[match.route.id] : void 0;
824
- errorElement = match.route.errorElement || defaultErrorElement;
825
- if (renderFallback) {
826
- if (fallbackIndex < 0 && index === 0) {
827
- warningOnce(
828
- "route-fallback",
829
- false,
830
- "No `HydrateFallback` element provided to render during initial hydration"
831
- );
832
- shouldRenderHydrateFallback = true;
833
- hydrateFallbackElement = null;
834
- } else if (fallbackIndex === index) {
835
- shouldRenderHydrateFallback = true;
836
- hydrateFallbackElement = match.route.hydrateFallbackElement || null;
837
- }
838
- }
839
- }
840
- let matches2 = parentMatches.concat(renderedMatches.slice(0, index + 1));
841
- let getChildren = () => {
842
- let children;
843
- if (error) {
844
- children = errorElement;
845
- } else if (shouldRenderHydrateFallback) {
846
- children = hydrateFallbackElement;
847
- } else if (match.route.Component) {
848
- children = /* @__PURE__ */ React2.createElement(match.route.Component, null);
849
- } else if (match.route.element) {
850
- children = match.route.element;
851
- } else {
852
- children = outlet;
853
- }
854
- return /* @__PURE__ */ React2.createElement(
855
- RenderedRoute,
856
- {
857
- match,
858
- routeContext: {
859
- outlet,
860
- matches: matches2,
861
- isDataRoute: dataRouterState != null
862
- },
863
- children
864
- }
865
- );
866
- };
867
- return dataRouterState && (match.route.ErrorBoundary || match.route.errorElement || index === 0) ? /* @__PURE__ */ React2.createElement(
868
- RenderErrorBoundary,
869
- {
870
- location: dataRouterState.location,
871
- revalidation: dataRouterState.revalidation,
872
- component: errorElement,
873
- error,
874
- children: getChildren(),
875
- routeContext: { outlet: null, matches: matches2, isDataRoute: true },
876
- unstable_onError
877
- }
878
- ) : getChildren();
879
- },
880
- null
881
- );
882
- }
883
- function getDataRouterConsoleError(hookName) {
884
- return `${hookName} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`;
885
- }
886
- function useDataRouterContext(hookName) {
887
- let ctx = React2.useContext(DataRouterContext);
888
- invariant(ctx, getDataRouterConsoleError(hookName));
889
- return ctx;
890
- }
891
- function useDataRouterState(hookName) {
892
- let state = React2.useContext(DataRouterStateContext);
893
- invariant(state, getDataRouterConsoleError(hookName));
894
- return state;
895
- }
896
- function useRouteContext(hookName) {
897
- let route = React2.useContext(RouteContext);
898
- invariant(route, getDataRouterConsoleError(hookName));
899
- return route;
900
- }
901
- function useCurrentRouteId(hookName) {
902
- let route = useRouteContext(hookName);
903
- let thisRoute = route.matches[route.matches.length - 1];
904
- invariant(
905
- thisRoute.route.id,
906
- `${hookName} can only be used on routes that contain a unique "id"`
907
- );
908
- return thisRoute.route.id;
909
- }
910
- function useRouteId() {
911
- return useCurrentRouteId(
912
- "useRouteId"
913
- /* UseRouteId */
914
- );
915
- }
916
- function useNavigation() {
917
- let state = useDataRouterState(
918
- "useNavigation"
919
- /* UseNavigation */
920
- );
921
- return state.navigation;
922
- }
923
- function useMatches() {
924
- let { matches, loaderData } = useDataRouterState(
925
- "useMatches"
926
- /* UseMatches */
927
- );
928
- return React2.useMemo(
929
- () => matches.map((m) => convertRouteMatchToUiMatch(m, loaderData)),
930
- [matches, loaderData]
931
- );
932
- }
933
- function useRouteError() {
934
- let error = React2.useContext(RouteErrorContext);
935
- let state = useDataRouterState(
936
- "useRouteError"
937
- /* UseRouteError */
938
- );
939
- let routeId = useCurrentRouteId(
940
- "useRouteError"
941
- /* UseRouteError */
942
- );
943
- if (error !== void 0) {
944
- return error;
945
- }
946
- return state.errors?.[routeId];
947
- }
948
- function useNavigateStable() {
949
- let { router } = useDataRouterContext(
950
- "useNavigate"
951
- /* UseNavigateStable */
952
- );
953
- let id = useCurrentRouteId(
954
- "useNavigate"
955
- /* UseNavigateStable */
956
- );
957
- let activeRef = React2.useRef(false);
958
- useIsomorphicLayoutEffect(() => {
959
- activeRef.current = true;
960
- });
961
- let navigate = React2.useCallback(
962
- async (to, options = {}) => {
963
- warning(activeRef.current, navigateEffectWarning);
964
- if (!activeRef.current) return;
965
- if (typeof to === "number") {
966
- router.navigate(to);
967
- } else {
968
- await router.navigate(to, { fromRouteId: id, ...options });
969
- }
970
- },
971
- [router, id]
972
- );
973
- return navigate;
974
- }
975
- var alreadyWarned = {};
976
- function warningOnce(key, cond, message) {
977
- if (!cond && !alreadyWarned[key]) {
978
- alreadyWarned[key] = true;
979
- warning(false, message);
980
- }
981
- }
982
- var MemoizedDataRoutes = React3.memo(DataRoutes);
983
- function DataRoutes({
984
- routes,
985
- future,
986
- state,
987
- unstable_onError
988
- }) {
989
- return useRoutesImpl(routes, void 0, state, unstable_onError, future);
990
- }
991
- function Router({
992
- basename: basenameProp = "/",
993
- children = null,
994
- location: locationProp,
995
- navigationType = "POP",
996
- navigator,
997
- static: staticProp = false
998
- }) {
999
- invariant(
1000
- !useInRouterContext(),
1001
- `You cannot render a <Router> inside another <Router>. You should never have more than one in your app.`
1002
- );
1003
- let basename = basenameProp.replace(/^\/*/, "/");
1004
- let navigationContext = React3.useMemo(
1005
- () => ({
1006
- basename,
1007
- navigator,
1008
- static: staticProp,
1009
- future: {}
1010
- }),
1011
- [basename, navigator, staticProp]
1012
- );
1013
- if (typeof locationProp === "string") {
1014
- locationProp = parsePath(locationProp);
1015
- }
1016
- let {
1017
- pathname = "/",
1018
- search = "",
1019
- hash = "",
1020
- state = null,
1021
- key = "default"
1022
- } = locationProp;
1023
- let locationContext = React3.useMemo(() => {
1024
- let trailingPathname = stripBasename(pathname, basename);
1025
- if (trailingPathname == null) {
1026
- return null;
1027
- }
1028
- return {
1029
- location: {
1030
- pathname: trailingPathname,
1031
- search,
1032
- hash,
1033
- state,
1034
- key
1035
- },
1036
- navigationType
1037
- };
1038
- }, [basename, pathname, search, hash, state, key, navigationType]);
1039
- warning(
1040
- locationContext != null,
1041
- `<Router basename="${basename}"> is not able to match the URL "${pathname}${search}${hash}" because it does not start with the basename, so the <Router> won't render anything.`
1042
- );
1043
- if (locationContext == null) {
1044
- return null;
1045
- }
1046
- return /* @__PURE__ */ React3.createElement(NavigationContext.Provider, { value: navigationContext }, /* @__PURE__ */ React3.createElement(LocationContext.Provider, { children, value: locationContext }));
1047
- }
1048
- var defaultMethod = "get";
1049
- var defaultEncType = "application/x-www-form-urlencoded";
1050
- function isHtmlElement(object) {
1051
- return object != null && typeof object.tagName === "string";
1052
- }
1053
- function isButtonElement(object) {
1054
- return isHtmlElement(object) && object.tagName.toLowerCase() === "button";
1055
- }
1056
- function isFormElement(object) {
1057
- return isHtmlElement(object) && object.tagName.toLowerCase() === "form";
1058
- }
1059
- function isInputElement(object) {
1060
- return isHtmlElement(object) && object.tagName.toLowerCase() === "input";
1061
- }
1062
- function isModifiedEvent(event) {
1063
- return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
1064
- }
1065
- function shouldProcessLinkClick(event, target) {
1066
- return event.button === 0 && // Ignore everything but left clicks
1067
- (!target || target === "_self") && // Let browser handle "target=_blank" etc.
1068
- !isModifiedEvent(event);
1069
- }
1070
- var _formDataSupportsSubmitter = null;
1071
- function isFormDataSubmitterSupported() {
1072
- if (_formDataSupportsSubmitter === null) {
1073
- try {
1074
- new FormData(
1075
- document.createElement("form"),
1076
- // @ts-expect-error if FormData supports the submitter parameter, this will throw
1077
- 0
1078
- );
1079
- _formDataSupportsSubmitter = false;
1080
- } catch (e) {
1081
- _formDataSupportsSubmitter = true;
1082
- }
1083
- }
1084
- return _formDataSupportsSubmitter;
1085
- }
1086
- var supportedFormEncTypes = /* @__PURE__ */ new Set([
1087
- "application/x-www-form-urlencoded",
1088
- "multipart/form-data",
1089
- "text/plain"
1090
- ]);
1091
- function getFormEncType(encType) {
1092
- if (encType != null && !supportedFormEncTypes.has(encType)) {
1093
- warning(
1094
- false,
1095
- `"${encType}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${defaultEncType}"`
1096
- );
1097
- return null;
1098
- }
1099
- return encType;
1100
- }
1101
- function getFormSubmissionInfo(target, basename) {
1102
- let method;
1103
- let action;
1104
- let encType;
1105
- let formData;
1106
- let body;
1107
- if (isFormElement(target)) {
1108
- let attr = target.getAttribute("action");
1109
- action = attr ? stripBasename(attr, basename) : null;
1110
- method = target.getAttribute("method") || defaultMethod;
1111
- encType = getFormEncType(target.getAttribute("enctype")) || defaultEncType;
1112
- formData = new FormData(target);
1113
- } else if (isButtonElement(target) || isInputElement(target) && (target.type === "submit" || target.type === "image")) {
1114
- let form = target.form;
1115
- if (form == null) {
1116
- throw new Error(
1117
- `Cannot submit a <button> or <input type="submit"> without a <form>`
1118
- );
1119
- }
1120
- let attr = target.getAttribute("formaction") || form.getAttribute("action");
1121
- action = attr ? stripBasename(attr, basename) : null;
1122
- method = target.getAttribute("formmethod") || form.getAttribute("method") || defaultMethod;
1123
- encType = getFormEncType(target.getAttribute("formenctype")) || getFormEncType(form.getAttribute("enctype")) || defaultEncType;
1124
- formData = new FormData(form, target);
1125
- if (!isFormDataSubmitterSupported()) {
1126
- let { name, type, value } = target;
1127
- if (type === "image") {
1128
- let prefix = name ? `${name}.` : "";
1129
- formData.append(`${prefix}x`, "0");
1130
- formData.append(`${prefix}y`, "0");
1131
- } else if (name) {
1132
- formData.append(name, value);
1133
- }
1134
- }
1135
- } else if (isHtmlElement(target)) {
1136
- throw new Error(
1137
- `Cannot submit element that is not <form>, <button>, or <input type="submit|image">`
1138
- );
1139
- } else {
1140
- method = defaultMethod;
1141
- action = null;
1142
- encType = defaultEncType;
1143
- body = target;
1144
- }
1145
- if (formData && encType === "text/plain") {
1146
- body = formData;
1147
- formData = void 0;
1148
- }
1149
- return { action, method: method.toLowerCase(), encType, formData, body };
1150
- }
1151
- var objectProtoNames = Object.getOwnPropertyNames(Object.prototype).sort().join("\0");
1152
- function invariant2(value, message) {
1153
- if (value === false || value === null || typeof value === "undefined") {
1154
- throw new Error(message);
1155
- }
1156
- }
1157
- var SingleFetchRedirectSymbol = Symbol("SingleFetchRedirect");
1158
- function singleFetchUrl(reqUrl, basename, extension) {
1159
- let url = typeof reqUrl === "string" ? new URL(
1160
- reqUrl,
1161
- // This can be called during the SSR flow via PrefetchPageLinksImpl so
1162
- // don't assume window is available
1163
- typeof window === "undefined" ? "server://singlefetch/" : window.location.origin
1164
- ) : reqUrl;
1165
- if (url.pathname === "/") {
1166
- url.pathname = `_root.${extension}`;
1167
- } else if (basename && stripBasename(url.pathname, basename) === "/") {
1168
- url.pathname = `${basename.replace(/\/$/, "")}/_root.${extension}`;
1169
- } else {
1170
- url.pathname = `${url.pathname.replace(/\/$/, "")}.${extension}`;
1171
- }
1172
- return url;
1173
- }
1174
- async function loadRouteModule(route, routeModulesCache) {
1175
- if (route.id in routeModulesCache) {
1176
- return routeModulesCache[route.id];
1177
- }
1178
- try {
1179
- let routeModule = await import(
1180
- /* @vite-ignore */
1181
- /* webpackIgnore: true */
1182
- route.module
1183
- );
1184
- routeModulesCache[route.id] = routeModule;
1185
- return routeModule;
1186
- } catch (error) {
1187
- console.error(
1188
- `Error loading route module \`${route.module}\`, reloading page...`
1189
- );
1190
- console.error(error);
1191
- if (window.__reactRouterContext && window.__reactRouterContext.isSpaMode && // @ts-expect-error
1192
- import.meta.hot) {
1193
- throw error;
1194
- }
1195
- window.location.reload();
1196
- return new Promise(() => {
1197
- });
1198
- }
1199
- }
1200
- function isPageLinkDescriptor(object) {
1201
- return object != null && typeof object.page === "string";
1202
- }
1203
- function isHtmlLinkDescriptor(object) {
1204
- if (object == null) {
1205
- return false;
1206
- }
1207
- if (object.href == null) {
1208
- return object.rel === "preload" && typeof object.imageSrcSet === "string" && typeof object.imageSizes === "string";
1209
- }
1210
- return typeof object.rel === "string" && typeof object.href === "string";
1211
- }
1212
- async function getKeyedPrefetchLinks(matches, manifest, routeModules) {
1213
- let links = await Promise.all(
1214
- matches.map(async (match) => {
1215
- let route = manifest.routes[match.route.id];
1216
- if (route) {
1217
- let mod = await loadRouteModule(route, routeModules);
1218
- return mod.links ? mod.links() : [];
1219
- }
1220
- return [];
1221
- })
1222
- );
1223
- return dedupeLinkDescriptors(
1224
- links.flat(1).filter(isHtmlLinkDescriptor).filter((link) => link.rel === "stylesheet" || link.rel === "preload").map(
1225
- (link) => link.rel === "stylesheet" ? { ...link, rel: "prefetch", as: "style" } : { ...link, rel: "prefetch" }
1226
- )
1227
- );
1228
- }
1229
- function getNewMatchesForLinks(page, nextMatches, currentMatches, manifest, location, mode) {
1230
- let isNew = (match, index) => {
1231
- if (!currentMatches[index]) return true;
1232
- return match.route.id !== currentMatches[index].route.id;
1233
- };
1234
- let matchPathChanged = (match, index) => {
1235
- return (
1236
- // param change, /users/123 -> /users/456
1237
- currentMatches[index].pathname !== match.pathname || // splat param changed, which is not present in match.path
1238
- // e.g. /files/images/avatar.jpg -> files/finances.xls
1239
- currentMatches[index].route.path?.endsWith("*") && currentMatches[index].params["*"] !== match.params["*"]
1240
- );
1241
- };
1242
- if (mode === "assets") {
1243
- return nextMatches.filter(
1244
- (match, index) => isNew(match, index) || matchPathChanged(match, index)
1245
- );
1246
- }
1247
- if (mode === "data") {
1248
- return nextMatches.filter((match, index) => {
1249
- let manifestRoute = manifest.routes[match.route.id];
1250
- if (!manifestRoute || !manifestRoute.hasLoader) {
1251
- return false;
1252
- }
1253
- if (isNew(match, index) || matchPathChanged(match, index)) {
1254
- return true;
1255
- }
1256
- if (match.route.shouldRevalidate) {
1257
- let routeChoice = match.route.shouldRevalidate({
1258
- currentUrl: new URL(
1259
- location.pathname + location.search + location.hash,
1260
- window.origin
1261
- ),
1262
- currentParams: currentMatches[0]?.params || {},
1263
- nextUrl: new URL(page, window.origin),
1264
- nextParams: match.params,
1265
- defaultShouldRevalidate: true
1266
- });
1267
- if (typeof routeChoice === "boolean") {
1268
- return routeChoice;
1269
- }
1270
- }
1271
- return true;
1272
- });
1273
- }
1274
- return [];
1275
- }
1276
- function getModuleLinkHrefs(matches, manifest, { includeHydrateFallback } = {}) {
1277
- return dedupeHrefs(
1278
- matches.map((match) => {
1279
- let route = manifest.routes[match.route.id];
1280
- if (!route) return [];
1281
- let hrefs = [route.module];
1282
- if (route.clientActionModule) {
1283
- hrefs = hrefs.concat(route.clientActionModule);
1284
- }
1285
- if (route.clientLoaderModule) {
1286
- hrefs = hrefs.concat(route.clientLoaderModule);
1287
- }
1288
- if (includeHydrateFallback && route.hydrateFallbackModule) {
1289
- hrefs = hrefs.concat(route.hydrateFallbackModule);
1290
- }
1291
- if (route.imports) {
1292
- hrefs = hrefs.concat(route.imports);
1293
- }
1294
- return hrefs;
1295
- }).flat(1)
1296
- );
1297
- }
1298
- function dedupeHrefs(hrefs) {
1299
- return [...new Set(hrefs)];
1300
- }
1301
- function sortKeys(obj) {
1302
- let sorted = {};
1303
- let keys = Object.keys(obj).sort();
1304
- for (let key of keys) {
1305
- sorted[key] = obj[key];
1306
- }
1307
- return sorted;
1308
- }
1309
- function dedupeLinkDescriptors(descriptors, preloads) {
1310
- let set = /* @__PURE__ */ new Set();
1311
- let preloadsSet = new Set(preloads);
1312
- return descriptors.reduce((deduped, descriptor) => {
1313
- let alreadyModulePreload = preloads && !isPageLinkDescriptor(descriptor) && descriptor.as === "script" && descriptor.href && preloadsSet.has(descriptor.href);
1314
- if (alreadyModulePreload) {
1315
- return deduped;
1316
- }
1317
- let key = JSON.stringify(sortKeys(descriptor));
1318
- if (!set.has(key)) {
1319
- set.add(key);
1320
- deduped.push({ key, link: descriptor });
1321
- }
1322
- return deduped;
1323
- }, []);
1324
- }
1325
- function useDataRouterContext2() {
1326
- let context = React8.useContext(DataRouterContext);
1327
- invariant2(
1328
- context,
1329
- "You must render this element inside a <DataRouterContext.Provider> element"
1330
- );
1331
- return context;
1332
- }
1333
- function useDataRouterStateContext() {
1334
- let context = React8.useContext(DataRouterStateContext);
1335
- invariant2(
1336
- context,
1337
- "You must render this element inside a <DataRouterStateContext.Provider> element"
1338
- );
1339
- return context;
1340
- }
1341
- var FrameworkContext = React8.createContext(void 0);
1342
- FrameworkContext.displayName = "FrameworkContext";
1343
- function useFrameworkContext() {
1344
- let context = React8.useContext(FrameworkContext);
1345
- invariant2(
1346
- context,
1347
- "You must render this element inside a <HydratedRouter> element"
1348
- );
1349
- return context;
1350
- }
1351
- function usePrefetchBehavior(prefetch, theirElementProps) {
1352
- let frameworkContext = React8.useContext(FrameworkContext);
1353
- let [maybePrefetch, setMaybePrefetch] = React8.useState(false);
1354
- let [shouldPrefetch, setShouldPrefetch] = React8.useState(false);
1355
- let { onFocus, onBlur, onMouseEnter, onMouseLeave, onTouchStart } = theirElementProps;
1356
- let ref = React8.useRef(null);
1357
- React8.useEffect(() => {
1358
- if (prefetch === "render") {
1359
- setShouldPrefetch(true);
1360
- }
1361
- if (prefetch === "viewport") {
1362
- let callback = (entries) => {
1363
- entries.forEach((entry) => {
1364
- setShouldPrefetch(entry.isIntersecting);
1365
- });
1366
- };
1367
- let observer = new IntersectionObserver(callback, { threshold: 0.5 });
1368
- if (ref.current) observer.observe(ref.current);
1369
- return () => {
1370
- observer.disconnect();
1371
- };
1372
- }
1373
- }, [prefetch]);
1374
- React8.useEffect(() => {
1375
- if (maybePrefetch) {
1376
- let id = setTimeout(() => {
1377
- setShouldPrefetch(true);
1378
- }, 100);
1379
- return () => {
1380
- clearTimeout(id);
1381
- };
1382
- }
1383
- }, [maybePrefetch]);
1384
- let setIntent = () => {
1385
- setMaybePrefetch(true);
1386
- };
1387
- let cancelIntent = () => {
1388
- setMaybePrefetch(false);
1389
- setShouldPrefetch(false);
1390
- };
1391
- if (!frameworkContext) {
1392
- return [false, ref, {}];
1393
- }
1394
- if (prefetch !== "intent") {
1395
- return [shouldPrefetch, ref, {}];
1396
- }
1397
- return [
1398
- shouldPrefetch,
1399
- ref,
1400
- {
1401
- onFocus: composeEventHandlers(onFocus, setIntent),
1402
- onBlur: composeEventHandlers(onBlur, cancelIntent),
1403
- onMouseEnter: composeEventHandlers(onMouseEnter, setIntent),
1404
- onMouseLeave: composeEventHandlers(onMouseLeave, cancelIntent),
1405
- onTouchStart: composeEventHandlers(onTouchStart, setIntent)
1406
- }
1407
- ];
1408
- }
1409
- function composeEventHandlers(theirHandler, ourHandler) {
1410
- return (event) => {
1411
- theirHandler && theirHandler(event);
1412
- if (!event.defaultPrevented) {
1413
- ourHandler(event);
1414
- }
1415
- };
1416
- }
1417
- function PrefetchPageLinks({ page, ...linkProps }) {
1418
- let { router } = useDataRouterContext2();
1419
- let matches = React8.useMemo(
1420
- () => matchRoutes(router.routes, page, router.basename),
1421
- [router.routes, page, router.basename]
1422
- );
1423
- if (!matches) {
1424
- return null;
1425
- }
1426
- return /* @__PURE__ */ React8.createElement(PrefetchPageLinksImpl, { page, matches, ...linkProps });
1427
- }
1428
- function useKeyedPrefetchLinks(matches) {
1429
- let { manifest, routeModules } = useFrameworkContext();
1430
- let [keyedPrefetchLinks, setKeyedPrefetchLinks] = React8.useState([]);
1431
- React8.useEffect(() => {
1432
- let interrupted = false;
1433
- void getKeyedPrefetchLinks(matches, manifest, routeModules).then(
1434
- (links) => {
1435
- if (!interrupted) {
1436
- setKeyedPrefetchLinks(links);
1437
- }
1438
- }
1439
- );
1440
- return () => {
1441
- interrupted = true;
1442
- };
1443
- }, [matches, manifest, routeModules]);
1444
- return keyedPrefetchLinks;
1445
- }
1446
- function PrefetchPageLinksImpl({
1447
- page,
1448
- matches: nextMatches,
1449
- ...linkProps
1450
- }) {
1451
- let location = useLocation();
1452
- let { manifest, routeModules } = useFrameworkContext();
1453
- let { basename } = useDataRouterContext2();
1454
- let { loaderData, matches } = useDataRouterStateContext();
1455
- let newMatchesForData = React8.useMemo(
1456
- () => getNewMatchesForLinks(
1457
- page,
1458
- nextMatches,
1459
- matches,
1460
- manifest,
1461
- location,
1462
- "data"
1463
- ),
1464
- [page, nextMatches, matches, manifest, location]
1465
- );
1466
- let newMatchesForAssets = React8.useMemo(
1467
- () => getNewMatchesForLinks(
1468
- page,
1469
- nextMatches,
1470
- matches,
1471
- manifest,
1472
- location,
1473
- "assets"
1474
- ),
1475
- [page, nextMatches, matches, manifest, location]
1476
- );
1477
- let dataHrefs = React8.useMemo(() => {
1478
- if (page === location.pathname + location.search + location.hash) {
1479
- return [];
1480
- }
1481
- let routesParams = /* @__PURE__ */ new Set();
1482
- let foundOptOutRoute = false;
1483
- nextMatches.forEach((m) => {
1484
- let manifestRoute = manifest.routes[m.route.id];
1485
- if (!manifestRoute || !manifestRoute.hasLoader) {
1486
- return;
1487
- }
1488
- if (!newMatchesForData.some((m2) => m2.route.id === m.route.id) && m.route.id in loaderData && routeModules[m.route.id]?.shouldRevalidate) {
1489
- foundOptOutRoute = true;
1490
- } else if (manifestRoute.hasClientLoader) {
1491
- foundOptOutRoute = true;
1492
- } else {
1493
- routesParams.add(m.route.id);
1494
- }
1495
- });
1496
- if (routesParams.size === 0) {
1497
- return [];
1498
- }
1499
- let url = singleFetchUrl(page, basename, "data");
1500
- if (foundOptOutRoute && routesParams.size > 0) {
1501
- url.searchParams.set(
1502
- "_routes",
1503
- nextMatches.filter((m) => routesParams.has(m.route.id)).map((m) => m.route.id).join(",")
1504
- );
1505
- }
1506
- return [url.pathname + url.search];
1507
- }, [
1508
- basename,
1509
- loaderData,
1510
- location,
1511
- manifest,
1512
- newMatchesForData,
1513
- nextMatches,
1514
- page,
1515
- routeModules
1516
- ]);
1517
- let moduleHrefs = React8.useMemo(
1518
- () => getModuleLinkHrefs(newMatchesForAssets, manifest),
1519
- [newMatchesForAssets, manifest]
1520
- );
1521
- let keyedPrefetchLinks = useKeyedPrefetchLinks(newMatchesForAssets);
1522
- return /* @__PURE__ */ React8.createElement(React8.Fragment, null, dataHrefs.map((href) => /* @__PURE__ */ React8.createElement("link", { key: href, rel: "prefetch", as: "fetch", href, ...linkProps })), moduleHrefs.map((href) => /* @__PURE__ */ React8.createElement("link", { key: href, rel: "modulepreload", href, ...linkProps })), keyedPrefetchLinks.map(({ key, link }) => (
1523
- // these don't spread `linkProps` because they are full link descriptors
1524
- // already with their own props
1525
- /* @__PURE__ */ React8.createElement("link", { key, nonce: linkProps.nonce, ...link })
1526
- )));
1527
- }
1528
- function mergeRefs(...refs) {
1529
- return (value) => {
1530
- refs.forEach((ref) => {
1531
- if (typeof ref === "function") {
1532
- ref(value);
1533
- } else if (ref != null) {
1534
- ref.current = value;
1535
- }
1536
- });
1537
- };
1538
- }
1539
- var isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined";
1540
- try {
1541
- if (isBrowser) {
1542
- window.__reactRouterVersion = // @ts-expect-error
1543
- "7.9.1";
1544
- }
1545
- } catch (e) {
1546
- }
1547
- function HistoryRouter({
1548
- basename,
1549
- children,
1550
- history
1551
- }) {
1552
- let [state, setStateImpl] = React10.useState({
1553
- action: history.action,
1554
- location: history.location
1555
- });
1556
- let setState = React10.useCallback(
1557
- (newState) => {
1558
- React10.startTransition(() => setStateImpl(newState));
1559
- },
1560
- [setStateImpl]
1561
- );
1562
- React10.useLayoutEffect(() => history.listen(setState), [history, setState]);
1563
- return /* @__PURE__ */ React10.createElement(
1564
- Router,
1565
- {
1566
- basename,
1567
- children,
1568
- location: state.location,
1569
- navigationType: state.action,
1570
- navigator: history
1571
- }
1572
- );
1573
- }
1574
- HistoryRouter.displayName = "unstable_HistoryRouter";
1575
- var ABSOLUTE_URL_REGEX2 = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
1576
- var Link = React10.forwardRef(
1577
- function LinkWithRef({
1578
- onClick,
1579
- discover = "render",
1580
- prefetch = "none",
1581
- relative,
1582
- reloadDocument,
1583
- replace: replace2,
1584
- state,
1585
- target,
1586
- to,
1587
- preventScrollReset,
1588
- viewTransition,
1589
- ...rest
1590
- }, forwardedRef) {
1591
- let { basename } = React10.useContext(NavigationContext);
1592
- let isAbsolute = typeof to === "string" && ABSOLUTE_URL_REGEX2.test(to);
1593
- let absoluteHref;
1594
- let isExternal = false;
1595
- if (typeof to === "string" && isAbsolute) {
1596
- absoluteHref = to;
1597
- if (isBrowser) {
1598
- try {
1599
- let currentUrl = new URL(window.location.href);
1600
- let targetUrl = to.startsWith("//") ? new URL(currentUrl.protocol + to) : new URL(to);
1601
- let path = stripBasename(targetUrl.pathname, basename);
1602
- if (targetUrl.origin === currentUrl.origin && path != null) {
1603
- to = path + targetUrl.search + targetUrl.hash;
1604
- } else {
1605
- isExternal = true;
1606
- }
1607
- } catch (e) {
1608
- warning(
1609
- false,
1610
- `<Link to="${to}"> contains an invalid URL which will probably break when clicked - please update to a valid URL path.`
1611
- );
1612
- }
1613
- }
1614
- }
1615
- let href = useHref(to, { relative });
1616
- let [shouldPrefetch, prefetchRef, prefetchHandlers] = usePrefetchBehavior(
1617
- prefetch,
1618
- rest
1619
- );
1620
- let internalOnClick = useLinkClickHandler(to, {
1621
- replace: replace2,
1622
- state,
1623
- target,
1624
- preventScrollReset,
1625
- relative,
1626
- viewTransition
1627
- });
1628
- function handleClick(event) {
1629
- if (onClick) onClick(event);
1630
- if (!event.defaultPrevented) {
1631
- internalOnClick(event);
1632
- }
1633
- }
1634
- let link = (
1635
- // eslint-disable-next-line jsx-a11y/anchor-has-content
1636
- /* @__PURE__ */ React10.createElement(
1637
- "a",
1638
- {
1639
- ...rest,
1640
- ...prefetchHandlers,
1641
- href: absoluteHref || href,
1642
- onClick: isExternal || reloadDocument ? onClick : handleClick,
1643
- ref: mergeRefs(forwardedRef, prefetchRef),
1644
- target,
1645
- "data-discover": !isAbsolute && discover === "render" ? "true" : void 0
1646
- }
1647
- )
1648
- );
1649
- return shouldPrefetch && !isAbsolute ? /* @__PURE__ */ React10.createElement(React10.Fragment, null, link, /* @__PURE__ */ React10.createElement(PrefetchPageLinks, { page: href })) : link;
1650
- }
1651
- );
1652
- Link.displayName = "Link";
1653
- var NavLink = React10.forwardRef(
1654
- function NavLinkWithRef({
1655
- "aria-current": ariaCurrentProp = "page",
1656
- caseSensitive = false,
1657
- className: classNameProp = "",
1658
- end = false,
1659
- style: styleProp,
1660
- to,
1661
- viewTransition,
1662
- children,
1663
- ...rest
1664
- }, ref) {
1665
- let path = useResolvedPath(to, { relative: rest.relative });
1666
- let location = useLocation();
1667
- let routerState = React10.useContext(DataRouterStateContext);
1668
- let { navigator, basename } = React10.useContext(NavigationContext);
1669
- let isTransitioning = routerState != null && // Conditional usage is OK here because the usage of a data router is static
1670
- // eslint-disable-next-line react-hooks/rules-of-hooks
1671
- useViewTransitionState(path) && viewTransition === true;
1672
- let toPathname = navigator.encodeLocation ? navigator.encodeLocation(path).pathname : path.pathname;
1673
- let locationPathname = location.pathname;
1674
- let nextLocationPathname = routerState && routerState.navigation && routerState.navigation.location ? routerState.navigation.location.pathname : null;
1675
- if (!caseSensitive) {
1676
- locationPathname = locationPathname.toLowerCase();
1677
- nextLocationPathname = nextLocationPathname ? nextLocationPathname.toLowerCase() : null;
1678
- toPathname = toPathname.toLowerCase();
1679
- }
1680
- if (nextLocationPathname && basename) {
1681
- nextLocationPathname = stripBasename(nextLocationPathname, basename) || nextLocationPathname;
1682
- }
1683
- const endSlashPosition = toPathname !== "/" && toPathname.endsWith("/") ? toPathname.length - 1 : toPathname.length;
1684
- let isActive = locationPathname === toPathname || !end && locationPathname.startsWith(toPathname) && locationPathname.charAt(endSlashPosition) === "/";
1685
- let isPending = nextLocationPathname != null && (nextLocationPathname === toPathname || !end && nextLocationPathname.startsWith(toPathname) && nextLocationPathname.charAt(toPathname.length) === "/");
1686
- let renderProps = {
1687
- isActive,
1688
- isPending,
1689
- isTransitioning
1690
- };
1691
- let ariaCurrent = isActive ? ariaCurrentProp : void 0;
1692
- let className;
1693
- if (typeof classNameProp === "function") {
1694
- className = classNameProp(renderProps);
1695
- } else {
1696
- className = [
1697
- classNameProp,
1698
- isActive ? "active" : null,
1699
- isPending ? "pending" : null,
1700
- isTransitioning ? "transitioning" : null
1701
- ].filter(Boolean).join(" ");
1702
- }
1703
- let style = typeof styleProp === "function" ? styleProp(renderProps) : styleProp;
1704
- return /* @__PURE__ */ React10.createElement(
1705
- Link,
1706
- {
1707
- ...rest,
1708
- "aria-current": ariaCurrent,
1709
- className,
1710
- ref,
1711
- style,
1712
- to,
1713
- viewTransition
1714
- },
1715
- typeof children === "function" ? children(renderProps) : children
1716
- );
1717
- }
1718
- );
1719
- NavLink.displayName = "NavLink";
1720
- var Form = React10.forwardRef(
1721
- ({
1722
- discover = "render",
1723
- fetcherKey,
1724
- navigate,
1725
- reloadDocument,
1726
- replace: replace2,
1727
- state,
1728
- method = defaultMethod,
1729
- action,
1730
- onSubmit,
1731
- relative,
1732
- preventScrollReset,
1733
- viewTransition,
1734
- ...props
1735
- }, forwardedRef) => {
1736
- let submit = useSubmit();
1737
- let formAction = useFormAction(action, { relative });
1738
- let formMethod = method.toLowerCase() === "get" ? "get" : "post";
1739
- let isAbsolute = typeof action === "string" && ABSOLUTE_URL_REGEX2.test(action);
1740
- let submitHandler = (event) => {
1741
- onSubmit && onSubmit(event);
1742
- if (event.defaultPrevented) return;
1743
- event.preventDefault();
1744
- let submitter = event.nativeEvent.submitter;
1745
- let submitMethod = submitter?.getAttribute("formmethod") || method;
1746
- submit(submitter || event.currentTarget, {
1747
- fetcherKey,
1748
- method: submitMethod,
1749
- navigate,
1750
- replace: replace2,
1751
- state,
1752
- relative,
1753
- preventScrollReset,
1754
- viewTransition
1755
- });
1756
- };
1757
- return /* @__PURE__ */ React10.createElement(
1758
- "form",
1759
- {
1760
- ref: forwardedRef,
1761
- method: formMethod,
1762
- action: formAction,
1763
- onSubmit: reloadDocument ? onSubmit : submitHandler,
1764
- ...props,
1765
- "data-discover": !isAbsolute && discover === "render" ? "true" : void 0
1766
- }
1767
- );
1768
- }
1769
- );
1770
- Form.displayName = "Form";
1771
- function ScrollRestoration({
1772
- getKey,
1773
- storageKey,
1774
- ...props
1775
- }) {
1776
- let remixContext = React10.useContext(FrameworkContext);
1777
- let { basename } = React10.useContext(NavigationContext);
1778
- let location = useLocation();
1779
- let matches = useMatches();
1780
- useScrollRestoration({ getKey, storageKey });
1781
- let ssrKey = React10.useMemo(
1782
- () => {
1783
- if (!remixContext || !getKey) return null;
1784
- let userKey = getScrollRestorationKey(
1785
- location,
1786
- matches,
1787
- basename,
1788
- getKey
1789
- );
1790
- return userKey !== location.key ? userKey : null;
1791
- },
1792
- // Nah, we only need this the first time for the SSR render
1793
- // eslint-disable-next-line react-hooks/exhaustive-deps
1794
- []
1795
- );
1796
- if (!remixContext || remixContext.isSpaMode) {
1797
- return null;
1798
- }
1799
- let restoreScroll = ((storageKey2, restoreKey) => {
1800
- if (!window.history.state || !window.history.state.key) {
1801
- let key = Math.random().toString(32).slice(2);
1802
- window.history.replaceState({ key }, "");
1803
- }
1804
- try {
1805
- let positions = JSON.parse(sessionStorage.getItem(storageKey2) || "{}");
1806
- let storedY = positions[restoreKey || window.history.state.key];
1807
- if (typeof storedY === "number") {
1808
- window.scrollTo(0, storedY);
1809
- }
1810
- } catch (error) {
1811
- console.error(error);
1812
- sessionStorage.removeItem(storageKey2);
1813
- }
1814
- }).toString();
1815
- return /* @__PURE__ */ React10.createElement(
1816
- "script",
1817
- {
1818
- ...props,
1819
- suppressHydrationWarning: true,
1820
- dangerouslySetInnerHTML: {
1821
- __html: `(${restoreScroll})(${JSON.stringify(
1822
- storageKey || SCROLL_RESTORATION_STORAGE_KEY
1823
- )}, ${JSON.stringify(ssrKey)})`
1824
- }
1825
- }
1826
- );
1827
- }
1828
- ScrollRestoration.displayName = "ScrollRestoration";
1829
- function getDataRouterConsoleError2(hookName) {
1830
- return `${hookName} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`;
1831
- }
1832
- function useDataRouterContext3(hookName) {
1833
- let ctx = React10.useContext(DataRouterContext);
1834
- invariant(ctx, getDataRouterConsoleError2(hookName));
1835
- return ctx;
1836
- }
1837
- function useDataRouterState2(hookName) {
1838
- let state = React10.useContext(DataRouterStateContext);
1839
- invariant(state, getDataRouterConsoleError2(hookName));
1840
- return state;
1841
- }
1842
- function useLinkClickHandler(to, {
1843
- target,
1844
- replace: replaceProp,
1845
- state,
1846
- preventScrollReset,
1847
- relative,
1848
- viewTransition
1849
- } = {}) {
1850
- let navigate = useNavigate();
1851
- let location = useLocation();
1852
- let path = useResolvedPath(to, { relative });
1853
- return React10.useCallback(
1854
- (event) => {
1855
- if (shouldProcessLinkClick(event, target)) {
1856
- event.preventDefault();
1857
- let replace2 = replaceProp !== void 0 ? replaceProp : createPath(location) === createPath(path);
1858
- navigate(to, {
1859
- replace: replace2,
1860
- state,
1861
- preventScrollReset,
1862
- relative,
1863
- viewTransition
1864
- });
1865
- }
1866
- },
1867
- [
1868
- location,
1869
- navigate,
1870
- path,
1871
- replaceProp,
1872
- state,
1873
- target,
1874
- to,
1875
- preventScrollReset,
1876
- relative,
1877
- viewTransition
1878
- ]
1879
- );
1880
- }
1881
- var fetcherId = 0;
1882
- var getUniqueFetcherId = () => `__${String(++fetcherId)}__`;
1883
- function useSubmit() {
1884
- let { router } = useDataRouterContext3(
1885
- "useSubmit"
1886
- /* UseSubmit */
1887
- );
1888
- let { basename } = React10.useContext(NavigationContext);
1889
- let currentRouteId = useRouteId();
1890
- return React10.useCallback(
1891
- async (target, options = {}) => {
1892
- let { action, method, encType, formData, body } = getFormSubmissionInfo(
1893
- target,
1894
- basename
1895
- );
1896
- if (options.navigate === false) {
1897
- let key = options.fetcherKey || getUniqueFetcherId();
1898
- await router.fetch(key, currentRouteId, options.action || action, {
1899
- preventScrollReset: options.preventScrollReset,
1900
- formData,
1901
- body,
1902
- formMethod: options.method || method,
1903
- formEncType: options.encType || encType,
1904
- flushSync: options.flushSync
1905
- });
1906
- } else {
1907
- await router.navigate(options.action || action, {
1908
- preventScrollReset: options.preventScrollReset,
1909
- formData,
1910
- body,
1911
- formMethod: options.method || method,
1912
- formEncType: options.encType || encType,
1913
- replace: options.replace,
1914
- state: options.state,
1915
- fromRouteId: currentRouteId,
1916
- flushSync: options.flushSync,
1917
- viewTransition: options.viewTransition
1918
- });
1919
- }
1920
- },
1921
- [router, basename, currentRouteId]
1922
- );
1923
- }
1924
- function useFormAction(action, { relative } = {}) {
1925
- let { basename } = React10.useContext(NavigationContext);
1926
- let routeContext = React10.useContext(RouteContext);
1927
- invariant(routeContext, "useFormAction must be used inside a RouteContext");
1928
- let [match] = routeContext.matches.slice(-1);
1929
- let path = { ...useResolvedPath(action ? action : ".", { relative }) };
1930
- let location = useLocation();
1931
- if (action == null) {
1932
- path.search = location.search;
1933
- let params = new URLSearchParams(path.search);
1934
- let indexValues = params.getAll("index");
1935
- let hasNakedIndexParam = indexValues.some((v) => v === "");
1936
- if (hasNakedIndexParam) {
1937
- params.delete("index");
1938
- indexValues.filter((v) => v).forEach((v) => params.append("index", v));
1939
- let qs = params.toString();
1940
- path.search = qs ? `?${qs}` : "";
1941
- }
1942
- }
1943
- if ((!action || action === ".") && match.route.index) {
1944
- path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index";
1945
- }
1946
- if (basename !== "/") {
1947
- path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
1948
- }
1949
- return createPath(path);
1950
- }
1951
- var SCROLL_RESTORATION_STORAGE_KEY = "react-router-scroll-positions";
1952
- var savedScrollPositions = {};
1953
- function getScrollRestorationKey(location, matches, basename, getKey) {
1954
- let key = null;
1955
- if (getKey) {
1956
- if (basename !== "/") {
1957
- key = getKey(
1958
- {
1959
- ...location,
1960
- pathname: stripBasename(location.pathname, basename) || location.pathname
1961
- },
1962
- matches
1963
- );
1964
- } else {
1965
- key = getKey(location, matches);
1966
- }
1967
- }
1968
- if (key == null) {
1969
- key = location.key;
1970
- }
1971
- return key;
1972
- }
1973
- function useScrollRestoration({
1974
- getKey,
1975
- storageKey
1976
- } = {}) {
1977
- let { router } = useDataRouterContext3(
1978
- "useScrollRestoration"
1979
- /* UseScrollRestoration */
1980
- );
1981
- let { restoreScrollPosition, preventScrollReset } = useDataRouterState2(
1982
- "useScrollRestoration"
1983
- /* UseScrollRestoration */
1984
- );
1985
- let { basename } = React10.useContext(NavigationContext);
1986
- let location = useLocation();
1987
- let matches = useMatches();
1988
- let navigation = useNavigation();
1989
- React10.useEffect(() => {
1990
- window.history.scrollRestoration = "manual";
1991
- return () => {
1992
- window.history.scrollRestoration = "auto";
1993
- };
1994
- }, []);
1995
- usePageHide(
1996
- React10.useCallback(() => {
1997
- if (navigation.state === "idle") {
1998
- let key = getScrollRestorationKey(location, matches, basename, getKey);
1999
- savedScrollPositions[key] = window.scrollY;
2000
- }
2001
- try {
2002
- sessionStorage.setItem(
2003
- storageKey || SCROLL_RESTORATION_STORAGE_KEY,
2004
- JSON.stringify(savedScrollPositions)
2005
- );
2006
- } catch (error) {
2007
- warning(
2008
- false,
2009
- `Failed to save scroll positions in sessionStorage, <ScrollRestoration /> will not work properly (${error}).`
2010
- );
2011
- }
2012
- window.history.scrollRestoration = "auto";
2013
- }, [navigation.state, getKey, basename, location, matches, storageKey])
2014
- );
2015
- if (typeof document !== "undefined") {
2016
- React10.useLayoutEffect(() => {
2017
- try {
2018
- let sessionPositions = sessionStorage.getItem(
2019
- storageKey || SCROLL_RESTORATION_STORAGE_KEY
2020
- );
2021
- if (sessionPositions) {
2022
- savedScrollPositions = JSON.parse(sessionPositions);
2023
- }
2024
- } catch (e) {
2025
- }
2026
- }, [storageKey]);
2027
- React10.useLayoutEffect(() => {
2028
- let disableScrollRestoration = router?.enableScrollRestoration(
2029
- savedScrollPositions,
2030
- () => window.scrollY,
2031
- getKey ? (location2, matches2) => getScrollRestorationKey(location2, matches2, basename, getKey) : void 0
2032
- );
2033
- return () => disableScrollRestoration && disableScrollRestoration();
2034
- }, [router, basename, getKey]);
2035
- React10.useLayoutEffect(() => {
2036
- if (restoreScrollPosition === false) {
2037
- return;
2038
- }
2039
- if (typeof restoreScrollPosition === "number") {
2040
- window.scrollTo(0, restoreScrollPosition);
2041
- return;
2042
- }
2043
- try {
2044
- if (location.hash) {
2045
- let el = document.getElementById(
2046
- decodeURIComponent(location.hash.slice(1))
2047
- );
2048
- if (el) {
2049
- el.scrollIntoView();
2050
- return;
2051
- }
2052
- }
2053
- } catch {
2054
- warning(
2055
- false,
2056
- `"${location.hash.slice(
2057
- 1
2058
- )}" is not a decodable element ID. The view will not scroll to it.`
2059
- );
2060
- }
2061
- if (preventScrollReset === true) {
2062
- return;
2063
- }
2064
- window.scrollTo(0, 0);
2065
- }, [location, restoreScrollPosition, preventScrollReset]);
2066
- }
2067
- }
2068
- function usePageHide(callback, options) {
2069
- let { capture } = options || {};
2070
- React10.useEffect(() => {
2071
- let opts = capture != null ? { capture } : void 0;
2072
- window.addEventListener("pagehide", callback, opts);
2073
- return () => {
2074
- window.removeEventListener("pagehide", callback, opts);
2075
- };
2076
- }, [callback, capture]);
2077
- }
2078
- function useViewTransitionState(to, { relative } = {}) {
2079
- let vtContext = React10.useContext(ViewTransitionContext);
2080
- invariant(
2081
- vtContext != null,
2082
- "`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?"
2083
- );
2084
- let { basename } = useDataRouterContext3(
2085
- "useViewTransitionState"
2086
- /* useViewTransitionState */
2087
- );
2088
- let path = useResolvedPath(to, { relative });
2089
- if (!vtContext.isTransitioning) {
2090
- return false;
2091
- }
2092
- let currentPath = stripBasename(vtContext.currentLocation.pathname, basename) || vtContext.currentLocation.pathname;
2093
- let nextPath = stripBasename(vtContext.nextLocation.pathname, basename) || vtContext.nextLocation.pathname;
2094
- return matchPath(path.pathname, nextPath) != null || matchPath(path.pathname, currentPath) != null;
2095
- }
2096
-
2097
- // src/hooks/use-weaverse-data-context.ts
2098
- function createFlatDataContext(matches) {
2099
- const context = {};
2100
- for (const match of matches) {
2101
- if (match.data && typeof match.data === "object") {
2102
- context[match.id] = match.data;
2103
- }
2104
- }
2105
- return context;
2106
- }
2107
- function useWeaverseDataContext() {
2108
- const matches = useMatches();
2109
- return createFlatDataContext(matches);
2110
- }
2111
- function createWeaverseDataContext(matches) {
2112
- return createFlatDataContext(matches);
2113
- }
12
+ import { useContext } from "react";
2114
13
 
2115
14
  // src/utils/data-connector.ts
2116
15
  var TEMPLATE_REGEX = /\{\{([^}]+)\}\}/g;
@@ -2158,16 +57,19 @@ function sanitizeValue(value) {
2158
57
  const stringValue = String(value);
2159
58
  return stringValue.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#x27;").replace(/\//g, "&#x2F;");
2160
59
  }
2161
- function createCacheKey(content, data2) {
60
+ function createCacheKey(content, data) {
2162
61
  try {
2163
- const dataStr = JSON.stringify(data2);
62
+ const dataStr = JSON.stringify(data);
2164
63
  return `${content}:${dataStr.slice(0, 100)}`;
2165
64
  } catch {
2166
- const keys = Object.keys(data2).sort().join(",");
65
+ const keys = Object.keys(data).sort().join(",");
2167
66
  return `${content}:keys:${keys}`;
2168
67
  }
2169
68
  }
2170
69
  function resolveDataFromContext(path, dataContext) {
70
+ if (!dataContext) {
71
+ return void 0;
72
+ }
2171
73
  const trimmedPath = path.trim();
2172
74
  const pathParts = trimmedPath.split(".");
2173
75
  const potentialRouteKey = pathParts[0];
@@ -2253,50 +155,50 @@ function replaceContentDataConnectors(content, dataContext) {
2253
155
  return content;
2254
156
  }
2255
157
  }
2256
- function replaceContentDataConnectorsDeep(data2, dataContext, visited = /* @__PURE__ */ new WeakSet()) {
158
+ function replaceContentDataConnectorsDeep(data, dataContext, visited = /* @__PURE__ */ new WeakSet()) {
2257
159
  if (!dataContext) {
2258
- return data2;
160
+ return data;
2259
161
  }
2260
- if (typeof data2 === "string") {
2261
- return replaceContentDataConnectors(data2, dataContext);
162
+ if (typeof data === "string") {
163
+ return replaceContentDataConnectors(data, dataContext);
2262
164
  }
2263
- if (typeof data2 !== "object" || data2 === null) {
2264
- return data2;
165
+ if (typeof data !== "object" || data === null) {
166
+ return data;
2265
167
  }
2266
- if (visited.has(data2)) {
168
+ if (visited.has(data)) {
2267
169
  console.warn(
2268
170
  "Circular reference detected in deep data connector replacement"
2269
171
  );
2270
- return data2;
172
+ return data;
2271
173
  }
2272
- visited.add(data2);
174
+ visited.add(data);
2273
175
  try {
2274
- if (Array.isArray(data2)) {
2275
- return data2.map(
176
+ if (Array.isArray(data)) {
177
+ return data.map(
2276
178
  (item) => replaceContentDataConnectorsDeep(item, dataContext, visited)
2277
179
  );
2278
180
  }
2279
181
  const result = {};
2280
- for (const [key, value] of Object.entries(data2)) {
182
+ for (const [key, value] of Object.entries(data)) {
2281
183
  ;
2282
184
  result[key] = replaceContentDataConnectorsDeep(value, dataContext, visited);
2283
185
  }
2284
186
  return result;
2285
187
  } catch (error) {
2286
188
  console.warn("Error in deep data connector replacement:", error);
2287
- return data2;
189
+ return data;
2288
190
  } finally {
2289
- visited.delete(data2);
191
+ visited.delete(data);
2290
192
  }
2291
193
  }
2292
194
 
2293
195
  // src/hooks.ts
2294
196
  function useWeaverse() {
2295
- let weaverse = useContext6(WeaverseContext);
197
+ let weaverse = useContext(WeaverseContext);
2296
198
  return weaverse;
2297
199
  }
2298
200
  var useItemInstance = (id) => {
2299
- let { id: currentId } = useContext6(WeaverseItemContext);
201
+ let { id: currentId } = useContext(WeaverseItemContext);
2300
202
  let instance = Weaverse.itemInstances.get(id || currentId);
2301
203
  if (!instance) {
2302
204
  console.log(`Item instance ${id} not found`);
@@ -2305,7 +207,7 @@ var useItemInstance = (id) => {
2305
207
  return instance;
2306
208
  };
2307
209
  var useParentInstance = () => {
2308
- let { parentId } = useContext6(WeaverseItemContext);
210
+ let { parentId } = useContext(WeaverseItemContext);
2309
211
  return useItemInstance(parentId || "");
2310
212
  };
2311
213
  var useChildInstances = (id) => {
@@ -2322,8 +224,8 @@ var useChildInstances = (id) => {
2322
224
 
2323
225
  // src/renderer.tsx
2324
226
  import clsx2 from "clsx";
2325
- import * as React12 from "react";
2326
- import { memo as memo2, useEffect as useEffect6, useRef as useRef5 } from "react";
227
+ import * as React from "react";
228
+ import { memo, useEffect, useRef } from "react";
2327
229
 
2328
230
  // src/utils/css.ts
2329
231
  import clsx from "clsx";
@@ -2362,25 +264,25 @@ function generateItemClassName(instance, stitchesInstance) {
2362
264
 
2363
265
  // src/renderer.tsx
2364
266
  import { jsx, jsxs } from "react/jsx-runtime";
2365
- import { createElement as createElement11 } from "react";
2366
- var reactVersion = Number(React12.version?.split(".")[0]) || 0;
267
+ import { createElement } from "react";
268
+ var reactVersion = Number(React.version?.split(".")[0]) || 0;
2367
269
  var useSafeExternalStore = (subscribe, getSnapshot, getServerSnapshot = getSnapshot) => {
2368
270
  if (typeof window === "undefined") {
2369
271
  return getServerSnapshot();
2370
272
  }
2371
- if (React12.useSyncExternalStore) {
2372
- return React12.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
273
+ if (React.useSyncExternalStore) {
274
+ return React.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
2373
275
  }
2374
276
  return getSnapshot();
2375
277
  };
2376
- var WeaverseRoot = memo2(({ context }) => {
2377
- let data2 = useSafeExternalStore(
278
+ var WeaverseRoot = memo(({ context }) => {
279
+ let data = useSafeExternalStore(
2378
280
  context.subscribe,
2379
281
  context.getSnapShot,
2380
282
  context.getSnapShot
2381
283
  );
2382
- let rootRef = useRef5(null);
2383
- useEffect6(() => {
284
+ let rootRef = useRef(null);
285
+ useEffect(() => {
2384
286
  context.contentRootElement = rootRef.current;
2385
287
  }, [context]);
2386
288
  let eventHandlers = context?.studioBridge?.eventHandlers || {};
@@ -2392,7 +294,7 @@ var WeaverseRoot = memo2(({ context }) => {
2392
294
  className: `weaverse-content-root ${themeClass}`,
2393
295
  ...eventHandlers,
2394
296
  "data-weaverse-project-id": context.projectId,
2395
- "data-weaverse-template-id": data2.id,
297
+ "data-weaverse-template-id": data.id,
2396
298
  ref: rootRef,
2397
299
  children: /* @__PURE__ */ jsx(WeaverseContextProvider, { value: context, children: /* @__PURE__ */ jsx(
2398
300
  ItemInstance,
@@ -2407,10 +309,10 @@ var WeaverseRoot = memo2(({ context }) => {
2407
309
  return null;
2408
310
  });
2409
311
  WeaverseRoot.displayName = "WeaverseRoot";
2410
- var ItemComponent = memo2(({ instance }) => {
312
+ var ItemComponent = memo(({ instance }) => {
2411
313
  let context = useWeaverse();
2412
314
  let { stitchesInstance, elementRegistry, platformType } = context;
2413
- let data2 = useSafeExternalStore(
315
+ let data = useSafeExternalStore(
2414
316
  instance.subscribe,
2415
317
  instance.getSnapShot,
2416
318
  instance.getSnapShot
@@ -2430,12 +332,12 @@ var ItemComponent = memo2(({ instance }) => {
2430
332
  data: _,
2431
333
  content,
2432
334
  ...rest
2433
- } = data2;
335
+ } = data;
2434
336
  if (content !== void 0 && content !== null) {
2435
337
  content = replaceContentDataConnectorsDeep(content, context.dataContext);
2436
338
  rest.content = content;
2437
339
  }
2438
- useEffect6(() => {
340
+ useEffect(() => {
2439
341
  if (!instance.ref.current) {
2440
342
  Object.assign(instance.ref, {
2441
343
  current: document.querySelector(`[data-wv-id="${id}"]`)
@@ -2447,14 +349,14 @@ var ItemComponent = memo2(({ instance }) => {
2447
349
  }
2448
350
  let Element = elementRegistry.get(type);
2449
351
  if (Element?.Component) {
2450
- let Component4 = Element.Component;
2451
- Component4.displayName = type;
2452
- if (Component4.$$typeof === Symbol.for("react.forward_ref") || reactVersion > 18) {
352
+ let Component = Element.Component;
353
+ Component.displayName = type;
354
+ if (Component.$$typeof === Symbol.for("react.forward_ref") || reactVersion > 18) {
2453
355
  rest.ref = instance.ref;
2454
356
  }
2455
357
  let renderChildren = (children?.length ? children : childIds?.length ? childIds.map((cid) => ({ id: cid })) : []).map((item, index) => /* @__PURE__ */ jsx(ItemInstance, { id: item.id, parentId: id }, `${item.id}-${index}`));
2456
- return /* @__PURE__ */ createElement11(
2457
- Component4,
358
+ return /* @__PURE__ */ createElement(
359
+ Component,
2458
360
  {
2459
361
  ...rest,
2460
362
  children: renderChildren.length ? renderChildren : void 0,
@@ -2473,7 +375,7 @@ var ItemComponent = memo2(({ instance }) => {
2473
375
  return null;
2474
376
  });
2475
377
  ItemComponent.displayName = "WeaverseComponent";
2476
- var ItemInstance = memo2(
378
+ var ItemInstance = memo(
2477
379
  ({ id, parentId }) => {
2478
380
  let instance = useItemInstance(id);
2479
381
  if (!instance) {
@@ -2492,29 +394,12 @@ export {
2492
394
  WeaverseContextProvider,
2493
395
  WeaverseItemContext,
2494
396
  WeaverseRoot,
2495
- createWeaverseDataContext,
2496
397
  replaceContentDataConnectors,
2497
398
  replaceContentDataConnectorsDeep,
2498
399
  useChildInstances,
2499
400
  useItemInstance,
2500
401
  useParentInstance,
2501
402
  useSafeExternalStore,
2502
- useWeaverse,
2503
- useWeaverseDataContext
403
+ useWeaverse
2504
404
  };
2505
- /*! Bundled license information:
2506
-
2507
- react-router/dist/development/chunk-B7RQU5TL.mjs:
2508
- react-router/dist/development/index.mjs:
2509
- (**
2510
- * react-router v7.9.1
2511
- *
2512
- * Copyright (c) Remix Software Inc.
2513
- *
2514
- * This source code is licensed under the MIT license found in the
2515
- * LICENSE.md file in the root directory of this source tree.
2516
- *
2517
- * @license MIT
2518
- *)
2519
- */
2520
405
  //# sourceMappingURL=index.mjs.map