This commit is contained in:
Timi
2026-10-30 14:28:27 +08:00
parent ef71681bd5
commit 1909587a0b
68 changed files with 6616 additions and 772 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: []
};
}
+149
View File
@@ -0,0 +1,149 @@
/**
* 组件元数据清单。
*
* 这是文档站的唯一数据源,三处消费它:
* - `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;
}
export const COMPONENT_LIST: ComponentMeta[] = [
// ---------- 布局组件 ----------
{
name: "RootLayout",
title: "RootLayout 根布局",
description: "提供页面级骨架与统一留白,承载顶部区域与主内容。",
category: "布局组件",
entry: "src/components/root-layout/index.vue"
},
{
name: "AdminLayout",
title: "AdminLayout 管理台布局",
description: "侧边菜单、顶部栏与内容区三区合一的后台骨架,支持菜单折叠。",
category: "布局组件",
entry: "src/components/admin-layout/index.vue"
},
// ---------- 编辑器组件 ----------
{
name: "CodeEditor",
title: "CodeEditor 代码编辑器",
description: "带行号、语法高亮与查找替换的代码输入框。",
category: "编辑器组件",
entry: "src/components/code-editor/index.vue"
},
{
name: "TiptapEditor",
title: "TiptapEditor 富文本编辑器",
description: "基于 Tiptap 的富文本编辑器,内置媒体、表格、链接与代码块等工具栏能力。",
category: "编辑器组件",
entry: "src/components/tiptap-editor/index.vue"
},
{
name: "TiptapView",
title: "TiptapView 富文本视图",
description: "Tiptap 内容的只读渲染视图,与编辑器共用同一套样式。",
category: "编辑器组件",
entry: "src/components/tiptap-view/index.vue"
},
{
name: "ArticleEditor",
title: "ArticleEditor 文章编辑器",
description: "以 Article 为数据模型,按正文类型切换纯文本、Markdown 与富文本编辑。",
category: "编辑器组件",
entry: "src/components/article-editor/index.vue"
},
{
name: "ArticleView",
title: "ArticleView 文章视图",
description: "按 Article 的正文类型渲染标题、正文与附件列表。",
category: "编辑器组件",
entry: "src/components/article-view/index.vue"
},
{
name: "NotifyEditor",
title: "NotifyEditor 通知编辑器",
description: "以 NotifyDetail 为数据模型的通知编辑表单,复用文章编辑器能力。",
category: "编辑器组件",
entry: "src/components/notify-editor/index.vue"
},
{
name: "NotifyView",
title: "NotifyView 通知视图",
description: "渲染通知主题、状态与正文内容。",
category: "编辑器组件",
entry: "src/components/notify-view/index.vue"
},
// ---------- 用户组件 ----------
{
name: "AuthorizeForm",
title: "AuthorizeForm 授权表单",
description: "登录与注册合一的授权表单,验证码、请求与回调全部由外部注入。",
category: "用户组件",
entry: "src/components/authorize-form/index.vue"
},
{
name: "UserProfile",
title: "UserProfile 用户资料",
description: "展示用户头像、昵称与等级信息,支持点击展开资料弹窗。",
category: "用户组件",
entry: "src/components/user-profile/index.vue"
},
{
name: "UserProfilePopup",
title: "UserProfilePopup 用户资料弹窗",
description: "用户资料卡弹窗,由 UserProfile 唤起,也可独立使用。",
category: "用户组件",
entry: "src/components/user-profile/popup/index.vue"
},
{
name: "UserLevel",
title: "UserLevel 用户等级",
description: "按等级值渲染等级图标与文案,等级规则可外部覆盖。",
category: "用户组件",
entry: "src/components/user-level/index.vue"
}
];
/** PascalCase 转 kebab-case,用于推导文档路径与路由。 */
export function toKebabCase(name: string): string {
return name.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
}
/** 组件文档页的站内绝对路径。 */
export function toDocLink(meta: ComponentMeta): string {
return `/components/${toKebabCase(meta.name)}`;
}
/** 按分类分组,保持 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);
}
+131
View File
@@ -0,0 +1,131 @@
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 { docgenPlugin } from "./plugins/docgen";
import { timiWebSsrStub } from "./plugins/ssr-stub";
/** `__dirname` 由 VitePress 打包配置时注入,指向 `docs/.vitepress`。 */
const docsDir = resolve(__dirname, "..");
/** 仓库根目录,组件源码位于它的 `src` 下。 */
const repoRoot = resolve(docsDir, "..");
/** timi-web 仓库目录,docs 通过 link 依赖它。 */
const timiWebRoot = resolve(repoRoot, "../timi-web");
/**
* 源码引用别名。
*
* demo 组件直接引用 `src` 源码而非构建产物,改组件即可热更新文档。
* markdown 里的 `:::preview` 也共用这份别名来定位演示文件。
*/
const alias = {
"~": resolve(repoRoot, "src"),
"timi-tdesign-pc": resolve(repoRoot, "src/index.ts"),
"timi-web/editor": resolve(timiWebRoot, "src/editor/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)
}))
}));
export default defineConfig({
title: "timi-tdesign-pc",
description: "PC 端 TDesign 组件库的演示与 API 文档",
lang: "zh-CN",
cleanUrls: true,
themeConfig: {
nav: [
{ text: "指南", link: "/guide/" },
{ text: "场景", link: "/scenarios/editor" },
{ text: "组件", link: "/components/" }
],
sidebar: [
{
text: "指南",
items: [
{ text: "快速开始", link: "/guide/" },
{ text: "演示与文档约定", link: "/guide/demo" }
]
},
{
text: "场景示例",
collapsed: false,
items: [
{ text: "编辑器能力总览", link: "/scenarios/editor" },
{ text: "文章编辑与预览", link: "/scenarios/article" },
{ text: "通知编辑与预览", link: "/scenarios/notify" }
]
},
...componentSidebar
],
outline: {
level: [2, 3],
label: "本页目录"
},
search: {
provider: "local"
},
docFooter: {
prev: "上一篇",
next: "下一篇"
},
darkModeSwitchLabel: "主题",
sidebarMenuLabel: "目录",
returnToTopLabel: "回到顶部",
lastUpdated: {
text: "最后更新于"
}
},
markdown: {
theme: {
light: "vitesse-light",
dark: "vitesse-dark"
},
lineNumbers: true,
config(md) {
// 组件几乎都依赖浏览器 API(Tiptap、Prism、剪贴板等),
// 统一开启 clientOnly 交给浏览器渲染,避免 SSR 阶段报错。
md.use(componentPreview, { clientOnly: true, alias });
md.use(containerPreview, { clientOnly: true, alias });
}
},
vite: {
resolve: {
alias
},
plugins: [
// 必须最先执行:SSR 阶段拦截 timi-web,否则整个构建无法通过。
timiWebSsrStub(docsDir),
docgenPlugin(repoRoot),
// src 源码依赖自动导入(内部没有任何一处显式 import vue),
// 这里仅为其提供支持;docs 自身的代码一律显式导入。
AutoImport({
imports: ["vue"],
dts: false
})
],
server: {
port: 3004,
host: true,
fs: {
// demo 需要读取 docs 之外的 src 与 timi-web 源码。
allow: [repoRoot, timiWebRoot]
}
}
}
});
+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" });
}
}
};
}
+141
View File
@@ -0,0 +1,141 @@
import { existsSync, readFileSync } from "node:fs";
import { resolve } from "node:path";
import type { Plugin } from "vite";
/** 虚拟 stub 模块标识。 */
const STUB_ID = "\0timi-web-ssr-stub";
/** 被 stub 的模块说明符。 */
const STUBBED_MODULES = new Set(["timi-web", "timi-web/editor"]);
/**
* SSR 阶段必须存在的具名导出。
*
* 这是对 `src` 与 `docs` 中所有 `timi-web` / `timi-web/editor` 值导入取并集得到的,
* 是 stub 的保底名单;若构建产物可读,`collectExportNames` 会在此基础上补全全部导出。
*
* 注意:demo 组件虽然以 `clientOnly` 延迟渲染,但它们的动态导入仍会进入 SSR 的模块图,
* 因此 demo 里用到的 `Popup` 也必须在这里。
*/
const REQUIRED_EXPORTS = [
// ---------- timi-web ----------
"VPopup",
"Popup",
"Icon",
"Copyright",
"Captcha",
"MarkdownView",
"MarkdownEditor",
"Toolkit",
"WebToolkit",
"PopupType",
// 仅出现在类型位置,esbuild 通常会摇掉;保留以免转换策略变化时构建失败。
"PopupConfig",
// ---------- timi-web/editor ----------
"findTextMatches",
"replaceAllText",
"replaceMatchText",
"buildSearchRegex",
"highlightCode",
"resolveCodeEditorKeydown",
"resolvePrismLanguage",
"useTiptapEditor",
"useTiptapView",
"buildHeadingOptions",
"formatPaddingValue",
"normalizeSliderValue",
"ATTACHMENT_ID_ATTR",
"TEMP_FILE_ID_ATTR",
"LOCAL_MEDIA_ID_PREFIX",
"isLocalMediaId",
"normalizeContent",
"TABLE_PICKER_SIZE"
];
/** 从构建产物中提取具名导出,让 stub 自动跟上上游变化。 */
function collectExportNames(distFile: string): Set<string> {
const names = new Set<string>(REQUIRED_EXPORTS);
if (!existsSync(distFile)) {
return names;
}
try {
const source = readFileSync(distFile, "utf-8");
for (const match of source.matchAll(/export\s*\{([^}]*)\}/g)) {
for (const part of match[1].split(",")) {
const bits = part.trim().split(/\s+as\s+/);
const name = (bits[1] ?? bits[0]).trim();
if (/^[A-Za-z_$][\w$]*$/.test(name)) {
names.add(name);
}
}
}
} catch {
// 读取失败时退回保底名单,不影响构建。
}
return names;
}
/** 生成 stub 模块源码:每个导出都是可调用、可解构、可当插件安装的空实现。 */
function buildStubSource(names: Set<string>): string {
const named = [...names]
.filter(name => name !== "default")
.map(name => `export const ${name} = stub;`)
.join("\n");
return `const stub = new Proxy(function () {}, {
get(target, key) {
if (key === Symbol.toPrimitive || key === "valueOf" || key === "toString") {
return () => "";
}
return stub;
},
apply() {
return stub;
},
construct() {
return {};
}
});
export default stub;
${named}
`;
}
/**
* 在 SSR 阶段把 timi-web 替换为空实现。
*
* timi-web 的构建产物在模块顶层就访问 `window` 并启动 Prism 自动高亮定时器,
* 在 Node 中 import 会直接抛错,导致 VitePress 的 SSR 构建必然失败。
*
* 而文档站里真正需要 timi-web 的只有 demo 组件,它们全部通过 `clientOnly` 延迟到浏览器渲染,
* SSR 阶段只需要「能 import 且不报错」,因此这里返回一个 Proxy 空实现。
* 客户端构建不受影响,`options.ssr` 为 false 时照常解析到真实模块。
* @param docsDir docs 目录绝对路径,用于定位 timi-web 构建产物
*/
export function timiWebSsrStub(docsDir: string): Plugin {
const distFile = resolve(docsDir, "node_modules/timi-web/dist/timi-web.mjs");
let stubSource: string | null = null;
return {
name: "timi-web-ssr-stub",
enforce: "pre",
resolveId(source, importer, options) {
// 只拦截精确的包名,`timi-web/style.css` 等子路径照常交给 Vite 处理。
if (options?.ssr && STUBBED_MODULES.has(source)) {
return STUB_ID;
}
return null;
},
load(id) {
if (id !== STUB_ID) {
return null;
}
if (stubSource === null) {
stubSource = buildStubSource(collectExportNames(distFile));
}
return stubSource;
}
};
}
@@ -0,0 +1,156 @@
<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>
<t-alert
v-if="isEmpty && !api.parsed"
theme="warning"
title="未能从源码中解析出 API 信息,请检查组件是否使用了 defineProps / defineEmits / defineExpose"
/>
<t-alert
v-else-if="isEmpty"
theme="info"
title="该组件不需要任何 props、events、slots 或实例方法"
/>
</div>
<t-alert
v-else
theme="error"
:title="`未找到组件 ${name} 的 API 数据,请检查 components.ts 中的 name 是否与组件 defineOptions 一致`"
/>
</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(--td-error-color);
}
}
</style>
@@ -0,0 +1,148 @@
<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">
<t-button size="small" variant="text" @click="handleCopy">
复制代码
</t-button>
<t-button size="small" variant="text" @click="toggleExpanded">
{{ expanded ? "收起代码" : "展开代码" }}
</t-button>
</div>
</section>
<section v-show="expanded" class="source">
<div class="language-vue" v-html="sourceHtml" />
</section>
</div>
</template>
<script lang="ts" setup>
import { computed, ref } from "vue";
import { MessagePlugin } from "tdesign-vue-next";
/**
* 预览容器。
*
* props 契约由 `@vitepress-demo-preview/plugin` 决定,它把 markdown 里的
* `:::preview` 容器编译成 `<demo-preview>` 标签并传入下列属性:
* - `code`:`encodeURI` 处理过的组件源码
* - `showCode`:`encodeURIComponent` 处理过的高亮 HTML
*
* 这里刻意只依赖 TDesign,不引入官方的 AntDesign / ElementPlus / NaiveUI 容器,
* 那些容器会额外带来 vue-sonner 与 floating-vue 两套 UI 库。
*/
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 sourceHtml = computed(() => decodeURIComponent(props.showCode));
const sourceText = computed(() => decodeURIComponent(props.code));
/** 复制源码到剪贴板,clipboard 不可用时提示手动复制。 */
async function handleCopy() {
try {
await navigator.clipboard.writeText(sourceText.value);
MessagePlugin.success("代码已复制到剪贴板");
} catch {
MessagePlugin.warning("当前环境不支持自动复制,请手动选择代码");
}
}
function toggleExpanded() {
expanded.value = !expanded.value;
}
</script>
<style lang="less" scoped>
.tui-demo {
overflow: hidden;
border: 1px solid var(--td-component-stroke);
border-radius: .75rem;
background: var(--td-bg-color-container);
.stage {
padding: 2rem;
}
.meta {
display: flex;
gap: 1rem;
align-items: center;
justify-content: space-between;
padding: .75rem 1.5rem;
border-top: 1px solid var(--td-component-stroke);
background: var(--td-bg-color-container-hover);
}
.info {
min-width: 0;
}
.title {
margin: 0;
font-size: .875rem;
font-weight: 600;
color: var(--td-text-color-primary);
}
.desc {
margin: .25rem 0 0;
font-size: .75rem;
line-height: 1.5;
color: var(--td-text-color-secondary);
}
.actions {
display: flex;
flex: none;
gap: .25rem;
}
.source {
border-top: 1px solid var(--td-component-stroke);
: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>
+16
View File
@@ -0,0 +1,16 @@
/// <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;
}
declare module "*.vue" {
import type { DefineComponent } from "vue";
const component: DefineComponent<Record<string, unknown>, Record<string, unknown>, unknown>;
export default component;
}
+45
View File
@@ -0,0 +1,45 @@
import DefaultTheme from "vitepress/theme";
import { watch } from "vue";
import { useData } from "vitepress";
import type { App } from "vue";
import TDesign from "tdesign-vue-next";
import TimiWebUI, { VPopup } from "timi-web";
import "tdesign-vue-next/dist/tdesign.css";
import "./styles/index.less";
import DemoPreview from "./containers/DemoPreview.vue";
import ApiTable from "./components/ApiTable.vue";
/**
* 同步深色模式。
*
* VitePress 通过 `html.dark` 切换深色,而 TDesign 依赖 `html[theme-mode="dark"]`,
* 两者不是同一套机制,不同步会导致深色模式下 TDesign 组件仍是亮色。
*/
function syncThemeMode(dark: boolean) {
if (typeof document === "undefined") {
return;
}
document.documentElement.setAttribute("theme-mode", dark ? "dark" : "light");
}
export default {
extends: DefaultTheme,
enhanceApp({ app }: { app: App }) {
// 全量注册 TDesign,演示区内所有 t-* 组件直接可用,无需额外 resolver。
app.use(TDesign);
// 组件内部大量使用 v-popup 指令与 timi-web 的全局组件。
app.use(TimiWebUI);
app.directive("popup", VPopup);
app.component("demo-preview", DemoPreview);
app.component("api-table", ApiTable);
},
setup() {
const { isDark } = useData();
watch(isDark, syncThemeMode, { immediate: true });
}
};
+18
View File
@@ -0,0 +1,18 @@
/**
* 文档站全局样式。
*
* 只处理 VitePress 正文与演示容器、API 表格的交界处;
* 组件自身的样式一律各自 scoped,避免相互污染。
*/
.vp-doc {
// 演示容器与正文的呼吸感
.tui-demo {
margin: 1rem 0;
}
// API 表格里的类型与默认值不换行,避免长签名把列挤变形
table code {
white-space: nowrap;
}
}
+30
View File
@@ -0,0 +1,30 @@
# AdminLayout 管理台布局
侧边菜单、顶部栏与内容区三区合一的后台骨架,支持扁平菜单、`t-menu-group` 分组菜单、菜单折叠,以及可选的移动端抽屉。
## 基础用法
:::preview 基础用法 || 通过 v-model 双向绑定选中项,menuItems 描述扁平侧边菜单
demo-preview=../demos/admin-layout/basic.vue
:::
传入 `menuGroups` 后,布局会按分组渲染 `t-menu-group`,此时优先使用 `menuGroups`,`menuItems` 作为兼容回退。
## 何时使用
需要标准后台管理界面骨架时使用。菜单只负责渲染与选中态,路由跳转交给菜单项的 `href`、`to` 或 `onClick`。
## 插槽
| 名称 | 说明 |
| --- | --- |
| `logo` | 顶部栏左侧的标识区域。 |
| `menu` | 顶部栏右侧的操作区域。 |
| `sidebar` | 自定义侧边栏内容;不提供时使用 `menuItems` 渲染默认菜单。 |
| 默认 | 主体内容区。 |
## API
<api-table name="AdminLayout" />
+41
View File
@@ -0,0 +1,41 @@
# ArticleEditor 文章编辑器
以 `Article` 为数据模型,按正文类型切换纯文本、Markdown 与富文本三种编辑形态。
## 基础用法
:::preview 基础用法 || 切换正文类型会同时替换内容,提交时读取完整文章
demo-preview=../demos/article-editor/basic.vue
:::
## 何时使用
需要在一套表单里同时支持多种正文格式时使用。切换只改 `contentType`,上层不需要关心具体编辑器。
## 数据模型
组件只约束三个字段,其他字段会原样保留:
| 字段 | 说明 |
| --- | --- |
| `contentType` | 正文类型,支持 `TEXT`、`MARKDOWN`、`TIP_TAP`(`TIPTAP` 为兼容写法)。 |
| `content` | 正文内容,随类型分别是纯文本、Markdown 源码或 HTML。 |
| `attachmentList` | 附件列表,元素至少包含 `id`、`name`、`url`。 |
## 附件与媒体
`uploadImage`、`uploadVideo` 负责上传,`resolveAttachmentUrl`、`resolveTempUrl` 负责把附件标识换成可访问地址。四个回调都是可选的,不传时对应能力自动降级。
## 提交内容
编辑过程中抛出的是实时值,提交时建议调用 `submit()`,它会等待富文本里未完成的上传再返回最终数据:
```ts
const article = await editorRef.value?.submit();
```
## API
<api-table name="ArticleEditor" />
+29
View File
@@ -0,0 +1,29 @@
# ArticleView 文章视图
按 `Article` 的正文类型渲染正文内容。
## 基础用法
:::preview 基础用法 || 把 contentType 换成 TEXT 或 MARKDOWN 会切换渲染分支
demo-preview=../demos/article-view/basic.vue
:::
## 何时使用
需要在详情页只读展示文章正文时使用,与 `ArticleEditor` 共用同一套数据类型。
## 渲染分支
| contentType | 渲染方式 |
| --- | --- |
| `TEXT` | 只读文本域。 |
| `MARKDOWN` | 由 `timi-web` 的 MarkdownView 渲染。 |
| `TIP_TAP` | 由 [TiptapView](/components/tiptap-view) 渲染。 |
内容为空时统一显示 `emptyText`。
## API
<api-table name="ArticleView" />
+29
View File
@@ -0,0 +1,29 @@
# AuthorizeForm 授权表单
登录与注册合一的授权表单,验证码、请求与回调全部由外部注入。
## 基础用法
:::preview 基础用法 || 演示用验证码由内联 SVG 生成,提交函数为模拟实现
demo-preview=../demos/authorize-form/basic.vue
:::
## 何时使用
需要登录与注册并排在一个面板里切换时使用。组件不发起任何请求,也不保存登录态,全部通过回调交由业务层处理。
## 注入能力
| 属性 | 说明 |
| --- | --- |
| `captcha` | 拉取验证码,返回 `{ id, data }`,`data` 会直接作为图片地址使用。 |
| `login` | 提交登录,入参含验证码与表单数据。 |
| `register` | 提交注册,入参同上。 |
表单内部只在请求成功后抛出 `loginSuccess` 或 `registerSuccess`,跳转、写入 token 等动作由外层完成。
## API
<api-table name="AuthorizeForm" />
+34
View File
@@ -0,0 +1,34 @@
# CodeEditor 代码编辑器
带行号、语法高亮与查找替换的代码输入框,基于 textarea 与 Prism 实现。
## 基础用法
:::preview 基础用法 || 通过 v-model 绑定内容,实例暴露 openSearch 等方法
demo-preview=../demos/code-editor/basic.vue
:::
## 何时使用
需要让用户输入或查看结构化代码时使用。组件不做代码校验,只负责输入、高亮与检索。
## 内容绑定
`modelValue` 与 `value` 都可作为输入源,`value` 的优先级更高。组件内部会维护一份受控副本,输入时同步抛出 `update:modelValue` 与 `change`。
## 实例方法
通过模板引用可以调用组件暴露的方法,例如打开查找栏、定位匹配项或替换内容:
```ts
import type { CodeEditorExpose } from "timi-tdesign-pc";
const editorRef = ref<CodeEditorExpose>();
editorRef.value?.openSearch(true);
```
## API
<api-table name="CodeEditor" />
+31
View File
@@ -0,0 +1,31 @@
# 组件总览
共 13 个组件,分为布局、编辑器与用户三类。
## 布局组件
| 组件 | 说明 |
| --- | --- |
| [RootLayout](/components/root-layout) | 提供页面级骨架与统一留白,承载顶部区域与主内容。 |
| [AdminLayout](/components/admin-layout) | 侧边菜单、顶部栏与内容区三区合一的后台骨架,支持菜单折叠。 |
## 编辑器组件
| 组件 | 说明 |
| --- | --- |
| [CodeEditor](/components/code-editor) | 带行号、语法高亮与查找替换的代码输入框。 |
| [TiptapEditor](/components/tiptap-editor) | 基于 Tiptap 的富文本编辑器,内置媒体、表格、链接与代码块等工具栏能力。 |
| [TiptapView](/components/tiptap-view) | Tiptap 内容的只读渲染视图,与编辑器共用同一套样式。 |
| [ArticleEditor](/components/article-editor) | 以 Article 为数据模型,按正文类型切换纯文本、Markdown 与富文本编辑。 |
| [ArticleView](/components/article-view) | 按 Article 的正文类型渲染标题、正文与附件列表。 |
| [NotifyEditor](/components/notify-editor) | 以 NotifyDetail 为数据模型的通知编辑表单,复用文章编辑器能力。 |
| [NotifyView](/components/notify-view) | 渲染通知主题、状态与正文内容。 |
## 用户组件
| 组件 | 说明 |
| --- | --- |
| [AuthorizeForm](/components/authorize-form) | 登录与注册合一的授权表单,验证码、请求与回调全部由外部注入。 |
| [UserProfile](/components/user-profile) | 展示用户头像、昵称与等级信息,支持点击展开资料弹窗。 |
| [UserProfilePopup](/components/user-profile-popup) | 用户资料卡弹窗,由 UserProfile 唤起,也可独立使用。 |
| [UserLevel](/components/user-level) | 按等级值渲染等级图标与文案,等级规则可外部覆盖。 |
+37
View File
@@ -0,0 +1,37 @@
# NotifyEditor 通知编辑器
以 `NotifyDetail` 为数据模型的通知编辑表单,正文部分复用文章编辑器。
## 基础用法
:::preview 基础用法 || 通知复用文章编辑器,同时保留主题等自有字段
demo-preview=../demos/notify-editor/basic.vue
:::
## 何时使用
需要编辑系统通知、站内信等内容时使用。通知与文章的差别只在元数据,正文能力完全一致。
## 数据模型
`NotifyDetail` 只约束正文相关字段,主题、状态等业务字段由外层自行维护并原样保留:
| 字段 | 说明 |
| --- | --- |
| `content` | 正文内容。 |
| `contentType` | 正文类型,支持 `TEXT`、`TIP_TAP`。 |
| `attachmentList` | 附件列表。 |
## 提交内容
```ts
const detail = await editorRef.value?.submit();
```
与文章编辑器一致,`submit()` 会等待未完成的媒体上传。
## API
<api-table name="NotifyEditor" />
+19
View File
@@ -0,0 +1,19 @@
# NotifyView 通知视图
渲染通知的正文内容,是 `ArticleView` 在通知场景下的薄封装。
## 基础用法
:::preview 基础用法 || 传入 NotifyDetail 即可渲染正文
demo-preview=../demos/notify-view/basic.vue
:::
## 何时使用
需要在通知详情页只读展示正文时使用。主题、状态等元数据由业务页面自行呈现,组件只负责正文。
## API
<api-table name="NotifyView" />
+19
View File
@@ -0,0 +1,19 @@
# RootLayout 根布局
提供页面级骨架与统一留白,承载顶部区域与主内容,底部自动渲染版权与备案信息。
## 基础用法
:::preview 基础用法 || 插槽填充主体内容,版权信息由四个属性拼装
demo-preview=../demos/root-layout/basic.vue
:::
## 何时使用
需要一套带页脚版权信息的整页容器时使用。组件在窄屏下会自动取消外边距与阴影并撑满视口。
## API
<api-table name="RootLayout" />
+43
View File
@@ -0,0 +1,43 @@
# TiptapEditor 富文本编辑器
基于 Tiptap 的富文本编辑器,内置媒体、表格、链接与代码块等工具栏能力。
## 基础用法
:::preview 基础用法 || 工具栏覆盖标题、颜色、列表、表格、链接、代码块与媒体插入
demo-preview=../demos/tiptap-editor/basic.vue
:::
## 何时使用
需要所见即所得的正文编辑时使用。内容以 HTML 字符串双向绑定,可直接存入数据库。
## 媒体上传
图片与视频通过 `uploadImage`、`uploadVideo` 回调上传,组件不绑定具体接口。拖拽或粘贴文件时会先插入占位内容,上传成功后替换为真实地址:
```ts
async function uploadMedia(file: File): Promise<UploadResult> {
return await api.upload(file);
}
```
未上传成功的媒体会在提交前统一处理,`getPendingMediaCount()` 可查询待处理数量。
## 提交内容
编辑过程中的 `v-model` 是实时值,提交时建议调用 `submit()` 以等待未完成的上传并归一化内容:
```ts
const html = await editorRef.value?.submit();
```
## 内边距
`paddingTB` 与 `paddingLR` 控制正文内边距,配合 `showPaddingTool` 决定是否显示工具栏里的内边距调节入口,两个方向都支持 `v-model:` 双向绑定。
## API
<api-table name="TiptapEditor" />
+23
View File
@@ -0,0 +1,23 @@
# TiptapView 富文本视图
Tiptap 内容的只读渲染视图,与编辑器共用同一套样式与扩展。
## 基础用法
:::preview 基础用法 || 超出 maxHeight 时可滚动查看
demo-preview=../demos/tiptap-view/basic.vue
:::
## 何时使用
需要在详情页、审批流等只读场景渲染富文本时使用。相比直接 `v-html`,它复用了编辑器的扩展与样式,能保证展示与编辑效果一致。
## 空内容
内容为空或规范化后为空字符串时,组件渲染 `emptyText` 占位文案而不是空白区域。
## API
<api-table name="TiptapView" />
+25
View File
@@ -0,0 +1,25 @@
# UserLevel 用户等级
按等级值渲染等级图标,图标来自一张纵向雪碧图,每个等级对应一行。
## 基础用法
:::preview 全部等级 || 传入 0 到 9 的等级值即可切换到对应图标
demo-preview=../demos/user-level/basic.vue
:::
## 计算等级
组件本体只负责展示,等级换算由导出的 `toUserLevel` 完成。它按固定经验表把经验值换算成等级、当前进度与距下一级所需经验:
```ts
import { toUserLevel } from "timi-tdesign-pc";
const { value, percent, nextLevelUp } = toUserLevel(96);
```
## API
<api-table name="UserLevel" />
+37
View File
@@ -0,0 +1,37 @@
# UserProfilePopup 用户资料弹窗
用户资料卡弹窗,把 `UserProfile` 挂载到 `timi-web` 的弹层容器中,由悬停触发显示。
## 基础用法
:::preview 基础用法 || 把鼠标移到文字上查看,切换按钮可更换展示的用户
demo-preview=../demos/user-profile-popup/basic.vue
:::
## 何时使用
页面上出现用户名、头像等标识,且希望悬停时展示完整资料时使用。
## 工作原理
组件本身是一个隐藏容器,挂载后把自己注册到 `popupUserStore.config`,弹层类型为 `PopupType.EL`:
```ts
import { UserProfilePopup, popupUserStore } from "timi-tdesign-pc";
// 决定弹层里展示谁
popupUserStore.user.value = user;
```
页面上需要同时放置两样东西:
- `<user-profile-popup />`:资料内容容器,只挂载一次
- `<popup />`:`timi-web` 的弹层容器,同样只挂载一次
然后在任意元素上用 `v-popup="popupUserStore.config"` 绑定悬停行为。弹层关闭后 `user` 会被自动清空。
## API
<api-table name="UserProfilePopup" />
+24
View File
@@ -0,0 +1,24 @@
# UserProfile 用户资料
展示用户头像、昵称、性别与等级信息。
## 基础用法
:::preview 基础用法 || 传入 UserView 即可,头像与背景支持自定义解析
demo-preview=../demos/user-profile/basic.vue
:::
## 图片来源
按优先级依次取值:
1. `user.profile.avatarUrl` / `user.profile.wrapperUrl`
2. `resolveAvatarUrl` / `resolveWrapperUrl` 回调的返回值
回调适合根据 `attachmentList` 里的附件动态换取带签名的地址。`avatarType` 与 `wrapperType` 用于控制图片渲染模式,取值见导出的 `ImageType`。
## API
<api-table name="UserProfile" />
+93
View File
@@ -0,0 +1,93 @@
<template>
<div class="demo">
<div class="bar">
<t-button size="small" variant="outline" @click="collapsed = !collapsed">
{{ collapsed ? "展开菜单" : "收起菜单" }}
</t-button>
<span class="status" v-text="`当前选中:${active}`" />
</div>
<div class="frame">
<admin-layout
v-model="active"
:menu-items="menuItems"
:collapsed="collapsed"
>
<template #logo>
<span class="logo" v-text="'Timi'" />
</template>
<template #menu>
<t-tag theme="primary" variant="light">管理台</t-tag>
</template>
<div class="content">
<h3 v-text="`内容区:${active}`" />
<p v-text="'主体区域由默认插槽填充,顶部栏与侧边菜单各自独立成插槽。'" />
</div>
</admin-layout>
</div>
</div>
</template>
<script lang="ts" setup>
import { ref } from "vue";
import { AdminLayout } from "timi-tdesign-pc";
import type { AdminMenuItem } from "timi-tdesign-pc";
const menuItems: AdminMenuItem[] = [
{ value: "dashboard", label: "工作台" },
{ value: "article", label: "文章管理" },
{ value: "notify", label: "通知管理" },
{ value: "setting", label: "系统设置", disabled: true }
];
const active = ref<string | number>("dashboard");
const collapsed = ref(false);
</script>
<style lang="less" scoped>
.demo {
.bar {
display: flex;
gap: .75rem;
align-items: center;
margin-bottom: 1rem;
}
.status {
font-size: .75rem;
color: var(--td-text-color-secondary);
}
// 组件自身按 100vh 撑满,这里压缩到可视范围内便于演示
.frame {
height: 28rem;
overflow: hidden;
border: 1px solid var(--td-component-stroke);
border-radius: .75rem;
:deep(.tui-admin-layout) {
height: 100%;
}
}
.logo {
font-size: 1.25rem;
font-weight: 700;
color: var(--td-brand-color);
}
.content {
padding: 1.5rem;
h3 {
margin: 0 0 .5rem;
}
p {
margin: 0;
color: var(--td-text-color-secondary);
}
}
}
</style>
+115
View File
@@ -0,0 +1,115 @@
<template>
<div class="demo">
<div class="bar">
<t-button
v-for="item in contentTypeList"
:key="item.value"
size="small"
variant="outline"
:theme="value.contentType === item.value ? 'primary' : 'default'"
@click="switchContentType(item.value)"
>
{{ item.label }}
</t-button>
<t-button size="small" theme="primary" @click="submit">提交</t-button>
</div>
<t-input v-model="value.title" class="field" placeholder="文章标题" />
<article-editor
ref="editorRef"
:model-value="value"
:upload-image="uploadMedia"
:upload-video="uploadMedia"
@change="onChange"
@update:model-value="onChange"
/>
<p class="status" v-text="status" />
</div>
</template>
<script lang="ts" setup>
import { ref } from "vue";
import { ArticleEditor } from "timi-tdesign-pc";
import type {
Article,
ArticleContentType,
ArticleEditorExpose,
UploadResult
} from "timi-tdesign-pc";
const RICH_CONTENT = `<h2>正文类型可切换</h2>
<p>同一份 <code>Article</code> 数据,按 <code>contentType</code> 切换三种编辑形态。</p>`;
const contentTypeList: Array<{ label: string; value: ArticleContentType }> = [
{ label: "纯文本", value: "TEXT" },
{ label: "Markdown", value: "MARKDOWN" },
{ label: "富文本", value: "TIP_TAP" }
];
const value = ref<Article>({
title: "编辑器演示文章",
contentType: "TIP_TAP",
content: RICH_CONTENT,
attachmentList: []
});
const status = ref("等待提交");
const editorRef = ref<ArticleEditorExpose>();
/** 切换正文类型时同步替换内容,避免不同格式互相污染。 */
function switchContentType(contentType: ArticleContentType) {
const content = contentType === "TEXT"
? "这是一段纯文本正文。"
: contentType === "MARKDOWN"
? "## Markdown 标题\n\n这是一段 Markdown 正文。"
: RICH_CONTENT;
value.value = {
...value.value,
contentType,
content
};
}
function onChange(article: Article) {
value.value = article;
}
async function submit() {
const article = await editorRef.value?.submit();
if (article) {
value.value = article;
status.value = `已提交,标题为「${article.title}」`;
}
}
async function uploadMedia(file: File): Promise<UploadResult> {
return {
id: `demo-${Date.now()}-${file.name}`,
name: file.name,
url: URL.createObjectURL(file)
};
}
</script>
<style lang="less" scoped>
.demo {
.bar {
display: flex;
flex-wrap: wrap;
gap: .5rem;
margin-bottom: 1rem;
}
.field {
margin-bottom: 1rem;
}
.status {
margin: 1rem 0 0;
font-size: .75rem;
color: var(--td-text-color-secondary);
}
}
</style>
+20
View File
@@ -0,0 +1,20 @@
<template>
<div class="demo">
<article-view :article="article" />
</div>
</template>
<script lang="ts" setup>
import { ArticleView } from "timi-tdesign-pc";
import type { Article } from "timi-tdesign-pc";
/** ArticleView 按 contentType 选择渲染方式,这里演示富文本形态。 */
const article: Article = {
title: "文章视图",
contentType: "TIP_TAP",
content: `<h2>文章视图</h2>
<p>标题与正文按 <code>Article</code> 结构渲染,空内容时显示占位文案。</p>
<blockquote><p>把 <code>contentType</code> 换成 TEXT 或 MARKDOWN 会切换渲染分支。</p></blockquote>`,
attachmentList: []
};
</script>
+68
View File
@@ -0,0 +1,68 @@
<template>
<div class="demo">
<authorize-form
:captcha="requestCaptcha"
:login="handleLogin"
:register="handleRegister"
@login-success="onLoginSuccess"
@register-success="onRegisterSuccess"
/>
<p class="status" v-text="status" />
</div>
</template>
<script lang="ts" setup>
import { ref } from "vue";
import { AuthorizeForm } from "timi-tdesign-pc";
import type {
CaptchaData,
CaptchaResult,
LoginRequest,
RegisterRequest
} from "timi-tdesign-pc";
const status = ref("等待操作");
/** 演示用验证码:直接生成一张 SVG 图片,无需后端接口。 */
async function requestCaptcha(width: number, height: number): Promise<CaptchaResult> {
const text = String(Math.floor(1000 + Math.random() * 9000));
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}">` +
`<rect width="100%" height="100%" fill="#f3f3f3"/>` +
`<text x="50%" y="50%" font-family="monospace" font-size="24" fill="#0052d9" ` +
`text-anchor="middle" dominant-baseline="central">${text}</text></svg>`;
return {
id: `demo-${Date.now()}`,
data: `data:image/svg+xml;utf8,${encodeURIComponent(svg)}`
};
}
/** 真实项目里在这里调用登录接口。 */
async function handleLogin(request: CaptchaData<LoginRequest>) {
await new Promise(resolve => setTimeout(resolve, 300));
status.value = `登录请求:${request.data.user}`;
}
async function handleRegister(request: CaptchaData<RegisterRequest>) {
await new Promise(resolve => setTimeout(resolve, 300));
status.value = `注册请求:${request.data.name}`;
}
async function onLoginSuccess() {
status.value = "登录成功,由外层处理跳转与状态刷新";
}
async function onRegisterSuccess() {
status.value = "注册成功,由外层处理后续流程";
}
</script>
<style lang="less" scoped>
.demo {
.status {
margin: 1rem 0 0;
font-size: .75rem;
text-align: center;
color: var(--td-text-color-secondary);
}
}
</style>
+72
View File
@@ -0,0 +1,72 @@
<template>
<div class="demo">
<div class="bar">
<t-button size="small" theme="primary" @click="readValue">读取内容</t-button>
<t-button size="small" variant="outline" @click="openSearch">打开查找</t-button>
<span class="status" v-text="status" />
</div>
<div class="box">
<code-editor
ref="editorRef"
v-model="code"
language="typescript"
placeholder="请输入代码"
@change="onChange"
/>
</div>
</div>
</template>
<script lang="ts" setup>
import { ref } from "vue";
import { CodeEditor } from "timi-tdesign-pc";
import type { CodeEditorExpose } from "timi-tdesign-pc";
const DEMO_CODE = `type DemoUser = {
id: string;
name: string;
};
const user: DemoUser = {
id: "demo-001",
name: "Timi"
};
console.log(user.name);`;
const code = ref(DEMO_CODE);
const status = ref("等待操作");
const editorRef = ref<CodeEditorExpose>();
function onChange(value: string) {
status.value = `内容已更新,${value.length} 个字符`;
}
function readValue() {
status.value = `当前共 ${code.value.length} 个字符`;
}
function openSearch() {
editorRef.value?.openSearch(true);
}
</script>
<style lang="less" scoped>
.demo {
.bar {
display: flex;
gap: .5rem;
align-items: center;
margin-bottom: 1rem;
}
.status {
font-size: .75rem;
color: var(--td-text-color-secondary);
}
.box {
height: 20rem;
}
}
</style>
+76
View File
@@ -0,0 +1,76 @@
<template>
<div class="demo">
<t-input v-model="value.subject" class="field" placeholder="通知主题" />
<notify-editor
ref="editorRef"
:model-value="value"
:upload-image="uploadMedia"
:upload-video="uploadMedia"
@change="onChange"
@update:model-value="onChange"
/>
<div class="footer">
<t-button size="small" theme="primary" @click="submit">提交</t-button>
<span class="status" v-text="status" />
</div>
</div>
</template>
<script lang="ts" setup>
import { ref } from "vue";
import { NotifyEditor } from "timi-tdesign-pc";
import type { NotifyDetail, NotifyEditorExpose, UploadResult } from "timi-tdesign-pc";
const value = ref<NotifyDetail>({
subject: "编辑器通知演示",
contentType: "TIP_TAP",
content: `<h2>通知内容</h2>
<p>通知复用文章编辑器,同时保留自己的元数据字段(如 <code>subject</code>)。</p>`,
attachmentList: []
});
const status = ref("等待提交");
const editorRef = ref<NotifyEditorExpose>();
function onChange(detail: NotifyDetail) {
value.value = detail;
}
async function submit() {
const detail = await editorRef.value?.submit();
if (detail) {
value.value = detail;
status.value = `已提交,正文 ${detail.content?.length || 0} 个字符`;
}
}
async function uploadMedia(file: File): Promise<UploadResult> {
return {
id: `demo-${Date.now()}-${file.name}`,
name: file.name,
url: URL.createObjectURL(file)
};
}
</script>
<style lang="less" scoped>
.demo {
.field {
margin-bottom: 1rem;
}
.footer {
display: flex;
gap: .75rem;
align-items: center;
margin-top: 1rem;
}
.status {
font-size: .75rem;
color: var(--td-text-color-secondary);
}
}
</style>
+19
View File
@@ -0,0 +1,19 @@
<template>
<div class="demo">
<notify-view :detail="detail" />
</div>
</template>
<script lang="ts" setup>
import { NotifyView } from "timi-tdesign-pc";
import type { NotifyDetail } from "timi-tdesign-pc";
/** NotifyView 只关心正文相关字段,主题与状态由业务页面自行呈现。 */
const detail: NotifyDetail = {
subject: "系统维护通知",
contentType: "TIP_TAP",
content: `<h2>系统维护通知</h2>
<p>本周六 02:00 - 04:00 进行数据库升级,期间服务不可用。</p>
<ul><li>请提前保存工作内容</li><li>升级完成后会同步通知</li></ul>`
};
</script>
+32
View File
@@ -0,0 +1,32 @@
<template>
<root-layout
icp="京ICP备 00000000 号"
domain="example.com"
author="Timi"
text="组件演示"
>
<div class="body">
<h3 v-text="'RootLayout'" />
<p v-text="'页面级骨架:插槽填充主体内容,底部自动渲染版权与备案信息。'" />
</div>
</root-layout>
</template>
<script lang="ts" setup>
import { RootLayout } from "timi-tdesign-pc";
</script>
<style lang="less" scoped>
.body {
padding: 2rem;
h3 {
margin: 0 0 .5rem;
}
p {
margin: 0;
color: var(--td-text-color-secondary);
}
}
</style>
+147
View File
@@ -0,0 +1,147 @@
<template>
<div class="demo">
<div class="bar">
<t-button
v-for="item in contentTypeList"
:key="item.value"
size="small"
variant="outline"
:theme="article.contentType === item.value ? 'primary' : 'default'"
@click="switchContentType(item.value)"
>
{{ item.label }}
</t-button>
<t-button size="small" theme="primary" @click="submit">提交文章</t-button>
</div>
<div class="grid">
<section class="pane">
<h4 v-text="'编辑'" />
<t-input v-model="article.title" class="title" placeholder="文章标题" />
<article-editor
ref="editorRef"
:model-value="article"
:upload-image="uploadMedia"
:upload-video="uploadMedia"
@change="onChange"
@update:model-value="onChange"
/>
</section>
<section class="pane">
<h4 v-text="'预览'" />
<article-view :article="article" />
</section>
</div>
<p class="status" v-text="status" />
</div>
</template>
<script lang="ts" setup>
import { ref } from "vue";
import { ArticleEditor, ArticleView } from "timi-tdesign-pc";
import type {
Article,
ArticleContentType,
ArticleEditorExpose,
UploadResult
} from "timi-tdesign-pc";
/** 本场景验证「同一份 Article 数据,编辑与预览实时联动」。 */
const RICH_CONTENT = `<h2>文章编辑与预览</h2>
<p>左侧改动会立刻反映到右侧,两侧共用同一个 <code>Article</code> 对象。</p>
<blockquote><p>切换正文类型时,编辑区与预览区会同时切换渲染分支。</p></blockquote>`;
const contentTypeList: Array<{ label: string; value: ArticleContentType }> = [
{ label: "纯文本", value: "TEXT" },
{ label: "Markdown", value: "MARKDOWN" },
{ label: "富文本", value: "TIP_TAP" }
];
const article = ref<Article>({
title: "编辑器组件演示文章",
contentType: "TIP_TAP",
content: RICH_CONTENT,
attachmentList: []
});
const status = ref("等待提交");
const editorRef = ref<ArticleEditorExpose>();
function switchContentType(contentType: ArticleContentType) {
const content = contentType === "TEXT"
? "这是一段纯文本示例。"
: contentType === "MARKDOWN"
? "## Markdown 示例\n\n这是一段 Markdown 正文。"
: RICH_CONTENT;
article.value = {
...article.value,
contentType,
content
};
status.value = `已切换到 ${contentType}`;
}
function onChange(value: Article) {
article.value = value;
}
async function submit() {
const value = await editorRef.value?.submit();
if (value) {
article.value = value;
status.value = `已提交,${value.attachmentList?.length || 0} 个附件`;
}
}
async function uploadMedia(file: File): Promise<UploadResult> {
return {
id: `demo-${Date.now()}-${file.name}`,
name: file.name,
url: URL.createObjectURL(file)
};
}
</script>
<style lang="less" scoped>
.demo {
.bar {
display: flex;
flex-wrap: wrap;
gap: .5rem;
margin-bottom: 1rem;
}
.grid {
display: grid;
gap: 1rem;
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.pane {
min-width: 0;
h4 {
margin: 0 0 .75rem;
font-size: .875rem;
}
}
.title {
margin-bottom: .75rem;
}
.status {
margin: 1rem 0 0;
font-size: .75rem;
color: var(--td-text-color-secondary);
}
@media (max-width: 60rem) {
.grid {
grid-template-columns: 1fr;
}
}
}
</style>
+179
View File
@@ -0,0 +1,179 @@
<template>
<div class="demo">
<div class="bar">
<t-button size="small" theme="primary" @click="openSearch">
同时打开两处查找
</t-button>
<t-button size="small" variant="outline" @click="submitRich">
提交富文本
</t-button>
<span class="status" v-text="status" />
</div>
<section class="block">
<div class="head">
<h4 v-text="'富文本编辑器'" />
<span v-text="'支持拖入图片与视频'" />
</div>
<div class="box rich">
<tiptap-editor
ref="tiptapRef"
v-model="rich"
:upload-image="uploadMedia"
:upload-video="uploadMedia"
@change="onRichChange"
/>
</div>
</section>
<section class="block">
<div class="head">
<h4 v-text="'只读视图'" />
<t-input
v-model="maxHeight"
class="height-input"
placeholder="最大高度,如 20rem"
/>
</div>
<tiptap-view :content="rich" :max-height="maxHeight" />
</section>
<section class="block">
<div class="head">
<h4 v-text="'代码编辑器'" />
<t-button size="small" variant="text" @click="resetCode">
恢复示例
</t-button>
</div>
<div class="box code">
<code-editor
ref="codeRef"
v-model="code"
language="typescript"
placeholder="请输入代码"
/>
</div>
</section>
</div>
</template>
<script lang="ts" setup>
import { ref } from "vue";
import { CodeEditor, TiptapEditor, TiptapView } from "timi-tdesign-pc";
import type {
CodeEditorExpose,
TiptapEditorExpose,
UploadResult
} from "timi-tdesign-pc";
/** 本场景把三类编辑器放在一起,验证它们共用同一套内容与检索能力。 */
const DEMO_CODE = `type DemoUser = {
id: string;
name: string;
};
const user: DemoUser = {
id: "demo-001",
name: "Timi"
};
console.log(user.name);`;
const rich = ref(`<h2>跨平台编辑器</h2>
<p>这段内容同时验证标题、段落、链接、表格和代码块的渲染。</p>
<blockquote><p>移动端和 PC 端只替换交互层,共享文档模型。</p></blockquote>`);
const code = ref(DEMO_CODE);
const maxHeight = ref("20rem");
const status = ref("等待操作");
const tiptapRef = ref<TiptapEditorExpose>();
const codeRef = ref<CodeEditorExpose>();
function onRichChange(value: string) {
status.value = `富文本已更新,${value.length} 个字符`;
}
function resetCode() {
code.value = DEMO_CODE;
status.value = "代码已恢复为示例内容";
}
/** 两个编辑器各有独立的查找栏,这里一次性把它们都唤起来。 */
function openSearch() {
tiptapRef.value?.openSearch(true);
codeRef.value?.openSearch(true);
status.value = "已打开查找栏";
}
async function submitRich() {
const value = await tiptapRef.value?.submit();
if (value !== undefined) {
rich.value = value;
status.value = `富文本已提交,${value.length} 个字符`;
}
}
async function uploadMedia(file: File): Promise<UploadResult> {
return {
id: `demo-${Date.now()}-${file.name}`,
name: file.name,
url: URL.createObjectURL(file)
};
}
</script>
<style lang="less" scoped>
.demo {
.bar {
display: flex;
flex-wrap: wrap;
gap: .5rem;
align-items: center;
margin-bottom: 1.25rem;
}
.status {
font-size: .75rem;
color: var(--td-text-color-secondary);
}
.block {
margin-bottom: 1.5rem;
&:last-child {
margin-bottom: 0;
}
}
.head {
display: flex;
gap: .75rem;
align-items: center;
justify-content: space-between;
margin-bottom: .75rem;
h4 {
margin: 0;
font-size: .875rem;
}
span {
font-size: .75rem;
color: var(--td-text-color-secondary);
}
}
.height-input {
width: 12rem;
}
.box {
height: 20rem;
}
.rich {
height: 24rem;
}
}
</style>
+137
View File
@@ -0,0 +1,137 @@
<template>
<div class="demo">
<div class="bar">
<t-button size="small" variant="outline" @click="switchStatus">
切换状态
</t-button>
<t-button size="small" theme="primary" @click="submit">提交通知</t-button>
<t-tag variant="light">{{ detail.status }}</t-tag>
</div>
<div class="grid">
<section class="pane">
<h4 v-text="'编辑'" />
<t-input
v-model="detail.subject"
class="subject"
placeholder="通知主题"
/>
<notify-editor
ref="editorRef"
:model-value="detail"
:upload-image="uploadMedia"
:upload-video="uploadMedia"
@change="onChange"
@update:model-value="onChange"
/>
</section>
<section class="pane">
<h4 v-text="'预览'" />
<notify-view :detail="detail" />
</section>
</div>
<p class="status" v-text="status" />
</div>
</template>
<script lang="ts" setup>
import { ref } from "vue";
import { NotifyEditor, NotifyView } from "timi-tdesign-pc";
import type {
NotifyDetail,
NotifyEditorExpose,
UploadResult
} from "timi-tdesign-pc";
/** 本场景验证通知复用文章编辑能力,同时保留自己的元数据字段。 */
const RICH_CONTENT = `<h2>系统维护通知</h2>
<p>本周六 02:00 - 04:00 进行数据库升级,期间服务不可用。</p>
<ul><li>请提前保存工作内容</li><li>升级完成后会同步通知</li></ul>`;
const statusList = ["WAITING", "SENT", "FAILED"];
const detail = ref<NotifyDetail>({
subject: "编辑器通知演示",
contentType: "TIP_TAP",
content: RICH_CONTENT,
status: "WAITING",
attachmentList: []
});
const status = ref("等待提交");
const editorRef = ref<NotifyEditorExpose>();
function switchStatus() {
const index = statusList.indexOf(detail.value.status);
const next = statusList[(index + 1) % statusList.length];
detail.value = {
...detail.value,
status: next
};
}
function onChange(value: NotifyDetail) {
detail.value = value;
}
async function submit() {
const value = await editorRef.value?.submit();
if (value) {
detail.value = value;
status.value = `已提交,正文 ${value.content?.length || 0} 个字符`;
}
}
async function uploadMedia(file: File): Promise<UploadResult> {
return {
id: `demo-${Date.now()}-${file.name}`,
name: file.name,
url: URL.createObjectURL(file)
};
}
</script>
<style lang="less" scoped>
.demo {
.bar {
display: flex;
flex-wrap: wrap;
gap: .5rem;
align-items: center;
margin-bottom: 1rem;
}
.grid {
display: grid;
gap: 1rem;
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.pane {
min-width: 0;
h4 {
margin: 0 0 .75rem;
font-size: .875rem;
}
}
.subject {
margin-bottom: .75rem;
}
.status {
margin: 1rem 0 0;
font-size: .75rem;
color: var(--td-text-color-secondary);
}
@media (max-width: 60rem) {
.grid {
grid-template-columns: 1fr;
}
}
}
</style>
+76
View File
@@ -0,0 +1,76 @@
<template>
<div class="demo">
<div class="bar">
<t-button size="small" theme="primary" @click="submit">提交</t-button>
<t-button size="small" variant="outline" @click="openSearch">打开查找</t-button>
<span class="status" v-text="status" />
</div>
<div class="box">
<tiptap-editor
ref="editorRef"
v-model="content"
:upload-image="uploadMedia"
:upload-video="uploadMedia"
@change="onChange"
/>
</div>
</div>
</template>
<script lang="ts" setup>
import { ref } from "vue";
import { TiptapEditor } from "timi-tdesign-pc";
import type { TiptapEditorExpose, UploadResult } from "timi-tdesign-pc";
const content = ref(`<h2>富文本编辑器</h2>
<p>工具栏覆盖标题、颜色、列表、表格、链接、代码块与媒体插入。</p>
<blockquote><p>把图片或视频拖进正文即可触发上传回调。</p></blockquote>`);
const status = ref("等待操作");
const editorRef = ref<TiptapEditorExpose>();
function onChange(value: string) {
status.value = `内容已更新,${value.length} 个字符`;
}
async function submit() {
const value = await editorRef.value?.submit();
if (value !== undefined) {
content.value = value;
status.value = `已提交,${value.length} 个字符`;
}
}
function openSearch() {
editorRef.value?.openSearch(true);
}
/** 演示用上传:直接把本地文件转成临时地址,无需后端。 */
async function uploadMedia(file: File): Promise<UploadResult> {
return {
id: `demo-${Date.now()}-${file.name}`,
name: file.name,
url: URL.createObjectURL(file)
};
}
</script>
<style lang="less" scoped>
.demo {
.bar {
display: flex;
gap: .5rem;
align-items: center;
margin-bottom: 1rem;
}
.status {
font-size: .75rem;
color: var(--td-text-color-secondary);
}
.box {
height: 28rem;
}
}
</style>
+30
View File
@@ -0,0 +1,30 @@
<template>
<div class="demo">
<t-input
v-model="maxHeight"
class="field"
placeholder="最大高度,如 20rem"
/>
<tiptap-view :content="content" :max-height="maxHeight" />
</div>
</template>
<script lang="ts" setup>
import { ref } from "vue";
import { TiptapView } from "timi-tdesign-pc";
const content = `<h2>只读视图</h2>
<p>与编辑器共用同一套渲染规则,内容超出 <code>maxHeight</code> 时可滚动查看。</p>
<blockquote><p>适合详情页、审批流等只需要阅读的场景。</p></blockquote>`;
const maxHeight = ref("20rem");
</script>
<style lang="less" scoped>
.demo {
.field {
width: 16rem;
margin-bottom: 1rem;
}
}
</style>
+37
View File
@@ -0,0 +1,37 @@
<template>
<div class="demo">
<div v-for="item in levelList" :key="item.value" class="item">
<user-level :value="item.value" />
<span class="label" v-text="item.label" />
</div>
</div>
</template>
<script lang="ts" setup>
import { UserLevel } from "timi-tdesign-pc";
/** 等级图标是一张纵向雪碧图,每个等级对应一行。 */
const levelList = Array.from({ length: 10 }, (_, index) => ({
value: index,
label: `Lv.${index}`
}));
</script>
<style lang="less" scoped>
.demo {
display: flex;
flex-wrap: wrap;
gap: 1.5rem;
}
.item {
display: flex;
gap: .5rem;
align-items: center;
}
.label {
font-size: .75rem;
color: var(--td-text-color-secondary);
}
</style>
+87
View File
@@ -0,0 +1,87 @@
<template>
<div class="demo">
<div class="bar">
<t-button size="small" theme="primary" @click="switchUser">切换用户</t-button>
<span class="status" v-text="`当前:${currentName}`" />
</div>
<p class="tip">
<span v-popup="popupUserStore.config" v-text="'把鼠标移到这段文字上查看用户资料'" />
</p>
<user-profile-popup />
<popup />
</div>
</template>
<script lang="ts" setup>
import { computed, onMounted, ref } from "vue";
import { Popup } from "timi-web";
import { UserProfilePopup, popupUserStore } from "timi-tdesign-pc";
import type { UserView } from "timi-tdesign-pc";
/**
* 演示用数据。
*
* popup 内容是真实 DOM 节点,通过 PopupType.EL 挂到 timi-web 的弹层容器里,
* 所以每次切换用户后直接悬停即可看到最新资料。
*/
const userList: UserView[] = [
{
id: "demo-001",
name: "Timi",
profile: {
exp: 96,
sex: 1,
description: "全栈开发,关注前端工程化。"
}
},
{
id: "demo-002",
name: "Mia",
profile: {
exp: 32,
sex: 2,
description: "产品设计,负责交互与视觉。"
}
}
];
const activeIndex = ref(0);
const currentName = computed(() => userList[activeIndex.value].name);
function switchUser() {
activeIndex.value = (activeIndex.value + 1) % userList.length;
popupUserStore.user.value = userList[activeIndex.value];
}
onMounted(() => {
popupUserStore.user.value = userList[activeIndex.value];
});
</script>
<style lang="less" scoped>
.demo {
.bar {
display: flex;
gap: .75rem;
align-items: center;
}
.status {
font-size: .75rem;
color: var(--td-text-color-secondary);
}
.tip {
margin: 1rem 0 0;
}
.tip span {
cursor: help;
border-bottom: 1px dashed var(--td-brand-color);
color: var(--td-brand-color);
}
}
</style>
+33
View File
@@ -0,0 +1,33 @@
<template>
<div class="demo">
<user-profile :user="user" />
</div>
</template>
<script lang="ts" setup>
import { UserProfile } from "timi-tdesign-pc";
import type { UserView } from "timi-tdesign-pc";
/** 演示用图片:内联 SVG,避免依赖外部图床。 */
function buildImage(label: string, background: string, width = 320, height = 120) {
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}">` +
`<rect width="100%" height="100%" fill="${background}"/>` +
`<text x="50%" y="50%" font-size="20" fill="#ffffff" text-anchor="middle" ` +
`dominant-baseline="central">${label}</text></svg>`;
return `data:image/svg+xml;utf8,${encodeURIComponent(svg)}`;
}
const user: UserView = {
id: "demo-001",
name: "Timi",
profile: {
exp: 96,
sex: 1,
description: "全栈开发,关注前端工程化与组件沉淀。",
avatarType: "IR-AUTO",
wrapperType: "IR-AUTO",
avatarUrl: buildImage("T", "#0052d9", 64, 64),
wrapperUrl: buildImage("背景图", "#0594fa")
}
};
</script>
+113
View File
@@ -0,0 +1,113 @@
# 演示与文档约定
本站的演示与 API 文档都由源码驱动,新增组件时只需按下面的顺序补齐三处内容。
## 目录结构
```text
docs/
├── .vitepress/
│ ├── components.ts # 组件元数据清单(唯一数据源)
│ ├── config.ts # 站点配置、侧边栏、markdown 插件
│ ├── plugins/
│ │ ├── docgen.ts # vue-docgen-api 解析,产出虚拟模块
│ │ └── ssr-stub.ts # SSR 阶段替换 timi-web
│ └── theme/
│ ├── index.ts # 主题入口,注册 TDesign 与自定义组件
│ ├── containers/ # :::preview 的预览容器
│ └── components/ # api-table 等文档组件
├── demos/ # 演示组件,按组件名分目录
│ └── scenarios/ # 跨组件的组合场景演示
├── components/ # 组件文档页
└── scenarios/ # 组合场景文档页
```
单组件文档只回答「这个组件怎么用」,跨组件的协作方式放在 `scenarios/` 下。
## 新增一个组件
### 1. 登记元数据
在 `docs/.vitepress/components.ts` 的 `COMPONENT_LIST` 中追加一项。侧边栏导航、API 数据解析都从这里读取,不需要另外维护列表:
```ts
{
name: "CodeEditor", // 必须与组件 defineOptions 的 name 一致
title: "CodeEditor 代码编辑器",
description: "带行号、语法高亮与查找替换的代码输入框。",
category: "编辑器组件",
entry: "src/components/code-editor/index.vue"
}
```
### 2. 编写演示
演示组件放在 `docs/demos/<kebab-case 组件名>/` 下。演示直接引用 `src` 源码,改组件会即时热更新:
```vue
<script lang="ts" setup>
import { ref } from "vue";
import { CodeEditor } from "timi-tdesign-pc";
const code = ref("");
</script>
<template>
<code-editor v-model="code" />
</template>
```
### 3. 编写文档页
在 `docs/components/` 下建立同名 markdown,用 `:::preview` 容器引用演示:
````md
# CodeEditor 代码编辑器
带行号、语法高亮与查找替换的代码输入框。
## 基础用法
:::preview 基础用法 || 通过 v-model 双向绑定内容
demo-preview=../demos/code-editor/basic.vue
:::
## API
<api-table name="CodeEditor" />
````
路径以 markdown 文件所在位置为基准,因此 `docs/components/` 下的页面统一使用 `../demos/`。
## API 表从哪来
`<api-table>` 的数据由 `vue-docgen-api` 在构建期解析组件源码得到,通过虚拟模块 `virtual:timi-api` 交给页面渲染。
因此:
- 不需要手写 props / events / slots 表格,改源码后文档自动更新
- 想让说明出现在表里,就在 props 类型上写 JSDoc 注释:
```ts
const props = withDefaults(defineProps<{
/** 侧边栏菜单配置。 */
menuItems?: AdminMenuItem[];
}>(), {
menuItems: () => []
});
```
某个组件解析失败时只会让该组件的 API 区降级为空,不会影响整站构建;构建日志里会打出对应的组件名。
## 样式与主题
- 演示容器基于 TDesign 实现,未引入额外的 UI 依赖
- 深色模式由主题入口同步 VitePress 与 TDesign 两套开关,组件内直接使用 TDesign 的 CSS 变量即可自动适配
## 关于 SSR
`timi-web` 的构建产物在模块顶层访问 `window`,无法在 Node 中加载。文档站里真正需要它的只有演示组件,它们全部以 `clientOnly` 方式延迟到浏览器渲染,SSR 阶段则由 `ssr-stub.ts` 提供空实现。
所以演示组件不需要额外处理 SSR,但也不要把它当作服务端渲染能力的验证。
+80
View File
@@ -0,0 +1,80 @@
# 快速开始
`timi-tdesign-pc` 是面向 PC 端的 Vue 3 业务组件库,底层复用 `timi-web` 的基础组件与编辑器能力。
## 安装
```sh
pnpm add timi-tdesign-pc tdesign-vue-next
```
## 按需引入
组件在 `<script setup>` 中导入后即可在模板里使用,这是推荐方式:
```vue
<script lang="ts" setup>
import { ref } from "vue";
import { CodeEditor } from "timi-tdesign-pc";
const code = ref("const answer = 42;");
</script>
<template>
<code-editor v-model="code" language="typescript" />
</template>
```
## 全局注册
每个组件都带有 `install` 方法,可以单独注册为全局组件:
```ts
import { createApp } from "vue";
import { CodeEditor, TiptapEditor } from "timi-tdesign-pc";
const app = createApp(App);
app.use(CodeEditor);
app.use(TiptapEditor);
```
## 注册 timi-web 能力
组件内部依赖 `timi-web` 的 `v-popup` 指令与 `Popup` 弹层容器,需要在应用入口注册一次:
```ts
import TimiWebUI, { VPopup } from "timi-web";
app.use(TimiWebUI);
app.directive("popup", VPopup);
```
## 引入样式
```ts
import "timi-tdesign-pc/style.css";
```
该样式入口已经包含 TDesign 定制与编辑器正文样式,`timi-web` 的样式也会一并带入,无需重复引入。
## 数据与回调
文章、通知类组件只约束对象的最小字段,业务对象上的其他字段会原样保留。上传与附件地址通过回调注入,库本身不绑定任何接口实现:
```vue
<article-editor
:model-value="article"
:upload-image="uploadImage"
:upload-video="uploadVideo"
:resolve-attachment-url="resolveAttachmentUrl"
@update:model-value="article = $event"
/>
```
没有附件上传需求时,可以不传上传回调。
## 下一步
- 在[组件总览](/components/)中浏览全部组件
- 看[编辑器能力总览](/scenarios/editor)等组合场景,了解多个组件如何协作
- 了解本站的[演示与文档约定](/guide/demo),向文档站补充新组件
+23
View File
@@ -0,0 +1,23 @@
---
layout: home
hero:
name: timi-tdesign-pc
text: PC 端 TDesign 组件库
tagline: 基于 Vue 3 与 TDesign Vue Next 的业务组件,每个组件都配有可交互演示与自动生成的 API 文档
actions:
- theme: brand
text: 快速开始
link: /guide/
- theme: alt
text: 浏览组件
link: /components/
features:
- title: 真实可交互
details: 演示直接运行 src 源码而非静态截图,改动组件源码后文档即时热更新。
- title: API 自动生成
details: 由 vue-docgen-api 在构建期解析组件源码提取 props、events、slots 与 expose,文档与代码不会脱节。
- title: 深色模式联动
details: 跟随 VitePress 的明暗切换,并同步 TDesign 的 theme-mode,组件在两种主题下都正确显示。
---
+27
View File
@@ -0,0 +1,27 @@
{
"name": "timi-tdesign-pc-docs",
"private": true,
"version": "0.0.1",
"type": "module",
"description": "timi-tdesign-pc 组件演示与 API 文档站",
"scripts": {
"dev": "vitepress dev .",
"build": "vitepress build .",
"preview": "vitepress preview ."
},
"dependencies": {
"tdesign-vue-next": "^1.18.6",
"timi-web": "link:E:/WebProject/timi-web",
"vue": "^3.5.26"
},
"devDependencies": {
"@types/node": "^25.0.8",
"@vitepress-demo-preview/plugin": "^1.4.1",
"less": "^4.5.1",
"markdown-it-container": "^3.0.0",
"typescript": "^5.9.3",
"unplugin-auto-import": "^21.0.0",
"vitepress": "^1.6.4",
"vue-docgen-api": "^4.79.2"
}
}
+2826
View File
File diff suppressed because it is too large Load Diff
+23
View File
@@ -0,0 +1,23 @@
# 文章编辑与预览
左侧编辑、右侧预览,两侧共用同一个 `Article` 对象,改动实时联动。
## 组合演示
:::preview 编辑与预览联动 || 切换正文类型时两侧同时切换渲染分支
demo-preview=../demos/scenarios/article.vue
:::
## 这个场景覆盖了什么
- **正文类型切换**:纯文本、Markdown、富文本三种形态共用一份数据
- **实时联动**:`ArticleEditor` 抛出的更新直接喂给 `ArticleView`
- **字段保留**:`title` 等业务字段由外层维护,编辑器不会丢字段
- **提交语义**:`submit()` 等待未完成的媒体上传后再返回最终数据
## 相关组件
- [ArticleEditor](/components/article-editor)
- [ArticleView](/components/article-view)
+24
View File
@@ -0,0 +1,24 @@
# 编辑器能力总览
把富文本编辑器、只读视图与代码编辑器放在一起,验证它们共用同一套内容模型与检索能力。
## 组合演示
:::preview 组合用法 || 两个编辑器各有独立查找栏,提交富文本会等待未完成的上传
demo-preview=../demos/scenarios/editor.vue
:::
## 这个场景覆盖了什么
- **富文本编辑**:工具栏、媒体上传、提交前的占位内容处理
- **只读渲染**:同一份 HTML 交给 `TiptapView`,展示效果与编辑态一致
- **代码编辑**:行号、语法高亮与查找替换
- **统一检索**:`openSearch()` 在两类编辑器上语义一致,便于封装统一的快捷键
## 相关组件
- [TiptapEditor](/components/tiptap-editor)
- [TiptapView](/components/tiptap-view)
- [CodeEditor](/components/code-editor)
+22
View File
@@ -0,0 +1,22 @@
# 通知编辑与预览
通知复用文章编辑器的正文能力,同时保留主题、状态等自有字段。
## 组合演示
:::preview 编辑与预览联动 || 状态字段由外层维护,切状态不会影响正文
demo-preview=../demos/scenarios/notify.vue
:::
## 这个场景覆盖了什么
- **能力复用**:`NotifyEditor` 内部就是 `ArticleEditor`,正文体验完全一致
- **元数据独立**:`subject`、`status` 等字段与正文互不干扰
- **字段透传**:业务字段在编辑过程中原样保留
## 相关组件
- [NotifyEditor](/components/notify-editor)
- [NotifyView](/components/notify-view)
+44
View File
@@ -0,0 +1,44 @@
{
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"moduleResolution": "Bundler",
"lib": [
"ESNext",
"DOM",
"DOM.Iterable"
],
"jsx": "preserve",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"types": [
"node"
],
"baseUrl": ".",
"paths": {
"~/*": [
"../src/*"
],
"timi-tdesign-pc": [
"../src/index.ts"
],
"timi-web/editor": [
"../../timi-web/src/editor/index.ts"
]
}
},
"include": [
"./**/*.ts",
"./**/*.d.ts",
"./**/*.vue"
],
"exclude": [
"node_modules",
".vitepress/cache",
".vitepress/dist"
]
}