Skip to content
10 changes: 9 additions & 1 deletion src/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ const DEFAULTS: ModuleOptions = {
classPrefix: '',
classSuffix: '-mode',
dataValue: '',
storageKey: 'nuxt-color-mode'
storageKey: 'nuxt-color-mode',
disableTransition: true
}

export default defineNuxtModule({
Expand Down Expand Up @@ -162,4 +163,11 @@ export interface ModuleOptions {
* The script that will be injected into the head of the page
*/
script?: string
/**
* Disable transition on switch
*
* @see https://paco.me/writing/disable-theme-transitions
* @default true
*/
disableTransition?: boolean
}
13 changes: 13 additions & 0 deletions src/runtime/plugin.client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { globalName, storageKey, dataValue } from '#color-mode-options'
const helper = window[globalName] as unknown as {
preference: string
value: string
disableTransition: string
getColorScheme: () => string
addColorScheme: (className: string) => void
removeColorScheme: (className: string) => void
Expand Down Expand Up @@ -87,8 +88,20 @@ export default defineNuxtPlugin((nuxtApp) => {
}, { immediate: true })

watch(() => colorMode.value, (newValue, oldValue) => {
let style: HTMLStyleElement | undefined
if (helper.disableTransition === 'true') {
style = window!.document.createElement('style')
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)
}
helper.removeColorScheme(oldValue)
helper.addColorScheme(newValue)
if (helper.disableTransition === 'true') {
// Calling getComputedStyle forces the browser to redraw
// @ts-expect-error unused variable
const _ = window!.getComputedStyle(style!).opacity
document.head.removeChild(style!)
}
})

if (colorMode.preference === 'system') {
Expand Down
1 change: 1 addition & 0 deletions src/script.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ addColorScheme(value)
w['<%= options.globalName %>'] = {
preference,
value,
disableTransition: '<%= options.disableTransition %>',
getColorScheme,
addColorScheme,
removeColorScheme
Expand Down