aboutsummaryrefslogtreecommitdiffstats
path: root/src/components/organisms/widgets/table-of-contents.tsx
diff options
context:
space:
mode:
authorArmand Philippot <git@armandphilippot.com>2022-04-22 18:33:04 +0200
committerArmand Philippot <git@armandphilippot.com>2022-04-22 18:33:04 +0200
commit947a06bfdfdc5bca62c27fa2ee27f0ab9fefa0ea (patch)
tree3207696494c9564f7a3d9092ce83471717da7dac /src/components/organisms/widgets/table-of-contents.tsx
parent52c185d0f23504fc6410cf36285968eff9e7b21f (diff)
chore: add a TableOfContents component
Diffstat (limited to 'src/components/organisms/widgets/table-of-contents.tsx')
-rw-r--r--src/components/organisms/widgets/table-of-contents.tsx53
1 files changed, 53 insertions, 0 deletions
diff --git a/src/components/organisms/widgets/table-of-contents.tsx b/src/components/organisms/widgets/table-of-contents.tsx
new file mode 100644
index 0000000..3778e02
--- /dev/null
+++ b/src/components/organisms/widgets/table-of-contents.tsx
@@ -0,0 +1,53 @@
+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';
+
+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)}
+ />
+ );
+};
+
+export default TableOfContents;