Skip to content

Commit

Permalink
Added instant dark mode toggle support
Browse files Browse the repository at this point in the history
  • Loading branch information
Zaydek Michels-Gualtieri committed Dec 21, 2020
1 parent e84989d commit 661f87b
Showing 1 changed file with 17 additions and 10 deletions.
27 changes: 17 additions & 10 deletions src/runtime/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
* TypeScript
*/

type DEV_MODE = "development" | "production"
type NODE_ENV = "development" | "production"
// type Theme = undefined | "light" | "dark"

declare global {
interface Window {
Expand All @@ -17,7 +18,7 @@ declare global {
const themePreferenceKey = "duomo-theme-preference" as const

interface IRuntime {
init(mode: DEV_MODE): () => void
init(mode: NODE_ENV): () => void
toggleDebugMode(): void
toggleDebugSpaceMode(): void
toggleDarkMode(): void
Expand All @@ -42,7 +43,7 @@ function OSPrefersDarkMode() {
}

const Duomo: IRuntime = {
init(mode: DEV_MODE = "production") {
init(mode: NODE_ENV = "production") {
const html = document.documentElement
const deferers: (() => void)[] = []

Expand Down Expand Up @@ -100,7 +101,6 @@ const Duomo: IRuntime = {
},
toggleDebugMode() {
const html = document.documentElement

const hasAttribute = html.hasAttribute("data-debug")
if (!hasAttribute) {
console.log("[Duomo] debugMode=on")
Expand All @@ -112,7 +112,6 @@ const Duomo: IRuntime = {
},
toggleDebugSpaceMode() {
const html = document.documentElement

const hasAttribute = html.hasAttribute("data-debug-space")
if (!hasAttribute) {
console.log("[Duomo] debugSpaceMode=on")
Expand All @@ -122,13 +121,10 @@ const Duomo: IRuntime = {
html.removeAttribute("data-debug-space")
}
},
// TODO: `toggleDarkMode` is not currently cancelable. Should it be?
// TODO: Implement `toggleMode(mode: string = "dark")`.
toggleDarkMode() {
toggleDarkMode(disableEffect = false) {
const html = document.documentElement

html.setAttribute("data-theme-effect", "true")
setTimeout(() => {
function toggle() {
const hasAttribute = html.hasAttribute("data-theme")
if (!hasAttribute) {
console.log("[Duomo] darkMode=on")
Expand All @@ -139,6 +135,17 @@ const Duomo: IRuntime = {
html.removeAttribute("data-theme")
window.localStorage.setItem(themePreferenceKey, "light")
}
}

if (disableEffect) {
toggle()
return
}

// TODO: `toggleDarkMode` is not currently cancelable. Should it be?
html.setAttribute("data-theme-effect", "true")
setTimeout(() => {
toggle()
setTimeout(() => {
html.removeAttribute("data-theme-effect")
}, 300)
Expand Down

0 comments on commit 661f87b

Please sign in to comment.