1
0
mirror of https://github.com/robonen/tools.git synced 2026-03-20 02:44:45 +00:00

feat(docs): add document generator

This commit is contained in:
2026-02-15 16:49:37 +07:00
parent a83e2bb797
commit abd6605db3
38 changed files with 9547 additions and 86 deletions

4
docs/.gitignore vendored Normal file
View File

@@ -0,0 +1,4 @@
.nuxt/
.output/
node_modules/
dist/

5
docs/app/app.vue Normal file
View File

@@ -0,0 +1,5 @@
<template>
<NuxtLayout>
<NuxtPage />
</NuxtLayout>
</template>

View File

@@ -0,0 +1,69 @@
@import "tailwindcss";
@source "../../../../web/vue/src/**/demo.vue";
@source "../../../../core/stdlib/src/**/demo.vue";
@source "../../../../core/platform/src/**/demo.vue";
@theme {
--font-sans: 'Inter', system-ui, sans-serif;
--font-mono: 'JetBrains Mono', 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;
}
: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);
}
@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);
}
}
body {
background-color: var(--color-bg);
color: var(--color-text);
font-family: var(--font-sans);
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code, pre {
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;
}
}

View File

@@ -0,0 +1,37 @@
<script setup lang="ts">
defineProps<{
kind: string;
size?: 'sm' | 'md';
}>();
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',
};
const kindLabels: Record<string, string> = {
function: 'fn',
class: 'C',
interface: 'I',
type: 'T',
enum: 'E',
variable: 'V',
};
</script>
<template>
<span
:class="[
'inline-flex items-center justify-center rounded font-mono font-medium shrink-0',
kindColors[kind] ?? kindColors.variable,
size === 'sm' ? 'w-5 h-5 text-[10px]' : 'w-6 h-6 text-xs',
]"
:title="kind"
>
{{ kindLabels[kind] ?? '?' }}
</span>
</template>

View File

@@ -0,0 +1,28 @@
<script setup lang="ts">
const props = defineProps<{
code: string;
lang?: string;
}>();
const { highlight } = useShiki();
const html = ref('');
onMounted(async () => {
html.value = await highlight(props.code, props.lang ?? 'typescript');
});
watch(() => props.code, async (newCode) => {
html.value = await highlight(newCode, props.lang ?? 'typescript');
});
</script>
<template>
<div class="code-block relative group rounded-lg border border-(--color-border) overflow-hidden max-w-full">
<div
v-if="html"
class="overflow-x-auto text-sm leading-relaxed [&_pre]:p-4 [&_pre]:m-0 [&_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>
</div>
</template>

View File

@@ -0,0 +1,71 @@
<script setup lang="ts">
import type { Component } from 'vue';
const props = defineProps<{
component: Component;
source: string;
}>();
const showSource = ref(false);
const { highlighted, highlightReactive } = useShiki();
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">
<!-- Live demo -->
<div class="p-6 bg-(--color-bg-soft)">
<component :is="component" />
</div>
<!-- Source toggle bar -->
<div class="flex items-center border-t border-(--color-border) bg-(--color-bg)">
<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"
@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>
{{ 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' : ''"
>
<polyline points="6 9 12 15 18 9" />
</svg>
</button>
</div>
<!-- Source code -->
<div v-if="showSource" class="border-t border-(--color-border)">
<div class="overflow-x-auto text-sm" v-html="highlighted" />
</div>
</div>
</template>

View File

@@ -0,0 +1,46 @@
<script setup lang="ts">
import type { MethodMeta } from '../../modules/extractor/types';
defineProps<{
methods: MethodMeta[];
}>();
</script>
<template>
<div v-if="methods.length > 0" class="space-y-4">
<div
v-for="method in methods"
:key="method.name"
class="border border-(--color-border) rounded-lg 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>
<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)"
>
{{ method.visibility }}
</span>
</div>
<p v-if="method.description" class="text-sm text-(--color-text-soft) mb-3">
{{ method.description }}
</p>
<DocsCode
v-for="(sig, i) in method.signatures"
:key="i"
:code="sig"
class="mb-3"
/>
<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>
</div>
</div>
</div>
</template>

View File

@@ -0,0 +1,44 @@
<script setup lang="ts">
import type { ParamMeta } from '../../modules/extractor/types';
defineProps<{
params: ParamMeta[];
}>();
</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">
<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>
</thead>
<tbody>
<tr
v-for="param in params"
:key="param.name"
class="border-b border-(--color-border) last:border-b-0"
>
<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>
<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>
<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>
<td class="py-2 text-(--color-text-soft)">
{{ param.description || '—' }}
</td>
</tr>
</tbody>
</table>
</div>
</template>

View File

@@ -0,0 +1,45 @@
<script setup lang="ts">
import type { PropertyMeta } from '../../modules/extractor/types';
defineProps<{
properties: PropertyMeta[];
}>();
</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">
<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>
</thead>
<tbody>
<tr
v-for="prop in properties"
:key="prop.name"
class="border-b border-(--color-border) last:border-b-0"
>
<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>
<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>
<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>
<td class="py-2 text-(--color-text-soft)">
{{ prop.description || '—' }}
</td>
</tr>
</tbody>
</table>
</div>
</template>

View File

@@ -0,0 +1,120 @@
<script setup lang="ts">
const { searchItems } = useDocs();
const isOpen = ref(false);
const query = ref('');
const results = computed(() => searchItems(query.value).slice(0, 20));
function open() {
isOpen.value = true;
nextTick(() => {
const input = document.querySelector<HTMLInputElement>('[data-search-input]');
input?.focus();
});
}
function close() {
isOpen.value = false;
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();
}
});
}
function useEventListener(target: Window, event: string, handler: (e: any) => void) {
onMounted(() => target.addEventListener(event, handler));
onUnmounted(() => target.removeEventListener(event, handler));
}
</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"
@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>
<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>
</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"
>
<div v-if="isOpen" class="fixed inset-0 z-50">
<div class="fixed inset-0 bg-black/50" @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" />
</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"
>
</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>
<ul v-else-if="results.length > 0" class="py-2">
<li v-for="{ pkg, item } in results" :key="`${pkg.slug}-${item.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"
@click="close"
>
<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>
</div>
</NuxtLink>
</li>
</ul>
<div v-else class="py-8 text-center text-sm text-(--color-text-mute)">
Type to search...
</div>
</div>
</div>
</div>
</div>
</Transition>
</Teleport>
</div>
</template>

View File

@@ -0,0 +1,24 @@
<script setup lang="ts">
defineProps<{
label: string;
variant?: 'since' | 'test' | 'demo' | 'wip';
}>();
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',
};
</script>
<template>
<span
:class="[
'inline-flex items-center px-2 py-0.5 text-xs font-medium rounded-full',
variantClasses[variant ?? 'since'],
]"
>
{{ label }}
</span>
</template>

View File

@@ -0,0 +1,64 @@
import metadata from '#docs/metadata';
import type { DocsMetadata, PackageMeta, CategoryMeta, ItemMeta } from '../../modules/extractor/types';
export function useDocs() {
const data = metadata as unknown as DocsMetadata;
function getPackages(): PackageMeta[] {
return data.packages;
}
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 {
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 };
}
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 }> = [];
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 });
}
}
}
}
return results;
}
function getTotalItems(): number {
return data.packages.reduce(
(sum, pkg) => sum + pkg.categories.reduce(
(catSum, cat) => catSum + cat.items.length, 0,
), 0,
);
}
return {
data,
getPackages,
getPackage,
getItem,
searchItems,
getTotalItems,
};
}

View File

@@ -0,0 +1,41 @@
import { createHighlighter, type Highlighter } from 'shiki';
let highlighterPromise: Promise<Highlighter> | null = null;
function getHighlighter(): Promise<Highlighter> {
if (!highlighterPromise) {
highlighterPromise = createHighlighter({
themes: ['github-light', 'github-dark'],
langs: ['typescript', 'vue', 'json', 'bash'],
});
}
return highlighterPromise;
}
export function useShiki() {
const highlighted = ref<string>('');
const isReady = ref(false);
async function highlight(code: string, lang: string = 'typescript'): Promise<string> {
const highlighter = await getHighlighter();
return highlighter.codeToHtml(code, {
lang,
themes: {
light: 'github-light',
dark: 'github-dark',
},
});
}
async function highlightReactive(code: string, lang: string = 'typescript'): Promise<void> {
highlighted.value = await highlight(code, lang);
isReady.value = true;
}
return {
highlight,
highlighted,
highlightReactive,
isReady,
};
}

View File

