docs/.vitepress/utils/tooltips.ts

12477b9242fb06be8abaf5f2b874b35addef3897
wotaku/docs/.vitepress/utils/tooltips.ts history · blame · raw

58 lines · 1579 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 matter from 'gray-matter'
 9import { readdirSync, readFileSync } from 'node:fs'
10import { basename, join, resolve } from 'pathe'
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()