|
| 1 | +/** |
| 2 | + * Forked from https://github.com/rehypejs/rehype-slug to support PlatformIdentifier nodes |
| 3 | + */ |
| 4 | + |
| 5 | +/** |
| 6 | + * @typedef {import('hast').Root} Root |
| 7 | + */ |
| 8 | + |
| 9 | +/** |
| 10 | + * @typedef Options |
| 11 | + * Configuration (optional). |
| 12 | + * @property {string} [prefix=''] |
| 13 | + * Prefix to add in front of `id`s (default: `''`). |
| 14 | + */ |
| 15 | + |
| 16 | +import GithubSlugger from 'github-slugger'; |
| 17 | +import {headingRank} from 'hast-util-heading-rank'; |
| 18 | +import {toString} from 'hast-util-to-string'; |
| 19 | +import {visit} from 'unist-util-visit'; |
| 20 | + |
| 21 | +/** @type {Options} */ |
| 22 | +const emptyOptions = {}; |
| 23 | +const slugs = new GithubSlugger(); |
| 24 | + |
| 25 | +/** |
| 26 | + * Add `id`s to headings. |
| 27 | + * |
| 28 | + * @param {Options | null | undefined} [options] |
| 29 | + * Configuration (optional). |
| 30 | + * @returns |
| 31 | + * Transform. |
| 32 | + */ |
| 33 | +export default function rehypeSlug(options) { |
| 34 | + const settings = options || emptyOptions; |
| 35 | + const prefix = settings.prefix || ''; |
| 36 | + |
| 37 | + /** |
| 38 | + * @param {Root} tree |
| 39 | + * Tree. |
| 40 | + * @returns {undefined} |
| 41 | + * Nothing. |
| 42 | + */ |
| 43 | + return function (tree) { |
| 44 | + slugs.reset(); |
| 45 | + |
| 46 | + // Custom function to handle PlatformIdentifier nodes |
| 47 | + /** |
| 48 | + * @param {Root} n |
| 49 | + * @returns {string} |
| 50 | + */ |
| 51 | + const myToString = n => |
| 52 | + n.children.length |
| 53 | + ? n.children |
| 54 | + .map(node => |
| 55 | + node.name === 'PlatformIdentifier' |
| 56 | + ? node.attributes.find(att => att.name === 'name').value |
| 57 | + : toString(node) |
| 58 | + ) |
| 59 | + .join('') |
| 60 | + : n.value; |
| 61 | + |
| 62 | + visit(tree, 'element', function (node) { |
| 63 | + if (headingRank(node) && !node.properties.id) { |
| 64 | + node.properties.id = prefix + slugs.slug(myToString(node)); |
| 65 | + } |
| 66 | + }); |
| 67 | + }; |
| 68 | +} |
0 commit comments