aboutsummaryrefslogtreecommitdiffstats
path: root/src/components/Widgets/ToC/ToC.tsx
blob: 89ca8d47c9ab40aba82f814c6dabd1f1df4ee6a9 (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
import { ExpandableWidget, OrderedList } from '@components/WidgetParts';
import { Heading } from '@ts/types/app';
import useHeadingsTree from '@utils/hooks/useHeadingsTree';
import { FormattedMessage, useIntl } from 'react-intl';

const ToC = () => {
  const intl = useIntl();
  const headingsTree = useHeadingsTree('article');
  const title = intl.formatMessage({
    defaultMessage: 'Table of contents',
    description: 'ToC: widget title',
  });

  const getItems = (headings: Heading[]) => {
    return headings.map((heading) => {
      return (
        <li key={heading.id}>
          <a href={`#${heading.id}`}>
            <FormattedMessage
              defaultMessage="<a11y>Jump to </a11y>{title}"
              description="ToC: link"
              values={{
                title: heading.title,
                a11y: (chunks: string) => (
                  <span className="screen-reader-text">{chunks}</span>
                ),
              }}
            />
          </a>
          {heading.children.length > 0 && (
            <OrderedList items={getItems(heading.children)} />
          )}
        </li>
      );
    });
  };

  return (
    <ExpandableWidget title={title} kind="toc" expand={true} withBorders={true}>
      <noscript>
        {intl.formatMessage({
          defaultMessage:
            'Javascript is required to use the table of contents.',
          description: 'ToC: noscript tag',
        })}
      </noscript>
      <OrderedList items={getItems(headingsTree)} />
    </ExpandableWidget>
  );
};

export default ToC;