@@ -0,0 +1,105 @@
<script setup lang="ts">
const { getPackages } = useDocs();
const packages = getPackages();
const route = useRoute();
const isSidebarOpen = ref(false);
const currentPackageSlug = computed(() => {
const param = route.params.package;
return typeof param === 'string' ? param : undefined;
});
watch(() => route.path, () => {
isSidebarOpen.value = false;
});
</script>
<template>
<div class="min-h-screen flex flex-col">
<!-- 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>
</div>
</header>
<div class="mx-auto max-w-7xl w-full flex flex-1 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',
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>
</div>
</div>
</nav>
</aside>
<!-- Sidebar overlay -->
<div
v-if="isSidebarOpen"
class="fixed inset-0 z-30 bg-black/20 lg:hidden"
@click="isSidebarOpen = false"
/>
<!-- Main content -->
<main class="flex-1 min-w-0 overflow-hidden py-8 lg:pl-8">
<slot />
</main>
</div>
</div>
</template>

View File

@@ -0,0 +1,204 @@
<script setup lang="ts">
import { demos } from '#docs/demos';
const route = useRoute();
const { getItem } = 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));
if (!result.value) {
throw createError({
statusCode: 404,
message: `Item "${utilitySlug.value}" not found in package "${packageSlug.value}"`,
});
}
const { pkg, category, item } = result.value;
useHead({
title: `${item.name}${pkg.name} — @robonen/tools`,
meta: [
{ name: 'description', content: item.description },
],
});
const sourceUrl = computed(() => `https://github.com/robonen/tools/blob/main/${item.sourcePath}`);
const demoComponent = computed(() => {
const key = `${pkg.slug}/${item.slug}`;
return demos[key] ?? null;
});
</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>
<!-- 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>
</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>
</div>
</section>
</div>
</template>

View File

@@ -0,0 +1,74 @@
<script setup lang="ts">
const route = useRoute();
const { getPackage } = useDocs();
const slug = computed(() => route.params.package as string);
const pkg = computed(() => getPackage(slug.value));
if (!pkg.value) {
throw createError({ statusCode: 404, message: `Package "${slug.value}" not found` });
}
useHead({
title: `${pkg.value.name} — @robonen/tools`,
});
</script>
<template>
<div v-if="pkg" class="max-w-3xl min-w-0">
<!-- 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" />
</div>
<p class="text-(--color-text-soft)">
{{ pkg.description }}
</p>
</div>
<!-- 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" />
</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>
</div>
</template>

73
docs/app/pages/index.vue Normal file
View File

@@ -0,0 +1,73 @@
<script setup lang="ts">
const { getPackages, getTotalItems } = useDocs();
const packages = getPackages();
const totalItems = getTotalItems();
const packageIcons: Record<string, string> = {
stdlib: '📦',
platform: '🖥️',
vue: '💚',
oxlint: '🔍',
};
</script>
<template>
<div class="max-w-3xl min-w-0">
<!-- Hero -->
<div class="mb-12">
<h1 class="text-3xl font-bold tracking-tight text-(--color-text) mb-3">
@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>
<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>
</div>
<!-- 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
</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>
</div>
</div>
</template>

View File

