Skip to content

Commit

Permalink
feat: add useDisableTransition to transition between themes smoothly
Browse files Browse the repository at this point in the history
  • Loading branch information
yzh990918 committed May 14, 2023
1 parent 463a280 commit bb59cdc
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/components/ui/ThemeToggle.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,20 @@
import { Show, onMount } from 'solid-js'
import { useDark } from '@/hooks'
import { useDark, useDisableTransition } from '@/hooks'

export default () => {
const [isDark, setIsDark] = useDark()
const { disableTransition, removeDisableTransition } = useDisableTransition()

onMount(() => {
document.querySelector('meta[name="theme-color"]')?.setAttribute('content', isDark() ? '#222222' : '#fafafa')
})

const handleDarkChanged = () => {
disableTransition()
const dark = !isDark()
document.querySelector('meta[name="theme-color"]')?.setAttribute('content', dark ? '#222222' : '#fafafa')
setIsDark(dark)
removeDisableTransition()
}

return (
Expand Down
1 change: 1 addition & 0 deletions src/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ export * from './useCopy'
export * from './useClickOutside'
export * from './useLargeScreen'
export * from './useMobileScreen'
export * from './useDisableTransition'
32 changes: 32 additions & 0 deletions src/hooks/useDisableTransition.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
export const useDisableTransition = () => {
// https://paco.me/writing/disable-theme-transitions
const css = document.createElement('style')
const disableTransition = () => {
css.type = 'text/css'
css.appendChild(
document.createTextNode(
`* {
-webkit-transition: none !important;
-moz-transition: none !important;
-o-transition: none !important;
-ms-transition: none !important;
transition: none !important;
}`,
),
)
document.head.appendChild(css)
}

// Calling getComputedStyle forces the browser to redraw
const removeDisableTransition = () => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const _ = window.getComputedStyle(css).opacity
document.head.removeChild(css)
}

return {
css,
disableTransition,
removeDisableTransition,
}
}

0 comments on commit bb59cdc

Please sign in to comment.