Skip to content

📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

4.3 KB
Raw Blame
interface TocItem {
  id: string
  text: string
  level: number
  children: TocItem[]
}

export interface ArticleHeading {
  id: string
  text: string
  level: number
}

import { escapeHtml } from './generic'

function stripHtmlTags(input: string): string {
  const tagRegex = /<[^>]*>/g
  let result = input
  let previous: string

  // Repeatedly remove HTML tags until no more changes occur
  do {
    previous = result
    result = result.replace(tagRegex, '')
  } while (result !== previous)

  return result.trim()
}

function generateSlug(text: string): string {
  return text
    .toLowerCase()
    .replace(/[^\w\s-]/g, '') // Remove special characters except spaces and hyphens
    .replace(/\s+/g, '-') // Replace spaces with hyphens
    .replace(/-+/g, '-') // Replace multiple hyphens with single hyphen
    .trim()
}

export function renderTocAsHtml(items: TocItem[]): string {
  if (items.length === 0) return ''

  const renderTocList = (
    tocItems: TocItem[],
    level = 0,
    parentNum = '',
  ): string => {
    if (tocItems.length === 0) return ''

    let html = `<ol class="${level > 0 ? '!my-0' : ''}">`

    tocItems.forEach((item, index) => {
      const currentNumber = parentNum
        ? `${parentNum}.${index + 1}`
        : `${index + 1}`

      html += `<li class="flex flex-col">`
      html += `<div class="flex items-start gap-0.5">`
      html += `<span class="text-gray-600 dark:text-gray-400 font-medium mr-[1ch]">${currentNumber}.</span>`
      html += `<a href="#${escapeHtml(item.id)}">${escapeHtml(item.text)}</a>`
      html += `</div>`

      if (item.children.length > 0) {
        html += renderTocList(item.children, level + 1, currentNumber)
      }

      html += `</li>`
    })

    html += `</ol>`
    return html
  }

  const tocHtml = renderTocList(items)

  return tocHtml
}

export function extractTableOfContents(html: string): TocItem[] {
  const headerRegex = /<h([1-6])(?:\s+id="([^"]*)")?[^>]*>(.*?)<\/h[1-6]>/gi
  const tocItems: TocItem[] = []
  const stack: TocItem[] = []
  let match

  while ((match = headerRegex.exec(html)) !== null) {
    const level = parseInt(match[1])
    const existingId = match[2]
    const text = stripHtmlTags(match[3])
    const id = existingId || generateSlug(text)

    const tocItem: TocItem = {
      id,
      text,
      level,
      children: [],
    }

    // Pop stack until we find a parent with lower level
    while (stack.length > 0 && stack[stack.length - 1].level >= level) {
      stack.pop()
    }

    if (stack.length === 0) {
      // Top level item
      tocItems.push(tocItem)
    } else {
      // Child item
      stack[stack.length - 1].children.push(tocItem)
    }

    stack.push(tocItem)
  }

  return tocItems
}

export function ensureHeaderIds(html: string): string {
  const used = new Set<string>()
  return html.replace(
    /<h([1-6])(?:\s+id="([^"]*)")?([^>]*)>(.*?)<\/h[1-6]>/gi,
    (match, level, existingId, attrs, content) => {
      const text = stripHtmlTags(content)
      const base = existingId || generateSlug(text) || 'section'
      let id = base
      let suffix = 2
      while (used.has(id)) id = `${base}-${suffix++}`
      used.add(id)

      return `<h${level} id="${id}"${attrs}>${content}</h${level}>`
    },
  )
}

export function extractArticleHeadings(html: string): ArticleHeading[] {
  const headings: ArticleHeading[] = []
  const collect = (items: TocItem[]) => {
    for (const item of items) {
      if (item.level === 2 || item.level === 3) {
        const text = item.text.replace(
          /&(#x[\da-f]+|#\d+|amp|lt|gt|quot|apos|nbsp);/gi,
          (entity, name: string) => {
            const named: Record<string, string> = {
              amp: '&',
              lt: '<',
              gt: '>',
              quot: '"',
              apos: "'",
              nbsp: ' ',
            }
            if (!name.startsWith('#'))
              return named[name.toLowerCase()] || entity
            const value =
              name[1].toLowerCase() === 'x'
                ? parseInt(name.slice(2), 16)
                : Number(name.slice(1))
            return value > 0 && value <= 0x10ffff
              ? String.fromCodePoint(value)
              : entity
          },
        )
        headings.push({ id: item.id, text, level: item.level })
      }
      collect(item.children)
    }
  }
  collect(extractTableOfContents(html))
  return headings
}