UNPKG

50 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, '__esModule', {
4 value: true
5});
6
7var clientLogger = require('@storybook/client-logger');
8
9var memoize = require('memoizerific');
10
11var qs = require('qs');
12
13var React = require('react');
14
15function _interopDefaultLegacy(e) {
16 return e && typeof e === 'object' && 'default' in e ? e : {
17 'default': e
18 };
19}
20
21var memoize__default = /*#__PURE__*/_interopDefaultLegacy(memoize);
22
23var qs__default = /*#__PURE__*/_interopDefaultLegacy(qs);
24
25var React__default = /*#__PURE__*/_interopDefaultLegacy(React);
26
27var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
28
29var fastDeepEqual = function equal(a, b) {
30 if (a === b) return true;
31
32 if (a && b && typeof a == 'object' && typeof b == 'object') {
33 if (a.constructor !== b.constructor) return false;
34 var length, i, keys;
35
36 if (Array.isArray(a)) {
37 length = a.length;
38 if (length != b.length) return false;
39
40 for (i = length; i-- !== 0;) if (!equal(a[i], b[i])) return false;
41
42 return true;
43 }
44
45 if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
46 if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();
47 if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();
48 keys = Object.keys(a);
49 length = keys.length;
50 if (length !== Object.keys(b).length) return false;
51
52 for (i = length; i-- !== 0;) if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;
53
54 for (i = length; i-- !== 0;) {
55 var key = keys[i];
56 if (!equal(a[key], b[key])) return false;
57 }
58
59 return true;
60 } // true if both NaN, false otherwise
61
62
63 return a !== a && b !== b;
64};
65/** Detect free variable `global` from Node.js. */
66
67
68var freeGlobal$1 = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
69var _freeGlobal = freeGlobal$1;
70var freeGlobal = _freeGlobal;
71/** Detect free variable `self`. */
72
73var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
74/** Used as a reference to the global object. */
75
76var root$1 = freeGlobal || freeSelf || Function('return this')();
77var _root = root$1;
78var root = _root;
79/** Built-in value references. */
80
81var Symbol$3 = root.Symbol;
82var _Symbol = Symbol$3;
83var Symbol$2 = _Symbol;
84/** Used for built-in method references. */
85
86var objectProto$2 = Object.prototype;
87/** Used to check objects for own properties. */
88
89var hasOwnProperty$1 = objectProto$2.hasOwnProperty;
90/**
91 * Used to resolve the
92 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
93 * of values.
94 */
95
96var nativeObjectToString$1 = objectProto$2.toString;
97/** Built-in value references. */
98
99var symToStringTag$1 = Symbol$2 ? Symbol$2.toStringTag : undefined;
100/**
101 * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
102 *
103 * @private
104 * @param {*} value The value to query.
105 * @returns {string} Returns the raw `toStringTag`.
106 */
107
108function getRawTag$1(value) {
109 var isOwn = hasOwnProperty$1.call(value, symToStringTag$1),
110 tag = value[symToStringTag$1];
111
112 try {
113 value[symToStringTag$1] = undefined;
114 var unmasked = true;
115 } catch (e) {}
116
117 var result = nativeObjectToString$1.call(value);
118
119 if (unmasked) {
120 if (isOwn) {
121 value[symToStringTag$1] = tag;
122 } else {
123 delete value[symToStringTag$1];
124 }
125 }
126
127 return result;
128}
129
130var _getRawTag = getRawTag$1;
131/** Used for built-in method references. */
132
133var objectProto$1 = Object.prototype;
134/**
135 * Used to resolve the
136 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
137 * of values.
138 */
139
140var nativeObjectToString = objectProto$1.toString;
141/**
142 * Converts `value` to a string using `Object.prototype.toString`.
143 *
144 * @private
145 * @param {*} value The value to convert.
146 * @returns {string} Returns the converted string.
147 */
148
149function objectToString$1(value) {
150 return nativeObjectToString.call(value);
151}
152
153var _objectToString = objectToString$1;
154var Symbol$1 = _Symbol,
155 getRawTag = _getRawTag,
156 objectToString = _objectToString;
157/** `Object#toString` result references. */
158
159var nullTag = '[object Null]',
160 undefinedTag = '[object Undefined]';
161/** Built-in value references. */
162
163var symToStringTag = Symbol$1 ? Symbol$1.toStringTag : undefined;
164/**
165 * The base implementation of `getTag` without fallbacks for buggy environments.
166 *
167 * @private
168 * @param {*} value The value to query.
169 * @returns {string} Returns the `toStringTag`.
170 */
171
172function baseGetTag$1(value) {
173 if (value == null) {
174 return value === undefined ? undefinedTag : nullTag;
175 }
176
177 return symToStringTag && symToStringTag in Object(value) ? getRawTag(value) : objectToString(value);
178}
179
180var _baseGetTag = baseGetTag$1;
181/**
182 * Creates a unary function that invokes `func` with its argument transformed.
183 *
184 * @private
185 * @param {Function} func The function to wrap.
186 * @param {Function} transform The argument transform.
187 * @returns {Function} Returns the new function.
188 */
189
190function overArg$1(func, transform) {
191 return function (arg) {
192 return func(transform(arg));
193 };
194}
195
196var _overArg = overArg$1;
197var overArg = _overArg;
198/** Built-in value references. */
199
200var getPrototype$1 = overArg(Object.getPrototypeOf, Object);
201var _getPrototype = getPrototype$1;
202/**
203 * Checks if `value` is object-like. A value is object-like if it's not `null`
204 * and has a `typeof` result of "object".
205 *
206 * @static
207 * @memberOf _
208 * @since 4.0.0
209 * @category Lang
210 * @param {*} value The value to check.
211 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
212 * @example
213 *
214 * _.isObjectLike({});
215 * // => true
216 *
217 * _.isObjectLike([1, 2, 3]);
218 * // => true
219 *
220 * _.isObjectLike(_.noop);
221 * // => false
222 *
223 * _.isObjectLike(null);
224 * // => false
225 */
226
227function isObjectLike$1(value) {
228 return value != null && typeof value == 'object';
229}
230
231var isObjectLike_1 = isObjectLike$1;
232var baseGetTag = _baseGetTag,
233 getPrototype = _getPrototype,
234 isObjectLike = isObjectLike_1;
235/** `Object#toString` result references. */
236
237var objectTag = '[object Object]';
238/** Used for built-in method references. */
239
240var funcProto = Function.prototype,
241 objectProto = Object.prototype;
242/** Used to resolve the decompiled source of functions. */
243
244var funcToString = funcProto.toString;
245/** Used to check objects for own properties. */
246
247var hasOwnProperty = objectProto.hasOwnProperty;
248/** Used to infer the `Object` constructor. */
249
250var objectCtorString = funcToString.call(Object);
251/**
252 * Checks if `value` is a plain object, that is, an object created by the
253 * `Object` constructor or one with a `[[Prototype]]` of `null`.
254 *
255 * @static
256 * @memberOf _
257 * @since 0.8.0
258 * @category Lang
259 * @param {*} value The value to check.
260 * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
261 * @example
262 *
263 * function Foo() {
264 * this.a = 1;
265 * }
266 *
267 * _.isPlainObject(new Foo);
268 * // => false
269 *
270 * _.isPlainObject([1, 2, 3]);
271 * // => false
272 *
273 * _.isPlainObject({ 'x': 0, 'y': 0 });
274 * // => true
275 *
276 * _.isPlainObject(Object.create(null));
277 * // => true
278 */
279
280function isPlainObject(value) {
281 if (!isObjectLike(value) || baseGetTag(value) != objectTag) {
282 return false;
283 }
284
285 var proto = getPrototype(value);
286
287 if (proto === null) {
288 return true;
289 }
290
291 var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;
292 return typeof Ctor == 'function' && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString;
293}
294
295var isPlainObject_1 = isPlainObject;
296
297function dedent(templ) {
298 var values = [];
299
300 for (var _i = 1; _i < arguments.length; _i++) {
301 values[_i - 1] = arguments[_i];
302 }
303
304 var strings = Array.from(typeof templ === 'string' ? [templ] : templ);
305 strings[strings.length - 1] = strings[strings.length - 1].replace(/\r?\n([\t ]*)$/, '');
306 var indentLengths = strings.reduce(function (arr, str) {
307 var matches = str.match(/\n([\t ]+|(?!\s).)/g);
308
309 if (matches) {
310 return arr.concat(matches.map(function (match) {
311 var _a, _b;
312
313 return (_b = (_a = match.match(/[\t ]/g)) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0;
314 }));
315 }
316
317 return arr;
318 }, []);
319
320 if (indentLengths.length) {
321 var pattern_1 = new RegExp("\n[\t ]{" + Math.min.apply(Math, indentLengths) + "}", 'g');
322 strings = strings.map(function (str) {
323 return str.replace(pattern_1, '\n');
324 });
325 }
326
327 strings[0] = strings[0].replace(/^\r?\n/, '');
328 var string = strings[0];
329 values.forEach(function (value, i) {
330 var endentations = string.match(/(?:^|\n)( *)$/);
331 var endentation = endentations ? endentations[1] : '';
332 var indentedValue = value;
333
334 if (typeof value === 'string' && value.includes('\n')) {
335 indentedValue = String(value).split('\n').map(function (str, i) {
336 return i === 0 ? str : "" + endentation + str;
337 }).join('\n');
338 }
339
340 string += indentedValue + strings[i + 1];
341 });
342 return string;
343}
344
345const splitPathRegex = /\/([^/]+)\/(?:(.*)_)?([^/]+)?/;
346const parsePath$2 = memoize__default["default"](1000)(path => {
347 const result = {
348 viewMode: undefined,
349 storyId: undefined,
350 refId: undefined
351 };
352
353 if (path) {
354 const [, viewMode, refId, storyId] = path.toLowerCase().match(splitPathRegex) || [];
355
356 if (viewMode) {
357 Object.assign(result, {
358 viewMode,
359 storyId,
360 refId
361 });
362 }
363 }
364
365 return result;
366});
367const DEEPLY_EQUAL = Symbol('Deeply equal');
368
369const deepDiff = (value, update) => {
370 if (typeof value !== typeof update) return update;
371 if (fastDeepEqual(value, update)) return DEEPLY_EQUAL;
372
373 if (Array.isArray(value) && Array.isArray(update)) {
374 const res = update.reduce((acc, upd, index) => {
375 const diff = deepDiff(value[index], upd);
376 if (diff !== DEEPLY_EQUAL) acc[index] = diff;
377 return acc;
378 }, new Array(update.length));
379 if (update.length >= value.length) return res;
380 return res.concat(new Array(value.length - update.length).fill(undefined));
381 }
382
383 if (isPlainObject_1(value) && isPlainObject_1(update)) {
384 return Object.keys(Object.assign(Object.assign({}, value), update)).reduce((acc, key) => {
385 const diff = deepDiff(value === null || value === void 0 ? void 0 : value[key], update === null || update === void 0 ? void 0 : update[key]);
386 return diff === DEEPLY_EQUAL ? acc : Object.assign(acc, {
387 [key]: diff
388 });
389 }, {});
390 }
391
392 return update;
393}; // Keep this in sync with validateArgs in core-client/src/preview/parseArgsParam.ts
394
395
396const VALIDATION_REGEXP = /^[a-zA-Z0-9 _-]*$/;
397const NUMBER_REGEXP = /^-?[0-9]+(\.[0-9]+)?$/;
398const HEX_REGEXP = /^#([a-f0-9]{3,4}|[a-f0-9]{6}|[a-f0-9]{8})$/i;
399const COLOR_REGEXP = /^(rgba?|hsla?)\(([0-9]{1,3}),\s?([0-9]{1,3})%?,\s?([0-9]{1,3})%?,?\s?([0-9](\.[0-9]{1,2})?)?\)$/i;
400
401const validateArgs = (key = '', value) => {
402 if (key === null) return false;
403 if (key === '' || !VALIDATION_REGEXP.test(key)) return false;
404 if (value === null || value === undefined) return true; // encoded as `!null` or `!undefined`
405
406 if (value instanceof Date) return true; // encoded as modified ISO string
407
408 if (typeof value === 'number' || typeof value === 'boolean') return true;
409
410 if (typeof value === 'string') {
411 return VALIDATION_REGEXP.test(value) || NUMBER_REGEXP.test(value) || HEX_REGEXP.test(value) || COLOR_REGEXP.test(value);
412 }
413
414 if (Array.isArray(value)) return value.every(v => validateArgs(key, v));
415 if (isPlainObject_1(value)) return Object.entries(value).every(([k, v]) => validateArgs(k, v));
416 return false;
417};
418
419const encodeSpecialValues = value => {
420 if (value === undefined) return '!undefined';
421 if (value === null) return '!null';
422
423 if (typeof value === 'string') {
424 if (HEX_REGEXP.test(value)) return `!hex(${value.slice(1)})`;
425 if (COLOR_REGEXP.test(value)) return `!${value.replace(/[\s%]/g, '')}`;
426 return value;
427 }
428
429 if (Array.isArray(value)) return value.map(encodeSpecialValues);
430
431 if (isPlainObject_1(value)) {
432 return Object.entries(value).reduce((acc, [key, val]) => Object.assign(acc, {
433 [key]: encodeSpecialValues(val)
434 }), {});
435 }
436
437 return value;
438};
439
440const QS_OPTIONS = {
441 encode: false,
442 delimiter: ';',
443 allowDots: true,
444 format: 'RFC1738',
445 serializeDate: date => `!date(${date.toISOString()})`
446};
447
448const buildArgsParam = (initialArgs, args) => {
449 const update = deepDiff(initialArgs, args);
450 if (!update || update === DEEPLY_EQUAL) return '';
451 const object = Object.entries(update).reduce((acc, [key, value]) => {
452 if (validateArgs(key, value)) return Object.assign(acc, {
453 [key]: value
454 });
455 clientLogger.once.warn(dedent`
456 Omitted potentially unsafe URL args.
457
458 More info: https://storybook.js.org/docs/react/writing-stories/args#setting-args-through-the-url
459 `);
460 return acc;
461 }, {});
462 return qs__default["default"].stringify(encodeSpecialValues(object), QS_OPTIONS).replace(/ /g, '+').split(';').map(part => part.replace('=', ':')).join(';');
463};
464
465const queryFromString = memoize__default["default"](1000)(s => qs__default["default"].parse(s, {
466 ignoreQueryPrefix: true
467}));
468
469const queryFromLocation = location => queryFromString(location.search);
470
471const stringifyQuery = query => qs__default["default"].stringify(query, {
472 addQueryPrefix: true,
473 encode: false
474});
475
476const getMatch = memoize__default["default"](1000)((current, target, startsWith = true) => {
477 const startsWithTarget = current && startsWith && current.startsWith(target);
478 const currentIsTarget = typeof target === 'string' && current === target;
479 const matchTarget = current && target && current.match(target);
480
481 if (startsWithTarget || currentIsTarget || matchTarget) {
482 return {
483 path: current
484 };
485 }
486
487 return null;
488});
489/*! *****************************************************************************
490Copyright (c) Microsoft Corporation.
491
492Permission to use, copy, modify, and/or distribute this software for any
493purpose with or without fee is hereby granted.
494
495THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
496REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
497AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
498INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
499LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
500OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
501PERFORMANCE OF THIS SOFTWARE.
502***************************************************************************** */
503
504function __rest(s, e) {
505 var t = {};
506
507 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
508
509 if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
510 if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
511 }
512 return t;
513}
514
515var win;
516
517if (typeof window !== "undefined") {
518 win = window;
519} else if (typeof commonjsGlobal !== "undefined") {
520 win = commonjsGlobal;
521} else if (typeof self !== "undefined") {
522 win = self;
523} else {
524 win = {};
525}
526
527var window_1 = win;
528
529function _extends$1() {
530 _extends$1 = Object.assign || function (target) {
531 for (var i = 1; i < arguments.length; i++) {
532 var source = arguments[i];
533
534 for (var key in source) {
535 if (Object.prototype.hasOwnProperty.call(source, key)) {
536 target[key] = source[key];
537 }
538 }
539 }
540
541 return target;
542 };
543
544 return _extends$1.apply(this, arguments);
545}
546/**
547 * Actions represent the type of change to a location value.
548 *
549 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#action
550 */
551
552
553var Action$1;
554
555(function (Action) {
556 /**
557 * A POP indicates a change to an arbitrary index in the history stack, such
558 * as a back or forward navigation. It does not describe the direction of the
559 * navigation, only that the current index changed.
560 *
561 * Note: This is the default action for newly created history objects.
562 */
563 Action["Pop"] = "POP";
564 /**
565 * A PUSH indicates a new entry being added to the history stack, such as when
566 * a link is clicked and a new page loads. When this happens, all subsequent
567 * entries in the stack are lost.
568 */
569
570 Action["Push"] = "PUSH";
571 /**
572 * A REPLACE indicates the entry at the current index in the history stack
573 * being replaced by a new one.
574 */
575
576 Action["Replace"] = "REPLACE";
577})(Action$1 || (Action$1 = {}));
578
579var readOnly = process.env.NODE_ENV !== "production" ? function (obj) {
580 return Object.freeze(obj);
581} : function (obj) {
582 return obj;
583};
584
585function warning$1(cond, message) {
586 if (!cond) {
587 // eslint-disable-next-line no-console
588 if (typeof console !== 'undefined') console.warn(message);
589
590 try {
591 // Welcome to debugging history!
592 //
593 // This error is thrown as a convenience so you can more easily
594 // find the source for a warning that appears in the console by
595 // enabling "pause on exceptions" in your JavaScript debugger.
596 throw new Error(message); // eslint-disable-next-line no-empty
597 } catch (e) {}
598 }
599}
600
601var BeforeUnloadEventType = 'beforeunload';
602var PopStateEventType = 'popstate';
603/**
604 * Browser history stores the location in regular URLs. This is the standard for
605 * most web apps, but it requires some configuration on the server to ensure you
606 * serve the same app at multiple URLs.
607 *
608 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory
609 */
610
611function createBrowserHistory(options) {
612 if (options === void 0) {
613 options = {};
614 }
615
616 var _options = options,
617 _options$window = _options.window,
618 window = _options$window === void 0 ? document.defaultView : _options$window;
619 var globalHistory = window.history;
620
621 function getIndexAndLocation() {
622 var _window$location = window.location,
623 pathname = _window$location.pathname,
624 search = _window$location.search,
625 hash = _window$location.hash;
626 var state = globalHistory.state || {};
627 return [state.idx, readOnly({
628 pathname: pathname,
629 search: search,
630 hash: hash,
631 state: state.usr || null,
632 key: state.key || 'default'
633 })];
634 }
635
636 var blockedPopTx = null;
637
638 function handlePop() {
639 if (blockedPopTx) {
640 blockers.call(blockedPopTx);
641 blockedPopTx = null;
642 } else {
643 var nextAction = Action$1.Pop;
644
645 var _getIndexAndLocation = getIndexAndLocation(),
646 nextIndex = _getIndexAndLocation[0],
647 nextLocation = _getIndexAndLocation[1];
648
649 if (blockers.length) {
650 if (nextIndex != null) {
651 var delta = index - nextIndex;
652
653 if (delta) {
654 // Revert the POP
655 blockedPopTx = {
656 action: nextAction,
657 location: nextLocation,
658 retry: function retry() {
659 go(delta * -1);
660 }
661 };
662 go(delta);
663 }
664 } else {
665 // Trying to POP to a location with no index. We did not create
666 // this location, so we can't effectively block the navigation.
667 process.env.NODE_ENV !== "production" ? warning$1(false, // TODO: Write up a doc that explains our blocking strategy in
668 // detail and link to it here so people can understand better what
669 // is going on and how to avoid it.
670 "You are trying to block a POP navigation to a location that was not " + "created by the history library. The block will fail silently in " + "production, but in general you should do all navigation with the " + "history library (instead of using window.history.pushState directly) " + "to avoid this situation.") : void 0;
671 }
672 } else {
673 applyTx(nextAction);
674 }
675 }
676 }
677
678 window.addEventListener(PopStateEventType, handlePop);
679 var action = Action$1.Pop;
680
681 var _getIndexAndLocation2 = getIndexAndLocation(),
682 index = _getIndexAndLocation2[0],
683 location = _getIndexAndLocation2[1];
684
685 var listeners = createEvents();
686 var blockers = createEvents();
687
688 if (index == null) {
689 index = 0;
690 globalHistory.replaceState(_extends$1({}, globalHistory.state, {
691 idx: index
692 }), '');
693 }
694
695 function createHref(to) {
696 return typeof to === 'string' ? to : createPath(to);
697 } // state defaults to `null` because `window.history.state` does
698
699
700 function getNextLocation(to, state) {
701 if (state === void 0) {
702 state = null;
703 }
704
705 return readOnly(_extends$1({
706 pathname: location.pathname,
707 hash: '',
708 search: ''
709 }, typeof to === 'string' ? parsePath$1(to) : to, {
710 state: state,
711 key: createKey()
712 }));
713 }
714
715 function getHistoryStateAndUrl(nextLocation, index) {
716 return [{
717 usr: nextLocation.state,
718 key: nextLocation.key,
719 idx: index
720 }, createHref(nextLocation)];
721 }
722
723 function allowTx(action, location, retry) {
724 return !blockers.length || (blockers.call({
725 action: action,
726 location: location,
727 retry: retry
728 }), false);
729 }
730
731 function applyTx(nextAction) {
732 action = nextAction;
733
734 var _getIndexAndLocation3 = getIndexAndLocation();
735
736 index = _getIndexAndLocation3[0];
737 location = _getIndexAndLocation3[1];
738 listeners.call({
739 action: action,
740 location: location
741 });
742 }
743
744 function push(to, state) {
745 var nextAction = Action$1.Push;
746 var nextLocation = getNextLocation(to, state);
747
748 function retry() {
749 push(to, state);
750 }
751
752 if (allowTx(nextAction, nextLocation, retry)) {
753 var _getHistoryStateAndUr = getHistoryStateAndUrl(nextLocation, index + 1),
754 historyState = _getHistoryStateAndUr[0],
755 url = _getHistoryStateAndUr[1]; // TODO: Support forced reloading
756 // try...catch because iOS limits us to 100 pushState calls :/
757
758
759 try {
760 globalHistory.pushState(historyState, '', url);
761 } catch (error) {
762 // They are going to lose state here, but there is no real
763 // way to warn them about it since the page will refresh...
764 window.location.assign(url);
765 }
766
767 applyTx(nextAction);
768 }
769 }
770
771 function replace(to, state) {
772 var nextAction = Action$1.Replace;
773 var nextLocation = getNextLocation(to, state);
774
775 function retry() {
776 replace(to, state);
777 }
778
779 if (allowTx(nextAction, nextLocation, retry)) {
780 var _getHistoryStateAndUr2 = getHistoryStateAndUrl(nextLocation, index),
781 historyState = _getHistoryStateAndUr2[0],
782 url = _getHistoryStateAndUr2[1]; // TODO: Support forced reloading
783
784
785 globalHistory.replaceState(historyState, '', url);
786 applyTx(nextAction);
787 }
788 }
789
790 function go(delta) {
791 globalHistory.go(delta);
792 }
793
794 var history = {
795 get action() {
796 return action;
797 },
798
799 get location() {
800 return location;
801 },
802
803 createHref: createHref,
804 push: push,
805 replace: replace,
806 go: go,
807 back: function back() {
808 go(-1);
809 },
810 forward: function forward() {
811 go(1);
812 },
813 listen: function listen(listener) {
814 return listeners.push(listener);
815 },
816 block: function block(blocker) {
817 var unblock = blockers.push(blocker);
818
819 if (blockers.length === 1) {
820 window.addEventListener(BeforeUnloadEventType, promptBeforeUnload);
821 }
822
823 return function () {
824 unblock(); // Remove the beforeunload listener so the document may
825 // still be salvageable in the pagehide event.
826 // See https://html.spec.whatwg.org/#unloading-documents
827
828 if (!blockers.length) {
829 window.removeEventListener(BeforeUnloadEventType, promptBeforeUnload);
830 }
831 };
832 }
833 };
834 return history;
835}
836
837function promptBeforeUnload(event) {
838 // Cancel the event.
839 event.preventDefault(); // Chrome (and legacy IE) requires returnValue to be set.
840
841 event.returnValue = '';
842}
843
844function createEvents() {
845 var handlers = [];
846 return {
847 get length() {
848 return handlers.length;
849 },
850
851 push: function push(fn) {
852 handlers.push(fn);
853 return function () {
854 handlers = handlers.filter(function (handler) {
855 return handler !== fn;
856 });
857 };
858 },
859 call: function call(arg) {
860 handlers.forEach(function (fn) {
861 return fn && fn(arg);
862 });
863 }
864 };
865}
866
867function createKey() {
868 return Math.random().toString(36).substr(2, 8);
869}
870/**
871 * Creates a string URL path from the given pathname, search, and hash components.
872 *
873 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createpath
874 */
875
876
877function createPath(_ref) {
878 var _ref$pathname = _ref.pathname,
879 pathname = _ref$pathname === void 0 ? '/' : _ref$pathname,
880 _ref$search = _ref.search,
881 search = _ref$search === void 0 ? '' : _ref$search,
882 _ref$hash = _ref.hash,
883 hash = _ref$hash === void 0 ? '' : _ref$hash;
884 if (search && search !== '?') pathname += search.charAt(0) === '?' ? search : '?' + search;
885 if (hash && hash !== '#') pathname += hash.charAt(0) === '#' ? hash : '#' + hash;
886 return pathname;
887}
888/**
889 * Parses a string URL path into its separate pathname, search, and hash components.
890 *
891 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#parsepath
892 */
893
894
895function parsePath$1(path) {
896 var parsedPath = {};
897
898 if (path) {
899 var hashIndex = path.indexOf('#');
900
901 if (hashIndex >= 0) {
902 parsedPath.hash = path.substr(hashIndex);
903 path = path.substr(0, hashIndex);
904 }
905
906 var searchIndex = path.indexOf('?');
907
908 if (searchIndex >= 0) {
909 parsedPath.search = path.substr(searchIndex);
910 path = path.substr(0, searchIndex);
911 }
912
913 if (path) {
914 parsedPath.pathname = path;
915 }
916 }
917
918 return parsedPath;
919}
920/**
921 * Actions represent the type of change to a location value.
922 *
923 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#action
924 */
925
926
927var Action;
928
929(function (Action) {
930 /**
931 * A POP indicates a change to an arbitrary index in the history stack, such
932 * as a back or forward navigation. It does not describe the direction of the
933 * navigation, only that the current index changed.
934 *
935 * Note: This is the default action for newly created history objects.
936 */
937 Action["Pop"] = "POP";
938 /**
939 * A PUSH indicates a new entry being added to the history stack, such as when
940 * a link is clicked and a new page loads. When this happens, all subsequent
941 * entries in the stack are lost.
942 */
943
944 Action["Push"] = "PUSH";
945 /**
946 * A REPLACE indicates the entry at the current index in the history stack
947 * being replaced by a new one.
948 */
949
950 Action["Replace"] = "REPLACE";
951})(Action || (Action = {}));
952
953process.env.NODE_ENV !== "production" ? function (obj) {
954 return Object.freeze(obj);
955} : function (obj) {
956 return obj;
957};
958/**
959 * Parses a string URL path into its separate pathname, search, and hash components.
960 *
961 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#parsepath
962 */
963
964function parsePath(path) {
965 var parsedPath = {};
966
967 if (path) {
968 var hashIndex = path.indexOf('#');
969
970 if (hashIndex >= 0) {
971 parsedPath.hash = path.substr(hashIndex);
972 path = path.substr(0, hashIndex);
973 }
974
975 var searchIndex = path.indexOf('?');
976
977 if (searchIndex >= 0) {
978 parsedPath.search = path.substr(searchIndex);
979 path = path.substr(0, searchIndex);
980 }
981
982 if (path) {
983 parsedPath.pathname = path;
984 }
985 }
986
987 return parsedPath;
988}
989/**
990 * React Router v6.0.2
991 *
992 * Copyright (c) Remix Software Inc.
993 *
994 * This source code is licensed under the MIT license found in the
995 * LICENSE.md file in the root directory of this source tree.
996 *
997 * @license MIT
998 */
999
1000
1001function invariant(cond, message) {
1002 if (!cond) throw new Error(message);
1003}
1004
1005function warning(cond, message) {
1006 if (!cond) {
1007 // eslint-disable-next-line no-console
1008 if (typeof console !== "undefined") console.warn(message);
1009
1010 try {
1011 // Welcome to debugging React Router!
1012 //
1013 // This error is thrown as a convenience so you can more easily
1014 // find the source for a warning that appears in the console by
1015 // enabling "pause on exceptions" in your JavaScript debugger.
1016 throw new Error(message); // eslint-disable-next-line no-empty
1017 } catch (e) {}
1018 }
1019} // CONTEXT
1020///////////////////////////////////////////////////////////////////////////////
1021
1022/**
1023 * A Navigator is a "location changer"; it's how you get to different locations.
1024 *
1025 * Every history instance conforms to the Navigator interface, but the
1026 * distinction is useful primarily when it comes to the low-level <Router> API
1027 * where both the location and a navigator must be provided separately in order
1028 * to avoid "tearing" that may occur in a suspense-enabled app if the action
1029 * and/or location were to be read directly from the history instance.
1030 */
1031
1032
1033const NavigationContext = /*#__PURE__*/React.createContext(null);
1034
1035if (process.env.NODE_ENV !== "production") {
1036 NavigationContext.displayName = "Navigation";
1037}
1038
1039const LocationContext = /*#__PURE__*/React.createContext(null);
1040
1041if (process.env.NODE_ENV !== "production") {
1042 LocationContext.displayName = "Location";
1043}
1044
1045const RouteContext = /*#__PURE__*/React.createContext({
1046 outlet: null,
1047 matches: []
1048});
1049
1050if (process.env.NODE_ENV !== "production") {
1051 RouteContext.displayName = "Route";
1052} ///////////////////////////////////////////////////////////////////////////////
1053
1054/**
1055 * Provides location context for the rest of the app.
1056 *
1057 * Note: You usually won't render a <Router> directly. Instead, you'll render a
1058 * router that is more specific to your environment such as a <BrowserRouter>
1059 * in web browsers or a <StaticRouter> for server rendering.
1060 *
1061 * @see https://reactrouter.com/docs/en/v6/api#router
1062 */
1063
1064
1065function Router(_ref3) {
1066 let {
1067 basename: basenameProp = "/",
1068 children = null,
1069 location: locationProp,
1070 navigationType = Action.Pop,
1071 navigator,
1072 static: staticProp = false
1073 } = _ref3;
1074 !!useInRouterContext() ? process.env.NODE_ENV !== "production" ? invariant(false, "You cannot render a <Router> inside another <Router>." + " You should never have more than one in your app.") : invariant(false) : void 0;
1075 let basename = normalizePathname(basenameProp);
1076 let navigationContext = React.useMemo(() => ({
1077 basename,
1078 navigator,
1079 static: staticProp
1080 }), [basename, navigator, staticProp]);
1081
1082 if (typeof locationProp === "string") {
1083 locationProp = parsePath(locationProp);
1084 }
1085
1086 let {
1087 pathname = "/",
1088 search = "",
1089 hash = "",
1090 state = null,
1091 key = "default"
1092 } = locationProp;
1093 let location = React.useMemo(() => {
1094 let trailingPathname = stripBasename(pathname, basename);
1095
1096 if (trailingPathname == null) {
1097 return null;
1098 }
1099
1100 return {
1101 pathname: trailingPathname,
1102 search,
1103 hash,
1104 state,
1105 key
1106 };
1107 }, [basename, pathname, search, hash, state, key]);
1108 process.env.NODE_ENV !== "production" ? warning(location != null, "<Router basename=\"" + basename + "\"> is not able to match the URL " + ("\"" + pathname + search + hash + "\" because it does not start with the ") + "basename, so the <Router> won't render anything.") : void 0;
1109
1110 if (location == null) {
1111 return null;
1112 }
1113
1114 return /*#__PURE__*/React.createElement(NavigationContext.Provider, {
1115 value: navigationContext
1116 }, /*#__PURE__*/React.createElement(LocationContext.Provider, {
1117 children: children,
1118 value: {
1119 location,
1120 navigationType
1121 }
1122 }));
1123} // HOOKS
1124///////////////////////////////////////////////////////////////////////////////
1125
1126/**
1127 * Returns the full href for the given "to" value. This is useful for building
1128 * custom links that are also accessible and preserve right-click behavior.
1129 *
1130 * @see https://reactrouter.com/docs/en/v6/api#usehref
1131 */
1132
1133
1134function useHref(to) {
1135 !useInRouterContext() ? process.env.NODE_ENV !== "production" ? invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
1136 // router loaded. We can help them understand how to avoid that.
1137 "useHref() may be used only in the context of a <Router> component.") : invariant(false) : void 0;
1138 let {
1139 basename,
1140 navigator
1141 } = React.useContext(NavigationContext);
1142 let {
1143 hash,
1144 pathname,
1145 search
1146 } = useResolvedPath(to);
1147 let joinedPathname = pathname;
1148
1149 if (basename !== "/") {
1150 let toPathname = getToPathname(to);
1151 let endsWithSlash = toPathname != null && toPathname.endsWith("/");
1152 joinedPathname = pathname === "/" ? basename + (endsWithSlash ? "/" : "") : joinPaths([basename, pathname]);
1153 }
1154
1155 return navigator.createHref({
1156 pathname: joinedPathname,
1157 search,
1158 hash
1159 });
1160}
1161/**
1162 * Returns true if this component is a descendant of a <Router>.
1163 *
1164 * @see https://reactrouter.com/docs/en/v6/api#useinroutercontext
1165 */
1166
1167
1168function useInRouterContext() {
1169 return React.useContext(LocationContext) != null;
1170}
1171/**
1172 * Returns the current location object, which represents the current URL in web
1173 * browsers.
1174 *
1175 * Note: If you're using this it may mean you're doing some of your own
1176 * "routing" in your app, and we'd like to know what your use case is. We may
1177 * be able to provide something higher-level to better suit your needs.
1178 *
1179 * @see https://reactrouter.com/docs/en/v6/api#uselocation
1180 */
1181
1182
1183function useLocation() {
1184 !useInRouterContext() ? process.env.NODE_ENV !== "production" ? invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
1185 // router loaded. We can help them understand how to avoid that.
1186 "useLocation() may be used only in the context of a <Router> component.") : invariant(false) : void 0;
1187 return React.useContext(LocationContext).location;
1188}
1189/**
1190 * The interface for the navigate() function returned from useNavigate().
1191 */
1192
1193/**
1194 * Returns an imperative method for changing the location. Used by <Link>s, but
1195 * may also be used by other elements to change the location.
1196 *
1197 * @see https://reactrouter.com/docs/en/v6/api#usenavigate
1198 */
1199
1200
1201function useNavigate$1() {
1202 !useInRouterContext() ? process.env.NODE_ENV !== "production" ? invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
1203 // router loaded. We can help them understand how to avoid that.
1204 "useNavigate() may be used only in the context of a <Router> component.") : invariant(false) : void 0;
1205 let {
1206 basename,
1207 navigator
1208 } = React.useContext(NavigationContext);
1209 let {
1210 matches
1211 } = React.useContext(RouteContext);
1212 let {
1213 pathname: locationPathname
1214 } = useLocation();
1215 let routePathnamesJson = JSON.stringify(matches.map(match => match.pathnameBase));
1216 let activeRef = React.useRef(false);
1217 React.useEffect(() => {
1218 activeRef.current = true;
1219 });
1220 let navigate = React.useCallback(function (to, options) {
1221 if (options === void 0) {
1222 options = {};
1223 }
1224
1225 process.env.NODE_ENV !== "production" ? warning(activeRef.current, "You should call navigate() in a React.useEffect(), not when " + "your component is first rendered.") : void 0;
1226 if (!activeRef.current) return;
1227
1228 if (typeof to === "number") {
1229 navigator.go(to);
1230 return;
1231 }
1232
1233 let path = resolveTo(to, JSON.parse(routePathnamesJson), locationPathname);
1234
1235 if (basename !== "/") {
1236 path.pathname = joinPaths([basename, path.pathname]);
1237 }
1238
1239 (!!options.replace ? navigator.replace : navigator.push)(path, options.state);
1240 }, [basename, navigator, routePathnamesJson, locationPathname]);
1241 return navigate;
1242}
1243/**
1244 * Resolves the pathname of the given `to` value against the current location.
1245 *
1246 * @see https://reactrouter.com/docs/en/v6/api#useresolvedpath
1247 */
1248
1249
1250function useResolvedPath(to) {
1251 let {
1252 matches
1253 } = React.useContext(RouteContext);
1254 let {
1255 pathname: locationPathname
1256 } = useLocation();
1257 let routePathnamesJson = JSON.stringify(matches.map(match => match.pathnameBase));
1258 return React.useMemo(() => resolveTo(to, JSON.parse(routePathnamesJson), locationPathname), [to, routePathnamesJson, locationPathname]);
1259}
1260/**
1261 * Returns a resolved path object relative to the given pathname.
1262 *
1263 * @see https://reactrouter.com/docs/en/v6/api#resolvepath
1264 */
1265
1266
1267function resolvePath(to, fromPathname) {
1268 if (fromPathname === void 0) {
1269 fromPathname = "/";
1270 }
1271
1272 let {
1273 pathname: toPathname,
1274 search = "",
1275 hash = ""
1276 } = typeof to === "string" ? parsePath(to) : to;
1277 let pathname = toPathname ? toPathname.startsWith("/") ? toPathname : resolvePathname(toPathname, fromPathname) : fromPathname;
1278 return {
1279 pathname,
1280 search: normalizeSearch(search),
1281 hash: normalizeHash(hash)
1282 };
1283}
1284
1285function resolvePathname(relativePath, fromPathname) {
1286 let segments = fromPathname.replace(/\/+$/, "").split("/");
1287 let relativeSegments = relativePath.split("/");
1288 relativeSegments.forEach(segment => {
1289 if (segment === "..") {
1290 // Keep the root "" segment so the pathname starts at /
1291 if (segments.length > 1) segments.pop();
1292 } else if (segment !== ".") {
1293 segments.push(segment);
1294 }
1295 });
1296 return segments.length > 1 ? segments.join("/") : "/";
1297}
1298
1299function resolveTo(toArg, routePathnames, locationPathname) {
1300 let to = typeof toArg === "string" ? parsePath(toArg) : toArg;
1301 let toPathname = toArg === "" || to.pathname === "" ? "/" : to.pathname; // If a pathname is explicitly provided in `to`, it should be relative to the
1302 // route context. This is explained in `Note on `<Link to>` values` in our
1303 // migration guide from v5 as a means of disambiguation between `to` values
1304 // that begin with `/` and those that do not. However, this is problematic for
1305 // `to` values that do not provide a pathname. `to` can simply be a search or
1306 // hash string, in which case we should assume that the navigation is relative
1307 // to the current location's pathname and *not* the route pathname.
1308
1309 let from;
1310
1311 if (toPathname == null) {
1312 from = locationPathname;
1313 } else {
1314 let routePathnameIndex = routePathnames.length - 1;
1315
1316 if (toPathname.startsWith("..")) {
1317 let toSegments = toPathname.split("/"); // Each leading .. segment means "go up one route" instead of "go up one
1318 // URL segment". This is a key difference from how <a href> works and a
1319 // major reason we call this a "to" value instead of a "href".
1320
1321 while (toSegments[0] === "..") {
1322 toSegments.shift();
1323 routePathnameIndex -= 1;
1324 }
1325
1326 to.pathname = toSegments.join("/");
1327 } // If there are more ".." segments than parent routes, resolve relative to
1328 // the root / URL.
1329
1330
1331 from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : "/";
1332 }
1333
1334 let path = resolvePath(to, from); // Ensure the pathname has a trailing slash if the original to value had one.
1335
1336 if (toPathname && toPathname !== "/" && toPathname.endsWith("/") && !path.pathname.endsWith("/")) {
1337 path.pathname += "/";
1338 }
1339
1340 return path;
1341}
1342
1343function getToPathname(to) {
1344 // Empty strings should be treated the same as / paths
1345 return to === "" || to.pathname === "" ? "/" : typeof to === "string" ? parsePath(to).pathname : to.pathname;
1346}
1347
1348function stripBasename(pathname, basename) {
1349 if (basename === "/") return pathname;
1350
1351 if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {
1352 return null;
1353 }
1354
1355 let nextChar = pathname.charAt(basename.length);
1356
1357 if (nextChar && nextChar !== "/") {
1358 // pathname does not start with basename/
1359 return null;
1360 }
1361
1362 return pathname.slice(basename.length) || "/";
1363}
1364
1365const joinPaths = paths => paths.join("/").replace(/\/\/+/g, "/");
1366
1367const normalizePathname = pathname => pathname.replace(/\/+$/, "").replace(/^\/*/, "/");
1368
1369const normalizeSearch = search => !search || search === "?" ? "" : search.startsWith("?") ? search : "?" + search;
1370
1371const normalizeHash = hash => !hash || hash === "#" ? "" : hash.startsWith("#") ? hash : "#" + hash; ///////////////////////////////////////////////////////////////////////////////
1372
1373/**
1374 * React Router DOM v6.0.2
1375 *
1376 * Copyright (c) Remix Software Inc.
1377 *
1378 * This source code is licensed under the MIT license found in the
1379 * LICENSE.md file in the root directory of this source tree.
1380 *
1381 * @license MIT
1382 */
1383
1384
1385function _extends() {
1386 _extends = Object.assign || function (target) {
1387 for (var i = 1; i < arguments.length; i++) {
1388 var source = arguments[i];
1389
1390 for (var key in source) {
1391 if (Object.prototype.hasOwnProperty.call(source, key)) {
1392 target[key] = source[key];
1393 }
1394 }
1395 }
1396
1397 return target;
1398 };
1399
1400 return _extends.apply(this, arguments);
1401}
1402
1403function _objectWithoutPropertiesLoose(source, excluded) {
1404 if (source == null) return {};
1405 var target = {};
1406 var sourceKeys = Object.keys(source);
1407 var key, i;
1408
1409 for (i = 0; i < sourceKeys.length; i++) {
1410 key = sourceKeys[i];
1411 if (excluded.indexOf(key) >= 0) continue;
1412 target[key] = source[key];
1413 }
1414
1415 return target;
1416}
1417
1418const _excluded = ["onClick", "reloadDocument", "replace", "state", "target", "to"],
1419 _excluded2 = ["aria-current", "caseSensitive", "className", "end", "style", "to"]; // COMPONENTS
1420////////////////////////////////////////////////////////////////////////////////
1421
1422/**
1423 * A <Router> for use in web browsers. Provides the cleanest URLs.
1424 */
1425
1426function BrowserRouter(_ref) {
1427 let {
1428 basename,
1429 children,
1430 window
1431 } = _ref;
1432 let historyRef = React.useRef();
1433
1434 if (historyRef.current == null) {
1435 historyRef.current = createBrowserHistory({
1436 window
1437 });
1438 }
1439
1440 let history = historyRef.current;
1441 let [state, setState] = React.useState({
1442 action: history.action,
1443 location: history.location
1444 });
1445 React.useLayoutEffect(() => history.listen(setState), [history]);
1446 return /*#__PURE__*/React.createElement(Router, {
1447 basename: basename,
1448 children: children,
1449 location: state.location,
1450 navigationType: state.action,
1451 navigator: history
1452 });
1453}
1454
1455function isModifiedEvent(event) {
1456 return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
1457}
1458/**
1459 * The public API for rendering a history-aware <a>.
1460 */
1461
1462
1463const Link$1 = /*#__PURE__*/React.forwardRef(function LinkWithRef(_ref3, ref) {
1464 let {
1465 onClick,
1466 reloadDocument,
1467 replace = false,
1468 state,
1469 target,
1470 to
1471 } = _ref3,
1472 rest = _objectWithoutPropertiesLoose(_ref3, _excluded);
1473
1474 let href = useHref(to);
1475 let internalOnClick = useLinkClickHandler(to, {
1476 replace,
1477 state,
1478 target
1479 });
1480
1481 function handleClick(event) {
1482 if (onClick) onClick(event);
1483
1484 if (!event.defaultPrevented && !reloadDocument) {
1485 internalOnClick(event);
1486 }
1487 }
1488
1489 return (
1490 /*#__PURE__*/
1491 // eslint-disable-next-line jsx-a11y/anchor-has-content
1492 React.createElement("a", _extends({}, rest, {
1493 href: href,
1494 onClick: handleClick,
1495 ref: ref,
1496 target: target
1497 }))
1498 );
1499});
1500
1501if (process.env.NODE_ENV !== "production") {
1502 Link$1.displayName = "Link";
1503}
1504/**
1505 * A <Link> wrapper that knows if it's "active" or not.
1506 */
1507
1508
1509const NavLink = /*#__PURE__*/React.forwardRef(function NavLinkWithRef(_ref4, ref) {
1510 let {
1511 "aria-current": ariaCurrentProp = "page",
1512 caseSensitive = false,
1513 className: classNameProp = "",
1514 end = false,
1515 style: styleProp,
1516 to
1517 } = _ref4,
1518 rest = _objectWithoutPropertiesLoose(_ref4, _excluded2);
1519
1520 let location = useLocation();
1521 let path = useResolvedPath(to);
1522 let locationPathname = location.pathname;
1523 let toPathname = path.pathname;
1524
1525 if (!caseSensitive) {
1526 locationPathname = locationPathname.toLowerCase();
1527 toPathname = toPathname.toLowerCase();
1528 }
1529
1530 let isActive = locationPathname === toPathname || !end && locationPathname.startsWith(toPathname) && locationPathname.charAt(toPathname.length) === "/";
1531 let ariaCurrent = isActive ? ariaCurrentProp : undefined;
1532 let className;
1533
1534 if (typeof classNameProp === "function") {
1535 className = classNameProp({
1536 isActive
1537 });
1538 } else {
1539 // If the className prop is not a function, we use a default `active`
1540 // class for <NavLink />s that are active. In v5 `active` was the default
1541 // value for `activeClassName`, but we are removing that API and can still
1542 // use the old default behavior for a cleaner upgrade path and keep the
1543 // simple styling rules working as they currently do.
1544 className = [classNameProp, isActive ? "active" : null].filter(Boolean).join(" ");
1545 }
1546
1547 let style = typeof styleProp === "function" ? styleProp({
1548 isActive
1549 }) : styleProp;
1550 return /*#__PURE__*/React.createElement(Link$1, _extends({}, rest, {
1551 "aria-current": ariaCurrent,
1552 className: className,
1553 ref: ref,
1554 style: style,
1555 to: to
1556 }));
1557});
1558
1559if (process.env.NODE_ENV !== "production") {
1560 NavLink.displayName = "NavLink";
1561} ////////////////////////////////////////////////////////////////////////////////
1562// HOOKS
1563////////////////////////////////////////////////////////////////////////////////
1564
1565/**
1566 * Handles the click behavior for router `<Link>` components. This is useful if
1567 * you need to create custom `<Link>` components with the same click behavior we
1568 * use in our exported `<Link>`.
1569 */
1570
1571
1572function useLinkClickHandler(to, _temp) {
1573 let {
1574 target,
1575 replace: replaceProp,
1576 state
1577 } = _temp === void 0 ? {} : _temp;
1578 let navigate = useNavigate$1();
1579 let location = useLocation();
1580 let path = useResolvedPath(to);
1581 return React.useCallback(event => {
1582 if (event.button === 0 && ( // Ignore everything but left clicks
1583 !target || target === "_self") && // Let browser handle "target=_blank" etc.
1584 !isModifiedEvent(event) // Ignore clicks with modifier keys
1585 ) {
1586 event.preventDefault(); // If the URL hasn't changed, a regular <a> will do a replace instead of
1587 // a push, so do the same here.
1588
1589 let replace = !!replaceProp || createPath(location) === createPath(path);
1590 navigate(to, {
1591 replace,
1592 state
1593 });
1594 }
1595 }, [location, navigate, path, replaceProp, state, target, to]);
1596}
1597
1598const ToggleVisibility = ({
1599 hidden,
1600 children
1601}) => React__default["default"].createElement("div", {
1602 hidden: hidden
1603}, children);
1604
1605const {
1606 document: document$1
1607} = window_1;
1608
1609const getBase = () => `${document$1.location.pathname}?`; // const queryNavigate: NavigateFn = (to: string | number, options?: NavigateOptions<{}>) =>
1610// typeof to === 'number' ? navigate(to) : navigate(`${getBase()}path=${to}`, options);
1611
1612
1613const useNavigate = () => {
1614 const navigate = useNavigate$1();
1615 return React.useCallback((to, _a = {}) => {
1616 var {
1617 plain
1618 } = _a,
1619 options = __rest(_a, ["plain"]);
1620
1621 if (typeof to === 'string' && to.startsWith('#')) {
1622 document$1.location.hash = to;
1623 return undefined;
1624 }
1625
1626 if (typeof to === 'string') {
1627 const target = plain ? to : `?path=${to}`;
1628 return navigate(target, options);
1629 }
1630
1631 if (typeof to === 'number') {
1632 return navigate(to);
1633 }
1634
1635 return undefined;
1636 }, []);
1637}; // A component that will navigate to a new location/path when clicked
1638
1639
1640const Link = _a => {
1641 var {
1642 to,
1643 children
1644 } = _a,
1645 rest = __rest(_a, ["to", "children"]);
1646
1647 return React__default["default"].createElement(Link$1, Object.assign({
1648 to: `${getBase()}path=${to}`
1649 }, rest), children);
1650};
1651
1652Link.displayName = 'QueryLink'; // A render-prop component where children is called with a location
1653// and will be called whenever it changes when it changes
1654
1655const Location = ({
1656 children
1657}) => {
1658 const location = useLocation();
1659 const {
1660 path,
1661 singleStory
1662 } = queryFromString(location.search);
1663 const {
1664 viewMode,
1665 storyId,
1666 refId
1667 } = parsePath$2(path);
1668 return React__default["default"].createElement(React__default["default"].Fragment, null, children({
1669 path,
1670 location,
1671 viewMode,
1672 storyId,
1673 refId,
1674 singleStory: singleStory === 'true'
1675 }));
1676};
1677
1678Location.displayName = 'QueryLocation'; // A render-prop component for rendering when a certain path is hit.
1679// It's immensely similar to `Location` but it receives an addition data property: `match`.
1680// match has a truthy value when the path is hit.
1681
1682const Match = ({
1683 children,
1684 path: targetPath,
1685 startsWith = false
1686}) => React__default["default"].createElement(Location, null, _a => {
1687 var {
1688 path: urlPath
1689 } = _a,
1690 rest = __rest(_a, ["path"]);
1691
1692 return children(Object.assign({
1693 match: getMatch(urlPath, targetPath, startsWith)
1694 }, rest));
1695});
1696
1697Match.displayName = 'QueryMatch'; // A component to conditionally render children based on matching a target path
1698
1699const Route = ({
1700 path,
1701 children,
1702 startsWith = false,
1703 hideOnly = false
1704}) => React__default["default"].createElement(Match, {
1705 path: path,
1706 startsWith: startsWith
1707}, ({
1708 match
1709}) => {
1710 if (hideOnly) {
1711 return React__default["default"].createElement(ToggleVisibility, {
1712 hidden: !match
1713 }, children);
1714 }
1715
1716 return match ? children : null;
1717});
1718
1719Route.displayName = 'Route';
1720
1721const LocationProvider = (...args) => BrowserRouter(...args);
1722
1723const BaseLocationProvider = (...args) => Router(...args);
1724
1725exports.BaseLocationProvider = BaseLocationProvider;
1726exports.DEEPLY_EQUAL = DEEPLY_EQUAL;
1727exports.Link = Link;
1728exports.Location = Location;
1729exports.LocationProvider = LocationProvider;
1730exports.Match = Match;
1731exports.Route = Route;
1732exports.buildArgsParam = buildArgsParam;
1733exports.deepDiff = deepDiff;
1734exports.getMatch = getMatch;
1735exports.parsePath = parsePath$2;
1736exports.queryFromLocation = queryFromLocation;
1737exports.queryFromString = queryFromString;
1738exports.stringifyQuery = stringifyQuery;
1739exports.useNavigate = useNavigate;