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
+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" });
}
}
};
}