Skip to content

Commit 2f37efd

Browse files
authored
minimize content in miniToc prop (github#28522)
* make miniToc pure data and no html strings * fixups * minimize content in miniToc prop * minimize content in miniToc prop * some types refactoring * fix tests
1 parent 8f83f60 commit 2f37efd

File tree

3 files changed

+16
-9
lines changed

3 files changed

+16
-9
lines changed

components/context/ArticleContext.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ export type LearningTrack = {
88
}
99

1010
export type MiniTocItem = {
11-
platform: string
11+
platform?: string
1212
contents: {
1313
href: string
1414
title: string

lib/get-mini-toc-items.js

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,7 @@
11
import cheerio from 'cheerio'
22
import { range } from 'lodash-es'
33

4-
export default function getMiniTocItems(
5-
html,
6-
maxHeadingLevel = 2,
7-
headingScope = '',
8-
isRestPage = false
9-
) {
4+
export default function getMiniTocItems(html, maxHeadingLevel = 2, headingScope = '') {
105
const $ = cheerio.load(html, { xmlMode: true })
116

127
// eg `h2, h3` or `h2, h3, h4` depending on maxHeadingLevel
@@ -67,7 +62,7 @@ export default function getMiniTocItems(
6762
// convert the flatToc to a nested structure to simplify semantic rendering on the client
6863
const nestedToc = buildNestedToc(flatToc)
6964

70-
return nestedToc
65+
return minimalMiniToc(nestedToc)
7166
}
7267

7368
// Recursively build a tree from the list of allItems
@@ -116,3 +111,15 @@ function buildNestedToc(allItems, startIndex = 0) {
116111

117112
return currentLevel
118113
}
114+
115+
// Strip the bits and pieces from each object in the array that are
116+
// not needed in the React component rendering.
117+
function minimalMiniToc(toc) {
118+
return toc.map(({ platform, contents, items }) => {
119+
const minimal = { contents }
120+
const subItems = minimalMiniToc(items)
121+
if (subItems.length) minimal.items = subItems
122+
if (platform) minimal.platform = platform
123+
return minimal
124+
})
125+
}

tests/unit/mini-toc-items.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ describe('mini toc items', () => {
6363
`
6464
const tocItems = getMiniTocItems(html, 3)
6565
expect(tocItems.length).toBe(2)
66-
expect(tocItems[0].items.length).toBe(0)
66+
expect(tocItems[0].items).toBeUndefined()
6767
})
6868

6969
test('handles deeply nested toc', async () => {

0 commit comments

Comments
 (0)