/* ═══════════════════════════════════════════════════════════════ CONTENTS The headings in a list of content blocks, with the anchor id each one gets: ContentBlocks puts the ids on the headings, and PostContents lists them. Both call headingAnchors on the same blocks, so the links always match. An id is the heading's text as a slug ("Getting there" → "getting-there"); a repeat gets -2, -3. ═══════════════════════════════════════════════════════════════ */ import type { ContentBlock } from './useContent.ts' export type ContentsEntry = { id: string; text: string; level: 1 | 2 } const slug = (text: string) => text .toLowerCase() .normalize('NFKD') .replace(/[^\w\s-]/g, '') .trim() .replace(/[\s_]+/g, '-') .replace(/-+/g, '-') .slice(0, 60) || 'section' /* One entry per heading or subheading block, in order, and the id for each block index that is one. prefix keeps a blog post's tabs apart (splitTabs): "Overview" in two tabs is two ids. */ export function headingAnchors(blocks?: ContentBlock[] | null, prefix = ''): { entries: ContentsEntry[] idAt: Map } { const entries: ContentsEntry[] = [] const idAt = new Map() const seen = new Map() ;(blocks ?? []).forEach((block, index) => { if (block.type !== 'heading' && block.type !== 'subheading') return const text = (block.text ?? '').trim() if (!text) return const base = slug(text) const n = (seen.get(base) ?? 0) + 1 seen.set(base, n) const id = `${prefix}${n === 1 ? base : `${base}-${n}`}` idAt.set(index, id) entries.push({ id, text, level: block.type === 'heading' ? 1 : 2 }) }) return { entries, idAt } } /* ── A blog post's tabs (079) ────────────────────────────────── A 'tab' block starts a tab, titled by its text, holding the blocks after it up to the next; the blocks before the first are the intro above the tabs. Each tab's heading ids start with its own, so the same heading in two tabs is two ids; the intro's keep their plain ids. */ export type PostTab = { id: string; title: string; prefix: string; blocks: ContentBlock[] } export function splitTabs(blocks?: ContentBlock[] | null): { intro: ContentBlock[]; tabs: PostTab[] } { const intro: ContentBlock[] = [] const tabs: PostTab[] = [] const seen = new Map() for (const block of blocks ?? []) { if (block.type === 'tab') { const title = (block.text ?? '').trim() || `Part ${tabs.length + 1}` const base = `tab-${slug(title)}` const n = (seen.get(base) ?? 0) + 1 seen.set(base, n) const id = n === 1 ? base : `${base}-${n}` tabs.push({ id, title, prefix: `${id}-`, blocks: [] }) } else if (tabs.length) { tabs[tabs.length - 1].blocks.push(block) } else { intro.push(block) } } return { intro, tabs } }