chore(docs): eslint migration + extractor updates

Migrate docs to eslint flat config (build-script console override); doc
extractor points at configs/eslint.
This commit is contained in:
2026-06-07 16:30:14 +07:00
parent 23a2795523
commit 96ac895f7a
30 changed files with 1934 additions and 864 deletions
+167 -45
View File
@@ -1,69 +1,191 @@
@import "tailwindcss";
@source "../../../../vue/toolkit/src/**/demo.vue";
@source "../../../../vue/primitives/src/**/demo.vue";
@source "../../../../core/stdlib/src/**/demo.vue";
@source "../../../../core/platform/src/**/demo.vue";
/* Class-based dark mode (toggled on <html class="dark">) */
@custom-variant dark (&:where(.dark, .dark *));
@theme {
--font-sans: 'Inter', system-ui, sans-serif;
--font-mono: 'JetBrains Mono', monospace;
--font-sans: 'Inter', system-ui, -apple-system, sans-serif;
--font-mono: 'JetBrains Mono', ui-monospace, SFMono-Regular, monospace;
--color-brand-50: #eef2ff;
--color-brand-100: #e0e7ff;
--color-brand-200: #c7d2fe;
--color-brand-300: #a5b4fc;
--color-brand-400: #818cf8;
--color-brand-500: #6366f1;
--color-brand-600: #4f46e5;
--color-brand-700: #4338ca;
--color-brand-800: #3730a3;
--color-brand-900: #312e81;
--color-brand-950: #1e1b4b;
--radius-card: 0.75rem;
}
/* ── Semantic design tokens — Geist-minimal ──────────────────────────────── */
:root {
--color-bg: #ffffff;
--color-bg-soft: #f9fafb;
--color-bg-mute: #f3f4f6;
--color-border: #e5e7eb;
--color-text: #111827;
--color-text-soft: #4b5563;
--color-text-mute: #9ca3af;
--color-header-bg: rgba(255, 255, 255, 0.8);
--bg: #ffffff;
--bg-subtle: #fafafa;
--bg-elevated: #ffffff;
--bg-inset: #f4f4f5;
--border: #ececec;
--border-strong: #d8d8dc;
--fg: #18181b;
--fg-muted: #52525b;
--fg-subtle: #a1a1aa;
--accent: #2563eb;
--accent-hover: #1d4ed8;
--accent-fg: #ffffff;
--accent-subtle: #eef3ff;
--accent-text: #2563eb;
--header-bg: rgba(255, 255, 255, 0.72);
--ring: rgba(37, 99, 235, 0.35);
--shadow-card: 0 1px 2px rgba(16, 24, 40, 0.04), 0 1px 3px rgba(16, 24, 40, 0.06);
color-scheme: light;
}
@media (prefers-color-scheme: dark) {
:root {
--color-bg: #0f172a;
--color-bg-soft: #1e293b;
--color-bg-mute: #334155;
--color-border: #334155;
--color-text: #f1f5f9;
--color-text-soft: #94a3b8;
--color-text-mute: #64748b;
--color-header-bg: rgba(15, 23, 42, 0.8);
}
.dark {
--bg: #0a0a0a;
--bg-subtle: #0f0f10;
--bg-elevated: #141416;
--bg-inset: #1b1b1e;
--border: #232327;
--border-strong: #34343a;
--fg: #ededed;
--fg-muted: #a1a1aa;
--fg-subtle: #6c6c75;
--accent: #3b82f6;
--accent-hover: #60a5fa;
--accent-fg: #ffffff;
--accent-subtle: #14203a;
--accent-text: #74a8ff;
--header-bg: rgba(10, 10, 10, 0.72);
--ring: rgba(59, 130, 246, 0.4);
--shadow-card: 0 1px 2px rgba(0, 0, 0, 0.4), 0 1px 3px rgba(0, 0, 0, 0.5);
color-scheme: dark;
}
html {
scroll-behavior: smooth;
scroll-padding-top: 5rem;
}
body {
background-color: var(--color-bg);
color: var(--color-text);
background-color: var(--bg);
color: var(--fg);
font-family: var(--font-sans);
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-rendering: optimizeLegibility;
}
code, pre {
code, pre, kbd {
font-family: var(--font-mono);
}
/* Shiki dual-theme: activate dark colors via prefers-color-scheme */
@media (prefers-color-scheme: dark) {
.shiki,
.shiki span {
color: var(--shiki-dark) !important;
background-color: var(--shiki-dark-bg) !important;
font-style: var(--shiki-dark-font-style) !important;
font-weight: var(--shiki-dark-font-weight) !important;
text-decoration: var(--shiki-dark-text-decoration) !important;
}
::selection {
background-color: var(--accent-subtle);
color: var(--accent-text);
}
/* Subtle, theme-aware scrollbars */
* {
scrollbar-width: thin;
scrollbar-color: var(--border-strong) transparent;
}
*::-webkit-scrollbar { width: 8px; height: 8px; }
*::-webkit-scrollbar-thumb { background: var(--border-strong); border-radius: 9999px; }
*::-webkit-scrollbar-track { background: transparent; }
/* Shiki dual-theme: switch to dark colors under .dark */
.dark .shiki,
.dark .shiki span {
color: var(--shiki-dark) !important;
background-color: var(--shiki-dark-bg) !important;
font-style: var(--shiki-dark-font-style) !important;
font-weight: var(--shiki-dark-font-weight) !important;
text-decoration: var(--shiki-dark-text-decoration) !important;
}
/* ── Markdown (guide) typography ──────────────────────────────────────────── */
.prose-docs {
color: var(--fg-muted);
font-size: 0.9375rem;
line-height: 1.7;
}
.prose-docs > :first-child { margin-top: 0; }
.prose-docs h1 {
color: var(--fg);
font-size: 1.875rem;
font-weight: 700;
letter-spacing: -0.02em;
margin: 0 0 1rem;
}
.prose-docs h2 {
color: var(--fg);
font-size: 1.375rem;
font-weight: 650;
letter-spacing: -0.01em;
margin: 2.5rem 0 1rem;
padding-bottom: 0.5rem;
border-bottom: 1px solid var(--border);
scroll-margin-top: 5rem;
}
.prose-docs h3 {
color: var(--fg);
font-size: 1.0625rem;
font-weight: 600;
margin: 2rem 0 0.75rem;
scroll-margin-top: 5rem;
}
.prose-docs p { margin: 1rem 0; }
.prose-docs a {
color: var(--accent-text);
text-decoration: none;
font-weight: 500;
}
.prose-docs a:hover { text-decoration: underline; }
.prose-docs strong { color: var(--fg); font-weight: 600; }
.prose-docs ul, .prose-docs ol { margin: 1rem 0; padding-left: 1.5rem; }
.prose-docs ul { list-style: disc; }
.prose-docs ol { list-style: decimal; }
.prose-docs li { margin: 0.375rem 0; }
.prose-docs li::marker { color: var(--fg-subtle); }
.prose-docs blockquote {
border-left: 3px solid var(--border-strong);
padding-left: 1rem;
margin: 1.25rem 0;
color: var(--fg-muted);
}
.prose-docs hr { border: 0; border-top: 1px solid var(--border); margin: 2rem 0; }
/* inline code */
.prose-docs :not(pre) > code {
font-size: 0.85em;
background-color: var(--bg-inset);
border: 1px solid var(--border);
border-radius: 0.375rem;
padding: 0.1rem 0.35rem;
color: var(--fg);
}
/* fenced code (shiki replaces, but style the fallback + wrapper) */
.prose-docs pre {
background-color: var(--bg-subtle);
border: 1px solid var(--border);
border-radius: 0.625rem;
padding: 1rem;
overflow-x: auto;
margin: 1.25rem 0;
font-size: 0.85rem;
line-height: 1.6;
}
.prose-docs pre code { background: none; border: 0; padding: 0; }
.prose-docs table {
width: 100%;
border-collapse: collapse;
margin: 1.25rem 0;
font-size: 0.875rem;
}
.prose-docs th, .prose-docs td {
border: 1px solid var(--border);
padding: 0.5rem 0.75rem;
text-align: left;
}
.prose-docs th { background-color: var(--bg-subtle); color: var(--fg); font-weight: 600; }
/* Page-enter fade for route transitions */
.page-enter-active, .page-leave-active { transition: opacity 0.18s ease, transform 0.18s ease; }
.page-enter-from { opacity: 0; transform: translateY(4px); }
.page-leave-to { opacity: 0; }
+11 -7
View File
@@ -4,12 +4,14 @@
}>();
const kindColors: Record<string, string> = {
function: 'bg-indigo-100 text-indigo-700 dark:bg-indigo-900/30 dark:text-indigo-300',
class: 'bg-violet-100 text-violet-700 dark:bg-violet-900/30 dark:text-violet-300',
interface: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-300',
type: 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300',
enum: 'bg-rose-100 text-rose-700 dark:bg-rose-900/30 dark:text-rose-300',
variable: 'bg-slate-100 text-slate-700 dark:bg-slate-800/50 dark:text-slate-300',
function: 'bg-blue-100 text-blue-700 dark:bg-blue-500/15 dark:text-blue-300',
class: 'bg-violet-100 text-violet-700 dark:bg-violet-500/15 dark:text-violet-300',
interface: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-500/15 dark:text-emerald-300',
type: 'bg-amber-100 text-amber-700 dark:bg-amber-500/15 dark:text-amber-300',
enum: 'bg-rose-100 text-rose-700 dark:bg-rose-500/15 dark:text-rose-300',
variable: 'bg-zinc-100 text-zinc-600 dark:bg-zinc-500/15 dark:text-zinc-300',
component: 'bg-fuchsia-100 text-fuchsia-700 dark:bg-fuchsia-500/15 dark:text-fuchsia-300',
guide: 'bg-teal-100 text-teal-700 dark:bg-teal-500/15 dark:text-teal-300',
};
const kindLabels: Record<string, string> = {
@@ -19,13 +21,15 @@ const kindLabels: Record<string, string> = {
type: 'T',
enum: 'E',
variable: 'V',
component: '◇',
guide: '¶',
};
</script>
<template>
<span
:class="[
'inline-flex items-center justify-center rounded font-mono font-medium shrink-0',
'inline-flex items-center justify-center rounded-md font-mono font-semibold shrink-0',
kindColors[kind] ?? kindColors.variable,
size === 'sm' ? 'w-5 h-5 text-[10px]' : 'w-6 h-6 text-xs',
]"
+63 -9
View File
@@ -1,27 +1,81 @@
<script setup lang="ts">const props = defineProps<{
code: string;
lang?: string;
/** Show the header bar with language label + copy button */
bare?: boolean;
}>();
const { highlight } = useShiki();
const html = ref('');
onMounted(async () => {
html.value = await highlight(props.code, props.lang ?? 'typescript');
});
const resolvedLang = computed(() => props.lang ?? 'typescript');
const langLabel = computed(() => ({
typescript: 'ts',
javascript: 'js',
bash: 'sh',
vue: 'vue',
json: 'json',
}[resolvedLang.value] ?? resolvedLang.value));
watch(() => props.code, async (newCode) => {
html.value = await highlight(newCode, props.lang ?? 'typescript');
});
async function render() {
html.value = await highlight(props.code, resolvedLang.value);
}
onMounted(render);
watch(() => props.code, render);
const copied = ref(false);
let copyTimer: ReturnType<typeof setTimeout> | undefined;
async function copy() {
try {
await navigator.clipboard.writeText(props.code);
copied.value = true;
clearTimeout(copyTimer);
copyTimer = setTimeout(() => (copied.value = false), 1500);
}
catch { /* clipboard unavailable */ }
}
</script>
<template>
<div class="code-block relative group rounded-lg border border-(--color-border) overflow-hidden max-w-full">
<div class="group relative rounded-xl border border-(--border) bg-(--bg-subtle) overflow-hidden max-w-full">
<div v-if="!bare" class="flex items-center justify-between px-3 h-9 border-b border-(--border) bg-(--bg-subtle)">
<span class="text-[11px] font-mono uppercase tracking-wider text-(--fg-subtle)">{{ langLabel }}</span>
<button
type="button"
class="inline-flex items-center gap-1 text-[11px] font-medium text-(--fg-subtle) hover:text-(--fg) transition-colors cursor-pointer"
@click="copy"
>
<svg v-if="!copied" xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<rect x="9" y="9" width="13" height="13" rx="2" /><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />
</svg>
<svg v-else xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-emerald-500">
<path d="M20 6 9 17l-5-5" />
</svg>
{{ copied ? 'Copied' : 'Copy' }}
</button>
</div>
<button
v-else
type="button"
class="absolute right-2 top-2 z-10 inline-flex items-center justify-center w-7 h-7 rounded-md bg-(--bg-elevated) border border-(--border) text-(--fg-subtle) opacity-0 group-hover:opacity-100 hover:text-(--fg) transition-all cursor-pointer"
title="Copy"
@click="copy"
>
<svg v-if="!copied" xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<rect x="9" y="9" width="13" height="13" rx="2" /><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />
</svg>
<svg v-else xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-emerald-500">
<path d="M20 6 9 17l-5-5" />
</svg>
</button>
<div
v-if="html"
class="overflow-x-auto text-sm leading-relaxed [&_pre]:p-4 [&_pre]:m-0 [&_pre]:min-w-0"
class="overflow-x-auto text-[13px] leading-relaxed [&_pre]:p-4 [&_pre]:m-0 [&_pre]:bg-transparent! [&_pre]:min-w-0"
v-html="html"
/>
<pre v-else class="p-4 text-sm bg-(--color-bg-soft) overflow-x-auto"><code>{{ code }}</code></pre>
<pre v-else class="p-4 text-[13px] overflow-x-auto"><code>{{ code }}</code></pre>
</div>
</template>
@@ -0,0 +1,96 @@
<script setup lang="ts">import type { ComponentMeta } from '../../modules/extractor/types';
const props = defineProps<{
component: ComponentMeta;
packageName: string;
}>();
const importPath = computed(() => {
const sub = props.component.entryPoint.replace(/^\.\/?/, '');
return sub ? `${props.packageName}/${sub}` : props.packageName;
});
const partNames = computed(() => props.component.parts.map(p => p.name));
/** Import statement + a composition skeleton (Root wraps the remaining parts). */
const anatomyCode = computed(() => {
const names = partNames.value;
if (names.length === 0) return '';
const imports = `import {\n${names.map(n => ` ${n},`).join('\n')}\n} from '${importPath.value}';`;
const [root, ...rest] = names;
let tree: string;
if (rest.length === 0) {
tree = `<${root} />`;
}
else {
tree = `<${root}>\n${rest.map(n => ` <${n} />`).join('\n')}\n</${root}>`;
}
return `${imports}\n\n${tree}`;
});
const roleColor: Record<string, string> = {
Root: 'bg-fuchsia-100 text-fuchsia-700 dark:bg-fuchsia-500/15 dark:text-fuchsia-300',
};
</script>
<template>
<div class="space-y-10">
<!-- Anatomy snippet -->
<section>
<h2 class="text-xs font-semibold uppercase tracking-wider text-(--fg-subtle) mb-3">
Anatomy
</h2>
<p class="text-sm text-(--fg-muted) mb-3">
Import the parts and compose them. Each part forwards attributes to its underlying element.
</p>
<DocsCode :code="anatomyCode" lang="vue" />
</section>
<!-- Parts -->
<section>
<h2 class="text-xs font-semibold uppercase tracking-wider text-(--fg-subtle) mb-4">
API Reference
</h2>
<div class="space-y-8">
<div
v-for="part in component.parts"
:id="part.name.toLowerCase()"
:key="part.name"
class="scroll-mt-20"
>
<div class="flex items-center gap-2.5 mb-2">
<h3 class="font-mono text-base font-semibold text-(--fg)">{{ part.name }}</h3>
<span
:class="[
'text-[11px] px-2 py-0.5 rounded-full font-medium leading-none',
roleColor[part.role] ?? 'bg-(--bg-inset) text-(--fg-muted) border border-(--border)',
]"
>
{{ part.role }}
</span>
</div>
<p v-if="part.description" class="text-sm text-(--fg-muted) mb-3 max-w-2xl">
{{ part.description }}
</p>
<div v-if="part.props.length > 0" class="mb-3">
<DocsPropsTable :properties="part.props" label="Prop" />
</div>
<div v-if="part.emits.length > 0" class="mb-3">
<div class="text-[11px] font-semibold uppercase tracking-wider text-(--fg-subtle) mb-2">Emits</div>
<DocsEmitsTable :emits="part.emits" />
</div>
<p v-if="part.props.length === 0 && part.emits.length === 0" class="text-sm text-(--fg-subtle) italic">
No props or events renders its element and forwards attributes.
</p>
</div>
</div>
</section>
</div>
</template>
+12 -31
View File
@@ -13,49 +13,30 @@ watch(showSource, async (show) => {
if (show && !highlighted.value) {
await highlightReactive(props.source, 'vue');
}
}, { immediate: false });
});
</script>
<template>
<div class="border border-(--color-border) rounded-lg overflow-hidden">
<div class="rounded-xl border border-(--border) overflow-hidden">
<!-- Live demo -->
<div class="p-6 bg-(--color-bg-soft)">
<div class="p-8 bg-(--bg-subtle) flex items-center justify-center min-h-32">
<component :is="component" />
</div>
<!-- Source toggle bar -->
<div class="flex items-center border-t border-(--color-border) bg-(--color-bg)">
<div class="flex items-center border-t border-(--border) bg-(--bg-elevated)">
<button
class="flex items-center gap-1.5 px-4 py-2 text-xs font-medium text-(--color-text-mute) hover:text-(--color-text) transition-colors cursor-pointer"
type="button"
class="flex items-center gap-1.5 px-4 py-2.5 text-xs font-medium text-(--fg-muted) hover:text-(--fg) transition-colors cursor-pointer"
@click="showSource = !showSource"
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="14"
height="14"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<polyline points="16 18 22 12 16 6" />
<polyline points="8 6 2 12 8 18" />
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<polyline points="16 18 22 12 16 6" /><polyline points="8 6 2 12 8 18" />
</svg>
{{ showSource ? 'Hide source' : 'View source' }}
<svg
xmlns="http://www.w3.org/2000/svg"
width="12"
height="12"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
class="transition-transform"
:class="showSource ? 'rotate-180' : ''"
xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
class="transition-transform" :class="showSource ? 'rotate-180' : ''"
>
<polyline points="6 9 12 15 18 9" />
</svg>
@@ -63,8 +44,8 @@ watch(showSource, async (show) => {
</div>
<!-- Source code -->
<div v-if="showSource" class="border-t border-(--color-border)">
<div class="overflow-x-auto text-sm" v-html="highlighted" />
<div v-if="showSource" class="border-t border-(--border) bg-(--bg-subtle)">
<div class="overflow-x-auto text-[13px] [&_pre]:p-4 [&_pre]:m-0 [&_pre]:bg-transparent!" v-html="highlighted" />
</div>
</div>
</template>
+29
View File
@@ -0,0 +1,29 @@
<script setup lang="ts">import type { EmitMeta } from '../../modules/extractor/types';
defineProps<{
emits: EmitMeta[];
}>();
</script>
<template>
<div v-if="emits.length > 0" class="overflow-hidden rounded-xl border border-(--border)">
<table class="w-full text-sm border-collapse">
<thead>
<tr class="bg-(--bg-subtle) text-left">
<th class="py-2.5 px-4 font-medium text-(--fg-muted) text-xs uppercase tracking-wider">Event</th>
<th class="py-2.5 px-4 font-medium text-(--fg-muted) text-xs uppercase tracking-wider">Payload</th>
</tr>
</thead>
<tbody>
<tr v-for="e in emits" :key="e.name" class="border-t border-(--border) align-top">
<td class="py-2.5 px-4 whitespace-nowrap">
<code class="text-(--accent-text) font-mono text-[13px] font-medium">{{ e.name }}</code>
</td>
<td class="py-2.5 px-4">
<code class="text-xs font-mono text-(--fg-muted) bg-(--bg-inset) px-1.5 py-0.5 rounded border border-(--border) wrap-break-word">{{ e.payload }}</code>
</td>
</tr>
</tbody>
</table>
</div>
</template>
+48
View File
@@ -0,0 +1,48 @@
<script setup lang="ts">const props = defineProps<{
source: string;
}>();
const { highlight } = useShiki();
const html = computed(() => renderMarkdown(props.source));
const root = ref<HTMLElement | null>(null);
/** Replace marked's <pre><code> blocks with Shiki-highlighted markup. */
async function highlightCodeBlocks() {
const el = root.value;
if (!el) return;
const blocks = Array.from(el.querySelectorAll('pre > code'));
for (const code of blocks) {
const langClass = Array.from(code.classList).find(c => c.startsWith('language-'));
const lang = langClass?.replace('language-', '') || 'typescript';
const supported = ['typescript', 'javascript', 'ts', 'js', 'vue', 'json', 'bash', 'sh'];
const resolved = supported.includes(lang)
? ({ ts: 'typescript', js: 'javascript', sh: 'bash' }[lang] ?? lang)
: 'typescript';
const text = code.textContent ?? '';
const pre = code.parentElement;
if (!pre) continue;
try {
const out = await highlight(text, resolved);
const wrapper = document.createElement('div');
wrapper.className = 'not-prose rounded-xl border border-(--border) bg-(--bg-subtle) overflow-x-auto text-[13px] my-5 [&_pre]:p-4 [&_pre]:m-0 [&_pre]:bg-transparent!';
wrapper.innerHTML = out;
pre.replaceWith(wrapper);
}
catch { /* leave the fallback <pre> as-is */ }
}
}
onMounted(highlightCodeBlocks);
watch(() => props.source, async () => {
await nextTick();
await highlightCodeBlocks();
});
</script>
<template>
<div ref="root" class="prose-docs max-w-none" v-html="html" />
</template>
+8 -8
View File
@@ -6,23 +6,23 @@ defineProps<{
</script>
<template>
<div v-if="methods.length > 0" class="space-y-4">
<div v-if="methods.length > 0" class="space-y-3">
<div
v-for="method in methods"
:key="method.name"
class="border border-(--color-border) rounded-lg p-4"
class="rounded-xl border border-(--border) bg-(--bg-subtle) p-4"
>
<div class="flex items-center gap-2 mb-2">
<code class="text-sm font-mono font-semibold text-(--color-text)">{{ method.name }}</code>
<code class="text-sm font-mono font-semibold text-(--fg)">{{ method.name }}</code>
<span
v-if="method.visibility !== 'public'"
class="text-[10px] uppercase px-1.5 py-0.5 rounded bg-(--color-bg-mute) text-(--color-text-mute)"
class="text-[10px] uppercase px-1.5 py-0.5 rounded bg-(--bg-inset) border border-(--border) text-(--fg-subtle)"
>
{{ method.visibility }}
</span>
</div>
<p v-if="method.description" class="text-sm text-(--color-text-soft) mb-3">
<p v-if="method.description" class="text-sm text-(--fg-muted) mb-3">
{{ method.description }}
</p>
@@ -36,9 +36,9 @@ defineProps<{
<DocsParamsTable v-if="method.params.length > 0" :params="method.params" />
<div v-if="method.returns" class="mt-2 text-sm">
<span class="text-(--color-text-mute)">Returns:</span>
<code class="ml-1 text-xs font-mono bg-(--color-bg-mute) px-1.5 py-0.5 rounded">{{ method.returns.type }}</code>
<span v-if="method.returns.description" class="ml-2 text-(--color-text-soft)">{{ method.returns.description }}</span>
<span class="text-(--fg-subtle)">Returns</span>
<code class="ml-1.5 text-xs font-mono bg-(--bg-inset) border border-(--border) px-1.5 py-0.5 rounded">{{ method.returns.type }}</code>
<span v-if="method.returns.description" class="ml-2 text-(--fg-muted)">{{ method.returns.description }}</span>
</div>
</div>
</div>
+16 -17
View File
@@ -6,34 +6,33 @@ defineProps<{
</script>
<template>
<div v-if="params.length > 0" class="overflow-x-auto max-w-full">
<table class="w-full text-sm border-collapse table-fixed">
<div v-if="params.length > 0" class="overflow-hidden rounded-xl border border-(--border)">
<table class="w-full text-sm border-collapse">
<thead>
<tr class="border-b border-(--color-border)">
<th class="text-left py-2 pr-4 font-medium text-(--color-text-soft)">Parameter</th>
<th class="text-left py-2 pr-4 font-medium text-(--color-text-soft)">Type</th>
<th class="text-left py-2 pr-4 font-medium text-(--color-text-soft)">Default</th>
<th class="text-left py-2 font-medium text-(--color-text-soft)">Description</th>
<tr class="bg-(--bg-subtle) text-left">
<th class="py-2.5 px-4 font-medium text-(--fg-muted) text-xs uppercase tracking-wider">Parameter</th>
<th class="py-2.5 px-4 font-medium text-(--fg-muted) text-xs uppercase tracking-wider">Type</th>
<th class="py-2.5 px-4 font-medium text-(--fg-muted) text-xs uppercase tracking-wider hidden sm:table-cell">Default</th>
<th class="py-2.5 px-4 font-medium text-(--fg-muted) text-xs uppercase tracking-wider">Description</th>
</tr>
</thead>
<tbody>
<tr
v-for="param in params"
:key="param.name"
class="border-b border-(--color-border) last:border-b-0"
class="border-t border-(--border) align-top"
>
<td class="py-2 pr-4">
<code class="text-brand-600 font-mono text-xs">{{ param.name }}</code>
<span v-if="param.optional" class="text-(--color-text-mute) text-xs ml-1">?</span>
<td class="py-2.5 px-4 whitespace-nowrap">
<code class="text-(--accent-text) font-mono text-[13px] font-medium">{{ param.name }}</code><span v-if="param.optional" class="text-(--fg-subtle) text-xs">?</span>
</td>
<td class="py-2 pr-4 max-w-48 overflow-hidden">
<code class="text-xs font-mono text-(--color-text-soft) bg-(--color-bg-mute) px-1.5 py-0.5 rounded break-all">{{ param.type }}</code>
<td class="py-2.5 px-4">
<code class="text-xs font-mono text-(--fg-muted) bg-(--bg-inset) px-1.5 py-0.5 rounded border border-(--border) wrap-break-word">{{ param.type }}</code>
</td>
<td class="py-2 pr-4">
<code v-if="param.defaultValue" class="text-xs font-mono text-(--color-text-mute)">{{ param.defaultValue }}</code>
<span v-else class="text-(--color-text-mute)"></span>
<td class="py-2.5 px-4 hidden sm:table-cell">
<code v-if="param.defaultValue" class="text-xs font-mono text-(--fg-muted)">{{ param.defaultValue }}</code>
<span v-else class="text-(--fg-subtle)"></span>
</td>
<td class="py-2 text-(--color-text-soft)">
<td class="py-2.5 px-4 text-(--fg-muted) min-w-48">
{{ param.description || '—' }}
</td>
</tr>
+19 -18
View File
@@ -2,39 +2,40 @@
defineProps<{
properties: PropertyMeta[];
/** Column label for the first column */
label?: string;
}>();
</script>
<template>
<div v-if="properties.length > 0" class="overflow-x-auto max-w-full">
<table class="w-full text-sm border-collapse table-fixed">
<div v-if="properties.length > 0" class="overflow-hidden rounded-xl border border-(--border)">
<table class="w-full text-sm border-collapse">
<thead>
<tr class="border-b border-(--color-border)">
<th class="text-left py-2 pr-4 font-medium text-(--color-text-soft)">Property</th>
<th class="text-left py-2 pr-4 font-medium text-(--color-text-soft)">Type</th>
<th class="text-left py-2 pr-4 font-medium text-(--color-text-soft)">Default</th>
<th class="text-left py-2 font-medium text-(--color-text-soft)">Description</th>
<tr class="bg-(--bg-subtle) text-left">
<th class="py-2.5 px-4 font-medium text-(--fg-muted) text-xs uppercase tracking-wider">{{ label ?? 'Property' }}</th>
<th class="py-2.5 px-4 font-medium text-(--fg-muted) text-xs uppercase tracking-wider">Type</th>
<th class="py-2.5 px-4 font-medium text-(--fg-muted) text-xs uppercase tracking-wider hidden sm:table-cell">Default</th>
<th class="py-2.5 px-4 font-medium text-(--fg-muted) text-xs uppercase tracking-wider">Description</th>
</tr>
</thead>
<tbody>
<tr
v-for="prop in properties"
:key="prop.name"
class="border-b border-(--color-border) last:border-b-0"
class="border-t border-(--border) align-top"
>
<td class="py-2 pr-4">
<code class="text-brand-600 font-mono text-xs">{{ prop.name }}</code>
<span v-if="prop.readonly" class="text-(--color-text-mute) text-[10px] ml-1 uppercase">readonly</span>
<span v-if="prop.optional" class="text-(--color-text-mute) text-xs ml-1">?</span>
<td class="py-2.5 px-4 whitespace-nowrap">
<code class="text-(--accent-text) font-mono text-[13px] font-medium">{{ prop.name }}</code><span v-if="prop.optional" class="text-(--fg-subtle) text-xs">?</span>
<span v-if="prop.readonly" class="block text-[10px] text-(--fg-subtle) uppercase tracking-wide mt-0.5">readonly</span>
</td>
<td class="py-2 pr-4 max-w-48 overflow-hidden">
<code class="text-xs font-mono text-(--color-text-soft) bg-(--color-bg-mute) px-1.5 py-0.5 rounded break-all">{{ prop.type }}</code>
<td class="py-2.5 px-4">
<code class="text-xs font-mono text-(--fg-muted) bg-(--bg-inset) px-1.5 py-0.5 rounded border border-(--border) wrap-break-word">{{ prop.type }}</code>
</td>
<td class="py-2 pr-4">
<code v-if="prop.defaultValue" class="text-xs font-mono text-(--color-text-mute)">{{ prop.defaultValue }}</code>
<span v-else class="text-(--color-text-mute)"></span>
<td class="py-2.5 px-4 hidden sm:table-cell">
<code v-if="prop.defaultValue" class="text-xs font-mono text-(--fg-muted)">{{ prop.defaultValue }}</code>
<span v-else class="text-(--fg-subtle)"></span>
</td>
<td class="py-2 text-(--color-text-soft)">
<td class="py-2.5 px-4 text-(--fg-muted) min-w-48">
{{ prop.description || '—' }}
</td>
</tr>
+79 -63
View File
@@ -1,16 +1,18 @@
<script setup lang="ts">const { searchItems } = useDocs();
<script setup lang="ts">const { search } = useDocs();
const isOpen = ref(false);
const query = ref('');
const activeIndex = ref(0);
const results = computed(() => searchItems(query.value).slice(0, 20));
const results = computed(() => search(query.value).slice(0, 24));
watch(results, () => {
activeIndex.value = 0;
});
function open() {
isOpen.value = true;
nextTick(() => {
const input = document.querySelector<HTMLInputElement>('[data-search-input]');
input?.focus();
});
nextTick(() => document.querySelector<HTMLInputElement>('[data-search-input]')?.focus());
}
function close() {
@@ -18,96 +20,110 @@ function close() {
query.value = '';
}
// Keyboard shortcut: Cmd+K / Ctrl+K
if (import.meta.client) {
useEventListener(window, 'keydown', (e: KeyboardEvent) => {
if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
e.preventDefault();
if (isOpen.value) close();
else open();
}
if (e.key === 'Escape' && isOpen.value) {
close();
}
});
const router = useRouter();
function goTo(slug: string) {
const r = results.value[activeIndex.value];
// slug param kept for click handlers that pass an explicit target
const target = slug || (r ? `/${r.pkg.slug}/${r.slug}` : '');
if (target) {
router.push(target);
close();
}
}
function useEventListener(target: Window, event: string, handler: (e: any) => void) {
onMounted(() => target.addEventListener(event, handler));
onUnmounted(() => target.removeEventListener(event, handler));
function onKeydown(e: KeyboardEvent) {
if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
e.preventDefault();
if (isOpen.value) close();
else open();
return;
}
if (!isOpen.value) return;
if (e.key === 'Escape') {
close();
}
else if (e.key === 'ArrowDown') {
e.preventDefault();
activeIndex.value = Math.min(activeIndex.value + 1, results.value.length - 1);
}
else if (e.key === 'ArrowUp') {
e.preventDefault();
activeIndex.value = Math.max(activeIndex.value - 1, 0);
}
else if (e.key === 'Enter') {
e.preventDefault();
goTo('');
}
}
onMounted(() => globalThis.addEventListener('keydown', onKeydown));
onUnmounted(() => globalThis.removeEventListener('keydown', onKeydown));
</script>
<template>
<div>
<button
class="flex items-center gap-2 px-3 py-1.5 text-sm text-(--color-text-mute) bg-(--color-bg-mute) border border-(--color-border) rounded-lg hover:border-(--color-text-mute) transition-colors"
type="button"
class="flex items-center gap-2 px-2.5 h-9 text-sm text-(--fg-subtle) bg-(--bg-subtle) border border-(--border) rounded-lg hover:border-(--border-strong) transition-colors w-9 sm:w-56 justify-center sm:justify-start cursor-pointer"
@click="open"
>
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="11" cy="11" r="8" />
<path d="m21 21-4.3-4.3" />
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="shrink-0">
<circle cx="11" cy="11" r="8" /><path d="m21 21-4.3-4.3" />
</svg>
<span class="hidden sm:inline">Search...</span>
<kbd class="hidden sm:inline-flex items-center gap-0.5 px-1.5 py-0.5 text-[10px] font-mono bg-(--color-bg) border border-(--color-border) rounded">
<span></span>K
</kbd>
<span class="hidden sm:inline flex-1 text-left">Search</span>
<kbd class="hidden sm:inline-flex items-center gap-0.5 px-1.5 py-0.5 text-[10px] font-mono bg-(--bg) border border-(--border) rounded text-(--fg-subtle)">K</kbd>
</button>
<!-- Search modal -->
<Teleport to="body">
<Transition
enter-active-class="duration-200 ease-out"
enter-from-class="opacity-0"
enter-to-class="opacity-100"
leave-active-class="duration-150 ease-in"
leave-from-class="opacity-100"
leave-to-class="opacity-0"
enter-active-class="duration-200 ease-out" enter-from-class="opacity-0" enter-to-class="opacity-100"
leave-active-class="duration-150 ease-in" leave-from-class="opacity-100" leave-to-class="opacity-0"
>
<div v-if="isOpen" class="fixed inset-0 z-50">
<div class="fixed inset-0 bg-black/50" @click="close" />
<div v-if="isOpen" class="fixed inset-0 z-100">
<div class="fixed inset-0 bg-black/40 backdrop-blur-sm" @click="close" />
<div class="fixed inset-x-0 top-[10vh] mx-auto max-w-lg px-4">
<div class="bg-(--color-bg) rounded-xl border border-(--color-border) shadow-2xl overflow-hidden">
<div class="flex items-center px-4 border-b border-(--color-border)">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-(--color-text-mute) shrink-0">
<circle cx="11" cy="11" r="8" />
<path d="m21 21-4.3-4.3" />
<div class="fixed inset-x-0 top-[12vh] mx-auto max-w-xl px-4">
<div class="bg-(--bg-elevated) rounded-2xl border border-(--border) shadow-2xl overflow-hidden">
<div class="flex items-center px-4 border-b border-(--border)">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-(--fg-subtle) shrink-0">
<circle cx="11" cy="11" r="8" /><path d="m21 21-4.3-4.3" />
</svg>
<input
v-model="query"
data-search-input
type="text"
placeholder="Search documentation..."
class="w-full py-3 px-3 bg-transparent text-(--color-text) placeholder:text-(--color-text-mute) focus:outline-none"
placeholder="Search across all packages…"
class="w-full py-3.5 px-3 bg-transparent text-(--fg) placeholder:text-(--fg-subtle) focus:outline-none text-[15px]"
>
<kbd class="hidden sm:inline-flex items-center px-1.5 py-0.5 text-[10px] font-mono bg-(--bg-inset) border border-(--border) rounded text-(--fg-subtle)">ESC</kbd>
</div>
<div class="max-h-80 overflow-y-auto">
<div v-if="query && results.length === 0" class="py-8 text-center text-sm text-(--color-text-mute)">
No results found
<div class="max-h-[60vh] overflow-y-auto p-2">
<div v-if="query && results.length === 0" class="py-12 text-center text-sm text-(--fg-subtle)">
No results for "{{ query }}"
</div>
<ul v-else-if="results.length > 0" class="py-2">
<li v-for="{ pkg, item } in results" :key="`${pkg.slug}-${item.slug}`">
<ul v-else-if="results.length > 0" class="space-y-0.5">
<li v-for="(r, i) in results" :key="`${r.pkg.slug}-${r.slug}`">
<NuxtLink
:to="`/${pkg.slug}/${item.slug}`"
class="flex items-center gap-3 px-4 py-2.5 hover:bg-(--color-bg-mute) transition-colors"
:to="`/${r.pkg.slug}/${r.slug}`"
:class="[
'flex items-center gap-3 px-3 py-2.5 rounded-lg transition-colors',
i === activeIndex ? 'bg-(--accent-subtle)' : 'hover:bg-(--bg-inset)',
]"
@click="close"
@mouseenter="activeIndex = i"
>
<DocsBadge :kind="item.kind" size="sm" />
<div class="min-w-0">
<div class="text-sm font-medium text-(--color-text) truncate">
{{ item.name }}
</div>
<div class="text-xs text-(--color-text-mute) truncate">
{{ pkg.name }} · {{ item.description }}
</div>
<DocsBadge :kind="r.badge" size="sm" />
<div class="min-w-0 flex-1">
<div class="text-sm font-medium text-(--fg) truncate">{{ r.name }}</div>
<div class="text-xs text-(--fg-subtle) truncate">{{ r.pkg.name }} · {{ r.description }}</div>
</div>
</NuxtLink>
</li>
</ul>
<div v-else class="py-8 text-center text-sm text-(--color-text-mute)">
Type to search...
<div v-else class="py-12 text-center text-sm text-(--fg-subtle)">
Type to search functions, components &amp; guides
</div>
</div>
</div>
+7 -6
View File
@@ -1,20 +1,21 @@
<script setup lang="ts">defineProps<{
label: string;
variant?: 'since' | 'test' | 'demo' | 'wip';
variant?: 'since' | 'test' | 'demo' | 'wip' | 'neutral';
}>();
const variantClasses: Record<string, string> = {
since: 'bg-(--color-bg-mute) text-(--color-text-mute)',
test: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400',
demo: 'bg-indigo-100 text-indigo-700 dark:bg-indigo-900/30 dark:text-indigo-400',
wip: 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400',
since: 'bg-(--bg-inset) text-(--fg-muted) border border-(--border)',
neutral: 'bg-(--bg-inset) text-(--fg-muted) border border-(--border)',
test: 'bg-emerald-50 text-emerald-700 border border-emerald-200 dark:bg-emerald-500/10 dark:text-emerald-300 dark:border-emerald-500/20',
demo: 'bg-blue-50 text-blue-700 border border-blue-200 dark:bg-blue-500/10 dark:text-blue-300 dark:border-blue-500/20',
wip: 'bg-amber-50 text-amber-700 border border-amber-200 dark:bg-amber-500/10 dark:text-amber-300 dark:border-amber-500/20',
};
</script>
<template>
<span
:class="[
'inline-flex items-center px-2 py-0.5 text-xs font-medium rounded-full',
'inline-flex items-center px-2 py-0.5 text-[11px] font-medium rounded-full leading-none h-5',
variantClasses[variant ?? 'since'],
]"
>
+41
View File
@@ -0,0 +1,41 @@
<script setup lang="ts">const { preference, cycle } = useTheme();
const label = computed(() => ({
light: 'Light',
dark: 'Dark',
system: 'System',
}[preference.value]));
</script>
<template>
<button
type="button"
:title="`Theme: ${label} (click to change)`"
:aria-label="`Theme: ${label}`"
class="inline-flex items-center justify-center w-9 h-9 rounded-lg text-(--fg-muted) hover:text-(--fg) hover:bg-(--bg-inset) transition-colors cursor-pointer"
@click="cycle"
>
<ClientOnly>
<!-- Light -->
<svg v-if="preference === 'light'" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="12" cy="12" r="4" />
<path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M6.34 17.66l-1.41 1.41M19.07 4.93l-1.41 1.41" />
</svg>
<!-- Dark -->
<svg v-else-if="preference === 'dark'" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z" />
</svg>
<!-- System -->
<svg v-else xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<rect x="2" y="3" width="20" height="14" rx="2" />
<path d="M8 21h8M12 17v4" />
</svg>
<template #fallback>
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<rect x="2" y="3" width="20" height="14" rx="2" />
<path d="M8 21h8M12 17v4" />
</svg>
</template>
</ClientOnly>
</button>
</template>
+70
View File
@@ -0,0 +1,70 @@
<script setup lang="ts">interface TocItem {
id: string;
text: string;
depth: number;
}
const props = defineProps<{
items: TocItem[];
}>();
const activeId = ref<string>('');
let observer: IntersectionObserver | null = null;
function setup() {
if (!import.meta.client || props.items.length === 0) return;
observer?.disconnect();
observer = new IntersectionObserver(
(entries) => {
for (const entry of entries) {
if (entry.isIntersecting) activeId.value = entry.target.id;
}
},
{ rootMargin: '0px 0px -75% 0px', threshold: 0 },
);
for (const item of props.items) {
const el = document.getElementById(item.id);
if (el) observer.observe(el);
}
}
onMounted(() => nextTick(setup));
watch(() => props.items, () => nextTick(setup));
onUnmounted(() => observer?.disconnect());
function go(id: string) {
const el = document.getElementById(id);
if (el) {
activeId.value = id;
el.scrollIntoView({ behavior: 'smooth', block: 'start' });
history.replaceState(null, '', `#${id}`);
}
}
</script>
<template>
<nav v-if="items.length > 0" class="text-sm">
<div class="text-[11px] font-semibold uppercase tracking-wider text-(--fg-subtle) mb-3">
On this page
</div>
<ul class="space-y-1 border-l border-(--border)">
<li v-for="item in items" :key="item.id">
<a
:href="`#${item.id}`"
:class="[
'block py-1 -ml-px border-l-2 transition-colors',
item.depth === 3 ? 'pl-6' : 'pl-4',
activeId === item.id
? 'border-(--accent) text-(--accent-text) font-medium'
: 'border-transparent text-(--fg-muted) hover:text-(--fg)',
]"
@click.prevent="go(item.id)"
>
{{ item.text }}
</a>
</li>
</ul>
</nav>
</template>
+104 -23
View File
@@ -1,5 +1,37 @@
import metadata from '#docs/metadata';
import type { DocsMetadata, PackageMeta, CategoryMeta, ItemMeta } from '../../modules/extractor/types';
import type {
CategoryMeta,
ComponentMeta,
DocsMetadata,
GuideSection,
ItemMeta,
PackageGroup,
PackageMeta,
} from '../../modules/extractor/types';
/** A unified, normalised entry for any documented leaf, regardless of kind. */
export type DocEntry
= | { kind: 'api'; pkg: PackageMeta; category: CategoryMeta; item: ItemMeta }
| { kind: 'components'; pkg: PackageMeta; component: ComponentMeta }
| { kind: 'guide'; pkg: PackageMeta; section: GuideSection };
export interface SearchResult {
pkg: PackageMeta;
slug: string;
name: string;
description: string;
/** Display kind for the badge */
badge: string;
}
const GROUP_LABELS: Record<PackageGroup, string> = {
core: 'Core',
vue: 'Vue',
configs: 'Configs',
infra: 'Infra',
};
const GROUP_ORDER: PackageGroup[] = ['core', 'vue', 'configs', 'infra'];
export function useDocs() {
const data = metadata as unknown as DocsMetadata;
@@ -8,35 +40,85 @@ export function useDocs() {
return data.packages;
}
/** Packages grouped & ordered for sidebar / landing. */
function getGroupedPackages(): Array<{ group: PackageGroup; label: string; packages: PackageMeta[] }> {
return GROUP_ORDER
.map(group => ({
group,
label: GROUP_LABELS[group],
packages: data.packages.filter(p => p.group === group),
}))
.filter(g => g.packages.length > 0);
}
function getPackage(slug: string): PackageMeta | undefined {
return data.packages.find(p => p.slug === slug);
}
function getItem(packageSlug: string, itemSlug: string): { pkg: PackageMeta; category: CategoryMeta; item: ItemMeta } | undefined {
/** Number of documented leaves in a package, whatever its kind. */
function countEntries(pkg: PackageMeta): number {
if (pkg.kind === 'api') return pkg.categories.reduce((s, c) => s + c.items.length, 0);
if (pkg.kind === 'components') return pkg.components.length;
return pkg.sections.length;
}
/** Resolve any `/:package/:slug` route to a normalised entry. */
function resolveEntry(packageSlug: string, slug: string): DocEntry | undefined {
const pkg = getPackage(packageSlug);
if (!pkg) return undefined;
for (const category of pkg.categories) {
const item = category.items.find(i => i.slug === itemSlug);
if (item) return { pkg, category, item };
if (pkg.kind === 'api') {
for (const category of pkg.categories) {
const item = category.items.find(i => i.slug === slug);
if (item) return { kind: 'api', pkg, category, item };
}
}
else if (pkg.kind === 'components') {
const component = pkg.components.find(c => c.slug === slug);
if (component) return { kind: 'components', pkg, component };
}
else {
const section = pkg.sections.find(s => s.slug === slug);
if (section) return { kind: 'guide', pkg, section };
}
return undefined;
}
function searchItems(query: string): Array<{ pkg: PackageMeta; item: ItemMeta }> {
if (!query.trim()) return [];
const q = query.toLowerCase();
const results: Array<{ pkg: PackageMeta; item: ItemMeta }> = [];
/** The default entry to open when landing on a package, if any. */
function firstEntrySlug(pkg: PackageMeta): string | undefined {
if (pkg.kind === 'api') return pkg.categories[0]?.items[0]?.slug;
if (pkg.kind === 'components') return pkg.components[0]?.slug;
return pkg.sections[0]?.slug;
}
function search(query: string): SearchResult[] {
const q = query.trim().toLowerCase();
if (!q) return [];
const results: SearchResult[] = [];
for (const pkg of data.packages) {
for (const category of pkg.categories) {
for (const item of category.items) {
if (
item.name.toLowerCase().includes(q)
|| item.description.toLowerCase().includes(q)
) {
results.push({ pkg, item });
if (pkg.kind === 'api') {
for (const category of pkg.categories) {
for (const item of category.items) {
if (item.name.toLowerCase().includes(q) || item.description.toLowerCase().includes(q)) {
results.push({ pkg, slug: item.slug, name: item.name, description: item.description, badge: item.kind });
}
}
}
}
else if (pkg.kind === 'components') {
for (const c of pkg.components) {
if (c.name.toLowerCase().includes(q) || c.description.toLowerCase().includes(q)) {
results.push({ pkg, slug: c.slug, name: c.name, description: c.description || `${c.parts.length} parts`, badge: 'component' });
}
}
}
else {
for (const s of pkg.sections) {
if (s.title.toLowerCase().includes(q) || s.markdown.toLowerCase().includes(q)) {
results.push({ pkg, slug: s.slug, name: s.title, description: pkg.name, badge: 'guide' });
}
}
}
@@ -46,19 +128,18 @@ export function useDocs() {
}
function getTotalItems(): number {
return data.packages.reduce(
(sum, pkg) => sum + pkg.categories.reduce(
(catSum, cat) => catSum + cat.items.length, 0,
), 0,
);
return data.packages.reduce((sum, pkg) => sum + countEntries(pkg), 0);
}
return {
data,
getPackages,
getGroupedPackages,
getPackage,
getItem,
searchItems,
countEntries,
resolveEntry,
firstEntrySlug,
search,
getTotalItems,
};
}
+63
View File
@@ -0,0 +1,63 @@
import { marked } from 'marked';
export interface Heading {
depth: number;
text: string;
id: string;
}
export function slugHeading(text: string): string {
return text
.toLowerCase()
.replace(/`/g, '')
.replace(/[^\w\s-]/g, '')
.trim()
.replace(/\s+/g, '-');
}
/** Collect h2/h3 headings for the table of contents. */
export function extractHeadings(markdown: string): Heading[] {
const headings: Heading[] = [];
const seen = new Map<string, number>();
let inFence = false;
for (const line of markdown.split('\n')) {
if (/^\s*```/.test(line)) {
inFence = !inFence;
continue;
}
if (inFence) continue;
const m = line.match(/^(#{2,3})\s+(.+?)\s*#*$/);
if (!m) continue;
const depth = m[1]!.length;
const text = m[2]!.replace(/`/g, '').trim();
let id = slugHeading(text);
const count = seen.get(id) ?? 0;
seen.set(id, count + 1);
if (count > 0) id = `${id}-${count}`;
headings.push({ depth, text, id });
}
return headings;
}
/** Render markdown to HTML with stable heading ids (matching extractHeadings). */
export function renderMarkdown(markdown: string): string {
const seen = new Map<string, number>();
const renderer = new marked.Renderer();
renderer.heading = function ({ tokens, depth }) {
const inner = this.parser.parseInline(tokens);
const plain = inner.replace(/<[^>]+>/g, '');
let id = slugHeading(plain);
const count = seen.get(id) ?? 0;
seen.set(id, count + 1);
if (count > 0) id = `${id}-${count}`;
return `<h${depth} id="${id}">${inner}</h${depth}>\n`;
};
return marked.parse(markdown, { renderer, async: false }) as string;
}
+3 -3
View File
@@ -7,7 +7,7 @@ function getHighlighter(): Promise<Highlighter> {
if (!highlighterPromise) {
highlighterPromise = createHighlighter({
themes: ['github-light', 'github-dark'],
langs: ['typescript', 'vue', 'json', 'bash'],
langs: ['typescript', 'javascript', 'vue', 'json', 'bash'],
});
}
return highlighterPromise;
@@ -17,7 +17,7 @@ export function useShiki() {
const highlighted = ref<string>('');
const isReady = ref(false);
async function highlight(code: string, lang: string = 'typescript'): Promise<string> {
async function highlight(code: string, lang = 'typescript'): Promise<string> {
const highlighter = await getHighlighter();
return highlighter.codeToHtml(code, {
lang,
@@ -28,7 +28,7 @@ export function useShiki() {
});
}
async function highlightReactive(code: string, lang: string = 'typescript'): Promise<void> {
async function highlightReactive(code: string, lang = 'typescript'): Promise<void> {
highlighted.value = await highlight(code, lang);
isReady.value = true;
}
+62
View File
@@ -0,0 +1,62 @@
export type ThemePreference = 'light' | 'dark' | 'system';
const STORAGE_KEY = 'docs-theme';
/**
* Theme controller. The actual `.dark` class is set as early as possible by the
* inline head script (see nuxt.config) to avoid a flash; this composable keeps a
* reactive preference, persists it, and re-applies the resolved theme on change.
*/
export function useTheme() {
const preference = useState<ThemePreference>('theme-preference', () => 'system');
function resolve(pref: ThemePreference): 'light' | 'dark' {
if (pref === 'system') {
return import.meta.client && globalThis.matchMedia('(prefers-color-scheme: dark)').matches
? 'dark'
: 'light';
}
return pref;
}
function apply(pref: ThemePreference) {
if (!import.meta.client) return;
const resolved = resolve(pref);
document.documentElement.classList.toggle('dark', resolved === 'dark');
}
function setTheme(pref: ThemePreference) {
preference.value = pref;
if (import.meta.client) {
if (pref === 'system') localStorage.removeItem(STORAGE_KEY);
else localStorage.setItem(STORAGE_KEY, pref);
apply(pref);
}
}
function cycle() {
const order: ThemePreference[] = ['light', 'dark', 'system'];
const next = order[(order.indexOf(preference.value) + 1) % order.length]!;
setTheme(next);
}
// Initialise reactive preference from storage on the client.
if (import.meta.client) {
onMounted(() => {
const stored = localStorage.getItem(STORAGE_KEY) as ThemePreference | null;
preference.value = stored ?? 'system';
// Track OS changes while in `system` mode.
const mq = globalThis.matchMedia('(prefers-color-scheme: dark)');
const onChange = () => {
if (preference.value === 'system') apply('system');
};
mq.addEventListener('change', onChange);
onUnmounted(() => mq.removeEventListener('change', onChange));
});
}
const resolved = computed(() => resolve(preference.value));
return { preference, resolved, setTheme, cycle };
}
+128 -67
View File
@@ -1,5 +1,5 @@
<script setup lang="ts">const { getPackages } = useDocs();
const packages = getPackages();
<script setup lang="ts">const { getGroupedPackages, getPackage } = useDocs();
const groups = getGroupedPackages();
const route = useRoute();
const isSidebarOpen = ref(false);
@@ -9,94 +9,155 @@ const currentPackageSlug = computed(() => {
return typeof param === 'string' ? param : undefined;
});
const currentPackage = computed(() =>
currentPackageSlug.value ? getPackage(currentPackageSlug.value) : undefined,
);
function isActive(pkgSlug: string, slug: string) {
return route.path === `/${pkgSlug}/${slug}`;
}
watch(() => route.path, () => {
isSidebarOpen.value = false;
});
</script>
<template>
<div class="min-h-screen flex flex-col">
<div class="min-h-screen">
<!-- Header -->
<header class="sticky top-0 z-50 border-b border-(--color-border) backdrop-blur-sm" style="background-color: var(--color-header-bg)">
<div class="mx-auto max-w-7xl flex items-center justify-between px-4 h-14 sm:px-6">
<div class="flex items-center gap-4">
<button
class="lg:hidden p-1.5 -ml-1.5 text-(--color-text-soft) hover:text-(--color-text)"
@click="isSidebarOpen = !isSidebarOpen"
>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="3" y1="6" x2="21" y2="6" />
<line x1="3" y1="12" x2="21" y2="12" />
<line x1="3" y1="18" x2="21" y2="18" />
</svg>
</button>
<NuxtLink to="/" class="flex items-center gap-2 font-semibold text-(--color-text)">
<span class="text-brand-600">@robonen</span><span class="text-(--color-text-mute)">/</span><span>tools</span>
</NuxtLink>
</div>
<div class="flex items-center gap-3">
<DocsSearch />
<a
href="https://github.com/robonen/tools"
target="_blank"
rel="noopener noreferrer"
class="p-1.5 text-(--color-text-soft) hover:text-(--color-text) transition-colors"
>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
<path d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z" />
</svg>
</a>
</div>
<header class="sticky top-0 z-50 border-b border-(--border) backdrop-blur-md" style="background-color: var(--header-bg)">
<div class="mx-auto max-w-352 flex items-center gap-3 px-4 h-14 sm:px-6">
<button
type="button"
class="lg:hidden inline-flex items-center justify-center w-9 h-9 -ml-1.5 rounded-lg text-(--fg-muted) hover:text-(--fg) hover:bg-(--bg-inset)"
aria-label="Toggle navigation"
@click="isSidebarOpen = !isSidebarOpen"
>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="3" y1="6" x2="21" y2="6" /><line x1="3" y1="12" x2="21" y2="12" /><line x1="3" y1="18" x2="21" y2="18" />
</svg>
</button>
<NuxtLink to="/" class="flex items-center gap-2 font-semibold text-[15px] mr-auto">
<span class="inline-flex items-center justify-center w-7 h-7 rounded-lg bg-(--fg) text-(--bg) text-xs font-bold">R</span>
<span class="hidden sm:flex items-center">
<span class="text-(--accent-text)">@robonen</span><span class="text-(--fg-subtle)">/</span><span class="text-(--fg)">tools</span>
</span>
</NuxtLink>
<DocsSearch />
<DocsThemeToggle />
<a
href="https://github.com/robonen/tools"
target="_blank"
rel="noopener noreferrer"
class="inline-flex items-center justify-center w-9 h-9 rounded-lg text-(--fg-muted) hover:text-(--fg) hover:bg-(--bg-inset) transition-colors"
aria-label="GitHub"
>
<svg xmlns="http://www.w3.org/2000/svg" width="19" height="19" viewBox="0 0 24 24" fill="currentColor">
<path d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z" />
</svg>
</a>
</div>
</header>
<div class="mx-auto max-w-7xl w-full flex flex-1 px-4 sm:px-6">
<div class="mx-auto max-w-352 w-full flex px-4 sm:px-6">
<!-- Sidebar -->
<aside
:class="[
'fixed inset-y-0 left-0 z-40 w-64 bg-(--color-bg) border-r border-(--color-border) pt-14 transform transition-transform lg:sticky lg:top-14 lg:z-auto lg:h-[calc(100vh-3.5rem)] lg:w-56 lg:shrink-0 lg:translate-x-0 lg:pt-0 lg:border-r-0 lg:bg-transparent lg:transform-none',
'fixed inset-y-0 left-0 z-40 w-72 bg-(--bg) border-r border-(--border) pt-14 transform transition-transform lg:sticky lg:top-14 lg:z-auto lg:h-[calc(100vh-3.5rem)] lg:w-64 lg:shrink-0 lg:translate-x-0 lg:pt-0 lg:border-r-0 lg:bg-transparent',
isSidebarOpen ? 'translate-x-0' : '-translate-x-full',
]"
>
<nav class="h-full overflow-y-auto py-6 px-4 lg:pr-6 lg:pl-0 overscroll-contain">
<div v-for="pkg in packages" :key="pkg.slug" class="mb-6">
<NuxtLink
:to="`/${pkg.slug}`"
class="block text-xs font-semibold uppercase tracking-wider mb-2"
:class="currentPackageSlug === pkg.slug ? 'text-brand-600' : 'text-(--color-text-mute) hover:text-(--color-text-soft)'"
>
{{ pkg.name }}
</NuxtLink>
<div v-for="category in pkg.categories" :key="category.slug" class="mb-3">
<div class="text-xs font-medium text-(--color-text-mute) mb-1 pl-2">
{{ category.name }}
</div>
<ul class="space-y-0.5">
<li v-for="item in category.items" :key="item.slug">
<NuxtLink
:to="`/${pkg.slug}/${item.slug}`"
class="block py-1 px-2 text-sm rounded-md transition-colors"
active-class="bg-brand-50 text-brand-700 dark:bg-brand-950 dark:text-brand-300 font-medium"
:class="route.path !== `/${pkg.slug}/${item.slug}` ? 'text-(--color-text-soft) hover:text-(--color-text) hover:bg-(--color-bg-mute)' : ''"
>
{{ item.name }}
</NuxtLink>
</li>
</ul>
<nav class="h-full overflow-y-auto py-8 px-4 lg:pr-6 lg:pl-0 overscroll-contain">
<div v-for="grp in groups" :key="grp.group" class="mb-7">
<div class="text-[11px] font-semibold uppercase tracking-wider text-(--fg-subtle) mb-2 px-2">
{{ grp.label }}
</div>
<ul class="space-y-0.5">
<li v-for="pkg in grp.packages" :key="pkg.slug">
<NuxtLink
:to="`/${pkg.slug}`"
:class="[
'flex items-center justify-between py-1.5 px-2 rounded-lg text-sm transition-colors',
currentPackageSlug === pkg.slug
? 'text-(--fg) font-medium bg-(--bg-inset)'
: 'text-(--fg-muted) hover:text-(--fg) hover:bg-(--bg-inset)',
]"
>
<span>{{ pkg.name.replace('@robonen/', '') }}</span>
<span class="text-[10px] uppercase tracking-wide text-(--fg-subtle)">{{ pkg.kind === 'api' ? 'api' : pkg.kind === 'components' ? 'ui' : 'guide' }}</span>
</NuxtLink>
<!-- Expanded tree for the current package -->
<div v-if="currentPackageSlug === pkg.slug && currentPackage" class="mt-1 mb-2 ml-2 pl-3 border-l border-(--border)">
<!-- api -->
<template v-if="currentPackage.kind === 'api'">
<div v-for="cat in currentPackage.categories" :key="cat.slug" class="mb-2">
<div class="text-[11px] font-medium text-(--fg-subtle) py-1 px-1">{{ cat.name }}</div>
<ul>
<li v-for="item in cat.items" :key="item.slug">
<NuxtLink
:to="`/${pkg.slug}/${item.slug}`"
:class="[
'block py-1 px-2 text-[13px] rounded-md font-mono transition-colors truncate',
isActive(pkg.slug, item.slug)
? 'text-(--accent-text) bg-(--accent-subtle) font-medium'
: 'text-(--fg-muted) hover:text-(--fg) hover:bg-(--bg-inset)',
]"
>
{{ item.name }}
</NuxtLink>
</li>
</ul>
</div>
</template>
<!-- components -->
<ul v-else-if="currentPackage.kind === 'components'">
<li v-for="c in currentPackage.components" :key="c.slug">
<NuxtLink
:to="`/${pkg.slug}/${c.slug}`"
:class="[
'block py-1 px-2 text-[13px] rounded-md transition-colors truncate',
isActive(pkg.slug, c.slug)
? 'text-(--accent-text) bg-(--accent-subtle) font-medium'
: 'text-(--fg-muted) hover:text-(--fg) hover:bg-(--bg-inset)',
]"
>
{{ c.name }}
</NuxtLink>
</li>
</ul>
<!-- guide -->
<ul v-else>
<li v-for="s in currentPackage.sections" :key="s.slug">
<NuxtLink
:to="`/${pkg.slug}/${s.slug}`"
:class="[
'block py-1 px-2 text-[13px] rounded-md transition-colors truncate',
isActive(pkg.slug, s.slug)
? 'text-(--accent-text) bg-(--accent-subtle) font-medium'
: 'text-(--fg-muted) hover:text-(--fg) hover:bg-(--bg-inset)',
]"
>
{{ s.title }}
</NuxtLink>
</li>
</ul>
</div>
</li>
</ul>
</div>
</nav>
</aside>
<!-- Sidebar overlay -->
<div
v-if="isSidebarOpen"
class="fixed inset-0 z-30 bg-black/20 lg:hidden"
@click="isSidebarOpen = false"
/>
<!-- Mobile overlay -->
<div v-if="isSidebarOpen" class="fixed inset-0 z-30 bg-black/30 lg:hidden" @click="isSidebarOpen = false" />
<!-- Main content -->
<main class="flex-1 min-w-0 overflow-hidden py-8 lg:pl-8">
<main class="flex-1 min-w-0 py-10 lg:pl-10">
<slot />
</main>
</div>
+184 -177
View File
@@ -1,203 +1,210 @@
<script setup lang="ts">import { demos } from '#docs/demos';
const route = useRoute();
const { getItem } = useDocs();
const { resolveEntry } = useDocs();
const packageSlug = computed(() => route.params.package as string);
const utilitySlug = computed(() => route.params.utility as string);
const result = computed(() => getItem(packageSlug.value, utilitySlug.value));
const entry = computed(() => resolveEntry(packageSlug.value, utilitySlug.value));
if (!result.value) {
if (!entry.value) {
throw createError({
statusCode: 404,
message: `Item "${utilitySlug.value}" not found in package "${packageSlug.value}"`,
message: `"${utilitySlug.value}" not found in package "${packageSlug.value}"`,
});
}
const { pkg, category, item } = result.value;
const pkg = computed(() => entry.value!.pkg);
useHead({
title: `${item.name}${pkg.name} — @robonen/tools`,
meta: [
{ name: 'description', content: item.description },
],
const demoComponent = computed(() => demos[`${packageSlug.value}/${utilitySlug.value}`] ?? null);
function ghUrl(path: string) {
return `https://github.com/robonen/tools/blob/master/${path}`;
}
// ── Page title & TOC ─────────────────────────────────────────────────────────
const title = computed(() => {
const e = entry.value!;
if (e.kind === 'api') return e.item.name;
if (e.kind === 'components') return e.component.name;
return e.section.title;
});
const sourceUrl = computed(() => `https://github.com/robonen/tools/blob/main/${item.sourcePath}`);
useHead(() => ({
title: `${title.value}${pkg.value.name}`,
meta: [{
name: 'description',
content: entry.value?.kind === 'api' ? entry.value.item.description : pkg.value.description,
}],
}));
const demoComponent = computed(() => {
const key = `${pkg.slug}/${item.slug}`;
return demos[key] ?? null;
const toc = computed(() => {
const e = entry.value;
if (!e) return [];
if (e.kind === 'guide') {
return extractHeadings(e.section.markdown).map(h => ({ id: h.id, text: h.text, depth: h.depth }));
}
if (e.kind === 'components') {
return e.component.parts.map(p => ({ id: p.name.toLowerCase(), text: p.name, depth: 2 }));
}
// api: derive from present sections
const i = e.item;
const items: Array<{ id: string; text: string; depth: number }> = [];
if (i.examples.length) items.push({ id: 'example', text: 'Example', depth: 2 });
if (i.hasDemo && demoComponent.value) items.push({ id: 'demo', text: 'Demo', depth: 2 });
if (i.signatures.length) items.push({ id: 'signature', text: 'Signature', depth: 2 });
if (i.typeParams.length) items.push({ id: 'type-parameters', text: 'Type Parameters', depth: 2 });
if (i.params.length) items.push({ id: 'parameters', text: 'Parameters', depth: 2 });
if (i.returns) items.push({ id: 'returns', text: 'Returns', depth: 2 });
if (i.properties.length) items.push({ id: 'properties', text: 'Properties', depth: 2 });
if (i.methods.length) items.push({ id: 'methods', text: 'Methods', depth: 2 });
if (i.relatedTypes?.length) items.push({ id: 'related-types', text: 'Related Types', depth: 2 });
return items;
});
const sectionTitle = 'text-xs font-semibold uppercase tracking-wider text-(--fg-subtle) mb-3';
</script>
<template>
<div v-if="item" class="max-w-3xl min-w-0">
<!-- Breadcrumb -->
<nav class="flex items-center gap-1.5 text-sm text-(--color-text-mute) mb-6">
<NuxtLink :to="`/${pkg.slug}`" class="hover:text-(--color-text-soft) transition-colors">
{{ pkg.name }}
</NuxtLink>
<span>/</span>
<span>{{ category.name }}</span>
<span>/</span>
<span class="text-(--color-text)">{{ item.name }}</span>
</nav>
<div v-if="entry" class="xl:grid xl:grid-cols-[minmax(0,1fr)_14rem] xl:gap-12">
<article class="min-w-0 max-w-3xl">
<!-- Breadcrumb -->
<nav class="flex items-center gap-1.5 text-sm text-(--fg-subtle) mb-6">
<NuxtLink :to="`/${pkg.slug}`" class="hover:text-(--fg) transition-colors">{{ pkg.name }}</NuxtLink>
<span>/</span>
<span class="text-(--fg)">{{ title }}</span>
</nav>
<!-- Header -->
<div class="mb-8">
<div class="flex items-center gap-3 mb-2 flex-wrap">
<DocsBadge :kind="item.kind" size="md" />
<h1 class="text-2xl font-bold font-mono tracking-tight text-(--color-text)">
{{ item.name }}
</h1>
<DocsTag v-if="item.since" :label="`v${item.since}`" variant="since" />
<DocsTag v-if="item.hasTests" label="tested" variant="test" />
<DocsTag v-if="item.hasDemo" label="demo" variant="demo" />
</div>
<p class="text-(--color-text-soft) leading-relaxed">
{{ item.description }}
</p>
<!-- Links (source, tests) -->
<div class="flex items-center gap-4 mt-3 text-sm">
<a
:href="sourceUrl"
target="_blank"
rel="noopener noreferrer"
class="flex items-center gap-1.5 text-(--color-text-mute) hover:text-(--color-text) transition-colors"
>
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M15 22v-4a4.8 4.8 0 0 0-1-3.5c3 0 6-2 6-5.5.08-1.25-.27-2.48-1-3.5.28-1.15.28-2.35 0-3.5 0 0-1 0-3 1.5-2.64-.5-5.36-.5-8 0C6 2 5 2 5 2c-.3 1.15-.3 2.35 0 3.5A5.403 5.403 0 0 0 4 9c0 3.5 3 5.5 6 5.5-.39.49-.68 1.05-.85 1.65-.17.6-.22 1.23-.15 1.85v4" />
<path d="M9 18c-4.51 2-5-2-7-2" />
</svg>
Source
</a>
<a
v-if="item.hasTests"
:href="`${sourceUrl.replace('index.ts', 'index.test.ts')}`"
target="_blank"
rel="noopener noreferrer"
class="flex items-center gap-1.5 text-(--color-text-mute) hover:text-(--color-text) transition-colors"
>
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z" />
<polyline points="14 2 14 8 20 8" />
<path d="m9 15 2 2 4-4" />
</svg>
Tests
</a>
</div>
</div>
<!-- Examples (moved to top for quick reference) -->
<section v-if="item.examples.length > 0" class="mb-8">
<h2 class="text-sm font-semibold uppercase tracking-wider text-(--color-text-mute) mb-3">
{{ item.examples.length > 1 ? 'Examples' : 'Example' }}
</h2>
<div class="space-y-3">
<DocsCode v-for="(example, i) in item.examples" :key="i" :code="example" />
</div>
</section>
<!-- Demo -->
<section v-if="item.hasDemo && demoComponent" class="mb-8">
<h2 class="text-sm font-semibold uppercase tracking-wider text-(--color-text-mute) mb-3">
Demo
</h2>
<DocsDemo :component="demoComponent" :source="item.demoSource" />
</section>
<!-- Signatures -->
<section v-if="item.signatures.length > 0" class="mb-8">
<h2 class="text-sm font-semibold uppercase tracking-wider text-(--color-text-mute) mb-3">
{{ item.signatures.length > 1 ? 'Signatures' : 'Signature' }}
</h2>
<div class="space-y-2">
<DocsCode v-for="(sig, i) in item.signatures" :key="i" :code="sig" />
</div>
</section>
<!-- Type Parameters -->
<section v-if="item.typeParams.length > 0" class="mb-8">
<h2 class="text-sm font-semibold uppercase tracking-wider text-(--color-text-mute) mb-3">
Type Parameters
</h2>
<div class="space-y-2">
<div
v-for="tp in item.typeParams"
:key="tp.name"
class="flex items-baseline gap-2 text-sm"
>
<code class="font-mono font-medium text-brand-600">{{ tp.name }}</code>
<span v-if="tp.constraint" class="text-(--color-text-mute)">
extends <code class="font-mono text-xs">{{ tp.constraint }}</code>
</span>
<span v-if="tp.default" class="text-(--color-text-mute)">
= <code class="font-mono text-xs">{{ tp.default }}</code>
</span>
</div>
</div>
</section>
<!-- Parameters -->
<section v-if="item.params.length > 0" class="mb-8">
<h2 class="text-sm font-semibold uppercase tracking-wider text-(--color-text-mute) mb-3">
Parameters
</h2>
<DocsParamsTable :params="item.params" />
</section>
<!-- Return value -->
<section v-if="item.returns" class="mb-8">
<h2 class="text-sm font-semibold uppercase tracking-wider text-(--color-text-mute) mb-3">
Returns
</h2>
<div class="flex items-baseline gap-2 text-sm">
<code class="font-mono bg-(--color-bg-mute) px-2 py-1 rounded text-xs break-all">{{ item.returns.type }}</code>
<span v-if="item.returns.description" class="text-(--color-text-soft)">{{ item.returns.description }}</span>
</div>
</section>
<!-- Properties (interfaces, classes) -->
<section v-if="item.properties.length > 0" class="mb-8">
<h2 class="text-sm font-semibold uppercase tracking-wider text-(--color-text-mute) mb-3">
Properties
</h2>
<DocsPropsTable :properties="item.properties" />
</section>
<!-- Methods (classes) -->
<section v-if="item.methods.length > 0" class="mb-8">
<h2 class="text-sm font-semibold uppercase tracking-wider text-(--color-text-mute) mb-3">
Methods
</h2>
<DocsMethodsList :methods="item.methods" />
</section>
<!-- Related Types -->
<section v-if="item.relatedTypes?.length" class="mb-8">
<h2 class="text-sm font-semibold uppercase tracking-wider text-(--color-text-mute) mb-3">
Related Types
</h2>
<div class="space-y-4">
<div
v-for="rt in item.relatedTypes"
:key="rt.name"
class="border border-(--color-border) rounded-lg p-4 bg-(--color-bg-soft)"
>
<div class="flex items-center gap-2 mb-2">
<DocsBadge :kind="rt.kind" size="sm" />
<h3 class="font-mono font-semibold text-sm">{{ rt.name }}</h3>
<!-- API ITEM -->
<template v-if="entry.kind === 'api'">
<header class="mb-8">
<div class="flex items-center gap-2.5 mb-2 flex-wrap">
<DocsBadge :kind="entry.item.kind" size="md" />
<h1 class="text-2xl font-bold font-mono tracking-tight text-(--fg)">{{ entry.item.name }}</h1>
<DocsTag v-if="entry.item.since" :label="`v${entry.item.since}`" variant="neutral" />
<DocsTag v-if="entry.item.hasTests" label="tested" variant="test" />
<DocsTag v-if="entry.item.hasDemo" label="demo" variant="demo" />
</div>
<p v-if="rt.description" class="text-sm text-(--color-text-soft) mb-3">
{{ rt.description }}
</p>
<DocsCode v-if="rt.signatures.length > 0" :code="rt.signatures[0]!" />
<DocsPropsTable v-if="rt.properties.length > 0" :properties="rt.properties" class="mt-3" />
</div>
<p v-if="entry.item.description" class="text-(--fg-muted) text-[15px] leading-relaxed">{{ entry.item.description }}</p>
<div class="flex items-center gap-4 mt-4 text-sm">
<a :href="ghUrl(entry.item.sourcePath)" target="_blank" rel="noopener noreferrer" class="flex items-center gap-1.5 text-(--fg-subtle) hover:text-(--fg) transition-colors">
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M15 22v-4a4.8 4.8 0 0 0-1-3.5c3 0 6-2 6-5.5.08-1.25-.27-2.48-1-3.5.28-1.15.28-2.35 0-3.5 0 0-1 0-3 1.5-2.64-.5-5.36-.5-8 0C6 2 5 2 5 2c-.3 1.15-.3 2.35 0 3.5A5.403 5.403 0 0 0 4 9c0 3.5 3 5.5 6 5.5-.39.49-.68 1.05-.85 1.65-.17.6-.22 1.23-.15 1.85v4" /><path d="M9 18c-4.51 2-5-2-7-2" /></svg>
Source
</a>
<a v-if="entry.item.hasTests" :href="ghUrl(entry.item.sourcePath).replace('index.ts', 'index.test.ts')" target="_blank" rel="noopener noreferrer" class="flex items-center gap-1.5 text-(--fg-subtle) hover:text-(--fg) transition-colors">
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z" /><polyline points="14 2 14 8 20 8" /><path d="m9 15 2 2 4-4" /></svg>
Tests
</a>
</div>
</header>
<section v-if="entry.item.examples.length" id="example" class="mb-8 scroll-mt-20">
<h2 :class="sectionTitle">{{ entry.item.examples.length > 1 ? 'Examples' : 'Example' }}</h2>
<div class="space-y-3">
<DocsCode v-for="(ex, i) in entry.item.examples" :key="i" :code="ex" />
</div>
</section>
<section v-if="entry.item.hasDemo && demoComponent" id="demo" class="mb-8 scroll-mt-20">
<h2 :class="sectionTitle">Demo</h2>
<DocsDemo :component="demoComponent" :source="entry.item.demoSource" />
</section>
<section v-if="entry.item.signatures.length" id="signature" class="mb-8 scroll-mt-20">
<h2 :class="sectionTitle">{{ entry.item.signatures.length > 1 ? 'Signatures' : 'Signature' }}</h2>
<div class="space-y-2">
<DocsCode v-for="(sig, i) in entry.item.signatures" :key="i" :code="sig" />
</div>
</section>
<section v-if="entry.item.typeParams.length" id="type-parameters" class="mb-8 scroll-mt-20">
<h2 :class="sectionTitle">Type Parameters</h2>
<div class="space-y-1.5">
<div v-for="tp in entry.item.typeParams" :key="tp.name" class="flex items-baseline gap-2 text-sm flex-wrap">
<code class="font-mono font-medium text-(--accent-text)">{{ tp.name }}</code>
<span v-if="tp.constraint" class="text-(--fg-subtle)">extends <code class="font-mono text-xs">{{ tp.constraint }}</code></span>
<span v-if="tp.default" class="text-(--fg-subtle)">= <code class="font-mono text-xs">{{ tp.default }}</code></span>
</div>
</div>
</section>
<section v-if="entry.item.params.length" id="parameters" class="mb-8 scroll-mt-20">
<h2 :class="sectionTitle">Parameters</h2>
<DocsParamsTable :params="entry.item.params" />
</section>
<section v-if="entry.item.returns" id="returns" class="mb-8 scroll-mt-20">
<h2 :class="sectionTitle">Returns</h2>
<div class="flex items-baseline gap-2 text-sm flex-wrap">
<code class="font-mono bg-(--bg-inset) border border-(--border) px-2 py-1 rounded text-xs wrap-break-word">{{ entry.item.returns.type }}</code>
<span v-if="entry.item.returns.description" class="text-(--fg-muted)">{{ entry.item.returns.description }}</span>
</div>
</section>
<section v-if="entry.item.properties.length" id="properties" class="mb-8 scroll-mt-20">
<h2 :class="sectionTitle">Properties</h2>
<DocsPropsTable :properties="entry.item.properties" />
</section>
<section v-if="entry.item.methods.length" id="methods" class="mb-8 scroll-mt-20">
<h2 :class="sectionTitle">Methods</h2>
<DocsMethodsList :methods="entry.item.methods" />
</section>
<section v-if="entry.item.relatedTypes?.length" id="related-types" class="mb-8 scroll-mt-20">
<h2 :class="sectionTitle">Related Types</h2>
<div class="space-y-4">
<div v-for="rt in entry.item.relatedTypes" :key="rt.name" class="rounded-xl border border-(--border) bg-(--bg-subtle) p-4">
<div class="flex items-center gap-2 mb-2">
<DocsBadge :kind="rt.kind" size="sm" />
<h3 class="font-mono font-semibold text-sm text-(--fg)">{{ rt.name }}</h3>
</div>
<p v-if="rt.description" class="text-sm text-(--fg-muted) mb-3">{{ rt.description }}</p>
<DocsCode v-if="rt.signatures.length" :code="rt.signatures[0]!" />
<DocsPropsTable v-if="rt.properties.length" :properties="rt.properties" class="mt-3" />
</div>
</div>
</section>
</template>
<!-- COMPONENT -->
<template v-else-if="entry.kind === 'components'">
<header class="mb-8">
<div class="flex items-center gap-2.5 mb-2 flex-wrap">
<DocsBadge kind="component" size="md" />
<h1 class="text-2xl font-bold tracking-tight text-(--fg)">{{ entry.component.name }}</h1>
<DocsTag :label="`${entry.component.parts.length} parts`" variant="neutral" />
</div>
<p v-if="entry.component.description" class="text-(--fg-muted) text-[15px] leading-relaxed">{{ entry.component.description }}</p>
<div class="flex items-center gap-4 mt-4 text-sm">
<a :href="ghUrl(entry.component.sourcePath)" target="_blank" rel="noopener noreferrer" class="flex items-center gap-1.5 text-(--fg-subtle) hover:text-(--fg) transition-colors">
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M15 22v-4a4.8 4.8 0 0 0-1-3.5c3 0 6-2 6-5.5.08-1.25-.27-2.48-1-3.5.28-1.15.28-2.35 0-3.5 0 0-1 0-3 1.5-2.64-.5-5.36-.5-8 0C6 2 5 2 5 2c-.3 1.15-.3 2.35 0 3.5A5.403 5.403 0 0 0 4 9c0 3.5 3 5.5 6 5.5-.39.49-.68 1.05-.85 1.65-.17.6-.22 1.23-.15 1.85v4" /><path d="M9 18c-4.51 2-5-2-7-2" /></svg>
Source
</a>
</div>
</header>
<section v-if="entry.component.hasDemo && demoComponent" class="mb-10">
<h2 :class="sectionTitle">Demo</h2>
<DocsDemo :component="demoComponent" :source="entry.component.demoSource" />
</section>
<DocsComponentAnatomy :component="entry.component" :package-name="pkg.name" />
</template>
<!-- GUIDE -->
<template v-else>
<DocsMarkdown :source="entry.section.markdown" />
</template>
</article>
<!-- Right rail TOC -->
<aside class="hidden xl:block">
<div class="sticky top-20 max-h-[calc(100vh-6rem)] overflow-y-auto">
<DocsToc :items="toc" />
</div>
</section>
</aside>
</div>
</template>
+114 -55
View File
@@ -1,5 +1,5 @@
<script setup lang="ts">const route = useRoute();
const { getPackage } = useDocs();
const { getPackage, countEntries } = useDocs();
const slug = computed(() => route.params.package as string);
const pkg = computed(() => getPackage(slug.value));
@@ -8,66 +8,125 @@ if (!pkg.value) {
throw createError({ statusCode: 404, message: `Package "${slug.value}" not found` });
}
useHead({
title: `${pkg.value.name} — @robonen/tools`,
});
useHead({ title: `${pkg.value.name} — @robonen/tools` });
const kindLabel = computed(() => ({
api: 'API Reference',
components: 'Components',
guide: 'Guide',
}[pkg.value!.kind]));
// For guide packages, surface the overview section inline.
const overview = computed(() =>
pkg.value?.kind === 'guide' ? pkg.value.sections.find(s => s.slug === 'overview') : undefined,
);
const otherSections = computed(() =>
pkg.value?.kind === 'guide' ? pkg.value.sections.filter(s => s.slug !== 'overview') : [],
);
</script>
<template>
<div v-if="pkg" class="max-w-3xl min-w-0">
<div v-if="pkg" class="max-w-3xl">
<!-- Header -->
<div class="mb-8">
<div class="flex items-center gap-3 mb-2">
<h1 class="text-2xl font-bold tracking-tight text-(--color-text)">
{{ pkg.name }}
</h1>
<DocsTag :label="`v${pkg.version}`" variant="since" />
<header class="mb-8 pb-8 border-b border-(--border)">
<div class="flex items-center gap-2.5 mb-2">
<h1 class="font-mono text-2xl font-bold tracking-tight text-(--fg)">{{ pkg.name }}</h1>
<DocsTag :label="`v${pkg.version}`" variant="neutral" />
</div>
<p class="text-(--color-text-soft)">
{{ pkg.description }}
</p>
</div>
<p class="text-(--fg-muted) text-[15px] leading-relaxed">{{ pkg.description }}</p>
<div class="mt-4 flex items-center gap-3 text-xs text-(--fg-subtle)">
<span>{{ kindLabel }}</span>
<span>·</span>
<span>{{ countEntries(pkg) }} entries</span>
</div>
<div class="mt-5">
<DocsCode :code="`pnpm add ${pkg.name}`" lang="bash" />
</div>
</header>
<!-- Install -->
<div class="mb-8">
<h2 class="text-sm font-semibold uppercase tracking-wider text-(--color-text-mute) mb-2">
Installation
</h2>
<DocsCode :code="`pnpm add ${pkg.name}`" lang="bash" />
</div>
<!-- Categories -->
<div v-for="category in pkg.categories" :key="category.slug" class="mb-8">
<h2 class="text-lg font-semibold text-(--color-text) mb-4 pb-2 border-b border-(--color-border)">
{{ category.name }}
</h2>
<div class="grid gap-2">
<NuxtLink
v-for="item in category.items"
:key="item.slug"
:to="`/${pkg.slug}/${item.slug}`"
class="group flex items-center gap-3 p-3 rounded-lg border border-(--color-border) hover:border-brand-300 hover:bg-(--color-bg-soft) transition-all"
>
<DocsBadge :kind="item.kind" />
<div class="min-w-0 flex-1">
<div class="flex items-center gap-2">
<span class="font-mono text-sm font-medium text-(--color-text) group-hover:text-brand-600 transition-colors">
{{ item.name }}
</span>
<DocsTag v-if="item.since" :label="`v${item.since}`" variant="since" />
<DocsTag v-if="item.hasTests" label="tested" variant="test" />
<DocsTag v-if="item.hasDemo" label="demo" variant="demo" />
<!-- API: categories of items -->
<template v-if="pkg.kind === 'api'">
<section v-for="category in pkg.categories" :key="category.slug" class="mb-10">
<h2 class="text-xs font-semibold uppercase tracking-wider text-(--fg-subtle) mb-4">
{{ category.name }}
<span class="ml-1 text-(--fg-subtle) normal-case font-normal">· {{ category.items.length }}</span>
</h2>
<div class="grid gap-2">
<NuxtLink
v-for="item in category.items"
:key="item.slug"
:to="`/${pkg.slug}/${item.slug}`"
class="group flex items-center gap-3 p-3 rounded-xl border border-(--border) bg-(--bg-elevated) hover:border-(--border-strong) hover:bg-(--bg-subtle) transition-all"
>
<DocsBadge :kind="item.kind" />
<div class="min-w-0 flex-1">
<div class="flex items-center gap-2 flex-wrap">
<span class="font-mono text-sm font-medium text-(--fg) group-hover:text-(--accent-text) transition-colors">{{ item.name }}</span>
<DocsTag v-if="item.hasTests" label="tested" variant="test" />
<DocsTag v-if="item.hasDemo" label="demo" variant="demo" />
</div>
<p v-if="item.description" class="text-sm text-(--fg-subtle) mt-0.5 truncate">{{ item.description }}</p>
</div>
<p v-if="item.description" class="text-sm text-(--color-text-mute) mt-0.5 truncate">
{{ item.description }}
</p>
</div>
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-(--color-text-mute) group-hover:text-brand-600 transition-colors shrink-0">
<polyline points="9 18 15 12 9 6" />
</svg>
</NuxtLink>
</div>
</div>
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-(--fg-subtle) group-hover:text-(--accent-text) transition-colors shrink-0">
<polyline points="9 18 15 12 9 6" />
</svg>
</NuxtLink>
</div>
</section>
</template>
<!-- Components: gallery -->
<template v-else-if="pkg.kind === 'components'">
<section>
<h2 class="text-xs font-semibold uppercase tracking-wider text-(--fg-subtle) mb-4">
All components <span class="normal-case font-normal">· {{ pkg.components.length }}</span>
</h2>
<div class="grid gap-3 sm:grid-cols-2">
<NuxtLink
v-for="c in pkg.components"
:key="c.slug"
:to="`/${pkg.slug}/${c.slug}`"
class="group block p-4 rounded-xl border border-(--border) bg-(--bg-elevated) hover:border-(--border-strong) hover:shadow-(--shadow-card) transition-all"
>
<div class="flex items-center justify-between gap-2 mb-1.5">
<span class="font-semibold text-(--fg) group-hover:text-(--accent-text) transition-colors">{{ c.name }}</span>
<span class="text-[11px] text-(--fg-subtle)">{{ c.parts.length }} parts</span>
</div>
<p v-if="c.description" class="text-sm text-(--fg-subtle) line-clamp-2">{{ c.description }}</p>
<div class="mt-3 flex flex-wrap gap-1">
<span
v-for="part in c.parts.slice(0, 4)"
:key="part.name"
class="text-[10px] font-mono px-1.5 py-0.5 rounded bg-(--bg-inset) border border-(--border) text-(--fg-subtle)"
>
{{ part.role }}
</span>
<span v-if="c.parts.length > 4" class="text-[10px] text-(--fg-subtle) px-1">+{{ c.parts.length - 4 }}</span>
</div>
</NuxtLink>
</div>
</section>
</template>
<!-- Guide: overview markdown + section links -->
<template v-else>
<DocsMarkdown v-if="overview" :source="overview.markdown" />
<section v-if="otherSections.length > 0" class="mt-10 pt-8 border-t border-(--border)">
<h2 class="text-xs font-semibold uppercase tracking-wider text-(--fg-subtle) mb-4">Sections</h2>
<div class="grid gap-2 sm:grid-cols-2">
<NuxtLink
v-for="s in otherSections"
:key="s.slug"
:to="`/${pkg.slug}/${s.slug}`"
class="group flex items-center justify-between gap-3 p-3.5 rounded-xl border border-(--border) bg-(--bg-elevated) hover:border-(--border-strong) hover:bg-(--bg-subtle) transition-all"
>
<span class="text-sm font-medium text-(--fg) group-hover:text-(--accent-text) transition-colors">{{ s.title }}</span>
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-(--fg-subtle) group-hover:text-(--accent-text) transition-colors shrink-0">
<polyline points="9 18 15 12 9 6" />
</svg>
</NuxtLink>
</div>
</section>
</template>
</div>
</template>
+52 -55
View File
@@ -1,72 +1,69 @@
<script setup lang="ts">const { getPackages, getTotalItems } = useDocs();
<script setup lang="ts">const { getGroupedPackages, getPackages, countEntries, getTotalItems } = useDocs();
const groups = getGroupedPackages();
const packages = getPackages();
const totalItems = getTotalItems();
const packageIcons: Record<string, string> = {
stdlib: '📦',
platform: '🖥️',
vue: '💚',
oxlint: '🔍',
const kindMeta: Record<string, { label: string; cls: string }> = {
api: { label: 'API', cls: 'bg-blue-100 text-blue-700 dark:bg-blue-500/15 dark:text-blue-300' },
components: { label: 'Components', cls: 'bg-fuchsia-100 text-fuchsia-700 dark:bg-fuchsia-500/15 dark:text-fuchsia-300' },
guide: { label: 'Guide', cls: 'bg-teal-100 text-teal-700 dark:bg-teal-500/15 dark:text-teal-300' },
};
useHead({ title: '@robonen/tools — Documentation' });
</script>
<template>
<div class="max-w-3xl min-w-0">
<div class="max-w-4xl">
<!-- Hero -->
<div class="mb-12">
<h1 class="text-3xl font-bold tracking-tight text-(--color-text) mb-3">
<section class="mb-14">
<div class="inline-flex items-center gap-2 mb-5 px-3 py-1 rounded-full border border-(--border) bg-(--bg-subtle) text-xs text-(--fg-muted)">
<span class="w-1.5 h-1.5 rounded-full bg-emerald-500" />
Auto-generated from source &amp; JSDoc
</div>
<h1 class="text-4xl sm:text-5xl font-bold tracking-tight text-(--fg) mb-4">
@robonen/tools
</h1>
<p class="text-lg text-(--color-text-soft) leading-relaxed">
A collection of TypeScript utilities, Vue composables, and developer tools.
Auto-generated documentation from source types and JSDoc annotations.
<p class="text-lg text-(--fg-muted) leading-relaxed max-w-2xl">
A monorepo of TypeScript utilities, Vue composables, headless UI primitives
and shared tooling documented, typed and tested.
</p>
<div class="mt-4 flex items-center gap-4 text-sm text-(--color-text-mute)">
<span>{{ packages.length }} packages</span>
<span>·</span>
<span>{{ totalItems }} documented items</span>
<div class="mt-6 flex flex-wrap items-center gap-x-6 gap-y-2 text-sm text-(--fg-subtle)">
<span><span class="text-(--fg) font-semibold">{{ packages.length }}</span> packages</span>
<span><span class="text-(--fg) font-semibold">{{ totalItems }}</span> documented items</span>
<span><span class="text-(--fg) font-semibold">{{ groups.length }}</span> groups</span>
</div>
</div>
</section>
<!-- Package cards -->
<div class="grid gap-4 sm:grid-cols-2">
<NuxtLink
v-for="pkg in packages"
:key="pkg.slug"
:to="`/${pkg.slug}`"
class="group block p-5 rounded-xl border border-(--color-border) hover:border-brand-300 hover:shadow-sm transition-all bg-(--color-bg)"
>
<div class="flex items-start gap-3">
<span class="text-2xl">{{ packageIcons[pkg.slug] ?? '📦' }}</span>
<div class="min-w-0">
<h2 class="font-semibold text-(--color-text) group-hover:text-brand-600 transition-colors">
{{ pkg.name }}
</h2>
<p class="text-sm text-(--color-text-soft) mt-1">
{{ pkg.description }}
</p>
<div class="mt-3 flex items-center gap-3 text-xs text-(--color-text-mute)">
<span>v{{ pkg.version }}</span>
<span>·</span>
<span>{{ pkg.categories.reduce((sum, c) => sum + c.items.length, 0) }} items</span>
<span>·</span>
<span>{{ pkg.categories.length }} categories</span>
</div>
</div>
</div>
</NuxtLink>
</div>
<!-- Quick start -->
<div class="mt-12">
<h2 class="text-lg font-semibold text-(--color-text) mb-4">
Quick Start
<!-- Package groups -->
<section v-for="grp in groups" :key="grp.group" class="mb-10">
<h2 class="text-xs font-semibold uppercase tracking-wider text-(--fg-subtle) mb-4">
{{ grp.label }}
</h2>
<div class="space-y-3">
<div v-for="pkg in packages" :key="pkg.slug">
<DocsCode :code="`pnpm add ${pkg.name}`" lang="bash" />
</div>
<div class="grid gap-3 sm:grid-cols-2">
<NuxtLink
v-for="pkg in grp.packages"
:key="pkg.slug"
:to="`/${pkg.slug}`"
class="group relative block p-5 rounded-card border border-(--border) bg-(--bg-elevated) hover:border-(--border-strong) hover:shadow-(--shadow-card) transition-all"
>
<div class="flex items-start justify-between gap-3 mb-2">
<h3 class="font-mono text-sm font-semibold text-(--fg) group-hover:text-(--accent-text) transition-colors">
{{ pkg.name }}
</h3>
<span :class="['text-[10px] px-2 py-0.5 rounded-full font-medium leading-none shrink-0', kindMeta[pkg.kind]?.cls]">
{{ kindMeta[pkg.kind]?.label }}
</span>
</div>
<p class="text-sm text-(--fg-muted) leading-relaxed line-clamp-2">
{{ pkg.description }}
</p>
<div class="mt-4 flex items-center gap-3 text-xs text-(--fg-subtle)">
<span class="font-mono">v{{ pkg.version }}</span>
<span>·</span>
<span>{{ countEntries(pkg) }} {{ pkg.kind === 'components' ? 'components' : pkg.kind === 'guide' ? 'sections' : 'items' }}</span>
</div>
</NuxtLink>
</div>
</div>
</section>
</div>
</template>
+10
View File
@@ -0,0 +1,10 @@
import { base, compose, imports, stylistic, typescript, vue } from '@robonen/eslint';
export default compose(base, typescript, vue, imports, stylistic, {
name: 'docs/build-scripts',
files: ['modules/**'],
rules: {
/* Build-time tooling (doc extractor) logs progress to the console. */
'no-console': 'off',
},
});
+420 -260
View File
@@ -1,42 +1,73 @@
/**
* ts-morph based metadata extractor for @robonen/tools packages.
*
* Scans package source files, extracts JSDoc annotations and TypeScript signatures,
* and produces a structured JSON metadata file consumed by the Nuxt docs site.
* Each package declares a {@link PackageKind} so it can be documented in the way
* that fits it best:
* - `api` → scans source for exported functions / classes / types + JSDoc
* - `components` → walks `.vue` parts and extracts per-part props / emits (anatomy)
* - `guide` → collects co-located Markdown files into prose sections
*
* Produces a single structured JSON metadata file consumed by the Nuxt docs site.
*/
import { resolve, relative, dirname } from 'node:path';
import { existsSync, readFileSync } from 'node:fs';
import { basename, dirname, relative, resolve } from 'node:path';
import { existsSync, readFileSync, readdirSync } from 'node:fs';
import { Project } from 'ts-morph';
import type { SourceFile, FunctionDeclaration, ClassDeclaration, InterfaceDeclaration, TypeAliasDeclaration, JSDoc, JSDocTag, MethodDeclaration, PropertyDeclaration, PropertySignature } from 'ts-morph';
import type { ClassDeclaration, FunctionDeclaration, InterfaceDeclaration, JSDoc, JSDocTag, MethodDeclaration, PropertyDeclaration, PropertySignature, SourceFile, TypeAliasDeclaration } from 'ts-morph';
import type {
DocsMetadata,
PackageMeta,
CategoryMeta,
ComponentMeta,
ComponentPartMeta,
DocsMetadata,
EmitMeta,
GuideSection,
ItemMeta,
MethodMeta,
PackageGroup,
PackageKind,
PackageMeta,
ParamMeta,
PropertyMeta,
ReturnMeta,
TypeParamMeta,
MethodMeta,
PropertyMeta,
} from './types';
/** Repository root — docs/modules/extractor → three levels up */
const ROOT = resolve(import.meta.dirname, '..', '..', '..');
/** Packages to document — relative paths from repo root */
const PACKAGES: PackageConfig[] = [
{ path: 'core/stdlib', slug: 'stdlib' },
{ path: 'core/platform', slug: 'platform' },
{ path: 'vue/toolkit', slug: 'vue' },
{ path: 'configs/oxlint', slug: 'oxlint' },
];
interface PackageConfig {
/** Path relative to repo root */
path: string;
/** URL slug */
slug: string;
/** Presentation kind */
kind: PackageKind;
/** Sidebar group */
group: PackageGroup;
/** For `guide` kind: markdown sources relative to the package dir.
* Supports exact files (`README.md`) and single-level globs (`rules/*.md`). */
guideSources?: string[];
}
/** Packages to document. */
const PACKAGES: PackageConfig[] = [
// ── core ──
{ path: 'core/stdlib', slug: 'stdlib', kind: 'api', group: 'core' },
{ path: 'core/platform', slug: 'platform', kind: 'api', group: 'core' },
{ path: 'core/fetch', slug: 'fetch', kind: 'api', group: 'core' },
{ path: 'core/encoding', slug: 'encoding', kind: 'api', group: 'core' },
// ── vue ──
{ path: 'vue/toolkit', slug: 'vue', kind: 'api', group: 'vue' },
{ path: 'vue/editor', slug: 'editor', kind: 'api', group: 'vue' },
{ path: 'vue/primitives', slug: 'primitives', kind: 'components', group: 'vue' },
// ── configs ──
{ path: 'configs/eslint', slug: 'eslint', kind: 'guide', group: 'configs', guideSources: ['README.md', 'rules/*.md'] },
{ path: 'configs/tsconfig', slug: 'tsconfig', kind: 'guide', group: 'configs', guideSources: ['README.md'] },
{ path: 'configs/tsdown', slug: 'tsdown', kind: 'guide', group: 'configs', guideSources: ['README.md'] },
// ── infra ──
{ path: 'infra/renovate', slug: 'renovate', kind: 'guide', group: 'infra', guideSources: ['README.md'] },
];
// ── Helpers ────────────────────────────────────────────────────────────────
function toKebabCase(str: string): string {
@@ -50,6 +81,14 @@ function slugify(name: string): string {
return toKebabCase(name);
}
function toPascalCase(slug: string): string {
return slug
.split(/[-_]/)
.filter(Boolean)
.map(s => s.charAt(0).toUpperCase() + s.slice(1))
.join('');
}
function getJsDocTags(jsdocs: JSDoc[]): JSDocTag[] {
return jsdocs.flatMap(doc => doc.getTags());
}
@@ -62,11 +101,9 @@ function getTagValue(tags: JSDocTag[], tagName: string): string {
}
function getDescription(jsdocs: JSDoc[], tags: JSDocTag[]): string {
// Try @description tag first
const descTag = getTagValue(tags, 'description');
if (descTag) return descTag;
// Fall back to the main JSDoc comment text
for (const doc of jsdocs) {
const desc = doc.getDescription().trim();
if (desc) return desc;
@@ -80,7 +117,6 @@ function getExamples(tags: JSDocTag[]): string[] {
.filter(t => t.getTagName() === 'example')
.map((t) => {
const text = t.getCommentText()?.trim() ?? '';
// Strip surrounding ```ts ... ``` if present
return text.replace(/^```(?:ts|typescript)?\n?/, '').replace(/\n?```$/, '').trim();
})
.filter(Boolean);
@@ -96,16 +132,11 @@ function extractParams(tags: JSDocTag[], node: FunctionDeclaration | MethodDecla
const optional = param.isOptional();
const defaultValue = param.getInitializer()?.getText() ?? null;
// Find matching @param tag
const paramTag = paramTags.find((t) => {
const tagText = t.getText();
return tagText.includes(name);
});
const paramTag = paramTags.find(t => t.getText().includes(name));
let description = '';
if (paramTag) {
const comment = paramTag.getCommentText() ?? '';
// Remove leading {type} annotation and param name
description = comment
.replace(/^\{[^}]*\}\s*/, '')
.replace(new RegExp(`^${name}\\s*[-–—]?\\s*`), '')
@@ -121,8 +152,7 @@ function extractParams(tags: JSDocTag[], node: FunctionDeclaration | MethodDecla
}
function extractTypeParams(node: FunctionDeclaration | ClassDeclaration | InterfaceDeclaration | TypeAliasDeclaration): TypeParamMeta[] {
const typeParams = node.getTypeParameters();
return typeParams.map(tp => ({
return node.getTypeParameters().map(tp => ({
name: tp.getName(),
constraint: tp.getConstraint()?.getText() ?? null,
default: tp.getDefault()?.getText() ?? null,
@@ -143,20 +173,14 @@ function extractReturnMeta(tags: JSDocTag[], node: FunctionDeclaration | MethodD
function extractMethodMeta(method: MethodDeclaration): MethodMeta {
const jsdocs = method.getJsDocs();
const tags = getJsDocTags(jsdocs);
const name = method.getName();
// Simplified signature
const signature = method.getText().split('{')[0]?.trim() ?? '';
const visibility = method.getScope() ?? 'public';
return {
name,
name: method.getName(),
description: getDescription(jsdocs, tags),
signatures: [signature],
signatures: [method.getText().split('{')[0]?.trim() ?? ''],
params: extractParams(tags, method),
returns: extractReturnMeta(tags, method),
visibility,
visibility: method.getScope() ?? 'public',
};
}
@@ -175,50 +199,42 @@ function extractPropertyMeta(prop: PropertyDeclaration | PropertySignature): Pro
}
function getSourceDir(itemPath: string): string {
// Get the directory containing the item's index.ts
return dirname(itemPath);
}
function hasDemoFile(sourceFilePath: string): boolean {
const dir = getSourceDir(sourceFilePath);
return existsSync(resolve(dir, 'demo.vue'));
return existsSync(resolve(getSourceDir(sourceFilePath), 'demo.vue'));
}
function readDemoSource(sourceFilePath: string): string {
const dir = getSourceDir(sourceFilePath);
const demoPath = resolve(dir, 'demo.vue');
const demoPath = resolve(getSourceDir(sourceFilePath), 'demo.vue');
if (!existsSync(demoPath)) return '';
return readFileSync(demoPath, 'utf-8');
}
function hasTestFile(sourceFilePath: string): boolean {
const dir = getSourceDir(sourceFilePath);
return existsSync(resolve(dir, 'index.test.ts'));
return existsSync(resolve(dir, 'index.test.ts')) || existsSync(resolve(dir, '__test__'));
}
// ── Extraction ─────────────────────────────────────────────────────────────
// ── API Extraction ───────────────────────────────────────────────────────────
function extractFunction(fn: FunctionDeclaration, sourceFilePath: string, entryPoint: string): ItemMeta | null {
const name = fn.getName();
if (!name) return null;
// Skip private/internal functions
if (name.startsWith('_')) return null;
if (!name || name.startsWith('_')) return null;
const jsdocs = fn.getJsDocs();
const tags = getJsDocTags(jsdocs);
const description = getDescription(jsdocs, tags);
// Get signature text without body
const signatureText = fn.getOverloads().length > 0
? fn.getOverloads().map(o => o.getText().trim())
: [fn.getText().split('{')[0]?.trim() + '{ ... }'];
: [`${fn.getText().split('{')[0]?.trim()}{ ... }`];
return {
name,
slug: slugify(name),
kind: 'function',
description,
description: getDescription(jsdocs, tags),
since: getTagValue(tags, 'since'),
signatures: signatureText,
params: extractParams(tags, fn),
@@ -252,7 +268,6 @@ function extractClass(cls: ClassDeclaration, sourceFilePath: string, entryPoint:
.filter(p => (p.getScope() ?? 'public') === 'public')
.map(p => extractPropertyMeta(p));
// Also include get accessors as readonly properties
const getters = cls.getGetAccessors()
.filter(g => (g.getScope() ?? 'public') === 'public')
.map(g => ({
@@ -264,11 +279,8 @@ function extractClass(cls: ClassDeclaration, sourceFilePath: string, entryPoint:
readonly: true,
}));
// Build class signature
const typeParams = cls.getTypeParameters();
const typeParamStr = typeParams.length > 0
? `<${typeParams.map(tp => tp.getText()).join(', ')}>`
: '';
const typeParamStr = typeParams.length > 0 ? `<${typeParams.map(tp => tp.getText()).join(', ')}>` : '';
const extendsClause = cls.getExtends() ? ` extends ${cls.getExtends()!.getText()}` : '';
const implementsClause = cls.getImplements().length > 0
? ` implements ${cls.getImplements().map(i => i.getText()).join(', ')}`
@@ -307,13 +319,9 @@ function extractInterface(iface: InterfaceDeclaration, sourceFilePath: string, e
const properties = iface.getProperties().map(p => extractPropertyMeta(p));
const typeParams = iface.getTypeParameters();
const typeParamStr = typeParams.length > 0
? `<${typeParams.map(tp => tp.getText()).join(', ')}>`
: '';
const typeParamStr = typeParams.length > 0 ? `<${typeParams.map(tp => tp.getText()).join(', ')}>` : '';
const extendsExprs = iface.getExtends();
const extendsStr = extendsExprs.length > 0
? ` extends ${extendsExprs.map(e => e.getText()).join(', ')}`
: '';
const extendsStr = extendsExprs.length > 0 ? ` extends ${extendsExprs.map(e => e.getText()).join(', ')}` : '';
const signature = `interface ${name}${typeParamStr}${extendsStr}`;
return {
@@ -345,15 +353,13 @@ function extractTypeAlias(typeAlias: TypeAliasDeclaration, sourceFilePath: strin
const jsdocs = typeAlias.getJsDocs();
const tags = getJsDocTags(jsdocs);
const signature = typeAlias.getText().trim();
return {
name,
slug: slugify(name),
kind: 'type',
description: getDescription(jsdocs, tags),
since: getTagValue(tags, 'since'),
signatures: [signature],
signatures: [typeAlias.getText().trim()],
params: [],
returns: null,
typeParams: extractTypeParams(typeAlias),
@@ -369,34 +375,25 @@ function extractTypeAlias(typeAlias: TypeAliasDeclaration, sourceFilePath: strin
};
}
// ── Source Tree Walking ────────────────────────────────────────────────────
function collectExportedItems(
sourceFile: SourceFile,
entryPoint: string,
visited: Set<string> = new Set(),
): ItemMeta[] {
function collectExportedItems(sourceFile: SourceFile, entryPoint: string, visited: Set<string> = new Set()): ItemMeta[] {
const filePath = sourceFile.getFilePath();
if (visited.has(filePath)) return [];
visited.add(filePath);
const items: ItemMeta[] = [];
// Direct exports from this file
for (const fn of sourceFile.getFunctions()) {
if (!fn.isExported()) continue;
// Skip implementation signatures that have overloads
const overloads = fn.getOverloads();
if (overloads.length > 0) {
// Use the first overload's doc for metadata, but collect all signatures
const firstOverload = overloads[0]!;
const jsdocs = firstOverload.getJsDocs();
const tags = getJsDocTags(jsdocs);
const name = fn.getName();
if (!name || name.startsWith('_')) continue;
const item: ItemMeta = {
items.push({
name,
slug: slugify(name),
kind: 'function',
@@ -415,8 +412,7 @@ function collectExportedItems(
relatedTypes: [],
sourcePath: relative(ROOT, filePath),
entryPoint,
};
items.push(item);
});
}
else {
const item = extractFunction(fn, filePath, entryPoint);
@@ -432,11 +428,9 @@ function collectExportedItems(
for (const iface of sourceFile.getInterfaces()) {
if (!iface.isExported()) continue;
// Skip internal interfaces (e.g. Options, Return types that are documented inline)
const jsdocs = iface.getJsDocs();
const tags = getJsDocTags(jsdocs);
const hasCategory = getTagValue(tags, 'category') !== '';
// Only include interfaces with @category or that have significant documentation
if (!hasCategory && jsdocs.length === 0) continue;
const item = extractInterface(iface, filePath, entryPoint);
if (item) items.push(item);
@@ -452,73 +446,344 @@ function collectExportedItems(
if (item) items.push(item);
}
// Follow barrel re-exports: export * from './...'
for (const exportDecl of sourceFile.getExportDeclarations()) {
const moduleSpecifier = exportDecl.getModuleSpecifierValue();
if (!moduleSpecifier) continue;
if (!exportDecl.getModuleSpecifierValue()) continue;
const referencedFile = exportDecl.getModuleSpecifierSourceFile();
if (referencedFile) {
items.push(...collectExportedItems(referencedFile, entryPoint, visited));
}
if (referencedFile) items.push(...collectExportedItems(referencedFile, entryPoint, visited));
}
return items;
}
// ── Co-located Type Grouping ───────────────────────────────────────────────
/**
* Groups types/interfaces from `types.ts` files with their sibling
* class/function items from the same directory.
*
* For example, Transition and TransitionConfig from StateMachine/types.ts
* get attached as relatedTypes of StateMachine and AsyncStateMachine.
* class/function items from the same directory as `relatedTypes`.
*/
function groupCoLocatedTypes(items: ItemMeta[]): ItemMeta[] {
// Build a map: directory → items from types.ts
const typesByDir = new Map<string, ItemMeta[]>();
// Build a map: directory → primary items (classes, functions)
const primaryByDir = new Map<string, ItemMeta[]>();
for (const item of items) {
const dir = dirname(item.sourcePath);
const isTypesFile = item.sourcePath.endsWith('/types.ts');
const isSecondary = isTypesFile && (item.kind === 'type' || item.kind === 'interface');
const isSecondary = item.sourcePath.endsWith('/types.ts') && (item.kind === 'type' || item.kind === 'interface');
if (isSecondary) {
const existing = typesByDir.get(dir) ?? [];
existing.push(item);
typesByDir.set(dir, existing);
}
else {
const existing = primaryByDir.get(dir) ?? [];
existing.push(item);
primaryByDir.set(dir, existing);
}
const target = isSecondary ? typesByDir : primaryByDir;
const existing = target.get(dir) ?? [];
existing.push(item);
target.set(dir, existing);
}
// Attach co-located types to their primary items
const absorbed = new Set<string>();
for (const entry of Array.from(typesByDir.entries())) {
const [dir, types] = entry;
for (const [dir, types] of Array.from(typesByDir.entries())) {
const primaries = primaryByDir.get(dir);
if (!primaries || primaries.length === 0) continue;
// Distribute types to all primary items in the same directory
for (const primary of primaries) {
primary.relatedTypes = [...types];
}
for (const t of types) {
absorbed.add(`${t.entryPoint}:${t.name}`);
}
for (const primary of primaries) primary.relatedTypes = [...types];
for (const t of types) absorbed.add(`${t.entryPoint}:${t.name}`);
}
// Return items without the absorbed types
return items.filter(item => !absorbed.has(`${item.entryPoint}:${item.name}`));
}
// ── Package Extraction ─────────────────────────────────────────────────────
function inferCategoryFromItem(item: ItemMeta): string {
const parts = item.sourcePath.split('/src/');
if (parts.length < 2) return 'General';
const segments = parts[1]!.split('/');
if (segments[0] === 'composables' && segments.length >= 3) {
const cat = segments[1]!;
return cat.charAt(0).toUpperCase() + cat.slice(1);
}
if (segments[0] && segments.length >= 2) {
const cat = segments[0];
return cat.charAt(0).toUpperCase() + cat.slice(1);
}
return 'General';
}
/** Resolve a package's export subpaths to source entry files. */
function resolveEntryPoints(pkgDir: string, exportsField: Record<string, any>): Array<{ subpath: string; filePath: string }> {
const entryPoints: Array<{ subpath: string; filePath: string }> = [];
for (const [subpath, value] of Object.entries(exportsField)) {
if (typeof value !== 'object' || value === null) continue;
let entry: any = (value as Record<string, any>).import ?? (value as Record<string, any>).types;
if (typeof entry === 'object' && entry !== null) entry = entry.types || entry.default;
if (!entry || typeof entry !== 'string') continue;
// Wildcard exports (e.g. "./*") can't be resolved to a single file here.
if (entry.includes('*')) continue;
const srcPath = entry
.replace(/^\.\/dist\//, 'src/')
.replace(/\.m?js$/, '.ts')
.replace(/\.d\.m?ts$/, '.ts');
const fullPath = resolve(pkgDir, srcPath);
if (existsSync(fullPath)) {
entryPoints.push({ subpath, filePath: fullPath });
}
else {
const altPath = resolve(pkgDir, srcPath.replace(/\.ts$/, '/index.ts'));
if (existsSync(altPath)) entryPoints.push({ subpath, filePath: altPath });
}
}
// Fallback: a conventional src/index.ts entry.
if (entryPoints.length === 0) {
const idx = resolve(pkgDir, 'src/index.ts');
if (existsSync(idx)) entryPoints.push({ subpath: '.', filePath: idx });
}
return entryPoints;
}
function buildApiCategories(pkgDir: string): CategoryMeta[] {
const pkgJson = JSON.parse(readFileSync(resolve(pkgDir, 'package.json'), 'utf-8'));
const entryPoints = resolveEntryPoints(pkgDir, pkgJson.exports ?? {});
if (entryPoints.length === 0) return [];
const tsconfigPath = resolve(pkgDir, 'tsconfig.json');
const project = new Project({
tsConfigFilePath: existsSync(tsconfigPath) ? tsconfigPath : undefined,
skipAddingFilesFromTsConfig: true,
});
for (const ep of entryPoints) project.addSourceFileAtPath(ep.filePath);
project.resolveSourceFileDependencies();
const allItems: ItemMeta[] = [];
for (const ep of entryPoints) {
const sourceFile = project.getSourceFile(ep.filePath);
if (!sourceFile) continue;
allItems.push(...collectExportedItems(sourceFile, ep.subpath));
}
const seen = new Set<string>();
const uniqueItems = allItems.filter((item) => {
const key = `${item.entryPoint}:${item.name}`;
if (seen.has(key)) return false;
seen.add(key);
return true;
});
const groupedItems = groupCoLocatedTypes(uniqueItems);
const categoryMap = new Map<string, ItemMeta[]>();
for (const item of groupedItems) {
const cat = inferCategoryFromItem(item);
const existing = categoryMap.get(cat) ?? [];
existing.push(item);
categoryMap.set(cat, existing);
}
return Array.from(categoryMap.entries())
.map(([name, items]) => ({
name,
slug: slugify(name),
items: items.sort((a, b) => a.name.localeCompare(b.name)),
}))
.sort((a, b) => a.name.localeCompare(b.name));
}
// ── Component Extraction ───────────────────────────────────────────────────────
/** Pull a named `<script>` block's inner content out of an SFC string. */
function extractScriptBlock(sfc: string, setup: boolean): string {
// Match <script ... lang="ts"> ... </script>; distinguish setup vs plain.
const re = /<script\b([^>]*)>([\s\S]*?)<\/script>/g;
let match: RegExpExecArray | null;
while ((match = re.exec(sfc)) !== null) {
const attrs = match[1] ?? '';
const isSetup = /\bsetup\b/.test(attrs);
if (isSetup === setup) return match[2] ?? '';
}
return '';
}
/** Parse `defineEmits<{ 'a': [x: T]; b: [] }>()` from a setup block. */
function extractEmits(setupScript: string): EmitMeta[] {
const m = setupScript.match(/defineEmits<\{([\s\S]*?)\}>\s*\(\s*\)/);
if (!m) return [];
const body = m[1] ?? '';
const emits: EmitMeta[] = [];
// Split on ; or newlines, then match `name: [payload]`
for (const raw of body.split(/[;\n]/)) {
const line = raw.trim();
if (!line) continue;
const em = line.match(/^['"]?([\w:-]+)['"]?\s*:\s*(\[[\s\S]*\])\s*$/);
if (em) emits.push({ name: em[1]!, payload: em[2]!, description: '' });
}
return emits;
}
let partProjectCounter = 0;
/** Parse the `XxxProps` interface from a `.vue` part using ts-morph in-memory. */
function extractPartProps(plainScript: string): { props: PropertyMeta[]; description: string } {
if (!plainScript.trim()) return { props: [], description: '' };
// Strip imports — types they reference are unresolved here, which is fine:
// getText() on property type nodes still yields the written type text.
const project = new Project({ useInMemoryFileSystem: true, skipAddingFilesFromTsConfig: true, compilerOptions: { allowJs: true, skipLibCheck: true } });
const sf = project.createSourceFile(`__part_${partProjectCounter++}.ts`, plainScript);
const propsIface = sf.getInterfaces().find(i => i.getName().endsWith('Props'));
if (!propsIface) return { props: [], description: '' };
const jsdocs = propsIface.getJsDocs();
const description = getDescription(jsdocs, getJsDocTags(jsdocs));
const props = propsIface.getProperties().map((p) => {
const pj = p.getJsDocs();
const ptags = getJsDocTags(pj);
return {
name: p.getName(),
// Use the written type text (declared), not the resolved type.
type: p.getTypeNode()?.getText() ?? p.getType().getText(p),
description: getDescription(pj, ptags),
optional: p.hasQuestionToken(),
defaultValue: getTagValue(ptags, 'default') || null,
readonly: p.isReadonly(),
} satisfies PropertyMeta;
});
return { props, description };
}
/** Read default-export component names from an index.ts barrel, in source order. */
function readPartOrder(indexPath: string): string[] {
if (!existsSync(indexPath)) return [];
const src = readFileSync(indexPath, 'utf-8');
const order: string[] = [];
const re = /export\s*\{\s*default\s+as\s+(\w+)\s*\}\s*from\s*['"]\.\/([\w.-]+)\.vue['"]/g;
let m: RegExpExecArray | null;
while ((m = re.exec(src)) !== null) order.push(m[1]!);
return order;
}
function roleFromName(componentName: string, base: string): string {
// AccordionRoot + base "Accordion" → "Root"; AccordionItem → "Item"
let role = componentName;
if (componentName.startsWith(base)) role = componentName.slice(base.length);
return role || 'Root';
}
function buildComponents(pkgDir: string): ComponentMeta[] {
const srcDir = resolve(pkgDir, 'src');
if (!existsSync(srcDir)) return [];
const components: ComponentMeta[] = [];
for (const entry of readdirSync(srcDir, { withFileTypes: true })) {
if (!entry.isDirectory()) continue;
const dir = resolve(srcDir, entry.name);
// A component group is any dir that ships at least one .vue file.
const vueFiles = readdirSync(dir).filter(f => f.endsWith('.vue'));
if (vueFiles.length === 0) continue;
const slug = entry.name;
const base = toPascalCase(slug);
// Preserve the anatomy order declared in index.ts; fall back to filenames.
const order = readPartOrder(resolve(dir, 'index.ts'));
const orderedFiles = [
...order.map(name => `${name}.vue`).filter(f => vueFiles.includes(f)),
...vueFiles.filter(f => !order.includes(f.replace(/\.vue$/, ''))),
];
const parts: ComponentPartMeta[] = [];
let groupDescription = '';
for (const file of orderedFiles) {
const sfc = readFileSync(resolve(dir, file), 'utf-8');
const plain = extractScriptBlock(sfc, false);
const setup = extractScriptBlock(sfc, true);
const { props, description } = extractPartProps(plain);
const name = file.replace(/\.vue$/, '');
const role = roleFromName(name, base);
if (role === 'Root' && description && !groupDescription) groupDescription = description;
parts.push({ name, role, description, props, emits: extractEmits(setup) });
}
const entryPoint = `./${slug}`;
const demoPath = resolve(dir, 'demo.vue');
const hasDemo = existsSync(demoPath);
components.push({
name: base,
slug,
description: groupDescription,
entryPoint,
parts,
hasDemo,
demoSource: hasDemo ? readFileSync(demoPath, 'utf-8') : '',
sourcePath: relative(ROOT, dir),
});
}
return components.sort((a, b) => a.name.localeCompare(b.name));
}
// ── Guide Extraction ───────────────────────────────────────────────────────────
/** Resolve guide source patterns (exact files + single-level `dir/*.md`). */
function resolveGuideFiles(pkgDir: string, patterns: string[]): string[] {
const files: string[] = [];
for (const pattern of patterns) {
if (pattern.includes('*')) {
const dir = resolve(pkgDir, dirname(pattern));
if (!existsSync(dir)) continue;
const ext = pattern.slice(pattern.lastIndexOf('.'));
const matched = readdirSync(dir)
.filter(f => f.endsWith(ext) && f.toLowerCase() !== 'readme.md')
.sort()
.map(f => resolve(dir, f));
files.push(...matched);
}
else {
const full = resolve(pkgDir, pattern);
if (existsSync(full)) files.push(full);
}
}
return files;
}
function titleFromMarkdown(md: string, fallback: string): string {
const m = md.match(/^\s*#\s+(.+)$/m);
return m ? m[1]!.trim() : fallback;
}
function buildGuideSections(pkgDir: string, patterns: string[], pkgDescription: string): GuideSection[] {
const files = resolveGuideFiles(pkgDir, patterns);
const sections: GuideSection[] = [];
for (const file of files) {
const markdown = readFileSync(file, 'utf-8');
const fileSlug = basename(file).replace(/\.md$/i, '');
const slug = /readme/i.test(fileSlug) ? 'overview' : slugify(fileSlug);
const fallbackTitle = slug === 'overview' ? 'Overview' : fileSlug;
sections.push({ title: titleFromMarkdown(markdown, fallbackTitle), slug, markdown });
}
// Ensure an overview exists even when there's no README.
if (!sections.some(s => s.slug === 'overview')) {
sections.unshift({
title: 'Overview',
slug: 'overview',
markdown: `# Overview\n\n${pkgDescription || 'Documentation for this package.'}\n`,
});
}
else {
// Move overview to the front.
sections.sort((a, b) => (a.slug === 'overview' ? -1 : b.slug === 'overview' ? 1 : 0));
}
return sections;
}
// ── Package Extraction ─────────────────────────────────────────────────────────
function extractPackage(config: PackageConfig): PackageMeta | null {
const pkgDir = resolve(ROOT, config.path);
@@ -530,136 +795,31 @@ function extractPackage(config: PackageConfig): PackageMeta | null {
}
const pkgJson = JSON.parse(readFileSync(pkgJsonPath, 'utf-8'));
const exports = pkgJson.exports ?? {};
// Determine entry points
const entryPoints: Array<{ subpath: string; filePath: string }> = [];
for (const [subpath, value] of Object.entries(exports)) {
if (typeof value === 'object' && value !== null) {
const entry = (value as Record<string, string>).import ?? (value as Record<string, string>).types;
if (entry) {
// Map dist path back to source path
// e.g. "./dist/index.js" → "src/index.ts" or "./dist/browsers.js" → "src/browsers/index.ts"
const srcPath = entry
.replace(/^\.\/dist\//, 'src/')
.replace(/\.js$/, '.ts')
.replace(/\.d\.ts$/, '.ts');
const fullPath = resolve(pkgDir, srcPath);
if (existsSync(fullPath)) {
entryPoints.push({ subpath, filePath: fullPath });
}
else {
// Try index.ts in subdirectory
const altPath = resolve(pkgDir, srcPath.replace(/\.ts$/, '/index.ts'));
if (existsSync(altPath)) {
entryPoints.push({ subpath, filePath: altPath });
}
else {
console.warn(`[extractor] Entry point not found: ${fullPath} or ${altPath}`);
}
}
}
}
}
if (entryPoints.length === 0) {
console.warn(`[extractor] No entry points found for ${pkgJson.name}`);
return null;
}
// Create ts-morph project for this package
const tsconfigPath = resolve(pkgDir, 'tsconfig.json');
const project = new Project({
tsConfigFilePath: existsSync(tsconfigPath) ? tsconfigPath : undefined,
skipAddingFilesFromTsConfig: true,
});
// Add entry files
for (const ep of entryPoints) {
project.addSourceFileAtPath(ep.filePath);
}
// Resolve all referenced files
project.resolveSourceFileDependencies();
// Extract items from all entry points
const allItems: ItemMeta[] = [];
for (const ep of entryPoints) {
const sourceFile = project.getSourceFile(ep.filePath);
if (!sourceFile) continue;
const items = collectExportedItems(sourceFile, ep.subpath);
allItems.push(...items);
}
// Deduplicate by name (overloaded functions may appear once already)
const seen = new Set<string>();
const uniqueItems = allItems.filter((item) => {
const key = `${item.entryPoint}:${item.name}`;
if (seen.has(key)) return false;
seen.add(key);
return true;
});
// Group co-located types with their parent class/function.
// Types/interfaces from a types.ts file in the same directory as a
// class or function become relatedTypes of that primary item.
const groupedItems = groupCoLocatedTypes(uniqueItems);
// Group by category
const categoryMap = new Map<string, ItemMeta[]>();
for (const item of groupedItems) {
// Infer category from source path if not set
const jsdocCategory = inferCategoryFromItem(item);
const existing = categoryMap.get(jsdocCategory) ?? [];
existing.push(item);
categoryMap.set(jsdocCategory, existing);
}
const categories: CategoryMeta[] = Array.from(categoryMap.entries())
.map(([name, items]) => ({
name,
slug: slugify(name),
items: items.sort((a, b) => a.name.localeCompare(b.name)),
}))
.sort((a, b) => a.name.localeCompare(b.name));
return {
const base: PackageMeta = {
name: pkgJson.name,
version: pkgJson.version,
description: pkgJson.description ?? '',
slug: config.slug,
entryPoints: entryPoints.map(ep => ep.subpath),
categories,
kind: config.kind,
group: config.group,
entryPoints: Object.keys(pkgJson.exports ?? { '.': {} }),
categories: [],
components: [],
sections: [],
};
}
function inferCategoryFromItem(item: ItemMeta): string {
// Parse from source path
const parts = item.sourcePath.split('/src/');
if (parts.length < 2) return 'General';
const segments = parts[1]!.split('/');
// Patterns:
// composables/browser/useIntervalFn/index.ts → "Browser"
// arrays/cluster/index.ts → "Arrays"
// patterns/behavioral/PubSub/index.ts → "Patterns"
// types/js/primitives.ts → "Types"
// structs/Stack/index.ts → "Data Structures" (use @category if available)
if (segments[0] === 'composables' && segments.length >= 3) {
const cat = segments[1]!;
return cat.charAt(0).toUpperCase() + cat.slice(1);
if (config.kind === 'api') {
base.categories = buildApiCategories(pkgDir);
}
else if (config.kind === 'components') {
base.components = buildComponents(pkgDir);
}
else if (config.kind === 'guide') {
base.sections = buildGuideSections(pkgDir, config.guideSources ?? ['README.md'], base.description);
}
if (segments[0] && segments.length >= 2) {
const cat = segments[0];
return cat.charAt(0).toUpperCase() + cat.slice(1);
}
return 'General';
return base;
}
// ── Main ───────────────────────────────────────────────────────────────────
@@ -670,31 +830,31 @@ export function extract(): DocsMetadata {
const packages: PackageMeta[] = [];
for (const config of PACKAGES) {
console.log(`[extractor] Processing ${config.path}...`);
const pkg = extractPackage(config);
if (pkg) {
const itemCount = pkg.categories.reduce((sum, c) => sum + c.items.length, 0);
console.log(`[extractor] → ${pkg.name}@${pkg.version}: ${itemCount} items in ${pkg.categories.length} categories`);
packages.push(pkg);
if (!pkg) continue;
let summary: string;
if (pkg.kind === 'api') {
const itemCount = pkg.categories.reduce((s, c) => s + c.items.length, 0);
summary = `${itemCount} items / ${pkg.categories.length} categories`;
}
else if (pkg.kind === 'components') {
const partCount = pkg.components.reduce((s, c) => s + c.parts.length, 0);
summary = `${pkg.components.length} components / ${partCount} parts`;
}
else {
summary = `${pkg.sections.length} sections`;
}
console.log(`[extractor] → ${pkg.name}@${pkg.version} [${pkg.kind}]: ${summary}`);
packages.push(pkg);
}
const metadata: DocsMetadata = {
packages,
generatedAt: new Date().toISOString(),
};
console.log(`[extractor] Done — ${packages.length} packages`);
const totalItems = packages.reduce(
(sum, pkg) => sum + pkg.categories.reduce((s, c) => s + c.items.length, 0),
0,
);
console.log(`[extractor] Done — ${totalItems} items across ${packages.length} packages`);
return metadata;
return { packages, generatedAt: new Date().toISOString() };
}
// Allow running directly — prints metadata as JSON to stdout
if (import.meta.filename === process.argv[1]) {
const metadata = extract();
console.log(JSON.stringify(metadata, null, 2));
console.log(JSON.stringify(extract(), null, 2));
}
+25 -7
View File
@@ -6,8 +6,8 @@
* pages/components via `import metadata from '#docs/metadata'`.
*/
import { defineNuxtModule, addTemplate, createResolver } from '@nuxt/kit';
import { resolve, dirname } from 'node:path';
import { addTemplate, createResolver, defineNuxtModule } from '@nuxt/kit';
import { dirname, resolve } from 'node:path';
import type { DocsMetadata } from './types';
export default defineNuxtModule({
@@ -81,16 +81,26 @@ declare module '#docs/metadata' {
},
});
// Register prerender routes from metadata
// Register prerender routes from metadata — one detail route per documented
// leaf, regardless of package kind (api items / components / guide sections).
nuxt.hook('prerender:routes', async ({ routes }: { routes: Set<string> }) => {
if (metadata.packages.length === 0) return;
for (const pkg of metadata.packages) {
routes.add(`/${pkg.slug}`);
for (const category of pkg.categories) {
for (const item of category.items) {
routes.add(`/${pkg.slug}/${item.slug}`);
}
if (pkg.kind === 'api') {
for (const category of pkg.categories)
for (const item of category.items)
routes.add(`/${pkg.slug}/${item.slug}`);
}
else if (pkg.kind === 'components') {
for (const component of pkg.components)
routes.add(`/${pkg.slug}/${component.slug}`);
}
else if (pkg.kind === 'guide') {
for (const section of pkg.sections)
routes.add(`/${pkg.slug}/${section.slug}`);
}
}
@@ -105,6 +115,7 @@ declare module '#docs/metadata' {
const entries: string[] = [];
for (const pkg of metadata.packages) {
// api items
for (const cat of pkg.categories) {
for (const item of cat.items) {
if (item.hasDemo) {
@@ -113,6 +124,13 @@ declare module '#docs/metadata' {
}
}
}
// component groups
for (const component of pkg.components) {
if (component.hasDemo) {
const demoPath = resolve(ROOT, component.sourcePath, 'demo.vue');
entries.push(` '${pkg.slug}/${component.slug}': defineAsyncComponent(() => import('${demoPath}')),`);
}
}
}
if (entries.length === 0) {
+85 -3
View File
@@ -1,7 +1,11 @@
/**
* Metadata types for the documentation extractor.
* These types represent the structured data extracted from source packages
* via ts-morph, used to generate documentation pages.
*
* The docs site is "flexible": every package declares a {@link PackageKind}
* and is rendered with a layout that fits its nature —
* - `api` → reference of functions / classes / types (from JSDoc)
* - `components` → component gallery with per-part anatomy (props/emits/slots)
* - `guide` → prose guide rendered from co-located Markdown
*/
export interface DocsMetadata {
@@ -9,6 +13,12 @@ export interface DocsMetadata {
generatedAt: string;
}
/** How a package's documentation should be presented. */
export type PackageKind = 'api' | 'components' | 'guide';
/** Top-level grouping used for sidebar / landing organisation. */
export type PackageGroup = 'core' | 'vue' | 'configs' | 'infra';
export interface PackageMeta {
/** Package name from package.json, e.g. "@robonen/stdlib" */
name: string;
@@ -18,12 +28,28 @@ export interface PackageMeta {
description: string;
/** URL-friendly slug derived from package name, e.g. "stdlib" */
slug: string;
/** Presentation kind — drives which layout the page uses */
kind: PackageKind;
/** Sidebar / landing group */
group: PackageGroup;
/** Subpath export entries (e.g. "." or "./browsers") */
entryPoints: string[];
/** All documented items grouped by category */
// ── kind: 'api' ──────────────────────────────────────────────────────────
/** Documented API items grouped by category (kind === 'api') */
categories: CategoryMeta[];
// ── kind: 'components' ─────────────────────────────────────────────────────
/** Documented component groups (kind === 'components') */
components: ComponentMeta[];
// ── kind: 'guide' ──────────────────────────────────────────────────────────
/** Prose sections rendered from Markdown (kind === 'guide') */
sections: GuideSection[];
}
// ── API kind ─────────────────────────────────────────────────────────────────
export interface CategoryMeta {
/** Category name from @category JSDoc tag or directory name */
name: string;
@@ -72,6 +98,62 @@ export interface ItemMeta {
entryPoint: string;
}
// ── Components kind ────────────────────────────────────────────────────────────
export interface ComponentMeta {
/** Display name of the component group, e.g. "Accordion" */
name: string;
/** URL-friendly slug, e.g. "accordion" */
slug: string;
/** Short description (from README heading or first JSDoc) */
description: string;
/** Subpath export, e.g. "./accordion" */
entryPoint: string;
/** Ordered parts that compose the anatomy (Root, Item, Trigger, …) */
parts: ComponentPartMeta[];
/** Whether a demo.vue exists for the group */
hasDemo: boolean;
/** Raw demo source */
demoSource: string;
/** Relative path to the component directory from repo root */
sourcePath: string;
}
export interface ComponentPartMeta {
/** Component name, e.g. "AccordionRoot" */
name: string;
/** Short role label derived from the suffix (Root, Item, Trigger…) */
role: string;
/** Description from the Props interface JSDoc */
description: string;
/** Props parsed from the `XxxProps` interface */
props: PropertyMeta[];
/** Emitted events parsed from `defineEmits` */
emits: EmitMeta[];
}
export interface EmitMeta {
/** Event name, e.g. "update:modelValue" */
name: string;
/** Payload signature, e.g. "[value: string]" */
payload: string;
/** Description, if documented */
description: string;
}
// ── Guide kind ─────────────────────────────────────────────────────────────────
export interface GuideSection {
/** Heading-derived title, e.g. "imports preset" */
title: string;
/** URL-friendly slug, e.g. "imports" */
slug: string;
/** Raw Markdown content (rendered client-side) */
markdown: string;
}
// ── Shared leaf types ──────────────────────────────────────────────────────────
export interface ParamMeta {
name: string;
type: string;
+12 -1
View File
@@ -38,14 +38,25 @@ export default defineNuxtConfig({
},
app: {
pageTransition: { name: 'page', mode: 'out-in' },
head: {
title: '@robonen/tools — Documentation',
meta: [
{ name: 'description', content: 'Auto-generated documentation for @robonen/tools monorepo' },
{ name: 'description', content: 'Auto-generated documentation for the @robonen/tools monorepo' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ name: 'theme-color', content: '#ffffff', media: '(prefers-color-scheme: light)' },
{ name: 'theme-color', content: '#0a0a0a', media: '(prefers-color-scheme: dark)' },
],
htmlAttrs: {
lang: 'en',
},
script: [
{
// Set the theme class before first paint to avoid a flash.
innerHTML: `(function(){try{var t=localStorage.getItem('docs-theme');var d=t==='dark'||((!t||t==='system')&&matchMedia('(prefers-color-scheme: dark)').matches);document.documentElement.classList.toggle('dark',d);}catch(e){}})();`,
tagPosition: 'head',
},
],
},
},
-4
View File
@@ -1,4 +0,0 @@
import { defineConfig } from 'oxlint';
import { compose, base, imports, stylistic, typescript, vue } from '@robonen/oxlint';
export default defineConfig(compose(base, typescript, imports, vue, stylistic));
+5 -5
View File
@@ -6,8 +6,8 @@
"description": "Auto-generated documentation site for @robonen/tools",
"type": "module",
"scripts": {
"lint:check": "oxlint -c oxlint.config.ts",
"lint:fix": "oxlint -c oxlint.config.ts --fix",
"lint:check": "eslint .",
"lint:fix": "eslint . --fix",
"dev": "nuxt dev",
"build": "nuxt build",
"generate": "nuxt generate",
@@ -15,17 +15,17 @@
"extract": "jiti ./modules/extractor/extract.ts"
},
"dependencies": {
"marked": "^18.0.5",
"shiki": "^4.0.1"
},
"devDependencies": {
"@nuxt/fonts": "^0.14.0",
"@nuxt/kit": "^4.3.1",
"@robonen/oxlint": "workspace:*",
"@stylistic/eslint-plugin": "catalog:",
"@robonen/eslint": "workspace:*",
"@tailwindcss/vite": "^4.2.1",
"eslint": "catalog:",
"jiti": "^2.6.1",
"nuxt": "catalog:",
"oxlint": "catalog:",
"tailwindcss": "^4.2.1",
"ts-morph": "^27.0.2",
"vue": "catalog:",
+1
View File
@@ -0,0 +1 @@
{"root":["./.nuxt/nuxt.d.ts","./app/app.vue","./app/components/docsbadge.vue","./app/components/docscode.vue","./app/components/docscomponentanatomy.vue","./app/components/docsdemo.vue","./app/components/docsemitstable.vue","./app/components/docsmarkdown.vue","./app/components/docsmethodslist.vue","./app/components/docsparamstable.vue","./app/components/docspropstable.vue","./app/components/docssearch.vue","./app/components/docstag.vue","./app/components/docsthemetoggle.vue","./app/components/docstoc.vue","./app/composables/usedocs.ts","./app/composables/usemarkdown.ts","./app/composables/useshiki.ts","./app/composables/usetheme.ts","./app/layouts/default.vue","./app/pages/index.vue","./app/pages/[package]/[utility].vue","./app/pages/[package]/index.vue","./.nuxt/nuxt.node.d.ts","./nuxt.config.ts"],"errors":true,"version":"5.9.3"}