Skip to content

Commit

Permalink
feat: add disableTransition option (#192)
Browse files Browse the repository at this point in the history
  • Loading branch information
zcf0508 committed Mar 21, 2024
1 parent 4200432 commit 23ef3d9
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
10 changes: 9 additions & 1 deletion src/module.ts
Expand Up @@ -13,7 +13,8 @@ const DEFAULTS: ModuleOptions = {
classPrefix: '',
classSuffix: '-mode',
dataValue: '',
storageKey: 'nuxt-color-mode'
storageKey: 'nuxt-color-mode',
disableTransition: false
}

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 false
*/
disableTransition?: boolean
}
14 changes: 13 additions & 1 deletion src/runtime/plugin.client.ts
Expand Up @@ -2,7 +2,7 @@ import { computed, reactive, watch } from 'vue'

import type { ColorModeInstance } from './types'
import { defineNuxtPlugin, isVue2, isVue3, useRouter, useHead, useState } from '#imports'
import { globalName, storageKey, dataValue } from '#color-mode-options'
import { globalName, storageKey, dataValue, disableTransition } from '#color-mode-options'

// Initialise to empty object to avoid hard error when hydrating app in test mode
const helper = (window[globalName] || {}) as unknown as {
Expand Down Expand Up @@ -88,8 +88,20 @@ export default defineNuxtPlugin((nuxtApp) => {
}, { immediate: true })

watch(() => colorMode.value, (newValue, oldValue) => {
let style: HTMLStyleElement | undefined
if (disableTransition) {
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 (disableTransition) {
// Calling getComputedStyle forces the browser to redraw
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const _ = window!.getComputedStyle(style!).opacity
document.head.removeChild(style!)
}
})

if (colorMode.preference === 'system') {
Expand Down

0 comments on commit 23ef3d9

Please sign in to comment.