forked from github/docs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
get-english-headings.js
54 lines (46 loc) · 1.69 KB
/
get-english-headings.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
import { fromMarkdown } from 'mdast-util-from-markdown'
import { toString } from 'mdast-util-to-string'
import { visit } from 'unist-util-visit'
import findPage from './find-page.js'
// for any translated page, first get corresponding English markdown
// then get the headings on both the translated and English pageMap
// finally, create a map of translation:English for all headings on the page
export default function getEnglishHeadings(page, context) {
// Special handling for glossaries, because their headings are
// generated programatically.
if (page.relativePath.endsWith('/github-glossary.md')) {
// Return an object of `{ localized-term: english-slug }`
const languageGlossary = context.site.data.glossaries.external
return languageGlossary.reduce((prev, curr) => {
prev[curr.term] = curr.slug
return prev
}, {})
}
const translatedHeadings = getHeadings(page.markdown)
if (!translatedHeadings.length) return
const englishPage = findPage(
`/en/${page.relativePath.replace(/.md$/, '')}`,
context.pages,
context.redirects
)
if (!englishPage) return
// FIX there may be bugs if English headings are updated before Crowdin syncs up :/
const englishHeadings = getHeadings(englishPage.markdown)
if (!englishHeadings.length) return
// return a map from translation:English
return Object.assign(
...translatedHeadings.map((k, i) => ({
[k]: englishHeadings[i],
}))
)
}
function getHeadings(markdown) {
const ast = fromMarkdown(markdown)
const headings = []
visit(ast, (node) => {
if (node.type !== 'heading') return
if (![2, 3, 4].includes(node.depth)) return
headings.push(toString(node))
})
return headings
}