From 7a729db684f4bc54f8376aeee242511a1cb06aaf Mon Sep 17 00:00:00 2001 From: Niraj Acharya Date: Thu, 29 Feb 2024 16:50:08 +0545 Subject: [PATCH] adding collapsible table of content --- src/components/detail/ContentSidebar.vue | 29 +-------- src/components/detail/TOC.vue | 81 ++++++++++++++++++++++++ src/helpers/markdown.js | 44 ++++++++++++- 3 files changed, 124 insertions(+), 30 deletions(-) create mode 100644 src/components/detail/TOC.vue diff --git a/src/components/detail/ContentSidebar.vue b/src/components/detail/ContentSidebar.vue index d6b2fb9..2791447 100644 --- a/src/components/detail/ContentSidebar.vue +++ b/src/components/detail/ContentSidebar.vue @@ -2,14 +2,7 @@
Table of content
-
- - {{ item.text }} -
+

Tags
@@ -28,6 +21,7 @@ diff --git a/src/helpers/markdown.js b/src/helpers/markdown.js index 71f6f8c..8012369 100644 --- a/src/helpers/markdown.js +++ b/src/helpers/markdown.js @@ -84,12 +84,50 @@ export const getTableOfContent = (source) => { const tokens = marked.lexer(source) // remove the first 2 tokens to avoid meta information // and then return every tokens that is of header type - const headers = tokens.slice(2).filter(token => token.type === "heading" && token.depth <= 4) - headers.forEach(header => { + const hg = [] + const headers = tokens + .slice(2) + .filter((token) => token.type === "heading")// && token.depth <= 4) + headers.forEach((header) => { const html = marked.parser([header]) const doc = new DOMParser().parseFromString(html, "text/xml") header.id = doc.firstChild.id header.text = doc.firstChild.textContent + hg.push(new Graph(header.depth, header.text, header.id, null)) }) - return headers + const stack = [hg[0]] + const ans = [] + hg.forEach((h) => { + if (h.val === stack[0].val) { + ans.push(h) + stack.push(h) + } else if (h.val > stack[stack.length - 1].val) { + stack[stack.length - 1].addNode(h) + stack.push(h) + } else if (h.val < stack[stack.length - 1].val) { + while (!(h.val > stack[stack.length - 1].val)) { + stack.splice(stack.length - 1, 1) + } + stack[stack.length - 1].addNode(h) + stack.push(h) + } else { + stack.splice(stack.length - 1, 1) + stack[stack.length - 1].addNode(h) + stack.push(h) + } + }) + return ans +} + +class Graph { + constructor (val, title, id) { + this.val = val + this.title = title + this.id = id + this.node = [] + } + + addNode (node) { + this.node.push(node) + } }