-
Notifications
You must be signed in to change notification settings - Fork 170
Expand file tree
/
Copy pathinertia.ts
More file actions
91 lines (74 loc) · 2.21 KB
/
Copy pathinertia.ts
File metadata and controls
91 lines (74 loc) · 2.21 KB
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
import "@fontsource-variable/spline-sans";
import { createInertiaApp, type ResolvedComponent } from "@inertiajs/svelte";
import AppLayout from "../layouts/AppLayout.svelte";
const pages = import.meta.glob<ResolvedComponent>("../pages/**/*.svelte");
const prefetchedPages = new Set<string>();
function currentPageName(): string | null {
if (typeof document === "undefined") return null;
const node = document.querySelector<HTMLScriptElement>(
'#app > script[type="application/json"]',
);
const raw = node?.textContent;
if (!raw) return null;
try {
const page = JSON.parse(raw) as { component?: string };
return typeof page.component === "string" ? page.component : null;
} catch {
return null;
}
}
function likelyNextPages(pageName: string | null): string[] {
switch (pageName) {
case "Home/SignedOut":
case "Auth/SignIn":
return ["Home/SignedIn"];
case "Home/SignedIn":
return ["Setup/Index"];
default:
return [];
}
}
function prefetchPage(name: string) {
const pagePath = `../pages/${name}.svelte`;
const loadPage = pages[pagePath];
if (!loadPage || prefetchedPages.has(pagePath)) return;
prefetchedPages.add(pagePath);
void loadPage().catch((error) => {
prefetchedPages.delete(pagePath);
console.debug(
`Failed to prefetch Inertia page component: '${name}.svelte'`,
error,
);
});
}
function prefetchLikelyNextPages() {
likelyNextPages(currentPageName()).forEach(prefetchPage);
}
function schedulePrefetch() {
if (typeof window === "undefined") return;
if ("requestIdleCallback" in window) {
window.requestIdleCallback(prefetchLikelyNextPages, { timeout: 1500 });
return;
}
globalThis.setTimeout(prefetchLikelyNextPages, 400);
}
createInertiaApp({
// see https://inertia-rails.dev/guide/progress-indicators
progress: {
color: "var(--color-primary)",
},
layout: () => AppLayout,
resolve: async (name) => {
const loadPage = pages[`../pages/${name}.svelte`];
if (!loadPage) {
throw new Error(`Missing Inertia page component: '${name}.svelte'`);
}
return await loadPage();
},
defaults: {
form: {
forceIndicesArrayFormatInFormData: false,
},
},
});
schedulePrefetch();