forked from valeriangalliat/markdown-it-anchor
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.es6.js
92 lines (73 loc) · 2.32 KB
/
index.es6.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import string from 'string'
const slugify = s =>
string(s).slugify().toString()
const position = {
false: 'push',
true: 'unshift'
}
const hasProp = ({}).hasOwnProperty
const permalinkHref = slug => `#${slug}`
const renderPermalink = (slug, opts, state, idx) => {
const space = () =>
Object.assign(new state.Token('text', '', 0), { content: ' ' })
const linkTokens = [
Object.assign(new state.Token('link_open', 'a', 1), {
attrs: [
['class', opts.permalinkClass],
['href', opts.permalinkHref(slug, state)],
['aria-hidden', 'true']
]
}),
Object.assign(new state.Token('html_block', '', 0), { content: opts.permalinkSymbol }),
new state.Token('link_close', 'a', -1)
]
// `push` or `unshift` according to position option.
// Space is at the opposite side.
linkTokens[position[!opts.permalinkBefore]](space())
state.tokens[idx + 1].children[position[opts.permalinkBefore]](...linkTokens)
}
const uniqueSlug = (slug, slugs) => {
// Mark this slug as used in the environment.
slugs[slug] = (hasProp.call(slugs, slug) ? slugs[slug] : 0) + 1
// First slug, return as is.
if (slugs[slug] === 1) {
return slug
}
// Duplicate slug, add a `-2`, `-3`, etc. to keep ID unique.
return slug + '-' + slugs[slug]
}
const anchor = (md, opts) => {
opts = Object.assign({}, anchor.defaults, opts)
md.core.ruler.push('anchor', state => {
const slugs = {}
const tokens = state.tokens
tokens
.filter(token => token.type === 'heading_open')
.filter(token => token.tag.substr(1) >= opts.level)
.forEach(token => {
// Aggregate the next token children text.
const title = tokens[tokens.indexOf(token) + 1].children
.filter(token => token.type === 'text')
.reduce((acc, t) => acc + t.content, '')
const slug = uniqueSlug(opts.slugify(title), slugs)
token.attrPush(['id', slug])
if (opts.permalink) {
opts.renderPermalink(slug, opts, state, tokens.indexOf(token))
}
if (opts.callback) {
opts.callback(token, { slug, title })
}
})
})
}
anchor.defaults = {
level: 1,
slugify,
permalink: false,
renderPermalink,
permalinkClass: 'header-anchor',
permalinkSymbol: '¶',
permalinkBefore: false,
permalinkHref
}
export default anchor