docs/.vitepress/theme/components/extrepo/useTooltip.ts
38 lines · 961 bytes
1import { inject, provide, ref, type InjectionKey } 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
16export function provideTooltip() {
17 const tooltip = ref<TooltipState | null>(null)
18
19 function show(e: MouseEvent, text: string) {
20 if (typeof window === 'undefined' || !window.matchMedia('(hover: hover)').matches) return
21 const rect = (e.currentTarget as HTMLElement).getBoundingClientRect()
22 tooltip.value = { text, x: rect.left + rect.width / 2, y: rect.top }
23 }
24
25 function hide() {
26 tooltip.value = null
27 }
28
29 provide(KEY, { show, hide })
30
31 return { tooltip }
32}
33
34export function useTooltip(): TooltipCtx {
35 const ctx = inject(KEY)
36 if (!ctx) throw new Error('useTooltip() must be called within a component tree wrapped by provideTooltip()')
37 return ctx
38}