/
root.tsx
795 lines (746 loc) · 24.2 KB
/
root.tsx
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
import {withSentry} from '@sentry/remix'
import {
json,
type DataFunctionArgs,
type HeadersFunction,
type LinksFunction,
type MetaFunction,
type SerializeFrom,
} from '@remix-run/node'
import {
isRouteErrorResponse,
Link,
Links,
LiveReload,
Meta,
Outlet,
Scripts,
ScrollRestoration,
useLoaderData,
useLocation,
useNavigation,
} from '@remix-run/react'
import * as React from 'react'
import {MetronomeLinks} from '@metronome-sh/react'
import {clsx} from 'clsx'
import {isFuture} from 'date-fns'
import {AnimatePresence, motion} from 'framer-motion'
import {getInstanceInfo} from '~/utils/cjs/litefs-js.server.js'
import {useSpinDelay} from 'spin-delay'
import {type KCDHandle} from '~/types.ts'
import {ArrowLink} from './components/arrow-button.tsx'
import {ErrorPage, FourHundred} from './components/errors.tsx'
import {Footer} from './components/footer.tsx'
import {ArrowIcon, LaptopIcon, PartyIcon} from './components/icons.tsx'
import {Grimmacing, MissingSomething} from './components/kifs.tsx'
import {Navbar} from './components/navbar.tsx'
import {NotificationMessage} from './components/notification-message.tsx'
import {Spacer} from './components/spacer.tsx'
import {TeamCircle} from './components/team-circle.tsx'
import {getGenericSocialImage, illustrationImages, images} from './images.tsx'
import {
Promotification,
getPromoCookieValue,
} from './routes/resources+/promotification.tsx'
import appStyles from './styles/app.css?url'
import noScriptStyles from './styles/no-script.css?url'
import proseStyles from './styles/prose.css?url'
import tailwindStyles from './styles/tailwind.css?url'
import vendorStyles from './styles/vendors.css?url'
import {getClientSession} from './utils/client.server.ts'
import {getEnv} from './utils/env.server.ts'
import {getLoginInfoSession} from './utils/login.server.ts'
import {
getDisplayUrl,
getDomainUrl,
getUrl,
parseDate,
removeTrailingSlash,
typedBoolean,
} from './utils/misc.tsx'
import {useNonce} from './utils/nonce-provider.ts'
import {getSocialMetas} from './utils/seo.ts'
import {getSession} from './utils/session.server.ts'
import {TeamProvider, useTeam} from './utils/team-provider.tsx'
import {ClientHintCheck, getHints} from './utils/client-hints.tsx'
import {getServerTimeHeader} from './utils/timing.server.ts'
import {getUserInfo} from './utils/user-info.server.ts'
import {getScheduledEvents} from './utils/workshop-tickets.server.ts'
import {getWorkshops} from './utils/workshops.server.ts'
import {getTheme} from './utils/theme.server.ts'
import {useTheme} from './utils/theme.tsx'
import {useCapturedRouteError} from '~/utils/misc.tsx'
export const handle: KCDHandle & {id: string} = {
id: 'root',
}
export const meta: MetaFunction<typeof loader> = ({data}) => {
const requestInfo = data?.requestInfo
const title = 'Kent C. Dodds'
const description =
'Come check out how Kent C. Dodds can help you level up your career as a software engineer.'
return [
{viewport: 'width=device-width,initial-scale=1,viewport-fit=cover'},
{
'theme-color':
requestInfo?.userPrefs.theme === 'dark' ? '#1F2028' : '#FFF',
},
...getSocialMetas({
keywords:
'Learn React, React Workshops, Testing JavaScript Training, React Training, Learn JavaScript, Learn TypeScript',
url: getUrl(requestInfo),
image: getGenericSocialImage({
url: getDisplayUrl(requestInfo),
words:
'Helping people make the world a better place through quality software.',
featuredImage: 'kentcdodds.com/illustrations/kody-flying_blue',
}),
title,
description,
}),
]
}
export const links: LinksFunction = () => {
return [
{
rel: 'apple-touch-icon',
sizes: '180x180',
href: '/favicons/apple-touch-icon.png',
},
{
rel: 'icon',
type: 'image/png',
sizes: '32x32',
href: '/favicons/favicon-32x32.png',
},
{
rel: 'icon',
type: 'image/png',
sizes: '16x16',
href: '/favicons/favicon-16x16.png',
},
{rel: 'manifest', href: '/site.webmanifest'},
{rel: 'icon', href: '/favicon.ico'},
{rel: 'stylesheet', href: vendorStyles},
{rel: 'stylesheet', href: tailwindStyles},
{rel: 'stylesheet', href: proseStyles},
{rel: 'stylesheet', href: appStyles},
]
}
export type LoaderData = SerializeFrom<typeof loader>
const WORKSHOP_PROMO_NAME = 'workshop-promo'
const EPIC_WEB_CONF_EARLY_BIRD_PROMO_NAME = 'epic-web-conf-early-bird-promo'
const EPIC_WEB_CONF_EARLY_BIRD_START_DATE = '2024-01-24T19:00:00.000Z'
const EPIC_WEB_CONF_EARLY_BIRD_END_DATE = '2024-02-16T19:00:00.000Z'
const EPIC_WEB_CONF_REGULAR_TICKET_NAME = 'epic-web-conf-regular-ticket'
const EPIC_WEB_CONF_REGULAR_TICKET_START_DATE =
EPIC_WEB_CONF_EARLY_BIRD_END_DATE
const EPIC_WEB_CONF_REGULAR_TICKET_END_DATE = '2024-03-15T19:00:00.000Z'
const EPIC_WEB_CONF_LATE_TICKET_NAME = 'epic-web-conf-late-ticket'
const EPIC_WEB_CONF_LATE_TICKET_START_DATE =
EPIC_WEB_CONF_REGULAR_TICKET_END_DATE
const EPIC_WEB_CONF_LATE_TICKET_END_DATE = '2024-04-10T19:00:00.000Z'
const EPIC_WEB_CONF_LIVE = 'epic-web-conf-live'
const EPIC_WEB_CONF_LIVE_START_DATE = '2024-04-11T13:00:00.000Z'
const EPIC_WEB_CONF_LIVE_END_DATE = '2024-04-12T00:00:00.000Z'
export async function loader({request}: DataFunctionArgs) {
const timings = {}
const session = await getSession(request)
const [
user,
clientSession,
loginInfoSession,
primaryInstance,
workshops,
workshopEvents,
] = await Promise.all([
session.getUser({timings}),
getClientSession(request, session.getUser({timings})),
getLoginInfoSession(request),
getInstanceInfo().then(i => i.primaryInstance),
getWorkshops({request, timings}),
getScheduledEvents({request, timings}),
])
const randomFooterImageKeys = Object.keys(illustrationImages)
const randomFooterImageKey = randomFooterImageKeys[
Math.floor(Math.random() * randomFooterImageKeys.length)
] as keyof typeof illustrationImages
const data = {
user,
userInfo: user ? await getUserInfo(user, {request, timings}) : null,
ENV: getEnv(),
randomFooterImageKey,
epicWebPromotifications: {
earlyBird: {
promoName: EPIC_WEB_CONF_EARLY_BIRD_PROMO_NAME,
cookieValue: getPromoCookieValue({
request,
promoName: EPIC_WEB_CONF_EARLY_BIRD_PROMO_NAME,
}),
startDate: EPIC_WEB_CONF_EARLY_BIRD_START_DATE,
endDate: EPIC_WEB_CONF_EARLY_BIRD_END_DATE,
text: 'early bird sale is going on right now!',
ticketLinkText: 'Limited time discount available',
},
regularTicket: {
promoName: EPIC_WEB_CONF_REGULAR_TICKET_NAME,
cookieValue: getPromoCookieValue({
request,
promoName: EPIC_WEB_CONF_REGULAR_TICKET_NAME,
}),
startDate: EPIC_WEB_CONF_REGULAR_TICKET_START_DATE,
endDate: EPIC_WEB_CONF_REGULAR_TICKET_END_DATE,
text: 'regular tickets are available now!',
ticketLinkText: 'Prices go up soon',
},
lateTicket: {
promoName: EPIC_WEB_CONF_LATE_TICKET_NAME,
cookieValue: getPromoCookieValue({
request,
promoName: EPIC_WEB_CONF_LATE_TICKET_NAME,
}),
startDate: EPIC_WEB_CONF_LATE_TICKET_START_DATE,
endDate: EPIC_WEB_CONF_LATE_TICKET_END_DATE,
text: 'late-bird tickets are available now, hurry!',
ticketLinkText: 'Get your tickets here',
},
live: {
promoName: EPIC_WEB_CONF_LIVE,
cookieValue: getPromoCookieValue({
request,
promoName: EPIC_WEB_CONF_LIVE,
}),
startDate: EPIC_WEB_CONF_LIVE_START_DATE,
endDate: EPIC_WEB_CONF_LIVE_END_DATE,
text: 'is live right now!',
ticketLinkText: null,
},
},
workshopPromotifications: workshopEvents
.map(e => {
const workshop = workshops.find(w => w.slug === e.metadata.workshopSlug)
if (!workshop) return null
const discounts = Object.entries(e.discounts)
.filter(([, discount]) => isFuture(parseDate(discount.ends)))
.sort(([, a], [, b]) => {
return parseDate(a.ends).getTime() - parseDate(b.ends).getTime()
})
// the promoEndTime should be the earliest of:
// 1. earliest discount end
// 2. the end of ticket sales
// 3. the start of the event
const promoEndTime = [
discounts[0]
? {
type: 'discount' as const,
time: parseDate(discounts[0][1].ends).getTime(),
url: discounts[0][1].url,
}
: null,
e.salesEndTime
? {
type: 'sales' as const,
time: parseDate(e.salesEndTime).getTime(),
url: e.url,
}
: null,
e.startTime
? {
type: 'start' as const,
time: parseDate(e.startTime).getTime(),
url: e.url,
}
: null,
]
.filter(typedBoolean)
.sort((a, b) => a.time - b.time)[0]
if (!promoEndTime) return null
const promoName = `${WORKSHOP_PROMO_NAME}-${workshop.slug}`
return {
title: e.title,
slug: workshop.slug,
promoName,
dismissTimeSeconds: Math.min(
Math.max(
// one quarter of the time until the salesEndTime (in seconds)
(promoEndTime.time - Date.now()) / 4 / 1000,
// Minimum of 3 hours (in seconds)
60 * 60 * 3,
),
// Maximum of 1 week (in seconds)
60 * 60 * 24 * 7,
),
cookieValue: getPromoCookieValue({
promoName,
request,
}),
promoEndTime,
}
})
.filter(typedBoolean),
requestInfo: {
hints: getHints(request),
origin: getDomainUrl(request),
path: new URL(request.url).pathname,
flyPrimaryInstance: primaryInstance,
userPrefs: {
theme: getTheme(request),
},
session: {
email: loginInfoSession.getEmail(),
magicLinkVerified: loginInfoSession.getMagicLinkVerified(),
},
},
}
const headers: HeadersInit = new Headers()
// this can lead to race conditions if a child route is also trying to commit
// the cookie as well. This is a bug in remix that will hopefully be fixed.
// we reduce the likelihood of a problem by only committing if the value is
// different.
await session.getHeaders(headers)
await clientSession.getHeaders(headers)
await loginInfoSession.getHeaders(headers)
headers.append('Server-Timing', getServerTimeHeader(timings))
return json(data, {headers})
}
export type RootLoaderType = typeof loader
export const headers: HeadersFunction = ({loaderHeaders}) => {
return {
'Server-Timing': loaderHeaders.get('Server-Timing') ?? '',
}
}
const LOADER_WORDS = [
'loading',
'checking cdn',
'checking cache',
'fetching from db',
'compiling mdx',
'updating cache',
'transfer',
]
const ACTION_WORDS = [
'packaging',
'zapping',
'validating',
'processing',
'calculating',
'computing',
'computering',
]
// we don't want to show the loading indicator on page load
let firstRender = true
function PageLoadingMessage() {
const navigation = useNavigation()
const [words, setWords] = React.useState<Array<string>>([])
const [pendingPath, setPendingPath] = React.useState('')
const showLoader = useSpinDelay(Boolean(navigation.state !== 'idle'), {
delay: 400,
minDuration: 1000,
})
React.useEffect(() => {
if (firstRender) return
if (navigation.state === 'idle') return
if (navigation.state === 'loading') setWords(LOADER_WORDS)
if (navigation.state === 'submitting') setWords(ACTION_WORDS)
const interval = setInterval(() => {
setWords(([first, ...rest]) => [...rest, first] as Array<string>)
}, 2000)
return () => clearInterval(interval)
}, [pendingPath, navigation.state])
React.useEffect(() => {
if (firstRender) return
if (navigation.state === 'idle') return
setPendingPath(navigation.location.pathname)
}, [navigation])
React.useEffect(() => {
firstRender = false
}, [])
const action = words[0]
return (
<NotificationMessage position="bottom-right" visible={showLoader}>
<div className="flex w-64 items-center">
<motion.div
transition={{repeat: Infinity, duration: 2, ease: 'linear'}}
animate={{rotate: 360}}
>
<TeamCircle size={48} team="UNKNOWN" />
</motion.div>
<div className="ml-4 inline-grid">
<AnimatePresence>
<div className="col-start-1 row-start-1 flex overflow-hidden">
<motion.span
key={action}
initial={{y: 15, opacity: 0}}
animate={{y: 0, opacity: 1}}
exit={{y: -15, opacity: 0}}
transition={{duration: 0.25}}
className="flex-none"
>
{action}
</motion.span>
</div>
</AnimatePresence>
<span className="text-secondary truncate">path: {pendingPath}</span>
</div>
</div>
</NotificationMessage>
)
}
declare global {
interface Window {
fathom:
| {
trackPageview(): void
}
| undefined
}
}
type FathomQueue = Array<{command: 'trackPageview'}>
function CanonicalLink({
origin,
fathomQueue,
}: {
origin: string
fathomQueue: React.MutableRefObject<FathomQueue>
}) {
const {pathname} = useLocation()
const canonicalUrl = removeTrailingSlash(`${origin}${pathname}`)
React.useEffect(() => {
if (window.fathom) {
window.fathom.trackPageview()
} else {
// Fathom hasn't finished loading yet! queue the command
fathomQueue.current.push({command: 'trackPageview'})
}
// Fathom looks uses the canonical URL to track visits, so we're using it
// as a dependency even though we're not using it explicitly
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [canonicalUrl])
return <link rel="canonical" href={canonicalUrl} />
}
function App() {
const data = useLoaderData<typeof loader>()
const nonce = useNonce()
const [team] = useTeam()
const theme = useTheme()
const fathomQueue = React.useRef<FathomQueue>([])
return (
<html
lang="en"
className={clsx(theme, `set-color-team-current-${team.toLowerCase()}`)}
>
<head>
<ClientHintCheck nonce={nonce} />
<Meta />
<meta
name="viewport"
content="width=device-width,initial-scale=1,viewport-fit=cover"
/>
<CanonicalLink
origin={data.requestInfo.origin}
fathomQueue={fathomQueue}
/>
<Links />
{ENV.NODE_ENV === 'production' && !ENV.DISABLE_METRONOME ? (
<MetronomeLinks nonce={nonce} />
) : null}
<noscript>
<link rel="stylesheet" href={noScriptStyles} />
</noscript>
</head>
<body className="bg-white transition duration-500 dark:bg-gray-900">
<PageLoadingMessage />
{Object.values(data.epicWebPromotifications).map(
({
promoName,
cookieValue,
startDate,
endDate,
text,
ticketLinkText,
}) =>
new Date(startDate).getTime() < Date.now() ? (
<Promotification
key={promoName}
cookieValue={cookieValue}
promoName={promoName}
promoEndTime={new Date(endDate)}
>
<div className="flex flex-col">
<p className="flex items-center gap-1">
<PartyIcon />
<span>
<a
href="https://www.epicweb.dev/conf"
className="underline"
>
Epic Web Conf
</a>{' '}
{text}
</span>
</p>
{ticketLinkText ? (
<p className="mt-1 text-sm">
<a
href="https://www.epicweb.dev/conf"
className="inline-flex items-center gap-1 underline"
>
<span>{ticketLinkText}</span>
<ArrowIcon direction="top-right" size={16} />
</a>
</p>
) : null}
<p className="mt-2 text-sm">
Join the community and network with other great web devs.
</p>
</div>
</Promotification>
) : null,
)}
{data.workshopPromotifications.map(e => (
<Promotification
key={e.slug}
cookieValue={e.cookieValue}
promoName={e.promoName}
promoEndTime={new Date(e.promoEndTime.time)}
dismissTimeSeconds={e.dismissTimeSeconds}
>
<div className="flex flex-col">
<p className="flex items-center gap-1">
<LaptopIcon />
<span>
Join Kent for an interactive{' '}
<Link to="/workshops" className="underline">
live workshop
</Link>
</span>
</p>
<Link
className="mt-3 text-lg underline"
to={`/workshops/${e.slug}`}
>
{e.title}
</Link>
{e.promoEndTime.type === 'discount' ? (
<p className="mt-1 text-sm text-gray-500">
Limited time{' '}
<a
href={e.promoEndTime.url}
className="inline-flex items-center gap-1 underline"
>
<span>discount available</span>
<ArrowIcon direction="top-right" size={16} />
</a>
</p>
) : e.promoEndTime.type === 'sales' ? (
<p className="mt-1 text-sm text-gray-500">
Limited time{' '}
<a
href={e.promoEndTime.url}
className="inline-flex items-center gap-1 underline"
>
<span>tickets available</span>
<ArrowIcon direction="top-right" size={16} />
</a>
</p>
) : null}
</div>
</Promotification>
))}
<NotificationMessage queryStringKey="message" delay={0.3} />
<Navbar />
<Outlet />
<Spacer size="base" />
<Footer image={images[data.randomFooterImageKey]} />
<ScrollRestoration nonce={nonce} />
{ENV.NODE_ENV === 'development' ? null : (
<script
nonce={nonce}
src="https://cdn.usefathom.com/script.js"
data-site="HJUUDKMT"
data-spa="history"
data-auto="false" // prevent tracking visit twice on initial page load
data-excluded-domains="localhost"
defer
onLoad={() => {
fathomQueue.current.forEach(({command}) => {
if (window.fathom) {
window.fathom[command]()
} else {
// Fathom isn't available even though the script has loaded
// this should never happen!
}
})
fathomQueue.current = []
}}
/>
)}
<Scripts nonce={nonce} />
<script
nonce={nonce}
suppressHydrationWarning
dangerouslySetInnerHTML={{
__html: `window.ENV = ${JSON.stringify(data.ENV)};`,
}}
/>
{ENV.NODE_ENV === 'development' ? (
<>
<LiveReload nonce={nonce} />
<script
nonce={nonce}
suppressHydrationWarning
dangerouslySetInnerHTML={{__html: getWebsocketJS()}}
/>
</>
) : null}
</body>
</html>
)
}
function AppWithProviders() {
return (
<TeamProvider>
<App />
</TeamProvider>
)
}
export default withSentry(AppWithProviders)
function ErrorDoc({children}: {children: React.ReactNode}) {
const nonce = useNonce()
return (
<html lang="en" className="dark">
<head>
<title>Oh no...</title>
<Links />
</head>
<body className="bg-white transition duration-500 dark:bg-gray-900">
{children}
<Scripts nonce={nonce} />
</body>
</html>
)
}
// best effort, last ditch error boundary. This should only catch root errors
// all other errors should be caught by the index route which will include
// the footer and stuff, which is much better.
export function ErrorBoundary() {
const error = useCapturedRouteError()
const location = useLocation()
if (isRouteErrorResponse(error)) {
console.error('CatchBoundary', error)
if (error.status === 404) {
return (
<ErrorDoc>
<ErrorPage
heroProps={{
title: "404 - Oh no, you found a page that's missing stuff.",
subtitle: `"${location.pathname}" is not a page on kentcdodds.com. So sorry.`,
image: (
<MissingSomething className="rounded-lg" aspectRatio="3:4" />
),
action: <ArrowLink href="/">Go home</ArrowLink>,
}}
/>
</ErrorDoc>
)
}
if (error.status === 400) {
return (
<ErrorDoc>
<FourHundred error={error.data} />
</ErrorDoc>
)
}
if (error.status === 409) {
return (
<ErrorDoc>
<ErrorPage
heroProps={{
title: '409 - Oh no, you should never see this.',
subtitle: `"${location.pathname}" tried telling fly to replay your request and missed this one.`,
image: <Grimmacing className="rounded-lg" aspectRatio="3:4" />,
action: <ArrowLink href="/">Go home</ArrowLink>,
}}
/>
</ErrorDoc>
)
}
if (error.status !== 500) {
return (
<ErrorDoc>
<ErrorPage
heroProps={{
title: `${error.status} - Oh no, something did not go well.`,
subtitle: `"${location.pathname}" is currently not working. So sorry.`,
image: <Grimmacing className="rounded-lg" aspectRatio="3:4" />,
action: <ArrowLink href="/">Go home</ArrowLink>,
}}
/>
</ErrorDoc>
)
}
throw new Error(`Unhandled error: ${error.status}`)
}
console.error(error)
return (
<ErrorDoc>
<ErrorPage
heroProps={{
title: '500 - Oh no, something did not go well.',
subtitle: `"${location.pathname}" is currently not working. So sorry.`,
image: <Grimmacing className="rounded-lg" aspectRatio="3:4" />,
action: <ArrowLink href="/">Go home</ArrowLink>,
}}
/>
</ErrorDoc>
)
}
function kcdLiveReloadConnect(config?: {onOpen: () => void}) {
const protocol = location.protocol === 'https:' ? 'wss:' : 'ws:'
const host = location.hostname
const port = location.port
const socketPath = `${protocol}//${host}:${port}/__ws`
const ws = new WebSocket(socketPath)
ws.onmessage = message => {
const event = JSON.parse(message.data)
if (
event.type === 'kentcdodds.com:file-change' &&
event.data.relativePath === location.pathname
) {
window.location.reload()
}
}
ws.onopen = () => {
if (config && typeof config.onOpen === 'function') {
config.onOpen()
}
}
ws.onclose = event => {
if (event.code === 1006) {
console.log(
'kentcdodds.com dev server web socket closed. Reconnecting...',
)
setTimeout(
() =>
kcdLiveReloadConnect({
onOpen: () => window.location.reload(),
}),
1000,
)
}
}
ws.onerror = error => {
console.log('kentcdodds.com dev server web socket error:')
console.error(error)
}
}
function getWebsocketJS() {
const js = /* javascript */ `
${kcdLiveReloadConnect.toString()}
kcdLiveReloadConnect();
`
return js
}
/*
eslint
@typescript-eslint/no-use-before-define: "off",
*/