_app.tsx 4.13 KB
Newer Older
Stefan Probst's avatar
Stefan Probst committed
1
2
3
4
5
6
7
8
// import 'focus-visible'
import '@/styles/global.css'
import 'tailwindcss/tailwind.css'
import '@/styles/nprogress.css'
/** should use ReactToastify.minimal.css */
import 'react-toastify/dist/ReactToastify.css'
import '@/styles/dialog.css'

Stefan Probst's avatar
Stefan Probst committed
9
10
import { I18nProvider } from '@react-aria/i18n'
import { useInteractionModality } from '@react-aria/interactions'
11
import { SSRProvider } from '@react-aria/ssr'
Stefan Probst's avatar
Stefan Probst committed
12
13
14
15
16
17
18
import Layout from '@stefanprobst/next-app-layout'
import ErrorBoundary from '@stefanprobst/next-error-boundary'
import type { AppProps, NextWebVitalsMetric } from 'next/app'
import Head from 'next/head'
import { Router } from 'next/router'
import np from 'nprogress'
import type { PropsWithChildren } from 'react'
19
import { Fragment, useState } from 'react'
Stefan Probst's avatar
Stefan Probst committed
20
21
import { QueryClient, QueryClientProvider } from 'react-query'
import { ReactQueryDevtools } from 'react-query/devtools'
Stefan Probst's avatar
Stefan Probst committed
22
23
import { Slide, ToastContainer } from 'react-toastify'

Stefan Probst's avatar
Stefan Probst committed
24
25
26
27
28
29
30
31
32
import AuthProvider from '@/modules/auth/AuthContext'
import ClientError from '@/modules/error/ClientError'
import PageLayout from '@/modules/page/PageLayout'

/**
 * Report web vitals.
 */
export function reportWebVitals(metric: NextWebVitalsMetric): void {
  /** should be dispatched to an analytics service */
Stefan Probst's avatar
Stefan Probst committed
33
  // console.info(metric)
Stefan Probst's avatar
Stefan Probst committed
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
}

/**
 * Report page transitions to Matomo analytics.
 */
Router.events.on('routeChangeComplete', (url) => {
  if (typeof window !== 'undefined') {
    const w = window as typeof window & { _paq?: Array<unknown> }
    if (w._paq !== undefined) {
      w._paq.push(['setCustomUrl', url])
      w._paq.push(['setDocumentTitle', document.title])
      w._paq.push(['trackPageView'])
    }
  }
})

/**
 * Progress bar for client-side page transitions.
 */
np.configure({ showSpinner: false })
/** show progress indicator only if transition takes longer than `delay` */
const delay = 250
let timeout: number
function startProgressIndicator() {
  timeout = window.setTimeout(np.start, delay)
}
function stopProgressIndicator() {
  window.clearTimeout(timeout)
  np.done()
}
Router.events.on('routeChangeStart', startProgressIndicator)
Router.events.on('routeChangeComplete', stopProgressIndicator)
Router.events.on('routeChangeError', stopProgressIndicator)

/**
69
 * Create client side cache for server data.
Stefan Probst's avatar
Stefan Probst committed
70
 */
71
72
73
74
75
76
77
78
function createQueryClient() {
  const queryClient = new QueryClient({
    defaultOptions: {
      queries: {
        cacheTime: Infinity,
        staleTime: Infinity,
        structuralSharing: false,
      },
Stefan Probst's avatar
Stefan Probst committed
79
    },
80
81
82
83
  })

  return queryClient
}
Stefan Probst's avatar
Stefan Probst committed
84
85
86
87
88

/**
 * Providers.
 */
function Providers({ children }: PropsWithChildren<unknown>) {
89
90
  const [queryClient] = useState(() => createQueryClient())

Stefan Probst's avatar
Stefan Probst committed
91
92
  useInteractionModality()

Stefan Probst's avatar
Stefan Probst committed
93
  return (
94
95
96
    <SSRProvider>
      <I18nProvider locale="en">
        <QueryClientProvider client={queryClient}>
Stefan Probst's avatar
Stefan Probst committed
97
98
99
100
101
102
          <AuthProvider
            onSignIn={queryClient.clear}
            onSignOut={queryClient.clear}
          >
            {children}
          </AuthProvider>
103
104
105
        </QueryClientProvider>
      </I18nProvider>
    </SSRProvider>
Stefan Probst's avatar
Stefan Probst committed
106
107
108
109
110
111
  )
}

/**
 * App shell.
 */
112
113
114
115
116
export default function App({
  Component,
  pageProps,
  router,
}: AppProps): JSX.Element {
Stefan Probst's avatar
Stefan Probst committed
117
118
119
120
121
  return (
    <Fragment>
      <Head>
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      </Head>
122
      <ErrorBoundary fallback={ClientError} resetOnChange={[router.asPath]}>
Stefan Probst's avatar
Stefan Probst committed
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
        <Providers {...pageProps}>
          <Layout {...pageProps} default={PageLayout}>
            <Component {...pageProps} />
          </Layout>
          <ToastContainer
            transition={Slide}
            toastClassName={({ type } = {}) => {
              const shared =
                'relative mb-4 p-4 rounded shadow-md flex justify-between overflow-hidden cursor-pointer'
              switch (type) {
                case 'error':
                  return [shared, 'bg-error-600 text-white'].join(' ')
                default:
                  return [shared, 'bg-secondary-600 text-white'].join(' ')
              }
            }}
            bodyClassName="text-sm font-medium p-2 flex-1 mx-auto"
          />
          <ReactQueryDevtools />
        </Providers>
      </ErrorBoundary>
    </Fragment>
  )
}