Skip to content

Commit

Permalink
Refactor code-style
Browse files Browse the repository at this point in the history
  • Loading branch information
wooorm committed Aug 31, 2023
1 parent 22f1ee7 commit 463cd39
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 13 deletions.
33 changes: 22 additions & 11 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,30 +6,41 @@
* @typedef Options
* Configuration (optional).
* @property {string} [prefix='']
* Prefix to add in front of `id`s.
* Prefix to add in front of `id`s (default: `''`).
*/

import Slugger from 'github-slugger'
import {hasProperty} from 'hast-util-has-property'
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'

const slugs = new Slugger()
/** @type {Options} */
const emptyOptions = {}
const slugs = new GithubSlugger()

/**
* Plugin to add `id`s to headings.
* Add `id`s to headings.
*
* @type {import('unified').Plugin<[Options?]|Array<void>, Root>}
* @param {Options | null | undefined} [options]
* Configuration (optional).
* @returns
* Transform.
*/
export default function rehypeSlug(options = {}) {
const prefix = options.prefix || ''
export default function rehypeSlug(options) {
const settings = options || emptyOptions
const prefix = settings.prefix || ''

return (tree) => {
/**
* @param {Root} tree
* Tree.
* @returns {undefined}
* Nothing.
*/
return function (tree) {
slugs.reset()

visit(tree, 'element', (node) => {
if (headingRank(node) && node.properties && !hasProperty(node, 'id')) {
visit(tree, 'element', function (node) {
if (headingRank(node) && !node.properties.id) {
node.properties.id = prefix + slugs.slug(toString(node))
}
})
Expand Down
2 changes: 0 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,8 @@
"dependencies": {
"@types/hast": "^3.0.0",
"github-slugger": "^2.0.0",
"hast-util-has-property": "^3.0.0",
"hast-util-heading-rank": "^3.0.0",
"hast-util-to-string": "^3.0.0",
"unified": "^11.0.0",
"unist-util-visit": "^5.0.0"
},
"devDependencies": {
Expand Down
6 changes: 6 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@ import {rehype} from 'rehype'
import rehypeSlug from './index.js'

test('rehypeSlug', async function (t) {
await t.test('should expose the public api', async function () {
assert.deepEqual(Object.keys(await import('./index.js')).sort(), [
'default'
])
})

await t.test('should work', async function () {
const file = await rehype()
.data('settings', {fragment: true})
Expand Down

0 comments on commit 463cd39

Please sign in to comment.