| 1 | /** Which of a repository's files are its docs in Docs, and their titles (src/repo-spaces.ts). Pure. */ |
| 2 | |
| 3 | /** Files kept per repository: the first this many Markdown files, README first, then by path. */ |
| 4 | export const MAX_REPO_FILES = 300; |
| 5 | |
| 6 | /** Whether a path is one of a project's docs: Markdown under `docs/`, or the README at the root. */ |
| 7 | export function isRepoDoc(path: string): boolean { |
| 8 | if (/^readme\.(md|markdown|mdx)$/i.test(path)) return true; |
| 9 | return /^docs\/.+\.(md|markdown|mdx)$/i.test(path); |
| 10 | } |
| 11 | |
| 12 | /** A file's title: its first heading, the `title:` of its front matter, or its name. */ |
| 13 | export function repoDocTitle(path: string, markdown: string): string { |
| 14 | const front = /^---\r?\n([\s\S]*?)\r?\n---/.exec(markdown); |
| 15 | const fromFront = front ? /^title:\s*["']?(.+?)["']?\s*$/m.exec(front[1]!)?.[1] : null; |
| 16 | if (fromFront) return fromFront.slice(0, 200); |
| 17 | const body = front ? markdown.slice(front[0].length) : markdown; |
| 18 | const heading = /^\s{0,3}#\s+(.+?)\s*#*\s*$/m.exec(body)?.[1]; |
| 19 | if (heading) return heading.replace(/[*_`]/g, "").slice(0, 200); |
| 20 | const name = path.split("/").pop()!.replace(/\.(md|markdown|mdx)$/i, ""); |
| 21 | if (/^readme$/i.test(name)) return path.includes("/") ? path.split("/").slice(-2, -1)[0]! : "README"; |
| 22 | return name.replace(/[-_]+/g, " ").replace(/^\w/, (c) => c.toUpperCase()); |
| 23 | } |
| 24 | |
| 25 | /** The docs files in a listing, README first, then by path; at most MAX_REPO_FILES. */ |
| 26 | export function pickRepoDocs<T extends { path: string }>(files: T[]): T[] { |
| 27 | return files |
| 28 | .filter((f) => isRepoDoc(f.path)) |
| 29 | .sort((a, b) => { |
| 30 | const ra = a.path.toLowerCase().startsWith("readme.") ? 0 : 1; |
| 31 | const rb = b.path.toLowerCase().startsWith("readme.") ? 0 : 1; |
| 32 | return ra - rb || a.path.localeCompare(b.path); |
| 33 | }) |
| 34 | .slice(0, MAX_REPO_FILES); |
| 35 | } |
| 36 | |