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