summaryrefslogtreecommitdiffstats
path: root/src/components/organisms/widgets/table-of-contents.tsx
blob: 800ff58c39e1047bf56cb15addd73723e2714dbd (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
50
51
52
53
54
55
import useHeadingsTree, { type Heading } from '@utils/hooks/use-headings-tree';
import { FC } from 'react';
import { useIntl } from 'react-intl';
import LinksListWidget, { type LinksListItems } from './links-list-widget';
import styles from './table-of-contents.module.scss';

type TableOfContentsProps = {
  /**
   * A reference to the HTML element that contains the headings.
   */
  wrapper: HTMLElement;
};

/**
 * Table of Contents widget component
 *
 * Render a table of contents.
 */
const TableOfContents: FC<TableOfContentsProps> = ({ wrapper }) => {
  const intl = useIntl();
  const headingsTree = useHeadingsTree(wrapper);
  const title = intl.formatMessage({
    defaultMessage: 'Table of Contents',
    description: 'TableOfContents: the widget title',
    id: 'WKG9wj',
  });

  /**
   * Convert an headings tree to list items.
   *
   * @param {Heading[]} tree - The headings tree.
   * @returns {LinksListItems[]} The list items.
   */
  const getItems = (tree: Heading[]): LinksListItems[] => {
    return tree.map((heading) => {
      return {
        name: heading.title,
        url: `#${heading.id}`,
        child: getItems(heading.children),
      };
    });
  };

  return (
    <LinksListWidget
      kind="ordered"
      title={title}
      level={2}
      items={getItems(headingsTree)}
      className={styles.list}
    />
  );
};

export default TableOfContents;