Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ storybook-static/

# Generated
public/r/
public/_pagefind/
apps/registry/public/_pagefind/
next-env.d.ts

# Local config
Expand Down
16 changes: 12 additions & 4 deletions apps/registry/components/header/header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { NavbarSaas, SearchDialog } from "@vllnt/ui";
import { Github } from "lucide-react";
import { useRouter } from "next/navigation";

import { searchPagefind } from "@/components/header/pagefind-search";
import registryData from "@/registry.json";

const GITHUB_URL = "https://github.com/vllnt/ui";
Expand All @@ -26,6 +27,7 @@ export function Header() {
.filter((item) => item.type === "registry:component")
.map((item) => ({
description: item.description,
href: `/components/${item.name}`,
id: item.name,
title: item.title,
}));
Expand All @@ -37,14 +39,20 @@ export function Header() {
rightSlot={
<div className="flex items-center gap-2">
<SearchDialog
buttonText="Search components..."
emptyText="No components found."
buttonText="Search..."
docsEmptyText="No docs found."
docsGroupHeading="Docs"
docsSearch={searchPagefind}
emptyText="No results found."
groupHeading="Components"
items={searchItems}
onDocsSelect={(item) => {
router.push(item.href ?? item.id);
}}
onSelect={(item) => {
router.push(`/components/${item.id}`);
router.push(item.href ?? `/components/${item.id}`);
}}
searchPlaceholder="Search components..."
searchPlaceholder="Search docs and components..."
/>
<a
aria-label="VLLNT UI on GitHub"
Expand Down
175 changes: 175 additions & 0 deletions apps/registry/components/header/pagefind-search.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
import type { SearchItem } from "@vllnt/ui";

type PagefindResultData = {
excerpt?: string;
meta?: {
title?: string;
};
url: string;
} & Partial<Record<"plain_excerpt", string>> &
Partial<Record<"sub_results", PagefindSubResult[]>>;

type PagefindSubResult = {
excerpt?: string;
title?: string;
url: string;
} & Partial<Record<"plain_excerpt", string>>;

type PagefindSearchResponse = {
results: {
data: () => Promise<PagefindResultData>;
id: string;
}[];
};

type PagefindModule = {
debouncedSearch?: (
query: string,
options?: Record<string, never>,
timeout?: number,
) => Promise<null | PagefindSearchResponse>;
init?: () => Promise<void> | void;
search: (query: string) => Promise<PagefindSearchResponse>;
};

const PAGEFIND_BUNDLE_PATH = "/_pagefind/pagefind.js";
const MAX_RESULTS = 8;
const SNIPPET_CONTEXT = 50;

let pagefindPromise: Promise<PagefindModule> | undefined;

async function loadPagefind() {
pagefindPromise ??= import(
/* webpackIgnore: true */ PAGEFIND_BUNDLE_PATH
).then((module) => {
const pagefind = module as PagefindModule;
void pagefind.init?.();
return pagefind;
});

return pagefindPromise;
}

function stripMarkup(value: string) {
return value.replaceAll(/<[^>]*>/g, "");

Check failure

Code scanning / CodeQL

Incomplete multi-character sanitization High

This string may still contain
<script
, which may cause an HTML element injection vulnerability.
}

function getFallbackTitle(url: string) {
const path = url.split("#")[0]?.replaceAll(/^\/|\/$/g, "") || "Home";
const lastSegment = path.split("/").findLast(Boolean) ?? path;

return lastSegment
.split("-")
.filter(Boolean)
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
.join(" ");
}

function getSnippet(text: string, query: string) {
const compactText = text.replaceAll(/\s+/g, " ").trim();

if (compactText.length <= SNIPPET_CONTEXT) {
return compactText;
}

const index = compactText.toLowerCase().indexOf(query.toLowerCase());

if (index === -1) {
return `${compactText.slice(0, SNIPPET_CONTEXT).trim()}…`;
}

const start = Math.max(0, index - Math.floor(SNIPPET_CONTEXT / 2));
const end = Math.min(
compactText.length,
index + query.length + Math.floor(SNIPPET_CONTEXT / 2),
);
const prefix = start > 0 ? "… " : "";
const suffix = end < compactText.length ? " …" : "";

return `${prefix}${compactText.slice(start, end).trim()}${suffix}`;
}

type SearchItemInput = {
entry: PagefindResultData | PagefindSubResult;
index: number;
query: string;
result: PagefindResultData;
};

function toSearchItem({
entry,
index,
query,
result,
}: SearchItemInput): SearchItem {
const plainExcerpt =
entry.plain_excerpt ?? stripMarkup(entry.excerpt ?? result.excerpt ?? "");
const url = entry.url || result.url;
const title =
"title" in entry && entry.title
? entry.title
: (result.meta?.title ?? getFallbackTitle(url));

return {
description: url,
href: url,
id: `docs:${url}:${index}`,
keywords: plainExcerpt,
snippet: getSnippet(plainExcerpt, query),
title,
};
}

async function runPagefindSearch(query: string) {
const pagefind = await loadPagefind();

return (
(await pagefind.debouncedSearch?.(query, {}, 150)) ??
(await pagefind.search(query))
);
}

async function loadSearchItems(
response: PagefindSearchResponse,
query: string,
) {
const resultData = await Promise.all(
response.results.slice(0, MAX_RESULTS).map((result) => result.data()),
);
const items = resultData.flatMap((result, resultIndex) => {
const entries = result.sub_results?.length
? result.sub_results.slice(0, 2)
: [result];

return entries.map((entry, entryIndex) =>
toSearchItem({
entry,
index: resultIndex * 10 + entryIndex,
query,
result,
}),
);
});

return [...new Map(items.map((item) => [item.href, item])).values()].slice(
0,
MAX_RESULTS,
);
}

export async function searchPagefind(query: string): Promise<SearchItem[]> {
const trimmedQuery = query.trim();

if (trimmedQuery.length < 2 || typeof window === "undefined") {
return [];
}

try {
const response = await runPagefindSearch(trimmedQuery);
return response === null
? []
: await loadSearchItems(response, trimmedQuery);
} catch {
return [];
}
}
8 changes: 6 additions & 2 deletions apps/registry/lib/component-metadata.json
Original file line number Diff line number Diff line change
Expand Up @@ -2904,13 +2904,17 @@
},
"search-dialog": {
"category": "learning",
"defaultStoryId": "exampletitle--default",
"defaultStoryId": "learning-searchdialog--default",
"description": "Full-screen search dialog with keyboard navigation.",
"name": "search-dialog",
"stories": [
{
"id": "exampletitle--default",
"id": "learning-searchdialog--default",
"name": "Default"
},
{
"id": "learning-searchdialog--with-docs",
"name": "With Docs"
}
],
"title": "Search Dialog"
Expand Down
6 changes: 4 additions & 2 deletions apps/registry/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,14 @@
"type": "module",
"scripts": {
"dev": "next dev",
"build": "pnpm registry:build && next build",
"clean": "rm -rf .next node_modules public/r",
"build": "pnpm registry:build && next build && pnpm search:index",
"clean": "rm -rf .next node_modules public/r public/_pagefind",
"start": "next start",
"lint": "eslint .",
"lint:fix": "eslint . --fix",
"registry:build": "tsx scripts/inline-component-source.ts && shadcn build && tsx scripts/stamp-registry-metadata.ts && tsx scripts/generate-component-metadata.ts",
"registry:sync-shims": "tsx scripts/inline-component-source.ts",
"search:index": "pagefind --site .next/server/app --output-path public/_pagefind --root-selector main --force-language en",
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking: this adds search:index to generate public/_pagefind, but the registry build cache contract still omits public/_pagefind/** from Turbo outputs. A cached build can restore .next/** without restoring /_pagefind/pagefind.js, so the docs-search UI can ship with no Pagefind bundle. Add public/_pagefind/** to the package-relative Turbo build outputs, or make the search indexing step uncached and always run before deploy artifact collection.

"sync-storybook": "tsx scripts/generate-component-metadata.ts"
},
"dependencies": {
Expand Down Expand Up @@ -42,6 +43,7 @@
"@vllnt/typescript": "^1.0.0",
"autoprefixer": "^10.4.20",
"eslint": "^9.39.1",
"pagefind": "^1.5.2",
"postcss": "^8.5",
"tailwindcss": "^3.4.17",
"tailwindcss-animate": "^1.0.7",
Expand Down
2 changes: 1 addition & 1 deletion apps/registry/registry.json
Original file line number Diff line number Diff line change
Expand Up @@ -4492,5 +4492,5 @@
}
],
"version": "0.2.1",
"generatedAt": "2026-05-10T19:14:31.709Z"
"generatedAt": "2026-05-13T20:57:25.231Z"
}
Loading
Loading