docs/.vitepress/theme/components/extrepo/useTooltip.ts

52 lines · 1142 bytes

8 symbols in this file
 1import { inject, type InjectionKey, provide, ref } from 'vue'
 2
 3interface TooltipState {
 4  text: string
 5  x: number
 6  y: number
 7}
 8
 9interface TooltipCtx {
10  show: (e: MouseEvent, text: string) => void
11  hide: () => void
12}
13
14const KEY: InjectionKey<TooltipCtx> = Symbol('ext-tooltip')
15
16let hoverable: boolean | undefined
17
18function canHover(): boolean {
19  if (hoverable === undefined) {
20    hoverable = typeof window !== 'undefined' &&
21      window.matchMedia('(hover: hover)').matches
22  }
23  return hoverable
24}
25
26export function provideTooltip() {
27  const tooltip = ref<TooltipState | null>(null)
28
29  function show(e: MouseEvent, text: string) {
30    if (!canHover()) return
31    const rect = (e.currentTarget as HTMLElement).getBoundingClientRect()
32    tooltip.value = { text, x: rect.left + rect.width / 2, y: rect.top }
33  }
34
35  function hide() {
36    tooltip.value = null
37  }
38
39  provide(KEY, { show, hide })
40
41  return { tooltip }
42}
43
44export function useTooltip(): TooltipCtx {
45  const ctx = inject(KEY)
46  if (!ctx) {
47    throw new Error(
48      'useTooltip() must be called within a component tree wrapped by provideTooltip()'
49    )
50  }
51  return ctx
52}