Add support for system-theme (dark/default)

This commit is contained in:
Jesús Espino 2021-03-20 08:52:24 +01:00
parent c8a06c6a8e
commit bc9be643a5
2 changed files with 31 additions and 12 deletions

View file

@ -363,6 +363,11 @@ class Sidebar extends React.Component<Props, State> {
name={intl.formatMessage({id: 'Sidebar.light-theme', defaultMessage: 'Light theme'})}
onClick={async () => this.updateTheme(lightTheme)}
/>
<Menu.Text
id='system-theme'
name={intl.formatMessage({id: 'Sidebar.system-theme', defaultMessage: 'System theme'})}
onClick={async () => this.updateTheme(null)}
/>
</Menu.SubMenu>
</Menu>
</MenuWrapper>
@ -370,9 +375,9 @@ class Sidebar extends React.Component<Props, State> {
)
}
private updateTheme(theme: Theme) {
setTheme(theme)
const whiteLogo = (theme.sidebarWhiteLogo === 'true')
private updateTheme(theme: Theme | null) {
const consolidatedTheme = setTheme(theme)
const whiteLogo = (consolidatedTheme.sidebarWhiteLogo === 'true')
this.setState({whiteLogo})
}

View file

@ -87,8 +87,18 @@ export const lightTheme = {
sidebarWhiteLogo: 'false',
}
export function setTheme(theme: Theme): void {
const consolidatedTheme = {...defaultTheme, ...theme}
export function setTheme(theme: Theme | null): Theme {
let consolidatedTheme = defaultTheme
if (theme) {
consolidatedTheme = {...defaultTheme, ...theme}
localStorage.setItem('theme', JSON.stringify(consolidatedTheme))
} else {
localStorage.setItem('theme', '')
const darkThemeMq = window.matchMedia('(prefers-color-scheme: dark)')
if (darkThemeMq.matches) {
consolidatedTheme = {...defaultTheme, ...darkTheme}
}
}
document.documentElement.style.setProperty('--main-bg', consolidatedTheme.mainBg)
document.documentElement.style.setProperty('--main-fg', consolidatedTheme.mainFg)
@ -113,22 +123,26 @@ export function setTheme(theme: Theme): void {
document.documentElement.style.setProperty('--prop-pink', consolidatedTheme.propPink)
document.documentElement.style.setProperty('--prop-red', consolidatedTheme.propRed)
localStorage.setItem('theme', JSON.stringify(consolidatedTheme))
return consolidatedTheme
}
export function loadTheme(): Theme {
const darkThemeMq = window.matchMedia('(prefers-color-scheme: dark)')
darkThemeMq.addListener(() => {
const themeStr = localStorage.getItem('theme')
if (!themeStr) {
setTheme(null)
}
})
const themeStr = localStorage.getItem('theme')
if (themeStr) {
try {
const theme = JSON.parse(themeStr)
setTheme(theme)
return theme
return setTheme(theme)
} catch (e) {
setTheme(defaultTheme)
return defaultTheme
return setTheme(null)
}
} else {
setTheme(defaultTheme)
return defaultTheme
return setTheme(null)
}
}