-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathrehype-slug.js
68 lines (60 loc) · 1.56 KB
/
rehype-slug.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
/**
* Forked from https://github.com/rehypejs/rehype-slug to support PlatformIdentifier nodes
*/
/**
* @typedef {import('hast').Root} Root
*/
/**
* @typedef Options
* Configuration (optional).
* @property {string} [prefix='']
* Prefix to add in front of `id`s (default: `''`).
*/
import GithubSlugger from 'github-slugger';
import {headingRank} from 'hast-util-heading-rank';
import {toString} from 'hast-util-to-string';
import {visit} from 'unist-util-visit';
/** @type {Options} */
const emptyOptions = {};
const slugs = new GithubSlugger();
/**
* Add `id`s to headings.
*
* @param {Options | null | undefined} [options]
* Configuration (optional).
* @returns
* Transform.
*/
export default function rehypeSlug(options) {
const settings = options || emptyOptions;
const prefix = settings.prefix || '';
/**
* @param {Root} tree
* Tree.
* @returns {undefined}
* Nothing.
*/
return function (tree) {
slugs.reset();
// Custom function to handle PlatformIdentifier nodes
/**
* @param {Root} n
* @returns {string}
*/
const myToString = n =>
n.children.length
? n.children
.map(node =>
node.name === 'PlatformIdentifier'
? node.attributes.find(att => att.name === 'name').value
: toString(node)
)
.join('')
: n.value;
visit(tree, 'element', function (node) {
if (headingRank(node) && !node.properties.id) {
node.properties.id = prefix + slugs.slug(myToString(node));
}
});
};
}