diff --git a/components/context/ArticleContext.tsx b/components/context/ArticleContext.tsx index 5e314879f5..1c6535da21 100644 --- a/components/context/ArticleContext.tsx +++ b/components/context/ArticleContext.tsx @@ -8,7 +8,7 @@ export type LearningTrack = { } export type MiniTocItem = { - platform: string + platform?: string contents: { href: string title: string diff --git a/lib/get-mini-toc-items.js b/lib/get-mini-toc-items.js index 4ab4dc63f6..537ea5cd12 100644 --- a/lib/get-mini-toc-items.js +++ b/lib/get-mini-toc-items.js @@ -1,12 +1,7 @@ import cheerio from 'cheerio' import { range } from 'lodash-es' -export default function getMiniTocItems( - html, - maxHeadingLevel = 2, - headingScope = '', - isRestPage = false -) { +export default function getMiniTocItems(html, maxHeadingLevel = 2, headingScope = '') { const $ = cheerio.load(html, { xmlMode: true }) // eg `h2, h3` or `h2, h3, h4` depending on maxHeadingLevel @@ -67,7 +62,7 @@ export default function getMiniTocItems( // convert the flatToc to a nested structure to simplify semantic rendering on the client const nestedToc = buildNestedToc(flatToc) - return nestedToc + return minimalMiniToc(nestedToc) } // Recursively build a tree from the list of allItems @@ -116,3 +111,15 @@ function buildNestedToc(allItems, startIndex = 0) { return currentLevel } + +// Strip the bits and pieces from each object in the array that are +// not needed in the React component rendering. +function minimalMiniToc(toc) { + return toc.map(({ platform, contents, items }) => { + const minimal = { contents } + const subItems = minimalMiniToc(items) + if (subItems.length) minimal.items = subItems + if (platform) minimal.platform = platform + return minimal + }) +} diff --git a/tests/unit/mini-toc-items.js b/tests/unit/mini-toc-items.js index d52ac8323f..5344c77377 100644 --- a/tests/unit/mini-toc-items.js +++ b/tests/unit/mini-toc-items.js @@ -63,7 +63,7 @@ describe('mini toc items', () => { ` const tocItems = getMiniTocItems(html, 3) expect(tocItems.length).toBe(2) - expect(tocItems[0].items.length).toBe(0) + expect(tocItems[0].items).toBeUndefined() }) test('handles deeply nested toc', async () => {