docs/.vitepress/utils/tooltips.ts

6de72007af586349ad242e2b1cd9e70cf12bd1dd
wotaku/docs/.vitepress/utils/tooltips.ts history · blame · raw

67 lines · 1921 bytes

 1/**
 2 *  Copyright (c) 2024 taskylizard
 3 *
 4 *  Licensed under the Apache License, Version 2.0 (the "License");
 5 *  you may not use this file except in compliance with the License.
 6 *  You may obtain a copy of the License at
 7 *
 8 *  http://www.apache.org/licenses/LICENSE-2.0
 9 *
10 *  Unless required by applicable law or agreed to in writing, software
11 *  distributed under the License is distributed on an "AS IS" BASIS,
12 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 *  See the License for the specific language governing permissions and
14 *  limitations under the License.
15 */
16
17import { readdirSync, readFileSync } from "node:fs";
18import { basename, join, resolve } from "pathe";
19import matter from "gray-matter";
20
21export interface TooltipData {
22  id: string;
23  frontmatter: Record<string, string>;
24  content: string;
25}
26
27let tooltipsCache: TooltipData[] | null = null;
28
29export function loadTooltips(): TooltipData[] {
30  if (tooltipsCache) return tooltipsCache;
31
32  const tooltipsDir = resolve(process.cwd(), "docs/.vitepress/tooltips");
33  const tooltips: TooltipData[] = [];
34
35  try {
36    const files = readdirSync(tooltipsDir).filter((file) =>
37      file.endsWith(".md"),
38    );
39
40    for (const file of files) {
41      const filePath = join(tooltipsDir, file);
42      const fileContent = readFileSync(filePath, "utf-8");
43      const { data, content } = matter(fileContent);
44
45      const id = basename(file, ".md");
46      const cleanContent = content.trim();
47
48      tooltips.push({
49        id,
50        frontmatter: data,
51        content: cleanContent,
52      });
53    }
54  } catch (error) {
55    console.warn("Failed to load tooltips:", error);
56  }
57
58  tooltipsCache = tooltips;
59  return tooltips;
60}
61
62export function getTooltip(id: string): TooltipData | undefined {
63  const tooltips = loadTooltips();
64  return tooltips.find((tooltip) => tooltip.id === id);
65}
66
67export const tooltips = loadTooltips();