Welcome to mirror list, hosted at ThFree Co, Russian Federation.

dom_parse_toc.js « shared « frontend « content - gitlab.com/gitlab-org/gitlab-docs.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 552550a1ddd4454ec18dec9f97379cf5db18d013 (plain)
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
45
46
47
48
49
/* eslint-disable import/prefer-default-export */
import { findChildByTagName } from './dom';

const TAG_LI = 'LI';
const TAG_A = 'A';
const TAG_UL = 'UL';

/**
 * Parses the given HTML Table of Contents into a data structure
 *
 * ```
 * type Item = { text: String, href: String, id: String, items: Item[] }
 *
 * parseTOC: Element => Item[]
 * ```
 *
 * @param {Element} menu Parent <ul> element
 */
export const parseTOC = menu => {
  const items = [];

  if (!menu) {
    return items;
  }

  menu.childNodes.forEach(li => {
    if (li.tagName !== TAG_LI) {
      return;
    }

    const link = findChildByTagName(li, TAG_A);
    const subMenu = findChildByTagName(li, TAG_UL);

    if (!link) {
      return;
    }

    const item = {
      text: link.textContent,
      href: link.getAttribute('href'),
      id: link.id,
      items: parseTOC(subMenu),
    };

    items.push(item);
  });

  return items;
};