Skip to content

Commit

Permalink
night mode day mode
Browse files Browse the repository at this point in the history
  • Loading branch information
satouriko committed May 28, 2022
1 parent 6e52cad commit 8cbc3f7
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 9 deletions.
2 changes: 1 addition & 1 deletion gatsby-ssr.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ export const onPreRenderHTML = ({
<script
key="prefers-dark-mode"
dangerouslySetInnerHTML={{
__html: "window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches && (document.body.className = 'nightly')"
__html: "(localStorage.getItem('userNightMode') === 'true' || window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) && (document.body.className = 'nightly')"
}}
/>
)
Expand Down
23 changes: 15 additions & 8 deletions src/components/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,20 +22,23 @@ export default <P extends {}> (LayoutComponent: React.ComponentType<P & NightMod
constructor (props: any) {
super(props)
// tslint:disable-next-line: strict-type-predicates
const systemPreferNightMode = typeof window !== 'undefined' &&
window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
// tslint:disable-next-line: strict-type-predicates
const persistentNightMode = typeof localStorage !== 'undefined'
? localStorage.getItem('nightMode') === 'true' || systemPreferNightMode
: systemPreferNightMode
const persistentNightMode = (typeof localStorage !== 'undefined' && localStorage.getItem('userNightMode'))
? localStorage.getItem('userNightMode') === 'true'
: undefined
this.state = {
// tslint:disable-next-line: strict-type-predicates
nightMode: (typeof window !== 'undefined' && window.akari.nightMode) ?? persistentNightMode
nightMode: persistentNightMode ?? this.systemPreferNightMode
}
this.onToggledNightMode = this.onToggledNightMode.bind(this)
this.onToggledFont = this.onToggledFont.bind(this)
}

get systemPreferNightMode () {
// tslint:disable-next-line: strict-type-predicates
return typeof window !== 'undefined' &&
window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
}

componentDidMount () {
// tslint:disable-next-line: strict-type-predicates
if (typeof localStorage !== 'undefined' && localStorage.getItem('font')) {
Expand Down Expand Up @@ -90,7 +93,11 @@ export default <P extends {}> (LayoutComponent: React.ComponentType<P & NightMod
document.body.classList.add('daily')
}
window.akari.nightMode = nightMode
window.localStorage.setItem('nightMode', nightMode + '')
if (nightMode !== this.systemPreferNightMode) {
window.localStorage.setItem('userNightMode', nightMode + '')
} else {
window.localStorage.removeItem('userNightMode')
}
}

if (this.props.onNightModeToggled) {
Expand Down

0 comments on commit 8cbc3f7

Please sign in to comment.