Skip to content

Commit

Permalink
feat(useCssVar): introduce observe option (#2800)
Browse files Browse the repository at this point in the history
  • Loading branch information
Alfred-Skyblue committed Mar 2, 2023
1 parent 9194d59 commit ae6e174
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 8 deletions.
32 changes: 32 additions & 0 deletions packages/core/useCssVar/index.test.ts
@@ -0,0 +1,32 @@
import { defaultWindow } from '@vueuse/core'
import { nextTick } from 'vue-demi'
import { useCssVar } from '.'

describe('useCssVar', () => {
it('should be defined', () => {
expect(useCssVar).toBeDefined()
})

it('should work', () => {
const el = document.createElement('div')
const color = '--color'
const variable = useCssVar(color, el, { initialValue: 'red' })

expect(variable.value).toBe('red')
})

it('should work observe', async () => {
const window = defaultWindow
const el = document.createElement('div')
window?.document.body.appendChild(el)

const color = '--color'
const variable = useCssVar(color, el, { initialValue: 'red', observe: true })

expect(variable.value).toBe('red')

el.style.setProperty(color, 'blue')
await nextTick()
expect(variable.value).toBe('blue')
})
})
34 changes: 26 additions & 8 deletions packages/core/useCssVar/index.ts
@@ -1,3 +1,4 @@
import { useMutationObserver } from '@vueuse/core'
import { computed, ref, watch } from 'vue-demi'
import type { MaybeComputedRef } from '@vueuse/shared'
import { resolveUnref } from '@vueuse/shared'
Expand All @@ -8,6 +9,11 @@ import { unrefElement } from '../unrefElement'

export interface UseCssVarOptions extends ConfigurableWindow {
initialValue?: string
/**
* Use MutationObserver to monitor variable changes
* @default false
*/
observe?: boolean
}

/**
Expand All @@ -16,25 +22,37 @@ export interface UseCssVarOptions extends ConfigurableWindow {
* @see https://vueuse.org/useCssVar
* @param prop
* @param target
* @param initialValue
* @param options
*/
export function useCssVar(
prop: MaybeComputedRef<string>,
target?: MaybeElementRef,
{ window = defaultWindow, initialValue = '' }: UseCssVarOptions = {},
options: UseCssVarOptions = {},
) {
const { window = defaultWindow, initialValue = '', observe = false } = options
const variable = ref(initialValue)
const elRef = computed(() => unrefElement(target) || window?.document?.documentElement)

function updateCssVar() {
const key = resolveUnref(prop)
const el = resolveUnref(elRef)
if (el && window) {
const value = window.getComputedStyle(el).getPropertyValue(key)?.trim()
variable.value = value || initialValue
}
}

if (observe) {
useMutationObserver(elRef, updateCssVar, {
attributes:
true,
window,
})
}

watch(
[elRef, () => resolveUnref(prop)],
([el, prop]) => {
if (el && window) {
const value = window.getComputedStyle(el).getPropertyValue(prop)?.trim()
variable.value = value || initialValue
}
},
updateCssVar,
{ immediate: true },
)

Expand Down

0 comments on commit ae6e174

Please sign in to comment.