Skip to content

📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

Move theme functionality to Context API

Blue Mouse8eef8156a0c6
diff --git a/web/app/App.tsx b/web/app/App.tsx
index 5e4a78c66..c7258c2e0 100644
--- a/web/app/App.tsx
+++ b/web/app/App.tsx
@@ -20,24 +20,23 @@ import routesPath from '~/utils/routes'
import { getPageMeta } from '~/utils/server'
import { authMe, getInstalledExtensions } from './api'
+import { useTheme } from './providers/ThemeProvider'
interface AppProps {
- ssrTheme: 'dark' | 'light'
ssrAuthenticated: boolean
}
const TITLE_BLACKLIST = ['/projects/', '/captchas/', '/blog']
-const App = ({ ssrTheme, ssrAuthenticated }: AppProps) => {
+const App = ({ ssrAuthenticated }: AppProps) => {
const dispatch = useAppDispatch()
const { pathname } = useLocation()
const { t } = useTranslation('common')
const { loading } = useSelector((state: StateType) => state.auth)
const reduxAuthenticated = useSelector((state: StateType) => state.auth.authenticated)
- const reduxTheme = useSelector((state: StateType) => state.ui.theme.theme)
+ const { theme } = useTheme()
const accessToken = getAccessToken()
const authenticated = isBrowser ? (loading ? !!accessToken : reduxAuthenticated) : ssrAuthenticated
- const theme = isBrowser ? reduxTheme : ssrTheme
useEffect(() => {
void (async () => {
@@ -91,7 +90,7 @@ const App = ({ ssrTheme, ssrAuthenticated }: AppProps) => {
return (
<>
{!_includes(routesWithOutHeader, pathname) && !isReferralPage && !isProjectViewPage ? (
- <Header ssrTheme={ssrTheme} authenticated={authenticated} />
+ <Header authenticated={authenticated} />
) : null}
<Outlet />
<Toaster
diff --git a/web/app/components/GithubAuth.tsx b/web/app/components/GithubAuth.tsx
index d582c237f..f3c7e50ad 100644
--- a/web/app/components/GithubAuth.tsx
+++ b/web/app/components/GithubAuth.tsx
@@ -1,25 +1,21 @@
import cx from 'clsx'
import { useTranslation } from 'react-i18next'
-import { useSelector } from 'react-redux'
-import { isBrowser } from '~/lib/constants'
-import { StateType } from '~/lib/store/index'
+import { useTheme } from '~/providers/ThemeProvider'
import Button from '~/ui/Button'
import GithubDarkSVG from '~/ui/icons/GithubDark'
import GithubLightSVG from '~/ui/icons/GithubLight'
interface GoogleAuthProps {
- ssrTheme: string
isMiniButton?: boolean
className?: string
onClick: () => void
disabled?: boolean
}
-const GithubAuth = ({ isMiniButton, className, ssrTheme, onClick, disabled }: GoogleAuthProps) => {
+const GithubAuth = ({ isMiniButton, className, onClick, disabled }: GoogleAuthProps) => {
const { t } = useTranslation()
- const reduxTheme = useSelector((state: StateType) => state.ui.theme.theme)
- const theme = isBrowser ? reduxTheme : ssrTheme
+ const { theme } = useTheme()
if (isMiniButton) {
return (
diff --git a/web/app/components/Header/index.tsx b/web/app/components/Header/index.tsx
index 6f35828eb..8095b0c6d 100644
--- a/web/app/components/Header/index.tsx
+++ b/web/app/components/Header/index.tsx
@@ -21,7 +21,6 @@ import duration from 'dayjs/plugin/duration'
import utc from 'dayjs/plugin/utc'
import { type t as i18nextT } from 'i18next'
import { changeLanguage } from 'i18next'
-import _includes from 'lodash/includes'
import _map from 'lodash/map'
import _startsWith from 'lodash/startsWith'
import { GaugeIcon, ChartPieIcon, BugIcon, PuzzleIcon, PhoneIcon } from 'lucide-react'
@@ -36,15 +35,13 @@ import {
languageFlag,
isSelfhosted,
DOCS_URL,
- SUPPORTED_THEMES,
- isBrowser,
CAPTCHA_URL,
isDisableMarketingPages,
} from '~/lib/constants'
import { User } from '~/lib/models/User'
import { authActions } from '~/lib/reducers/auth'
-import UIActions from '~/lib/reducers/ui'
import { useAppDispatch, StateType } from '~/lib/store'
+import { useTheme } from '~/providers/ThemeProvider'
import Dropdown from '~/ui/Dropdown'
import Flag from '~/ui/Flag'
import SwetrixLogo from '~/ui/icons/SwetrixLogo'
@@ -205,7 +202,8 @@ const SolutionsMenu = () => {
)
}
-const ThemeMenu = ({ theme, switchTheme }: { theme: string; switchTheme: (i: string) => void }) => {
+const ThemeMenu = () => {
+ const { theme, setTheme } = useTheme()
const { t } = useTranslation('common')
return (
@@ -239,7 +237,7 @@ const ThemeMenu = ({ theme, switchTheme }: { theme: string; switchTheme: (i: str
'bg-gray-100 dark:bg-slate-800': active,
},
)}
- onClick={() => switchTheme('light')}
+ onClick={() => setTheme('light')}
>
<SunIcon className='mr-2 h-5 w-5 text-indigo-600 dark:text-gray-200' aria-hidden='true' />
{t('header.light')}
@@ -255,7 +253,7 @@ const ThemeMenu = ({ theme, switchTheme }: { theme: string; switchTheme: (i: str
'bg-gray-100 dark:bg-slate-800': active,
},
)}
- onClick={() => switchTheme('dark')}
+ onClick={() => setTheme('dark')}
>
<MoonIcon className='mr-2 h-5 w-5 text-gray-200 dark:text-indigo-400' aria-hidden='true' />
{t('header.dark')}
@@ -480,8 +478,6 @@ const Separator = () => (
const AuthedHeader = ({
user,
- switchTheme,
- theme,
rawStatus,
status,
logoutHandler,
@@ -489,14 +485,13 @@ const AuthedHeader = ({
openMenu,
}: {
user: User
- switchTheme: (thm?: string) => void
- theme: 'dark' | 'light'
rawStatus: string | number
status: string
logoutHandler: () => void
colourBackground: boolean
openMenu: () => void
}) => {
+ const { theme, setTheme } = useTheme()
const { t } = useTranslation('common')
return (
@@ -510,7 +505,7 @@ const AuthedHeader = ({
<div className='flex items-center'>
{/* Logo */}
<Link to={routes.main}>
- <SwetrixLogo theme={theme} />
+ <SwetrixLogo />
</Link>
<div className='ml-10 hidden gap-4 space-x-1 lg:flex'>
@@ -574,7 +569,7 @@ const AuthedHeader = ({
</div>
</div>
<div className='ml-1 hidden flex-wrap items-center justify-center space-y-1 space-x-2 sm:space-y-0 lg:ml-10 lg:flex lg:space-x-4'>
- <ThemeMenu theme={theme} switchTheme={switchTheme} />
+ <ThemeMenu />
<ProfileMenu user={user} logoutHandler={logoutHandler} />
</div>
<div className='flex items-center justify-center space-x-3 lg:hidden'>
@@ -582,14 +577,14 @@ const AuthedHeader = ({
{theme === 'dark' ? (
<div className='rotate-180 transition-all duration-1000 ease-in-out'>
<SunIcon
- onClick={() => switchTheme()}
+ onClick={() => setTheme('light')}
className='h-8 w-8 cursor-pointer text-gray-200 hover:text-gray-300'
/>
</div>
) : (
<div className='transition-all duration-1000 ease-in-out'>
<MoonIcon
- onClick={() => switchTheme()}
+ onClick={() => setTheme('dark')}
className='h-8 w-8 cursor-pointer text-slate-700 hover:text-slate-600'
/>
</div>
@@ -610,18 +605,15 @@ const AuthedHeader = ({
}
const NotAuthedHeader = ({
- switchTheme,
- theme,
colourBackground,
refPage,
openMenu,
}: {
- switchTheme: (a?: string) => void
- theme: 'dark' | 'light'
colourBackground: boolean
refPage?: boolean
openMenu: () => void
}) => {
+ const { theme, setTheme } = useTheme()
const {
t,
i18n: { language },
@@ -638,10 +630,10 @@ const NotAuthedHeader = ({
<div className='flex items-center'>
{/* Logo */}
{refPage ? (
- <SwetrixLogo theme={theme} />
+ <SwetrixLogo />
) : (
<Link to={routes.main}>
- <SwetrixLogo theme={theme} />
+ <SwetrixLogo />
</Link>
)}
@@ -717,7 +709,7 @@ const NotAuthedHeader = ({
}}
headless
/>
- <ThemeMenu theme={theme} switchTheme={switchTheme} />
+ <ThemeMenu />
{!refPage ? (
<>
<Separator />
@@ -736,14 +728,14 @@ const NotAuthedHeader = ({
{theme === 'dark' ? (
<div className='rotate-180 transition-all duration-1000 ease-in-out'>
<SunIcon
- onClick={() => switchTheme()}
+ onClick={() => setTheme('light')}
className='h-8 w-8 cursor-pointer text-gray-200 hover:text-gray-300'
/>
</div>
) : (
<div className='transition-all duration-1000 ease-in-out'>
<MoonIcon
- onClick={() => switchTheme()}
+ onClick={() => setTheme('dark')}
className='h-8 w-8 cursor-pointer text-slate-700 hover:text-slate-600'
/>
</div>
@@ -764,22 +756,20 @@ const NotAuthedHeader = ({
}
interface HeaderProps {
- ssrTheme: 'dark' | 'light'
authenticated: boolean
refPage?: boolean
transparent?: boolean
}
-const Header = ({ ssrTheme, authenticated, refPage, transparent }: HeaderProps) => {
+const Header = ({ authenticated, refPage, transparent }: HeaderProps) => {
const {
t,
i18n: { language },
} = useTranslation('common')
const dispatch = useAppDispatch()
const { user } = useSelector((state: StateType) => state.auth)
- const reduxTheme = useSelector((state: StateType) => state.ui.theme.theme)
const [mobileMenuOpen, setMobileMenuOpen] = useState(false)
- const theme = isBrowser ? reduxTheme : ssrTheme
+ const { theme, setTheme } = useTheme()
const solutions = getSolutions(t)
@@ -823,11 +813,6 @@ const Header = ({ ssrTheme, authenticated, refPage, transparent }: HeaderProps)
logout()
}
- const switchTheme = (_theme?: string) => {
- const newTheme = (_includes(SUPPORTED_THEMES, _theme) && _theme) || (theme === 'dark' ? 'light' : 'dark')
- dispatch(UIActions.setTheme(newTheme as 'light' | 'dark'))
- }
-
const openMenu = () => {
setMobileMenuOpen(true)
}
@@ -841,19 +826,11 @@ const Header = ({ ssrTheme, authenticated, refPage, transparent }: HeaderProps)
rawStatus={rawStatus || ''}
status={status || ''}
logoutHandler={logoutHandler}
- switchTheme={switchTheme}
- theme={theme}
colourBackground={!transparent}
openMenu={openMenu}
/>
) : (
- <NotAuthedHeader
- switchTheme={switchTheme}
- theme={theme}
- colourBackground={!transparent}
- refPage={refPage}
- openMenu={openMenu}
- />
+ <NotAuthedHeader colourBackground={!transparent} refPage={refPage} openMenu={openMenu} />
)}
{/* Mobile header popup */}
@@ -861,20 +838,20 @@ const Header = ({ ssrTheme, authenticated, refPage, transparent }: HeaderProps)
<div className='fixed inset-0 z-10' />
<DialogPanel className='fixed inset-y-0 top-0 right-0 z-30 w-full overflow-y-auto border-gray-300/80 bg-gray-100/80 p-4 backdrop-blur-2xl sm:max-w-sm sm:border dark:border-slate-900/80 dark:bg-slate-800/80'>
<div className='flex items-center justify-between'>
- <SwetrixLogo theme={theme} />
+ <SwetrixLogo />
<div className='flex items-center justify-center space-x-3'>
{/* Theme switch */}
{theme === 'dark' ? (
<div className='rotate-180 transition-all duration-1000 ease-in-out'>
<SunIcon
- onClick={() => switchTheme()}
+ onClick={() => setTheme('light')}
className='h-8 w-8 cursor-pointer text-gray-200 hover:text-gray-300'
/>
</div>
) : (
<div className='transition-all duration-1000 ease-in-out'>
<MoonIcon
- onClick={() => switchTheme()}
+ onClick={() => setTheme('dark')}
className='h-8 w-8 cursor-pointer text-slate-700 hover:text-slate-600'
/>
</div>
diff --git a/web/app/components/marketing/DitchGoogle.tsx b/web/app/components/marketing/DitchGoogle.tsx
index 3c1c082a7..febb08054 100644
--- a/web/app/components/marketing/DitchGoogle.tsx
+++ b/web/app/components/marketing/DitchGoogle.tsx
@@ -2,6 +2,7 @@ import { ArrowRightIcon } from '@heroicons/react/20/solid'
import { Trans, useTranslation } from 'react-i18next'
import { Link } from 'react-router'
+import { useTheme } from '~/providers/ThemeProvider'
import routes from '~/utils/routes'
interface DitchGoogleProps {
@@ -9,11 +10,11 @@ interface DitchGoogleProps {
light: string
dark: string
}
- theme: 'dark' | 'light'
}
-export const DitchGoogle = ({ screenshot: { light, dark }, theme }: DitchGoogleProps) => {
+export const DitchGoogle = ({ screenshot: { light, dark } }: DitchGoogleProps) => {
const { t } = useTranslation('common')
+ const { theme } = useTheme()
return (
<div className='bg-white px-4 pb-12 md:px-8 dark:bg-slate-900'>
diff --git a/web/app/components/marketing/Pricing.tsx b/web/app/components/marketing/Pricing.tsx
index 34b1532cd..a35263da3 100644
--- a/web/app/components/marketing/Pricing.tsx
+++ b/web/app/components/marketing/Pricing.tsx
@@ -26,6 +26,7 @@ import {
import { DEFAULT_METAINFO, Metainfo } from '~/lib/models/Metainfo'
import { authActions } from '~/lib/reducers/auth'
import { AppDispatch, StateType } from '~/lib/store'
+import { useTheme } from '~/providers/ThemeProvider'
import { Badge } from '~/ui/Badge'
import Button from '~/ui/Button'
import Loader from '~/ui/Loader'
@@ -62,7 +63,7 @@ const Pricing = ({ authenticated, isBillingPage, lastEvent }: PricingProps) => {
} = useTranslation('common')
const dispatch = useDispatch<AppDispatch>()
const { user } = useSelector((state: StateType) => state.auth)
- const { theme } = useSelector((state: StateType) => state.ui.theme)
+ const { theme } = useTheme()
const [metainfo, setMetainfo] = useState<Metainfo>(DEFAULT_METAINFO)
diff --git a/web/app/lib/reducers/ui/index.ts b/web/app/lib/reducers/ui/index.ts
deleted file mode 100644
index 54549f6dd..000000000
--- a/web/app/lib/reducers/ui/index.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import { themeActions } from './theme'
-
-const UIActions = {
- ...themeActions,
-}
-
-export default UIActions
diff --git a/web/app/lib/reducers/ui/theme.ts b/web/app/lib/reducers/ui/theme.ts
deleted file mode 100644
index 02471971d..000000000
--- a/web/app/lib/reducers/ui/theme.ts
+++ /dev/null
@@ -1,81 +0,0 @@
-import { createSlice, PayloadAction } from '@reduxjs/toolkit'
-import _includes from 'lodash/includes'
-
-import { isBrowser, LS_THEME_SETTING, SUPPORTED_THEMES, ThemeType } from '~/lib/constants'
-import { setCookie, getCookie } from '~/utils/cookie'
-
-const setThemeToDOM = (theme: string) => {
- if (!isBrowser) {
- return
- }
-
- const root = window.document.documentElement
- const isDark = theme === 'dark'
-
- root.classList.remove(isDark ? 'light' : 'dark')
- root.classList.add(theme)
-}
-
-const setTheme = (theme: string, storeToCookie = true): string => {
- setThemeToDOM(theme)
-
- if (storeToCookie) {
- setCookie(LS_THEME_SETTING, theme, 3600 * 24 * 90) // storing theme data for 90 days
- }
-
- return theme
-}
-
-const getInitialTheme = (): ThemeType => {
- if (!isBrowser) {
- return 'light'
- }
-
- const queryTheme = new URLSearchParams(window.location.search).get('theme') as ThemeType | null
-
- if (queryTheme && _includes(SUPPORTED_THEMES, queryTheme)) {
- setThemeToDOM(queryTheme)
- return queryTheme
- }
-
- const lsTheme: any = getCookie(LS_THEME_SETTING)
-
- if (_includes(SUPPORTED_THEMES, lsTheme)) {
- setThemeToDOM(lsTheme)
- return lsTheme
- }
-
- // const userMedia = window.matchMedia('(prefers-color-scheme: dark)')
- // if (userMedia.matches) {
- // setTheme('dark')
- // return 'dark'
- // }
-
- setTheme('light', false)
- return 'light' // light theme as the default
-}
-
-interface InitialState {
- theme: ThemeType
-}
-
-const getInitialState = (): InitialState => {
- return {
- theme: getInitialTheme(),
- }
-}
-
-const themeSlice = createSlice({
- name: 'theme',
- initialState: getInitialState(),
- reducers: {
- setTheme(state, { payload }: PayloadAction<ThemeType>) {
- setTheme(payload)
- state.theme = payload
- },
- },
-})
-
-export const themeActions = themeSlice.actions
-
-export default themeSlice.reducer
diff --git a/web/app/lib/store/index.ts b/web/app/lib/store/index.ts
index 2adc2eebe..6b11e2e07 100644
--- a/web/app/lib/store/index.ts
+++ b/web/app/lib/store/index.ts
@@ -4,13 +4,9 @@ import { useDispatch } from 'react-redux'
import { isDevelopment } from '~/lib/constants'
import authSlice from '../reducers/auth'
-import themeSlice from '../reducers/ui/theme'
const rootReducer = combineReducers({
auth: authSlice,
- ui: combineReducers({
- theme: themeSlice,
- }),
})
export const store = configureStore({
diff --git a/web/app/pages/Auth/Signin/Signin.tsx b/web/app/pages/Auth/Signin/Signin.tsx
index 662e005aa..72a1258f8 100644
--- a/web/app/pages/Auth/Signin/Signin.tsx
+++ b/web/app/pages/Auth/Signin/Signin.tsx
@@ -31,13 +31,9 @@ interface SigninForm {
dontRemember: boolean
}
-interface SigninProps {
- ssrTheme: string
-}
-
const HASH_CHECK_FREQUENCY = 1000
-const Signin = ({ ssrTheme }: SigninProps) => {
+const Signin = () => {
const dispatch = useAppDispatch()
const navigate = useNavigate()
const [searchParams] = useSearchParams()
@@ -360,7 +356,7 @@ const Signin = ({ ssrTheme }: SigninProps) => {
</div>
<div className='mt-6 grid grid-cols-2 gap-4'>
<GoogleAuth onClick={() => onSsoLogin('google')} disabled={isLoading} />
- <GithubAuth onClick={() => onSsoLogin('github')} ssrTheme={ssrTheme} disabled={isLoading} />
+ <GithubAuth onClick={() => onSsoLogin('github')} disabled={isLoading} />
</div>
</div>
) : null}
diff --git a/web/app/pages/Auth/Signup/Signup.tsx b/web/app/pages/Auth/Signup/Signup.tsx
index 9f141d7aa..521711920 100644
--- a/web/app/pages/Auth/Signup/Signup.tsx
+++ b/web/app/pages/Auth/Signup/Signup.tsx
@@ -35,13 +35,9 @@ interface SignupForm {
checkIfLeaked: boolean
}
-interface SignupProps {
- ssrTheme: string
-}
-
const HASH_CHECK_FREQUENCY = 1000
-const Signup = ({ ssrTheme }: SignupProps) => {
+const Signup = () => {
const dispatch = useAppDispatch()
const { authenticated: reduxAuthenticated, loading } = useSelector((state: StateType) => state.auth)
const { t } = useTranslation('common')
@@ -367,7 +363,7 @@ const Signup = ({ ssrTheme }: SignupProps) => {
</div>
<div className='mt-6 grid grid-cols-2 gap-4'>
<GoogleAuth onClick={() => onSsoLogin('google')} disabled={isLoading} />
- <GithubAuth onClick={() => onSsoLogin('github')} ssrTheme={ssrTheme} disabled={isLoading} />
+ <GithubAuth onClick={() => onSsoLogin('github')} disabled={isLoading} />
</div>
</div>
</div>
diff --git a/web/app/pages/Billing/index.tsx b/web/app/pages/Billing/index.tsx
index c9fd32f74..9e183497c 100644
--- a/web/app/pages/Billing/index.tsx
+++ b/web/app/pages/Billing/index.tsx
@@ -22,6 +22,7 @@ import {
import { DEFAULT_METAINFO, Metainfo } from '~/lib/models/Metainfo'
import { UsageInfo } from '~/lib/models/Usageinfo'
import { StateType } from '~/lib/store'
+import { useTheme } from '~/providers/ThemeProvider'
import Button from '~/ui/Button'
import Loader from '~/ui/Loader'
import Modal from '~/ui/Modal'
@@ -36,10 +37,9 @@ dayjs.extend(duration)
interface BillingProps {
ssrAuthenticated: boolean
- ssrTheme: 'dark' | 'light'
}
-const Billing = ({ ssrAuthenticated, ssrTheme }: BillingProps) => {
+const Billing = ({ ssrAuthenticated }: BillingProps) => {
const [isCancelSubModalOpened, setIsCancelSubModalOpened] = useState(false)
const [metainfo, setMetainfo] = useState<Metainfo>(DEFAULT_METAINFO)
@@ -48,8 +48,7 @@ const Billing = ({ ssrAuthenticated, ssrTheme }: BillingProps) => {
} | null>(null)
const { user, loading: authLoading } = useSelector((state: StateType) => state.auth)
- const { theme: reduxTheme } = useSelector((state: StateType) => state.ui.theme)
- const theme = isBrowser ? reduxTheme : ssrTheme
+ const { theme } = useTheme()
const reduxAuthenticated = useSelector((state: StateType) => state.auth.authenticated)
const [usageInfo, setUsageInfo] = useState<UsageInfo>({
total: 0,
@@ -391,7 +390,6 @@ const Billing = ({ ssrAuthenticated, ssrTheme }: BillingProps) => {
}
tooltipNode={
<MultiProgress
- theme={theme}
className='w-[85vw] max-w-[25rem]'
progress={[
{
diff --git a/web/app/pages/Captcha/View/ViewCaptcha.tsx b/web/app/pages/Captcha/View/ViewCaptcha.tsx
index cd2036b07..2daa6067e 100644
--- a/web/app/pages/Captcha/View/ViewCaptcha.tsx
+++ b/web/app/pages/Captcha/View/ViewCaptcha.tsx
@@ -11,7 +11,7 @@ import _map from 'lodash/map'
import _replace from 'lodash/replace'
import _startsWith from 'lodash/startsWith'
import { DownloadIcon, RotateCw, SettingsIcon } from 'lucide-react'
-import { useState, useEffect, useMemo, memo, useRef } from 'react'
+import { useState, useEffect, useMemo, useRef } from 'react'
import { useTranslation } from 'react-i18next'
import { useSelector } from 'react-redux'
import { useNavigate, useSearchParams } from 'react-router'
@@ -31,16 +31,15 @@ import {
BROWSER_LOGO_MAP,
OS_LOGO_MAP,
OS_LOGO_MAP_DARK,
- isBrowser,
- ThemeType,
DEFAULT_TIMEZONE,
} from '~/lib/constants'
import { StateType } from '~/lib/store'
-import { useCurrentProject } from '~/providers/CurrentProjectProvider'
import { Panel } from '~/pages/Project/View/Panels'
import { parseFiltersFromUrl } from '~/pages/Project/View/utils/filters'
import { ViewProjectContext } from '~/pages/Project/View/ViewProject'
import { deviceIconMapping, onCSVExportClick } from '~/pages/Project/View/ViewProject.helpers'
+import { useCurrentProject } from '~/providers/CurrentProjectProvider'
+import { useTheme } from '~/providers/ThemeProvider'
import Dropdown from '~/ui/Dropdown'
import FlatPicker from '~/ui/Flatpicker'
import BarChart from '~/ui/icons/BarChart'
@@ -73,15 +72,11 @@ const PageLoader = () => (
</div>
)
-interface ViewCaptchaProps {
- ssrTheme: ThemeType
-}
-
-const ViewCaptcha = ({ ssrTheme }: ViewCaptchaProps) => {
+const ViewCaptcha = () => {
const { id, project, preferences, updatePreferences } = useCurrentProject()
const { loading: authLoading, user } = useSelector((state: StateType) => state.auth)
- const { theme } = useSelector((state: StateType) => state.ui.theme)
+ const { theme } = useTheme()
const {
t,
@@ -127,8 +122,6 @@ const ViewCaptcha = ({ ssrTheme }: ViewCaptchaProps) => {
const [chartType, setChartType] = useState<string>((getItem('chartType') as string) || chartTypes.line)
const [mainChart, setMainChart] = useState<any>(null)
- const _theme = isBrowser ? theme : ssrTheme
-
const { timezone = DEFAULT_TIMEZONE } = user || {}
useEffect(() => {
@@ -854,7 +847,7 @@ const ViewCaptcha = ({ ssrTheme }: ViewCaptchaProps) => {
// @ts-expect-error
const logoPathDark = OS_LOGO_MAP_DARK[entryName]
- let logoPath = _theme === 'dark' ? logoPathDark : logoPathLight
+ let logoPath = theme === 'dark' ? logoPathDark : logoPathLight
logoPath ||= logoPathLight
if (!logoPath) {
@@ -914,4 +907,4 @@ const ViewCaptcha = ({ ssrTheme }: ViewCaptchaProps) => {
)
}
-export default memo(ViewCaptcha)
+export default ViewCaptcha
diff --git a/web/app/pages/ErrorTracking/index.tsx b/web/app/pages/ErrorTracking/index.tsx
index 10171bfe4..a8dbb7c4c 100644
--- a/web/app/pages/ErrorTracking/index.tsx
+++ b/web/app/pages/ErrorTracking/index.tsx
@@ -13,6 +13,7 @@ import Header from '~/components/Header'
import { DitchGoogle } from '~/components/marketing/DitchGoogle'
import { ERROR_TRACKING_LIVE_DEMO_URL, isBrowser } from '~/lib/constants'
import { StateType } from '~/lib/store/index'
+import { useTheme } from '~/providers/ThemeProvider'
import BackgroundSvg from '~/ui/icons/BackgroundSvg'
import { getAccessToken } from '~/utils/accessToken'
import routesPath from '~/utils/routes'
@@ -28,16 +29,14 @@ const Lines = () => (
)
interface ErrorTrackingProps {
- ssrTheme: 'dark' | 'light'
ssrAuthenticated: boolean
}
-const ErrorTracking = ({ ssrTheme, ssrAuthenticated }: ErrorTrackingProps) => {
+const ErrorTracking = ({ ssrAuthenticated }: ErrorTrackingProps) => {
const { t } = useTranslation('common')
- const reduxTheme = useSelector((state: StateType) => state.ui.theme.theme)
+ const { theme } = useTheme()
const { authenticated: reduxAuthenticated, loading } = useSelector((state: StateType) => state.auth)
const [lastBlogPost, setLastBlogPost] = useState<Awaited<ReturnType<typeof getLastPost>> | null>(null)
- const theme = isBrowser ? reduxTheme : ssrTheme
const accessToken = getAccessToken()
const authenticated = isBrowser ? (loading ? !!accessToken : reduxAuthenticated) : ssrAuthenticated
@@ -85,7 +84,7 @@ const ErrorTracking = ({ ssrTheme, ssrAuthenticated }: ErrorTrackingProps) => {
}}
/>
</div>
- <Header ssrTheme={ssrTheme} authenticated={authenticated} transparent />
+ <Header authenticated={authenticated} transparent />
<div className='relative mx-auto min-h-[740px] pt-10 pb-5 sm:px-3 lg:px-6 lg:pt-24 xl:px-8'>
<div className='relative z-20 flex flex-row content-between justify-center lg:justify-start 2xl:mr-[14vw] 2xl:justify-center'>
<div className='relative px-4 text-left lg:mt-0 lg:mr-14'>
@@ -242,16 +241,15 @@ const ErrorTracking = ({ ssrTheme, ssrAuthenticated }: ErrorTrackingProps) => {
dark: '/assets/screenshot_errors_dark.png',
light: '/assets/screenshot_errors_light.png',
}}
- theme={theme}
/>
{/* Become a developer */}
<section className='relative bg-white pt-20 pb-44 dark:bg-slate-900'>
<div className='absolute top-16 right-0 z-0'>
- <BackgroundSvg theme={theme} type='threecircle' />
+ <BackgroundSvg type='threecircle' />
</div>
<div className='absolute top-52 -left-9 rotate-90'>
- <BackgroundSvg theme={theme} type='shapes' />
+ <BackgroundSvg type='shapes' />
</div>
<PeopleLoveSwetrix />
</section>
diff --git a/web/app/pages/Landings/Marketers.tsx b/web/app/pages/Landings/Marketers.tsx
index 58c927e4e..4d03601a3 100644
--- a/web/app/pages/Landings/Marketers.tsx
+++ b/web/app/pages/Landings/Marketers.tsx
@@ -9,24 +9,23 @@ import { ComparisonTable } from '~/components/marketing/ComparisonTable'
import { DitchGoogle } from '~/components/marketing/DitchGoogle'
import { BOOK_A_CALL_URL, DISCORD_URL, isBrowser, LIVE_DEMO_URL } from '~/lib/constants'
import { StateType } from '~/lib/store'
+import { useTheme } from '~/providers/ThemeProvider'
import { getAccessToken } from '~/utils/accessToken'
import routesPath from '~/utils/routes'
interface LoaderProps {
- theme: 'dark' | 'light'
isAuth: boolean
}
const INTEGRATIONS_URL = 'https://docs.swetrix.com/integrations'
const Marketers = () => {
- const { theme: ssrTheme, isAuth } = useLoaderData<LoaderProps>()
+ const { isAuth } = useLoaderData<LoaderProps>()
const { t } = useTranslation('common')
- const reduxTheme = useSelector((state: StateType) => state.ui.theme.theme)
+ const { theme } = useTheme()
const accessToken = getAccessToken()
const { authenticated: reduxAuthenticated, loading } = useSelector((state: StateType) => state.auth)
const authenticated = isBrowser ? (loading ? !!accessToken : reduxAuthenticated) : isAuth
- const theme = isBrowser ? reduxTheme : ssrTheme
return (
<main className='bg-white dark:bg-slate-900'>
@@ -60,7 +59,7 @@ const Marketers = () => {
}}
/>
</div>
- <Header ssrTheme={ssrTheme} authenticated={authenticated} transparent />
+ <Header authenticated={authenticated} transparent />
<div className='relative mx-auto min-h-[740px] pt-10 pb-5 sm:px-3 lg:px-6 lg:pt-24 xl:px-8'>
<div className='relative z-20 flex flex-col content-between justify-center'>
<div className='relative mx-auto flex flex-col px-4 text-left'>
@@ -170,7 +169,6 @@ const Marketers = () => {
dark: '/assets/screenshot_dark.png',
light: '/assets/screenshot_light.png',
}}
- theme={theme}
/>
</main>
)
diff --git a/web/app/pages/Landings/SmallBusinesses.tsx b/web/app/pages/Landings/SmallBusinesses.tsx
index 1846c20b3..1f28614e0 100644
--- a/web/app/pages/Landings/SmallBusinesses.tsx
+++ b/web/app/pages/Landings/SmallBusinesses.tsx
@@ -9,24 +9,23 @@ import { ComparisonTable } from '~/components/marketing/ComparisonTable'
import { DitchGoogle } from '~/components/marketing/DitchGoogle'
import { BOOK_A_CALL_URL, DISCORD_URL, isBrowser, LIVE_DEMO_URL, TWITTER_URL } from '~/lib/constants'
import { StateType } from '~/lib/store'
+import { useTheme } from '~/providers/ThemeProvider'
import { getAccessToken } from '~/utils/accessToken'
import routesPath from '~/utils/routes'
interface LoaderProps {
- theme: 'dark' | 'light'
isAuth: boolean
}
const INTEGRATIONS_URL = 'https://docs.swetrix.com/integrations'
const SmallBusinesses = () => {
- const { theme: ssrTheme, isAuth } = useLoaderData<LoaderProps>()
+ const { isAuth } = useLoaderData<LoaderProps>()
const { t } = useTranslation('common')
- const reduxTheme = useSelector((state: StateType) => state.ui.theme.theme)
+ const { theme } = useTheme()
const accessToken = getAccessToken()
const { authenticated: reduxAuthenticated, loading } = useSelector((state: StateType) => state.auth)
const authenticated = isBrowser ? (loading ? !!accessToken : reduxAuthenticated) : isAuth
- const theme = isBrowser ? reduxTheme : ssrTheme
return (
<main className='bg-white dark:bg-slate-900'>
@@ -60,7 +59,7 @@ const SmallBusinesses = () => {
}}
/>
</div>
- <Header ssrTheme={ssrTheme} authenticated={authenticated} transparent />
+ <Header authenticated={authenticated} transparent />
<div className='relative mx-auto min-h-[740px] pt-10 pb-5 sm:px-3 lg:px-6 lg:pt-24 xl:px-8'>
<div className='relative z-20 flex flex-col content-between justify-center'>
<div className='relative mx-auto flex flex-col px-4 text-left'>
@@ -178,7 +177,6 @@ const SmallBusinesses = () => {
dark: '/assets/screenshot_dark.png',
light: '/assets/screenshot_light.png',
}}
- theme={theme}
/>
</main>
)
diff --git a/web/app/pages/Landings/Startups.tsx b/web/app/pages/Landings/Startups.tsx
index de7f1eaa8..f0f61779c 100644
--- a/web/app/pages/Landings/Startups.tsx
+++ b/web/app/pages/Landings/Startups.tsx
@@ -9,24 +9,23 @@ import { ComparisonTable } from '~/components/marketing/ComparisonTable'
import { DitchGoogle } from '~/components/marketing/DitchGoogle'
import { BOOK_A_CALL_URL, DISCORD_URL, isBrowser, LIVE_DEMO_URL } from '~/lib/constants'
import { StateType } from '~/lib/store'
+import { useTheme } from '~/providers/ThemeProvider'
import { getAccessToken } from '~/utils/accessToken'
import routesPath from '~/utils/routes'
interface LoaderProps {
- theme: 'dark' | 'light'
isAuth: boolean
}
const INTEGRATIONS_URL = 'https://docs.swetrix.com/integrations'
const Startups = () => {
- const { theme: ssrTheme, isAuth } = useLoaderData<LoaderProps>()
+ const { isAuth } = useLoaderData<LoaderProps>()
const { t } = useTranslation('common')
- const reduxTheme = useSelector((state: StateType) => state.ui.theme.theme)
+ const { theme } = useTheme()
const accessToken = getAccessToken()
const { authenticated: reduxAuthenticated, loading } = useSelector((state: StateType) => state.auth)
const authenticated = isBrowser ? (loading ? !!accessToken : reduxAuthenticated) : isAuth
- const theme = isBrowser ? reduxTheme : ssrTheme
return (
<main className='bg-white dark:bg-slate-900'>
@@ -60,7 +59,7 @@ const Startups = () => {
}}
/>
</div>
- <Header ssrTheme={ssrTheme} authenticated={authenticated} transparent />
+ <Header authenticated={authenticated} transparent />
<div className='relative mx-auto min-h-[740px] pt-10 pb-5 sm:px-3 lg:px-6 lg:pt-24 xl:px-8'>
<div className='relative z-20 flex flex-col content-between justify-center'>
<div className='relative mx-auto flex flex-col px-4 text-left'>
@@ -172,7 +171,6 @@ const Startups = () => {
dark: '/assets/screenshot_dark.png',
light: '/assets/screenshot_light.png',
}}
- theme={theme}
/>
</main>
)
diff --git a/web/app/pages/Performance/index.tsx b/web/app/pages/Performance/index.tsx
index 97088a20d..1b8729d57 100644
--- a/web/app/pages/Performance/index.tsx
+++ b/web/app/pages/Performance/index.tsx
@@ -14,6 +14,7 @@ import { DitchGoogle } from '~/components/marketing/DitchGoogle'
import { PERFORMANCE_LIVE_DEMO_URL, isBrowser } from '~/lib/constants'
import { Stats } from '~/lib/models/Stats'
import { StateType } from '~/lib/store/index'
+import { useTheme } from '~/providers/ThemeProvider'
import BackgroundSvg from '~/ui/icons/BackgroundSvg'
import { getAccessToken } from '~/utils/accessToken'
import { nFormatterSeparated } from '~/utils/generic'
@@ -29,7 +30,6 @@ const Lines = () => (
)
interface PerformanceProps {
- ssrTheme: 'dark' | 'light'
ssrAuthenticated: boolean
}
@@ -98,12 +98,11 @@ export const PeopleLoveSwetrix = () => {
)
}
-const Performance = ({ ssrTheme, ssrAuthenticated }: PerformanceProps) => {
+const Performance = ({ ssrAuthenticated }: PerformanceProps) => {
const { t } = useTranslation('common')
- const reduxTheme = useSelector((state: StateType) => state.ui.theme.theme)
+ const { theme } = useTheme()
const { authenticated: reduxAuthenticated, loading } = useSelector((state: StateType) => state.auth)
const [lastBlogPost, setLastBlogPost] = useState<Awaited<ReturnType<typeof getLastPost>> | null>(null)
- const theme = isBrowser ? reduxTheme : ssrTheme
const accessToken = getAccessToken()
const authenticated = isBrowser ? (loading ? !!accessToken : reduxAuthenticated) : ssrAuthenticated
@@ -151,7 +150,7 @@ const Performance = ({ ssrTheme, ssrAuthenticated }: PerformanceProps) => {
}}
/>
</div>
- <Header ssrTheme={ssrTheme} authenticated={authenticated} transparent />
+ <Header authenticated={authenticated} transparent />
<div className='relative mx-auto min-h-[740px] pt-10 pb-5 sm:px-3 lg:px-6 lg:pt-24 xl:px-8'>
<div className='relative z-20 flex flex-row content-between justify-center lg:justify-start 2xl:mr-[14vw] 2xl:justify-center'>
<div className='relative px-4 text-left lg:mt-0 lg:mr-14'>
@@ -305,16 +304,15 @@ const Performance = ({ ssrTheme, ssrAuthenticated }: PerformanceProps) => {
dark: '/assets/screenshot_perf_dark.png',
light: '/assets/screenshot_perf_light.png',
}}
- theme={theme}
/>
{/* Become a developer */}
<section className='relative bg-white pt-20 pb-44 dark:bg-slate-900'>
<div className='absolute top-16 right-0 z-0'>
- <BackgroundSvg theme={theme} type='threecircle' />
+ <BackgroundSvg type='threecircle' />
</div>
<div className='absolute top-52 -left-9 rotate-90'>
- <BackgroundSvg theme={theme} type='shapes' />
+ <BackgroundSvg type='shapes' />
</div>
<PeopleLoveSwetrix />
</section>
diff --git a/web/app/pages/Project/ProjectProtectedPassword/index.tsx b/web/app/pages/Project/ProjectProtectedPassword/index.tsx
index 9c17a1981..8583c1339 100644
--- a/web/app/pages/Project/ProjectProtectedPassword/index.tsx
+++ b/web/app/pages/Project/ProjectProtectedPassword/index.tsx
@@ -10,6 +10,7 @@ import { checkPassword } from '~/api'
import Footer from '~/components/Footer'
import Header from '~/components/Header'
import { useRequiredParams } from '~/hooks/useRequiredParams'
+import { useTheme } from '~/providers/ThemeProvider'
import Button from '~/ui/Button'
import Input from '~/ui/Input'
import routes from '~/utils/routes'
@@ -23,12 +24,12 @@ interface ProjectProtectedPasswordForm {
const MAX_PASSWORD_LENGTH = 80
interface ProjectProtectedPasswordProps {
- ssrTheme: 'light' | 'dark'
embedded: boolean
isAuth: boolean
}
-const ProjectProtectedPassword = ({ ssrTheme, embedded, isAuth }: ProjectProtectedPasswordProps) => {
+const ProjectProtectedPassword = ({ embedded, isAuth }: ProjectProtectedPasswordProps) => {
+ const { theme } = useTheme()
const { t } = useTranslation('common')
const [form, setForm] = useState<ProjectProtectedPasswordForm>({
password: '',
@@ -74,7 +75,7 @@ const ProjectProtectedPassword = ({ ssrTheme, embedded, isAuth }: ProjectProtect
setProjectPassword(id, data.password)
navigate({
pathname: _replace(routes.project, ':id', id),
- search: `?embedded=${embedded}&theme=${ssrTheme}`,
+ search: `?embedded=${embedded}&theme=${theme}`,
})
return
}
@@ -110,7 +111,7 @@ const ProjectProtectedPassword = ({ ssrTheme, embedded, isAuth }: ProjectProtect
return (
<>
- {!embedded ? <Header ssrTheme={ssrTheme} authenticated={isAuth} /> : null}
+ {!embedded ? <Header authenticated={isAuth} /> : null}
<div className='min-h-page flex flex-col bg-gray-50 px-4 py-6 sm:px-6 lg:px-8 dark:bg-slate-900'>
<form className='mx-auto w-full max-w-7xl' onSubmit={handleSubmit}>
<h2 className='mt-2 text-3xl font-bold text-gray-900 dark:text-gray-50'>{t('titles.passwordProtected')}</h2>
diff --git a/web/app/pages/Project/View/ViewProject.tsx b/web/app/pages/Project/View/ViewProject.tsx
index f71a0f700..f56cc215f 100644
--- a/web/app/pages/Project/View/ViewProject.tsx
+++ b/web/app/pages/Project/View/ViewProject.tsx
@@ -112,13 +112,13 @@ import {
ERROR_PANELS_ORDER,
ERROR_PERIOD_PAIRS,
FUNNELS_PERIOD_PAIRS,
- ThemeType,
} from '~/lib/constants'
import { CountryEntry } from '~/lib/models/Entry'
import { Funnel, AnalyticsFunnel, OverallObject, OverallPerformanceObject } from '~/lib/models/Project'
import { StateType } from '~/lib/store'
import NewFunnel from '~/modals/NewFunnel'
import ViewProjectHotkeys from '~/modals/ViewProjectHotkeys'
+import { useTheme } from '~/providers/ThemeProvider'
import Checkbox from '~/ui/Checkbox'
import Dropdown from '~/ui/Dropdown'
import FlatPicker from '~/ui/Flatpicker'
@@ -132,8 +132,8 @@ import { getTimeFromSeconds, getStringFromTime, getLocaleDisplayName, nLocaleFor
import { getItem, setItem } from '~/utils/localstorage'
import routes from '~/utils/routes'
-import ProjectAlertsView from '../Alerts/View'
import { useCurrentProject, useProjectPassword } from '../../../providers/CurrentProjectProvider'
+import ProjectAlertsView from '../Alerts/View'
import AddAViewModal from './components/AddAViewModal'
import BrowserDropdown from './components/BrowserDropdown'
@@ -253,12 +253,10 @@ const ViewProject = () => {
const projectPassword = useProjectPassword(id)
const {
- theme: ssrTheme,
embedded,
isAuth: ssrAuthenticated,
tabs: projectQueryTabs,
} = useLoaderData<{
- theme: ThemeType
embedded: boolean
isAuth: boolean
tabs: string[]
@@ -266,7 +264,7 @@ const ViewProject = () => {
const { loading: authLoading, authenticated: csrAuthenticated, user } = useSelector((state: StateType) => state.auth)
- const { theme } = useSelector((state: StateType) => state.ui.theme)
+ const { theme } = useTheme()
const { extensions } = useSelector((state: StateType) => state.auth)
@@ -278,8 +276,6 @@ const ViewProject = () => {
i18n: { language },
} = useTranslation('common')
- const _theme = isBrowser ? theme : ssrTheme
-
const [periodPairs, setPeriodPairs] = useState<TBPeriodPairsProps[]>(tbPeriodPairs(t, undefined, undefined, language))
const [customExportTypes, setCustomExportTypes] = useState<any[]>([])
@@ -2812,7 +2808,7 @@ const ViewProject = () => {
if (authLoading || !project) {
return (
<>
- {!embedded ? <Header ssrTheme={ssrTheme} authenticated={authenticated} /> : null}
+ {!embedded ? <Header authenticated={authenticated} /> : null}
<div
className={cx('min-h-min-footer bg-gray-50 dark:bg-slate-900', {
'min-h-min-footer': !embedded,
@@ -2829,7 +2825,7 @@ const ViewProject = () => {
if (project.isLocked) {
return (
<>
- {!embedded ? <Header ssrTheme={ssrTheme} authenticated={authenticated} /> : null}
+ {!embedded ? <Header authenticated={authenticated} /> : null}
<div
className={cx('mx-auto w-full max-w-[1584px] bg-gray-50 px-2 py-6 sm:px-4 lg:px-8 dark:bg-slate-900', {
'min-h-min-footer': !embedded,
@@ -2850,7 +2846,7 @@ const ViewProject = () => {
if (!project.isDataExists && activeTab !== PROJECT_TABS.errors && !analyticsLoading) {
return (
<>
- {!embedded ? <Header ssrTheme={ssrTheme} authenticated={authenticated} /> : null}
+ {!embedded ? <Header authenticated={authenticated} /> : null}
<div
className={cx('mx-auto w-full max-w-[1584px] bg-gray-50 px-2 py-6 sm:px-4 lg:px-8 dark:bg-slate-900', {
'min-h-min-footer': !embedded,
@@ -2875,7 +2871,7 @@ const ViewProject = () => {
) {
return (
<>
- {!embedded ? <Header ssrTheme={ssrTheme} authenticated={authenticated} /> : null}
+ {!embedded ? <Header authenticated={authenticated} /> : null}
<div
className={cx('mx-auto w-full max-w-[1584px] bg-gray-50 px-2 py-6 sm:px-4 lg:px-8 dark:bg-slate-900', {
'min-h-min-footer': !embedded,
@@ -2935,7 +2931,7 @@ const ViewProject = () => {
}}
>
<>
- {!embedded ? <Header ssrTheme={ssrTheme} authenticated={authenticated} /> : null}
+ {!embedded ? <Header authenticated={authenticated} /> : null}
<EventsRunningOutBanner />
<div
ref={ref}
@@ -3821,7 +3817,7 @@ const ViewProject = () => {
// @ts-expect-error
const logoPathDark = OS_LOGO_MAP_DARK[logoKey]
- let logoPath = _theme === 'dark' ? logoPathDark : logoPathLight
+ let logoPath = theme === 'dark' ? logoPathDark : logoPathLight
logoPath ||= logoPathLight
if (!logoPath) {
@@ -4126,7 +4122,7 @@ const ViewProject = () => {
// @ts-expect-error
const logoPathDark = OS_LOGO_MAP_DARK[logoKey]
- let logoPath = _theme === 'dark' ? logoPathDark : logoPathLight
+ let logoPath = theme === 'dark' ? logoPathDark : logoPathLight
logoPath ||= logoPathLight
if (!logoPath) {
diff --git a/web/app/pages/ReferralPage/index.tsx b/web/app/pages/ReferralPage/index.tsx
index 3bd17a28d..be92c5c3a 100644
--- a/web/app/pages/ReferralPage/index.tsx
+++ b/web/app/pages/ReferralPage/index.tsx
@@ -1,22 +1,16 @@
import { ArrowRightIcon } from '@heroicons/react/20/solid'
import { useTranslation, Trans } from 'react-i18next'
-import { useSelector } from 'react-redux'
import { Link, useParams } from 'react-router'
import Header from '~/components/Header'
import { Lines } from '~/components/marketing/Lines'
-import { isBrowser, REFERRAL_COOKIE_DAYS, REFERRAL_DISCOUNT } from '~/lib/constants'
-import { StateType } from '~/lib/store/index'
+import { REFERRAL_COOKIE_DAYS, REFERRAL_DISCOUNT } from '~/lib/constants'
+import { useTheme } from '~/providers/ThemeProvider'
import routes from '~/utils/routes'
-interface ReferralPageProps {
- ssrTheme: 'dark' | 'light'
-}
-
-const ReferralPage = ({ ssrTheme }: ReferralPageProps) => {
+const ReferralPage = () => {
const { t } = useTranslation('common')
- const reduxTheme = useSelector((state: StateType) => state.ui.theme.theme)
- const theme = isBrowser ? reduxTheme : ssrTheme
+ const { theme } = useTheme()
// Referral code
const { id } = useParams()
@@ -54,7 +48,7 @@ const ReferralPage = ({ ssrTheme }: ReferralPageProps) => {
}}
/>
</div>
- <Header ssrTheme={ssrTheme} authenticated={false} refPage transparent />
+ <Header authenticated={false} refPage transparent />
<div className='relative mx-auto min-h-[740px] pt-10 pb-5 sm:px-3 lg:px-6 lg:pt-24 xl:px-8'>
<div className='relative z-20 flex flex-row content-between justify-center lg:justify-start 2xl:mr-[14vw] 2xl:justify-center'>
<div className='relative px-4 text-left lg:mt-0 lg:mr-14'>
diff --git a/web/app/pages/UserSettings/components/Socialisations.tsx b/web/app/pages/UserSettings/components/Socialisations.tsx
index fe1d6d15d..3b02ca9e5 100644
--- a/web/app/pages/UserSettings/components/Socialisations.tsx
+++ b/web/app/pages/UserSettings/components/Socialisations.tsx
@@ -10,6 +10,7 @@ import { SSO_PROVIDERS } from '~/lib/constants'
import { User } from '~/lib/models/User'
import { authActions } from '~/lib/reducers/auth'
import { StateType, useAppDispatch } from '~/lib/store'
+import { useTheme } from '~/providers/ThemeProvider'
import Button from '~/ui/Button'
import GithubDark from '~/ui/icons/GithubDark'
import GithubLight from '~/ui/icons/GithubLight'
@@ -56,7 +57,7 @@ const HASH_CHECK_FREQUENCY = 1000 // 1 second
const Socialisations = () => {
const { user } = useSelector((state: StateType) => state.auth)
- const { theme } = useSelector((state: StateType) => state.ui.theme)
+ const { theme } = useTheme()
const dispatch = useAppDispatch()
const { t } = useTranslation('common')
const [isLoading, setIsLoading] = useState(false)
diff --git a/web/app/providers/CurrentProjectProvider.tsx b/web/app/providers/CurrentProjectProvider.tsx
index d8ddd41eb..68aa35689 100644
--- a/web/app/providers/CurrentProjectProvider.tsx
+++ b/web/app/providers/CurrentProjectProvider.tsx
@@ -2,11 +2,11 @@ import _replace from 'lodash/replace'
import { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useSelector } from 'react-redux'
-import { useLoaderData, useNavigate, useSearchParams } from 'react-router'
+import { useNavigate, useSearchParams } from 'react-router'
import { toast } from 'sonner'
import { checkPassword, getProject } from '~/api'
-import { LS_PROJECTS_PROTECTED_KEY, ThemeType } from '~/lib/constants'
+import { LS_PROJECTS_PROTECTED_KEY } from '~/lib/constants'
import { type Project } from '~/lib/models/Project'
import { type StateType } from '~/lib/store'
import { getItem, removeItem } from '~/utils/localstorage'
@@ -14,6 +14,7 @@ import routes from '~/utils/routes'
import { getProjectPreferences, setProjectPreferences } from '../pages/Project/View/utils/cache'
import { CHART_METRICS_MAPPING } from '../pages/Project/View/ViewProject.helpers'
+import { useTheme } from './ThemeProvider'
interface CurrentProjectContextType {
id: string
@@ -47,6 +48,7 @@ const useIsEmbedded = () => {
}
const useProject = (id: string) => {
+ const { theme } = useTheme()
const { t } = useTranslation('common')
const navigate = useNavigate()
const { loading: authLoading } = useSelector((state: StateType) => state.auth)
@@ -54,17 +56,13 @@ const useProject = (id: string) => {
const isEmbedded = useIsEmbedded()
const [project, setProject] = useState<Project | null>(null)
- const { theme: ssrTheme } = useLoaderData<{
- theme: ThemeType
- }>()
-
const onErrorLoading = useCallback(() => {
if (projectPassword) {
checkPassword(id, projectPassword).then((res) => {
if (res) {
navigate({
pathname: _replace(routes.project, ':id', id),
- search: `?theme=${ssrTheme}&embedded=${isEmbedded}`,
+ search: `?theme=${theme}&embedded=${isEmbedded}`,
})
return
}
@@ -72,7 +70,7 @@ const useProject = (id: string) => {
toast.error(t('apiNotifications.incorrectPassword'))
navigate({
pathname: _replace(routes.project_protected_password, ':id', id),
- search: `?theme=${ssrTheme}&embedded=${isEmbedded}`,
+ search: `?theme=${theme}&embedded=${isEmbedded}`,
})
removeItem(LS_PROJECTS_PROTECTED_KEY)
})
@@ -81,7 +79,7 @@ const useProject = (id: string) => {
toast.error(t('project.noExist'))
navigate(routes.dashboard)
- }, [id, projectPassword, navigate, t, isEmbedded, ssrTheme])
+ }, [id, projectPassword, navigate, t, isEmbedded, theme])
useEffect(() => {
if (authLoading || project) {
@@ -97,7 +95,7 @@ const useProject = (id: string) => {
if (result.isPasswordProtected && !result.role && projectPassword) {
navigate({
pathname: _replace(routes.project_protected_password, ':id', id),
- search: `?theme=${ssrTheme}&embedded=${isEmbedded}`,
+ search: `?theme=${theme}&embedded=${isEmbedded}`,
})
return
}
@@ -108,7 +106,7 @@ const useProject = (id: string) => {
console.error('[ERROR] (getProject)', reason)
onErrorLoading()
})
- }, [authLoading, project, id, projectPassword, navigate, onErrorLoading, isEmbedded, ssrTheme])
+ }, [authLoading, project, id, projectPassword, navigate, onErrorLoading, isEmbedded, theme])
return project
}
diff --git a/web/app/providers/ThemeProvider.tsx b/web/app/providers/ThemeProvider.tsx
new file mode 100644
index 000000000..83febb2a1
--- /dev/null
+++ b/web/app/providers/ThemeProvider.tsx
@@ -0,0 +1,37 @@
+import { createContext, useCallback, useContext, useState } from 'react'
+
+import { LS_THEME_SETTING, ThemeType } from '~/lib/constants'
+import { setCookie } from '~/utils/cookie'
+
+interface ThemeContextType {
+ theme: ThemeType
+ setTheme: (theme: ThemeType) => void
+}
+
+const ThemeContext = createContext<ThemeContextType | undefined>(undefined)
+
+interface ThemeProviderProps {
+ children: React.ReactNode
+ initialTheme: ThemeType
+}
+
+export const ThemeProvider = ({ children, initialTheme }: ThemeProviderProps) => {
+ const [theme, setTheme] = useState(initialTheme)
+
+ const _setTheme = useCallback((theme: ThemeType) => {
+ setTheme(theme)
+ setCookie(LS_THEME_SETTING, theme, 3600 * 24 * 90)
+ }, [])
+
+ return <ThemeContext.Provider value={{ theme, setTheme: _setTheme }}>{children}</ThemeContext.Provider>
+}
+
+export const useTheme = () => {
+ const context = useContext(ThemeContext)
+
+ if (context === undefined) {
+ throw new Error('useTheme must be used within a ThemeProvider')
+ }
+
+ return context
+}
diff --git a/web/app/root.tsx b/web/app/root.tsx
index 6bfb296a9..2fd2f54b0 100644
--- a/web/app/root.tsx
+++ b/web/app/root.tsx
@@ -9,7 +9,6 @@ import { useTranslation } from 'react-i18next'
import { Provider } from 'react-redux'
import type { LinksFunction, LoaderFunctionArgs, HeadersFunction } from 'react-router'
import {
- data,
redirect,
Links,
Meta,
@@ -32,11 +31,12 @@ import mainCss from '~/styles/index.css?url'
import sonnerCss from '~/styles/sonner.css?url'
import tailwindCss from '~/styles/tailwind.css?url'
import { trackViews, trackErrors } from '~/utils/analytics'
-import { getCookie, generateCookieString } from '~/utils/cookie'
+import { getCookie } from '~/utils/cookie'
import { detectTheme, isAuthenticated, isWWW } from '~/utils/server'
import AppWrapper from './App'
import { detectLanguage } from './i18n'
+import { ThemeProvider, useTheme } from './providers/ThemeProvider'
trackViews()
trackErrors()
@@ -174,7 +174,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
const locale = detectLanguage(request)
- const [theme, storeThemeToCookie] = detectTheme(request)
+ const theme = detectTheme(request)
const isAuthed = isAuthenticated(request)
const REMIX_ENV = {
@@ -188,22 +188,29 @@ export async function loader({ request }: LoaderFunctionArgs) {
PADDLE_CLIENT_SIDE_TOKEN: process.env.PADDLE_CLIENT_SIDE_TOKEN,
}
- const init = storeThemeToCookie
- ? {
- headers: {
- // 21600 seconds = 6 hours
- 'Set-Cookie': generateCookieString(LS_THEME_SETTING, theme, 21600),
- },
- }
- : undefined
-
- return data({ locale, url, theme, REMIX_ENV, isAuthed, pathname: urlObject.pathname }, init)
+ return { locale, url, theme, REMIX_ENV, isAuthed, pathname: urlObject.pathname }
}
export const handle = { i18n: 'common' }
+const Body = () => {
+ const { isAuthed } = useLoaderData<typeof loader>()
+ const { theme } = useTheme()
+
+ return (
+ <body className={cx(theme, { 'bg-white': theme === 'light', 'bg-slate-900': theme === 'dark' })}>
+ <Provider store={store}>
+ <AppWrapper ssrAuthenticated={isAuthed} />
+ </Provider>
+ <ScrollRestoration />
+ <ExternalScripts />
+ <Scripts />
+ </body>
+ )
+}
+
export default function App() {
- const { locale, url, theme, REMIX_ENV, isAuthed } = useLoaderData<any>()
+ const { locale, url, theme, REMIX_ENV } = useLoaderData<typeof loader>()
const { i18n } = useTranslation('common')
const urlObject = new URL(url)
@@ -212,14 +219,12 @@ export default function App() {
useChangeLanguage(locale)
return (
- <html className={cx('font-sans antialiased', theme)} lang={locale} dir={i18n.dir()}>
+ <html className='font-sans antialiased' lang={locale} dir={i18n.dir()}>
<head>
<meta charSet='utf-8' />
<SEO />
<meta name='google' content='notranslate' />
<link rel='icon' type='image/x-icon' href='/favicon.ico' />
- {/* <meta name='apple-mobile-web-app-title' content='Swetrix' /> */}
- {/* <meta name='application-name' content='Swetrix' /> */}
<Meta />
<meta name='viewport' content='width=device-width,initial-scale=1' />
<Links />
@@ -235,14 +240,9 @@ export default function App() {
/>
<script dangerouslySetInnerHTML={{ __html: `window.REMIX_ENV = ${JSON.stringify(REMIX_ENV)}` }} />
</head>
- <body className={cx({ 'bg-white': theme === 'light', 'bg-slate-900': theme === 'dark' })}>
- <Provider store={store}>
- <AppWrapper ssrTheme={theme} ssrAuthenticated={isAuthed} />
- </Provider>
- <ScrollRestoration />
- <ExternalScripts />
- <Scripts />
- </body>
+ <ThemeProvider initialTheme={theme}>
+ <Body />
+ </ThemeProvider>
</html>
)
}
diff --git a/web/app/routes/_index.tsx b/web/app/routes/_index.tsx
index 8fa9946c3..4beb0e6d9 100644
--- a/web/app/routes/_index.tsx
+++ b/web/app/routes/_index.tsx
@@ -37,10 +37,11 @@ import { Stats } from '~/lib/models/Stats'
import { StateType } from '~/lib/store/index'
import CCRow from '~/pages/Project/View/components/CCRow'
import { MetricCard, MetricCardSelect } from '~/pages/Project/View/components/MetricCards'
+import { useTheme } from '~/providers/ThemeProvider'
import { getAccessToken } from '~/utils/accessToken'
import { getStringFromTime, getTimeFromSeconds } from '~/utils/generic'
import routesPath from '~/utils/routes'
-import { detectTheme, isAuthenticated } from '~/utils/server'
+import { isAuthenticated } from '~/utils/server'
export const sitemap: SitemapFunction = () => ({
priority: 1,
@@ -52,7 +53,6 @@ export async function loader({ request }: LoaderFunctionArgs) {
return redirect('/login', 302)
}
- const [theme] = detectTheme(request)
const isAuth = isAuthenticated(request)
const userAgent = request.headers.get('user-agent')
@@ -74,7 +74,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
}
- return { theme, isAuth, deviceInfo }
+ return { isAuth, deviceInfo }
}
const Problem = () => {
@@ -200,7 +200,8 @@ const FeedbackHighlight = ({ children }: FeedbackHighlightProps) => (
<span className='bg-yellow-100/80 dark:bg-yellow-400/40'>{children}</span>
)
-const WeAreOpensource = ({ theme }: { theme: 'dark' | 'light' }) => {
+const WeAreOpensource = () => {
+ const { theme } = useTheme()
const { t } = useTranslation('common')
return (
@@ -406,7 +407,8 @@ const SdurMetric = () => {
)
}
-const FeatureBlocks = ({ theme }: { theme: 'dark' | 'light' }) => {
+const FeatureBlocks = () => {
+ const { theme } = useTheme()
const {
t,
i18n: { language },
@@ -668,7 +670,8 @@ const FeatureBlocks = ({ theme }: { theme: 'dark' | 'light' }) => {
)
}
-const CoreFeatures = ({ theme }: { theme: 'dark' | 'light' }) => {
+const CoreFeatures = () => {
+ const { theme } = useTheme()
const { t } = useTranslation('common')
return (
@@ -794,15 +797,8 @@ const CoreFeatures = ({ theme }: { theme: 'dark' | 'light' }) => {
)
}
-const Hero = ({
- theme,
- ssrTheme,
- authenticated,
-}: {
- theme: 'dark' | 'light'
- ssrTheme: 'dark' | 'light'
- authenticated: boolean
-}) => {
+const Hero = ({ authenticated }: { authenticated: boolean }) => {
+ const { theme } = useTheme()
const { t } = useTranslation('common')
return (
@@ -836,7 +832,7 @@ const Hero = ({
}}
/>
</div>
- <Header ssrTheme={ssrTheme} authenticated={authenticated} transparent />
+ <Header authenticated={authenticated} transparent />
<div className='relative mx-auto min-h-[740px] pt-10 pb-5 sm:px-3 lg:px-6 lg:pt-24 xl:px-8'>
<div className='relative z-20 flex flex-col content-between justify-center'>
<div className='relative mx-auto flex flex-col px-4 text-left'>
@@ -899,22 +895,21 @@ const Hero = ({
}
export default function Index() {
- const { theme: ssrTheme, isAuth } = useLoaderData<typeof loader>()
+ const { isAuth } = useLoaderData<typeof loader>()
- const reduxTheme = useSelector((state: StateType) => state.ui.theme.theme)
+ const { theme } = useTheme()
const { authenticated: reduxAuthenticated, loading } = useSelector((state: StateType) => state.auth)
- const theme = isBrowser ? reduxTheme : ssrTheme
const accessToken = getAccessToken()
const authenticated = isBrowser ? (loading ? !!accessToken : reduxAuthenticated) : isAuth
return (
<div className='overflow-hidden'>
<main className='bg-white dark:bg-slate-900'>
- <Hero theme={theme} ssrTheme={ssrTheme} authenticated={authenticated} />
+ <Hero authenticated={authenticated} />
<Problem />
- <FeatureBlocks theme={theme} />
+ <FeatureBlocks />
<Feedback
name='Alex Bowles'
@@ -930,7 +925,7 @@ export default function Index() {
}
/>
- <CoreFeatures theme={theme} />
+ <CoreFeatures />
{/* Hiding the Pricing for authenticated users on the main page as the Paddle script only loads on the Billing page */}
{!authenticated ? <Pricing authenticated={false} /> : null}
@@ -949,14 +944,13 @@ export default function Index() {
}
/>
- <WeAreOpensource theme={theme} />
+ <WeAreOpensource />
<DitchGoogle
screenshot={{
dark: '/assets/screenshot_dark.png',
light: '/assets/screenshot_light.png',
}}
- theme={theme}
/>
</main>
</div>
diff --git a/web/app/routes/billing.tsx b/web/app/routes/billing.tsx
index b43e04eaf..aea4fb345 100644
--- a/web/app/routes/billing.tsx
+++ b/web/app/routes/billing.tsx
@@ -4,7 +4,7 @@ import type { SitemapFunction } from 'remix-sitemap'
import { isSelfhosted } from '~/lib/constants'
import Billing from '~/pages/Billing'
-import { isAuthenticated, detectTheme } from '~/utils/server'
+import { isAuthenticated } from '~/utils/server'
export const sitemap: SitemapFunction = () => ({
exclude: true,
@@ -15,14 +15,13 @@ export async function loader({ request }: LoaderFunctionArgs) {
return redirect('/login', 302)
}
- const [theme] = detectTheme(request)
const isAuth = isAuthenticated(request)
- return data({ isAuth, theme })
+ return data({ isAuth })
}
export default function Index() {
- const { isAuth, theme } = useLoaderData<any>()
+ const { isAuth } = useLoaderData<any>()
- return <Billing ssrAuthenticated={isAuth} ssrTheme={theme} />
+ return <Billing ssrAuthenticated={isAuth} />
}
diff --git a/web/app/routes/captchas.$id.tsx b/web/app/routes/captchas.$id.tsx
index 508475862..1699b2855 100644
--- a/web/app/routes/captchas.$id.tsx
+++ b/web/app/routes/captchas.$id.tsx
@@ -1,29 +1,18 @@
-import type { LinksFunction, LoaderFunctionArgs } from 'react-router'
-import { useLoaderData } from 'react-router'
+import type { LinksFunction } from 'react-router'
import { useRequiredParams } from '~/hooks/useRequiredParams'
import ViewCaptcha from '~/pages/Captcha/View'
import { CurrentProjectProvider } from '~/providers/CurrentProjectProvider'
import ProjectViewStyle from '~/styles/ProjectViewStyle.css?url'
-import { detectTheme } from '~/utils/server'
export const links: LinksFunction = () => [{ rel: 'stylesheet', href: ProjectViewStyle }]
-export async function loader({ request }: LoaderFunctionArgs) {
- const [theme] = detectTheme(request)
-
- return {
- theme,
- }
-}
-
export default function Index() {
- const { theme } = useLoaderData<typeof loader>()
const { id } = useRequiredParams<{ id: string }>()
return (
<CurrentProjectProvider id={id}>
- <ViewCaptcha ssrTheme={theme} />
+ <ViewCaptcha />
</CurrentProjectProvider>
)
}
diff --git a/web/app/routes/error-tracking.tsx b/web/app/routes/error-tracking.tsx
index 0e7da8b01..5bd94718b 100644
--- a/web/app/routes/error-tracking.tsx
+++ b/web/app/routes/error-tracking.tsx
@@ -4,7 +4,7 @@ import type { SitemapFunction } from 'remix-sitemap'
import { isDisableMarketingPages, isSelfhosted } from '~/lib/constants'
import ErrorTracking from '~/pages/ErrorTracking'
-import { detectTheme, isAuthenticated } from '~/utils/server'
+import { isAuthenticated } from '~/utils/server'
export const sitemap: SitemapFunction = () => ({
priority: 1,
@@ -16,14 +16,13 @@ export async function loader({ request }: LoaderFunctionArgs) {
return redirect('/login', 302)
}
- const [theme] = detectTheme(request)
const isAuth = isAuthenticated(request)
- return { theme, isAuth }
+ return { isAuth }
}
export default function Index() {
- const { theme, isAuth } = useLoaderData<typeof loader>()
+ const { isAuth } = useLoaderData<typeof loader>()
- return <ErrorTracking ssrTheme={theme} ssrAuthenticated={isAuth} />
+ return <ErrorTracking ssrAuthenticated={isAuth} />
}
diff --git a/web/app/routes/for-marketers.tsx b/web/app/routes/for-marketers.tsx
index 02230789b..d04bd21a2 100644
--- a/web/app/routes/for-marketers.tsx
+++ b/web/app/routes/for-marketers.tsx
@@ -4,7 +4,7 @@ import type { SitemapFunction } from 'remix-sitemap'
import { isDisableMarketingPages, isSelfhosted } from '~/lib/constants'
import Marketers from '~/pages/Landings/Marketers'
-import { detectTheme, isAuthenticated } from '~/utils/server'
+import { isAuthenticated } from '~/utils/server'
export const sitemap: SitemapFunction = () => ({
priority: 0.9,
@@ -17,9 +17,8 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
const isAuth = isAuthenticated(request)
- const [theme] = detectTheme(request)
- return { theme, isAuth }
+ return { isAuth }
}
export default function Index() {
diff --git a/web/app/routes/for-small-businesses.tsx b/web/app/routes/for-small-businesses.tsx
index 3c8b561e7..bdd36fd95 100644
--- a/web/app/routes/for-small-businesses.tsx
+++ b/web/app/routes/for-small-businesses.tsx
@@ -4,7 +4,7 @@ import type { SitemapFunction } from 'remix-sitemap'
import { isDisableMarketingPages, isSelfhosted } from '~/lib/constants'
import SmallBusinesses from '~/pages/Landings/SmallBusinesses'
-import { detectTheme, isAuthenticated } from '~/utils/server'
+import { isAuthenticated } from '~/utils/server'
export const sitemap: SitemapFunction = () => ({
priority: 0.9,
@@ -17,9 +17,8 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
const isAuth = isAuthenticated(request)
- const [theme] = detectTheme(request)
- return { theme, isAuth }
+ return { isAuth }
}
export default function Index() {
diff --git a/web/app/routes/for-startups.tsx b/web/app/routes/for-startups.tsx
index 7d1ff6d9b..5e9b9d047 100644
--- a/web/app/routes/for-startups.tsx
+++ b/web/app/routes/for-startups.tsx
@@ -4,7 +4,7 @@ import type { SitemapFunction } from 'remix-sitemap'
import { isDisableMarketingPages, isSelfhosted } from '~/lib/constants'
import Startups from '~/pages/Landings/Startups'
-import { detectTheme, isAuthenticated } from '~/utils/server'
+import { isAuthenticated } from '~/utils/server'
export const sitemap: SitemapFunction = () => ({
priority: 0.9,
@@ -17,9 +17,8 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
const isAuth = isAuthenticated(request)
- const [theme] = detectTheme(request)
- return { theme, isAuth }
+ return { isAuth }
}
export default function Index() {
diff --git a/web/app/routes/login.tsx b/web/app/routes/login.tsx
index e17362c59..b8d6dfb72 100644
--- a/web/app/routes/login.tsx
+++ b/web/app/routes/login.tsx
@@ -1,22 +1,12 @@
-import type { HeadersFunction, LoaderFunctionArgs } from 'react-router'
-import { useLoaderData } from 'react-router'
+import type { HeadersFunction } from 'react-router'
import Signin from '~/pages/Auth/Signin'
-import { detectTheme } from '~/utils/server'
export const headers: HeadersFunction = ({ parentHeaders }) => {
parentHeaders.set('X-Frame-Options', 'DENY')
return parentHeaders
}
-export async function loader({ request }: LoaderFunctionArgs) {
- const [theme] = detectTheme(request)
-
- return { theme }
-}
-
-export default function Index() {
- const { theme } = useLoaderData<typeof loader>()
-
- return <Signin ssrTheme={theme} />
+export default function SigninRoute() {
+ return <Signin />
}
diff --git a/web/app/routes/performance.tsx b/web/app/routes/performance.tsx
index a643cbdb2..7cbc12447 100644
--- a/web/app/routes/performance.tsx
+++ b/web/app/routes/performance.tsx
@@ -4,7 +4,7 @@ import type { SitemapFunction } from 'remix-sitemap'
import { isDisableMarketingPages, isSelfhosted } from '~/lib/constants'
import Performance from '~/pages/Performance'
-import { detectTheme, isAuthenticated } from '~/utils/server'
+import { isAuthenticated } from '~/utils/server'
export const sitemap: SitemapFunction = () => ({
priority: 1,
@@ -16,14 +16,13 @@ export async function loader({ request }: LoaderFunctionArgs) {
return redirect('/login', 302)
}
- const [theme] = detectTheme(request)
const isAuth = isAuthenticated(request)
- return { theme, isAuth }
+ return { isAuth }
}
-export default function Index() {
- const { theme, isAuth } = useLoaderData<typeof loader>()
+export default function PerformanceRoute() {
+ const { isAuth } = useLoaderData<typeof loader>()
- return <Performance ssrTheme={theme} ssrAuthenticated={isAuth} />
+ return <Performance ssrAuthenticated={isAuth} />
}
diff --git a/web/app/routes/projects.$id.password.tsx b/web/app/routes/projects.$id.password.tsx
index 1da04e83e..85491c35f 100644
--- a/web/app/routes/projects.$id.password.tsx
+++ b/web/app/routes/projects.$id.password.tsx
@@ -2,22 +2,20 @@ import type { LoaderFunctionArgs } from 'react-router'
import { useLoaderData } from 'react-router'
import ProjectProtectedPassword from '~/pages/Project/ProjectProtectedPassword'
-import { detectTheme, isEmbedded, isAuthenticated } from '~/utils/server'
+import { isEmbedded, isAuthenticated } from '~/utils/server'
export async function loader({ request }: LoaderFunctionArgs) {
const embedded = isEmbedded(request)
- const [theme] = detectTheme(request)
const isAuth = isAuthenticated(request)
return {
- theme,
embedded,
isAuth,
}
}
-export default function Index() {
- const { theme, embedded, isAuth } = useLoaderData<typeof loader>()
+export default function ProjectProtectedPasswordRoute() {
+ const { embedded, isAuth } = useLoaderData<typeof loader>()
- return <ProjectProtectedPassword ssrTheme={theme} embedded={embedded} isAuth={isAuth} />
+ return <ProjectProtectedPassword embedded={embedded} isAuth={isAuth} />
}
diff --git a/web/app/routes/projects.$id.tsx b/web/app/routes/projects.$id.tsx
index fbb8e505d..1a9007646 100644
--- a/web/app/routes/projects.$id.tsx
+++ b/web/app/routes/projects.$id.tsx
@@ -3,10 +3,10 @@ import { type LinksFunction, type LoaderFunctionArgs, type MetaFunction } from '
import { useRequiredParams } from '~/hooks/useRequiredParams'
import { API_URL } from '~/lib/constants'
-import { CurrentProjectProvider } from '~/providers/CurrentProjectProvider'
import ViewProject from '~/pages/Project/View'
+import { CurrentProjectProvider } from '~/providers/CurrentProjectProvider'
import ProjectViewStyle from '~/styles/ProjectViewStyle.css?url'
-import { detectTheme, isEmbedded, isAuthenticated, getProjectTabs } from '~/utils/server'
+import { isEmbedded, isAuthenticated, getProjectTabs } from '~/utils/server'
export const links: LinksFunction = () => [{ rel: 'stylesheet', href: ProjectViewStyle }]
@@ -23,12 +23,10 @@ export const meta: MetaFunction = ({ location }) => {
export async function loader({ request }: LoaderFunctionArgs) {
const embedded = isEmbedded(request)
- const [theme] = detectTheme(request)
const isAuth = isAuthenticated(request)
const tabs = getProjectTabs(request)
return {
- theme,
embedded,
isAuth,
tabs,
diff --git a/web/app/routes/ref.$id.tsx b/web/app/routes/ref.$id.tsx
index 5d8616254..572f2bf75 100644
--- a/web/app/routes/ref.$id.tsx
+++ b/web/app/routes/ref.$id.tsx
@@ -1,22 +1,16 @@
-import type { LoaderFunctionArgs } from 'react-router'
-import { useLoaderData, redirect } from 'react-router'
+import { redirect } from 'react-router'
import { isSelfhosted } from '~/lib/constants'
import ReferralPage from '~/pages/ReferralPage'
-import { detectTheme } from '~/utils/server'
-export async function loader({ request }: LoaderFunctionArgs) {
+export async function loader() {
if (isSelfhosted) {
return redirect('/login', 302)
}
- const [theme] = detectTheme(request)
-
- return { theme }
+ return null
}
-export default function Index() {
- const { theme } = useLoaderData<typeof loader>()
-
- return <ReferralPage ssrTheme={theme} />
+export default function ReferralPageRoute() {
+ return <ReferralPage />
}
diff --git a/web/app/routes/signup.tsx b/web/app/routes/signup.tsx
index aa4fcfde5..8c0fd39b5 100644
--- a/web/app/routes/signup.tsx
+++ b/web/app/routes/signup.tsx
@@ -1,24 +1,21 @@
-import type { HeadersFunction, LoaderFunctionArgs } from 'react-router'
-import { useLoaderData, redirect } from 'react-router'
+import type { HeadersFunction } from 'react-router'
+import { redirect } from 'react-router'
import type { SitemapFunction } from 'remix-sitemap'
import { isSelfhosted } from '~/lib/constants'
import Singup from '~/pages/Auth/Signup'
-import { detectTheme } from '~/utils/server'
export const headers: HeadersFunction = ({ parentHeaders }) => {
parentHeaders.set('X-Frame-Options', 'DENY')
return parentHeaders
}
-export async function loader({ request }: LoaderFunctionArgs) {
+export async function loader() {
if (isSelfhosted) {
return redirect('/login', 302)
}
- const [theme] = detectTheme(request)
-
- return { theme }
+ return null
}
export const sitemap: SitemapFunction = () => ({
@@ -27,7 +24,5 @@ export const sitemap: SitemapFunction = () => ({
})
export default function Index() {
- const { theme } = useLoaderData<typeof loader>()
-
- return <Singup ssrTheme={theme} />
+ return <Singup />
}
diff --git a/web/app/ui/MultiProgress.tsx b/web/app/ui/MultiProgress.tsx
index fbda98341..604a5e62f 100644
--- a/web/app/ui/MultiProgress.tsx
+++ b/web/app/ui/MultiProgress.tsx
@@ -2,6 +2,8 @@ import cx from 'clsx'
import _map from 'lodash/map'
import { memo } from 'react'
+import { useTheme } from '~/providers/ThemeProvider'
+
interface Progress {
value: number
lightColour: string
@@ -10,25 +12,28 @@ interface Progress {
interface MultiProgressProps {
progress: Progress[]
- theme: 'dark' | 'light'
className?: string
}
-const MultiProgress = ({ progress, theme, className }: MultiProgressProps) => (
- <div className='relative'>
- <div className={cx('flex h-5 overflow-hidden rounded-sm bg-gray-200 text-xs dark:bg-slate-600', className)}>
- {_map(progress, ({ value, lightColour, darkColour }) => (
- <div
- key={`${value}-${lightColour}-${darkColour}`}
- style={{
- width: `${value}%`,
- backgroundColor: theme === 'dark' ? darkColour : lightColour,
- }}
- className='flex flex-col justify-center text-center whitespace-nowrap text-white shadow-none'
- />
- ))}
+const MultiProgress = ({ progress, className }: MultiProgressProps) => {
+ const { theme } = useTheme()
+
+ return (
+ <div className='relative'>
+ <div className={cx('flex h-5 overflow-hidden rounded-sm bg-gray-200 text-xs dark:bg-slate-600', className)}>
+ {_map(progress, ({ value, lightColour, darkColour }) => (
+ <div
+ key={`${value}-${lightColour}-${darkColour}`}
+ style={{
+ width: `${value}%`,
+ backgroundColor: theme === 'dark' ? darkColour : lightColour,
+ }}
+ className='flex flex-col justify-center text-center whitespace-nowrap text-white shadow-none'
+ />
+ ))}
+ </div>
</div>
- </div>
-)
+ )
+}
export default memo(MultiProgress)
diff --git a/web/app/ui/icons/BackgroundSvg.tsx b/web/app/ui/icons/BackgroundSvg.tsx
index 6ef6b6c7a..8bf668ccf 100644
--- a/web/app/ui/icons/BackgroundSvg.tsx
+++ b/web/app/ui/icons/BackgroundSvg.tsx
@@ -1,14 +1,17 @@
import cx from 'clsx'
import React from 'react'
+import { useTheme } from '~/providers/ThemeProvider'
+
interface BackgroundSvgProps {
className?: string
type: 'shapes' | 'circle' | 'semicircle' | 'twolinecircle' | 'threecircle' | 'twolinecircle2'
children?: React.ReactNode
- theme: 'dark' | 'light'
}
-const BackgroundSvg = ({ className, type, children, theme }: BackgroundSvgProps) => {
+const BackgroundSvg = ({ className, type, children }: BackgroundSvgProps) => {
+ const { theme } = useTheme()
+
if (type === 'shapes') {
return (
<svg
diff --git a/web/app/ui/icons/SwetrixLogo.tsx b/web/app/ui/icons/SwetrixLogo.tsx
index 48fcd28a3..e25f9c60d 100644
--- a/web/app/ui/icons/SwetrixLogo.tsx
+++ b/web/app/ui/icons/SwetrixLogo.tsx
@@ -2,14 +2,15 @@ import cx from 'clsx'
import { useTranslation } from 'react-i18next'
import { isSelfhosted } from '~/lib/constants'
+import { useTheme } from '~/providers/ThemeProvider'
interface SwetrixLogoProps {
className?: string
- theme?: 'dark' | 'light'
lazy?: boolean
}
-const SwetrixLogo = ({ className, theme = 'dark', lazy }: SwetrixLogoProps) => {
+const SwetrixLogo = ({ className, lazy }: SwetrixLogoProps) => {
+ const { theme } = useTheme()
const { t } = useTranslation()
return (
diff --git a/web/app/utils/server.ts b/web/app/utils/server.ts
index 9ad0a69a6..27a333c37 100644
--- a/web/app/utils/server.ts
+++ b/web/app/utils/server.ts
@@ -9,12 +9,12 @@ import routes from '~/utils/routes'
/**
* Function detects theme based on user's browser hints and cookies
*/
-export function detectTheme(request: Request): [ThemeType, boolean] {
+export function detectTheme(request: Request): ThemeType {
// Stage 1: Check if theme is set via `theme` query param
const queryTheme = new URL(request.url).searchParams.get('theme') as ThemeType | null
if (queryTheme && _includes(SUPPORTED_THEMES, queryTheme)) {
- return [queryTheme, false]
+ return queryTheme
}
// Stage 2: Check if user has set theme manually
@@ -22,7 +22,7 @@ export function detectTheme(request: Request): [ThemeType, boolean] {
const theme = cookie?.match(/(?<=colour-theme=)[^;]*/)?.[0] as ThemeType
if (_includes(SUPPORTED_THEMES, theme)) {
- return [theme, false]
+ return theme
}
// Stage 3: Try to detect theme based on Sec-CH browser hints
@@ -31,10 +31,10 @@ export function detectTheme(request: Request): [ThemeType, boolean] {
const hintedTheme = request.headers.get('Sec-CH-Prefers-Color-Scheme') as ThemeType
if (_includes(SUPPORTED_THEMES, hintedTheme)) {
- return [hintedTheme, true]
+ return hintedTheme
}
- return ['light', false]
+ return 'light'
}
export function isEmbedded(request: Request): boolean {