From 926e1df1e9a7de29134293fe2306c9d9ecb594a6 Mon Sep 17 00:00:00 2001
From: Armand Philippot <git@armandphilippot.com>
Date: Tue, 21 Dec 2021 15:20:17 +0100
Subject: chore: add a table of contents

---
 src/components/ToC/ToC.tsx | 31 +++++++++++++++++++++++++++++++
 1 file changed, 31 insertions(+)
 create mode 100644 src/components/ToC/ToC.tsx

(limited to 'src/components/ToC/ToC.tsx')

diff --git a/src/components/ToC/ToC.tsx b/src/components/ToC/ToC.tsx
new file mode 100644
index 0000000..e7aafa5
--- /dev/null
+++ b/src/components/ToC/ToC.tsx
@@ -0,0 +1,31 @@
+import { t } from '@lingui/macro';
+import { Heading } from '@ts/types/app';
+import { slugify } from '@utils/helpers/slugify';
+import useHeadingsTree from '@utils/hooks/useHeadingsTree';
+
+const ToC = () => {
+  const headingsTree = useHeadingsTree('article');
+  const title = t`Table of contents`;
+
+  const getItems = (headings: Heading[]) => {
+    return headings.map((heading) => {
+      if (heading.id === slugify(title)) return;
+
+      return (
+        <li key={heading.id}>
+          <a href={`#${heading.id}`}>{heading.title}</a>
+          {heading.children.length > 0 && <ol>{getItems(heading.children)}</ol>}
+        </li>
+      );
+    });
+  };
+
+  return (
+    <>
+      <h2>{title}</h2>
+      <ol>{getItems(headingsTree)}</ol>
+    </>
+  );
+};
+
+export default ToC;
-- 
cgit v1.2.3

