forked from github/docs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgeneric-toc.js
64 lines (53 loc) · 2.64 KB
/
generic-toc.js
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
const findPageInSiteTree = require('../../lib/find-page-in-site-tree')
// This module adds either flatTocItems or nestedTocItems to the context object for
// product, categorie, and map topic TOCs that don't have other layouts specified.
// They are rendered by includes/generic-toc-flat.html or inclueds/generic-toc-nested.html.
module.exports = async function genericToc (req, res, next) {
if (!req.context.page) return next()
if (req.context.currentLayoutName !== 'default') return next()
// This middleware can only run on product, category, and map topics.
if (req.context.page.documentType === 'homepage' || req.context.page.documentType === 'article') return next()
// This one product TOC is weird.
const isOneOffProductToc = req.context.page.relativePath === 'github/index.md'
// There are different types of TOC depending on the document type.
const tocTypes = {
product: 'flat',
category: 'nested',
mapTopic: 'flat'
}
// Find the current TOC type based on the current document type.
const currentTocType = tocTypes[req.context.page.documentType]
// Find the part of the site tree that corresponds to the current path.
const treePage = findPageInSiteTree(req.context.currentProductTree, req.context.currentEnglishTree, req.path)
// Conditionally run getTocItems() recursively.
let isRecursive
// Conditionally render intros.
let renderIntros
// Get an array of child links with intros and add it to the context object.
if (currentTocType === 'flat' && !isOneOffProductToc) {
isRecursive = false
renderIntros = true
req.context.genericTocFlat = await getTocItems(treePage.childPages, req.context, isRecursive, renderIntros)
}
// Get an array of child map topics and their child articles and add it to the context object.
if (currentTocType === 'nested' || isOneOffProductToc) {
isRecursive = !isOneOffProductToc
renderIntros = false
req.context.genericTocNested = await getTocItems(treePage.childPages, req.context, isRecursive, renderIntros)
}
return next()
}
async function getTocItems (pagesArray, context, isRecursive, renderIntros) {
return (await Promise.all(pagesArray.map(async (child) => {
// Do not include hidden child items on a TOC page
if (child.page.hidden) return
return {
title: child.renderedFullTitle,
fullPath: child.href,
// renderProp is the most expensive part of this function.
intro: renderIntros ? await child.page.renderProp('intro', context, { unwrap: true }) : null,
childTocItems: isRecursive && child.childPages ? getTocItems(child.childPages, context, isRecursive, renderIntros) : null
}
})))
.filter(Boolean)
}