-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathroot.tsx
More file actions
287 lines (253 loc) · 6.99 KB
/
Copy pathroot.tsx
File metadata and controls
287 lines (253 loc) · 6.99 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
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
import tailwindStylesheetUrl from '/app/styles/tailwind.css?url'
import appStylesheetUrl from '/app/styles/app.css?url'
import clsx from 'clsx'
import { useEffect } from 'react'
import { useTranslation } from 'react-i18next'
import {
data,
Links,
Outlet,
Scripts,
ScrollRestoration,
useRouteLoaderData,
} from 'react-router'
import invariant from 'tiny-invariant'
import { type Route } from './+types/root'
import ErrorMessage from './components/error-message'
import { Toaster } from './components/ui/toaster'
import { updateUserPreferencesById } from './db/models/user.server'
import { getEnv } from './lib/env.server'
import { getLocale, i18nCookie, i18nextMiddleware } from './middleware/i18next'
import { tosUiMiddleware } from './middleware/tos-ui.server'
import { prometheusMetricsMiddleware } from './middleware/metrics.server'
import { getUser } from './services/session-service.server'
import { getServerTheme, ThemePreferenceSchema } from './lib/theme'
import {
getThemePreference,
themeCookie,
} from './services/theme-service.server'
import { PreventFlashOnWrongTheme } from './components/prevent-theme-flash'
import { TooltipProvider } from './components/ui/tooltip'
export const middleware: Route.MiddlewareFunction[] = [
prometheusMetricsMiddleware,
i18nextMiddleware,
tosUiMiddleware,
]
export const links = () => {
return [
{
rel: 'preload',
as: 'font',
href: '/fonts/RobotoSlab-Medium.woff2',
type: 'font/woff2',
crossOrigin: 'anonymous',
},
{
rel: 'preload',
as: 'font',
href: '/fonts/RobotoSlab-Regular.woff2',
type: 'font/woff2',
crossOrigin: 'anonymous',
},
{
rel: 'preload',
as: 'font',
href: '/fonts/Urbanist-Medium.woff2',
type: 'font/woff2',
crossOrigin: 'anonymous',
},
{
rel: 'preload',
as: 'font',
href: '/fonts/Urbanist-Regular.woff2',
type: 'font/woff2',
crossOrigin: 'anonymous',
},
{ rel: 'stylesheet', href: tailwindStylesheetUrl },
{ rel: 'stylesheet', href: appStylesheetUrl },
{ rel: 'icon', href: '/img/logo.svg', type: 'image/svg+xml' },
{
rel: 'icon',
href: '/img/favicon-32x32.png',
sizes: '32x32',
type: 'image/png',
},
{ rel: 'apple-touch-icon', href: '/img/favicon-180x180.png' },
{ rel: 'manifest', href: '/manifest.json' },
]
}
export async function loader({ context, request }: Route.LoaderArgs) {
const locale = getLocale(context)
const user = await getUser(request)
const cookieThemePreference = await getThemePreference(request)
const userThemePreferenceResult = ThemePreferenceSchema.safeParse(
user?.themePreference,
)
const themePreference = userThemePreferenceResult.success
? userThemePreferenceResult.data
: cookieThemePreference
const theme = getServerTheme(themePreference)
const headers = new Headers()
// setting the cookie is required here to make sure we keep the server and client
// instance of i18n in synch
headers.append('Set-Cookie', await i18nCookie.serialize(locale))
// If the user has a DB-backed preference, mirror it into the cookie too.
if (userThemePreferenceResult.success) {
headers.append('Set-Cookie', await themeCookie.serialize(themePreference))
}
return data(
{
user,
locale,
themePreference,
theme,
ENV: getEnv(),
},
{ headers },
)
}
export async function action({ context, request }: Route.ActionArgs) {
const formData = await request.formData()
const setTheme = formData.get('set-theme')
if (setTheme !== null) {
const result = ThemePreferenceSchema.safeParse(setTheme)
if (!result.success) {
throw data('Invalid theme preference', { status: 400 })
}
const user = await getUser(request)
const headers = new Headers()
if (user) {
await updateUserPreferencesById(user.id, {
themePreference: result.data,
})
}
headers.append('Set-Cookie', await themeCookie.serialize(result.data))
return data(
{
ok: true,
themePreference: result.data,
},
{ headers },
)
}
const setLang = formData.get('set-language')?.toString() ?? null
if (setLang === null) return null
const locale = getLocale(context)
if (setLang === locale) return null
const user = await getUser(request)
if (user) {
// updating the user locale is sufficient,
// because the loader will set the cookie to
// the user locale on the next request
await updateUserPreferencesById(user.id, {
language: setLang,
})
return data({
ok: true,
locale: setLang,
})
}
return data(
{
ok: true,
locale: setLang,
},
{
headers: {
'Set-Cookie': await i18nCookie.serialize(setLang),
},
},
)
}
/**
* Convenience hook to get the {@link loader} data of the root route in order to access
* e.g. the current locale, user or others.
* @returns The loader data of the root route
*/
export const useRootRouteLoaderData = () => {
const rootData = useRouteLoaderData<typeof loader>('root')
invariant(rootData !== undefined, 'root loader should always return data')
return rootData
}
const meta = () => (
<>
<title>openSenseMap</title>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<meta
name="theme-color"
content="#3d843f"
media="(prefers-color-scheme: light)"
/>
<meta
name="theme-color"
content="#6fa161"
media="(prefers-color-scheme: dark)"
/>
<meta
name="description"
content="The environmental data platform to promote education, environmental and climate protection, enthusiasm for STEM, citizen science, open data, and open source."
/>
</>
)
export default function App({
loaderData: { locale, ENV, themePreference, theme },
}: Route.ComponentProps) {
const { i18n } = useTranslation()
useEffect(() => {
if (i18n.language !== locale) {
void i18n.changeLanguage(locale)
}
}, [locale, i18n])
return (
<html
lang={i18n.language}
dir={i18n.dir(i18n.language)}
className={clsx(theme, 'h-full')}
suppressHydrationWarning
>
<head>
<PreventFlashOnWrongTheme themePreference={themePreference} />
<Links />
</head>
<body className="dark:bg-dark-background dark:text-dark-text h-full">
{meta()}
<TooltipProvider>
<Outlet />
</TooltipProvider>
<Toaster />
<ScrollRestoration />
<Scripts />
<script
dangerouslySetInnerHTML={{
__html: `window.ENV = ${JSON.stringify(ENV)}`,
}}
/>
</body>
</html>
)
}
/**
* A catch-all error boundary that will render if any error is thrown in the app.
* Add a function like this to subpages, if you want to create a more specific
* error boundary for that page (e.g. with specific messages, styling etc.).
*
* Note that error boundaries are shown in place of the parent pages <Outlet />.
*/
export function ErrorBoundary() {
return (
<html className="light h-full" suppressHydrationWarning>
<head>
<PreventFlashOnWrongTheme themePreference="system" />
<Links />
</head>
<body className="bg-background text-foreground h-full">
{meta()}
<div className="flex h-screen w-screen items-center justify-center">
<ErrorMessage />
</div>
<Scripts />
</body>
</html>
)
}