-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.qwik.cjs
1875 lines (1874 loc) · 63 KB
/
index.qwik.cjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const jsxRuntime = require("@qwik.dev/core/jsx-runtime");
const core = require("@qwik.dev/core");
const build = require("@qwik.dev/core/build");
const qwikRouterConfig = require("@qwik-router-config");
const zod = require("zod");
const swRegister = require("@qwik-router-sw-register");
function _interopNamespaceDefault(e) {
const n = Object.create(null, { [Symbol.toStringTag]: { value: "Module" } });
if (e) {
for (const k in e) {
if (k !== "default") {
const d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: () => e[k]
});
}
}
}
n.default = e;
return Object.freeze(n);
}
const qwikRouterConfig__namespace = /* @__PURE__ */ _interopNamespaceDefault(qwikRouterConfig);
const MODULE_CACHE = /* @__PURE__ */ new WeakMap();
const CLIENT_DATA_CACHE = /* @__PURE__ */ new Map();
const PREFETCHED_NAVIGATE_PATHS = /* @__PURE__ */ new Set();
const QACTION_KEY = "qaction";
const QFN_KEY = "qfunc";
const QDATA_KEY = "qdata";
const toPath = (url) => url.pathname + url.search + url.hash;
const toUrl = (url, baseUrl) => new URL(url, baseUrl.href);
const isSameOrigin = (a, b) => a.origin === b.origin;
const withSlash = (path) => path.endsWith("/") ? path : path + "/";
const isSamePathname = ({ pathname: a }, { pathname: b }) => {
const lDiff = Math.abs(a.length - b.length);
return lDiff === 0 ? a === b : lDiff === 1 && withSlash(a) === withSlash(b);
};
const isSameSearchQuery = (a, b) => a.search === b.search;
const isSamePath = (a, b) => isSameSearchQuery(a, b) && isSamePathname(a, b);
const getClientDataPath = (pathname, pageSearch, action) => {
let search = pageSearch ?? "";
if (action) {
search += (search ? "&" : "?") + QACTION_KEY + "=" + encodeURIComponent(action.id);
}
return pathname + (pathname.endsWith("/") ? "" : "/") + "q-data.json" + search;
};
const getClientNavPath = (props, baseUrl) => {
const href = props.href;
if (typeof href === "string" && typeof props.target !== "string" && !props.reload) {
try {
const linkUrl = toUrl(href.trim(), baseUrl.url);
const currentUrl = toUrl("", baseUrl.url);
if (isSameOrigin(linkUrl, currentUrl)) {
return toPath(linkUrl);
}
} catch (e) {
console.error(e);
}
} else if (props.reload) {
return toPath(toUrl("", baseUrl.url));
}
return null;
};
const shouldPrefetchData = (clientNavPath, currentLoc) => {
if (clientNavPath) {
const prefetchUrl = toUrl(clientNavPath, currentLoc.url);
const currentUrl = toUrl("", currentLoc.url);
return !isSamePath(prefetchUrl, currentUrl);
}
return false;
};
const shouldPrefetchSymbols = (clientNavPath, currentLoc) => {
if (clientNavPath) {
const prefetchUrl = toUrl(clientNavPath, currentLoc.url);
const currentUrl = toUrl("", currentLoc.url);
return !isSamePathname(prefetchUrl, currentUrl);
}
return false;
};
const isPromise = (value) => {
return value && typeof value.then === "function";
};
const deepFreeze = (obj) => {
if (obj == null) {
return obj;
}
Object.getOwnPropertyNames(obj).forEach((prop) => {
const value = obj[prop];
if (value && typeof value === "object" && !Object.isFrozen(value)) {
deepFreeze(value);
}
});
return Object.freeze(obj);
};
const clientNavigate = (win, navType, fromURL, toURL, replaceState = false) => {
if (navType !== "popstate") {
const samePath = isSamePath(fromURL, toURL);
const sameHash = fromURL.hash === toURL.hash;
if (!samePath || !sameHash) {
const newState = {
_qRouterScroll: newScrollState()
};
if (replaceState) {
win.history.replaceState(newState, "", toPath(toURL));
} else {
win.history.pushState(newState, "", toPath(toURL));
}
}
}
};
const newScrollState = () => {
return {
x: 0,
y: 0,
w: 0,
h: 0
};
};
const prefetchSymbols = (path) => {
if (build.isBrowser) {
path = path.endsWith("/") ? path : path + "/";
if (!PREFETCHED_NAVIGATE_PATHS.has(path)) {
PREFETCHED_NAVIGATE_PATHS.add(path);
document.dispatchEvent(new CustomEvent("qprefetch", {
detail: {
links: [
path
]
}
}));
}
}
};
const loadClientData = async (url, element, opts) => {
const pagePathname = url.pathname;
const pageSearch = url.search;
const clientDataPath = getClientDataPath(pagePathname, pageSearch, opts?.action);
let qData;
if (!opts?.action) {
qData = CLIENT_DATA_CACHE.get(clientDataPath);
}
if (opts?.prefetchSymbols !== false) {
prefetchSymbols(pagePathname);
}
let resolveFn;
if (!qData) {
const fetchOptions = getFetchOptions(opts?.action);
if (opts?.action) {
opts.action.data = void 0;
}
qData = fetch(clientDataPath, fetchOptions).then((rsp) => {
if (rsp.redirected) {
const redirectedURL = new URL(rsp.url);
const isQData = redirectedURL.pathname.endsWith("/q-data.json");
if (!isQData || redirectedURL.origin !== location.origin) {
location.href = redirectedURL.href;
return;
}
}
if ((rsp.headers.get("content-type") || "").includes("json")) {
return rsp.text().then((text) => {
const [clientData] = core._deserialize(text, element);
if (!clientData) {
location.href = url.href;
return;
}
if (opts?.clearCache) {
CLIENT_DATA_CACHE.delete(clientDataPath);
}
if (clientData.redirect) {
location.href = clientData.redirect;
} else if (opts?.action) {
const { action } = opts;
const actionData = clientData.loaders[action.id];
resolveFn = () => {
action.resolve({
status: rsp.status,
result: actionData
});
};
}
return clientData;
});
} else {
if (opts?.isPrefetch !== true) {
location.href = url.href;
}
return void 0;
}
});
if (!opts?.action) {
CLIENT_DATA_CACHE.set(clientDataPath, qData);
}
}
return qData.then((v) => {
if (!v) {
CLIENT_DATA_CACHE.delete(clientDataPath);
}
resolveFn && resolveFn();
return v;
});
};
const getFetchOptions = (action) => {
const actionData = action?.data;
if (!actionData) {
return {
cache: "no-cache",
headers: {
"Cache-Control": "no-cache",
Pragma: "no-cache"
}
};
}
if (actionData instanceof FormData) {
return {
method: "POST",
body: actionData
};
} else {
return {
method: "POST",
body: JSON.stringify(actionData),
headers: {
"Content-Type": "application/json, charset=UTF-8"
}
};
}
};
const RouteStateContext = /* @__PURE__ */ core.createContextId("qc-s");
const ContentContext = /* @__PURE__ */ core.createContextId("qc-c");
const ContentInternalContext = /* @__PURE__ */ core.createContextId("qc-ic");
const DocumentHeadContext = /* @__PURE__ */ core.createContextId("qc-h");
const RouteLocationContext = /* @__PURE__ */ core.createContextId("qc-l");
const RouteNavigateContext = /* @__PURE__ */ core.createContextId("qc-n");
const RouteActionContext = /* @__PURE__ */ core.createContextId("qc-a");
const RouteInternalContext = /* @__PURE__ */ core.createContextId("qc-ir");
const RoutePreventNavigateContext = /* @__PURE__ */ core.createContextId("qc-p");
const useContent = () => core.useContext(ContentContext);
const useDocumentHead = () => core.useContext(DocumentHeadContext);
const useLocation = () => core.useContext(RouteLocationContext);
const useNavigate = () => core.useContext(RouteNavigateContext);
const usePreventNavigateQrl = (fn) => {
if (!__EXPERIMENTAL__.preventNavigate) {
throw new Error('usePreventNavigate$ is experimental and must be enabled with `experimental: ["preventNavigate"]` in the `qwikVite` plugin.');
}
const registerPreventNav = core.useContext(RoutePreventNavigateContext);
core.useVisibleTask$(() => registerPreventNav(fn));
};
const usePreventNavigate$ = core.implicit$FirstArg(usePreventNavigateQrl);
const useAction = () => core.useContext(RouteActionContext);
const useQwikRouterEnv = () => core.noSerialize(core.useServerData("qwikrouter"));
const Link = core.component$((props) => {
const nav = useNavigate();
const loc = useLocation();
const originalHref = props.href;
const { onClick$, prefetch: prefetchProp, reload, replaceState, scroll, ...linkProps } = /* @__PURE__ */ (() => props)();
const clientNavPath = core.untrack(() => getClientNavPath({
...linkProps,
reload
}, loc));
linkProps.href = clientNavPath || originalHref;
const prefetchData = core.untrack(() => !!clientNavPath && prefetchProp !== false && prefetchProp !== "js" && shouldPrefetchData(clientNavPath, loc) || void 0);
const prefetch = core.untrack(() => prefetchData || !!clientNavPath && prefetchProp !== false && shouldPrefetchSymbols(clientNavPath, loc));
const handlePrefetch = prefetch ? core.$((_, elm) => {
if (navigator.connection?.saveData) {
return;
}
if (elm && elm.href) {
const url = new URL(elm.href);
prefetchSymbols(url.pathname);
if (elm.hasAttribute("data-prefetch")) {
loadClientData(url, elm, {
prefetchSymbols: false,
isPrefetch: true
});
}
}
}) : void 0;
const preventDefault = clientNavPath ? core.sync$((event, target) => {
if (!(event.metaKey || event.ctrlKey || event.shiftKey || event.altKey)) {
event.preventDefault();
}
}) : void 0;
const handleClick = clientNavPath ? core.$(async (event, elm) => {
if (event.defaultPrevented) {
if (elm.hasAttribute("q:nbs")) {
await nav(location.href, {
type: "popstate"
});
} else if (elm.href) {
elm.setAttribute("aria-pressed", "true");
await nav(elm.href, {
forceReload: reload,
replaceState,
scroll
});
elm.removeAttribute("aria-pressed");
}
}
}) : void 0;
return /* @__PURE__ */ jsxRuntime.jsx("a", {
"q:link": !!clientNavPath,
...linkProps,
onClick$: [
preventDefault,
onClick$,
handleClick
],
"data-prefetch": prefetchData,
onMouseOver$: [
linkProps.onMouseOver$,
handlePrefetch
],
onFocus$: [
linkProps.onFocus$,
handlePrefetch
],
// Don't prefetch on visible in dev mode
onQVisible$: [
linkProps.onQVisible$,
!build.isDev ? handlePrefetch : void 0
],
children: /* @__PURE__ */ jsxRuntime.jsx(core.Slot, {})
});
});
const resolveHead = (endpoint, routeLocation, contentModules, locale) => {
const head = createDocumentHead();
const getData = (loaderOrAction) => {
const id = loaderOrAction.__id;
if (loaderOrAction.__brand === "server_loader") {
if (!(id in endpoint.loaders)) {
throw new Error("You can not get the returned data of a loader that has not been executed for this request.");
}
}
const data = endpoint.loaders[id];
if (isPromise(data)) {
throw new Error("Loaders returning a promise can not be resolved for the head function.");
}
return data;
};
const headProps = {
head,
withLocale: (fn) => core.withLocale(locale, fn),
resolveValue: getData,
...routeLocation
};
for (let i = contentModules.length - 1; i >= 0; i--) {
const contentModuleHead = contentModules[i] && contentModules[i].head;
if (contentModuleHead) {
if (typeof contentModuleHead === "function") {
resolveDocumentHead(head, core.withLocale(locale, () => contentModuleHead(headProps)));
} else if (typeof contentModuleHead === "object") {
resolveDocumentHead(head, contentModuleHead);
}
}
}
return headProps.head;
};
const resolveDocumentHead = (resolvedHead, updatedHead) => {
if (typeof updatedHead.title === "string") {
resolvedHead.title = updatedHead.title;
}
mergeArray(resolvedHead.meta, updatedHead.meta);
mergeArray(resolvedHead.links, updatedHead.links);
mergeArray(resolvedHead.styles, updatedHead.styles);
mergeArray(resolvedHead.scripts, updatedHead.scripts);
Object.assign(resolvedHead.frontmatter, updatedHead.frontmatter);
};
const mergeArray = (existingArr, newArr) => {
if (Array.isArray(newArr)) {
for (const newItem of newArr) {
if (typeof newItem.key === "string") {
const existingIndex = existingArr.findIndex((i) => i.key === newItem.key);
if (existingIndex > -1) {
existingArr[existingIndex] = newItem;
continue;
}
}
existingArr.push(newItem);
}
}
};
const createDocumentHead = () => ({
title: "",
meta: [],
links: [],
styles: [],
scripts: [],
frontmatter: {}
});
function matchRoute(route, path) {
const routeIdx = startIdxSkipSlash(route);
const routeLength = lengthNoTrailingSlash(route);
const pathIdx = startIdxSkipSlash(path);
const pathLength = lengthNoTrailingSlash(path);
return matchRoutePart(route, routeIdx, routeLength, path, pathIdx, pathLength);
}
function matchRoutePart(route, routeIdx, routeLength, path, pathIdx, pathLength) {
let params = null;
while (routeIdx < routeLength) {
const routeCh = route.charCodeAt(routeIdx++);
const pathCh = path.charCodeAt(pathIdx++);
if (routeCh === 91) {
const isMany = isThreeDots(route, routeIdx);
const paramNameStart = routeIdx + (isMany ? 3 : 0);
const paramNameEnd = scan(route, paramNameStart, routeLength, 93);
const paramName = route.substring(paramNameStart, paramNameEnd);
const paramSuffixEnd = scan(route, paramNameEnd + 1, routeLength, 47);
const suffix = route.substring(paramNameEnd + 1, paramSuffixEnd);
routeIdx = paramNameEnd + 1;
const paramValueStart = pathIdx - 1;
if (isMany) {
const match = recursiveScan(paramName, suffix, path, paramValueStart, pathLength, route, routeIdx + suffix.length + 1, routeLength);
if (match) {
return Object.assign(params || (params = {}), match);
}
}
const paramValueEnd = scan(path, paramValueStart, pathLength, 47, suffix);
if (paramValueEnd == -1) {
return null;
}
const paramValue = path.substring(paramValueStart, paramValueEnd);
if (!isMany && !suffix && !paramValue) {
return null;
}
pathIdx = paramValueEnd;
(params || (params = {}))[paramName] = decodeURIComponent(paramValue);
} else if (routeCh !== pathCh) {
if (!(isNaN(pathCh) && isRestParameter(route, routeIdx))) {
return null;
}
}
}
if (allConsumed(route, routeIdx) && allConsumed(path, pathIdx)) {
return params || {};
} else {
return null;
}
}
function isRestParameter(text, idx) {
return text.charCodeAt(idx) === 91 && isThreeDots(text, idx + 1);
}
function lengthNoTrailingSlash(text) {
const length = text.length;
return length > 1 && text.charCodeAt(length - 1) === 47 ? length - 1 : length;
}
function allConsumed(text, idx) {
const length = text.length;
return idx >= length || idx == length - 1 && text.charCodeAt(idx) === 47;
}
function startIdxSkipSlash(text) {
return text.charCodeAt(0) === 47 ? 1 : 0;
}
function isThreeDots(text, idx) {
return text.charCodeAt(idx) === 46 && text.charCodeAt(idx + 1) === 46 && text.charCodeAt(idx + 2) === 46;
}
function scan(text, idx, end, ch, suffix = "") {
while (idx < end && text.charCodeAt(idx) !== ch) {
idx++;
}
const suffixLength = suffix.length;
for (let i = 0; i < suffixLength; i++) {
if (text.charCodeAt(idx - suffixLength + i) !== suffix.charCodeAt(i)) {
return -1;
}
}
return idx - suffixLength;
}
function recursiveScan(paramName, suffix, path, pathStart, pathLength, route, routeStart, routeLength) {
if (path.charCodeAt(pathStart) === 47) {
pathStart++;
}
let pathIdx = pathLength;
const sep = suffix + "/";
while (pathIdx >= pathStart) {
const match = matchRoutePart(route, routeStart, routeLength, path, pathIdx, pathLength);
if (match) {
let value = path.substring(pathStart, Math.min(pathIdx, pathLength));
if (value.endsWith(sep)) {
value = value.substring(0, value.length - sep.length);
}
match[paramName] = decodeURIComponent(value);
return match;
}
const newPathIdx = lastIndexOf(path, pathStart, sep, pathIdx, pathStart - 1) + sep.length;
if (pathIdx === newPathIdx) {
break;
}
pathIdx = newPathIdx;
}
return null;
}
function lastIndexOf(text, start, match, searchIdx, notFoundIdx) {
let idx = text.lastIndexOf(match, searchIdx);
if (idx == searchIdx - match.length) {
idx = text.lastIndexOf(match, searchIdx - match.length - 1);
}
return idx > start ? idx : notFoundIdx;
}
const loadRoute = async (routes, menus, cacheModules, pathname) => {
if (!Array.isArray(routes)) {
return null;
}
for (const routeData of routes) {
const routeName = routeData[0];
const params = matchRoute(routeName, pathname);
if (!params) {
continue;
}
const loaders = routeData[1];
const routeBundleNames = routeData[3];
const modules = new Array(loaders.length);
const pendingLoads = [];
loaders.forEach((moduleLoader, i) => {
loadModule(moduleLoader, pendingLoads, (routeModule) => modules[i] = routeModule, cacheModules);
});
const menuLoader = getMenuLoader(menus, pathname);
let menu = void 0;
loadModule(menuLoader, pendingLoads, (menuModule) => menu = menuModule?.default, cacheModules);
if (pendingLoads.length > 0) {
await Promise.all(pendingLoads);
}
return [
routeName,
params,
modules,
deepFreeze(menu),
routeBundleNames
];
}
return null;
};
const loadModule = (moduleLoader, pendingLoads, moduleSetter, cacheModules) => {
if (typeof moduleLoader === "function") {
const loadedModule = MODULE_CACHE.get(moduleLoader);
if (loadedModule) {
moduleSetter(loadedModule);
} else {
const moduleOrPromise = moduleLoader();
if (typeof moduleOrPromise.then === "function") {
pendingLoads.push(moduleOrPromise.then((loadedModule2) => {
if (cacheModules !== false) {
MODULE_CACHE.set(moduleLoader, loadedModule2);
}
moduleSetter(loadedModule2);
}));
} else if (moduleOrPromise) {
moduleSetter(moduleOrPromise);
}
}
}
};
const getMenuLoader = (menus, pathname) => {
if (menus) {
pathname = pathname.endsWith("/") ? pathname : pathname + "/";
const menu = menus.find((m) => m[0] === pathname || pathname.startsWith(m[0] + (pathname.endsWith("/") ? "" : "/")));
if (menu) {
return menu[1];
}
}
};
function callRestoreScrollOnDocument() {
if (document.__q_scroll_restore__) {
document.__q_scroll_restore__();
document.__q_scroll_restore__ = void 0;
}
}
const restoreScroll = (type, toUrl2, fromUrl, scroller, scrollState) => {
if (type === "popstate" && scrollState) {
scroller.scrollTo(scrollState.x, scrollState.y);
} else if (type === "link" || type === "form") {
if (!hashScroll(toUrl2, fromUrl)) {
scroller.scrollTo(0, 0);
}
}
};
const hashScroll = (toUrl2, fromUrl) => {
const elmId = toUrl2.hash.slice(1);
const elm = elmId && document.getElementById(elmId);
if (elm) {
elm.scrollIntoView();
return true;
} else if (!elm && toUrl2.hash && isSamePath(toUrl2, fromUrl)) {
return true;
}
return false;
};
const currentScrollState = (elm) => {
return {
x: elm.scrollLeft,
y: elm.scrollTop,
w: Math.max(elm.scrollWidth, elm.clientWidth),
h: Math.max(elm.scrollHeight, elm.clientHeight)
};
};
const getScrollHistory = () => {
const state = history.state;
return state?._qRouterScroll;
};
const saveScrollHistory = (scrollState) => {
const state = history.state || {};
state._qRouterScroll = scrollState;
history.replaceState(state, "");
};
const spaInit = core.event$((_, el) => {
const win = window;
const spa = "_qRouterSPA";
const initPopstate = "_qRouterInitPopstate";
const initAnchors = "_qRouterInitAnchors";
const initVisibility = "_qRouterInitVisibility";
const initScroll = "_qRouterInitScroll";
if (!win[spa] && !win[initPopstate] && !win[initAnchors] && !win[initVisibility] && !win[initScroll]) {
const currentPath = location.pathname + location.search;
const historyPatch = "_qRouterHistoryPatch";
const bootstrap = "_qRouterBootstrap";
const scrollEnabled = "_qRouterScrollEnabled";
const debounceTimeout = "_qRouterScrollDebounce";
const scrollHistory = "_qRouterScroll";
const checkAndScroll = (scrollState) => {
if (scrollState) {
win.scrollTo(scrollState.x, scrollState.y);
}
};
const currentScrollState2 = () => {
const elm = document.documentElement;
return {
x: elm.scrollLeft,
y: elm.scrollTop,
w: Math.max(elm.scrollWidth, elm.clientWidth),
h: Math.max(elm.scrollHeight, elm.clientHeight)
};
};
const saveScrollState = (scrollState) => {
const state = history.state || {};
state[scrollHistory] = scrollState || currentScrollState2();
history.replaceState(state, "");
};
saveScrollState();
win[initPopstate] = () => {
if (win[spa]) {
return;
}
win[scrollEnabled] = false;
clearTimeout(win[debounceTimeout]);
if (currentPath !== location.pathname + location.search) {
const getContainer = (el2) => el2.closest("[q\\:container]:not([q\\:container=html]):not([q\\:container=text])");
const link = getContainer(el)?.querySelector("a[q\\:link]");
if (link) {
const container = getContainer(link);
const bootstrapLink = link.cloneNode();
bootstrapLink.setAttribute("q:nbs", "");
bootstrapLink.style.display = "none";
container.appendChild(bootstrapLink);
win[bootstrap] = bootstrapLink;
bootstrapLink.click();
} else {
location.reload();
}
} else {
if (history.scrollRestoration === "manual") {
const scrollState = history.state?.[scrollHistory];
checkAndScroll(scrollState);
win[scrollEnabled] = true;
}
}
};
if (!win[historyPatch]) {
win[historyPatch] = true;
const pushState = history.pushState;
const replaceState = history.replaceState;
const prepareState = (state) => {
if (state === null || typeof state === "undefined") {
state = {};
} else if (state?.constructor !== Object) {
state = {
_data: state
};
if (build.isDev) {
console.warn("In a Qwik SPA context, `history.state` is used to store scroll state. Direct calls to `pushState()` and `replaceState()` must supply an actual Object type. We need to be able to automatically attach the scroll state to your state object. A new state object has been created, your data has been moved to: `history.state._data`");
}
}
state._qRouterScroll = state._qRouterScroll || currentScrollState2();
return state;
};
history.pushState = (state, title, url) => {
state = prepareState(state);
return pushState.call(history, state, title, url);
};
history.replaceState = (state, title, url) => {
state = prepareState(state);
return replaceState.call(history, state, title, url);
};
}
win[initAnchors] = (event) => {
if (win[spa] || event.defaultPrevented) {
return;
}
const target = event.target.closest("a[href]");
if (target && !target.hasAttribute("preventdefault:click")) {
const href = target.getAttribute("href");
const prev = new URL(location.href);
const dest = new URL(href, prev);
const sameOrigin = dest.origin === prev.origin;
const samePath = dest.pathname + dest.search === prev.pathname + prev.search;
if (sameOrigin && samePath) {
event.preventDefault();
if (dest.href !== prev.href) {
history.pushState(null, "", dest);
}
if (!dest.hash) {
if (dest.href.endsWith("#")) {
window.scrollTo(0, 0);
} else {
win[scrollEnabled] = false;
clearTimeout(win[debounceTimeout]);
saveScrollState({
...currentScrollState2(),
x: 0,
y: 0
});
location.reload();
}
} else {
const elmId = dest.hash.slice(1);
const elm = document.getElementById(elmId);
if (elm) {
elm.scrollIntoView();
}
}
}
}
};
win[initVisibility] = () => {
if (!win[spa] && win[scrollEnabled] && document.visibilityState === "hidden") {
saveScrollState();
}
};
win[initScroll] = () => {
if (win[spa] || !win[scrollEnabled]) {
return;
}
clearTimeout(win[debounceTimeout]);
win[debounceTimeout] = setTimeout(() => {
saveScrollState();
win[debounceTimeout] = void 0;
}, 200);
};
win[scrollEnabled] = true;
setTimeout(() => {
addEventListener("popstate", win[initPopstate]);
addEventListener("scroll", win[initScroll], {
passive: true
});
document.body.addEventListener("click", win[initAnchors]);
if (!win.navigation) {
document.addEventListener("visibilitychange", win[initVisibility], {
passive: true
});
}
}, 0);
}
});
const QWIK_CITY_SCROLLER = "_qCityScroller";
const QWIK_ROUTER_SCROLLER = "_qRouterScroller";
const preventNav = {};
const internalState = {
navCount: 0
};
const QwikRouterProvider = core.component$((props) => {
core.useStyles$(`:root{view-transition-name:none}`);
const env = useQwikRouterEnv();
if (!env?.params) {
throw new Error(`Missing Qwik Router Env Data for help visit https://github.com/QwikDev/qwik/issues/6237`);
}
const urlEnv = core.useServerData("url");
if (!urlEnv) {
throw new Error(`Missing Qwik URL Env Data`);
}
const url = new URL(urlEnv);
const routeLocation = core.useStore({
url,
params: env.params,
isNavigating: false,
prevUrl: void 0
}, {
deep: false
});
const navResolver = {};
const loaderState = core._weakSerialize(core.useStore(env.response.loaders, {
deep: false
}));
const routeInternal = core.useSignal({
type: "initial",
dest: url,
forceReload: false,
replaceState: false,
scroll: true
});
const documentHead = core.useStore(createDocumentHead);
const content = core.useStore({
headings: void 0,
menu: void 0
});
const contentInternal = core.useSignal();
const currentActionId = env.response.action;
const currentAction = currentActionId ? env.response.loaders[currentActionId] : void 0;
const actionState = core.useSignal(currentAction ? {
id: currentActionId,
data: env.response.formData,
output: {
result: currentAction,
status: env.response.status
}
} : void 0);
const registerPreventNav = core.$((fn$) => {
if (!build.isBrowser) {
return;
}
preventNav.$handler$ || (preventNav.$handler$ = (event) => {
internalState.navCount++;
if (!preventNav.$cbs$) {
return;
}
const prevents = [
...preventNav.$cbs$.values()
].map((cb) => cb.resolved ? cb.resolved() : cb());
if (prevents.some(Boolean)) {
event.preventDefault();
event.returnValue = true;
}
});
(preventNav.$cbs$ || (preventNav.$cbs$ = /* @__PURE__ */ new Set())).add(fn$);
fn$.resolve();
window.addEventListener("beforeunload", preventNav.$handler$);
return () => {
if (preventNav.$cbs$) {
preventNav.$cbs$.delete(fn$);
if (!preventNav.$cbs$.size) {
preventNav.$cbs$ = void 0;
window.removeEventListener("beforeunload", preventNav.$handler$);
}
}
};
});
const goto = core.$(async (path, opt) => {
const { type = "link", forceReload = path === void 0, replaceState = false, scroll = true } = typeof opt === "object" ? opt : {
forceReload: opt
};
internalState.navCount++;
const lastDest = routeInternal.value.dest;
const dest = path === void 0 ? lastDest : typeof path === "number" ? path : toUrl(path, routeLocation.url);
if (preventNav.$cbs$ && (forceReload || typeof dest === "number" || !isSamePath(dest, lastDest) || !isSameOrigin(dest, lastDest))) {
const ourNavId = internalState.navCount;
const prevents = await Promise.all([
...preventNav.$cbs$.values()
].map((cb) => cb(dest)));
if (ourNavId !== internalState.navCount || prevents.some(Boolean)) {
if (ourNavId === internalState.navCount && type === "popstate") {
history.pushState(null, "", lastDest);
}
return;
}
}
if (typeof dest === "number") {
if (build.isBrowser) {
history.go(dest);
}
return;
}
if (!isSameOrigin(dest, lastDest)) {
if (build.isBrowser) {
location.href = dest.href;
}
return;
}
if (!forceReload && isSamePath(dest, lastDest)) {
if (build.isBrowser) {
if (type === "link" && dest.href !== location.href) {
history.pushState(null, "", dest);
}
let scroller = document.getElementById(QWIK_ROUTER_SCROLLER);
if (!scroller) {
scroller = document.getElementById(QWIK_CITY_SCROLLER);
if (scroller) {
console.warn(`Please update your scroller ID to "${QWIK_ROUTER_SCROLLER}" as "${QWIK_CITY_SCROLLER}" is deprecated and will be removed in V3`);
}
}
if (!scroller) {
scroller = document.documentElement;
}
restoreScroll(type, dest, new URL(location.href), scroller, getScrollHistory());
if (type === "popstate") {
window._qRouterScrollEnabled = true;
}
}
return;
}
routeInternal.value = {
type,
dest,
forceReload,
replaceState,
scroll
};
if (build.isBrowser) {
loadClientData(dest, core._getContextElement());
loadRoute(qwikRouterConfig__namespace.routes, qwikRouterConfig__namespace.menus, qwikRouterConfig__namespace.cacheModules, dest.pathname);
}
actionState.value = void 0;
routeLocation.isNavigating = true;
return new Promise((resolve) => {
navResolver.r = resolve;
});
});
core.useContextProvider(ContentContext, content);
core.useContextProvider(ContentInternalContext, contentInternal);
core.useContextProvider(DocumentHeadContext, documentHead);
core.useContextProvider(RouteLocationContext, routeLocation);
core.useContextProvider(RouteNavigateContext, goto);
core.useContextProvider(RouteStateContext, loaderState);
core.useContextProvider(RouteActionContext, actionState);
core.useContextProvider(RouteInternalContext, routeInternal);
core.useContextProvider(RoutePreventNavigateContext, registerPreventNav);
core.useTask$(({ track }) => {
async function run() {
const [navigation, action] = track(() => [
routeInternal.value,
actionState.value
]);
const locale = core.getLocale("");
const prevUrl = routeLocation.url;
const navType = action ? "form" : navigation.type;
const replaceState = navigation.replaceState;
let trackUrl;
let clientPageData;
let loadedRoute = null;
let elm;
if (build.isServer) {
trackUrl = new URL(navigation.dest, routeLocation.url);
loadedRoute = env.loadedRoute;
clientPageData = env.response;
} else {
trackUrl = new URL(navigation.dest, location);
if (trackUrl.pathname.endsWith("/")) {
if (!qwikRouterConfig__namespace.trailingSlash) {
trackUrl.pathname = trackUrl.pathname.slice(0, -1);
}
} else if (qwikRouterConfig__namespace.trailingSlash) {
trackUrl.pathname += "/";
}
let loadRoutePromise = loadRoute(qwikRouterConfig__namespace.routes, qwikRouterConfig__namespace.menus, qwikRouterConfig__namespace.cacheModules, trackUrl.pathname);
elm = core._getContextElement();
const pageData = clientPageData = await loadClientData(trackUrl, elm, {
action,
clearCache: true
});
if (!pageData) {
routeInternal.untrackedValue = {
type: navType,
dest: trackUrl
};
return;
}
const newHref = pageData.href;
const newURL = new URL(newHref, trackUrl);
if (!isSamePath(newURL, trackUrl)) {
trackUrl = newURL;
loadRoutePromise = loadRoute(qwikRouterConfig__namespace.routes, qwikRouterConfig__namespace.menus, qwikRouterConfig__namespace.cacheModules, trackUrl.pathname);
}
try {
loadedRoute = await loadRoutePromise;
} catch (e) {
window.location.href = newHref;
return;
}
}
if (loadedRoute) {
const [routeName, params, mods, menu] = loadedRoute;
const contentModules = mods;
const pageModule = contentModules[contentModules.length - 1];
const isRedirect = navType === "form" && !isSamePath(trackUrl, prevUrl);
if (navigation.dest.search && !isRedirect) {
trackUrl.search = navigation.dest.search;
}
routeLocation.prevUrl = prevUrl;
routeLocation.url = trackUrl;
routeLocation.params = {
...params
};
routeInternal.untrackedValue = {
type: navType,
dest: trackUrl
};
const resolvedHead = resolveHead(clientPageData, routeLocation, contentModules, locale);
content.headings = pageModule.headings;
content.menu = menu;
contentInternal.value = core.noSerialize(contentModules);
documentHead.links = resolvedHead.links;