@@ -0,0 +1,744 @@
/**
* 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.
*/
import { resolve, relative, dirname } from 'node:path';
import { existsSync, readFileSync } from 'node:fs';
import {
Project,
type SourceFile,
type FunctionDeclaration,
type ClassDeclaration,
type InterfaceDeclaration,
type TypeAliasDeclaration,
type JSDoc,
type JSDocTag,
type MethodDeclaration,
type PropertyDeclaration,
type PropertySignature,
SyntaxKind,
type Node,
} from 'ts-morph';
import type {
DocsMetadata,
PackageMeta,
CategoryMeta,
ItemMeta,
ParamMeta,
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: 'web/vue', slug: 'vue' },
{ path: 'configs/oxlint', slug: 'oxlint' },
];
interface PackageConfig {
path: string;
slug: string;
}
// ── Helpers ────────────────────────────────────────────────────────────────
function toKebabCase(str: string): string {
return str
.replace(/([a-z0-9])([A-Z])/g, '$1-$2')
.replace(/([A-Z])([A-Z][a-z])/g, '$1-$2')
.toLowerCase();
}
function slugify(name: string): string {
return toKebabCase(name);
}
function getJsDocTags(jsdocs: JSDoc[]): JSDocTag[] {
return jsdocs.flatMap(doc => doc.getTags());
}
function getTagValue(tags: JSDocTag[], tagName: string): string {
const tag = tags.find(t => t.getTagName() === tagName);
if (!tag) return '';
const comment = tag.getCommentText();
return comment?.trim() ?? '';
}
function getTagValues(tags: JSDocTag[], tagName: string): string[] {
return tags
.filter(t => t.getTagName() === tagName)
.map(t => {
const comment = t.getCommentText();
return comment?.trim() ?? '';
})
.filter(Boolean);
}
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;
}
return '';
}
function getExamples(tags: JSDocTag[]): string[] {
return tags
.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);
}
function extractParams(tags: JSDocTag[], node: FunctionDeclaration | MethodDeclaration): ParamMeta[] {
const params: ParamMeta[] = [];
const paramTags = tags.filter(t => t.getTagName() === 'param');
for (const param of node.getParameters()) {
const name = param.getName();
const type = param.getType().getText(param);
const optional = param.isOptional();
const defaultValue = param.getInitializer()?.getText() ?? null;
// Find matching @param tag
const paramTag = paramTags.find(t => {
const text = t.getCommentText() ?? '';
const tagText = t.getText();
return tagText.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*`), '')
.replace(new RegExp(`^${name}\\s+`), '')
.replace(/^[-–—]\s*/, '')
.trim();
}
params.push({ name, type, description, optional, defaultValue });
}
return params;
}
function extractTypeParams(node: FunctionDeclaration | ClassDeclaration | InterfaceDeclaration | TypeAliasDeclaration): TypeParamMeta[] {
const typeParams = node.getTypeParameters();
return typeParams.map(tp => ({
name: tp.getName(),
constraint: tp.getConstraint()?.getText() ?? null,
default: tp.getDefault()?.getText() ?? null,
description: '',
}));
}
function extractReturnMeta(tags: JSDocTag[], node: FunctionDeclaration | MethodDeclaration): ReturnMeta | null {
const returnType = node.getReturnType().getText(node);
if (returnType === 'void') return null;
const returnsTag = getTagValue(tags, 'returns') || getTagValue(tags, 'return');
const description = returnsTag.replace(/^\{[^}]*\}\s*/, '').trim();
return { type: returnType, description };
}
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,
description: getDescription(jsdocs, tags),
signatures: [signature],
params: extractParams(tags, method),
returns: extractReturnMeta(tags, method),
visibility,
};
}
function extractPropertyMeta(prop: PropertyDeclaration | PropertySignature): PropertyMeta {
const jsdocs = prop.getJsDocs();
const tags = getJsDocTags(jsdocs);
return {
name: prop.getName(),
type: prop.getType().getText(prop),
description: getDescription(jsdocs, tags),
optional: prop.hasQuestionToken?.() ?? false,
defaultValue: getTagValue(tags, 'default') || null,
readonly: prop.isReadonly?.() ?? false,
};
}
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'));
}
function readDemoSource(sourceFilePath: string): string {
const dir = getSourceDir(sourceFilePath);
const demoPath = resolve(dir, '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'));
}
function inferCategory(sourceFilePath: string, tags: JSDocTag[]): string {
// Try @category tag first
const categoryTag = getTagValue(tags, 'category');
if (categoryTag) return categoryTag;
// Infer from directory structure
const parts = sourceFilePath.split('/src/');
if (parts[1]) {
const segments = parts[1].split('/');
// For patterns like: composables/browser/useIntervalFn/index.ts → "Browser"
// For patterns like: arrays/cluster/index.ts → "Arrays"
if (segments.length >= 2) {
const category = segments.length >= 3 ? segments[1] : segments[0];
if (category) {
return category.charAt(0).toUpperCase() + category.slice(1);
}
}
}
return 'General';
}
// ── 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;
const jsdocs = fn.getJsDocs();
const tags = getJsDocTags(jsdocs);
const description = getDescription(jsdocs, tags);
const category = inferCategory(sourceFilePath, tags);
// Get signature text without body
const signatureText = fn.getOverloads().length > 0
? fn.getOverloads().map(o => o.getText().trim())
: [fn.getText().split('{')[0]?.trim() + '{ ... }'];
return {
name,
slug: slugify(name),
kind: 'function',
description,
since: getTagValue(tags, 'since'),
signatures: signatureText,
params: extractParams(tags, fn),
returns: extractReturnMeta(tags, fn),
typeParams: extractTypeParams(fn),
examples: getExamples(tags),
methods: [],
properties: [],
hasDemo: hasDemoFile(sourceFilePath),
demoSource: readDemoSource(sourceFilePath),
hasTests: hasTestFile(sourceFilePath),
relatedTypes: [],
sourcePath: relative(ROOT, sourceFilePath),
entryPoint,
};
}
function extractClass(cls: ClassDeclaration, sourceFilePath: string, entryPoint: string): ItemMeta | null {
const name = cls.getName();
if (!name) return null;
const jsdocs = cls.getJsDocs();
const tags = getJsDocTags(jsdocs);
const methods = cls.getMethods()
.filter(m => (m.getScope() ?? 'public') === 'public')
.filter(m => !m.getName().startsWith('_'))
.map(extractMethodMeta);
const properties = cls.getProperties()
.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 => ({
name: g.getName(),
type: g.getReturnType().getText(g),
description: getDescription(g.getJsDocs(), getJsDocTags(g.getJsDocs())),
optional: false,
defaultValue: null,
readonly: true,
}));
// Build class signature
const typeParams = cls.getTypeParameters();
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(', ')}`
: '';
const signature = `class ${name}${typeParamStr}${extendsClause}${implementsClause}`;
return {
name,
slug: slugify(name),
kind: 'class',
description: getDescription(jsdocs, tags),
since: getTagValue(tags, 'since'),
signatures: [signature],
params: [],
returns: null,
typeParams: extractTypeParams(cls),
examples: getExamples(tags),
methods,
properties: [...properties, ...getters],
hasDemo: hasDemoFile(sourceFilePath),
demoSource: readDemoSource(sourceFilePath),
hasTests: hasTestFile(sourceFilePath),
relatedTypes: [],
sourcePath: relative(ROOT, sourceFilePath),
entryPoint,
};
}
function extractInterface(iface: InterfaceDeclaration, sourceFilePath: string, entryPoint: string): ItemMeta | null {
const name = iface.getName();
if (!name) return null;
const jsdocs = iface.getJsDocs();
const tags = getJsDocTags(jsdocs);
const properties = iface.getProperties().map(p => extractPropertyMeta(p));
const typeParams = iface.getTypeParameters();
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 signature = `interface ${name}${typeParamStr}${extendsStr}`;
return {
name,
slug: slugify(name),
kind: 'interface',
description: getDescription(jsdocs, tags),
since: getTagValue(tags, 'since'),
signatures: [signature],
params: [],
returns: null,
typeParams: extractTypeParams(iface),
examples: getExamples(tags),
methods: [],
properties,
hasDemo: hasDemoFile(sourceFilePath),
demoSource: readDemoSource(sourceFilePath),
hasTests: hasTestFile(sourceFilePath),
relatedTypes: [],
sourcePath: relative(ROOT, sourceFilePath),
entryPoint,
};
}
function extractTypeAlias(typeAlias: TypeAliasDeclaration, sourceFilePath: string, entryPoint: string): ItemMeta | null {
const name = typeAlias.getName();
if (!name) return null;
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],
params: [],
returns: null,
typeParams: extractTypeParams(typeAlias),
examples: getExamples(tags),
methods: [],
properties: [],
hasDemo: hasDemoFile(sourceFilePath),
demoSource: readDemoSource(sourceFilePath),
hasTests: hasTestFile(sourceFilePath),
relatedTypes: [],
sourcePath: relative(ROOT, sourceFilePath),
entryPoint,
};
}
// ── Source Tree Walking ────────────────────────────────────────────────────
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 = {
name,
slug: slugify(name),
kind: 'function',
description: getDescription(jsdocs, tags),
since: getTagValue(tags, 'since'),
signatures: overloads.map(o => o.getText().trim()),
params: extractParams(tags, fn),
returns: extractReturnMeta(tags, fn),
typeParams: extractTypeParams(fn),
examples: getExamples(tags),
methods: [],
properties: [],
hasDemo: hasDemoFile(filePath),
demoSource: readDemoSource(filePath),
hasTests: hasTestFile(filePath),
relatedTypes: [],
sourcePath: relative(ROOT, filePath),
entryPoint,
};
items.push(item);
} else {
const item = extractFunction(fn, filePath, entryPoint);
if (item) items.push(item);
}
}
for (const cls of sourceFile.getClasses()) {
if (!cls.isExported()) continue;
const item = extractClass(cls, filePath, entryPoint);
if (item) items.push(item);
}
for (const iface of sourceFile.getInterfaces()) {
if (!iface.isExported()) continue;
// Skip internal interfaces (e.g. Options, Return types that are documented inline)
const name = iface.getName();
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);
}
for (const typeAlias of sourceFile.getTypeAliases()) {
if (!typeAlias.isExported()) continue;
const jsdocs = typeAlias.getJsDocs();
const tags = getJsDocTags(jsdocs);
const hasCategory = getTagValue(tags, 'category') !== '';
if (!hasCategory && jsdocs.length === 0) continue;
const item = extractTypeAlias(typeAlias, filePath, entryPoint);
if (item) items.push(item);
}
// Follow barrel re-exports: export * from './...'
for (const exportDecl of sourceFile.getExportDeclarations()) {
const moduleSpecifier = exportDecl.getModuleSpecifierValue();
if (!moduleSpecifier) continue;
const referencedFile = exportDecl.getModuleSpecifierSourceFile();
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.
*/
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');
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);
}
}
// 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;
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}`);
}
}
// Return items without the absorbed types
return items.filter(item => !absorbed.has(`${item.entryPoint}:${item.name}`));
}
// ── Package Extraction ─────────────────────────────────────────────────────
function extractPackage(config: PackageConfig): PackageMeta | null {
const pkgDir = resolve(ROOT, config.path);
const pkgJsonPath = resolve(pkgDir, 'package.json');
if (!existsSync(pkgJsonPath)) {
console.warn(`[extractor] package.json not found: ${pkgJsonPath}`);
return 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 {
name: pkgJson.name,
version: pkgJson.version,
description: pkgJson.description ?? '',
slug: config.slug,
entryPoints: entryPoints.map(ep => ep.subpath),
categories,
};
}
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 (segments[0] && segments.length >= 2) {
const cat = segments[0];
return cat.charAt(0).toUpperCase() + cat.slice(1);
}
return 'General';
}
// ── Main ───────────────────────────────────────────────────────────────────
export function extract(): DocsMetadata {
console.log('[extractor] Starting metadata extraction...');
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);
}
}
const metadata: DocsMetadata = {
packages,
generatedAt: new Date().toISOString(),
};
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;
}
// 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));
}

View File

@@ -0,0 +1,146 @@
/**
* Nuxt module that extracts TypeScript metadata from source packages
* and provides it as a virtual module `#docs/metadata`.
*
* Runs extraction at build start and makes the data available to all
* pages/components via `import metadata from '#docs/metadata'`.
*/
import { defineNuxtModule, addTemplate, createResolver } from '@nuxt/kit';
import { resolve, dirname } from 'node:path';
import type { DocsMetadata } from './types';
export default defineNuxtModule({
meta: {
name: 'docs-extractor',
configKey: 'docsExtractor',
},
async setup(_options, nuxt) {
const { resolve: resolveModule } = createResolver(import.meta.url);
const ROOT = resolve(import.meta.dirname, '..', '..', '..');
// Run extraction immediately during setup so metadata is available
// when templates are resolved (app:templates phase runs before build:before)
console.log('[docs-extractor] Running metadata extraction...');
const { extract } = await import('./extract');
const metadata: DocsMetadata = extract();
// Add Vite resolve aliases for source packages so demo.vue imports resolve.
// The web/vue package uses `@/` path aliases (e.g. `@/composables/...`).
// We prepend them via vite:extendConfig so they take priority over Nuxt's
// built-in `@` → srcDir alias.
const vueSrc = resolve(ROOT, 'web/vue/src');
nuxt.hook('vite:extendConfig', (config) => {
const existing = config.resolve?.alias;
const sourceAliases = [
{ find: '@/composables', replacement: resolve(vueSrc, 'composables') },
{ find: '@/types', replacement: resolve(vueSrc, 'types') },
{ find: '@/utils', replacement: resolve(vueSrc, 'utils') },
];
if (Array.isArray(existing)) {
existing.unshift(...sourceAliases);
} else {
config.resolve ??= {};
config.resolve.alias = [
...sourceAliases,
...Object.entries(existing ?? {}).map(([find, replacement]) => ({ find, replacement: replacement as string })),
];
}
});
// Provide metadata as a virtual template
addTemplate({
filename: 'docs-metadata.ts',
write: true,
getContents: () => {
const json = JSON.stringify(metadata, null, 2);
return `export default ${json} as const;`;
},
});
// Register the alias for the virtual module
nuxt.options.alias['#docs/metadata'] = resolve(nuxt.options.buildDir, 'docs-metadata');
// Add types reference
addTemplate({
filename: 'docs-metadata-types.d.ts',
write: true,
getContents: () => {
const typesPath = resolveModule('./types');
return `
import type { DocsMetadata } from '${typesPath}';
declare module '#docs/metadata' {
const metadata: DocsMetadata;
export default metadata;
}
`;
},
});
// Register prerender routes from metadata
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}`);
}
}
}
console.log(`[docs-extractor] Registered ${routes.size} routes for prerender`);
});
// Generate demo component import map
addTemplate({
filename: 'docs-demos.ts',
write: true,
getContents: () => {
const entries: string[] = [];
for (const pkg of metadata.packages) {
for (const cat of pkg.categories) {
for (const item of cat.items) {
if (item.hasDemo) {
const demoPath = resolve(ROOT, dirname(item.sourcePath), 'demo.vue');
entries.push(` '${pkg.slug}/${item.slug}': defineAsyncComponent(() => import('${demoPath}')),`);
}
}
}
}
if (entries.length === 0) {
return `import type { Component } from 'vue';\nexport const demos: Record<string, Component> = {};\n`;
}
return [
`import { defineAsyncComponent } from 'vue';`,
`import type { Component } from 'vue';`,
``,
`export const demos: Record<string, Component> = {`,
...entries,
`};`,
``,
].join('\n');
},
});
nuxt.options.alias['#docs/demos'] = resolve(nuxt.options.buildDir, 'docs-demos');
addTemplate({
filename: 'docs-demos-types.d.ts',
write: true,
getContents: () => `
import type { Component } from 'vue';
declare module '#docs/demos' {
export const demos: Record<string, Component>;
}
`,
});
},
});

View File

@@ -0,0 +1,112 @@
/**
* Metadata types for the documentation extractor.
* These types represent the structured data extracted from source packages
* via ts-morph, used to generate documentation pages.
*/
export interface DocsMetadata {
packages: PackageMeta[];
generatedAt: string;
}
export interface PackageMeta {
/** Package name from package.json, e.g. "@robonen/stdlib" */
name: string;
/** Package version */
version: string;
/** Package description from package.json */
description: string;
/** URL-friendly slug derived from package name, e.g. "stdlib" */
slug: string;
/** Subpath export entries (e.g. "." or "./browsers") */
entryPoints: string[];
/** All documented items grouped by category */
categories: CategoryMeta[];
}
export interface CategoryMeta {
/** Category name from @category JSDoc tag or directory name */
name: string;
/** URL-friendly slug */
slug: string;
/** Items in this category */
items: ItemMeta[];
}
export interface ItemMeta {
/** Export name */
name: string;
/** URL-friendly slug (camelCase → kebab-case) */
slug: string;
/** Kind of export */
kind: 'function' | 'class' | 'type' | 'interface' | 'enum' | 'variable';
/** Description from @description tag or first JSDoc line */
description: string;
/** Version when this item was introduced */
since: string;
/** Full TypeScript signature(s) — supports overloads */
signatures: string[];
/** Function/method parameters */
params: ParamMeta[];
/** Return type description */
returns: ReturnMeta | null;
/** Template/generic type parameters */
typeParams: TypeParamMeta[];
/** Code examples from @example tags */
examples: string[];
/** Class methods (only for kind === 'class') */
methods: MethodMeta[];
/** Class/interface properties (only for kind === 'class' or 'interface') */
properties: PropertyMeta[];
/** Whether a demo.vue file exists alongside */
hasDemo: boolean;
/** Raw source code of the demo.vue file (for syntax-highlighted display) */
demoSource: string;
/** Whether an index.test.ts file exists alongside */
hasTests: boolean;
/** Related types/interfaces co-located in the same module directory */
relatedTypes: ItemMeta[];
/** Relative path to the source file from repo root */
sourcePath: string;
/** Subpath export this belongs to (e.g. "." or "./browsers") */
entryPoint: string;
}
export interface ParamMeta {
name: string;
type: string;
description: string;
optional: boolean;
defaultValue: string | null;
}
export interface ReturnMeta {
type: string;
description: string;
}
export interface TypeParamMeta {
name: string;
constraint: string | null;
default: string | null;
description: string;
}
export interface MethodMeta {
name: string;
description: string;
signatures: string[];
params: ParamMeta[];
returns: ReturnMeta | null;
/** Visibility: public, protected, private */
visibility: string;
}
export interface PropertyMeta {
name: string;
type: string;
description: string;
optional: boolean;
defaultValue: string | null;
readonly: boolean;
}

53
docs/nuxt.config.ts Normal file
View File

@@ -0,0 +1,53 @@
import tailwindcss from '@tailwindcss/vite';
export default defineNuxtConfig({
future: {
compatibilityVersion: 4,
},
modules: [
'@nuxt/fonts',
'./modules/extractor',
],
vite: {
plugins: [
tailwindcss() as any,
],
},
css: ['~/assets/css/main.css'],
ssr: true,
routeRules: {
'/**': { prerender: true },
},
nitro: {
prerender: {
crawlLinks: true,
},
},
fonts: {
families: [
{ name: 'Inter', provider: 'google', weights: [400, 500, 600, 700] },
{ name: 'JetBrains Mono', provider: 'google', weights: [400, 500] },
],
},
app: {
head: {
title: '@robonen/tools — Documentation',
meta: [
{ name: 'description', content: 'Auto-generated documentation for @robonen/tools monorepo' },
],
htmlAttrs: {
lang: 'en',
},
},
},
compatibilityDate: '2026-02-15',
});

29
docs/package.json Normal file
View File

@@ -0,0 +1,29 @@
{
"name": "@robonen/docs",
"version": "0.0.1",
"private": true,
"license": "Apache-2.0",
"description": "Auto-generated documentation site for @robonen/tools",
"type": "module",
"scripts": {
"dev": "nuxt dev",
"build": "nuxt build",
"generate": "nuxt generate",
"preview": "nuxt preview",
"extract": "jiti ./modules/extractor/extract.ts"
},
"dependencies": {
"shiki": "^3.4.2"
},
"devDependencies": {
"@nuxt/fonts": "^0.11.4",
"@nuxt/kit": "^4.3.1",
"@tailwindcss/vite": "^4.1.0",
"jiti": "^2.6.1",
"nuxt": "catalog:",
"tailwindcss": "^4.1.0",
"ts-morph": "^25.0.0",
"vue": "catalog:",
"vue-router": "^4.5.1"
}
}

3
docs/tsconfig.json Normal file
View File

@@ -0,0 +1,3 @@
{
"extends": "./.nuxt/tsconfig.json"
}

View File

@@ -35,6 +35,10 @@
"lint": "pnpm -r lint",
"test": "vitest run",
"test:ui": "vitest --ui",
"create": "jiti ./bin/cli.ts"
"create": "jiti ./bin/cli.ts",
"docs:dev": "pnpm -C docs dev",
"docs:generate": "pnpm -C docs generate",
"docs:preview": "pnpm -C docs preview",
"docs:extract": "pnpm -C docs extract"
}
}

6063
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@@ -7,11 +7,15 @@ packages:
catalog:
'@vitest/coverage-v8': ^4.0.18
'@vitest/ui': ^4.0.18
'@vue/test-utils': ^2.4.6
jsdom: ^28.0.0
nuxt: ^4.3.1
oxlint: ^1.2.0
tsdown: ^0.12.5
vitest: ^4.0.18
'@vitest/ui': ^4.0.18
vue: ^3.5.28
nuxt: ^4.3.1
ignoredBuiltDependencies:
- '@parcel/watcher'
- esbuild

View File

@@ -1,4 +1,7 @@
export * from './useEventListener';
export * from './useFocusGuard';
export * from './useFps';
export * from './useIntervalFn';
export * from './useRafFn';
export * from './useSupported';
export * from './useTabLeader';

View File

@@ -0,0 +1,47 @@
<script setup lang="ts">
import { useFps } from './index';
const { fps, min, max, isActive, reset, toggle } = useFps({ every: 10 });
</script>
<template>
<div class="space-y-4">
<div class="flex items-end gap-8">
<div>
<div class="text-4xl font-mono font-bold tabular-nums text-(--color-text)">{{ fps }}</div>
<div class="text-xs text-(--color-text-mute) mt-1">FPS</div>
</div>
<div>
<div class="text-xl font-mono tabular-nums text-(--color-text-soft)">{{ min === Infinity ? '—' : min }}</div>
<div class="text-xs text-(--color-text-mute) mt-1">Min</div>
</div>
<div>
<div class="text-xl font-mono tabular-nums text-(--color-text-soft)">{{ max || '—' }}</div>
<div class="text-xs text-(--color-text-mute) mt-1">Max</div>
</div>
</div>
<div class="h-2 rounded-full border border-(--color-border) overflow-hidden">
<div
class="h-full rounded-full transition-all duration-300"
:class="fps >= 50 ? 'bg-emerald-500' : fps >= 30 ? 'bg-amber-500' : 'bg-red-500'"
:style="{ width: `${Math.min(fps / 60 * 100, 100)}%` }"
/>
</div>
<div class="flex items-center gap-2">
<button
class="px-3 py-1.5 text-sm rounded-md border border-(--color-border) bg-(--color-bg) hover:bg-(--color-bg-mute) text-(--color-text-soft) transition-colors cursor-pointer"
@click="toggle"
>
{{ isActive ? 'Pause' : 'Resume' }}
</button>
<button
class="px-3 py-1.5 text-sm rounded-md border border-(--color-border) bg-(--color-bg) hover:bg-(--color-bg-mute) text-(--color-text-soft) transition-colors cursor-pointer"
@click="reset"
>
Reset
</button>
</div>
</div>
</template>

View File

@@ -0,0 +1,244 @@
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest';
import { effectScope } from 'vue';
import { useFps } from '.';
let rafCallbacks: Array<(time: number) => void> = [];
let rafIdCounter = 0;
beforeEach(() => {
rafCallbacks = [];
rafIdCounter = 0;
vi.stubGlobal('requestAnimationFrame', (cb: (time: number) => void) => {
const id = ++rafIdCounter;
rafCallbacks.push(cb);
return id;
});
vi.stubGlobal('cancelAnimationFrame', vi.fn());
});
afterEach(() => {
vi.unstubAllGlobals();
});
function triggerFrame(time: number) {
const cbs = [...rafCallbacks];
rafCallbacks = [];
cbs.forEach(cb => cb(time));
}
function triggerFrames(startTime: number, interval: number, count: number) {
for (let i = 0; i < count; i++) {
triggerFrame(startTime + i * interval);
}
}
describe(useFps, () => {
it('starts at 0 fps', () => {
const scope = effectScope();
let result: ReturnType<typeof useFps>;
scope.run(() => {
result = useFps();
});
expect(result!.fps.value).toBe(0);
scope.stop();
});
it('reports fps after "every" frames', () => {
const scope = effectScope();
let result: ReturnType<typeof useFps>;
scope.run(() => {
result = useFps({ every: 5 });
});
// ~60fps = 16.67ms per frame
// First frame has delta=0, skipped by useFps. Need 5 real-delta frames.
triggerFrame(100); // delta=0, skipped
triggerFrame(116.67); // delta=16.67
triggerFrame(133.33); // delta=16.66
triggerFrame(150); // delta=16.67
triggerFrame(166.67); // delta=16.67
triggerFrame(183.33); // delta=16.66 → 5 deltas collected, update
expect(result!.fps.value).toBe(60);
scope.stop();
});
it('does not update fps before collecting enough frames', () => {
const scope = effectScope();
let result: ReturnType<typeof useFps>;
scope.run(() => {
result = useFps({ every: 10 });
});
triggerFrame(100);
triggerFrame(116.67);
triggerFrame(133.33);
expect(result!.fps.value).toBe(0);
scope.stop();
});
it('tracks min and max fps', () => {
const scope = effectScope();
let result: ReturnType<typeof useFps>;
scope.run(() => {
result = useFps({ every: 3 });
});
// First batch: ~60fps (16.67ms intervals)
triggerFrame(100); // delta=0, skipped
triggerFrame(116.67); // delta=16.67
triggerFrame(133.33); // delta=16.66
triggerFrame(150); // delta=16.67 → 3 deltas, update
const firstFps = result!.fps.value;
expect(firstFps).toBe(60);
// Second batch: ~30fps (33.33ms intervals)
triggerFrame(183.33); // delta=33.33
triggerFrame(216.67); // delta=33.34
triggerFrame(250); // delta=33.33 → 3 deltas, update
const secondFps = result!.fps.value;
expect(secondFps).toBe(30);
expect(result!.max.value).toBe(60);
expect(result!.min.value).toBe(30);
scope.stop();
});
it('resets min, max, and fps', () => {
const scope = effectScope();
let result: ReturnType<typeof useFps>;
scope.run(() => {
result = useFps({ every: 3 });
});
triggerFrame(100);
triggerFrame(116.67);
triggerFrame(133.33);
triggerFrame(150);
expect(result!.fps.value).toBe(60);
result!.reset();
expect(result!.fps.value).toBe(0);
expect(result!.min.value).toBe(Infinity);
expect(result!.max.value).toBe(0);
scope.stop();
});
it('cleans up on scope dispose', () => {
const scope = effectScope();
scope.run(() => {
useFps();
});
// Should not throw on stop
scope.stop();
// No more raf callbacks should be registered after stop
triggerFrame(100);
expect(rafCallbacks).toHaveLength(0);
});
it('does nothing when window is undefined (SSR)', () => {
const scope = effectScope();
let result: ReturnType<typeof useFps>;
scope.run(() => {
result = useFps({ window: undefined as any });
});
expect(result!.fps.value).toBe(0);
scope.stop();
});
it('is active by default', () => {
const scope = effectScope();
let result: ReturnType<typeof useFps>;
scope.run(() => {
result = useFps();
});
expect(result!.isActive.value).toBeTruthy();
scope.stop();
});
it('does not start when immediate is false', () => {
const scope = effectScope();
let result: ReturnType<typeof useFps>;
scope.run(() => {
result = useFps({ immediate: false });
});
expect(result!.isActive.value).toBeFalsy();
scope.stop();
});
it('pauses and resumes fps tracking', () => {
const scope = effectScope();
let result: ReturnType<typeof useFps>;
scope.run(() => {
result = useFps({ every: 3 });
});
// Collect one batch
triggerFrame(100);
triggerFrame(116.67);
triggerFrame(133.33);
triggerFrame(150);
expect(result!.fps.value).toBe(60);
result!.pause();
expect(result!.isActive.value).toBeFalsy();
// Frames while paused should not update
triggerFrame(200);
triggerFrame(300);
triggerFrame(400);
triggerFrame(500);
expect(result!.fps.value).toBe(60);
result!.resume();
expect(result!.isActive.value).toBeTruthy();
scope.stop();
});
it('toggles fps tracking', () => {
const scope = effectScope();
let result: ReturnType<typeof useFps>;
scope.run(() => {
result = useFps();
});
expect(result!.isActive.value).toBeTruthy();
result!.toggle();
expect(result!.isActive.value).toBeFalsy();
result!.toggle();
expect(result!.isActive.value).toBeTruthy();
scope.stop();
});
});

View File

@@ -0,0 +1,109 @@
import { ref } from 'vue';
import type { Ref } from 'vue';
import type { ConfigurableWindow, ResumableActions, ResumableOptions } from '@/types';
import { useRafFn } from '@/composables/browser/useRafFn';
import type { UseRafFnCallbackArgs } from '@/composables/browser/useRafFn';
export interface UseFpsOptions extends ResumableOptions, ConfigurableWindow {
/**
* Number of frames to average over for a smoother reading.
*
* @default 10
*/
every?: number;
}
export interface UseFpsReturn extends ResumableActions {
/**
* Current frames per second (averaged over the last `every` frames)
*/
fps: Readonly<Ref<number>>;
/**
* Minimum FPS recorded since the composable was created or last reset
*/
min: Readonly<Ref<number>>;
/**
* Maximum FPS recorded since the composable was created or last reset
*/
max: Readonly<Ref<number>>;
/**
* Whether the FPS counter is currently active
*/
isActive: Readonly<Ref<boolean>>;
/**
* Reset min/max tracking
*/
reset: () => void;
}
/**
* Reactive FPS counter based on `requestAnimationFrame`.
* Reports a smoothed FPS value averaged over a configurable number of frames,
* and tracks min/max values.
*
* @param options - Configuration options
*
* @example
* ```ts
* const { fps, min, max, reset } = useFps();
* ```
*/
export function useFps(options: UseFpsOptions = {}): UseFpsReturn {
const { every = 10, ...rafOptions } = options;
const fps = ref(0);
const min = ref(Infinity);
const max = ref(0);
let deltaSum = 0;
let frameCount = 0;
function update({ delta }: UseRafFnCallbackArgs) {
if (!delta)
return;
deltaSum += delta;
frameCount++;
if (frameCount < every)
return;
const currentFps = Math.round(1000 / (deltaSum / frameCount));
fps.value = currentFps;
if (currentFps < min.value)
min.value = currentFps;
if (currentFps > max.value)
max.value = currentFps;
deltaSum = 0;
frameCount = 0;
}
function reset() {
min.value = Infinity;
max.value = 0;
fps.value = 0;
deltaSum = 0;
frameCount = 0;
}
const { isActive, pause, resume, toggle } = useRafFn(update, rafOptions);
return {
fps,
min,
max,
isActive,
reset,
pause,
resume,
toggle,
};
}

View File

@@ -0,0 +1,259 @@
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest';
import { defineComponent, effectScope, nextTick, ref } from 'vue';
import { mount } from '@vue/test-utils';
import { useIntervalFn } from '.';
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
});
const ComponentStub = defineComponent({
props: {
callback: {
type: Function,
required: true,
},
interval: {
type: Number,
default: 1000,
},
options: {
type: Object,
default: () => ({}),
},
},
setup(props) {
const result = useIntervalFn(props.callback as () => void, props.interval, props.options);
return { ...result };
},
template: '<div>{{ isActive }}</div>',
});
describe(useIntervalFn, () => {
it('starts immediately by default', () => {
const callback = vi.fn();
const wrapper = mount(ComponentStub, {
props: { callback },
});
expect(wrapper.text()).toBe('true');
});
it('does not start when immediate is false', () => {
const callback = vi.fn();
mount(ComponentStub, {
props: {
callback,
options: { immediate: false },
},
});
expect(callback).not.toHaveBeenCalled();
vi.advanceTimersByTime(5000);
expect(callback).not.toHaveBeenCalled();
});
it('calls callback on each interval', () => {
const callback = vi.fn();
mount(ComponentStub, {
props: { callback, interval: 500 },
});
expect(callback).not.toHaveBeenCalled();
vi.advanceTimersByTime(500);
expect(callback).toHaveBeenCalledTimes(1);
vi.advanceTimersByTime(500);
expect(callback).toHaveBeenCalledTimes(2);
vi.advanceTimersByTime(1500);
expect(callback).toHaveBeenCalledTimes(5);
});
it('calls callback immediately when immediateCallback is true', () => {
const callback = vi.fn();
mount(ComponentStub, {
props: {
callback,
interval: 1000,
options: { immediateCallback: true },
},
});
expect(callback).toHaveBeenCalledTimes(1);
vi.advanceTimersByTime(1000);
expect(callback).toHaveBeenCalledTimes(2);
});
it('pauses and resumes', async () => {
const callback = vi.fn();
const wrapper = mount(ComponentStub, {
props: { callback, interval: 100 },
});
vi.advanceTimersByTime(300);
expect(callback).toHaveBeenCalledTimes(3);
wrapper.vm.pause();
await nextTick();
expect(wrapper.text()).toBe('false');
vi.advanceTimersByTime(500);
expect(callback).toHaveBeenCalledTimes(3);
wrapper.vm.resume();
await nextTick();
expect(wrapper.text()).toBe('true');
vi.advanceTimersByTime(200);
expect(callback).toHaveBeenCalledTimes(5);
});
it('toggles the interval', async () => {
const callback = vi.fn();
const wrapper = mount(ComponentStub, {
props: { callback },
});
expect(wrapper.text()).toBe('true');
wrapper.vm.toggle();
await nextTick();
expect(wrapper.text()).toBe('false');
wrapper.vm.toggle();
await nextTick();
expect(wrapper.text()).toBe('true');
});
it('supports reactive interval', async () => {
const callback = vi.fn();
const interval = ref(1000);
const scope = effectScope();
scope.run(() => {
useIntervalFn(callback, interval);
});
vi.advanceTimersByTime(1000);
expect(callback).toHaveBeenCalledTimes(1);
// Change interval to 200ms — watcher triggers async
interval.value = 200;
await nextTick();
vi.advanceTimersByTime(200);
expect(callback).toHaveBeenCalledTimes(2);
vi.advanceTimersByTime(200);
expect(callback).toHaveBeenCalledTimes(3);
scope.stop();
});
it('does not fire with interval <= 0', () => {
const callback = vi.fn();
const scope = effectScope();
scope.run(() => {
const { isActive } = useIntervalFn(callback, 0);
expect(isActive.value).toBeFalsy();
});
vi.advanceTimersByTime(5000);
expect(callback).not.toHaveBeenCalled();
scope.stop();
});
it('cleans up on scope dispose', () => {
const callback = vi.fn();
const scope = effectScope();
scope.run(() => {
useIntervalFn(callback, 100);
});
vi.advanceTimersByTime(300);
expect(callback).toHaveBeenCalledTimes(3);
scope.stop();
vi.advanceTimersByTime(500);
expect(callback).toHaveBeenCalledTimes(3);
});
it('cleans up on component unmount', () => {
const callback = vi.fn();
const wrapper = mount(ComponentStub, {
props: { callback, interval: 100 },
});
vi.advanceTimersByTime(300);
expect(callback).toHaveBeenCalledTimes(3);
wrapper.unmount();
vi.advanceTimersByTime(500);
expect(callback).toHaveBeenCalledTimes(3);
});
it('resume is idempotent when already active', () => {
const callback = vi.fn();
const scope = effectScope();
let result: ReturnType<typeof useIntervalFn>;
scope.run(() => {
result = useIntervalFn(callback, 100);
});
expect(result!.isActive.value).toBeTruthy();
result!.resume();
expect(result!.isActive.value).toBeTruthy();
// Should still tick normally — no double interval
vi.advanceTimersByTime(100);
expect(callback).toHaveBeenCalledTimes(1);
scope.stop();
});
it('pause is idempotent when already paused', () => {
const callback = vi.fn();
const scope = effectScope();
let result: ReturnType<typeof useIntervalFn>;
scope.run(() => {
result = useIntervalFn(callback, 100, { immediate: false });
});
expect(result!.isActive.value).toBeFalsy();
result!.pause();
expect(result!.isActive.value).toBeFalsy();
scope.stop();
});
it('uses default interval of 1000ms', () => {
const callback = vi.fn();
const scope = effectScope();
scope.run(() => {
useIntervalFn(callback);
});
vi.advanceTimersByTime(999);
expect(callback).not.toHaveBeenCalled();
vi.advanceTimersByTime(1);
expect(callback).toHaveBeenCalledTimes(1);
scope.stop();
});
});

View File

@@ -0,0 +1,112 @@
import { readonly, ref, toValue, watch } from 'vue';
import type { MaybeRefOrGetter, Ref } from 'vue';
import type { ResumableActions, ResumableOptions } from '@/types';
import { tryOnScopeDispose } from '@/composables/lifecycle/tryOnScopeDispose';
export interface UseIntervalFnOptions extends ResumableOptions {
/**
* Whether to invoke the callback immediately on start.
*
* @default false
*/
immediateCallback?: boolean;
}
export interface UseIntervalFnReturn extends ResumableActions {
/**
* Whether the interval is currently active
*/
isActive: Readonly<Ref<boolean>>;
}
/**
* Call a function on every interval. Supports reactive interval duration,
* pause/resume, and automatic cleanup on scope dispose.
*
* @param callback - Function to call on every interval tick
* @param interval - Interval duration in milliseconds (can be reactive)
* @param options - Configuration options
*
* @example
* ```ts
* const { pause, resume, isActive } = useIntervalFn(() => {
* console.log('tick');
* }, 1000);
* ```
*
* @example
* ```ts
* // Reactive interval
* const delay = ref(1000);
* useIntervalFn(() => console.log('tick'), delay);
* delay.value = 500; // interval restarts with new duration
* ```
*/
export function useIntervalFn(
callback: () => void,
interval: MaybeRefOrGetter<number> = 1000,
options: UseIntervalFnOptions = {},
): UseIntervalFnReturn {
const {
immediate = true,
immediateCallback = false,
} = options;
const isActive = ref(false);
let timerId: ReturnType<typeof setInterval> | null = null;
function clean() {
if (timerId !== null) {
clearInterval(timerId);
timerId = null;
}
}
function resume() {
const ms = toValue(interval);
if (ms <= 0)
return;
isActive.value = true;
if (immediateCallback)
callback();
clean();
timerId = setInterval(callback, ms);
}
function pause() {
isActive.value = false;
clean();
}
function toggle() {
if (isActive.value)
pause();
else
resume();
}
// Re-start when interval changes reactively
watch(() => toValue(interval), () => {
if (isActive.value) {
clean();
resume();
}
});
if (immediate)
resume();
tryOnScopeDispose(pause);
return {
isActive: readonly(isActive),
pause,
resume,
toggle,
};
}

View File

@@ -0,0 +1,252 @@
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest';
import { defineComponent, effectScope, nextTick } from 'vue';
import { mount } from '@vue/test-utils';
import { useRafFn } from '.';
let rafCallbacks: Array<(time: number) => void> = [];
let rafIdCounter = 0;
let currentTime = 0;
beforeEach(() => {
rafCallbacks = [];
rafIdCounter = 0;
currentTime = 0;
vi.stubGlobal('requestAnimationFrame', (cb: (time: number) => void) => {
const id = ++rafIdCounter;
rafCallbacks.push(cb);
return id;
});
vi.stubGlobal('cancelAnimationFrame', vi.fn());
});
afterEach(() => {
vi.unstubAllGlobals();
});
function triggerFrame(time: number) {
currentTime = time;
const cbs = [...rafCallbacks];
rafCallbacks = [];
cbs.forEach(cb => cb(currentTime));
}
const ComponentStub = defineComponent({
props: {
callback: {
type: Function,
required: true,
},
options: {
type: Object,
default: () => ({}),
},
},
setup(props) {
const result = useRafFn(props.callback as any, props.options);
return { ...result };
},
template: '<div>{{ isActive }}</div>',
});
describe(useRafFn, () => {
it('starts immediately by default', () => {
const callback = vi.fn();
const wrapper = mount(ComponentStub, {
props: { callback },
});
expect(wrapper.text()).toBe('true');
});
it('does not start when immediate is false', () => {
const callback = vi.fn();
const wrapper = mount(ComponentStub, {
props: {
callback,
options: { immediate: false },
},
});
expect(wrapper.text()).toBe('false');
expect(callback).not.toHaveBeenCalled();
});
it('calls the callback on animation frame with delta and timestamp', () => {
const callback = vi.fn();
mount(ComponentStub, {
props: { callback },
});
triggerFrame(100);
expect(callback).toHaveBeenCalledWith({ delta: 0, timestamp: 100 });
});
it('provides correct delta between frames', () => {
const callback = vi.fn();
mount(ComponentStub, {
props: { callback },
});
triggerFrame(100);
triggerFrame(116.67);
expect(callback).toHaveBeenCalledTimes(2);
expect(callback.mock.calls[1]![0]!.delta).toBeCloseTo(16.67, 1);
});
it('pauses and resumes the loop', async () => {
const callback = vi.fn();
const wrapper = mount(ComponentStub, {
props: { callback },
});
triggerFrame(100);
expect(callback).toHaveBeenCalledTimes(1);
wrapper.vm.pause();
await nextTick();
expect(wrapper.text()).toBe('false');
triggerFrame(200);
expect(callback).toHaveBeenCalledTimes(1);
wrapper.vm.resume();
await nextTick();
expect(wrapper.text()).toBe('true');
triggerFrame(300);
expect(callback).toHaveBeenCalledTimes(2);
});
it('resets delta after resume', () => {
const callback = vi.fn();
const wrapper = mount(ComponentStub, {
props: { callback },
});
triggerFrame(100);
wrapper.vm.pause();
wrapper.vm.resume();
triggerFrame(500);
// After resume, first frame delta resets to 0
const lastCall = callback.mock.calls[callback.mock.calls.length - 1]![0]!;
expect(lastCall.delta).toBe(0);
expect(lastCall.timestamp).toBe(500);
});
it('toggles the loop', async () => {
const callback = vi.fn();
const wrapper = mount(ComponentStub, {
props: { callback },
});
expect(wrapper.text()).toBe('true');
wrapper.vm.toggle();
await nextTick();
expect(wrapper.text()).toBe('false');
wrapper.vm.toggle();
await nextTick();
expect(wrapper.text()).toBe('true');
});
it('limits frame rate with fpsLimit', () => {
const callback = vi.fn();
mount(ComponentStub, {
props: {
callback,
options: { fpsLimit: 30 },
},
});
// First frame always fires (delta is 0)
triggerFrame(100);
expect(callback).toHaveBeenCalledTimes(1);
// 30fps = ~33.33ms per frame — too soon, skipped
triggerFrame(110);
expect(callback).toHaveBeenCalledTimes(1);
// Enough time passed (~40ms > 33.33ms)
triggerFrame(140);
expect(callback).toHaveBeenCalledTimes(2);
});
it('cleans up on scope dispose', () => {
const callback = vi.fn();
const scope = effectScope();
scope.run(() => {
useRafFn(callback);
});
triggerFrame(100);
expect(callback).toHaveBeenCalledTimes(1);
scope.stop();
triggerFrame(200);
expect(callback).toHaveBeenCalledTimes(1);
});
it('cleans up on component unmount', () => {
const callback = vi.fn();
const wrapper = mount(ComponentStub, {
props: { callback },
});
triggerFrame(100);
expect(callback).toHaveBeenCalledTimes(1);
wrapper.unmount();
triggerFrame(200);
expect(callback).toHaveBeenCalledTimes(1);
});
it('does nothing when window is undefined (SSR)', () => {
const callback = vi.fn();
const scope = effectScope();
scope.run(() => {
const { isActive } = useRafFn(callback, { window: undefined as any });
expect(isActive.value).toBeFalsy();
});
expect(callback).not.toHaveBeenCalled();
scope.stop();
});
it('resume is idempotent when already active', () => {
const scope = effectScope();
let result: ReturnType<typeof useRafFn>;
scope.run(() => {
result = useRafFn(vi.fn());
});
expect(result!.isActive.value).toBeTruthy();
result!.resume();
expect(result!.isActive.value).toBeTruthy();
scope.stop();
});
it('pause is idempotent when already paused', () => {
const scope = effectScope();
let result: ReturnType<typeof useRafFn>;
scope.run(() => {
result = useRafFn(vi.fn(), { immediate: false });
});
expect(result!.isActive.value).toBeFalsy();
result!.pause();
expect(result!.isActive.value).toBeFalsy();
scope.stop();
});
});

View File

@@ -0,0 +1,120 @@
import { readonly, ref } from 'vue';
import type { Ref } from 'vue';
import { defaultWindow } from '@/types';
import type { ConfigurableWindow, ResumableActions, ResumableOptions } from '@/types';
import { tryOnScopeDispose } from '@/composables/lifecycle/tryOnScopeDispose';
export interface UseRafFnCallbackArgs {
/**
* Time elapsed since the last frame in milliseconds
*/
delta: number;
/**
* `DOMHighResTimeStamp` passed by `requestAnimationFrame`
*/
timestamp: DOMHighResTimeStamp;
}
export interface UseRafFnOptions extends ResumableOptions, ConfigurableWindow {
/**
* Maximum frames per second. Set to `0` or `undefined` to disable the limit.
*
* @default undefined
*/
fpsLimit?: number;
}
export interface UseRafFnReturn extends ResumableActions {
/**
* Whether the RAF loop is currently active
*/
isActive: Readonly<Ref<boolean>>;
}
/**
* Call a function on every `requestAnimationFrame` with delta time tracking.
* Automatically cleans up when the component scope is disposed.
*
* @param callback - Function to call on every animation frame
* @param options - Configuration options
*
* @example
* ```ts
* const { pause, resume, isActive } = useRafFn(({ delta, timestamp }) => {
* console.log(`${delta}ms since last frame`);
* });
* ```
*/
export function useRafFn(
callback: (args: UseRafFnCallbackArgs) => void,
options: UseRafFnOptions = {},
): UseRafFnReturn {
const {
immediate = true,
fpsLimit,
} = options;
const window = 'window' in options ? options.window : defaultWindow;
const isActive = ref(false);
const intervalLimit = fpsLimit ? 1000 / fpsLimit : null;
let previousFrameTimestamp = 0;
let rafId: number | null = null;
function loop(timestamp: DOMHighResTimeStamp) {
if (!isActive.value || !window)
return;
if (!previousFrameTimestamp)
previousFrameTimestamp = timestamp;
const delta = timestamp - previousFrameTimestamp;
if (intervalLimit && delta && delta < intervalLimit) {
rafId = window.requestAnimationFrame(loop);
return;
}
previousFrameTimestamp = timestamp;
callback({ delta, timestamp });
rafId = window.requestAnimationFrame(loop);
}
function resume() {
if (!isActive.value && window) {
isActive.value = true;
previousFrameTimestamp = 0;
rafId = window.requestAnimationFrame(loop);
}
}
function pause() {
isActive.value = false;
if (rafId !== null && window) {
window.cancelAnimationFrame(rafId);
rafId = null;
}
}
function toggle() {
if (isActive.value)
pause();
else
resume();
}
if (immediate)
resume();
tryOnScopeDispose(pause);
return {
isActive: readonly(isActive),
pause,
resume,
toggle,
};
}

View File

@@ -0,0 +1,55 @@
<script setup lang="ts">
import { useTabLeader } from './index';
const { isLeader, isSupported, acquire, release } = useTabLeader('docs-demo-leader');
</script>
<template>
<div class="space-y-4">
<div class="flex items-center gap-3">
<span class="text-sm font-medium text-(--color-text-soft)">Web Locks API:</span>
<span
class="inline-flex items-center gap-1.5 text-sm font-mono px-2 py-0.5 rounded border"
:class="isSupported ? 'border-emerald-500/30 bg-emerald-500/10 text-emerald-700' : 'border-red-500/30 bg-red-500/10 text-red-700'"
>
{{ isSupported ? 'Supported' : 'Not supported' }}
</span>
</div>
<div class="flex items-center gap-3">
<span class="text-sm font-medium text-(--color-text-soft)">Leader status:</span>
<span
class="inline-flex items-center gap-1.5 text-sm font-mono px-2 py-0.5 rounded border"
:class="isLeader ? 'border-brand-500/30 bg-brand-500/10 text-brand-600' : 'border-(--color-border) bg-(--color-bg-mute) text-(--color-text-soft)'"
>
<span
class="w-2 h-2 rounded-full"
:class="isLeader ? 'bg-brand-500 animate-pulse' : 'bg-(--color-text-mute)'"
/>
{{ isLeader ? 'Leader' : 'Follower' }}
</span>
</div>
<p class="text-xs text-(--color-text-mute)">
Open this page in multiple tabs only one will be the leader.
Close the leader tab and another will take over automatically.
</p>
<div class="flex items-center gap-2 pt-2">
<button
class="px-3 py-1.5 text-sm rounded-md border border-(--color-border) bg-(--color-bg) hover:bg-(--color-bg-mute) text-(--color-text-soft) transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
:disabled="!isSupported || isLeader"
@click="acquire"
>
Acquire
</button>
<button
class="px-3 py-1.5 text-sm rounded-md border border-(--color-border) bg-(--color-bg) hover:bg-(--color-bg-mute) text-(--color-text-soft) transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
:disabled="!isSupported || !isLeader"
@click="release"
>
Release
</button>
</div>
</div>
</template>

View File

@@ -1,3 +1,4 @@
export * from './unrefElement';
export * from './useRenderCount';
export * from './useRenderInfo';
export * from './useTemplateRefsList';

View File

@@ -0,0 +1,141 @@
import { describe, expect, it } from 'vitest';
import { defineComponent, nextTick, ref } from 'vue';
import { mount } from '@vue/test-utils';
import { useTemplateRefsList } from '.';
describe(useTemplateRefsList, () => {
it('collects elements rendered with v-for', async () => {
const Component = defineComponent({
setup() {
const items = ref([1, 2, 3]);
const { refs, set } = useTemplateRefsList<HTMLDivElement>();
return { items, refs, set };
},
template: `<div v-for="item in items" :key="item" :ref="set">{{ item }}</div>`,
});
const wrapper = mount(Component);
await nextTick();
expect(wrapper.vm.refs).toHaveLength(3);
expect(wrapper.vm.refs[0]).toBeInstanceOf(HTMLDivElement);
expect(wrapper.vm.refs[1]).toBeInstanceOf(HTMLDivElement);
expect(wrapper.vm.refs[2]).toBeInstanceOf(HTMLDivElement);
});
it('updates refs when items are added', async () => {
const Component = defineComponent({
setup() {
const items = ref([1, 2]);
const { refs, set } = useTemplateRefsList<HTMLDivElement>();
return { items, refs, set };
},
template: `<div v-for="item in items" :key="item" :ref="set">{{ item }}</div>`,
});
const wrapper = mount(Component);
await nextTick();
expect(wrapper.vm.refs).toHaveLength(2);
wrapper.vm.items.push(3);
await nextTick();
expect(wrapper.vm.refs).toHaveLength(3);
});
it('updates refs when items are removed', async () => {
const Component = defineComponent({
setup() {
const items = ref([1, 2, 3]);
const { refs, set } = useTemplateRefsList<HTMLDivElement>();
return { items, refs, set };
},
template: `<div v-for="item in items" :key="item" :ref="set">{{ item }}</div>`,
});
const wrapper = mount(Component);
await nextTick();
expect(wrapper.vm.refs).toHaveLength(3);
wrapper.vm.items.splice(0, 1);
await nextTick();
expect(wrapper.vm.refs).toHaveLength(2);
});
it('returns empty array when no elements are rendered', async () => {
const Component = defineComponent({
setup() {
const items = ref<number[]>([]);
const { refs, set } = useTemplateRefsList<HTMLDivElement>();
return { items, refs, set };
},
template: `<div><span v-for="item in items" :key="item" :ref="set">{{ item }}</span></div>`,
});
const wrapper = mount(Component);
await nextTick();
expect(wrapper.vm.refs).toHaveLength(0);
});
it('unwraps component instances to their root elements', async () => {
const Child = defineComponent({
template: `<span class="child">child</span>`,
});
const Parent = defineComponent({
components: { Child },
setup() {
const items = ref([1, 2]);
const { refs, set } = useTemplateRefsList<HTMLSpanElement>();
return { items, refs, set };
},
template: `<div><Child v-for="item in items" :key="item" :ref="set" /></div>`,
});
const wrapper = mount(Parent);
await nextTick();
expect(wrapper.vm.refs).toHaveLength(2);
expect(wrapper.vm.refs[0]).toBeInstanceOf(HTMLSpanElement);
expect(wrapper.vm.refs[0]!.classList.contains('child')).toBe(true);
});
it('preserves element order matching v-for order', async () => {
const Component = defineComponent({
setup() {
const items = ref(['a', 'b', 'c']);
const { refs, set } = useTemplateRefsList<HTMLDivElement>();
return { items, refs, set };
},
template: `<div v-for="item in items" :key="item" :ref="set" :data-item="item">{{ item }}</div>`,
});
const wrapper = mount(Component);
await nextTick();
expect(wrapper.vm.refs[0]!.dataset.item).toBe('a');
expect(wrapper.vm.refs[1]!.dataset.item).toBe('b');
expect(wrapper.vm.refs[2]!.dataset.item).toBe('c');
});
it('handles complete list replacement', async () => {
const Component = defineComponent({
setup() {
const items = ref([1, 2, 3]);
const { refs, set } = useTemplateRefsList<HTMLDivElement>();
return { items, refs, set };
},
template: `<div v-for="item in items" :key="item" :ref="set" :data-item="item">{{ item }}</div>`,
});
const wrapper = mount(Component);
await nextTick();
expect(wrapper.vm.refs).toHaveLength(3);
wrapper.vm.items = [4, 5];
await nextTick();
expect(wrapper.vm.refs).toHaveLength(2);
expect(wrapper.vm.refs[0]!.dataset.item).toBe('4');
expect(wrapper.vm.refs[1]!.dataset.item).toBe('5');
});
});

View File

@@ -0,0 +1,72 @@
import { onBeforeUpdate, onMounted, onUpdated, readonly, shallowRef } from 'vue';
import type { DeepReadonly, ShallowRef } from 'vue';
import type { MaybeElement } from '../unrefElement';
import { unrefElement } from '../unrefElement';
export interface UseTemplateRefsListReturn<El extends Element> {
/** Reactive readonly array of collected template refs */
refs: DeepReadonly<ShallowRef<El[]>>;
/** Ref setter function — bind via `:ref="set"` in templates */
set: (el: MaybeElement) => void;
}
/**
* @name useTemplateRefsList
* @category Component
* @description Collects a dynamic list of template refs for use with `v-for`.
* Automatically clears the list before each component update and repopulates it
* with fresh element references. Handles both plain DOM elements and Vue component
* instances (unwraps `$el`).
*
* Uses a non-reactive buffer internally to collect refs during the render cycle,
* then flushes to a `shallowRef` in `onMounted`/`onUpdated` to avoid triggering
* recursive update loops.
*
* @returns {UseTemplateRefsListReturn<El>} An object with a reactive `refs` array and a `set` function
*
* @example
* const { refs, set } = useTemplateRefsList<HTMLDivElement>();
* // Template: <div v-for="item in items" :key="item.id" :ref="set" />
* // refs.value contains all rendered div elements
*
* @since 0.0.14
*/
export function useTemplateRefsList<El extends Element = Element>(): UseTemplateRefsListReturn<El> {
const refs = shallowRef<El[]>([]);
let buffer: El[] = [];
const set = (el: MaybeElement) => {
const plain = unrefElement(el);
if (plain)
buffer.push(plain as unknown as El);
};
const flush = () => {
buffer.sort(documentPositionComparator);
refs.value = buffer;
};
onBeforeUpdate(() => {
buffer = [];
});
onMounted(flush);
onUpdated(flush);
return {
refs: readonly(refs) as DeepReadonly<ShallowRef<El[]>>,
set,
};
}
function documentPositionComparator(a: Element, b: Element): number {
if (a === b) return 0;
const position = a.compareDocumentPosition(b);
if (position & Node.DOCUMENT_POSITION_FOLLOWING) return -1;
if (position & Node.DOCUMENT_POSITION_PRECEDING) return 1;
return 0;
}