@hmlr/govuk-react-components-library 1.2.1 → 1.2.3

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.esm.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
2
2
  import { Accordion as Accordion$1, createAll, Button as Button$1, Checkboxes as Checkboxes$1, ErrorSummary as ErrorSummary$1, ExitThisPage as ExitThisPage$1, PasswordInput as PasswordInput$1, Radios as Radios$1, SkipLink as SkipLink$1, Tabs as Tabs$1 } from 'govuk-frontend';
3
- import * as React3 from 'react';
4
- import React3__default, { useContext, useMemo, createElement, Component, useState, useRef, useEffect } from 'react';
3
+ import { Link, useLocation } from 'react-router';
4
+ import * as React from 'react';
5
+ import React__default, { useContext, useMemo, createElement, Component, useState, useRef, useEffect } from 'react';
5
6
 
6
7
  function ConfigureOverallAccordion($scope, config) {
7
8
  if (JSON.stringify(config) === JSON.stringify({})) {
@@ -77,1959 +78,6 @@ const Accordion = ({ headingLevel: HeadingLevel = "h2", items = [], className, i
77
78
  return (jsx("div", { ...remainingAttributes, id: id, className: `govuk-accordion ${className || ""}`, "data-module": "govuk-accordion", children: items.filter(Boolean).map((item, index) => (jsxs("div", { className: `govuk-accordion__section ${item.expanded ? "govuk-accordion__section--expanded" : ""}`, children: [jsxs("div", { className: "govuk-accordion__section-header", children: [jsx(HeadingLevel, { className: "govuk-accordion__section-heading", children: jsx("span", { className: "govuk-accordion__section-button", id: `${id}-heading-${index + 1}`, children: item.heading?.children }) }), item.summary && (jsx("div", { className: "govuk-accordion__section-summary govuk-body", id: `${id}-summary-${index + 1}`, children: item.summary.children }))] }), jsx("div", { id: `${id}-content-${index + 1}`, className: "govuk-accordion__section-content", "aria-labelledby": `${id}-heading-${index + 1}`, children: item.content?.children })] }, item.reactListKey || index))) }));
78
79
  };
79
80
 
80
- /**
81
- * react-router v7.13.2
82
- *
83
- * Copyright (c) Remix Software Inc.
84
- *
85
- * This source code is licensed under the MIT license found in the
86
- * LICENSE.md file in the root directory of this source tree.
87
- *
88
- * @license MIT
89
- */
90
- function invariant(value, message) {
91
- if (value === false || value === null || typeof value === "undefined") {
92
- throw new Error(message);
93
- }
94
- }
95
- function warning(cond, message) {
96
- if (!cond) {
97
- if (typeof console !== "undefined") console.warn(message);
98
- try {
99
- throw new Error(message);
100
- } catch (e) {
101
- }
102
- }
103
- }
104
- function createPath({
105
- pathname = "/",
106
- search = "",
107
- hash = ""
108
- }) {
109
- if (search && search !== "?")
110
- pathname += search.charAt(0) === "?" ? search : "?" + search;
111
- if (hash && hash !== "#")
112
- pathname += hash.charAt(0) === "#" ? hash : "#" + hash;
113
- return pathname;
114
- }
115
- function parsePath(path) {
116
- let parsedPath = {};
117
- if (path) {
118
- let hashIndex = path.indexOf("#");
119
- if (hashIndex >= 0) {
120
- parsedPath.hash = path.substring(hashIndex);
121
- path = path.substring(0, hashIndex);
122
- }
123
- let searchIndex = path.indexOf("?");
124
- if (searchIndex >= 0) {
125
- parsedPath.search = path.substring(searchIndex);
126
- path = path.substring(0, searchIndex);
127
- }
128
- if (path) {
129
- parsedPath.pathname = path;
130
- }
131
- }
132
- return parsedPath;
133
- }
134
- function matchRoutes(routes, locationArg, basename = "/") {
135
- return matchRoutesImpl(routes, locationArg, basename, false);
136
- }
137
- function matchRoutesImpl(routes, locationArg, basename, allowPartial) {
138
- let location = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
139
- let pathname = stripBasename(location.pathname || "/", basename);
140
- if (pathname == null) {
141
- return null;
142
- }
143
- let branches = flattenRoutes(routes);
144
- rankRouteBranches(branches);
145
- let matches = null;
146
- for (let i = 0; matches == null && i < branches.length; ++i) {
147
- let decoded = decodePath(pathname);
148
- matches = matchRouteBranch(
149
- branches[i],
150
- decoded,
151
- allowPartial
152
- );
153
- }
154
- return matches;
155
- }
156
- function flattenRoutes(routes, branches = [], parentsMeta = [], parentPath = "", _hasParentOptionalSegments = false) {
157
- let flattenRoute = (route, index, hasParentOptionalSegments = _hasParentOptionalSegments, relativePath) => {
158
- let meta = {
159
- relativePath: relativePath === void 0 ? route.path || "" : relativePath,
160
- caseSensitive: route.caseSensitive === true,
161
- childrenIndex: index,
162
- route
163
- };
164
- if (meta.relativePath.startsWith("/")) {
165
- if (!meta.relativePath.startsWith(parentPath) && hasParentOptionalSegments) {
166
- return;
167
- }
168
- invariant(
169
- meta.relativePath.startsWith(parentPath),
170
- `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.`
171
- );
172
- meta.relativePath = meta.relativePath.slice(parentPath.length);
173
- }
174
- let path = joinPaths([parentPath, meta.relativePath]);
175
- let routesMeta = parentsMeta.concat(meta);
176
- if (route.children && route.children.length > 0) {
177
- invariant(
178
- // Our types know better, but runtime JS may not!
179
- // @ts-expect-error
180
- route.index !== true,
181
- `Index routes must not have child routes. Please remove all child routes from route path "${path}".`
182
- );
183
- flattenRoutes(
184
- route.children,
185
- branches,
186
- routesMeta,
187
- path,
188
- hasParentOptionalSegments
189
- );
190
- }
191
- if (route.path == null && !route.index) {
192
- return;
193
- }
194
- branches.push({
195
- path,
196
- score: computeScore(path, route.index),
197
- routesMeta
198
- });
199
- };
200
- routes.forEach((route, index) => {
201
- if (route.path === "" || !route.path?.includes("?")) {
202
- flattenRoute(route, index);
203
- } else {
204
- for (let exploded of explodeOptionalSegments(route.path)) {
205
- flattenRoute(route, index, true, exploded);
206
- }
207
- }
208
- });
209
- return branches;
210
- }
211
- function explodeOptionalSegments(path) {
212
- let segments = path.split("/");
213
- if (segments.length === 0) return [];
214
- let [first, ...rest] = segments;
215
- let isOptional = first.endsWith("?");
216
- let required = first.replace(/\?$/, "");
217
- if (rest.length === 0) {
218
- return isOptional ? [required, ""] : [required];
219
- }
220
- let restExploded = explodeOptionalSegments(rest.join("/"));
221
- let result = [];
222
- result.push(
223
- ...restExploded.map(
224
- (subpath) => subpath === "" ? required : [required, subpath].join("/")
225
- )
226
- );
227
- if (isOptional) {
228
- result.push(...restExploded);
229
- }
230
- return result.map(
231
- (exploded) => path.startsWith("/") && exploded === "" ? "/" : exploded
232
- );
233
- }
234
- function rankRouteBranches(branches) {
235
- branches.sort(
236
- (a, b) => a.score !== b.score ? b.score - a.score : compareIndexes(
237
- a.routesMeta.map((meta) => meta.childrenIndex),
238
- b.routesMeta.map((meta) => meta.childrenIndex)
239
- )
240
- );
241
- }
242
- var paramRe = /^:[\w-]+$/;
243
- var dynamicSegmentValue = 3;
244
- var indexRouteValue = 2;
245
- var emptySegmentValue = 1;
246
- var staticSegmentValue = 10;
247
- var splatPenalty = -2;
248
- var isSplat = (s) => s === "*";
249
- function computeScore(path, index) {
250
- let segments = path.split("/");
251
- let initialScore = segments.length;
252
- if (segments.some(isSplat)) {
253
- initialScore += splatPenalty;
254
- }
255
- if (index) {
256
- initialScore += indexRouteValue;
257
- }
258
- return segments.filter((s) => !isSplat(s)).reduce(
259
- (score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : segment === "" ? emptySegmentValue : staticSegmentValue),
260
- initialScore
261
- );
262
- }
263
- function compareIndexes(a, b) {
264
- let siblings = a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);
265
- return siblings ? (
266
- // If two routes are siblings, we should try to match the earlier sibling
267
- // first. This allows people to have fine-grained control over the matching
268
- // behavior by simply putting routes with identical paths in the order they
269
- // want them tried.
270
- a[a.length - 1] - b[b.length - 1]
271
- ) : (
272
- // Otherwise, it doesn't really make sense to rank non-siblings by index,
273
- // so they sort equally.
274
- 0
275
- );
276
- }
277
- function matchRouteBranch(branch, pathname, allowPartial = false) {
278
- let { routesMeta } = branch;
279
- let matchedParams = {};
280
- let matchedPathname = "/";
281
- let matches = [];
282
- for (let i = 0; i < routesMeta.length; ++i) {
283
- let meta = routesMeta[i];
284
- let end = i === routesMeta.length - 1;
285
- let remainingPathname = matchedPathname === "/" ? pathname : pathname.slice(matchedPathname.length) || "/";
286
- let match = matchPath(
287
- { path: meta.relativePath, caseSensitive: meta.caseSensitive, end },
288
- remainingPathname
289
- );
290
- let route = meta.route;
291
- if (!match && end && allowPartial && !routesMeta[routesMeta.length - 1].route.index) {
292
- match = matchPath(
293
- {
294
- path: meta.relativePath,
295
- caseSensitive: meta.caseSensitive,
296
- end: false
297
- },
298
- remainingPathname
299
- );
300
- }
301
- if (!match) {
302
- return null;
303
- }
304
- Object.assign(matchedParams, match.params);
305
- matches.push({
306
- // TODO: Can this as be avoided?
307
- params: matchedParams,
308
- pathname: joinPaths([matchedPathname, match.pathname]),
309
- pathnameBase: normalizePathname(
310
- joinPaths([matchedPathname, match.pathnameBase])
311
- ),
312
- route
313
- });
314
- if (match.pathnameBase !== "/") {
315
- matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);
316
- }
317
- }
318
- return matches;
319
- }
320
- function matchPath(pattern, pathname) {
321
- if (typeof pattern === "string") {
322
- pattern = { path: pattern, caseSensitive: false, end: true };
323
- }
324
- let [matcher, compiledParams] = compilePath(
325
- pattern.path,
326
- pattern.caseSensitive,
327
- pattern.end
328
- );
329
- let match = pathname.match(matcher);
330
- if (!match) return null;
331
- let matchedPathname = match[0];
332
- let pathnameBase = matchedPathname.replace(/(.)\/+$/, "$1");
333
- let captureGroups = match.slice(1);
334
- let params = compiledParams.reduce(
335
- (memo2, { paramName, isOptional }, index) => {
336
- if (paramName === "*") {
337
- let splatValue = captureGroups[index] || "";
338
- pathnameBase = matchedPathname.slice(0, matchedPathname.length - splatValue.length).replace(/(.)\/+$/, "$1");
339
- }
340
- const value = captureGroups[index];
341
- if (isOptional && !value) {
342
- memo2[paramName] = void 0;
343
- } else {
344
- memo2[paramName] = (value || "").replace(/%2F/g, "/");
345
- }
346
- return memo2;
347
- },
348
- {}
349
- );
350
- return {
351
- params,
352
- pathname: matchedPathname,
353
- pathnameBase,
354
- pattern
355
- };
356
- }
357
- function compilePath(path, caseSensitive = false, end = true) {
358
- warning(
359
- path === "*" || !path.endsWith("*") || path.endsWith("/*"),
360
- `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(/\*$/, "/*")}".`
361
- );
362
- let params = [];
363
- let regexpSource = "^" + path.replace(/\/*\*?$/, "").replace(/^\/*/, "/").replace(/[\\.*+^${}|()[\]]/g, "\\$&").replace(
364
- /\/:([\w-]+)(\?)?/g,
365
- (match, paramName, isOptional, index, str) => {
366
- params.push({ paramName, isOptional: isOptional != null });
367
- if (isOptional) {
368
- let nextChar = str.charAt(index + match.length);
369
- if (nextChar && nextChar !== "/") {
370
- return "/([^\\/]*)";
371
- }
372
- return "(?:/([^\\/]*))?";
373
- }
374
- return "/([^\\/]+)";
375
- }
376
- ).replace(/\/([\w-]+)\?(\/|$)/g, "(/$1)?$2");
377
- if (path.endsWith("*")) {
378
- params.push({ paramName: "*" });
379
- regexpSource += path === "*" || path === "/*" ? "(.*)$" : "(?:\\/(.+)|\\/*)$";
380
- } else if (end) {
381
- regexpSource += "\\/*$";
382
- } else if (path !== "" && path !== "/") {
383
- regexpSource += "(?:(?=\\/|$))";
384
- } else ;
385
- let matcher = new RegExp(regexpSource, caseSensitive ? void 0 : "i");
386
- return [matcher, params];
387
- }
388
- function decodePath(value) {
389
- try {
390
- return value.split("/").map((v) => decodeURIComponent(v).replace(/\//g, "%2F")).join("/");
391
- } catch (error) {
392
- warning(
393
- false,
394
- `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}).`
395
- );
396
- return value;
397
- }
398
- }
399
- function stripBasename(pathname, basename) {
400
- if (basename === "/") return pathname;
401
- if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {
402
- return null;
403
- }
404
- let startIndex = basename.endsWith("/") ? basename.length - 1 : basename.length;
405
- let nextChar = pathname.charAt(startIndex);
406
- if (nextChar && nextChar !== "/") {
407
- return null;
408
- }
409
- return pathname.slice(startIndex) || "/";
410
- }
411
- var ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
412
- function resolvePath(to, fromPathname = "/") {
413
- let {
414
- pathname: toPathname,
415
- search = "",
416
- hash = ""
417
- } = typeof to === "string" ? parsePath(to) : to;
418
- let pathname;
419
- if (toPathname) {
420
- toPathname = toPathname.replace(/\/\/+/g, "/");
421
- if (toPathname.startsWith("/")) {
422
- pathname = resolvePathname(toPathname.substring(1), "/");
423
- } else {
424
- pathname = resolvePathname(toPathname, fromPathname);
425
- }
426
- } else {
427
- pathname = fromPathname;
428
- }
429
- return {
430
- pathname,
431
- search: normalizeSearch(search),
432
- hash: normalizeHash(hash)
433
- };
434
- }
435
- function resolvePathname(relativePath, fromPathname) {
436
- let segments = fromPathname.replace(/\/+$/, "").split("/");
437
- let relativeSegments = relativePath.split("/");
438
- relativeSegments.forEach((segment) => {
439
- if (segment === "..") {
440
- if (segments.length > 1) segments.pop();
441
- } else if (segment !== ".") {
442
- segments.push(segment);
443
- }
444
- });
445
- return segments.length > 1 ? segments.join("/") : "/";
446
- }
447
- function getInvalidPathError(char, field, dest, path) {
448
- return `Cannot include a '${char}' character in a manually specified \`to.${field}\` field [${JSON.stringify(
449
- path
450
- )}]. 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.`;
451
- }
452
- function getPathContributingMatches(matches) {
453
- return matches.filter(
454
- (match, index) => index === 0 || match.route.path && match.route.path.length > 0
455
- );
456
- }
457
- function getResolveToMatches(matches) {
458
- let pathMatches = getPathContributingMatches(matches);
459
- return pathMatches.map(
460
- (match, idx) => idx === pathMatches.length - 1 ? match.pathname : match.pathnameBase
461
- );
462
- }
463
- function resolveTo(toArg, routePathnames, locationPathname, isPathRelative = false) {
464
- let to;
465
- if (typeof toArg === "string") {
466
- to = parsePath(toArg);
467
- } else {
468
- to = { ...toArg };
469
- invariant(
470
- !to.pathname || !to.pathname.includes("?"),
471
- getInvalidPathError("?", "pathname", "search", to)
472
- );
473
- invariant(
474
- !to.pathname || !to.pathname.includes("#"),
475
- getInvalidPathError("#", "pathname", "hash", to)
476
- );
477
- invariant(
478
- !to.search || !to.search.includes("#"),
479
- getInvalidPathError("#", "search", "hash", to)
480
- );
481
- }
482
- let isEmptyPath = toArg === "" || to.pathname === "";
483
- let toPathname = isEmptyPath ? "/" : to.pathname;
484
- let from;
485
- if (toPathname == null) {
486
- from = locationPathname;
487
- } else {
488
- let routePathnameIndex = routePathnames.length - 1;
489
- if (!isPathRelative && toPathname.startsWith("..")) {
490
- let toSegments = toPathname.split("/");
491
- while (toSegments[0] === "..") {
492
- toSegments.shift();
493
- routePathnameIndex -= 1;
494
- }
495
- to.pathname = toSegments.join("/");
496
- }
497
- from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : "/";
498
- }
499
- let path = resolvePath(to, from);
500
- let hasExplicitTrailingSlash = toPathname && toPathname !== "/" && toPathname.endsWith("/");
501
- let hasCurrentTrailingSlash = (isEmptyPath || toPathname === ".") && locationPathname.endsWith("/");
502
- if (!path.pathname.endsWith("/") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) {
503
- path.pathname += "/";
504
- }
505
- return path;
506
- }
507
- var joinPaths = (paths) => paths.join("/").replace(/\/\/+/g, "/");
508
- var normalizePathname = (pathname) => pathname.replace(/\/+$/, "").replace(/^\/*/, "/");
509
- var normalizeSearch = (search) => !search || search === "?" ? "" : search.startsWith("?") ? search : "?" + search;
510
- var normalizeHash = (hash) => !hash || hash === "#" ? "" : hash.startsWith("#") ? hash : "#" + hash;
511
- var ErrorResponseImpl = class {
512
- constructor(status, statusText, data2, internal = false) {
513
- this.status = status;
514
- this.statusText = statusText || "";
515
- this.internal = internal;
516
- if (data2 instanceof Error) {
517
- this.data = data2.toString();
518
- this.error = data2;
519
- } else {
520
- this.data = data2;
521
- }
522
- }
523
- };
524
- function isRouteErrorResponse(error) {
525
- return error != null && typeof error.status === "number" && typeof error.statusText === "string" && typeof error.internal === "boolean" && "data" in error;
526
- }
527
- function getRoutePattern(matches) {
528
- return matches.map((m) => m.route.path).filter(Boolean).join("/").replace(/\/\/*/g, "/") || "/";
529
- }
530
- var isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined";
531
- function parseToInfo(_to, basename) {
532
- let to = _to;
533
- if (typeof to !== "string" || !ABSOLUTE_URL_REGEX.test(to)) {
534
- return {
535
- absoluteURL: void 0,
536
- isExternal: false,
537
- to
538
- };
539
- }
540
- let absoluteURL = to;
541
- let isExternal = false;
542
- if (isBrowser) {
543
- try {
544
- let currentUrl = new URL(window.location.href);
545
- let targetUrl = to.startsWith("//") ? new URL(currentUrl.protocol + to) : new URL(to);
546
- let path = stripBasename(targetUrl.pathname, basename);
547
- if (targetUrl.origin === currentUrl.origin && path != null) {
548
- to = path + targetUrl.search + targetUrl.hash;
549
- } else {
550
- isExternal = true;
551
- }
552
- } catch (e) {
553
- warning(
554
- false,
555
- `<Link to="${to}"> contains an invalid URL which will probably break when clicked - please update to a valid URL path.`
556
- );
557
- }
558
- }
559
- return {
560
- absoluteURL,
561
- isExternal,
562
- to
563
- };
564
- }
565
- Object.getOwnPropertyNames(Object.prototype).sort().join("\0");
566
-
567
- // lib/router/router.ts
568
- var validMutationMethodsArr = [
569
- "POST",
570
- "PUT",
571
- "PATCH",
572
- "DELETE"
573
- ];
574
- new Set(
575
- validMutationMethodsArr
576
- );
577
- var validRequestMethodsArr = [
578
- "GET",
579
- ...validMutationMethodsArr
580
- ];
581
- new Set(validRequestMethodsArr);
582
- var DataRouterContext = React3.createContext(null);
583
- DataRouterContext.displayName = "DataRouter";
584
- var DataRouterStateContext = React3.createContext(null);
585
- DataRouterStateContext.displayName = "DataRouterState";
586
- var RSCRouterContext = React3.createContext(false);
587
- var ViewTransitionContext = React3.createContext({
588
- isTransitioning: false
589
- });
590
- ViewTransitionContext.displayName = "ViewTransition";
591
- var FetchersContext = React3.createContext(
592
- /* @__PURE__ */ new Map()
593
- );
594
- FetchersContext.displayName = "Fetchers";
595
- var AwaitContext = React3.createContext(null);
596
- AwaitContext.displayName = "Await";
597
- var NavigationContext = React3.createContext(
598
- null
599
- );
600
- NavigationContext.displayName = "Navigation";
601
- var LocationContext = React3.createContext(
602
- null
603
- );
604
- LocationContext.displayName = "Location";
605
- var RouteContext = React3.createContext({
606
- outlet: null,
607
- matches: [],
608
- isDataRoute: false
609
- });
610
- RouteContext.displayName = "Route";
611
- var RouteErrorContext = React3.createContext(null);
612
- RouteErrorContext.displayName = "RouteError";
613
-
614
- // lib/errors.ts
615
- var ERROR_DIGEST_BASE = "REACT_ROUTER_ERROR";
616
- var ERROR_DIGEST_REDIRECT = "REDIRECT";
617
- var ERROR_DIGEST_ROUTE_ERROR_RESPONSE = "ROUTE_ERROR_RESPONSE";
618
- function decodeRedirectErrorDigest(digest) {
619
- if (digest.startsWith(`${ERROR_DIGEST_BASE}:${ERROR_DIGEST_REDIRECT}:{`)) {
620
- try {
621
- let parsed = JSON.parse(digest.slice(28));
622
- if (typeof parsed === "object" && parsed && typeof parsed.status === "number" && typeof parsed.statusText === "string" && typeof parsed.location === "string" && typeof parsed.reloadDocument === "boolean" && typeof parsed.replace === "boolean") {
623
- return parsed;
624
- }
625
- } catch {
626
- }
627
- }
628
- }
629
- function decodeRouteErrorResponseDigest(digest) {
630
- if (digest.startsWith(
631
- `${ERROR_DIGEST_BASE}:${ERROR_DIGEST_ROUTE_ERROR_RESPONSE}:{`
632
- )) {
633
- try {
634
- let parsed = JSON.parse(digest.slice(40));
635
- if (typeof parsed === "object" && parsed && typeof parsed.status === "number" && typeof parsed.statusText === "string") {
636
- return new ErrorResponseImpl(
637
- parsed.status,
638
- parsed.statusText,
639
- parsed.data
640
- );
641
- }
642
- } catch {
643
- }
644
- }
645
- }
646
-
647
- // lib/hooks.tsx
648
- function useHref(to, { relative } = {}) {
649
- invariant(
650
- useInRouterContext(),
651
- // TODO: This error is probably because they somehow have 2 versions of the
652
- // router loaded. We can help them understand how to avoid that.
653
- `useHref() may be used only in the context of a <Router> component.`
654
- );
655
- let { basename, navigator } = React3.useContext(NavigationContext);
656
- let { hash, pathname, search } = useResolvedPath(to, { relative });
657
- let joinedPathname = pathname;
658
- if (basename !== "/") {
659
- joinedPathname = pathname === "/" ? basename : joinPaths([basename, pathname]);
660
- }
661
- return navigator.createHref({ pathname: joinedPathname, search, hash });
662
- }
663
- function useInRouterContext() {
664
- return React3.useContext(LocationContext) != null;
665
- }
666
- function useLocation() {
667
- invariant(
668
- useInRouterContext(),
669
- // TODO: This error is probably because they somehow have 2 versions of the
670
- // router loaded. We can help them understand how to avoid that.
671
- `useLocation() may be used only in the context of a <Router> component.`
672
- );
673
- return React3.useContext(LocationContext).location;
674
- }
675
- var navigateEffectWarning = `You should call navigate() in a React.useEffect(), not when your component is first rendered.`;
676
- function useIsomorphicLayoutEffect(cb) {
677
- let isStatic = React3.useContext(NavigationContext).static;
678
- if (!isStatic) {
679
- React3.useLayoutEffect(cb);
680
- }
681
- }
682
- function useNavigate() {
683
- let { isDataRoute } = React3.useContext(RouteContext);
684
- return isDataRoute ? useNavigateStable() : useNavigateUnstable();
685
- }
686
- function useNavigateUnstable() {
687
- invariant(
688
- useInRouterContext(),
689
- // TODO: This error is probably because they somehow have 2 versions of the
690
- // router loaded. We can help them understand how to avoid that.
691
- `useNavigate() may be used only in the context of a <Router> component.`
692
- );
693
- let dataRouterContext = React3.useContext(DataRouterContext);
694
- let { basename, navigator } = React3.useContext(NavigationContext);
695
- let { matches } = React3.useContext(RouteContext);
696
- let { pathname: locationPathname } = useLocation();
697
- let routePathnamesJson = JSON.stringify(getResolveToMatches(matches));
698
- let activeRef = React3.useRef(false);
699
- useIsomorphicLayoutEffect(() => {
700
- activeRef.current = true;
701
- });
702
- let navigate = React3.useCallback(
703
- (to, options = {}) => {
704
- warning(activeRef.current, navigateEffectWarning);
705
- if (!activeRef.current) return;
706
- if (typeof to === "number") {
707
- navigator.go(to);
708
- return;
709
- }
710
- let path = resolveTo(
711
- to,
712
- JSON.parse(routePathnamesJson),
713
- locationPathname,
714
- options.relative === "path"
715
- );
716
- if (dataRouterContext == null && basename !== "/") {
717
- path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
718
- }
719
- (!!options.replace ? navigator.replace : navigator.push)(
720
- path,
721
- options.state,
722
- options
723
- );
724
- },
725
- [
726
- basename,
727
- navigator,
728
- routePathnamesJson,
729
- locationPathname,
730
- dataRouterContext
731
- ]
732
- );
733
- return navigate;
734
- }
735
- React3.createContext(null);
736
- function useResolvedPath(to, { relative } = {}) {
737
- let { matches } = React3.useContext(RouteContext);
738
- let { pathname: locationPathname } = useLocation();
739
- let routePathnamesJson = JSON.stringify(getResolveToMatches(matches));
740
- return React3.useMemo(
741
- () => resolveTo(
742
- to,
743
- JSON.parse(routePathnamesJson),
744
- locationPathname,
745
- relative === "path"
746
- ),
747
- [to, routePathnamesJson, locationPathname, relative]
748
- );
749
- }
750
- function useRoutesImpl(routes, locationArg, dataRouterOpts) {
751
- invariant(
752
- useInRouterContext(),
753
- // TODO: This error is probably because they somehow have 2 versions of the
754
- // router loaded. We can help them understand how to avoid that.
755
- `useRoutes() may be used only in the context of a <Router> component.`
756
- );
757
- let { navigator } = React3.useContext(NavigationContext);
758
- let { matches: parentMatches } = React3.useContext(RouteContext);
759
- let routeMatch = parentMatches[parentMatches.length - 1];
760
- let parentParams = routeMatch ? routeMatch.params : {};
761
- let parentPathname = routeMatch ? routeMatch.pathname : "/";
762
- let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : "/";
763
- let parentRoute = routeMatch && routeMatch.route;
764
- {
765
- let parentPath = parentRoute && parentRoute.path || "";
766
- warningOnce(
767
- parentPathname,
768
- !parentRoute || parentPath.endsWith("*") || parentPath.endsWith("*?"),
769
- `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.
770
-
771
- Please change the parent <Route path="${parentPath}"> to <Route path="${parentPath === "/" ? "*" : `${parentPath}/*`}">.`
772
- );
773
- }
774
- let locationFromContext = useLocation();
775
- let location;
776
- {
777
- location = locationFromContext;
778
- }
779
- let pathname = location.pathname || "/";
780
- let remainingPathname = pathname;
781
- if (parentPathnameBase !== "/") {
782
- let parentSegments = parentPathnameBase.replace(/^\//, "").split("/");
783
- let segments = pathname.replace(/^\//, "").split("/");
784
- remainingPathname = "/" + segments.slice(parentSegments.length).join("/");
785
- }
786
- let matches = matchRoutes(routes, { pathname: remainingPathname });
787
- {
788
- warning(
789
- parentRoute || matches != null,
790
- `No routes matched location "${location.pathname}${location.search}${location.hash}" `
791
- );
792
- warning(
793
- 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,
794
- `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.`
795
- );
796
- }
797
- let renderedMatches = _renderMatches(
798
- matches && matches.map(
799
- (match) => Object.assign({}, match, {
800
- params: Object.assign({}, parentParams, match.params),
801
- pathname: joinPaths([
802
- parentPathnameBase,
803
- // Re-encode pathnames that were decoded inside matchRoutes.
804
- // Pre-encode `%`, `?` and `#` ahead of `encodeLocation` because it uses
805
- // `new URL()` internally and we need to prevent it from treating
806
- // them as separators
807
- navigator.encodeLocation ? navigator.encodeLocation(
808
- match.pathname.replace(/%/g, "%25").replace(/\?/g, "%3F").replace(/#/g, "%23")
809
- ).pathname : match.pathname
810
- ]),
811
- pathnameBase: match.pathnameBase === "/" ? parentPathnameBase : joinPaths([
812
- parentPathnameBase,
813
- // Re-encode pathnames that were decoded inside matchRoutes
814
- // Pre-encode `%`, `?` and `#` ahead of `encodeLocation` because it uses
815
- // `new URL()` internally and we need to prevent it from treating
816
- // them as separators
817
- navigator.encodeLocation ? navigator.encodeLocation(
818
- match.pathnameBase.replace(/%/g, "%25").replace(/\?/g, "%3F").replace(/#/g, "%23")
819
- ).pathname : match.pathnameBase
820
- ])
821
- })
822
- ),
823
- parentMatches,
824
- dataRouterOpts
825
- );
826
- return renderedMatches;
827
- }
828
- function DefaultErrorComponent() {
829
- let error = useRouteError();
830
- let message = isRouteErrorResponse(error) ? `${error.status} ${error.statusText}` : error instanceof Error ? error.message : JSON.stringify(error);
831
- let stack = error instanceof Error ? error.stack : null;
832
- let lightgrey = "rgba(200,200,200, 0.5)";
833
- let preStyles = { padding: "0.5rem", backgroundColor: lightgrey };
834
- let codeStyles = { padding: "2px 4px", backgroundColor: lightgrey };
835
- let devInfo = null;
836
- {
837
- console.error(
838
- "Error handled by React Router default ErrorBoundary:",
839
- error
840
- );
841
- devInfo = /* @__PURE__ */ React3.createElement(React3.Fragment, null, /* @__PURE__ */ React3.createElement("p", null, "\u{1F4BF} Hey developer \u{1F44B}"), /* @__PURE__ */ React3.createElement("p", null, "You can provide a way better UX than this when your app throws errors by providing your own ", /* @__PURE__ */ React3.createElement("code", { style: codeStyles }, "ErrorBoundary"), " or", " ", /* @__PURE__ */ React3.createElement("code", { style: codeStyles }, "errorElement"), " prop on your route."));
842
- }
843
- return /* @__PURE__ */ React3.createElement(React3.Fragment, null, /* @__PURE__ */ React3.createElement("h2", null, "Unexpected Application Error!"), /* @__PURE__ */ React3.createElement("h3", { style: { fontStyle: "italic" } }, message), stack ? /* @__PURE__ */ React3.createElement("pre", { style: preStyles }, stack) : null, devInfo);
844
- }
845
- var defaultErrorElement = /* @__PURE__ */ React3.createElement(DefaultErrorComponent, null);
846
- var RenderErrorBoundary = class extends React3.Component {
847
- constructor(props) {
848
- super(props);
849
- this.state = {
850
- location: props.location,
851
- revalidation: props.revalidation,
852
- error: props.error
853
- };
854
- }
855
- static getDerivedStateFromError(error) {
856
- return { error };
857
- }
858
- static getDerivedStateFromProps(props, state) {
859
- if (state.location !== props.location || state.revalidation !== "idle" && props.revalidation === "idle") {
860
- return {
861
- error: props.error,
862
- location: props.location,
863
- revalidation: props.revalidation
864
- };
865
- }
866
- return {
867
- error: props.error !== void 0 ? props.error : state.error,
868
- location: state.location,
869
- revalidation: props.revalidation || state.revalidation
870
- };
871
- }
872
- componentDidCatch(error, errorInfo) {
873
- if (this.props.onError) {
874
- this.props.onError(error, errorInfo);
875
- } else {
876
- console.error(
877
- "React Router caught the following error during render",
878
- error
879
- );
880
- }
881
- }
882
- render() {
883
- let error = this.state.error;
884
- if (this.context && typeof error === "object" && error && "digest" in error && typeof error.digest === "string") {
885
- const decoded = decodeRouteErrorResponseDigest(error.digest);
886
- if (decoded) error = decoded;
887
- }
888
- let result = error !== void 0 ? /* @__PURE__ */ React3.createElement(RouteContext.Provider, { value: this.props.routeContext }, /* @__PURE__ */ React3.createElement(
889
- RouteErrorContext.Provider,
890
- {
891
- value: error,
892
- children: this.props.component
893
- }
894
- )) : this.props.children;
895
- if (this.context) {
896
- return /* @__PURE__ */ React3.createElement(RSCErrorHandler, { error }, result);
897
- }
898
- return result;
899
- }
900
- };
901
- RenderErrorBoundary.contextType = RSCRouterContext;
902
- var errorRedirectHandledMap = /* @__PURE__ */ new WeakMap();
903
- function RSCErrorHandler({
904
- children,
905
- error
906
- }) {
907
- let { basename } = React3.useContext(NavigationContext);
908
- if (typeof error === "object" && error && "digest" in error && typeof error.digest === "string") {
909
- let redirect2 = decodeRedirectErrorDigest(error.digest);
910
- if (redirect2) {
911
- let existingRedirect = errorRedirectHandledMap.get(error);
912
- if (existingRedirect) throw existingRedirect;
913
- let parsed = parseToInfo(redirect2.location, basename);
914
- if (isBrowser && !errorRedirectHandledMap.get(error)) {
915
- if (parsed.isExternal || redirect2.reloadDocument) {
916
- window.location.href = parsed.absoluteURL || parsed.to;
917
- } else {
918
- const redirectPromise = Promise.resolve().then(
919
- () => window.__reactRouterDataRouter.navigate(parsed.to, {
920
- replace: redirect2.replace
921
- })
922
- );
923
- errorRedirectHandledMap.set(error, redirectPromise);
924
- throw redirectPromise;
925
- }
926
- }
927
- return /* @__PURE__ */ React3.createElement(
928
- "meta",
929
- {
930
- httpEquiv: "refresh",
931
- content: `0;url=${parsed.absoluteURL || parsed.to}`
932
- }
933
- );
934
- }
935
- }
936
- return children;
937
- }
938
- function RenderedRoute({ routeContext, match, children }) {
939
- let dataRouterContext = React3.useContext(DataRouterContext);
940
- if (dataRouterContext && dataRouterContext.static && dataRouterContext.staticContext && (match.route.errorElement || match.route.ErrorBoundary)) {
941
- dataRouterContext.staticContext._deepestRenderedBoundaryId = match.route.id;
942
- }
943
- return /* @__PURE__ */ React3.createElement(RouteContext.Provider, { value: routeContext }, children);
944
- }
945
- function _renderMatches(matches, parentMatches = [], dataRouterOpts) {
946
- let dataRouterState = dataRouterOpts?.state;
947
- if (matches == null) {
948
- if (!dataRouterState) {
949
- return null;
950
- }
951
- if (dataRouterState.errors) {
952
- matches = dataRouterState.matches;
953
- } else if (parentMatches.length === 0 && !dataRouterState.initialized && dataRouterState.matches.length > 0) {
954
- matches = dataRouterState.matches;
955
- } else {
956
- return null;
957
- }
958
- }
959
- let renderedMatches = matches;
960
- let errors = dataRouterState?.errors;
961
- if (errors != null) {
962
- let errorIndex = renderedMatches.findIndex(
963
- (m) => m.route.id && errors?.[m.route.id] !== void 0
964
- );
965
- invariant(
966
- errorIndex >= 0,
967
- `Could not find a matching route for errors on route IDs: ${Object.keys(
968
- errors
969
- ).join(",")}`
970
- );
971
- renderedMatches = renderedMatches.slice(
972
- 0,
973
- Math.min(renderedMatches.length, errorIndex + 1)
974
- );
975
- }
976
- let renderFallback = false;
977
- let fallbackIndex = -1;
978
- if (dataRouterOpts && dataRouterState) {
979
- renderFallback = dataRouterState.renderFallback;
980
- for (let i = 0; i < renderedMatches.length; i++) {
981
- let match = renderedMatches[i];
982
- if (match.route.HydrateFallback || match.route.hydrateFallbackElement) {
983
- fallbackIndex = i;
984
- }
985
- if (match.route.id) {
986
- let { loaderData, errors: errors2 } = dataRouterState;
987
- let needsToRunLoader = match.route.loader && !loaderData.hasOwnProperty(match.route.id) && (!errors2 || errors2[match.route.id] === void 0);
988
- if (match.route.lazy || needsToRunLoader) {
989
- if (dataRouterOpts.isStatic) {
990
- renderFallback = true;
991
- }
992
- if (fallbackIndex >= 0) {
993
- renderedMatches = renderedMatches.slice(0, fallbackIndex + 1);
994
- } else {
995
- renderedMatches = [renderedMatches[0]];
996
- }
997
- break;
998
- }
999
- }
1000
- }
1001
- }
1002
- let onErrorHandler = dataRouterOpts?.onError;
1003
- let onError = dataRouterState && onErrorHandler ? (error, errorInfo) => {
1004
- onErrorHandler(error, {
1005
- location: dataRouterState.location,
1006
- params: dataRouterState.matches?.[0]?.params ?? {},
1007
- unstable_pattern: getRoutePattern(dataRouterState.matches),
1008
- errorInfo
1009
- });
1010
- } : void 0;
1011
- return renderedMatches.reduceRight(
1012
- (outlet, match, index) => {
1013
- let error;
1014
- let shouldRenderHydrateFallback = false;
1015
- let errorElement = null;
1016
- let hydrateFallbackElement = null;
1017
- if (dataRouterState) {
1018
- error = errors && match.route.id ? errors[match.route.id] : void 0;
1019
- errorElement = match.route.errorElement || defaultErrorElement;
1020
- if (renderFallback) {
1021
- if (fallbackIndex < 0 && index === 0) {
1022
- warningOnce(
1023
- "route-fallback",
1024
- false,
1025
- "No `HydrateFallback` element provided to render during initial hydration"
1026
- );
1027
- shouldRenderHydrateFallback = true;
1028
- hydrateFallbackElement = null;
1029
- } else if (fallbackIndex === index) {
1030
- shouldRenderHydrateFallback = true;
1031
- hydrateFallbackElement = match.route.hydrateFallbackElement || null;
1032
- }
1033
- }
1034
- }
1035
- let matches2 = parentMatches.concat(renderedMatches.slice(0, index + 1));
1036
- let getChildren = () => {
1037
- let children;
1038
- if (error) {
1039
- children = errorElement;
1040
- } else if (shouldRenderHydrateFallback) {
1041
- children = hydrateFallbackElement;
1042
- } else if (match.route.Component) {
1043
- children = /* @__PURE__ */ React3.createElement(match.route.Component, null);
1044
- } else if (match.route.element) {
1045
- children = match.route.element;
1046
- } else {
1047
- children = outlet;
1048
- }
1049
- return /* @__PURE__ */ React3.createElement(
1050
- RenderedRoute,
1051
- {
1052
- match,
1053
- routeContext: {
1054
- outlet,
1055
- matches: matches2,
1056
- isDataRoute: dataRouterState != null
1057
- },
1058
- children
1059
- }
1060
- );
1061
- };
1062
- return dataRouterState && (match.route.ErrorBoundary || match.route.errorElement || index === 0) ? /* @__PURE__ */ React3.createElement(
1063
- RenderErrorBoundary,
1064
- {
1065
- location: dataRouterState.location,
1066
- revalidation: dataRouterState.revalidation,
1067
- component: errorElement,
1068
- error,
1069
- children: getChildren(),
1070
- routeContext: { outlet: null, matches: matches2, isDataRoute: true },
1071
- onError
1072
- }
1073
- ) : getChildren();
1074
- },
1075
- null
1076
- );
1077
- }
1078
- function getDataRouterConsoleError(hookName) {
1079
- return `${hookName} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`;
1080
- }
1081
- function useDataRouterContext(hookName) {
1082
- let ctx = React3.useContext(DataRouterContext);
1083
- invariant(ctx, getDataRouterConsoleError(hookName));
1084
- return ctx;
1085
- }
1086
- function useDataRouterState(hookName) {
1087
- let state = React3.useContext(DataRouterStateContext);
1088
- invariant(state, getDataRouterConsoleError(hookName));
1089
- return state;
1090
- }
1091
- function useRouteContext(hookName) {
1092
- let route = React3.useContext(RouteContext);
1093
- invariant(route, getDataRouterConsoleError(hookName));
1094
- return route;
1095
- }
1096
- function useCurrentRouteId(hookName) {
1097
- let route = useRouteContext(hookName);
1098
- let thisRoute = route.matches[route.matches.length - 1];
1099
- invariant(
1100
- thisRoute.route.id,
1101
- `${hookName} can only be used on routes that contain a unique "id"`
1102
- );
1103
- return thisRoute.route.id;
1104
- }
1105
- function useRouteId() {
1106
- return useCurrentRouteId("useRouteId" /* UseRouteId */);
1107
- }
1108
- function useRouteError() {
1109
- let error = React3.useContext(RouteErrorContext);
1110
- let state = useDataRouterState("useRouteError" /* UseRouteError */);
1111
- let routeId = useCurrentRouteId("useRouteError" /* UseRouteError */);
1112
- if (error !== void 0) {
1113
- return error;
1114
- }
1115
- return state.errors?.[routeId];
1116
- }
1117
- function useNavigateStable() {
1118
- let { router } = useDataRouterContext("useNavigate" /* UseNavigateStable */);
1119
- let id = useCurrentRouteId("useNavigate" /* UseNavigateStable */);
1120
- let activeRef = React3.useRef(false);
1121
- useIsomorphicLayoutEffect(() => {
1122
- activeRef.current = true;
1123
- });
1124
- let navigate = React3.useCallback(
1125
- async (to, options = {}) => {
1126
- warning(activeRef.current, navigateEffectWarning);
1127
- if (!activeRef.current) return;
1128
- if (typeof to === "number") {
1129
- await router.navigate(to);
1130
- } else {
1131
- await router.navigate(to, { fromRouteId: id, ...options });
1132
- }
1133
- },
1134
- [router, id]
1135
- );
1136
- return navigate;
1137
- }
1138
- var alreadyWarned = {};
1139
- function warningOnce(key, cond, message) {
1140
- if (!cond && !alreadyWarned[key]) {
1141
- alreadyWarned[key] = true;
1142
- warning(false, message);
1143
- }
1144
- }
1145
- React3.memo(DataRoutes);
1146
- function DataRoutes({
1147
- routes,
1148
- future,
1149
- state,
1150
- isStatic,
1151
- onError
1152
- }) {
1153
- return useRoutesImpl(routes, void 0, { state, isStatic, onError});
1154
- }
1155
-
1156
- // lib/dom/dom.ts
1157
- var defaultMethod = "get";
1158
- var defaultEncType = "application/x-www-form-urlencoded";
1159
- function isHtmlElement(object) {
1160
- return typeof HTMLElement !== "undefined" && object instanceof HTMLElement;
1161
- }
1162
- function isButtonElement(object) {
1163
- return isHtmlElement(object) && object.tagName.toLowerCase() === "button";
1164
- }
1165
- function isFormElement(object) {
1166
- return isHtmlElement(object) && object.tagName.toLowerCase() === "form";
1167
- }
1168
- function isInputElement(object) {
1169
- return isHtmlElement(object) && object.tagName.toLowerCase() === "input";
1170
- }
1171
- function isModifiedEvent(event) {
1172
- return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
1173
- }
1174
- function shouldProcessLinkClick(event, target) {
1175
- return event.button === 0 && // Ignore everything but left clicks
1176
- (!target || target === "_self") && // Let browser handle "target=_blank" etc.
1177
- !isModifiedEvent(event);
1178
- }
1179
- var _formDataSupportsSubmitter = null;
1180
- function isFormDataSubmitterSupported() {
1181
- if (_formDataSupportsSubmitter === null) {
1182
- try {
1183
- new FormData(
1184
- document.createElement("form"),
1185
- // @ts-expect-error if FormData supports the submitter parameter, this will throw
1186
- 0
1187
- );
1188
- _formDataSupportsSubmitter = false;
1189
- } catch (e) {
1190
- _formDataSupportsSubmitter = true;
1191
- }
1192
- }
1193
- return _formDataSupportsSubmitter;
1194
- }
1195
- var supportedFormEncTypes = /* @__PURE__ */ new Set([
1196
- "application/x-www-form-urlencoded",
1197
- "multipart/form-data",
1198
- "text/plain"
1199
- ]);
1200
- function getFormEncType(encType) {
1201
- if (encType != null && !supportedFormEncTypes.has(encType)) {
1202
- warning(
1203
- false,
1204
- `"${encType}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${defaultEncType}"`
1205
- );
1206
- return null;
1207
- }
1208
- return encType;
1209
- }
1210
- function getFormSubmissionInfo(target, basename) {
1211
- let method;
1212
- let action;
1213
- let encType;
1214
- let formData;
1215
- let body;
1216
- if (isFormElement(target)) {
1217
- let attr = target.getAttribute("action");
1218
- action = attr ? stripBasename(attr, basename) : null;
1219
- method = target.getAttribute("method") || defaultMethod;
1220
- encType = getFormEncType(target.getAttribute("enctype")) || defaultEncType;
1221
- formData = new FormData(target);
1222
- } else if (isButtonElement(target) || isInputElement(target) && (target.type === "submit" || target.type === "image")) {
1223
- let form = target.form;
1224
- if (form == null) {
1225
- throw new Error(
1226
- `Cannot submit a <button> or <input type="submit"> without a <form>`
1227
- );
1228
- }
1229
- let attr = target.getAttribute("formaction") || form.getAttribute("action");
1230
- action = attr ? stripBasename(attr, basename) : null;
1231
- method = target.getAttribute("formmethod") || form.getAttribute("method") || defaultMethod;
1232
- encType = getFormEncType(target.getAttribute("formenctype")) || getFormEncType(form.getAttribute("enctype")) || defaultEncType;
1233
- formData = new FormData(form, target);
1234
- if (!isFormDataSubmitterSupported()) {
1235
- let { name, type, value } = target;
1236
- if (type === "image") {
1237
- let prefix = name ? `${name}.` : "";
1238
- formData.append(`${prefix}x`, "0");
1239
- formData.append(`${prefix}y`, "0");
1240
- } else if (name) {
1241
- formData.append(name, value);
1242
- }
1243
- }
1244
- } else if (isHtmlElement(target)) {
1245
- throw new Error(
1246
- `Cannot submit element that is not <form>, <button>, or <input type="submit|image">`
1247
- );
1248
- } else {
1249
- method = defaultMethod;
1250
- action = null;
1251
- encType = defaultEncType;
1252
- body = target;
1253
- }
1254
- if (formData && encType === "text/plain") {
1255
- body = formData;
1256
- formData = void 0;
1257
- }
1258
- return { action, method: method.toLowerCase(), encType, formData, body };
1259
- }
1260
- Object.getOwnPropertyNames(Object.prototype).sort().join("\0");
1261
-
1262
- // lib/dom/ssr/invariant.ts
1263
- function invariant2(value, message) {
1264
- if (value === false || value === null || typeof value === "undefined") {
1265
- throw new Error(message);
1266
- }
1267
- }
1268
- function singleFetchUrl(reqUrl, basename, trailingSlashAware, extension) {
1269
- let url = typeof reqUrl === "string" ? new URL(
1270
- reqUrl,
1271
- // This can be called during the SSR flow via PrefetchPageLinksImpl so
1272
- // don't assume window is available
1273
- typeof window === "undefined" ? "server://singlefetch/" : window.location.origin
1274
- ) : reqUrl;
1275
- if (trailingSlashAware) {
1276
- if (url.pathname.endsWith("/")) {
1277
- url.pathname = `${url.pathname}_.${extension}`;
1278
- } else {
1279
- url.pathname = `${url.pathname}.${extension}`;
1280
- }
1281
- } else {
1282
- if (url.pathname === "/") {
1283
- url.pathname = `_root.${extension}`;
1284
- } else if (basename && stripBasename(url.pathname, basename) === "/") {
1285
- url.pathname = `${basename.replace(/\/$/, "")}/_root.${extension}`;
1286
- } else {
1287
- url.pathname = `${url.pathname.replace(/\/$/, "")}.${extension}`;
1288
- }
1289
- }
1290
- return url;
1291
- }
1292
-
1293
- // lib/dom/ssr/routeModules.ts
1294
- async function loadRouteModule(route, routeModulesCache) {
1295
- if (route.id in routeModulesCache) {
1296
- return routeModulesCache[route.id];
1297
- }
1298
- try {
1299
- let routeModule = await import(
1300
- /* @vite-ignore */
1301
- /* webpackIgnore: true */
1302
- route.module
1303
- );
1304
- routeModulesCache[route.id] = routeModule;
1305
- return routeModule;
1306
- } catch (error) {
1307
- console.error(
1308
- `Error loading route module \`${route.module}\`, reloading page...`
1309
- );
1310
- console.error(error);
1311
- if (window.__reactRouterContext && window.__reactRouterContext.isSpaMode && // @ts-expect-error
1312
- import.meta.hot) {
1313
- throw error;
1314
- }
1315
- window.location.reload();
1316
- return new Promise(() => {
1317
- });
1318
- }
1319
- }
1320
- function isHtmlLinkDescriptor(object) {
1321
- if (object == null) {
1322
- return false;
1323
- }
1324
- if (object.href == null) {
1325
- return object.rel === "preload" && typeof object.imageSrcSet === "string" && typeof object.imageSizes === "string";
1326
- }
1327
- return typeof object.rel === "string" && typeof object.href === "string";
1328
- }
1329
- async function getKeyedPrefetchLinks(matches, manifest, routeModules) {
1330
- let links = await Promise.all(
1331
- matches.map(async (match) => {
1332
- let route = manifest.routes[match.route.id];
1333
- if (route) {
1334
- let mod = await loadRouteModule(route, routeModules);
1335
- return mod.links ? mod.links() : [];
1336
- }
1337
- return [];
1338
- })
1339
- );
1340
- return dedupeLinkDescriptors(
1341
- links.flat(1).filter(isHtmlLinkDescriptor).filter((link) => link.rel === "stylesheet" || link.rel === "preload").map(
1342
- (link) => link.rel === "stylesheet" ? { ...link, rel: "prefetch", as: "style" } : { ...link, rel: "prefetch" }
1343
- )
1344
- );
1345
- }
1346
- function getNewMatchesForLinks(page, nextMatches, currentMatches, manifest, location, mode) {
1347
- let isNew = (match, index) => {
1348
- if (!currentMatches[index]) return true;
1349
- return match.route.id !== currentMatches[index].route.id;
1350
- };
1351
- let matchPathChanged = (match, index) => {
1352
- return (
1353
- // param change, /users/123 -> /users/456
1354
- currentMatches[index].pathname !== match.pathname || // splat param changed, which is not present in match.path
1355
- // e.g. /files/images/avatar.jpg -> files/finances.xls
1356
- currentMatches[index].route.path?.endsWith("*") && currentMatches[index].params["*"] !== match.params["*"]
1357
- );
1358
- };
1359
- if (mode === "assets") {
1360
- return nextMatches.filter(
1361
- (match, index) => isNew(match, index) || matchPathChanged(match, index)
1362
- );
1363
- }
1364
- if (mode === "data") {
1365
- return nextMatches.filter((match, index) => {
1366
- let manifestRoute = manifest.routes[match.route.id];
1367
- if (!manifestRoute || !manifestRoute.hasLoader) {
1368
- return false;
1369
- }
1370
- if (isNew(match, index) || matchPathChanged(match, index)) {
1371
- return true;
1372
- }
1373
- if (match.route.shouldRevalidate) {
1374
- let routeChoice = match.route.shouldRevalidate({
1375
- currentUrl: new URL(
1376
- location.pathname + location.search + location.hash,
1377
- window.origin
1378
- ),
1379
- currentParams: currentMatches[0]?.params || {},
1380
- nextUrl: new URL(page, window.origin),
1381
- nextParams: match.params,
1382
- defaultShouldRevalidate: true
1383
- });
1384
- if (typeof routeChoice === "boolean") {
1385
- return routeChoice;
1386
- }
1387
- }
1388
- return true;
1389
- });
1390
- }
1391
- return [];
1392
- }
1393
- function getModuleLinkHrefs(matches, manifest, { includeHydrateFallback } = {}) {
1394
- return dedupeHrefs(
1395
- matches.map((match) => {
1396
- let route = manifest.routes[match.route.id];
1397
- if (!route) return [];
1398
- let hrefs = [route.module];
1399
- if (route.clientActionModule) {
1400
- hrefs = hrefs.concat(route.clientActionModule);
1401
- }
1402
- if (route.clientLoaderModule) {
1403
- hrefs = hrefs.concat(route.clientLoaderModule);
1404
- }
1405
- if (includeHydrateFallback && route.hydrateFallbackModule) {
1406
- hrefs = hrefs.concat(route.hydrateFallbackModule);
1407
- }
1408
- if (route.imports) {
1409
- hrefs = hrefs.concat(route.imports);
1410
- }
1411
- return hrefs;
1412
- }).flat(1)
1413
- );
1414
- }
1415
- function dedupeHrefs(hrefs) {
1416
- return [...new Set(hrefs)];
1417
- }
1418
- function sortKeys(obj) {
1419
- let sorted = {};
1420
- let keys = Object.keys(obj).sort();
1421
- for (let key of keys) {
1422
- sorted[key] = obj[key];
1423
- }
1424
- return sorted;
1425
- }
1426
- function dedupeLinkDescriptors(descriptors, preloads) {
1427
- let set = /* @__PURE__ */ new Set();
1428
- new Set(preloads);
1429
- return descriptors.reduce((deduped, descriptor) => {
1430
- let key = JSON.stringify(sortKeys(descriptor));
1431
- if (!set.has(key)) {
1432
- set.add(key);
1433
- deduped.push({ key, link: descriptor });
1434
- }
1435
- return deduped;
1436
- }, []);
1437
- }
1438
-
1439
- // lib/dom/ssr/components.tsx
1440
- function useDataRouterContext2() {
1441
- let context = React3.useContext(DataRouterContext);
1442
- invariant2(
1443
- context,
1444
- "You must render this element inside a <DataRouterContext.Provider> element"
1445
- );
1446
- return context;
1447
- }
1448
- function useDataRouterStateContext() {
1449
- let context = React3.useContext(DataRouterStateContext);
1450
- invariant2(
1451
- context,
1452
- "You must render this element inside a <DataRouterStateContext.Provider> element"
1453
- );
1454
- return context;
1455
- }
1456
- var FrameworkContext = React3.createContext(void 0);
1457
- FrameworkContext.displayName = "FrameworkContext";
1458
- function useFrameworkContext() {
1459
- let context = React3.useContext(FrameworkContext);
1460
- invariant2(
1461
- context,
1462
- "You must render this element inside a <HydratedRouter> element"
1463
- );
1464
- return context;
1465
- }
1466
- function usePrefetchBehavior(prefetch, theirElementProps) {
1467
- let frameworkContext = React3.useContext(FrameworkContext);
1468
- let [maybePrefetch, setMaybePrefetch] = React3.useState(false);
1469
- let [shouldPrefetch, setShouldPrefetch] = React3.useState(false);
1470
- let { onFocus, onBlur, onMouseEnter, onMouseLeave, onTouchStart } = theirElementProps;
1471
- let ref = React3.useRef(null);
1472
- React3.useEffect(() => {
1473
- if (prefetch === "render") {
1474
- setShouldPrefetch(true);
1475
- }
1476
- if (prefetch === "viewport") {
1477
- let callback = (entries) => {
1478
- entries.forEach((entry) => {
1479
- setShouldPrefetch(entry.isIntersecting);
1480
- });
1481
- };
1482
- let observer = new IntersectionObserver(callback, { threshold: 0.5 });
1483
- if (ref.current) observer.observe(ref.current);
1484
- return () => {
1485
- observer.disconnect();
1486
- };
1487
- }
1488
- }, [prefetch]);
1489
- React3.useEffect(() => {
1490
- if (maybePrefetch) {
1491
- let id = setTimeout(() => {
1492
- setShouldPrefetch(true);
1493
- }, 100);
1494
- return () => {
1495
- clearTimeout(id);
1496
- };
1497
- }
1498
- }, [maybePrefetch]);
1499
- let setIntent = () => {
1500
- setMaybePrefetch(true);
1501
- };
1502
- let cancelIntent = () => {
1503
- setMaybePrefetch(false);
1504
- setShouldPrefetch(false);
1505
- };
1506
- if (!frameworkContext) {
1507
- return [false, ref, {}];
1508
- }
1509
- if (prefetch !== "intent") {
1510
- return [shouldPrefetch, ref, {}];
1511
- }
1512
- return [
1513
- shouldPrefetch,
1514
- ref,
1515
- {
1516
- onFocus: composeEventHandlers(onFocus, setIntent),
1517
- onBlur: composeEventHandlers(onBlur, cancelIntent),
1518
- onMouseEnter: composeEventHandlers(onMouseEnter, setIntent),
1519
- onMouseLeave: composeEventHandlers(onMouseLeave, cancelIntent),
1520
- onTouchStart: composeEventHandlers(onTouchStart, setIntent)
1521
- }
1522
- ];
1523
- }
1524
- function composeEventHandlers(theirHandler, ourHandler) {
1525
- return (event) => {
1526
- theirHandler && theirHandler(event);
1527
- if (!event.defaultPrevented) {
1528
- ourHandler(event);
1529
- }
1530
- };
1531
- }
1532
- function PrefetchPageLinks({ page, ...linkProps }) {
1533
- let { router } = useDataRouterContext2();
1534
- let matches = React3.useMemo(
1535
- () => matchRoutes(router.routes, page, router.basename),
1536
- [router.routes, page, router.basename]
1537
- );
1538
- if (!matches) {
1539
- return null;
1540
- }
1541
- return /* @__PURE__ */ React3.createElement(PrefetchPageLinksImpl, { page, matches, ...linkProps });
1542
- }
1543
- function useKeyedPrefetchLinks(matches) {
1544
- let { manifest, routeModules } = useFrameworkContext();
1545
- let [keyedPrefetchLinks, setKeyedPrefetchLinks] = React3.useState([]);
1546
- React3.useEffect(() => {
1547
- let interrupted = false;
1548
- void getKeyedPrefetchLinks(matches, manifest, routeModules).then(
1549
- (links) => {
1550
- if (!interrupted) {
1551
- setKeyedPrefetchLinks(links);
1552
- }
1553
- }
1554
- );
1555
- return () => {
1556
- interrupted = true;
1557
- };
1558
- }, [matches, manifest, routeModules]);
1559
- return keyedPrefetchLinks;
1560
- }
1561
- function PrefetchPageLinksImpl({
1562
- page,
1563
- matches: nextMatches,
1564
- ...linkProps
1565
- }) {
1566
- let location = useLocation();
1567
- let { future, manifest, routeModules } = useFrameworkContext();
1568
- let { basename } = useDataRouterContext2();
1569
- let { loaderData, matches } = useDataRouterStateContext();
1570
- let newMatchesForData = React3.useMemo(
1571
- () => getNewMatchesForLinks(
1572
- page,
1573
- nextMatches,
1574
- matches,
1575
- manifest,
1576
- location,
1577
- "data"
1578
- ),
1579
- [page, nextMatches, matches, manifest, location]
1580
- );
1581
- let newMatchesForAssets = React3.useMemo(
1582
- () => getNewMatchesForLinks(
1583
- page,
1584
- nextMatches,
1585
- matches,
1586
- manifest,
1587
- location,
1588
- "assets"
1589
- ),
1590
- [page, nextMatches, matches, manifest, location]
1591
- );
1592
- let dataHrefs = React3.useMemo(() => {
1593
- if (page === location.pathname + location.search + location.hash) {
1594
- return [];
1595
- }
1596
- let routesParams = /* @__PURE__ */ new Set();
1597
- let foundOptOutRoute = false;
1598
- nextMatches.forEach((m) => {
1599
- let manifestRoute = manifest.routes[m.route.id];
1600
- if (!manifestRoute || !manifestRoute.hasLoader) {
1601
- return;
1602
- }
1603
- if (!newMatchesForData.some((m2) => m2.route.id === m.route.id) && m.route.id in loaderData && routeModules[m.route.id]?.shouldRevalidate) {
1604
- foundOptOutRoute = true;
1605
- } else if (manifestRoute.hasClientLoader) {
1606
- foundOptOutRoute = true;
1607
- } else {
1608
- routesParams.add(m.route.id);
1609
- }
1610
- });
1611
- if (routesParams.size === 0) {
1612
- return [];
1613
- }
1614
- let url = singleFetchUrl(
1615
- page,
1616
- basename,
1617
- future.unstable_trailingSlashAwareDataRequests,
1618
- "data"
1619
- );
1620
- if (foundOptOutRoute && routesParams.size > 0) {
1621
- url.searchParams.set(
1622
- "_routes",
1623
- nextMatches.filter((m) => routesParams.has(m.route.id)).map((m) => m.route.id).join(",")
1624
- );
1625
- }
1626
- return [url.pathname + url.search];
1627
- }, [
1628
- basename,
1629
- future.unstable_trailingSlashAwareDataRequests,
1630
- loaderData,
1631
- location,
1632
- manifest,
1633
- newMatchesForData,
1634
- nextMatches,
1635
- page,
1636
- routeModules
1637
- ]);
1638
- let moduleHrefs = React3.useMemo(
1639
- () => getModuleLinkHrefs(newMatchesForAssets, manifest),
1640
- [newMatchesForAssets, manifest]
1641
- );
1642
- let keyedPrefetchLinks = useKeyedPrefetchLinks(newMatchesForAssets);
1643
- return /* @__PURE__ */ React3.createElement(React3.Fragment, null, dataHrefs.map((href) => /* @__PURE__ */ React3.createElement("link", { key: href, rel: "prefetch", as: "fetch", href, ...linkProps })), moduleHrefs.map((href) => /* @__PURE__ */ React3.createElement("link", { key: href, rel: "modulepreload", href, ...linkProps })), keyedPrefetchLinks.map(({ key, link }) => (
1644
- // these don't spread `linkProps` because they are full link descriptors
1645
- // already with their own props
1646
- /* @__PURE__ */ React3.createElement(
1647
- "link",
1648
- {
1649
- key,
1650
- nonce: linkProps.nonce,
1651
- ...link,
1652
- crossOrigin: link.crossOrigin ?? linkProps.crossOrigin
1653
- }
1654
- )
1655
- )));
1656
- }
1657
- function mergeRefs(...refs) {
1658
- return (value) => {
1659
- refs.forEach((ref) => {
1660
- if (typeof ref === "function") {
1661
- ref(value);
1662
- } else if (ref != null) {
1663
- ref.current = value;
1664
- }
1665
- });
1666
- };
1667
- }
1668
- var isBrowser2 = typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined";
1669
- try {
1670
- if (isBrowser2) {
1671
- window.__reactRouterVersion = // @ts-expect-error
1672
- "7.13.2";
1673
- }
1674
- } catch (e) {
1675
- }
1676
- var ABSOLUTE_URL_REGEX2 = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
1677
- var Link = React3.forwardRef(
1678
- function LinkWithRef({
1679
- onClick,
1680
- discover = "render",
1681
- prefetch = "none",
1682
- relative,
1683
- reloadDocument,
1684
- replace: replace2,
1685
- unstable_mask,
1686
- state,
1687
- target,
1688
- to,
1689
- preventScrollReset,
1690
- viewTransition,
1691
- unstable_defaultShouldRevalidate,
1692
- ...rest
1693
- }, forwardedRef) {
1694
- let { basename, navigator, unstable_useTransitions } = React3.useContext(NavigationContext);
1695
- let isAbsolute = typeof to === "string" && ABSOLUTE_URL_REGEX2.test(to);
1696
- let parsed = parseToInfo(to, basename);
1697
- to = parsed.to;
1698
- let href = useHref(to, { relative });
1699
- let location = useLocation();
1700
- let maskedHref = null;
1701
- if (unstable_mask) {
1702
- let resolved = resolveTo(
1703
- unstable_mask,
1704
- [],
1705
- location.unstable_mask ? location.unstable_mask.pathname : "/",
1706
- true
1707
- );
1708
- if (basename !== "/") {
1709
- resolved.pathname = resolved.pathname === "/" ? basename : joinPaths([basename, resolved.pathname]);
1710
- }
1711
- maskedHref = navigator.createHref(resolved);
1712
- }
1713
- let [shouldPrefetch, prefetchRef, prefetchHandlers] = usePrefetchBehavior(
1714
- prefetch,
1715
- rest
1716
- );
1717
- let internalOnClick = useLinkClickHandler(to, {
1718
- replace: replace2,
1719
- unstable_mask,
1720
- state,
1721
- target,
1722
- preventScrollReset,
1723
- relative,
1724
- viewTransition,
1725
- unstable_defaultShouldRevalidate,
1726
- unstable_useTransitions
1727
- });
1728
- function handleClick(event) {
1729
- if (onClick) onClick(event);
1730
- if (!event.defaultPrevented) {
1731
- internalOnClick(event);
1732
- }
1733
- }
1734
- let isSpaLink = !(parsed.isExternal || reloadDocument);
1735
- let link = (
1736
- // eslint-disable-next-line jsx-a11y/anchor-has-content
1737
- /* @__PURE__ */ React3.createElement(
1738
- "a",
1739
- {
1740
- ...rest,
1741
- ...prefetchHandlers,
1742
- href: (isSpaLink ? maskedHref : void 0) || parsed.absoluteURL || href,
1743
- onClick: isSpaLink ? handleClick : onClick,
1744
- ref: mergeRefs(forwardedRef, prefetchRef),
1745
- target,
1746
- "data-discover": !isAbsolute && discover === "render" ? "true" : void 0
1747
- }
1748
- )
1749
- );
1750
- return shouldPrefetch && !isAbsolute ? /* @__PURE__ */ React3.createElement(React3.Fragment, null, link, /* @__PURE__ */ React3.createElement(PrefetchPageLinks, { page: href })) : link;
1751
- }
1752
- );
1753
- Link.displayName = "Link";
1754
- var NavLink = React3.forwardRef(
1755
- function NavLinkWithRef({
1756
- "aria-current": ariaCurrentProp = "page",
1757
- caseSensitive = false,
1758
- className: classNameProp = "",
1759
- end = false,
1760
- style: styleProp,
1761
- to,
1762
- viewTransition,
1763
- children,
1764
- ...rest
1765
- }, ref) {
1766
- let path = useResolvedPath(to, { relative: rest.relative });
1767
- let location = useLocation();
1768
- let routerState = React3.useContext(DataRouterStateContext);
1769
- let { navigator, basename } = React3.useContext(NavigationContext);
1770
- let isTransitioning = routerState != null && // Conditional usage is OK here because the usage of a data router is static
1771
- // eslint-disable-next-line react-hooks/rules-of-hooks
1772
- useViewTransitionState(path) && viewTransition === true;
1773
- let toPathname = navigator.encodeLocation ? navigator.encodeLocation(path).pathname : path.pathname;
1774
- let locationPathname = location.pathname;
1775
- let nextLocationPathname = routerState && routerState.navigation && routerState.navigation.location ? routerState.navigation.location.pathname : null;
1776
- if (!caseSensitive) {
1777
- locationPathname = locationPathname.toLowerCase();
1778
- nextLocationPathname = nextLocationPathname ? nextLocationPathname.toLowerCase() : null;
1779
- toPathname = toPathname.toLowerCase();
1780
- }
1781
- if (nextLocationPathname && basename) {
1782
- nextLocationPathname = stripBasename(nextLocationPathname, basename) || nextLocationPathname;
1783
- }
1784
- const endSlashPosition = toPathname !== "/" && toPathname.endsWith("/") ? toPathname.length - 1 : toPathname.length;
1785
- let isActive = locationPathname === toPathname || !end && locationPathname.startsWith(toPathname) && locationPathname.charAt(endSlashPosition) === "/";
1786
- let isPending = nextLocationPathname != null && (nextLocationPathname === toPathname || !end && nextLocationPathname.startsWith(toPathname) && nextLocationPathname.charAt(toPathname.length) === "/");
1787
- let renderProps = {
1788
- isActive,
1789
- isPending,
1790
- isTransitioning
1791
- };
1792
- let ariaCurrent = isActive ? ariaCurrentProp : void 0;
1793
- let className;
1794
- if (typeof classNameProp === "function") {
1795
- className = classNameProp(renderProps);
1796
- } else {
1797
- className = [
1798
- classNameProp,
1799
- isActive ? "active" : null,
1800
- isPending ? "pending" : null,
1801
- isTransitioning ? "transitioning" : null
1802
- ].filter(Boolean).join(" ");
1803
- }
1804
- let style = typeof styleProp === "function" ? styleProp(renderProps) : styleProp;
1805
- return /* @__PURE__ */ React3.createElement(
1806
- Link,
1807
- {
1808
- ...rest,
1809
- "aria-current": ariaCurrent,
1810
- className,
1811
- ref,
1812
- style,
1813
- to,
1814
- viewTransition
1815
- },
1816
- typeof children === "function" ? children(renderProps) : children
1817
- );
1818
- }
1819
- );
1820
- NavLink.displayName = "NavLink";
1821
- var Form = React3.forwardRef(
1822
- ({
1823
- discover = "render",
1824
- fetcherKey,
1825
- navigate,
1826
- reloadDocument,
1827
- replace: replace2,
1828
- state,
1829
- method = defaultMethod,
1830
- action,
1831
- onSubmit,
1832
- relative,
1833
- preventScrollReset,
1834
- viewTransition,
1835
- unstable_defaultShouldRevalidate,
1836
- ...props
1837
- }, forwardedRef) => {
1838
- let { unstable_useTransitions } = React3.useContext(NavigationContext);
1839
- let submit = useSubmit();
1840
- let formAction = useFormAction(action, { relative });
1841
- let formMethod = method.toLowerCase() === "get" ? "get" : "post";
1842
- let isAbsolute = typeof action === "string" && ABSOLUTE_URL_REGEX2.test(action);
1843
- let submitHandler = (event) => {
1844
- onSubmit && onSubmit(event);
1845
- if (event.defaultPrevented) return;
1846
- event.preventDefault();
1847
- let submitter = event.nativeEvent.submitter;
1848
- let submitMethod = submitter?.getAttribute("formmethod") || method;
1849
- let doSubmit = () => submit(submitter || event.currentTarget, {
1850
- fetcherKey,
1851
- method: submitMethod,
1852
- navigate,
1853
- replace: replace2,
1854
- state,
1855
- relative,
1856
- preventScrollReset,
1857
- viewTransition,
1858
- unstable_defaultShouldRevalidate
1859
- });
1860
- if (unstable_useTransitions && navigate !== false) {
1861
- React3.startTransition(() => doSubmit());
1862
- } else {
1863
- doSubmit();
1864
- }
1865
- };
1866
- return /* @__PURE__ */ React3.createElement(
1867
- "form",
1868
- {
1869
- ref: forwardedRef,
1870
- method: formMethod,
1871
- action: formAction,
1872
- onSubmit: reloadDocument ? onSubmit : submitHandler,
1873
- ...props,
1874
- "data-discover": !isAbsolute && discover === "render" ? "true" : void 0
1875
- }
1876
- );
1877
- }
1878
- );
1879
- Form.displayName = "Form";
1880
- function getDataRouterConsoleError2(hookName) {
1881
- return `${hookName} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`;
1882
- }
1883
- function useDataRouterContext3(hookName) {
1884
- let ctx = React3.useContext(DataRouterContext);
1885
- invariant(ctx, getDataRouterConsoleError2(hookName));
1886
- return ctx;
1887
- }
1888
- function useLinkClickHandler(to, {
1889
- target,
1890
- replace: replaceProp,
1891
- unstable_mask,
1892
- state,
1893
- preventScrollReset,
1894
- relative,
1895
- viewTransition,
1896
- unstable_defaultShouldRevalidate,
1897
- unstable_useTransitions
1898
- } = {}) {
1899
- let navigate = useNavigate();
1900
- let location = useLocation();
1901
- let path = useResolvedPath(to, { relative });
1902
- return React3.useCallback(
1903
- (event) => {
1904
- if (shouldProcessLinkClick(event, target)) {
1905
- event.preventDefault();
1906
- let replace2 = replaceProp !== void 0 ? replaceProp : createPath(location) === createPath(path);
1907
- let doNavigate = () => navigate(to, {
1908
- replace: replace2,
1909
- unstable_mask,
1910
- state,
1911
- preventScrollReset,
1912
- relative,
1913
- viewTransition,
1914
- unstable_defaultShouldRevalidate
1915
- });
1916
- if (unstable_useTransitions) {
1917
- React3.startTransition(() => doNavigate());
1918
- } else {
1919
- doNavigate();
1920
- }
1921
- }
1922
- },
1923
- [
1924
- location,
1925
- navigate,
1926
- path,
1927
- replaceProp,
1928
- unstable_mask,
1929
- state,
1930
- target,
1931
- to,
1932
- preventScrollReset,
1933
- relative,
1934
- viewTransition,
1935
- unstable_defaultShouldRevalidate,
1936
- unstable_useTransitions
1937
- ]
1938
- );
1939
- }
1940
- var fetcherId = 0;
1941
- var getUniqueFetcherId = () => `__${String(++fetcherId)}__`;
1942
- function useSubmit() {
1943
- let { router } = useDataRouterContext3("useSubmit" /* UseSubmit */);
1944
- let { basename } = React3.useContext(NavigationContext);
1945
- let currentRouteId = useRouteId();
1946
- let routerFetch = router.fetch;
1947
- let routerNavigate = router.navigate;
1948
- return React3.useCallback(
1949
- async (target, options = {}) => {
1950
- let { action, method, encType, formData, body } = getFormSubmissionInfo(
1951
- target,
1952
- basename
1953
- );
1954
- if (options.navigate === false) {
1955
- let key = options.fetcherKey || getUniqueFetcherId();
1956
- await routerFetch(key, currentRouteId, options.action || action, {
1957
- unstable_defaultShouldRevalidate: options.unstable_defaultShouldRevalidate,
1958
- preventScrollReset: options.preventScrollReset,
1959
- formData,
1960
- body,
1961
- formMethod: options.method || method,
1962
- formEncType: options.encType || encType,
1963
- flushSync: options.flushSync
1964
- });
1965
- } else {
1966
- await routerNavigate(options.action || action, {
1967
- unstable_defaultShouldRevalidate: options.unstable_defaultShouldRevalidate,
1968
- preventScrollReset: options.preventScrollReset,
1969
- formData,
1970
- body,
1971
- formMethod: options.method || method,
1972
- formEncType: options.encType || encType,
1973
- replace: options.replace,
1974
- state: options.state,
1975
- fromRouteId: currentRouteId,
1976
- flushSync: options.flushSync,
1977
- viewTransition: options.viewTransition
1978
- });
1979
- }
1980
- },
1981
- [routerFetch, routerNavigate, basename, currentRouteId]
1982
- );
1983
- }
1984
- function useFormAction(action, { relative } = {}) {
1985
- let { basename } = React3.useContext(NavigationContext);
1986
- let routeContext = React3.useContext(RouteContext);
1987
- invariant(routeContext, "useFormAction must be used inside a RouteContext");
1988
- let [match] = routeContext.matches.slice(-1);
1989
- let path = { ...useResolvedPath(action ? action : ".", { relative }) };
1990
- let location = useLocation();
1991
- if (action == null) {
1992
- path.search = location.search;
1993
- let params = new URLSearchParams(path.search);
1994
- let indexValues = params.getAll("index");
1995
- let hasNakedIndexParam = indexValues.some((v) => v === "");
1996
- if (hasNakedIndexParam) {
1997
- params.delete("index");
1998
- indexValues.filter((v) => v).forEach((v) => params.append("index", v));
1999
- let qs = params.toString();
2000
- path.search = qs ? `?${qs}` : "";
2001
- }
2002
- }
2003
- if ((!action || action === ".") && match.route.index) {
2004
- path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index";
2005
- }
2006
- if (basename !== "/") {
2007
- path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
2008
- }
2009
- return createPath(path);
2010
- }
2011
- function useViewTransitionState(to, { relative } = {}) {
2012
- let vtContext = React3.useContext(ViewTransitionContext);
2013
- invariant(
2014
- vtContext != null,
2015
- "`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?"
2016
- );
2017
- let { basename } = useDataRouterContext3(
2018
- "useViewTransitionState" /* useViewTransitionState */
2019
- );
2020
- let path = useResolvedPath(to, { relative });
2021
- if (!vtContext.isTransitioning) {
2022
- return false;
2023
- }
2024
- let currentPath = stripBasename(vtContext.currentLocation.pathname, basename) || vtContext.currentLocation.pathname;
2025
- let nextPath = stripBasename(vtContext.nextLocation.pathname, basename) || vtContext.nextLocation.pathname;
2026
- return matchPath(path.pathname, nextPath) != null || matchPath(path.pathname, currentPath) != null;
2027
- }
2028
-
2029
- function getDefaultExportFromCjs (x) {
2030
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
2031
- }
2032
-
2033
81
  const LinkWithRef = ({ children, to, href, forwardedRef = null, ...attributes }) => {
2034
82
  if (to) {
2035
83
  return (jsx(Link, { ref: forwardedRef, to: to, ...attributes, children: children }));
@@ -2135,7 +183,7 @@ const Boolean$1 = ({ className, errorMessage, fieldset, formGroup, hint, idPrefi
2135
183
  if (item.divider) {
2136
184
  return (jsx("div", { className: `govuk-${controlType}__divider`, children: item.divider }, reactListKey || index));
2137
185
  }
2138
- return (jsxs(React3__default.Fragment, { children: [jsxs("div", { className: `govuk-${controlType}__item`, children: [jsx("input", { className: `govuk-${controlType}__input`, id: idValue, name: nameValue, type: controlType === "radios" ? "radio" : "checkbox", "data-aria-controls": conditionalId, "aria-describedby": itemDescribedBy || undefined, onChange: onChange, onBlur: onBlur, "data-behaviour": behaviour, ...itemAttributes }), jsx(Label, { ...label,
186
+ return (jsxs(React__default.Fragment, { children: [jsxs("div", { className: `govuk-${controlType}__item`, children: [jsx("input", { className: `govuk-${controlType}__input`, id: idValue, name: nameValue, type: controlType === "radios" ? "radio" : "checkbox", "data-aria-controls": conditionalId, "aria-describedby": itemDescribedBy || undefined, onChange: onChange, onBlur: onBlur, "data-behaviour": behaviour, ...itemAttributes }), jsx(Label, { ...label,
2139
187
  className: `govuk-${controlType}__label ${label?.className || ""}`,
2140
188
  htmlFor: idValue,
2141
189
  isPageHeading: false, children: children }), itemHint ? (jsx(Hint, { ...itemHint,
@@ -2181,7 +229,7 @@ const Button = (props) => {
2181
229
  iconHtml = (jsx("svg", { className: "govuk-button__start-icon", xmlns: "http://www.w3.org/2000/svg", width: "17.5", height: "19", viewBox: "0 0 33 40", "aria-hidden": "true", focusable: "false", children: jsx("path", { fill: "currentColor", d: "M0 0h13l20 20-20 20H0l20-20z" }) }));
2182
230
  }
2183
231
  const commonAttributes = {
2184
- className: `govuk-button ${className || ""}${disabled ? " govuk-button--disabled" : ""} ${isStartButton ? "govuk-button--start" : ""}`,
232
+ className: `govuk-button ${className || ""} ${isStartButton ? "govuk-button--start" : ""}`,
2185
233
  // ref: buttonRef,
2186
234
  };
2187
235
  if (preventDoubleClick) {
@@ -2223,6 +271,10 @@ function ConfigureOverallButton($scope, config) {
2223
271
  createAll(Button$1, config, $scope);
2224
272
  }
2225
273
 
274
+ function getDefaultExportFromCjs (x) {
275
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
276
+ }
277
+
2226
278
  var classnames = {exports: {}};
2227
279
 
2228
280
  /*!
@@ -2312,7 +364,7 @@ var classNames = /*@__PURE__*/getDefaultExportFromCjs(classnamesExports);
2312
364
 
2313
365
  const DEFAULT_BREAKPOINTS = ['xxl', 'xl', 'lg', 'md', 'sm', 'xs'];
2314
366
  const DEFAULT_MIN_BREAKPOINT = 'xs';
2315
- const ThemeContext = /*#__PURE__*/React3.createContext({
367
+ const ThemeContext = /*#__PURE__*/React.createContext({
2316
368
  prefixes: {},
2317
369
  breakpoints: DEFAULT_BREAKPOINTS,
2318
370
  minBreakpoint: DEFAULT_MIN_BREAKPOINT
@@ -2328,7 +380,7 @@ function useBootstrapPrefix(prefix, defaultPrefix) {
2328
380
  return prefix || prefixes[defaultPrefix] || defaultPrefix;
2329
381
  }
2330
382
 
2331
- const CardBody = /*#__PURE__*/React3.forwardRef(({
383
+ const CardBody = /*#__PURE__*/React.forwardRef(({
2332
384
  className,
2333
385
  bsPrefix,
2334
386
  as: Component = 'div',
@@ -2343,7 +395,7 @@ const CardBody = /*#__PURE__*/React3.forwardRef(({
2343
395
  });
2344
396
  CardBody.displayName = 'CardBody';
2345
397
 
2346
- const CardFooter = /*#__PURE__*/React3.forwardRef(({
398
+ const CardFooter = /*#__PURE__*/React.forwardRef(({
2347
399
  className,
2348
400
  bsPrefix,
2349
401
  as: Component = 'div',
@@ -2358,10 +410,10 @@ const CardFooter = /*#__PURE__*/React3.forwardRef(({
2358
410
  });
2359
411
  CardFooter.displayName = 'CardFooter';
2360
412
 
2361
- const context = /*#__PURE__*/React3.createContext(null);
413
+ const context = /*#__PURE__*/React.createContext(null);
2362
414
  context.displayName = 'CardHeaderContext';
2363
415
 
2364
- const CardHeader = /*#__PURE__*/React3.forwardRef(({
416
+ const CardHeader = /*#__PURE__*/React.forwardRef(({
2365
417
  bsPrefix,
2366
418
  className,
2367
419
  // Need to define the default "as" during prop destructuring to be compatible with styled-components github.com/react-bootstrap/react-bootstrap/issues/3595
@@ -2383,7 +435,7 @@ const CardHeader = /*#__PURE__*/React3.forwardRef(({
2383
435
  });
2384
436
  CardHeader.displayName = 'CardHeader';
2385
437
 
2386
- const CardImg = /*#__PURE__*/React3.forwardRef(
438
+ const CardImg = /*#__PURE__*/React.forwardRef(
2387
439
  // Need to define the default "as" during prop destructuring to be compatible with styled-components github.com/react-bootstrap/react-bootstrap/issues/3595
2388
440
  ({
2389
441
  bsPrefix,
@@ -2401,7 +453,7 @@ const CardImg = /*#__PURE__*/React3.forwardRef(
2401
453
  });
2402
454
  CardImg.displayName = 'CardImg';
2403
455
 
2404
- const CardImgOverlay = /*#__PURE__*/React3.forwardRef(({
456
+ const CardImgOverlay = /*#__PURE__*/React.forwardRef(({
2405
457
  className,
2406
458
  bsPrefix,
2407
459
  as: Component = 'div',
@@ -2416,7 +468,7 @@ const CardImgOverlay = /*#__PURE__*/React3.forwardRef(({
2416
468
  });
2417
469
  CardImgOverlay.displayName = 'CardImgOverlay';
2418
470
 
2419
- const CardLink = /*#__PURE__*/React3.forwardRef(({
471
+ const CardLink = /*#__PURE__*/React.forwardRef(({
2420
472
  className,
2421
473
  bsPrefix,
2422
474
  as: Component = 'a',
@@ -2434,14 +486,14 @@ CardLink.displayName = 'CardLink';
2434
486
  var divWithClassName = (className =>
2435
487
  /*#__PURE__*/
2436
488
  // eslint-disable-next-line react/display-name
2437
- React3.forwardRef((p, ref) => /*#__PURE__*/jsx("div", {
489
+ React.forwardRef((p, ref) => /*#__PURE__*/jsx("div", {
2438
490
  ...p,
2439
491
  ref: ref,
2440
492
  className: classNames(p.className, className)
2441
493
  })));
2442
494
 
2443
495
  const DivStyledAsH6 = divWithClassName('h6');
2444
- const CardSubtitle = /*#__PURE__*/React3.forwardRef(({
496
+ const CardSubtitle = /*#__PURE__*/React.forwardRef(({
2445
497
  className,
2446
498
  bsPrefix,
2447
499
  as: Component = DivStyledAsH6,
@@ -2456,7 +508,7 @@ const CardSubtitle = /*#__PURE__*/React3.forwardRef(({
2456
508
  });
2457
509
  CardSubtitle.displayName = 'CardSubtitle';
2458
510
 
2459
- const CardText = /*#__PURE__*/React3.forwardRef(({
511
+ const CardText = /*#__PURE__*/React.forwardRef(({
2460
512
  className,
2461
513
  bsPrefix,
2462
514
  as: Component = 'p',
@@ -2472,7 +524,7 @@ const CardText = /*#__PURE__*/React3.forwardRef(({
2472
524
  CardText.displayName = 'CardText';
2473
525
 
2474
526
  const DivStyledAsH5 = divWithClassName('h5');
2475
- const CardTitle = /*#__PURE__*/React3.forwardRef(({
527
+ const CardTitle = /*#__PURE__*/React.forwardRef(({
2476
528
  className,
2477
529
  bsPrefix,
2478
530
  as: Component = DivStyledAsH5,
@@ -2487,7 +539,7 @@ const CardTitle = /*#__PURE__*/React3.forwardRef(({
2487
539
  });
2488
540
  CardTitle.displayName = 'CardTitle';
2489
541
 
2490
- const Card$1 = /*#__PURE__*/React3.forwardRef(({
542
+ const Card$1 = /*#__PURE__*/React.forwardRef(({
2491
543
  bsPrefix,
2492
544
  className,
2493
545
  bg,
@@ -2560,29 +612,37 @@ const defaultProps$1 = {
2560
612
  id: "",
2561
613
  name: "",
2562
614
  };
2563
- const Textarea = React3__default.forwardRef((props = defaultProps$1, ref) => {
2564
- const { className, "aria-describedby": describedBy, errorMessage, formGroup, hint, label, id, ...attributes } = props;
615
+ const Textarea = React__default.forwardRef((props = defaultProps$1, ref) => {
616
+ const { className, "aria-describedby": describedBy, errorMessage, formGroup, hint, label, id, name, ...attributes } = props;
617
+ // Mirrors govuk-frontend's Nunjucks macro, which defaults id to name when
618
+ // id isn't given - without this the textarea has no id, so its <label for>
619
+ // (and hint/error aria-describedby) can never associate with it.
620
+ const resolvedId = id || name;
2565
621
  let describedByValue = describedBy || "";
2566
622
  let hintComponent = null;
2567
623
  let errorMessageComponent = null;
2568
624
  if (hint) {
2569
- const hintId = `${id}-hint`;
625
+ const hintId = `${resolvedId}-hint`;
2570
626
  describedByValue += ` ${hintId}`;
2571
627
  hintComponent = jsx(Hint, { ...hint, id: hintId });
2572
628
  }
2573
629
  if (errorMessage) {
2574
- const errorId = id ? `${id}-error` : "";
630
+ const errorId = resolvedId ? `${resolvedId}-error` : "";
2575
631
  describedByValue += ` ${errorId}`;
2576
632
  errorMessageComponent = jsx(ErrorMessage, { ...errorMessage, id: errorId });
2577
633
  }
2578
- return (jsxs("div", { className: `govuk-form-group${errorMessage ? " govuk-form-group--error" : ""} ${formGroup?.className || ""}`, children: [jsx(Label, { ...label, htmlFor: id }), hintComponent, errorMessageComponent, jsx("textarea", { ...attributes, id: id, ref: ref, className: `govuk-textarea${errorMessage ? " govuk-textarea--error" : ""} ${className || ""}`, "aria-describedby": describedByValue?.trim() || undefined })] }));
634
+ return (jsxs("div", { className: `govuk-form-group${errorMessage ? " govuk-form-group--error" : ""} ${formGroup?.className || ""}`, children: [jsx(Label, { ...label, htmlFor: resolvedId }), hintComponent, errorMessageComponent, jsx("textarea", { name: name, ...attributes, id: resolvedId, ref: ref, className: `govuk-textarea${errorMessage ? " govuk-textarea--error" : ""} ${className || ""}`, "aria-describedby": describedByValue?.trim() || undefined })] }));
2579
635
  });
2580
636
  Textarea.displayName = "Textarea";
2581
637
 
2582
638
  const CharacterCount = (props) => {
2583
- const { id, className, maxlength, threshold, maxwords, errorMessage, countMessage, ...attributes } = props;
2584
- const characterCountInfoId = `${id}-info`;
2585
- return (jsxs("div", { className: "govuk-character-count", "data-module": "govuk-character-count", "data-maxlength": maxlength, "data-threshold": threshold, "data-maxwords": maxwords, children: [jsx(Textarea, { id: id, ...attributes, errorMessage: errorMessage, className: `govuk-js-character-count ${className || ""}${errorMessage ? " govuk-textarea--error" : ""}`, "aria-describedby": characterCountInfoId }), jsxs(Hint, { id: characterCountInfoId, className: `govuk-hint govuk-character-count__message ${countMessage?.className || ""}`, "aria-live": "polite", children: ["You have ", maxlength || maxwords, " ", maxwords ? "words" : "characters", " ", "remaining"] })] }));
639
+ const { id, name, className, maxlength, threshold, maxwords, errorMessage, countMessage, ...attributes } = props;
640
+ // Mirrors govuk-frontend's Nunjucks macro, which defaults id to name when
641
+ // id isn't given - without this the count message's id (referenced by the
642
+ // textarea's aria-describedby) would render as literally "undefined-info".
643
+ const resolvedId = id || name;
644
+ const characterCountInfoId = `${resolvedId}-info`;
645
+ return (jsxs("div", { className: "govuk-character-count", "data-module": "govuk-character-count", "data-maxlength": maxlength, "data-threshold": threshold, "data-maxwords": maxwords, children: [jsx(Textarea, { id: resolvedId, name: name, ...attributes, errorMessage: errorMessage, className: `govuk-js-character-count ${className || ""}${errorMessage ? " govuk-textarea--error" : ""}`, "aria-describedby": characterCountInfoId }), jsxs(Hint, { id: characterCountInfoId, className: `govuk-hint govuk-character-count__message ${countMessage?.className || ""}`, "aria-live": "polite", children: ["You have ", maxlength || maxwords, " ", maxwords ? "words" : "characters", " ", "remaining"] })] }));
2586
646
  };
2587
647
  CharacterCount.displayName = "CharacterCount";
2588
648
 
@@ -2628,23 +688,27 @@ const DataNavigation = ({ dataId, setDataFocus, previousText = "Previous", previ
2628
688
  const defaultProps = {
2629
689
  type: "text",
2630
690
  };
2631
- const Input = React3__default.forwardRef((props = defaultProps, ref) => {
691
+ const Input = React__default.forwardRef((props = defaultProps, ref) => {
2632
692
  const { className, "aria-describedby": describedBy, errorMessage, formGroup, hint, label, name, id, prefix, suffix, ...attributes } = props;
693
+ // Mirrors govuk-frontend's Nunjucks macro, which defaults id to name when
694
+ // id isn't given - without this the input has no id, so its <label for>
695
+ // (and hint/error aria-describedby) can never associate with it.
696
+ const resolvedId = id || name;
2633
697
  let describedByValue = describedBy || "";
2634
698
  let hintComponent = null;
2635
699
  let errorMessageComponent = null;
2636
700
  if (hint) {
2637
- const hintId = `${id}-hint`;
701
+ const hintId = `${resolvedId}-hint`;
2638
702
  describedByValue += ` ${hintId}`;
2639
703
  hintComponent = jsx(Hint, { ...hint, id: hintId });
2640
704
  }
2641
705
  if (errorMessage) {
2642
- const errorId = id ? `${id}-error` : "";
706
+ const errorId = resolvedId ? `${resolvedId}-error` : "";
2643
707
  describedByValue += ` ${errorId}`;
2644
708
  errorMessageComponent = jsx(ErrorMessage, { ...errorMessage, id: errorId });
2645
709
  }
2646
- const input = (jsx("input", { ref: ref, id: id, className: `govuk-input ${className || ""} ${errorMessage ? " govuk-input--error" : ""}`, name: name || id, "aria-describedby": describedByValue || undefined, ...attributes }));
2647
- return (jsxs("div", { className: `govuk-form-group ${formGroup?.className || ""} ${errorMessage ? "govuk-form-group--error" : ""}`, children: [jsx(Label, { ...label, htmlFor: id }), hintComponent, errorMessageComponent, prefix || suffix ? (jsxs("div", { className: "govuk-input__wrapper", children: [prefix ? (jsx("div", { "aria-hidden": "true", ...prefix,
710
+ const input = (jsx("input", { ref: ref, id: resolvedId, className: `govuk-input ${className || ""} ${errorMessage ? " govuk-input--error" : ""}`, name: name || resolvedId, "aria-describedby": describedByValue || undefined, ...attributes }));
711
+ return (jsxs("div", { className: `govuk-form-group ${formGroup?.className || ""} ${errorMessage ? "govuk-form-group--error" : ""}`, children: [jsx(Label, { ...label, htmlFor: resolvedId }), hintComponent, errorMessageComponent, prefix || suffix ? (jsxs("div", { className: "govuk-input__wrapper", children: [prefix ? (jsx("div", { "aria-hidden": "true", ...prefix,
2648
712
  className: `govuk-input__prefix ${prefix.className ? prefix.className : ""}` })) : null, input, suffix ? (jsx("div", { "aria-hidden": "true", ...suffix,
2649
713
  className: `govuk-input__suffix ${suffix.className ? suffix.className : ""}` })) : null] })) : (input)] }));
2650
714
  });
@@ -2825,21 +889,25 @@ function ConfigureOverallExitThisPage($scope) {
2825
889
  }
2826
890
 
2827
891
  const FileUpload = (props) => {
2828
- const { className, errorMessage, formGroup, hint, label, "aria-describedby": describedBy, id, ...attributes } = props;
892
+ const { className, errorMessage, formGroup, hint, label, "aria-describedby": describedBy, id, name, ...attributes } = props;
893
+ // Mirrors govuk-frontend's Nunjucks macro, which defaults id to name when
894
+ // id isn't given - without this the input has no id, so its <label for>
895
+ // (and hint/error aria-describedby) can never associate with it.
896
+ const resolvedId = id || name;
2829
897
  let hintComponent;
2830
898
  let errorMessageComponent;
2831
899
  let describedByValue = describedBy || "";
2832
900
  if (hint) {
2833
- const hintId = `${props.id}-hint`;
901
+ const hintId = `${resolvedId}-hint`;
2834
902
  describedByValue += ` ${hintId}`;
2835
- hintComponent = jsx(Hint, { ...props.hint, id: hintId });
903
+ hintComponent = jsx(Hint, { ...hint, id: hintId });
2836
904
  }
2837
905
  if (errorMessage) {
2838
- const errorId = `${id}-error`;
906
+ const errorId = `${resolvedId}-error`;
2839
907
  describedByValue += ` ${errorId}`;
2840
908
  errorMessageComponent = jsx(ErrorMessage, { ...errorMessage, id: errorId });
2841
909
  }
2842
- return (jsxs("div", { className: `govuk-form-group${errorMessage ? " govuk-form-group--error" : ""} ${formGroup?.className || ""}`, children: [jsx(Label, { ...label, htmlFor: id }), hintComponent, errorMessageComponent, jsx("input", { ...attributes, id: id, className: `govuk-file-upload ${className || ""}${errorMessage ? " govuk-file-upload--error" : ""}`, type: "file", "aria-describedby": describedByValue || undefined })] }));
910
+ return (jsxs("div", { className: `govuk-form-group${errorMessage ? " govuk-form-group--error" : ""} ${formGroup?.className || ""}`, children: [jsx(Label, { ...label, htmlFor: resolvedId }), hintComponent, errorMessageComponent, jsx("input", { name: name, ...attributes, id: resolvedId, className: `govuk-file-upload ${className || ""}${errorMessage ? " govuk-file-upload--error" : ""}`, type: "file", "aria-describedby": describedByValue || undefined })] }));
2843
911
  };
2844
912
  FileUpload.displayName = "FileUpload";
2845
913
 
@@ -2851,7 +919,7 @@ const Footer = (props) => {
2851
919
  if (navigation && navigation.length > 0) {
2852
920
  navigationComponent = (jsxs(Fragment, { children: [jsx("div", { className: "govuk-footer__navigation", children: navigation.map((nav, navIndex) => (jsxs("div", { className: `govuk-footer__section govuk-grid-column-${nav.width ? nav.width : "full"}`, children: [jsx("h2", { className: "govuk-footer__heading govuk-heading-m", children: nav.title }), nav.items && nav.items.length > 0 ? (jsx("ul", { className: `govuk-footer__list ${nav.columns ? `govuk-footer__list--columns-${nav.columns}` : ""}`, children: nav.items.map((item, index) => {
2853
921
  const { className: itemClassName, children: itemChildren, reactListKey, ...itemAttributes } = item;
2854
- return (jsx(React3__default.Fragment, { children: (item.href || item.to) && itemChildren && (jsx("li", { className: "govuk-footer__list-item", children: jsx(LinkWithRef, { className: `govuk-footer__link ${itemClassName || ""}`, ...itemAttributes, children: itemChildren }) })) }, reactListKey || index));
922
+ return (jsx(React__default.Fragment, { children: (item.href || item.to) && itemChildren && (jsx("li", { className: "govuk-footer__list-item", children: jsx(LinkWithRef, { className: `govuk-footer__link ${itemClassName || ""}`, ...itemAttributes, children: itemChildren }) })) }, reactListKey || index));
2855
923
  }) })) : null] }, nav.reactListKey || navIndex))) }), jsx("hr", { className: "govuk-footer__section-break" })] }));
2856
924
  }
2857
925
  if (meta) {
@@ -3000,7 +1068,7 @@ const Pagination = ({ previous, next, items, className, }) => {
3000
1068
  // Block layout is used when there are no numbered page items — govuk renders
3001
1069
  // the nav with an extra class and the link title with --decorated modifier.
3002
1070
  const isBlockLayout = !items || items.length === 0;
3003
- return (jsxs("nav", { className: `govuk-pagination${isBlockLayout ? " govuk-pagination--block" : ""}${className ? ` ${className}` : ""}`, role: "navigation", "aria-label": "Pagination", children: [previous && (jsx("div", { className: "govuk-pagination__prev", children: jsx(NavigationButton, { type: "previous", ...previous }) })), items && items.length > 0 && (jsx("ul", { className: "govuk-pagination__list", children: items.map((item, index) => item.ellipsis ? (jsx("li", { className: "govuk-pagination__item govuk-pagination__item--ellipses", children: DOTS }, index)) : (jsx("li", { className: `govuk-pagination__item${item.current ? " govuk-pagination__item--current" : ""}`, children: jsx("a", { className: "govuk-link govuk-pagination__link", href: item.href ?? "#", "aria-label": `Page ${item.number}`, ...(item.current ? { "aria-current": "page" } : {}), children: item.number }) }, index))) })), next && (jsx("div", { className: "govuk-pagination__next", children: jsx(NavigationButton, { type: "next", ...next }) }))] }));
1071
+ return (jsxs("nav", { className: `govuk-pagination${isBlockLayout ? " govuk-pagination--block" : ""}${className ? ` ${className}` : ""}`, role: "navigation", "aria-label": "Pagination", children: [previous && (jsx("div", { className: "govuk-pagination__prev", children: jsx(NavigationButton, { type: "previous", ...previous }) })), items && items.length > 0 && (jsx("ul", { className: "govuk-pagination__list", children: items.map((item, index) => item.ellipsis ? (jsx("li", { className: "govuk-pagination__item govuk-pagination__item--ellipsis", children: DOTS }, index)) : (jsx("li", { className: `govuk-pagination__item${item.current ? " govuk-pagination__item--current" : ""}`, children: jsx("a", { className: "govuk-link govuk-pagination__link", href: item.href ?? "#", "aria-label": `Page ${item.number}`, ...(item.current ? { "aria-current": "page" } : {}), children: item.number }) }, index))) })), next && (jsx("div", { className: "govuk-pagination__next", children: jsx(NavigationButton, { type: "next", ...next }) }))] }));
3004
1072
  };
3005
1073
 
3006
1074
  const Panel = (props) => {
@@ -3009,18 +1077,23 @@ const Panel = (props) => {
3009
1077
  return (jsxs("div", { className: `govuk-panel govuk-panel--confirmation ${className || ""}`, ...attributes, children: [jsx(HeadingLevel, { className: "govuk-panel__title", children: titleChildren }), innerHtml] }));
3010
1078
  };
3011
1079
 
3012
- const PasswordInput = React3__default.forwardRef((props, ref) => {
1080
+ const PasswordInput = React__default.forwardRef((props, ref) => {
3013
1081
  const { className, "aria-describedby": describedBy, errorMessage, formGroup, hint, label, name, id, autoComplete = "current-password", showPasswordText = "Show", hidePasswordText = "Hide", showPasswordAriaLabelText = "Show password", hidePasswordAriaLabelText = "Hide password", passwordShownAnnouncementText, passwordHiddenAnnouncementText, ...attributes } = props;
1082
+ // Mirrors govuk-frontend's Nunjucks macro, which defaults id to name
1083
+ // when id isn't given - without this the input has no id, so its
1084
+ // <label for> (and hint/error aria-describedby) can never associate
1085
+ // with it.
1086
+ const resolvedId = id || name;
3014
1087
  let describedByValue = describedBy || "";
3015
1088
  let hintComponent = null;
3016
1089
  let errorMessageComponent = null;
3017
1090
  if (hint) {
3018
- const hintId = `${id}-hint`;
1091
+ const hintId = `${resolvedId}-hint`;
3019
1092
  describedByValue += ` ${hintId}`;
3020
1093
  hintComponent = jsx(Hint, { ...hint, id: hintId });
3021
1094
  }
3022
1095
  if (errorMessage) {
3023
- const errorId = id ? `${id}-error` : "";
1096
+ const errorId = resolvedId ? `${resolvedId}-error` : "";
3024
1097
  describedByValue += ` ${errorId}`;
3025
1098
  errorMessageComponent = jsx(ErrorMessage, { ...errorMessage, id: errorId });
3026
1099
  }
@@ -3043,8 +1116,8 @@ const PasswordInput = React3__default.forwardRef((props, ref) => {
3043
1116
  i18nProps["data-i18n.password-hidden-announcement"] =
3044
1117
  passwordHiddenAnnouncementText;
3045
1118
  // Label handles isPageHeading internally — no extra wrapper needed here
3046
- const labelEl = jsx(Label, { ...label, htmlFor: id });
3047
- return (jsxs("div", { className: `govuk-form-group${formGroup?.className ? ` ${formGroup.className}` : ""}${errorMessage ? " govuk-form-group--error" : ""} govuk-password-input`, "data-module": "govuk-password-input", ...i18nProps, children: [labelEl, hintComponent, errorMessageComponent, jsxs("div", { className: "govuk-input__wrapper govuk-password-input__wrapper", children: [jsx("input", { ref: ref, id: id, className: `govuk-input govuk-password-input__input govuk-js-password-input-input${className ? ` ${className}` : ""}${errorMessage ? " govuk-input--error" : ""}`, name: name || id, type: "password", spellCheck: false, autoComplete: autoComplete, autoCapitalize: "none", "aria-describedby": describedByValue.trim() || undefined, ...attributes }), jsx("button", { type: "button", className: "govuk-button govuk-button--secondary govuk-password-input__toggle govuk-js-password-input-toggle", "data-module": "govuk-button", "aria-controls": id, "aria-label": showPasswordAriaLabelText, hidden: true, children: showPasswordText })] })] }));
1119
+ const labelEl = jsx(Label, { ...label, htmlFor: resolvedId });
1120
+ return (jsxs("div", { className: `govuk-form-group${formGroup?.className ? ` ${formGroup.className}` : ""}${errorMessage ? " govuk-form-group--error" : ""} govuk-password-input`, "data-module": "govuk-password-input", ...i18nProps, children: [labelEl, hintComponent, errorMessageComponent, jsxs("div", { className: "govuk-input__wrapper govuk-password-input__wrapper", children: [jsx("input", { ref: ref, id: resolvedId, className: `govuk-input govuk-password-input__input govuk-js-password-input-input${className ? ` ${className}` : ""}${errorMessage ? " govuk-input--error" : ""}`, name: name || resolvedId, type: "password", spellCheck: false, autoComplete: autoComplete, autoCapitalize: "none", "aria-describedby": describedByValue.trim() || undefined, ...attributes }), jsx("button", { type: "button", className: "govuk-button govuk-button--secondary govuk-password-input__toggle govuk-js-password-input-toggle", "data-module": "govuk-button", "aria-controls": resolvedId, "aria-label": showPasswordAriaLabelText, hidden: true, children: showPasswordText })] })] }));
3048
1121
  });
3049
1122
  PasswordInput.displayName = "PasswordInput";
3050
1123
 
@@ -3168,7 +1241,7 @@ const ResolvePDFSource = (source) => {
3168
1241
  };
3169
1242
 
3170
1243
  const PDFViewer = (props) => {
3171
- const viewerRef = React3__default.useRef(null);
1244
+ const viewerRef = React__default.useRef(null);
3172
1245
  const { iframeId, src, viewerLocation, documentName, documentNameColour, backend, toolbar = "minimal", additionalBackendAttributes,
3173
1246
  // optional: lets callers skip client-side fetch for remote resources
3174
1247
  disableClientFetch = false, ...attributes } = props;
@@ -3420,17 +1493,21 @@ function ConfigureOverallRadios($scope) {
3420
1493
  }
3421
1494
 
3422
1495
  const Select = (props) => {
3423
- const { className, "aria-describedby": describedBy, errorMessage, formGroup, hint, id, items, label, ...attributes } = props;
1496
+ const { className, "aria-describedby": describedBy, errorMessage, formGroup, hint, id, name, items, label, ...attributes } = props;
1497
+ // Mirrors govuk-frontend's Nunjucks macro, which defaults id to name when
1498
+ // id isn't given - without this the select has no id, so its <label for>
1499
+ // (and hint/error aria-describedby) can never associate with it.
1500
+ const resolvedId = id || name;
3424
1501
  let describedByValue = describedBy || "";
3425
1502
  let hintComponent;
3426
1503
  let errorMessageComponent;
3427
1504
  if (hint) {
3428
- const hintId = `${id}-hint`;
1505
+ const hintId = `${resolvedId}-hint`;
3429
1506
  describedByValue += ` ${hintId}`;
3430
1507
  hintComponent = jsx(Hint, { ...hint, id: hintId });
3431
1508
  }
3432
1509
  if (errorMessage) {
3433
- const errorId = id ? `${id}-error` : "";
1510
+ const errorId = resolvedId ? `${resolvedId}-error` : "";
3434
1511
  describedByValue += ` ${errorId}`;
3435
1512
  errorMessageComponent = jsx(ErrorMessage, { ...errorMessage, id: errorId });
3436
1513
  }
@@ -3442,12 +1519,12 @@ const Select = (props) => {
3442
1519
  return (createElement("option", { ...optionAttributes, key: reactListKey || index }, children));
3443
1520
  })
3444
1521
  : null;
3445
- return (jsxs("div", { className: `govuk-form-group${errorMessage ? " govuk-form-group--error" : ""} ${formGroup?.className || ""}`, children: [jsx(Label, { ...label, htmlFor: id }), hintComponent, errorMessageComponent, jsx("select", { className: `govuk-select ${className || ""}${errorMessage ? " govuk-select--error" : ""}`, id: id, "aria-describedby": describedByValue || undefined, ...attributes, children: options })] }));
1522
+ return (jsxs("div", { className: `govuk-form-group${errorMessage ? " govuk-form-group--error" : ""} ${formGroup?.className || ""}`, children: [jsx(Label, { ...label, htmlFor: resolvedId }), hintComponent, errorMessageComponent, jsx("select", { className: `govuk-select ${className || ""}${errorMessage ? " govuk-select--error" : ""}`, id: resolvedId, name: name, "aria-describedby": describedByValue || undefined, ...attributes, children: options })] }));
3446
1523
  };
3447
1524
 
3448
1525
  const ServiceNavigation = (props) => {
3449
1526
  const { className, containerClassName = "govuk-width-container", menuButtonLabel = "Show or hide menu", navigation, navigationClassName, navigationLabel = "Menu", serviceName, serviceUrlHref, serviceUrlTo, ...attributes } = props;
3450
- return (jsx("section", { "aria-label": "Service information", className: `govuk-service-navigation ${className || ""}`, "data-module": "govuk-service-navigation", ...attributes, children: jsx("div", { className: `govuk-width-container ${containerClassName}`, children: jsxs("div", { className: "govuk-service-navigation__container", children: [serviceName ? (jsx("span", { className: "govuk-service-navigation__service-name", children: jsx(LinkWithRef, { href: serviceUrlHref, to: serviceUrlTo, className: "govuk-header__link govuk-header__link--service-name", children: serviceName }) })) : null, navigation ? (jsxs("nav", { "aria-label": navigationLabel, className: `govuk-service-navigation__wrapper ${navigationClassName || ""}`, children: [jsx("button", { type: "button", className: "govuk-service-navigation__toggle govuk-js-service-navigation-toggle", "aria-controls": "navigation", "aria-label": menuButtonLabel, hidden: true, children: "Menu" }), jsx("ul", { className: "govuk-service-navigation__list", id: "navigation", children: navigation.map((item, index) => {
1527
+ return (jsx("section", { "aria-label": "Service information", className: `govuk-service-navigation ${className || ""}`, "data-module": "govuk-service-navigation", ...attributes, children: jsx("div", { className: `govuk-width-container ${containerClassName}`, children: jsxs("div", { className: "govuk-service-navigation__container", children: [serviceName ? (jsx("span", { className: "govuk-service-navigation__service-name", children: jsx(LinkWithRef, { href: serviceUrlHref, to: serviceUrlTo, className: "govuk-service-navigation__link", children: serviceName }) })) : null, navigation ? (jsxs("nav", { "aria-label": navigationLabel, className: `govuk-service-navigation__wrapper ${navigationClassName || ""}`, children: [jsx("button", { type: "button", className: "govuk-service-navigation__toggle govuk-js-service-navigation-toggle", "aria-controls": "navigation", "aria-label": menuButtonLabel, hidden: true, children: "Menu" }), jsx("ul", { className: "govuk-service-navigation__list", id: "navigation", children: navigation.map((item, index) => {
3451
1528
  const { active: itemActive, className: itemClassName, children: itemChildren, reactListKey, ...itemAttributes } = item;
3452
1529
  return itemChildren ? (jsx("li", { className: `govuk-service-navigation__item${itemActive
3453
1530
  ? " govuk-service-navigation__item--active"