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

c5d5a5e6d8127763d92162dd39b34a6092451d93
wotaku/docs/.vitepress/theme/components/extrepo/useTooltip.ts
Duck updatef93d8411b5 4 months ago

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}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form