All files / src/templates/sections toc.ts

100% Statements 9/9
100% Branches 4/4
100% Functions 2/2
100% Lines 9/9

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44                                            6x 1x     5x   5x   6x 6x 6x 6x       5x            
// SPDX-FileCopyrightText: 2024-2026 Hack23 AB
// SPDX-License-Identifier: Apache-2.0
 
/**
 * @module Templates/Sections/TOC
 * @description Table-of-contents navigation builder for article pages.
 * Split out of `section-builders.ts` (Refactor 8/8) so each section
 * builder can be unit-tested in isolation.
 */
 
import { escapeHTML } from '../../utils/file-utils.js';
import type { TOCEntry, LanguageCode } from '../../types/index.js';
import { getLocalizedString, TOC_ARIA_LABELS } from '../../constants/languages.js';
 
/**
 * Build an HTML table of contents navigation element from a list of entries.
 *
 * @param entries - Ordered list of {@link TOCEntry} items to render.
 * @param lang - Language code used for the localised aria-label.
 * @returns HTML string for the TOC `<nav>` element, or empty string when entries is empty.
 */
export function buildTableOfContents(entries: TOCEntry[], lang: LanguageCode): string {
  if (entries.length === 0) {
    return '';
  }
 
  const ariaLabel = escapeHTML(getLocalizedString(TOC_ARIA_LABELS, lang));
 
  const items = entries
    .map((entry) => {
      const safeLabel = escapeHTML(entry.label);
      const safeId = escapeHTML(entry.id.replace(/^#/, ''));
      const classAttr = entry.level === 2 ? ' class="toc-sub"' : '';
      return `<li${classAttr}><a href="#${safeId}">${safeLabel}</a></li>`;
    })
    .join('\n      ');
 
  return `<nav class="article-toc" aria-label="${ariaLabel}">
  <ol>
      ${items}
  </ol>
</nav>`;
}