-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
88 lines (77 loc) · 2.08 KB
/
index.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
/*
type Options = {
levels: remarkabke.HeadingValue[];
anchorClassName: string;
anchorText: string;
headerId(slug: string): string;
};
*/
const defaultOptions /*: Options */ = {
levels: [1, 2, 3, 4, 5, 6],
anchorClassName: "header-anchor",
anchorText: "#",
headerId: (slug) /*:string*/ => `heading-#${slug}`,
};
function HeaderIds(options /*:Partial<Options>*/) {
const appliedOptions /*: Options*/ = {
...defaultOptions,
...options,
};
return function (remarkable /*:Remarkable*/) {
const originalOpen =
remarkable.renderer.rules.heading_open;
remarkable.renderer.rules.heading_open = function (
tokens,
idx /*:number*/
) {
const hLevel = tokens[idx].hLevel;
const content = tokens[idx + 1].content;
const slug = slugify(content);
const href = `#${slug}`;
// Only anchorize supported header levels
if (appliedOptions.levels.indexOf(hLevel) !== -1) {
return (
`<h${hLevel} id="${appliedOptions.headerId(
slug
)}">` +
(appliedOptions.anchorText
? `<a class="${appliedOptions.anchorClassName}" id="${slug}" href="${href}">${appliedOptions.anchorText}</a>`
: "")
);
}
return originalOpen(tokens, idx);
};
};
}
// Marked.js Slugger: https://github.com/markedjs/marked/blob/master/src/Slugger.js
class Slugger {
constructor() {
this.seen /*:Record<string, number>*/ = {};
}
/**
* Convert string to unique id
*/
slug(value /*: string*/) {
let slug = value
.toLowerCase()
.trim()
.replace(
/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~]/g,
""
)
.replace(/\s/g, "-");
if (this.seen.hasOwnProperty(slug)) {
const originalSlug = slug;
do {
this.seen[originalSlug]++;
slug = originalSlug + "-" + this.seen[originalSlug];
} while (this.seen.hasOwnProperty(slug));
}
this.seen[slug] = 0;
return slug;
}
}
function slugify(str /*: string*/) {
return new Slugger().slug(str);
}
module.exports = HeaderIds;