Skip to content
Myr

article.ts

This file

Path

apps/web/src/features/docs/article.ts

73 lines · 2.0 KiB · TypeScript

Last changed by

Merge redesign into mainoscabrielbefore adoptioncaedd21

History of this file

Take it

Merge redesign into mainoscabrielbefore adoptioncaedd21

lines 1–73why, one step back
1/**
2 * A doc's article and its headings. The ids repeat what `rehype-slug` gives3 * the rendered headings (GitHub's slugs, numbered on a repeat), so "On this4 * page" links each one; `test/docs.test.tsx` holds the two equal on every page.5 */6import type { DocPage } from "@repo/agent-kit/docs/index";78export interface DocHeading {9 readonly id: string;10 readonly text: string;11}1213/** The Markdown under the page's title and summary, which the page draws itself. */14export const docBody = ({ markdown, summary, title }: DocPage) =>15 markdown.slice(`# ${title}\n\n${summary}\n\n`.length);1617const HEADING = /^(?<marks>#{1,6}) (?<source>.+)$/u;1819const FENCE = /^(?:```|~~~)/u;2021/** A heading's text as it reads on the page: no code ticks, emphasis or link targets. */22const plain = (source: string) =>23 source24 .replaceAll(/\[(?<label>[^\]]*)\]\([^)]*\)/gu, "$<label>")25 .replaceAll(/[`*]/gu, "")26 .trim();2728const slugOf = (text: string) =>29 text30 .toLowerCase()31 .replaceAll(/[^\p{L}\p{M}\p{N}\p{Pc} -]/gu, "")32 .replaceAll(" ", "-");3334const unique = (seen: ReadonlyMap<string, number>, slug: string) => {35 let count = seen.get(slug);36 let id = slug;3738 while (seen.has(id)) {39 count = (count ?? 0) + 1;40 id = `${slug}-${count}`;41 }4243 return { count: count ?? 0, id };44};4546/** The article's `h2`s, in order, each with the id its rendered heading carries. */47export const docHeadings = (page: DocPage): readonly DocHeading[] => {48 const seen = new Map<string, number>();49 const headings: DocHeading[] = [];50 let fenced = false;5152 for (const line of docBody(page).split("\n")) {53 if (FENCE.test(line)) {54 fenced = !fenced;55 }5657 const found = fenced ? null : HEADING.exec(line);5859 if (found?.groups !== undefined) {60 const text = plain(found.groups.source ?? "");61 const slug = slugOf(text);62 const { count, id } = unique(seen, slug);6364 seen.set(slug, count).set(id, 0);6566 if (found.groups.marks === "##") {67 headings.push({ id, text });68 }69 }70 }7172 return headings;73};