Skip to content

Commit

Permalink
Refactor to move implementation to lib/
Browse files Browse the repository at this point in the history
  • Loading branch information
wooorm committed Aug 31, 2023
1 parent 963f30c commit 87da225
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 45 deletions.
47 changes: 2 additions & 45 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,48 +1,5 @@
/**
* @typedef {import('hast').Root} Root
* @typedef {import('./lib/index.js').Options} Options
*/

/**
* @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()

visit(tree, 'element', function (node) {
if (headingRank(node) && !node.properties.id) {
node.properties.id = prefix + slugs.slug(toString(node))
}
})
}
}
export {default} from './lib/index.js'
48 changes: 48 additions & 0 deletions lib/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/**
* @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()

visit(tree, 'element', function (node) {
if (headingRank(node) && !node.properties.id) {
node.properties.id = prefix + slugs.slug(toString(node))
}
})
}
}
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"types": "index.d.ts",
"main": "index.js",
"files": [
"lib/",
"index.d.ts",
"index.js"
],
Expand Down

0 comments on commit 87da225

Please sign in to comment.