Skip to content

Commit

Permalink
feat(useDark, useColorMode): introduce disableTransition option
Browse files Browse the repository at this point in the history
  • Loading branch information
antfu committed Feb 24, 2023
1 parent bbf15f4 commit 320abd7
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions packages/core/useColorMode/index.ts
Expand Up @@ -77,6 +77,14 @@ export interface UseColorModeOptions<T extends string = BasicColorSchema> extend
* @default undefined
*/
emitAuto?: boolean

/**
* Disable transition on switch
*
* @see https://paco.me/writing/disable-theme-transitions
* @default false
*/
disableTransition?: boolean
}

/**
Expand All @@ -96,6 +104,8 @@ export function useColorMode<T extends string = BasicColorSchema>(options: UseCo
listenToStorageChanges = true,
storageRef,
emitAuto,
// TODO: switch to true in v10
disableTransition = false,
} = options

const modes = {
Expand Down Expand Up @@ -130,6 +140,14 @@ export function useColorMode<T extends string = BasicColorSchema>(options: UseCo
if (!el)
return

let style: HTMLStyleElement | undefined
if (disableTransition) {
style = window!.document.createElement('style')
style.type = 'text/css'
style.appendChild(document.createTextNode('*{-webkit-transition:none!important;-moz-transition:none!important;-o-transition:none!important;-ms-transition:none!important;transition:none!important}'))
window!.document.head.appendChild(style)
}

if (attribute === 'class') {
const current = value.split(/\s/g)
Object.values(modes)
Expand All @@ -145,6 +163,13 @@ export function useColorMode<T extends string = BasicColorSchema>(options: UseCo
else {
el.setAttribute(attribute, value)
}

if (disableTransition) {
// Calling getComputedStyle forces the browser to redraw
// @ts-expect-error unused variable
const _ = window!.getComputedStyle(style!).opacity
document.head.removeChild(style!)
}
})

function defaultOnChanged(mode: T | BasicColorSchema) {
Expand Down

0 comments on commit 320abd7

Please sign in to comment.