diff --git a/.gitignore b/.gitignore index e000ab1..979671f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,11 +1,16 @@ /.npmrc /.eslintrc-auto-import.json /components.d.ts -/examples/auto-imports.d.ts +/auto-imports.d.ts /CLAUDE.md /AGENTS.md /.claude +# 文档站 +/docs/.vitepress/cache +/docs/.vitepress/dist +/docs/.npmrc + # Logs logs *.log diff --git a/README.md b/README.md index dfbafb6..f4f3d34 100644 --- a/README.md +++ b/README.md @@ -12,9 +12,39 @@ Web 专属方法使用 `WebToolkit`,通用方法使用 `timi-ts` 导出的 `To import { Text, Toolkit } from "timi-web"; ``` +## 文档与演示 + +组件演示与 API 文档由 VitePress 驱动,源码位于 `docs/`。它作为独立子包维护,依赖版本与根项目隔离(根项目用 Vite 8,文档站需要 VitePress 自带的 Vite 5)。 + +首次使用先安装文档站依赖: + +```bash +pnpm -C docs install +``` + +启动演示站(默认 http://localhost:3003): + +```bash +pnpm run dev +``` + +构建静态站点: + +```bash +pnpm run build:doc +``` + +演示直接引用 `src` 源码,改动组件即可热更新;API 表格由 `vue-docgen-api` 在构建期解析组件源码生成,无需手写。新增组件的完整步骤见文档站的「演示与文档约定」页面。 + ## 开发 ```bash pnpm install pnpm run build ``` + +## 测试 + +```bash +pnpm test +``` diff --git a/docs/.vitepress/api-types.ts b/docs/.vitepress/api-types.ts new file mode 100644 index 0000000..d7cff6d --- /dev/null +++ b/docs/.vitepress/api-types.ts @@ -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; + +/** 生成一个空的 API 数据,用于解析失败时兜底,保证文档站不因单个组件而白屏。 */ +export function createEmptyApi(name: string): ComponentApi { + return { + name, + description: "", + parsed: false, + props: [], + events: [], + slots: [], + exposes: [] + }; +} diff --git a/docs/.vitepress/components.ts b/docs/.vitepress/components.ts new file mode 100644 index 0000000..fb2d3b9 --- /dev/null +++ b/docs/.vitepress/components.ts @@ -0,0 +1,179 @@ +/** + * 组件元数据清单。 + * + * 这是文档站的唯一数据源,三处消费它: + * - `config.ts` 生成侧边栏导航 + * - `plugins/docgen.ts` 按 `entry` 定位源码并交给 vue-docgen-api 解析 + * - 页面内的 `` 按 `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); +} diff --git a/docs/.vitepress/config.ts b/docs/.vitepress/config.ts new file mode 100644 index 0000000..1f623ec --- /dev/null +++ b/docs/.vitepress/config.ts @@ -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] + } + } + } +}); diff --git a/docs/.vitepress/plugins/docgen.ts b/docs/.vitepress/plugins/docgen.ts new file mode 100644 index 0000000..bdb9046 --- /dev/null +++ b/docs/.vitepress/plugins/docgen.ts @@ -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 { + 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" }); + } + } + }; +} diff --git a/docs/.vitepress/plugins/tsdocgen.ts b/docs/.vitepress/plugins/tsdocgen.ts new file mode 100644 index 0000000..205765d --- /dev/null +++ b/docs/.vitepress/plugins/tsdocgen.ts @@ -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" }); + } + } + }; +} diff --git a/docs/.vitepress/theme/components/ApiTable.vue b/docs/.vitepress/theme/components/ApiTable.vue new file mode 100644 index 0000000..1d558cc --- /dev/null +++ b/docs/.vitepress/theme/components/ApiTable.vue @@ -0,0 +1,162 @@ + + + + + diff --git a/docs/.vitepress/theme/components/UtilsApiTable.vue b/docs/.vitepress/theme/components/UtilsApiTable.vue new file mode 100644 index 0000000..33ffe31 --- /dev/null +++ b/docs/.vitepress/theme/components/UtilsApiTable.vue @@ -0,0 +1,149 @@ + + + + + diff --git a/docs/.vitepress/theme/containers/DemoPreview.vue b/docs/.vitepress/theme/containers/DemoPreview.vue new file mode 100644 index 0000000..499beff --- /dev/null +++ b/docs/.vitepress/theme/containers/DemoPreview.vue @@ -0,0 +1,184 @@ + + + + + diff --git a/docs/.vitepress/theme/env.d.ts b/docs/.vitepress/theme/env.d.ts new file mode 100644 index 0000000..21f48e9 --- /dev/null +++ b/docs/.vitepress/theme/env.d.ts @@ -0,0 +1,24 @@ +/// + +/** 构建期由 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, unknown>; + export default component; +} diff --git a/docs/.vitepress/theme/index.ts b/docs/.vitepress/theme/index.ts new file mode 100644 index 0000000..6d47742 --- /dev/null +++ b/docs/.vitepress/theme/index.ts @@ -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` 全局指令——需要它的演示在 ` + + diff --git a/docs/demos/captcha/basic.vue b/docs/demos/captcha/basic.vue new file mode 100644 index 0000000..55430bd --- /dev/null +++ b/docs/demos/captcha/basic.vue @@ -0,0 +1,68 @@ + + + + + diff --git a/docs/demos/contact-number/basic.vue b/docs/demos/contact-number/basic.vue new file mode 100644 index 0000000..5b62017 --- /dev/null +++ b/docs/demos/contact-number/basic.vue @@ -0,0 +1,47 @@ + + + + + diff --git a/docs/demos/copyright/basic.vue b/docs/demos/copyright/basic.vue new file mode 100644 index 0000000..86b9670 --- /dev/null +++ b/docs/demos/copyright/basic.vue @@ -0,0 +1,23 @@ + + + + + diff --git a/docs/demos/description-grid/basic.vue b/docs/demos/description-grid/basic.vue new file mode 100644 index 0000000..3f2aa66 --- /dev/null +++ b/docs/demos/description-grid/basic.vue @@ -0,0 +1,35 @@ + + + + + diff --git a/docs/demos/empty-tips/basic.vue b/docs/demos/empty-tips/basic.vue new file mode 100644 index 0000000..8f0e631 --- /dev/null +++ b/docs/demos/empty-tips/basic.vue @@ -0,0 +1,28 @@ + + + + + diff --git a/docs/demos/flower-fall/basic.vue b/docs/demos/flower-fall/basic.vue new file mode 100644 index 0000000..77460d7 --- /dev/null +++ b/docs/demos/flower-fall/basic.vue @@ -0,0 +1,51 @@ + + + + + diff --git a/docs/demos/hover-popup/basic.vue b/docs/demos/hover-popup/basic.vue new file mode 100644 index 0000000..3e4b722 --- /dev/null +++ b/docs/demos/hover-popup/basic.vue @@ -0,0 +1,79 @@ + + + + + diff --git a/docs/demos/icon/basic.vue b/docs/demos/icon/basic.vue new file mode 100644 index 0000000..e3f2543 --- /dev/null +++ b/docs/demos/icon/basic.vue @@ -0,0 +1,79 @@ + + + + + diff --git a/docs/demos/loading/basic.vue b/docs/demos/loading/basic.vue new file mode 100644 index 0000000..d0dff78 --- /dev/null +++ b/docs/demos/loading/basic.vue @@ -0,0 +1,52 @@ + + + + + diff --git a/docs/demos/markdown-editor/basic.vue b/docs/demos/markdown-editor/basic.vue new file mode 100644 index 0000000..7c39e75 --- /dev/null +++ b/docs/demos/markdown-editor/basic.vue @@ -0,0 +1,33 @@ + + + + + diff --git a/docs/demos/markdown-view/basic.vue b/docs/demos/markdown-view/basic.vue new file mode 100644 index 0000000..09fda21 --- /dev/null +++ b/docs/demos/markdown-view/basic.vue @@ -0,0 +1,48 @@ + + + + + diff --git a/docs/demos/passtime-label/basic.vue b/docs/demos/passtime-label/basic.vue new file mode 100644 index 0000000..ccb02f8 --- /dev/null +++ b/docs/demos/passtime-label/basic.vue @@ -0,0 +1,52 @@ + + + + + diff --git a/docs/demos/popup/basic.vue b/docs/demos/popup/basic.vue new file mode 100644 index 0000000..5855fd8 --- /dev/null +++ b/docs/demos/popup/basic.vue @@ -0,0 +1,65 @@ + + + + + diff --git a/docs/demos/utils/cooker.vue b/docs/demos/utils/cooker.vue new file mode 100644 index 0000000..67436db --- /dev/null +++ b/docs/demos/utils/cooker.vue @@ -0,0 +1,106 @@ + + + + + diff --git a/docs/demos/utils/draggable.vue b/docs/demos/utils/draggable.vue new file mode 100644 index 0000000..83987dc --- /dev/null +++ b/docs/demos/utils/draggable.vue @@ -0,0 +1,103 @@ + + + + + diff --git a/docs/demos/utils/markdown.vue b/docs/demos/utils/markdown.vue new file mode 100644 index 0000000..6f3c7d5 --- /dev/null +++ b/docs/demos/utils/markdown.vue @@ -0,0 +1,64 @@ +