Skip to content
Source
Sign inSign up
fuko/trytanstackdb.com
Open History to see the last commit

__root.tsx

255 lines7.8 KB

1import { TanStackDevtools } from "@tanstack/react-devtools";
2import type { QueryClient } from "@tanstack/react-query";
3import { ReactQueryDevtoolsPanel } from "@tanstack/react-query-devtools";
4import {
5 ClientOnly,
6 createRootRouteWithContext,
7 HeadContent,
8 ScriptOnce,
9 Scripts,
10} from "@tanstack/react-router";
11import { TanStackRouterDevtoolsPanel } from "@tanstack/react-router-devtools";
12import { RotateCwIcon, TriangleAlertIcon } from "lucide-react";
13import { useCallback, useState } from "react";
14import { ThemeProvider } from "@/components/theme-provider";
15import { Button } from "@/components/ui/button";
16import { Card, CardContent, CardHeader } from "@/components/ui/card";
17import { Toaster } from "@/components/ui/sonner";
18import { client, idbName } from "@/db";
19import { seo } from "@/utils/seo";
20import appCss from "../styles.css?url";
21​
22interface MyRouterContext {
23 queryClient: QueryClient;
25​
26export const Route = createRootRouteWithContext<MyRouterContext>()({
27 head: () => ({
28 meta: [
29 {
30 charSet: "utf-8",
31 },
32 {
33 name: "viewport",
34 content: "width=device-width, initial-scale=1",
35 },
36 ...seo({
37 title: "trytanstackdb | The interactive guide",
38 description: `Learn how to build ⚡BLAZING FAST⚡ front-ends with TanStack DB in 6-7 minutes`,
39 image: `https://trytanstackdb.com/og-image.png`,
40 keywords: "tanstack,tanstack db,reactjs,tutorial",
41 }),
42 ],
43 links: [
44 {
45 rel: "preconnect",
46 href: "https://fonts.googleapis.com",
47 },
48 {
49 rel: "preconnect",
50 href: "https://fonts.gstatic.com",
51 crossOrigin: "anonymous",
52 },
53 {
54 rel: "stylesheet",
55 href: "https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@300;400;500;600;700&display=swap",
56 },
57 {
58 rel: "stylesheet",
59 href: "https://fonts.googleapis.com/css2?family=JetBrains+Mono:ital,wght@0,100..800;1,100..800&display=swap",
60 },
61 {
62 rel: "stylesheet",
63 href: appCss,
64 },
65 ],
66 }),
67 shellComponent: RootDocument,
68 errorComponent: ErrorComponent,
69});
70​
71function RemoveDB() {
72 const [errorMessage, setErrorMessage] = useState<string | null>(null);
73​
74 const [showReloadButton, setShowReloadButton] = useState(false);
75​
76 const removeDB = useCallback(async () => {
77 if (typeof window !== "undefined" && "indexedDB" in window) {
78 try {
79 console.log({ idbName });
80 await client.close();
81 const request = window.indexedDB.deleteDatabase(idbName);
82 request.onsuccess = () => {
83 window.location.reload();
84 };
85 request.onerror = () => {
86 const errorMessage = "Failed to delete database";
87 console.error(errorMessage);
88 setErrorMessage(errorMessage);
89 };
90 request.onblocked = () => {
91 setShowReloadButton(true);
92 const errorMessage =
93 "Database deletion blocked - close other tabs using this site. If this site is not open in other tabs, try refreshing the page.";
94 setErrorMessage(errorMessage);
95 console.warn(errorMessage);
96 };
97 } catch (error) {
98 const errorMessage =
99 error instanceof Error ? error.message : "An unknown error occurred";
100 console.error("Error deleting database:", errorMessage);
101 setErrorMessage(errorMessage);
102 }
103 }
104 }, []);
105​
106 return (
107 <ClientOnly>
108 <Button
109 className="w-fit mx-auto"
110 variant="destructive"
111 onClick={removeDB}
112 >
113 <RotateCwIcon /> Reset the db
114 </Button>
115 <p className="text-destructive font-bold text-center">{errorMessage}</p>
116 {showReloadButton && (
117 <Button
118 className="mx-auto"
119 variant="outline"
120 onClick={() => {
121 window.location.reload();
122 }}
123 >
124 Reload page
125 </Button>
126 )}
127 </ClientOnly>
128 );
130​
131function ErrorComponent({ error }: { error: unknown }) {
132 const isServiceWorkerError =
133 error instanceof Error &&
134 error.message.includes("navigator.serviceWorker.addEventListener");
135​
136 const isDbQueryError =
137 error instanceof Error && error.message.startsWith("Failed query: ");
138​
139 return (
140 <div className="fixed inset-0 w-screen h-screen flex justify-center items-center p-6 bg-background">
141 <Card className="max-w-2xl w-full">
142 <CardHeader>
143 <h2 className="text-2xl font-bold text-destructive text-center justify-center flex items-center gap-2">
144 <TriangleAlertIcon /> An error occurred
145 </h2>
146 </CardHeader>
147​
148 <CardContent className="flex flex-col gap-4">
149 {isServiceWorkerError ? (
150 <>
151 <p className="block sm:hidden">
152 Embedded browsers (like those in some social media apps) might
153 not support Service Workers properly.
154 </p>
155 <p className="hidden sm:block">
156 It seems like your browser is having issues with Service
157 Workers. Please try using a different browser or updating your
158 current one.
159 </p>
160 </>
161 ) : isDbQueryError ? (
162 <>
163 <p>
164 There was an issue executing a database query. Please ensure
165 that the backend server is running and accessible.
166 </p>
167 <RemoveDB />
168 </>
169 ) : null}
170 <p className="font-bold">Error message:</p>
171 <pre className="wrap-break-word whitespace-pre-wrap text max-h-40 text-muted-foreground overflow-y-auto">
172 {error instanceof Error ? error.message : String(error)}
173 </pre>
174 </CardContent>
175 </Card>
176 </div>
177 );
179​
180function ServiceWorkerLoader() {
181 const serviceWorkerScript = (() => {
182 const registerServiceWorker = async () => {
183 const serviceWorkerLoadedVarName = "__SERVICE_WORKER_LOADED__";
184 // @ts-expect-error
185 if (!window[serviceWorkerLoadedVarName]) {
186 if ("serviceWorker" in navigator) {
187 try {
188 const registration = await navigator.serviceWorker.register(
189 "/sw.js",
190 {
191 scope: "/",
192 type: "module",
193 },
194 );
195 if (registration.installing) {
196 console.log("Service worker installing");
197 } else if (registration.waiting) {
198 console.log("Service worker installed");
199 } else if (registration.active) {
200 console.log("Service worker active");
201 }
202 } catch (error) {
203 console.error(`Registration failed with ${error}`);
204 }
205 }
206 // @ts-expect-error
207 window[serviceWorkerLoadedVarName] = true;
208 }
209 };
210​
211 registerServiceWorker();
212 return `(${registerServiceWorker.toString()})();`;
213 })();
214​
215 return <ScriptOnce children={serviceWorkerScript} />;
217​
218function RootDocument({ children }: { children: React.ReactNode }) {
219 return (
220 <html lang="en" suppressHydrationWarning className="overflow-hidden!">
221 <head>
222 <HeadContent />
223 </head>
224 <body>
225 <ServiceWorkerLoader />
226 <ThemeProvider>
227 {children}
228 <Toaster position="top-right" />
229 </ThemeProvider>
230 <TanStackDevtools
231 config={{
232 position: "bottom-right",
233 }}
234 plugins={[
235 {
236 name: "TanStack Query",
237 render: <ReactQueryDevtoolsPanel />,
238 defaultOpen: true,
239 },
240 {
241 name: "TanStack Router",
242 render: <TanStackRouterDevtoolsPanel />,
243 defaultOpen: false,
244 },
245 ]}
246 />
247 <script
248 defer
249 src="https://assets.onedollarstats.com/stonks.js"
250 ></script>
251 <Scripts />
252 </body>
253 </html>
254 );