All files / runtime-core/src/helpers useTemplateRef.ts

88.23% Statements 15/17
81.25% Branches 13/16
100% Functions 4/4
88.23% Lines 15/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45          93x             18x 18x 18x 18x 18x 1x   17x   3x 17x                 18x 18x 14x   18x         68x        
import { type ShallowRef, readonly, shallowRef } from '@vue/reactivity'
import { type Data, getCurrentInstance } from '../component'
import { warn } from '../warning'
import { EMPTY_OBJ } from '@vue/shared'
 
export const knownTemplateRefs: WeakSet<ShallowRef> = new WeakSet()
 
export type TemplateRef<T = unknown> = Readonly<ShallowRef<T | null>>
 
export function useTemplateRef<T = unknown, Keys extends string = string>(
  key: Keys,
): TemplateRef<T> {
  const i = getCurrentInstance()
  const r = shallowRef(null)
  if (i) {
    const refs = i.refs === EMPTY_OBJ ? (i.refs = {}) : i.refs
    if (__DEV__ && isTemplateRefKey(refs, key)) {
      warn(`useTemplateRef('${key}') already exists.`)
    } else {
      Object.defineProperty(refs, key, {
        enumerable: true,
        get: () => r.value,
        set: val => (r.value = val),
      })
    }
  } else if (E__DEV__) {
    warn(
      `useTemplateRef() is called when there is no active component ` +
        `instance to be associated with.`,
    )
  }
  const ret = __DEV__ ? readonly(r) : r
  if (__DEV__) {
    knownTemplateRefs.add(ret)
  }
  return ret
}
 
export function isTemplateRefKey(refs: Data, key: string): boolean {
  let desc: PropertyDescriptor | undefined
  return !!(
    (desc = Object.getOwnPropertyDescriptor(refs, key)) && !desc.configurable
  )
}