Skip to content

Commit

Permalink
feat(ui): add support for auto theme mode (system preference)
Browse files Browse the repository at this point in the history
  • Loading branch information
itsjavi committed Aug 30, 2023
1 parent a2c38c5 commit 7bc1833
Showing 1 changed file with 17 additions and 23 deletions.
40 changes: 17 additions & 23 deletions packages/storylite/src/app/getToolbarAddons.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {
BoxSelectIcon,
ContrastIcon,
ExpandIcon,
ExternalLinkIcon,
GridIcon,
Expand Down Expand Up @@ -161,42 +162,35 @@ function getDefaultRightToolbarAddons(): AddonSetup[] {
const darkModeAddon: AddonSetup = [
SLCoreAddon.ColorScheme,
{
tooltip: 'Toggle Dark Mode',
tooltip: 'Toggle Dark/Light/Auto theme',
defaultContent: <SunIcon />,
activeContent: <MoonIcon />,
placement,
stateful: true,
persistent: true,
defaultValue: SLColorScheme.Auto,
onRender: (ctx, [value, , setValue]) => {
if (value !== SLColorScheme.Auto) {
return
}

const updateColorScheme = (e: MediaQueryList | MediaQueryListEvent) => {
setValue(e.matches ? SLColorScheme.Dark : SLColorScheme.Light)
}
onClick: (_, [value, setValue]) => {
// Rotate between Auto -> Light -> Dark
if (value === SLColorScheme.Light) {
setValue(SLColorScheme.Auto)

const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
if (mediaQuery.matches) {
updateColorScheme(mediaQuery)
return
}
if (value === SLColorScheme.Dark) {
setValue(SLColorScheme.Light)

mediaQuery.addEventListener('change', updateColorScheme)

return () => {
mediaQuery.removeEventListener('change', updateColorScheme)
return
}
setValue(SLColorScheme.Dark)
},
onClick: (_, [value, setValue]) => {
if (value === false || value === SLColorScheme.Light) {
setValue(SLColorScheme.Dark)

return
render: (_, [value]) => {
if (value === SLColorScheme.Auto || !value) {
return <ContrastIcon />
}
setValue(SLColorScheme.Light)

return value === SLColorScheme.Light ? <SunIcon /> : <MoonIcon />
},
isActive: (_, [value]) => value === SLColorScheme.Dark,
isActive: (_, [value]) => value !== SLColorScheme.Auto,
} satisfies SLAddonPropsWithoutId<true>,
]

Expand Down

0 comments on commit 7bc1833

Please sign in to comment.