Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

get-mini-toc-items.js 1.8 KB

You have to be logged in to leave a comment. Sign In
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
  1. const cheerio = require('cheerio')
  2. const { range } = require('lodash')
  3. module.exports = function getMiniTocItems (html, maxHeadingLevel = 3, headingScope = '') {
  4. const $ = cheerio.load(html, { xmlMode: true })
  5. // eg `h2, h3` or `h2, h3, h4` depending on maxHeadingLevel
  6. const selector = range(2, maxHeadingLevel + 1).map(num => `${headingScope} h${num}`).join(', ')
  7. const headings = $(selector)
  8. // return an array of objects containing each heading's contents, level, and optional platform.
  9. // layouts/article.html uses these as follows:
  10. // - `contents` to render the mini TOC headings
  11. // - `headingLevel` the `2` in `h2`; used for determining required indentation
  12. // - `platform` to show or hide platform-specific headings via client JS
  13. const items = headings
  14. .get()
  15. .filter(item => {
  16. if (!item.parent || !item.parent.attribs) return true
  17. // Hide any items that belong to a hidden div
  18. const { attribs } = item.parent
  19. return !('hidden' in attribs)
  20. })
  21. .map(item => {
  22. // remove any <span> tags including their content
  23. $('span').remove()
  24. // remove any <strong> tags but leave content
  25. $('strong').map((i, el) => $(el).replaceWith($(el).contents()))
  26. const contents = $(item).html()
  27. const headingLevel = Number($(item)[0].name.replace(/^h/, '')) // the `2` from `h2`
  28. const platform = $(item).parent('.extended-markdown').attr('class')
  29. return { contents, headingLevel, platform }
  30. })
  31. // determine indentation level for each item based on the largest
  32. // heading level in the current article
  33. const largestHeadingLevel = items.map(item => item.headingLevel).sort()[0]
  34. items.forEach(item => {
  35. item.indentationLevel = item.headingLevel - largestHeadingLevel
  36. })
  37. return items
  38. }
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...