add vitepress doc

This commit is contained in:
Timi
2026-09-21 15:32:12 +08:00
parent 2fc96083c4
commit efd683e808
81 changed files with 7319 additions and 90 deletions
+83
View File
@@ -0,0 +1,83 @@
/**
* API 文档数据类型。
*
* 这些结构由 Node 侧的 `plugins/docgen.ts` 产出,通过虚拟模块交给浏览器渲染,
* 因此刻意保持为不含第三方类型的纯数据,避免 `vue-docgen-api` 被打进客户端产物。
*/
/** 单个 prop 的表格行数据。 */
export interface ApiPropRow {
/** prop 名称。 */
name: string;
/** 类型签名,如 `string`、`Article`。 */
type: string;
/** 默认值,未声明时为空字符串。 */
defaultValue: string;
/** 是否必填。 */
required: boolean;
/** 注释说明,取自源码 JSDoc。 */
description: string;
}
/** 单个事件的表格行数据。 */
export interface ApiEventRow {
/** 事件名,如 `update:modelValue`。 */
name: string;
/** 回调参数签名。 */
type: string;
/** 注释说明。 */
description: string;
}
/** 单个插槽的表格行数据。 */
export interface ApiSlotRow {
/** 插槽名。 */
name: string;
/** 注释说明或作用域参数。 */
description: string;
}
/** 单个暴露方法或属性的表格行数据。 */
export interface ApiExposeRow {
/** 暴露的名称。 */
name: string;
/** 类型签名。 */
type: string;
/** 注释说明。 */
description: string;
}
/** 一个组件解析完成后的完整 API 数据。 */
export interface ComponentApi {
/** 组件名。 */
name: string;
/** 组件自身的注释说明。 */
description: string;
/**
* 源码是否解析成功。
*
* 用来区分「解析失败」与「组件本身就没有 props/events/slots/expose」,
* 两者都会得到空数组,但提示语完全不同。
*/
parsed: boolean;
props: ApiPropRow[];
events: ApiEventRow[];
slots: ApiSlotRow[];
exposes: ApiExposeRow[];
}
/** 全部组件的 API 数据,键为组件名。 */
export type ComponentApiMap = Record<string, ComponentApi>;
/** 生成一个空的 API 数据,用于解析失败时兜底,保证文档站不因单个组件而白屏。 */
export function createEmptyApi(name: string): ComponentApi {
return {
name,
description: "",
parsed: false,
props: [],
events: [],
slots: [],
exposes: []
};
}
+179
View File
@@ -0,0 +1,179 @@
/**
* 组件元数据清单。
*
* 这是文档站的唯一数据源,三处消费它:
* - `config.ts` 生成侧边栏导航
* - `plugins/docgen.ts` 按 `entry` 定位源码并交给 vue-docgen-api 解析
* - 页面内的 `<api-table />` 按 `name` 查询解析结果
*
* 新增组件时只需在此追加一项,导航、API 表、文档路由会同步生效。
*/
/** 分类展示顺序即数组顺序。 */
export const CATEGORY_LIST = [
"基础组件",
"数据展示",
"内容与浮层",
"安全与特效"
] as const;
export type ComponentCategory = (typeof CATEGORY_LIST)[number];
export interface ComponentMeta {
/** 组件名,与组件内 `defineOptions` 的 name 一致,同时是 api-table 的查询键。 */
name: string;
/** 文档与侧边栏展示的中文标题。 */
title: string;
/** 一句话功能描述。 */
description: string;
/** 所属分类。 */
category: ComponentCategory;
/** 组件入口源码,相对仓库根目录。 */
entry: string;
/**
* 文档路径覆盖。
*
* 默认取 `entry` 所在目录名,只有目录名与对外组件名不一致时才需要显式指定
* (如 `v-popup` 目录导出的是 `HoverPopup`)。
*/
slug?: string;
}
export const COMPONENT_LIST: ComponentMeta[] = [
// ---------- 基础组件 ----------
{
name: "Icon",
title: "Icon 图标",
description: "内置 149 个 SVG 图标,支持缩放、着色与禁用态。",
category: "基础组件",
entry: "src/components/icon/index.vue"
},
{
name: "Loading",
title: "Loading 加载中",
description: "四段线动画的加载指示器,可延迟显示并支持内联或铺满两种形态。",
category: "基础组件",
entry: "src/components/loading/index.vue"
},
{
name: "EmptyTips",
title: "EmptyTips 空状态",
description: "列表或容器无数据时的居中占位文案。",
category: "基础组件",
entry: "src/components/empty-tips/index.vue"
},
{
name: "Copyright",
title: "Copyright 版权信息",
description: "统一页脚:版权声明、备案号与自定义文案。",
category: "基础组件",
entry: "src/components/copyright/index.vue"
},
// ---------- 数据展示 ----------
{
name: "AnimatedNumber",
title: "AnimatedNumber 数字动画",
description: "数值变化时按缓动函数滚动过渡,支持小数位与千分位。",
category: "数据展示",
entry: "src/components/animated-number/index.vue"
},
{
name: "DescriptionGrid",
title: "DescriptionGrid 描述栅格",
description: "键值对描述列表,可指定列数、对齐方式与逐项具名插槽。",
category: "数据展示",
entry: "src/components/description-grid/index.vue"
},
{
name: "PassTimeLabel",
title: "PassTimeLabel 时间标签",
description: "把时间戳显示为「多久以前」,点击可切换为完整日期时间。",
category: "数据展示",
entry: "src/components/passtime-label/index.vue"
},
{
name: "ContactNumber",
title: "ContactNumber 联系电话",
description: "按号段分组的电话号码展示,可点击拨号并支持前置图标。",
category: "数据展示",
entry: "src/components/contact-number/index.vue"
},
// ---------- 内容与浮层 ----------
{
name: "MarkdownView",
title: "MarkdownView 渲染视图",
description: "把 Markdown 或代码片段渲染为带语法高亮的富文本。",
category: "内容与浮层",
entry: "src/components/markdown-view/index.vue"
},
{
name: "MarkdownEditor",
title: "MarkdownEditor 编辑器",
description: "左侧编辑右侧预览的 Markdown 编辑器,窄屏自动折叠预览区。",
category: "内容与浮层",
entry: "src/components/markdown-editor/index.vue"
},
{
name: "Popup",
title: "Popup 浮层容器",
description: "全局唯一的浮层挂载点,配合 v-popup 指令或 HoverPopup 使用。",
category: "内容与浮层",
entry: "src/components/popup/index.vue"
},
{
name: "HoverPopup",
title: "HoverPopup 悬停浮层",
description: "鼠标悬停时在浮层容器里展示文本、图片或自定义节点。",
category: "内容与浮层",
entry: "src/components/v-popup/index.vue",
// 目录名是历史遗留的 v-popup,对外组件名是 HoverPopup,文档按后者取路径。
slug: "hover-popup"
},
// ---------- 安全与特效 ----------
{
name: "Captcha",
title: "Captcha 验证码",
description: "点击刷新的图形验证码,图片由外部 request 回调提供。",
category: "安全与特效",
entry: "src/components/captcha/index.vue"
},
{
name: "BEFlowerFall",
title: "BEFlowerFall 落花背景",
description: "飘落花瓣的页面背景特效,随窗口尺寸自适应。",
category: "安全与特效",
entry: "src/components/background-effect/flower-fall/index.vue"
}
];
/**
* 文档路径与路由片段。
*
* 默认取组件源码所在目录名,而不是把组件名转 kebab-case:
* 目录名天然就是合适的短横线形式(如 `flower-fall`),
* 而 `BEFlowerFall` 这类连续大写用正则会得到 `beflower-fall` 这种不理想的路径。
* 目录名与对外组件名不一致时,用 `slug` 显式覆盖。
*/
export function toSlug(meta: ComponentMeta): string {
if (meta.slug) {
return meta.slug;
}
const segments = meta.entry.split("/");
return segments[segments.length - 2];
}
/** 组件文档页的站内绝对路径。 */
export function toDocLink(meta: ComponentMeta): string {
return `/components/${toSlug(meta)}`;
}
/** 按分类分组,保持 CATEGORY_LIST 的声明顺序。 */
export function groupByCategory(): Array<{ category: ComponentCategory; items: ComponentMeta[] }> {
return CATEGORY_LIST.map(category => ({
category,
items: COMPONENT_LIST.filter(item => item.category === category)
})).filter(group => group.items.length > 0);
}
+144
View File
@@ -0,0 +1,144 @@
import { resolve } from "node:path";
import { defineConfig } from "vitepress";
import {
componentPreview,
containerPreview
} from "@vitepress-demo-preview/plugin";
import AutoImport from "unplugin-auto-import/vite";
import { groupByCategory, toDocLink } from "./components";
import { groupUtilsByCategory, toUtilLink } from "./utils";
import { docgenPlugin } from "./plugins/docgen";
import { tsdocgenPlugin } from "./plugins/tsdocgen";
/** `__dirname` 由 VitePress 打包配置时注入,指向 `docs/.vitepress`。 */
const docsDir = resolve(__dirname, "..");
/** 仓库根目录,组件源码位于它的 `src` 下。 */
const repoRoot = resolve(docsDir, "..");
/**
* 源码引用别名。
*
* demo 组件直接引用 `src` 源码而非构建产物,改组件即可热更新文档。
* 源码自身的传递依赖(prismjs、@tiptap/* 等)会从 timi-web 自己的
* node_modules 解析,docs 无需重复声明。
*
* `timi-ts` 例外:它编译为 CommonJS,桶文件用 `__exportStar(require(...))` 转发,
* Rollup 在生产构建里无法静态识别其具名导出(开发期走 esbuild 预打包所以正常)。
* 该包是本地 link 且带源码,直接指向源码即可绕开,同时获得热更新。
*/
const timiTsRoot = resolve(repoRoot, "../timi-ts");
const alias = {
"~": resolve(repoRoot, "src"),
"timi-web": resolve(repoRoot, "src/index.ts"),
"timi-web/editor": resolve(repoRoot, "src/editor/index.ts"),
"timi-ts": resolve(timiTsRoot, "src/index.ts")
};
/** 组件文档侧边栏,按 components.ts 的分类与顺序生成。 */
const componentSidebar = groupByCategory().map(group => ({
text: group.category,
collapsed: false,
items: group.items.map(item => ({
text: item.title,
link: toDocLink(item)
}))
}));
/** 工具文档侧边栏,按 utils.ts 的分类与顺序生成。 */
const utilSidebar = groupUtilsByCategory().map(group => ({
text: group.category,
collapsed: false,
items: group.items.map(item => ({
text: item.title,
link: toUtilLink(item)
}))
}));
export default defineConfig({
title: "timi-web",
description: "Vue 3 通用组件与编辑器能力的演示与 API 文档",
lang: "zh-CN",
cleanUrls: true,
themeConfig: {
nav: [
{ text: "指南", link: "/guide/" },
{ text: "组件", link: "/components/" },
{ text: "工具", link: "/utils/" }
],
sidebar: [
{
text: "指南",
items: [
{ text: "快速开始", link: "/guide/" },
{ text: "演示与文档约定", link: "/guide/demo" }
]
},
...componentSidebar,
{
text: "工具",
collapsed: false,
items: [
{ text: "工具总览", link: "/utils/" }
]
},
...utilSidebar
],
outline: {
level: [2, 3],
label: "本页目录"
},
search: {
provider: "local"
},
docFooter: {
prev: "上一篇",
next: "下一篇"
},
darkModeSwitchLabel: "主题",
sidebarMenuLabel: "目录",
returnToTopLabel: "回到顶部"
},
markdown: {
theme: {
light: "vitesse-light",
dark: "vitesse-dark"
},
lineNumbers: true,
config(md) {
// 组件大多依赖浏览器 API(Prism、ResizeObserver、requestAnimationFrame 等),
// 统一开启 clientOnly 交给浏览器渲染,避免 SSR 阶段报错。
md.use(componentPreview, { clientOnly: true, alias });
md.use(containerPreview, { clientOnly: true, alias });
}
},
vite: {
resolve: {
alias
},
plugins: [
docgenPlugin(repoRoot),
// 工具模块是 TS 文件,vue-docgen-api 无法解析,走 TypeScript AST 提取。
tsdocgenPlugin(repoRoot),
// src 源码依赖自动导入(内部没有任何一处显式 import vue),
// 这里仅为其提供支持;docs 自身的代码一律显式导入。
AutoImport({
imports: ["vue"],
dts: false
})
],
server: {
port: 3003,
host: true,
fs: {
// demo 需要读取 docs 之外的 src 与 timi-ts 源码。
allow: [repoRoot, timiTsRoot]
}
}
}
});
+163
View File
@@ -0,0 +1,163 @@
import { existsSync } from "node:fs";
import { resolve } from "node:path";
import { parse } from "vue-docgen-api";
import type { Plugin } from "vite";
import { COMPONENT_LIST } from "../components";
import {
createEmptyApi,
type ApiEventRow,
type ApiExposeRow,
type ApiPropRow,
type ApiSlotRow,
type ComponentApi,
type ComponentApiMap
} from "../api-types";
/** 虚拟模块的引用标识,业务代码与类型声明共用。 */
export const API_MODULE_ID = "virtual:timi-api";
/** Vite 内部使用的解析后标识,前置 `\0` 避免被其他插件处理。 */
const RESOLVED_ID = `\0${API_MODULE_ID}`;
/**
* 把 vue-docgen-api 的联合类型描述压平成可读文本。
* 不同版本对 `defineEmits` 的产出结构不一致,这里统一兜底。
*/
function normalizeType(type: unknown): string {
if (!type || typeof type !== "object") {
return "-";
}
const candidate = type as { name?: unknown; names?: unknown };
if (Array.isArray(candidate.names)) {
return candidate.names.length > 0 ? candidate.names.join(" | ") : "-";
}
if (typeof candidate.name === "string" && candidate.name.length > 0) {
return candidate.name;
}
return "-";
}
/** 转换 prop 描述符。 */
function toPropRow(descriptor: any): ApiPropRow {
return {
name: String(descriptor.name ?? ""),
type: normalizeType(descriptor.type),
defaultValue: descriptor.defaultValue?.value === undefined ? "-" : String(descriptor.defaultValue.value),
required: descriptor.required === true,
description: String(descriptor.description ?? "")
};
}
/** 转换事件描述符。 */
function toEventRow(descriptor: any): ApiEventRow {
return {
name: String(descriptor.name ?? ""),
type: normalizeType(descriptor.type),
description: String(descriptor.description ?? "")
};
}
/** 转换插槽描述符,把作用域参数并入说明列。 */
function toSlotRow(descriptor: any): ApiSlotRow {
const bindings = Array.isArray(descriptor.bindings)
? descriptor.bindings.map((item: any) => String(item.name ?? "")).filter(Boolean)
: [];
const description = String(descriptor.description ?? "");
const scope = bindings.length > 0 ? `作用域参数:${bindings.join("、")}` : "";
return {
name: String(descriptor.name ?? ""),
description: [description, scope].filter(Boolean).join(";")
};
}
/** 转换暴露描述符。 */
function toExposeRow(descriptor: any): ApiExposeRow {
return {
name: String(descriptor.name ?? ""),
type: normalizeType(descriptor.type),
description: String(descriptor.description ?? "")
};
}
/** 把单个组件文档规范化为纯数据。 */
function toComponentApi(name: string, doc: any): ComponentApi {
return {
name,
description: String(doc?.description ?? ""),
parsed: true,
props: Array.isArray(doc?.props) ? doc.props.map(toPropRow) : [],
events: Array.isArray(doc?.events) ? doc.events.map(toEventRow) : [],
slots: Array.isArray(doc?.slots) ? doc.slots.map(toSlotRow) : [],
exposes: Array.isArray(doc?.expose) ? doc.expose.map(toExposeRow) : []
};
}
/**
* 逐个解析组件源码。
* 单个组件解析失败只降级为空 API,不让整个文档站因一处语法而无法构建。
*/
async function parseAll(repoRoot: string): Promise<ComponentApiMap> {
const alias = {
"~": resolve(repoRoot, "src")
};
const result: ComponentApiMap = {};
for (const meta of COMPONENT_LIST) {
const filePath = resolve(repoRoot, meta.entry);
if (!existsSync(filePath)) {
console.warn(`[timi-docgen] 未找到组件入口,已跳过:${meta.entry}`);
result[meta.name] = createEmptyApi(meta.name);
continue;
}
try {
const doc = await parse(filePath, { alias });
result[meta.name] = toComponentApi(meta.name, doc);
} catch (error) {
console.warn(`[timi-docgen] 解析 ${meta.name} 失败,已降级为空 API:`, error);
result[meta.name] = createEmptyApi(meta.name);
}
}
return result;
}
/**
* 提供 `virtual:timi-api` 虚拟模块,内容为全部组件的 API 数据。
*
* 解析结果按需缓存,仅在组件源码变更时失效,避免每次页面请求都重复解析。
* @param repoRoot 仓库根目录的绝对路径
*/
export function docgenPlugin(repoRoot: string): Plugin {
const entryPathSet = new Set(COMPONENT_LIST.map(meta => resolve(repoRoot, meta.entry)));
let cache: ComponentApiMap | null = null;
return {
name: "timi-docgen",
resolveId(id: string) {
return id === API_MODULE_ID ? RESOLVED_ID : null;
},
async load(id: string) {
if (id !== RESOLVED_ID) {
return null;
}
if (cache === null) {
cache = await parseAll(repoRoot);
}
return `export default ${JSON.stringify(cache)};`;
},
handleHotUpdate({ file, server }) {
if (!entryPathSet.has(file)) {
return;
}
cache = null;
const invalidated = server.moduleGraph.getModuleById(RESOLVED_ID);
if (invalidated) {
server.moduleGraph.invalidateModule(invalidated);
server.ws.send({ type: "full-reload" });
}
}
};
}
+339
View File
@@ -0,0 +1,339 @@
import { existsSync, readFileSync } from "node:fs";
import { resolve } from "node:path";
import ts from "typescript";
import type { Plugin } from "vite";
import { UTIL_LIST } from "../utils";
import {
createEmptyUtilApi,
type UtilApi,
type UtilApiMap,
type UtilMemberRow,
type UtilTypeRow
} from "../utils-types";
/** 虚拟模块的引用标识,业务代码与类型声明共用。 */
export const UTILS_MODULE_ID = "virtual:timi-utils";
/** Vite 内部使用的解析后标识,前置 `\0` 避免被其他插件处理。 */
const RESOLVED_ID = `\0${UTILS_MODULE_ID}`;
/** 签名过长时截断的阈值。 */
const SIGNATURE_LIMIT = 90;
/** 取 JSDoc 原文,保留换行;剔除代码块,避免把用法示例混进说明。 */
function getRawDoc(node: ts.Node): string {
const parts: string[] = [];
for (const doc of ts.getJSDocCommentsAndTags(node)) {
if (ts.isJSDoc(doc) && doc.comment) {
parts.push(String(doc.comment));
}
}
return parts.join("\n").replace(/```[\s\S]*?```/g, " ");
}
/** 压平单段内的空白,去掉 markdown 标记。 */
function flattenParagraph(text: string): string {
return text.replace(/`/g, "").replace(/^#+\s*/, "").replace(/\s+/g, " ").trim();
}
/**
* 成员说明:按段保留换行。
*
* 不把多段压成一行,否则「摘要 + 补充说明」会连成读不通的长句;
* 交给渲染侧用 `white-space: pre-line` 呈现。
*/
function getDocComment(node: ts.Node): string {
return getRawDoc(node)
.split(/\n\s*\n/)
.map(flattenParagraph)
.filter(Boolean)
.join("\n");
}
/**
* 模块说明:只取第一段正文。
*
* 类注释常带 markdown 标题与用法代码块,取第一段可避免把代码塞进描述。
*/
function getModuleComment(node: ts.Node): string {
const firstParagraph = getRawDoc(node).split(/\n\s*\n/)[0] ?? "";
return flattenParagraph(firstParagraph);
}
/** 判断顶层声明是否被导出。 */
function isExported(node: ts.Node): boolean {
if (!ts.canHaveModifiers(node)) {
return false;
}
const modifiers = ts.getModifiers(node);
return modifiers?.some(item => item.kind === ts.SyntaxKind.ExportKeyword) ?? false;
}
/** 判断是否显式声明为 private / protected。 */
function isHiddenMember(node: ts.Node): boolean {
if (!ts.canHaveModifiers(node)) {
return false;
}
const modifiers = ts.getModifiers(node);
return modifiers?.some(item =>
item.kind === ts.SyntaxKind.PrivateKeyword ||
item.kind === ts.SyntaxKind.ProtectedKeyword
) ?? false;
}
/** 判断成员是否为静态成员。 */
function isStaticMember(node: ts.Node): boolean {
if (!ts.canHaveModifiers(node)) {
return false;
}
const modifiers = ts.getModifiers(node);
return modifiers?.some(item => item.kind === ts.SyntaxKind.StaticKeyword) ?? false;
}
/** 截断过长的签名。 */
function clampSignature(text: string): string {
const flat = text.replace(/\s+/g, " ").trim();
return flat.length > SIGNATURE_LIMIT ? `${flat.slice(0, SIGNATURE_LIMIT)}…` : flat;
}
/** 按源码中的类型标注还原单个参数。 */
function printParameter(param: ts.ParameterDeclaration, sourceFile: ts.SourceFile): string {
const rest = param.dotDotDotToken ? "..." : "";
const name = param.name.getText(sourceFile);
const optional = param.questionToken ? "?" : "";
const type = param.type ? `: ${param.type.getText(sourceFile)}` : "";
const initializer = param.initializer?.getText(sourceFile) ?? "";
// 默认值只在简短时保留,避免把大段字面量塞进签名
const fallback = initializer && initializer.length <= 20 ? ` = ${initializer}` : "";
return `${rest}${name}${optional}${type}${fallback}`;
}
/** 还原函数或方法的签名。 */
function printFunctionLike(
name: string,
node: ts.SignatureDeclaration,
sourceFile: ts.SourceFile
): string {
const typeParameters = node.typeParameters?.length
? `<${node.typeParameters.map(item => item.getText(sourceFile)).join(", ")}>`
: "";
const parameters = node.parameters
.map(item => printParameter(item, sourceFile))
.join(", ");
const returns = node.type ? `: ${node.type.getText(sourceFile)}` : "";
return `${name}${typeParameters}(${parameters})${returns}`;
}
/** 还原类属性或顶层常量的签名。 */
function printProperty(node: ts.PropertyDeclaration, sourceFile: ts.SourceFile): string {
if (node.type) {
return node.type.getText(sourceFile);
}
const initializer = node.initializer;
if (initializer && ts.isArrowFunction(initializer)) {
return printFunctionLike("", initializer, sourceFile);
}
if (initializer) {
return initializer.getText(sourceFile);
}
return "-";
}
/** 收集类成员。 */
function collectClassMembers(
node: ts.ClassDeclaration,
sourceFile: ts.SourceFile
): UtilMemberRow[] {
const rows: UtilMemberRow[] = [];
for (const member of node.members) {
if (isHiddenMember(member)) {
continue;
}
const prefix = isStaticMember(member) ? "static " : "";
if (ts.isMethodDeclaration(member)) {
const name = member.name.getText(sourceFile);
rows.push({
name,
signature: clampSignature(prefix + printFunctionLike(name, member, sourceFile)),
description: getDocComment(member)
});
continue;
}
if (ts.isPropertyDeclaration(member)) {
const name = member.name.getText(sourceFile);
rows.push({
name,
signature: clampSignature(prefix + printProperty(member, sourceFile)),
description: getDocComment(member)
});
}
}
return rows;
}
/** 收集导出的类型定义。 */
function collectType(
node: ts.TypeAliasDeclaration | ts.InterfaceDeclaration | ts.EnumDeclaration,
sourceFile: ts.SourceFile
): UtilTypeRow {
const kind = ts.isTypeAliasDeclaration(node)
? "类型别名"
: ts.isInterfaceDeclaration(node)
? "接口"
: "枚举";
return {
name: node.name.getText(sourceFile),
kind,
text: node.getText(sourceFile),
description: getModuleComment(node)
};
}
/** 解析单个工具模块源码。 */
function parseUtil(name: string, filePath: string): UtilApi {
const source = readFileSync(filePath, "utf-8");
const sourceFile = ts.createSourceFile(
filePath,
source,
ts.ScriptTarget.ESNext,
true,
ts.ScriptKind.TS
);
// `export default VDraggable;` 这类写法下,声明本身没有 export 修饰符,
// 先记录默认导出的标识符,第二轮再一并纳入。
let defaultExportName: string | null = null;
for (const statement of sourceFile.statements) {
if (ts.isExportAssignment(statement) && ts.isIdentifier(statement.expression)) {
defaultExportName = statement.expression.getText(sourceFile);
}
}
const api: UtilApi = {
name,
description: "",
parsed: true,
members: [],
types: []
};
for (const statement of sourceFile.statements) {
if (ts.isClassDeclaration(statement) && statement.name) {
const declaredName = statement.name.getText(sourceFile);
if (!isExported(statement) && declaredName !== defaultExportName) {
continue;
}
api.description = getModuleComment(statement);
api.members.push(...collectClassMembers(statement, sourceFile));
continue;
}
if (ts.isFunctionDeclaration(statement) && statement.name) {
if (!isExported(statement)) {
continue;
}
const functionName = statement.name.getText(sourceFile);
api.members.push({
name: functionName,
signature: clampSignature(printFunctionLike(functionName, statement, sourceFile)),
description: getDocComment(statement)
});
continue;
}
if (ts.isVariableStatement(statement)) {
for (const declaration of statement.declarationList.declarations) {
if (!ts.isIdentifier(declaration.name)) {
continue;
}
const declaredName = declaration.name.getText(sourceFile);
if (!isExported(statement) && declaredName !== defaultExportName) {
continue;
}
api.members.push({
name: declaredName,
signature: clampSignature(printProperty(declaration, sourceFile)),
description: getDocComment(statement) || getDocComment(declaration)
});
}
continue;
}
if (
(ts.isTypeAliasDeclaration(statement) ||
ts.isInterfaceDeclaration(statement) ||
ts.isEnumDeclaration(statement)) &&
isExported(statement)
) {
api.types.push(collectType(statement, sourceFile));
}
}
// 类没有写注释时保持为空,让文档页使用元数据里的描述;
// 退而取某个成员的说明会造成「模块说明=某个方法的说明」这种误导。
return api;
}
/** 逐个解析工具模块,单个失败只降级为空数据。 */
function parseAll(repoRoot: string): UtilApiMap {
const result: UtilApiMap = {};
for (const meta of UTIL_LIST) {
const filePath = resolve(repoRoot, meta.entry);
if (!existsSync(filePath)) {
console.warn(`[timi-tsdocgen] 未找到模块:${meta.entry}`);
result[meta.name] = createEmptyUtilApi(meta.name);
continue;
}
try {
result[meta.name] = parseUtil(meta.name, filePath);
} catch (error) {
console.warn(`[timi-tsdocgen] 解析 ${meta.name} 失败,已降级:`, error);
result[meta.name] = createEmptyUtilApi(meta.name);
}
}
return result;
}
/**
* 提供 `virtual:timi-utils` 虚拟模块,内容为全部工具模块的 API 数据。
*
* `vue-docgen-api` 只能解析 SFC,工具模块是 TS 文件,因此这里改用
* TypeScript 自带的解析器读 AST:签名直接从源码的类型标注还原,
* 不建 TypeChecker,既不依赖各模块的外部类型能否解析,也快得多。
*
* @param repoRoot 仓库根目录的绝对路径
*/
export function tsdocgenPlugin(repoRoot: string): Plugin {
const entryPathSet = new Set(UTIL_LIST.map(meta => resolve(repoRoot, meta.entry)));
let cache: UtilApiMap | null = null;
return {
name: "timi-tsdocgen",
resolveId(id: string) {
return id === UTILS_MODULE_ID ? RESOLVED_ID : null;
},
load(id: string) {
if (id !== RESOLVED_ID) {
return null;
}
if (cache === null) {
cache = parseAll(repoRoot);
}
return `export default ${JSON.stringify(cache)};`;
},
handleHotUpdate({ file, server }) {
if (!entryPathSet.has(file)) {
return;
}
cache = null;
const invalidated = server.moduleGraph.getModuleById(RESOLVED_ID);
if (invalidated) {
server.moduleGraph.invalidateModule(invalidated);
server.ws.send({ type: "full-reload" });
}
}
};
}
@@ -0,0 +1,162 @@
<template>
<div v-if="api" class="tui-api">
<section v-if="api.props.length > 0">
<h3>Props</h3>
<table>
<thead>
<tr>
<th>名称</th>
<th>类型</th>
<th>默认值</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr v-for="row in api.props" :key="row.name">
<td class="name">
<code v-text="row.name" />
<span v-if="row.required" class="required" title="必填">*</span>
</td>
<td><code v-text="row.type" /></td>
<td><code v-text="row.defaultValue" /></td>
<td v-text="row.description" />
</tr>
</tbody>
</table>
</section>
<section v-if="api.events.length > 0">
<h3>Events</h3>
<table>
<thead>
<tr>
<th>名称</th>
<th>参数</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr v-for="row in api.events" :key="row.name">
<td><code v-text="row.name" /></td>
<td><code v-text="row.type" /></td>
<td v-text="row.description" />
</tr>
</tbody>
</table>
</section>
<section v-if="api.slots.length > 0">
<h3>Slots</h3>
<table>
<thead>
<tr>
<th>名称</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr v-for="row in api.slots" :key="row.name">
<td><code v-text="row.name" /></td>
<td v-text="row.description" />
</tr>
</tbody>
</table>
</section>
<section v-if="api.exposes.length > 0">
<h3>Expose</h3>
<table>
<thead>
<tr>
<th>名称</th>
<th>类型</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr v-for="row in api.exposes" :key="row.name">
<td><code v-text="row.name" /></td>
<td><code v-text="row.type" /></td>
<td v-text="row.description" />
</tr>
</tbody>
</table>
</section>
<p v-if="isEmpty && !api.parsed" class="notice warn">
未能从源码中解析出 API 信息,请检查组件是否使用了 defineProps / defineEmits / defineExpose。
</p>
<p v-else-if="isEmpty" class="notice">
该组件不需要任何 props、events、slots 或实例方法。
</p>
</div>
<p v-else class="notice warn" v-text="`未找到组件 ${name} 的 API 数据,请检查 components.ts 中的 name 与 entry 是否正确`" />
</template>
<script lang="ts" setup>
import { computed } from "vue";
import apiMap from "virtual:timi-api";
/**
* 组件 API 表格。
*
* 数据来自构建期 `vue-docgen-api` 对组件源码的解析结果,
* 无需在 markdown 中手写 props / events / slots 表格。
* 某个分区没有内容时整段不渲染,避免出现空表。
*/
const props = defineProps<{
/** 组件名,需与 components.ts 中的 name 一致。 */
name: string;
}>();
const api = computed(() => apiMap[props.name]);
const isEmpty = computed(() => {
if (!api.value) {
return false;
}
const { props: propRows, events, slots, exposes } = api.value;
return propRows.length === 0 && events.length === 0 && slots.length === 0 && exposes.length === 0;
});
</script>
<style lang="less" scoped>
.tui-api {
section {
margin-bottom: 1.5rem;
&:last-child {
margin-bottom: 0;
}
}
h3 {
margin: 1.5rem 0 .75rem;
font-size: 1rem;
}
.name {
white-space: nowrap;
}
.required {
margin-left: .125rem;
color: var(--vp-c-danger-1);
}
.notice {
margin: 1rem 0;
padding: .75rem 1rem;
font-size: .875rem;
border-radius: .5rem;
color: var(--vp-c-text-2);
background: var(--vp-c-bg-soft);
&.warn {
color: var(--vp-c-warning-1);
background: var(--vp-c-warning-soft);
}
}
}
</style>
@@ -0,0 +1,149 @@
<template>
<div v-if="api" class="tui-utils-api">
<section v-if="api.members.length > 0">
<h3>成员</h3>
<table>
<thead>
<tr>
<th>名称</th>
<th>签名</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr v-for="row in api.members" :key="row.name">
<td class="name"><code v-text="row.name" /></td>
<td class="signature"><code v-text="row.signature" /></td>
<td class="desc" v-text="row.description" />
</tr>
</tbody>
</table>
</section>
<section v-if="api.types.length > 0">
<h3>类型</h3>
<div v-for="item in api.types" :key="item.name" class="type">
<p class="head">
<code v-text="item.name" />
<span class="kind" v-text="item.kind" />
</p>
<p v-if="item.description" class="desc" v-text="item.description" />
<pre class="body"><code v-text="item.text" /></pre>
</div>
</section>
<p v-if="isEmpty && !api.parsed" class="notice warn">
未能从源码中解析出该模块的成员,请检查文件是否为合法的 TypeScript 模块。
</p>
<p v-else-if="isEmpty" class="notice">
该模块没有可列出的导出成员。
</p>
</div>
<p v-else class="notice warn" v-text="`未找到模块 ${name} 的数据,请检查 utils.ts 中的 name 与 entry 是否正确`" />
</template>
<script lang="ts" setup>
import { computed } from "vue";
import utilsMap from "virtual:timi-utils";
/**
* 工具模块成员表。
*
* 数据由构建期 `plugins/tsdocgen.ts` 解析 TS 源码得到,通过虚拟模块
* `virtual:timi-utils` 交给页面渲染。`vue-docgen-api` 只支持 SFC,
* 因此工具模块走的是 TypeScript 自带的 AST 解析。
*/
const props = defineProps<{
/** 模块名,需与 utils.ts 中的 name 一致。 */
name: string;
}>();
const api = computed(() => utilsMap[props.name]);
const isEmpty = computed(() => {
if (!api.value) {
return false;
}
return api.value.members.length === 0 && api.value.types.length === 0;
});
</script>
<style lang="less" scoped>
.tui-utils-api {
section {
margin-bottom: 1.5rem;
&:last-child {
margin-bottom: 0;
}
}
h3 {
margin: 1.5rem 0 .75rem;
font-size: 1rem;
}
.name,
.signature {
white-space: nowrap;
}
// 说明里保留了 JSDoc 的段落结构
.desc {
white-space: pre-line;
}
.type {
margin-bottom: 1rem;
&:last-child {
margin-bottom: 0;
}
.head {
display: flex;
gap: .5rem;
align-items: center;
margin: 0 0 .25rem;
}
.desc {
margin: 0 0 .5rem;
font-size: .875rem;
color: var(--vp-c-text-2);
}
.kind {
padding: .0625rem .375rem;
font-size: .75rem;
border-radius: .25rem;
color: var(--vp-c-text-2);
background: var(--vp-c-bg-soft);
}
.body {
margin: 0;
padding: .75rem 1rem;
overflow-x: auto;
font-size: .8125rem;
border-radius: .5rem;
background: var(--vp-c-bg-soft);
}
}
.notice {
margin: 1rem 0;
padding: .75rem 1rem;
font-size: .875rem;
border-radius: .5rem;
color: var(--vp-c-text-2);
background: var(--vp-c-bg-soft);
&.warn {
color: var(--vp-c-warning-1);
background: var(--vp-c-warning-soft);
}
}
}
</style>
@@ -0,0 +1,184 @@
<template>
<div class="tui-demo">
<section class="stage">
<slot />
</section>
<section class="meta">
<div class="info">
<p v-if="title" class="title" v-text="title" />
<p v-if="description" class="desc" v-text="description" />
</div>
<div class="actions">
<button
class="action"
type="button"
@click="handleCopy"
v-text="copied ? '已复制' : '复制代码'"
/>
<button
class="action"
type="button"
@click="toggleExpanded"
v-text="expanded ? '收起代码' : '展开代码'"
/>
</div>
</section>
<section v-show="expanded" class="source">
<div class="language-vue" v-html="sourceHtml" />
</section>
</div>
</template>
<script lang="ts" setup>
import { computed, onUnmounted, ref } from "vue";
/**
* 预览容器。
*
* props 契约由 `@vitepress-demo-preview/plugin` 决定,它把 markdown 里的
* `:::preview` 容器编译成 `<demo-preview>` 标签并传入下列属性:
* - `code`:`encodeURI` 处理过的组件源码
* - `showCode`:`encodeURIComponent` 处理过的高亮 HTML
*
* 这里刻意不依赖官方容器,也不引入任何 UI 库(timi-web 本身不依赖 TDesign 等框架),
* 只用原生元素配合 VitePress 的 CSS 变量,深色模式随之自动适配。
*/
const props = withDefaults(defineProps<{
/** 源码原文,经 encodeURI 编码。 */
code?: string;
/** 高亮后的源码 HTML,经 encodeURIComponent 编码。 */
showCode?: string;
/** 演示标题,来自 `:::preview` 后方第一段文字。 */
title?: string;
/** 演示描述,来自 `:::preview` 中 `||` 之后的内容。 */
description?: string;
}>(), {
code: "",
showCode: "",
title: "",
description: ""
});
/** 源码区是否展开,默认收起以保持文档阅读节奏。 */
const expanded = ref(false);
/** 复制成功后的短暂反馈。 */
const copied = ref(false);
let copiedTimer: ReturnType<typeof setTimeout> | null = null;
const sourceHtml = computed(() => decodeURIComponent(props.showCode));
const sourceText = computed(() => decodeURIComponent(props.code));
/** 复制源码到剪贴板,clipboard 不可用时保持原按钮文案。 */
async function handleCopy() {
try {
await navigator.clipboard.writeText(sourceText.value);
} catch {
return;
}
copied.value = true;
if (copiedTimer !== null) {
clearTimeout(copiedTimer);
}
copiedTimer = setTimeout(() => {
copied.value = false;
copiedTimer = null;
}, 1500);
}
function toggleExpanded() {
expanded.value = !expanded.value;
}
onUnmounted(() => {
if (copiedTimer !== null) {
clearTimeout(copiedTimer);
}
});
</script>
<style lang="less" scoped>
.tui-demo {
overflow: hidden;
border: 1px solid var(--vp-c-divider);
border-radius: .75rem;
background: var(--vp-c-bg);
.stage {
padding: 2rem;
}
.meta {
display: flex;
gap: 1rem;
align-items: center;
justify-content: space-between;
padding: .75rem 1.5rem;
border-top: 1px solid var(--vp-c-divider);
background: var(--vp-c-bg-soft);
}
.info {
min-width: 0;
}
.title {
margin: 0;
font-size: .875rem;
font-weight: 600;
color: var(--vp-c-text-1);
}
.desc {
margin: .25rem 0 0;
font-size: .75rem;
line-height: 1.5;
color: var(--vp-c-text-2);
}
.actions {
display: flex;
flex: none;
gap: .25rem;
}
.action {
padding: .25rem .5rem;
font-size: .75rem;
cursor: pointer;
border: none;
border-radius: .25rem;
color: var(--vp-c-text-2);
background: transparent;
&:hover {
color: var(--vp-c-brand-1);
background: var(--vp-c-default-soft);
}
}
.source {
border-top: 1px solid var(--vp-c-divider);
:deep(div[class*="language-"]) {
margin: 0;
border-radius: 0;
}
}
}
@media (max-width: 48rem) {
.tui-demo {
.stage {
padding: 1rem;
}
.meta {
align-items: flex-start;
flex-direction: column;
padding: .75rem 1rem;
}
}
}
</style>
+24
View File
@@ -0,0 +1,24 @@
/// <reference types="vitepress/client" />
/** 构建期由 vue-docgen-api 解析生成的组件 API 数据。 */
declare module "virtual:timi-api" {
import type { ComponentApiMap } from "../api-types";
const apiMap: ComponentApiMap;
export default apiMap;
}
/** 构建期由 TypeScript AST 解析生成的工具模块数据。 */
declare module "virtual:timi-utils" {
import type { UtilApiMap } from "../utils-types";
const utilsMap: UtilApiMap;
export default utilsMap;
}
declare module "*.vue" {
import type { DefineComponent } from "vue";
const component: DefineComponent<Record<string, unknown>, Record<string, unknown>, unknown>;
export default component;
}
+28
View File
@@ -0,0 +1,28 @@
import DefaultTheme from "vitepress/theme";
import type { App } from "vue";
import "./styles/index.less";
import DemoPreview from "./containers/DemoPreview.vue";
import ApiTable from "./components/ApiTable.vue";
import UtilsApiTable from "./components/UtilsApiTable.vue";
/**
* 文档站主题。
*
* 刻意不在这里 import timi-web:组件的依赖(Prism、ResizeObserver、document 等)
* 只适合在浏览器里运行,而演示统一以 `clientOnly` 延迟渲染,
* 让 timi-web 只出现在演示的动态导入里,SSR 阶段完全不加载它。
*
* 同理也不注册 `v-popup` 全局指令——需要它的演示在 `<script setup>` 里
* 导入 `VPopup` 即可,编译器会把它解析为局部绑定。
*/
export default {
extends: DefaultTheme,
enhanceApp({ app }: { app: App }) {
app.component("demo-preview", DemoPreview);
app.component("api-table", ApiTable);
app.component("utils-api", UtilsApiTable);
}
};
+18
View File
@@ -0,0 +1,18 @@
/**
* 文档站全局样式。
*
* 只处理 VitePress 正文与演示容器、API 表格的交界处;
* 组件自身的样式一律各自 scoped,避免相互污染。
*/
.vp-doc {
// 演示容器与正文的呼吸感
.tui-demo {
margin: 1rem 0;
}
// API 表格里的类型与默认值不换行,避免长签名把列挤变形
table code {
white-space: nowrap;
}
}
+60
View File
@@ -0,0 +1,60 @@
/**
* 工具模块的文档数据类型。
*
* 与 `api-types.ts` 分离,因为两者来源不同:
* 组件由 `vue-docgen-api` 解析 SFC,工具模块由 `plugins/tsdocgen.ts`
* 解析 TS 模块,二者拿到的结构并不一致。
*/
/** 工具模块成员表中的一行。 */
export interface UtilMemberRow {
/** 成员名。 */
name: string;
/** 类型签名,直接取自源码中的类型标注;静态成员会带 `static` 前缀。 */
signature: string;
/** 注释说明,取自源码 JSDoc,未写注释时为空。 */
description: string;
}
/** 工具模块导出的类型定义。 */
export interface UtilTypeRow {
/** 类型名。 */
name: string;
/** 类型种类,如「类型别名」「接口」「枚举」。 */
kind: string;
/** 类型定义原文,多行时原样保留。 */
text: string;
/** 注释说明。 */
description: string;
}
/** 一个工具模块解析完成后的数据。 */
export interface UtilApi {
/** 模块名,与 utils.ts 中的 name 一致。 */
name: string;
/** 模块或类自身的注释说明。 */
description: string;
/**
* 源码是否解析成功。
*
* 用来区分「解析失败」与「模块本身没有可列出的成员」,
* 两者都会得到空数组,但提示语不同。
*/
parsed: boolean;
members: UtilMemberRow[];
types: UtilTypeRow[];
}
/** 全部工具模块的 API 数据,键为模块名。 */
export type UtilApiMap = Record<string, UtilApi>;
/** 生成空的工具数据,用于解析失败时兜底。 */
export function createEmptyUtilApi(name: string): UtilApi {
return {
name,
description: "",
parsed: false,
members: [],
types: []
};
}
+132
View File
@@ -0,0 +1,132 @@
/**
* 工具模块元数据清单。
*
* 与 `components.ts` 同构:侧边栏导航、`plugins/tsdocgen.ts` 的解析目标、
* 页面里的 `<utils-api />` 查询键都由这里驱动,新增模块只需追加一项。
*
* 这里只收录面向使用者的工具。`IconMapper`、`Popup.ts` 的 DOM 工具函数、
* `TDesignMessage` 属于内部实现或已在对应组件页说明,不单独建页;
* `timi-ts` 转出的能力源头在另一个仓库,只在总览页做指引。
*/
/** 分类展示顺序即数组顺序。 */
export const UTIL_CATEGORY_LIST = [
"状态持久化",
"Web 工具",
"尺寸与滚动",
"渲染与高亮",
"指令"
] as const;
export type UtilCategory = (typeof UTIL_CATEGORY_LIST)[number];
export interface UtilMeta {
/** 模块导出名,同时是 utils-api 的查询键。 */
name: string;
/** 文档与侧边栏展示的中文标题。 */
title: string;
/** 一句话功能描述。 */
description: string;
/** 所属分类。 */
category: UtilCategory;
/** 模块源码,相对仓库根目录。 */
entry: string;
/** 文档路径覆盖,默认取文件名转短横线。 */
slug?: string;
}
export const UTIL_LIST: UtilMeta[] = [
// ---------- 状态持久化 ----------
{
name: "Storage",
title: "Storage 本地存储",
description: "localStorage 的读写封装,自动区分 JSON 与普通字符串。",
category: "状态持久化",
entry: "src/utils/Storage.ts"
},
{
name: "Cooker",
title: "Cooker Cookie 读写",
description: "Cookie 的写入、读取与删除,写入时可指定毫秒级有效期。",
category: "状态持久化",
entry: "src/utils/Cooker.ts"
},
// ---------- Web 工具 ----------
{
name: "WebToolkit",
title: "WebToolkit Web 工具",
description: "文件判定、DOM 解析、FormData 扁平化、浏览器下载与组件安装。",
category: "Web 工具",
entry: "src/utils/WebToolkit.ts"
},
// ---------- 尺寸与滚动 ----------
{
name: "Resizer",
title: "Resizer 窗口尺寸监听",
description: "注册窗口缩放回调,回调里直接拿到当前视口宽高。",
category: "尺寸与滚动",
entry: "src/utils/Resizer.ts"
},
{
name: "Scroller",
title: "Scroller 滚动控制",
description: "读取滚动状态、注册触底加载与平滑滚动定位。",
category: "尺寸与滚动",
entry: "src/utils/Scroller.ts"
},
// ---------- 渲染与高亮 ----------
{
name: "Prism",
title: "Prism 代码高亮",
description: "Prism 语言名归一化与已支持的语言清单。",
category: "渲染与高亮",
entry: "src/utils/Prism.ts"
},
{
name: "Markdown",
title: "Markdown 解析器",
description: "Markdown 转 HTML 的单例,内置 Prism 高亮与自定义渲染规则。",
category: "渲染与高亮",
entry: "src/utils/Markdown.ts"
},
// ---------- 指令 ----------
{
name: "VDraggable",
title: "VDraggable 拖拽指令",
description: "同时支持鼠标与触控的拖拽指令,位置交给回调处理。",
category: "指令",
entry: "src/utils/directives/Draggable.ts"
}
];
/**
* 文档路径与路由片段。
*
* 取源码文件名去掉扩展名后转短横线,`WebToolkit` 得到 `web-toolkit`。
* 文件名与期望路径不一致时用 `slug` 覆盖。
*/
export function toUtilSlug(meta: UtilMeta): string {
if (meta.slug) {
return meta.slug;
}
const fileName = meta.entry.split("/").pop() ?? meta.name;
const baseName = fileName.replace(/\.\w+$/, "");
return baseName.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
}
/** 工具文档页的站内绝对路径。 */
export function toUtilLink(meta: UtilMeta): string {
return `/utils/${toUtilSlug(meta)}`;
}
/** 按分类分组,保持 UTIL_CATEGORY_LIST 的声明顺序。 */
export function groupUtilsByCategory(): Array<{ category: UtilCategory; items: UtilMeta[] }> {
return UTIL_CATEGORY_LIST.map(category => ({
category,
items: UTIL_LIST.filter(item => item.category === category)
})).filter(group => group.items.length > 0);
}