diff --git a/package.json b/package.json index 1886cce85c2cc..3eb740301a15e 100644 --- a/package.json +++ b/package.json @@ -90,7 +90,6 @@ "rehype-preset-minify": "^7.0.0", "rehype-prism-diff": "^1.1.2", "rehype-prism-plus": "^1.6.3", - "rehype-slug": "^6.0.0", "rehype-stringify": "^10.0.0", "remark-gfm": "^4.0.0", "remark-mdx-images": "^3.0.0", diff --git a/src/mdx.ts b/src/mdx.ts index 884295c337765..f701d34e0ae37 100644 --- a/src/mdx.ts +++ b/src/mdx.ts @@ -9,7 +9,6 @@ import rehypeAutolinkHeadings from 'rehype-autolink-headings'; import rehypePresetMinify from 'rehype-preset-minify'; import rehypePrismDiff from 'rehype-prism-diff'; import rehypePrismPlus from 'rehype-prism-plus'; -import rehypeSlug from 'rehype-slug'; import remarkGfm from 'remark-gfm'; import remarkMdxImages from 'remark-mdx-images'; @@ -18,6 +17,7 @@ import getPackageRegistry from './build/packageRegistry'; import {apiCategories} from './build/resolveOpenAPI'; import getAllFilesRecursively from './files'; import rehypeOnboardingLines from './rehype-onboarding-lines'; +import rehypeSlug from './rehype-slug.js'; import remarkCodeTabs from './remark-code-tabs'; import remarkCodeTitles from './remark-code-title'; import remarkComponentSpacing from './remark-component-spacing'; diff --git a/src/rehype-slug.js b/src/rehype-slug.js new file mode 100644 index 0000000000000..47870645d0cd0 --- /dev/null +++ b/src/rehype-slug.js @@ -0,0 +1,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)); + } + }); + }; +}