feat: initialize Vue component library and aligned documentation

This commit is contained in:
maoyingjie
2026-10-21 09:06:28 +08:00
commit 9d40dc0ecb
149 changed files with 13208 additions and 0 deletions
+103
View File
@@ -0,0 +1,103 @@
<script setup lang="ts">
import { IconCode, IconCopy } from "@tabler/icons-vue";
import { computed, ref, watch, onBeforeUnmount, useId } from "vue";
import { highlights } from "virtual:docs-data";
const props = defineProps<{ name: string }>();
const demos = import.meta.glob("../../demos/*.vue", {
eager: true,
import: "default",
});
const sources = import.meta.glob("../../demos/*.vue", {
eager: true,
query: "?raw",
import: "default",
});
const component = computed(() => demos[`../../demos/${props.name}.vue`]);
const code = computed(() =>
String(sources[`../../demos/${props.name}.vue`] ?? ""),
);
const expanded = ref(false),
copyStatus = ref("复制代码");
const id = useId();
const highlightedCode = ref("");
watch([expanded, () => props.name], async ([open, name], _, onCleanup) => {
let current = true;
onCleanup(() => {
current = false;
});
highlightedCode.value = "";
if (open) {
try {
const result = await highlights[name]?.();
if (current) highlightedCode.value = result?.default ?? "";
} catch {
// The plain source remains available if a highlight chunk cannot load.
}
}
});
let timer: ReturnType<typeof setTimeout> | undefined;
async function copy() {
clearTimeout(timer);
try {
await navigator.clipboard.writeText(code.value);
copyStatus.value = "已复制";
timer = setTimeout(() => {
copyStatus.value = "复制代码";
}, 2000);
} catch {
expanded.value = true;
copyStatus.value = "复制失败,请手动选择代码";
}
}
onBeforeUnmount(() => clearTimeout(timer));
</script>
<template>
<div class="component-preview-container" :data-name="name">
<div class="preview not-prose">
<div class="demo-row">
<component :is="component" v-if="component" />
<p v-else role="alert">示例不存在:{{ name }}</p>
</div>
</div>
<div class="code-section">
<div class="code-toolbar">
<span class="code-language">
<span class="code-dot" aria-hidden="true" />
Vue
</span>
<div>
<button
:aria-label="(expanded ? '收起' : '展开') + name + ' 示例代码'"
:aria-controls="id"
:aria-expanded="expanded"
@click="expanded = !expanded"
>
<IconCode aria-hidden="true" :size="14" />
{{ expanded ? "收起代码" : "展开代码" }}
</button>
<button :aria-label="'复制' + name + ' 示例代码'" @click="copy">
<IconCopy aria-hidden="true" :size="14" />
复制代码
</button>
</div>
</div>
<p
class="copy-feedback"
:class="{ 'sr-only': copyStatus === '复制代码' }"
role="status"
>
{{ copyStatus === "复制代码" ? "" : copyStatus }}
</p>
<div
v-if="expanded"
:id="id"
class="highlighted-source"
tabindex="0"
:aria-label="name + ' 示例源码'"
>
<div v-if="highlightedCode" v-html="highlightedCode" />
<pre v-else><code>{{ code }}</code></pre>
</div>
</div>
</div>
</template>
+156
View File
@@ -0,0 +1,156 @@
<script setup lang="ts">
import { IconSearch } from "@tabler/icons-vue";
import {
computed,
ref,
watch,
onMounted,
onBeforeUnmount,
nextTick,
} from "vue";
import { withBase, useRouter } from "vitepress";
import {
DialogRoot,
DialogTrigger,
DialogPortal,
DialogOverlay,
DialogContent,
DialogTitle,
DialogDescription,
DialogClose,
} from "reka-ui";
import { searchIndex } from "virtual:docs-data";
import { searchDocs, searchExcerpt } from "./search";
const router = useRouter();
const navigating = ref(false);
const open = ref(false),
query = ref(""),
active = ref(0),
field = ref<HTMLInputElement>();
const results = computed(() => searchDocs(searchIndex, query.value));
watch(query, () => {
active.value = 0;
});
watch(open, (value) => {
if (!value) query.value = "";
else navigating.value = false;
});
function shortcut(event: KeyboardEvent) {
if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "k") {
event.preventDefault();
open.value = !open.value;
}
}
function move(delta: number) {
if (!results.value.length) return;
active.value =
(active.value + delta + results.value.length) % results.value.length;
void nextTick(() =>
document
.getElementById("search-result-" + active.value)
?.scrollIntoView({ block: "nearest" }),
);
}
async function navigateTo(entry: (typeof searchIndex)[number]) {
navigating.value = true;
open.value = false;
await router.go(withBase(entry.url));
await nextTick();
const id = entry.url.split("#")[1];
const target = id
? document.getElementById(decodeURIComponent(id))
: document.querySelector<HTMLElement>(".docs-main h1");
target?.setAttribute("tabindex", "-1");
target?.focus({ preventScroll: true });
}
function navigate() {
const entry = results.value[active.value];
if (entry) void navigateTo(entry);
}
function closeAutoFocus(event: Event) {
if (navigating.value) event.preventDefault();
}
onMounted(() => window.addEventListener("keydown", shortcut));
onBeforeUnmount(() => window.removeEventListener("keydown", shortcut));
</script>
<template>
<DialogRoot v-model:open="open">
<DialogTrigger class="search-trigger" aria-label="搜索文档">
<IconSearch aria-hidden="true" :size="17" />
<span>搜索文档…</span>
<kbd>⌘ / Ctrl K</kbd>
</DialogTrigger>
<DialogPortal>
<DialogOverlay class="search-overlay" />
<DialogContent
class="search-dialog"
@open-auto-focus.prevent="field?.focus()"
@close-auto-focus="closeAutoFocus"
>
<DialogTitle class="sr-only">搜索文档</DialogTitle>
<DialogDescription class="sr-only">
搜索组件、参数和用法;使用方向键选择,回车打开,Esc 关闭。
</DialogDescription>
<div class="search-field">
<input
ref="field"
v-model="query"
placeholder="搜索组件、参数或用法…"
aria-label="搜索组件、参数或用法"
role="combobox"
aria-autocomplete="list"
aria-controls="doc-search-results"
:aria-expanded="Boolean(query.trim())"
:aria-activedescendant="
results.length ? 'search-result-' + active : undefined
"
@keydown.down.prevent="move(1)"
@keydown.up.prevent="move(-1)"
@keydown.enter.prevent="navigate"
/>
<DialogClose class="search-close" aria-label="关闭搜索">
Esc
</DialogClose>
</div>
<div
class="search-results"
id="doc-search-results"
role="listbox"
aria-label="搜索结果"
>
<p v-if="!query.trim()" class="search-empty">
试试搜索「isPending」「主题」或「受控」
</p>
<p v-else-if="!results.length" class="search-empty" role="status">
没有找到“{{ query }}”,试试组件名或参数名。
</p>
<a
v-for="(entry, index) in results"
:id="'search-result-' + index"
:key="entry.url"
:href="withBase(entry.url)"
role="option"
:aria-selected="index === active"
:tabindex="-1"
@mousemove="active = index"
@click.prevent="navigateTo(entry)"
>
<span class="result-title">
{{ entry.title }}
<span>{{ entry.section }}</span>
</span>
<span class="result-excerpt">
{{ searchExcerpt(entry, query) || "查看文档" }}
</span>
</a>
</div>
<div class="search-footer" aria-live="polite">
<span>
{{ query.trim() ? results.length + " 条结果" : "本地文档搜索" }}
</span>
<span>↑ ↓ 选择 ↵ 打开</span>
</div>
</DialogContent>
</DialogPortal>
</DialogRoot>
</template>
+300
View File
@@ -0,0 +1,300 @@
<script setup lang="ts">
import {
IconSun,
IconMoon,
IconMenu2,
IconX,
IconArrowUpRight,
} from "@tabler/icons-vue";
import {
computed,
ref,
watch,
nextTick,
onMounted,
onBeforeUnmount,
} from "vue";
import { useData, useRoute, withBase, onContentUpdated } from "vitepress";
import {
DialogRoot,
DialogTrigger,
DialogPortal,
DialogOverlay,
DialogContent,
DialogTitle,
DialogClose,
} from "reka-ui";
import DocSearch from "./DocSearch.vue";
const { frontmatter, page, isDark } = useData();
const route = useRoute();
const mobile = ref(false),
activeSlug = ref("");
const copyMessage = ref("");
let copyTimer: ReturnType<typeof setTimeout> | undefined;
onBeforeUnmount(() => clearTimeout(copyTimer));
const groups = [
{
title: "开始使用",
items: [
{ title: "介绍", url: "/introduction" },
{ title: "安装", url: "/guide" },
{ title: "主题", url: "/themes" },
],
},
{
title: "组件",
items: [
{ title: "Button 按钮", url: "/components/button" },
{ title: "Card 卡片", url: "/components/card" },
{ title: "Input 输入框", url: "/components/input" },
{ title: "Switch 开关", url: "/components/switch" },
],
},
];
const items = groups.flatMap((g) => g.items);
const currentIndex = computed(() =>
items.findIndex((item) => selected(item.url)),
);
const previous = computed(() => items[currentIndex.value - 1]);
const next = computed(() => items[currentIndex.value + 1]);
function selected(url: string) {
return (
route.path === withBase(url) ||
route.path === withBase(url + ".html") ||
(url === "/components/button" && route.path === withBase("/"))
);
}
const headers = computed(() => page.value.headers ?? []);
const flatHeaders = computed(() =>
headers.value.flatMap((h) => [h, ...(h.children ?? [])]),
);
let ticking = false;
function updateActive() {
ticking = false;
const headings = flatHeaders.value
.map((h) => document.getElementById(h.slug))
.filter((el): el is HTMLElement => Boolean(el));
let active = headings[0]?.id ?? "";
for (const heading of headings) {
if (heading.getBoundingClientRect().top <= 120) active = heading.id;
else break;
}
activeSlug.value = active;
}
function onScroll() {
if (!ticking) {
ticking = true;
requestAnimationFrame(updateActive);
}
}
onMounted(() => {
window.addEventListener("scroll", onScroll, { passive: true });
updateActive();
});
onBeforeUnmount(() => window.removeEventListener("scroll", onScroll));
onContentUpdated(() => {
void nextTick(updateActive);
});
watch(
() => route.path,
() => {
mobile.value = false;
void nextTick(() => {
if (!window.location.hash)
window.scrollTo({ top: 0, behavior: "instant" });
updateActive();
});
},
);
async function copyMarkdownCode(event: MouseEvent) {
const target = (event.target as HTMLElement).closest<HTMLButtonElement>(
"button.copy",
);
if (!target) return;
const code = target.parentElement?.querySelector("pre code")?.textContent;
if (!code) return;
try {
await navigator.clipboard.writeText(code);
target.classList.add("copied");
target.setAttribute("aria-label", "已复制");
copyMessage.value = "代码已复制";
clearTimeout(copyTimer);
copyTimer = setTimeout(() => {
target.classList.remove("copied");
target.setAttribute("aria-label", "复制代码");
copyMessage.value = "";
}, 2000);
} catch {
target.setAttribute("aria-label", "复制失败,请手动选择代码");
copyMessage.value = "复制失败,请手动选择代码";
}
}
</script>
<template>
<div class="docs-layout">
<a class="skip" href="#main">跳至内容</a>
<p class="sr-only" role="status">{{ copyMessage }}</p>
<header class="docs-nav">
<a class="brand" :href="withBase('/components/button')">
heroui
<span>Vue</span>
</a>
<span class="version">v0.0.1</span>
<nav aria-label="主导航">
<a
:href="withBase('/guide')"
:class="{
active:
!frontmatter.component && route.path !== withBase('/themes'),
}"
>
文档
</a>
<a
:href="withBase('/components/button')"
:class="{ active: Boolean(frontmatter.component) }"
>
组件
</a>
<a
:href="withBase('/themes')"
:class="{ active: route.path === withBase('/themes') }"
>
主题
</a>
</nav>
<div class="nav-tools">
<DocSearch />
<button
class="theme-toggle"
:aria-label="isDark ? '切换浅色主题' : '切换深色主题'"
@click="isDark = !isDark"
>
<IconSun v-if="isDark" aria-hidden="true" :size="18" />
<IconMoon v-else aria-hidden="true" :size="18" />
</button>
<DialogRoot v-model:open="mobile">
<DialogTrigger class="mobile-menu" aria-label="打开文档目录">
<IconMenu2 aria-hidden="true" :size="20" />
</DialogTrigger>
<DialogPortal>
<DialogOverlay class="mobile-nav-overlay" />
<DialogContent class="mobile-nav-dialog">
<div class="mobile-nav-heading">
<DialogTitle>文档目录</DialogTitle>
<DialogClose aria-label="关闭文档目录">
<IconX aria-hidden="true" :size="20" />
</DialogClose>
</div>
<nav aria-label="移动端文档导航">
<section v-for="group in groups" :key="group.title">
<h2>{{ group.title }}</h2>
<a
v-for="item in group.items"
:key="item.url"
:href="withBase(item.url)"
:aria-current="selected(item.url) ? 'page' : undefined"
@click="mobile = false"
>
{{ item.title }}
</a>
</section>
</nav>
</DialogContent>
</DialogPortal>
</DialogRoot>
</div>
</header>
<div class="docs-body">
<aside class="docs-sidebar" aria-label="文档导航">
<div class="framework">
<span class="vue-mark">V</span>
Vue
<span class="framework-note">组件库</span>
</div>
<section v-for="group in groups" :key="group.title">
<h2>{{ group.title }}</h2>
<a
v-for="item in group.items"
:key="item.url"
:href="withBase(item.url)"
:class="{ selected: selected(item.url) }"
:aria-current="selected(item.url) ? 'page' : undefined"
>
{{ item.title }}
</a>
</section>
<p class="community">
独立社区实现
<br />
设计基线 HeroUI v3.2.6
</p>
</aside>
<main id="main" class="docs-main">
<div class="breadcrumb">
{{ frontmatter.group ?? "文档" }}
<span>›</span>
{{ frontmatter.title }}
</div>
<h1>{{ frontmatter.title }}</h1>
<p class="page-description">{{ frontmatter.description }}</p>
<div v-if="frontmatter.component" class="source-links">
<a
:href="`https://github.com/heroui-inc/heroui/tree/ce90ea3ab49d58f6c428f71bfd6fe8ae2a87b960/packages/react/src/components/${frontmatter.component}`"
target="_blank"
rel="noreferrer"
>
React 参考源码
<IconArrowUpRight aria-hidden="true" :size="12" />
</a>
<a
:href="`https://github.com/heroui-inc/heroui/blob/ce90ea3ab49d58f6c428f71bfd6fe8ae2a87b960/packages/styles/components/${frontmatter.component}.css`"
target="_blank"
rel="noreferrer"
>
样式源码
<IconArrowUpRight aria-hidden="true" :size="12" />
</a>
</div>
<div @click="copyMarkdownCode"><Content class="docs-content" /></div>
<nav class="page-navigation" aria-label="相邻页面">
<a v-if="previous" :href="withBase(previous.url)">
<span>上一页</span>
<strong>{{ previous.title }}</strong>
</a>
<a v-if="next" class="page-next" :href="withBase(next.url)">
<span>下一页</span>
<strong>{{ next.title }}</strong>
</a>
</nav>
<footer class="docs-footer">
基于 HeroUI v3 设计的 Vue 实现 ·
<a :href="withBase('/introduction')">实现范围与差异</a>
</footer>
</main>
<aside v-if="headers.length" class="docs-toc" aria-label="本页目录">
<p>本页内容</p>
<template v-for="h in headers" :key="h.slug">
<a
:href="'#' + h.slug"
:class="{ current: activeSlug === h.slug }"
:aria-current="activeSlug === h.slug ? 'location' : undefined"
>
{{ h.title }}
</a>
<a
v-for="child in h.children"
:key="child.slug"
class="nested"
:class="{ current: activeSlug === child.slug }"
:aria-current="activeSlug === child.slug ? 'location' : undefined"
:href="'#' + child.slug"
>
{{ child.title }}
</a>
</template>
</aside>
</div>
</div>
</template>
+12
View File
@@ -0,0 +1,12 @@
import type { Theme } from "vitepress";
import Layout from "./Layout.vue";
import Demo from "./Demo.vue";
import "@heroui-vue/styles/css";
import "./utilities.css";
import "./style.css";
export default {
Layout,
enhanceApp({ app }) {
app.component("ComponentPreview", Demo);
},
} satisfies Theme;
+55
View File
@@ -0,0 +1,55 @@
export interface SearchEntry {
title: string;
section: string;
url: string;
text: string;
}
export function searchDocs(
entries: SearchEntry[],
query: string,
): SearchEntry[] {
const terms = query.toLocaleLowerCase().trim().split(/\s+/).filter(Boolean);
if (!terms.length) return [];
return entries
.map((entry, index) => {
const title = entry.title.toLocaleLowerCase(),
section = entry.section.toLocaleLowerCase(),
text = entry.text.toLocaleLowerCase();
if (
!terms.every((term) =>
(title + " " + section + " " + text).includes(term),
)
)
return null;
const score = terms.reduce(
(score, term) =>
score +
(title.includes(term) ? 12 : 0) +
(section.includes(term) ? 8 : 0) +
(text.includes(term) ? 1 : 0),
0,
);
return { entry, score, index };
})
.filter((item): item is NonNullable<typeof item> => item !== null)
.sort((a, b) => b.score - a.score || a.index - b.index)
.slice(0, 20)
.map((item) => item.entry);
}
export function searchExcerpt(entry: SearchEntry, query: string): string {
const text = entry.text
.replace(/[-:|]{3,}/g, " ")
.replace(/\s+/g, " ")
.trim();
const terms = query.trim().toLocaleLowerCase().split(/\s+/).filter(Boolean);
const positions = terms
.map((term) => text.toLocaleLowerCase().indexOf(term))
.filter((index) => index >= 0);
const start = positions.length ? Math.max(0, Math.min(...positions) - 28) : 0;
return (
(start ? "…" : "") +
text.slice(start, start + 140) +
(text.length > start + 140 ? "…" : "")
);
}
File diff suppressed because it is too large Load Diff
+15
View File
@@ -0,0 +1,15 @@
@import "tailwindcss/theme.css" layer(theme);
@import "../../../../packages/styles/themes/shared/theme.css";
@import "tailwindcss/utilities.css" layer(utilities);
@source "../../demos";
/* Follow the document's explicit theme, including nested preview scopes. */
@custom-variant dark (&:where(.dark, .dark *, [data-theme="dark"], [data-theme="dark"] *));
@custom-variant motion-reduce {
&:is([data-reduce-motion="true"], [data-reduce-motion="true"] *) {
@slot;
}
@media (prefers-reduced-motion: reduce) {
@slot;
}
}