Skip to content

Commit

Permalink
refactor: adjust theme color timer logic
Browse files Browse the repository at this point in the history
  • Loading branch information
starknt committed Jul 14, 2024
1 parent db61cd1 commit df1701c
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 7 deletions.
16 changes: 10 additions & 6 deletions src/composables/useDark.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export function useDark() {
return currentSystemColorScheme.value
})
const isDark = computed(() => currentAppColorScheme.value === 'dark')
let themeChangeTimer: NodeJS.Timeout | null = null

// Watch for changes in the 'settings.value.theme' variable and add the 'dark' class to the 'mainApp' element
// to prevent some Unocss dark-specific styles from failing to take effect
Expand All @@ -30,22 +31,25 @@ export function useDark() {
* to prevent some Unocss dark-specific styles from failing to take effect
*/
function setAppAppearance() {
if (themeChangeTimer)
clearInterval(themeChangeTimer)

if (isDark.value) {
document.querySelector('#bewly')?.classList.add('dark')
document.documentElement.classList.add('dark')
setCookie('theme_style', 'dark', 365 * 10)
// TODO: find a better way implement this
executeTimes(() => {
themeChangeTimer = executeTimes(() => {
setCookie('theme_style', 'dark', 365 * 10)
window.dispatchEvent(new CustomEvent('global.themeChange', { detail: 'dark' }))
}, 15, 200)
}, 10, 200)
}
else {
document.querySelector('#bewly')?.classList.remove('dark')
document.documentElement.classList.remove('dark')
setCookie('theme_style', 'light', 365 * 10)
executeTimes(() => {
themeChangeTimer = executeTimes(() => {
setCookie('theme_style', 'light', 365 * 10)
window.dispatchEvent(new CustomEvent('global.themeChange', { detail: 'light' }))
}, 15, 200)
}, 10, 200)
}
}

Expand Down
6 changes: 5 additions & 1 deletion src/utils/timer.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
export function executeTimes(fn: () => void | Promise<void>, times: number, interval: number = 1000) {
let count = 0
const timer = setInterval(async () => {
let timer: NodeJS.Timeout
// eslint-disable-next-line prefer-const
timer = setInterval(async () => {
await fn()
count++
if (count >= times) {
clearInterval(timer)
}
}, interval)

return timer
}

0 comments on commit df1701c

Please sign in to comment.