| 1 | /** |
| 2 | * Returns true when `linkHref` matches the current page `pathname` — |
| 3 | * used to mark nav links as active. Exact match for "/", prefix match otherwise. |
| 4 | * @param {string} pathname |
| 5 | * @param {string} [linkHref] |
| 6 | * @returns {boolean} |
| 7 | */ |
| 8 | export function isCurrentPath(pathname, linkHref) { |
| 9 | if (!linkHref) return false; |
| 10 | if (linkHref === '/') return pathname === '/'; |
| 11 | return pathname.startsWith(linkHref); |
| 12 | } |
| 13 | |
| 14 | /** |
| 15 | * Format a date as `Sep 5, 2024` (short) or `September 5, 2024` (long). |
| 16 | * 4-digit year strings (`"2021"`) are returned as-is. |
| 17 | * @param {Date|string|null|undefined} value |
| 18 | * @param {'short'|'long'} [format='short'] |
| 19 | * @returns {string} |
| 20 | */ |
| 21 | export function formatDate(value, format = 'short') { |
| 22 | if (!value) return ''; |
| 23 | if (typeof value === 'string' && /^\d{4}$/.test(value)) return value; |
| 24 | const d = value instanceof Date ? value : new Date(value); |
| 25 | return d.toLocaleDateString('en-US', { month: format, day: 'numeric', year: 'numeric' }); |
| 26 | } |
| 27 | |
| 28 | /** |
| 29 | * Converts any string into a URL-safe slug. |
| 30 | * Handles special characters, whitespace, unicode, file paths, and number prefixes. |
| 31 | * |
| 32 | * Examples: |
| 33 | * - "Alex Petros" → "alex-petros" |
| 34 | * - "JetBrains" → "jetbrains" |
| 35 | * - "Stack Overflow" → "stack-overflow" |
| 36 | * - "02-forms/05-reset-on-submit.md" → "forms/reset-on-submit" |
| 37 | * |
| 38 | * @param {string} str |
| 39 | * @returns {string} |
| 40 | */ |
| 41 | export function slugify(str) { |
| 42 | return str |
| 43 | // Remove common file extensions |
| 44 | .replace(/\.(astro|md|mdx|json|yaml|yml|toml)$/, '') |
| 45 | // Split by slash for path handling |
| 46 | .split('/') |
| 47 | .map(part => |
| 48 | part |
| 49 | // Remove number prefixes like "01-" |
| 50 | .replace(/^\d+-/, '') |
| 51 | .toLowerCase() |
| 52 | .trim() |
| 53 | // Remove special characters (keep word chars, spaces, hyphens) |
| 54 | .replace(/[^\w\s-]/g, '') |
| 55 | // Collapse whitespace/underscores/hyphens to single hyphen |
| 56 | .replace(/[\s_-]+/g, '-') |
| 57 | // Remove leading/trailing hyphens |
| 58 | .replace(/^-+|-+$/g, '') |
| 59 | ) |
| 60 | .join('/'); |
| 61 | } |
| 62 | |
| 63 | /** |
| 64 | * Rewrite root-relative markdown links `](/foo)` to absolute `](origin/foo)`. |
| 65 | * Used when serving a markdown document from a context where relative links |
| 66 | * won't resolve (llms.txt consumers, raw `.md` exports). |
| 67 | * |
| 68 | * @param {string} markdown |
| 69 | * @param {string} origin |
| 70 | * @returns {string} |
| 71 | */ |
| 72 | export function absolutizeRelativeLinks(markdown, origin) { |
| 73 | return markdown.replace(/\]\(\//g, `](${origin}/`); |
| 74 | } |