-
Notifications
You must be signed in to change notification settings - Fork 1
/
markdown-it-headline-adjust.js
50 lines (40 loc) · 1.43 KB
/
markdown-it-headline-adjust.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
// Author: rodneyrehm@github
// from: https://gist.github.com/rodneyrehm/4feec9af8a8635f7de7cb1754f146a39
// License: unkown
function getHeadingLevel(tagName) {
if(tagName[0].toLowerCase() === 'h') {
tagName = tagName.slice(1)
}
return parseInt(tagName, 10)
}
export function adjustHeadingLevel(md, options) {
let firstLevel = options.firstLevel
if(typeof firstLevel === 'string') {
firstLevel = getHeadingLevel(firstLevel)
}
if(!firstLevel || isNaN(firstLevel)) {
return
}
let levelOffset = firstLevel - 1
if(levelOffset < 1 || levelOffset > 6) {
return
}
md.core.ruler.push('adjust-heading-levels', function(state) {
let tokens = state.tokens
for(let i = 0; i < tokens.length; i++) {
if(tokens[i].type !== 'heading_close') {
continue
}
let headingOpen = tokens[i - 2]
// let heading_content = tokens[i - 1];
let headingClose = tokens[i]
// we could go deeper with <div role="heading" aria-level="7">
// see http://w3c.github.io/aria/aria/aria.html#aria-level
// but clamping to a depth of 6 should suffice for now
let currentLevel = getHeadingLevel(headingOpen.tag)
let tagName = 'h' + Math.min(currentLevel + levelOffset, 6)
headingOpen.tag = tagName
headingClose.tag = tagName
}
})
}