docs/.vitepress/utils/tabAnchors.ts

33a4e4c6fa7d78deb08b14d2b151ff82c28e461a
wotaku/docs/.vitepress/utils/tabAnchors.ts history · blame · raw

61 lines · 1592 bytes

 1const rControl = /[\u0000-\u001f]/g
 2const rSpecial = /[\s~`!@#$%^&*()\-_+=[\]{}|\\;:"'“”‘’<>,.?/]+/g
 3const rCombining = /[\u0300-\u036F]/g
 4
 5export interface ParsedTabLabel {
 6  anchor?: string
 7  label: string
 8}
 9
10export function stripHeadingMarkup(value: string) {
11  return value
12    .replace(/\{[^}]*\}\s*$/, '')
13    .replace(/<[^>]*>/g, '')
14    .replace(/`([^`]+)`/g, '$1')
15    .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
16    .replace(/[*_~]/g, '')
17    .trim()
18}
19
20export function slugifyAnchor(value: string) {
21  return stripHeadingMarkup(value)
22    .normalize('NFKD')
23    .replace(rCombining, '')
24    .replace(rControl, '')
25    .replace(rSpecial, '-')
26    .replace(/-{2,}/g, '-')
27    .replace(/^-+|-+$/g, '')
28    .replace(/^(\d)/, '_$1')
29    .toLowerCase()
30}
31
32export function parseTabLabel(value: string): ParsedTabLabel {
33  const trimmed = value.trim()
34  const match = trimmed.match(/\s+\{#([^}\s]+)\}\s*$/)
35  if (!match) return { label: trimmed }
36
37  return {
38    anchor: match[1],
39    label: trimmed.slice(0, match.index).trim()
40  }
41}
42
43export function getUniqueAnchor(base: string, counts: Map<string, number>) {
44  const fallback = 'tab'
45  const slug = slugifyAnchor(base) || fallback
46  const count = counts.get(slug) ?? 0
47  counts.set(slug, count + 1)
48  return count === 0 ? slug : `${slug}-${count}`
49}
50
51export function getTabAnchor(
52  rawLabel: string,
53  counts: Map<string, number>
54) {
55  const parsed = parseTabLabel(rawLabel)
56  return parsed.anchor || getUniqueAnchor(parsed.label, counts)
57}
58
59export function getTabHeadingAnchor(tabAnchor: string) {
60  return `tab-${tabAnchor}`
61}