Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add disableTransition option and set default to true #192

Merged
merged 10 commits into from
Mar 21, 2024
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: boolean
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) {
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) {
// 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
2 changes: 2 additions & 0 deletions src/script.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ addColorScheme(value)
w['<%= options.globalName %>'] = {
preference,
value,
// @ts-ignore
disableTransition: '<%= options.disableTransition %>' === 'true',
getColorScheme,
addColorScheme,
removeColorScheme
Expand Down