|
| 1 | +/** |
| 2 | + * Estimate reading time for Markdown/MDX content. |
| 3 | + * |
| 4 | + * This is intentionally lightweight (no external deps) and runs at build-time. |
| 5 | + * It strips common Markdown/MDX constructs (frontmatter, code blocks, tags, imports) |
| 6 | + * before counting words. |
| 7 | + */ |
| 8 | + |
| 9 | +const defaultWordsPerMinute = 200 |
| 10 | + |
| 11 | +export function getReadingTimeLabel( |
| 12 | + content: string, |
| 13 | + options?: { |
| 14 | + wordsPerMinute?: number |
| 15 | + } |
| 16 | +): string | undefined { |
| 17 | + const wordsPerMinute = options?.wordsPerMinute ?? defaultWordsPerMinute |
| 18 | + if (!Number.isFinite(wordsPerMinute) || wordsPerMinute <= 0) return undefined |
| 19 | + |
| 20 | + const wordCount = countWords(stripMarkdownForReadingTime(content)) |
| 21 | + if (wordCount <= 0) return undefined |
| 22 | + |
| 23 | + const minutes = Math.max(1, Math.ceil(wordCount / wordsPerMinute)) |
| 24 | + return `${minutes} min read` |
| 25 | +} |
| 26 | + |
| 27 | +function stripMarkdownForReadingTime(content: string): string { |
| 28 | + // Remove YAML frontmatter if present (defensive; Astro collection body usually excludes it). |
| 29 | + const withoutFrontmatter = content.replace(/^---\s*[\s\S]*?\s*---\s*/m, ' ') |
| 30 | + |
| 31 | + // Remove fenced code blocks. |
| 32 | + const withoutFences = withoutFrontmatter.replace(/```[\s\S]*?```/g, ' ') |
| 33 | + |
| 34 | + // Remove inline code. |
| 35 | + const withoutInlineCode = withoutFences.replace(/`[^`]*`/g, ' ') |
| 36 | + |
| 37 | + // Remove MDX/ESM imports/exports. |
| 38 | + const withoutImports = withoutInlineCode |
| 39 | + .replace(/^\s*import\s+[^;\n]+;?\s*$/gm, ' ') |
| 40 | + .replace(/^\s*export\s+[^;\n]+;?\s*$/gm, ' ') |
| 41 | + |
| 42 | + // Remove JSX/HTML tags. |
| 43 | + const withoutTags = withoutImports.replace(/<[^>]+>/g, ' ') |
| 44 | + |
| 45 | + // Collapse links/images to their visible text. |
| 46 | + const withoutImages = withoutTags.replace(/!\[[^\]]*\]\([^)]*\)/g, ' ') |
| 47 | + const withoutLinks = withoutImages.replace(/\[([^\]]+)\]\([^)]*\)/g, '$1') |
| 48 | + |
| 49 | + return withoutLinks |
| 50 | +} |
| 51 | + |
| 52 | +function countWords(text: string): number { |
| 53 | + const matches = text.match(/[\p{L}\p{N}]+(?:['’][\p{L}\p{N}]+)*/gu) |
| 54 | + return matches ? matches.length : 0 |
| 55 | +} |
0 commit comments