docs/.vitepress/utils/tooltips.ts

c9d998d7c10f502a00e00061980a0ee5058acd50
wotaku/docs/.vitepress/utils/tooltips.ts

58 lines · 1573 bytes

 1/**
 2*  All Rights Reserved
 3*
 4*  Copyright (c) 2025 taskylizard
 5*
 6*  All rights reserved. This code and its associated files may not be copied, modified, distributed, sublicensed, or used in any form, in whole or in part, without prior written permission from the copyright holder.
 7*/
 8import { readdirSync, readFileSync } from 'node:fs'
 9import { basename, join, resolve } from 'pathe'
10import matter from 'gray-matter'
11
12export interface TooltipData {
13  id: string
14  frontmatter: Record<string, string>
15  content: string
16}
17
18let tooltipsCache: TooltipData[] | null = null
19
20export function loadTooltips(): TooltipData[] {
21  if (tooltipsCache) return tooltipsCache
22
23  const tooltipsDir = resolve(process.cwd(), 'docs/.vitepress/tooltips')
24  const tooltips: TooltipData[] = []
25
26  try {
27    const files = readdirSync(tooltipsDir).filter((file) =>
28      file.endsWith('.md')
29    )
30
31    for (const file of files) {
32      const filePath = join(tooltipsDir, file)
33      const fileContent = readFileSync(filePath, 'utf-8')
34      const { data, content } = matter(fileContent)
35
36      const id = basename(file, '.md')
37      const cleanContent = content.trim()
38
39      tooltips.push({
40        id,
41        frontmatter: data,
42        content: cleanContent
43      })
44    }
45  } catch (error) {
46    console.warn('Failed to load tooltips:', error)
47  }
48
49  tooltipsCache = tooltips
50  return tooltips
51}
52
53export function getTooltip(id: string): TooltipData | undefined {
54  const tooltips = loadTooltips()
55  return tooltips.find((tooltip) => tooltip.id === id)
56}
57
58export const tooltips = loadTooltips()