Files
paseo/packages/website/src/docs.ts
T
Mohamed BoudraandGitHub dfd18a44a7 Document Hub and let docs pages nest (#2864)
* feat(website): nest docs pages under landable groups

The docs sidebar could already render groups from subdirectories in
public-docs, but nothing used it because every doc was a flat file, and
two things stopped it being usable.

A group had no page of its own, so its label was only a toggle and its
name came from the directory name via formatLabel. A directory's
index.md now supplies the group's label, order, and href, which makes
the group landable and lets the label be authored rather than derived.

Categories and top-level directories named the same thing, so a
categorised doc at hub/index.md produced a group nested inside its own
category. Only directories below the top level become groups now.

Also fixes two behaviours in the sidebar:

- The open/closed effect assigned containsActive on every change, so a
  group you expanded to browse collapsed the moment you navigated
  anywhere else. Navigating in now opens a group and navigating away
  leaves it alone.
- The sidebar scrolls independently of the page and never scrolled the
  active entry into view, so loading or refreshing a page far down the
  list left the sidebar parked at the top with no visible position.

The group row is a single target: it navigates and expands, and
collapses when clicked again from the page it points at. A separate
chevron button would put two actions a few pixels apart.

* docs(hub): document Hub

Adds a Hub section covering what it is, how it works, daemons,
triggers, configuration, activity, and the two ways to run it.

The section separates using Hub from running it. Overview, quickstart,
daemons, triggers, and configuration hold regardless of who operates
the deployment; the self-hosting branch owns deploying the service and
creating the GitHub, Slack, and Discord apps it talks to. That split
falls on a real seam, because those apps are exactly what a hosted Hub
would own on your behalf. Hosted is a placeholder until it ships.

Each provider gets a trigger page carrying its events, filter
semantics, and the full paseo.event.* reference for the data a prompt
can read. That data is the thing a config author actually needs and
the thing they cannot get from anywhere else.

Every YAML block was parsed against the Hub config schema rather than
eyeballed, which kept several plausible-looking things out of the
docs: worktree prNumber takes a literal number and not a merge
variable, only daemon environments run today, and github.push has no
actor so it can never satisfy the required from_users filter.

Troubleshooting moves to order 90 so it stays last.

* refactor(website): let the active docs entry scroll itself into view

The layout queried the sidebar for the active entry after every
navigation, which coupled it to when that entry mounts. A link inside a
collapsed group only mounts once the group's own effect opens it, so
the query could run against a DOM that does not contain it yet.

Moving the scroll to the entry removes the ordering question rather
than answering it, and drops the ref and the cross-component query.

Reported by Greptile on #2864. The failure it described does not
reproduce: navigating from a page outside a collapsed group into one of
its children still scrolls correctly, verified with the group confirmed
collapsed and the sidebar forced to the top. The coupling was real even
though the bug was not.

* docs(hub): stop listing BETTER_AUTH_URL as required

It falls back to PASEO_CLOUD_PUBLIC_URL, so a deployment that sets the
public origin already has a correct auth base URL. Listing it as
required made the Fly recipe look incomplete when it was not.

Moved to optional with its default, and recorded what actually breaks
without BETTER_AUTH_SECRET: the auth routes close and nobody can sign
in.

Reported by Codex on #2864, which read the same inconsistency the other
way round and proposed adding the variable to the Fly example.

* docs(hub): attach a database in the Fly recipe

The Fly section showed inline config and a secrets command, neither of
which supplied DATABASE_URL. It defaults to localhost:5432, which on
Fly reaches nothing, so the documented deployment could not start.

fly postgres attach sets DATABASE_URL as a secret, so the step is the
attach itself rather than another variable to copy.

Reported by Codex on #2864.

* docs: align Hub self-hosting contract
2026-08-05 03:58:27 +08:00

303 lines
7.7 KiB
TypeScript

import Slugger from "github-slugger";
interface DocFrontmatter {
title: string;
description: string;
nav: string;
order: number;
category?: string;
}
export interface DocHeading {
depth: number;
text: string;
id: string;
}
export interface Doc {
slug: string;
href: string;
sourcePath: string;
frontmatter: DocFrontmatter;
content: string;
headings: DocHeading[];
}
export type DocsNavNode =
| {
type: "category";
label: string;
children: DocsNavNode[];
order: number;
}
| {
type: "group";
segment: string;
label: string;
children: DocsNavNode[];
order: number;
/** Set when the directory has an `index.md`, which makes the group landable. */
href?: string;
}
| {
type: "page";
segment: string;
label: string;
href: string;
order: number;
};
function parseFrontmatter(raw: string): { data: Record<string, string>; content: string } {
const match = raw.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);
if (!match) return { data: {}, content: raw };
const data: Record<string, string> = {};
for (const line of match[1].split("\n")) {
const colonIdx = line.indexOf(":");
if (colonIdx === -1) continue;
const key = line.slice(0, colonIdx).trim();
const value = line
.slice(colonIdx + 1)
.trim()
.replace(/^["']|["']$/g, "");
data[key] = value;
}
return { data, content: match[2] };
}
function stripInlineMarkdown(text: string): string {
return text
.replace(/!?\[([^\]]*)\]\([^)]*\)/g, "$1")
.replace(/!?\[([^\]]*)\]\[[^\]]*\]/g, "$1")
.replace(/`([^`]+)`/g, "$1")
.replace(/(\*\*|__)(.*?)\1/g, "$2")
.replace(/(\*|_)(.*?)\1/g, "$2")
.replace(/<[^>]+>/g, "")
.trim();
}
function parseHeadings(content: string): DocHeading[] {
const slugger = new Slugger();
const headings: DocHeading[] = [];
const regex = /^(#{1,6})\s+(.+)$/gm;
let match: RegExpExecArray | null;
while ((match = regex.exec(content)) !== null) {
const depth = match[1].length;
if (depth < 2 || depth > 4) continue;
const text = stripInlineMarkdown(match[2].trim());
if (!text) continue;
headings.push({
depth,
text,
id: slugger.slug(text),
});
}
return headings;
}
const docModules = import.meta.glob("../../../public-docs/**/*.md", {
eager: true,
query: "?raw",
import: "default",
}) as Record<string, string>;
function pathToSlug(path: string): string {
const after = path.split("/public-docs/")[1] ?? path;
const noExt = after.replace(/\.md$/, "");
if (noExt === "index") return "";
return noExt.replace(/\/index$/, "");
}
function pathToSourcePath(path: string): string {
return path.split("/public-docs/")[1] ?? path;
}
function loadDocs(): Doc[] {
const docs: Doc[] = [];
for (const [path, raw] of Object.entries(docModules)) {
const { data, content } = parseFrontmatter(raw);
const slug = pathToSlug(path);
const href = slug === "" ? "/docs" : `/docs/${slug}`;
const order = Number.parseInt(data.order ?? "999", 10);
docs.push({
slug,
href,
sourcePath: `public-docs/${pathToSourcePath(path)}`,
frontmatter: {
title: data.title ?? "",
description: data.description ?? "",
nav: data.nav ?? data.title ?? slug,
order: Number.isFinite(order) ? order : 999,
category: data.category,
},
content,
headings: parseHeadings(content),
});
}
docs.sort((a, b) => a.frontmatter.order - b.frontmatter.order);
return docs;
}
let cached: Doc[] | undefined;
export function getDocs(): Doc[] {
if (!cached) cached = loadDocs();
return cached;
}
export function getDoc(slug: string): Doc | undefined {
return getDocs().find((d) => d.slug === slug);
}
function formatLabel(segment: string): string {
return segment.replace(/[-_]+/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
}
function insertDocByPath(nodes: DocsNavNode[], doc: Doc, stripTopDirectory = false): void {
const relative = doc.sourcePath.replace(/^public-docs\//, "");
const segments = relative.replace(/\.md$/, "").split("/");
const fileName = segments.pop() ?? "";
const directories = segments;
// A section's top-level directory and its category name the same thing, so
// only directories below it become collapsible groups.
if (stripTopDirectory) directories.shift();
let current = nodes;
let parent: Extract<DocsNavNode, { type: "group" }> | undefined;
for (const segment of directories) {
let group = current.find(
(node): node is Extract<DocsNavNode, { type: "group" }> =>
node.type === "group" && node.segment === segment,
);
if (!group) {
group = {
type: "group",
segment,
label: formatLabel(segment),
children: [],
order: doc.frontmatter.order,
};
current.push(group);
}
parent = group;
current = group.children;
}
// A directory's index.md describes its own group: it supplies the label and
// order the directory name can't, and makes the group itself navigable.
if (fileName === "index" && parent !== undefined) {
parent.label = doc.frontmatter.nav;
parent.order = doc.frontmatter.order;
parent.href = doc.href;
return;
}
current.push({
type: "page",
segment: fileName,
label: doc.frontmatter.nav,
href: doc.href,
order: doc.frontmatter.order,
});
}
function nodeOrder(node: DocsNavNode): number {
if (node.type === "page") return node.order;
if (node.type === "group" && node.href !== undefined) return node.order;
if (node.children.length === 0) return Infinity;
let min = Infinity;
for (const child of node.children) {
const childOrder = nodeOrder(child);
if (childOrder < min) min = childOrder;
}
return min;
}
function sortNodes(nodes: DocsNavNode[]): void {
nodes.sort((a, b) => nodeOrder(a) - nodeOrder(b));
for (const node of nodes) {
if (node.type !== "page") {
sortNodes(node.children);
}
}
}
export function buildDocsNavTree(docs: Doc[]): DocsNavNode[] {
const byCategory = new Map<string, Doc[]>();
const uncategorized: Doc[] = [];
for (const doc of docs) {
const category = doc.frontmatter.category?.trim();
if (category) {
const list = byCategory.get(category) ?? [];
list.push(doc);
byCategory.set(category, list);
} else {
uncategorized.push(doc);
}
}
const root: DocsNavNode[] = [];
for (const doc of uncategorized) {
insertDocByPath(root, doc);
}
for (const [label, docsInCategory] of byCategory) {
const children: DocsNavNode[] = [];
for (const doc of docsInCategory) {
insertDocByPath(children, doc, true);
}
root.push({
type: "category",
label,
children,
order: nodeOrder({ type: "category", label, children, order: Infinity }),
});
}
sortNodes(root);
return root;
}
function findNodePath(
nodes: DocsNavNode[],
href: string,
path: DocsNavNode[] = [],
): DocsNavNode[] | null {
for (const node of nodes) {
if (node.type === "page" && node.href === href) {
return [...path, node];
}
if (node.type !== "page") {
if (node.type === "group" && node.href === href) {
return [...path, node];
}
const found = findNodePath(node.children, href, [...path, node]);
if (found) return found;
}
}
return null;
}
export function getDocBreadcrumbGroups(doc: Doc, tree: DocsNavNode[]): { label: string }[] {
const path = findNodePath(tree, doc.href);
if (!path) return [];
return path
.slice(0, -1)
.filter((node): node is Extract<DocsNavNode, { type: "group" }> => node.type === "group")
.map((node) => ({ label: node.label }));
}