Skip to content

Commit

Permalink
Add options for setting a prefix
Browse files Browse the repository at this point in the history
  • Loading branch information
onyxcodes committed Oct 5, 2022
1 parent 31483c0 commit 82d837c
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 5 deletions.
14 changes: 10 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
/**
* @typedef {import('hast').Root} Root
* @typedef {string} Prefix
* @typedef Options
* Configuration.
* @property {Prefix} [prefix='']
*
*/

import Slugger from 'github-slugger'
Expand All @@ -12,16 +17,17 @@ const slugs = new Slugger()

/**
* Plugin to add `id`s to headings.
*
* @type {import('unified').Plugin<Array<void>, Root>}
* @type {import('unified').Plugin<[Options?]|Array<void>, Root>}
*/
export default function rehypeSlug() {
export default function rehypeSlug(options = {}) {
let prefix = options.prefix || '';

return (tree) => {
slugs.reset()

visit(tree, 'element', (node) => {
if (headingRank(node) && node.properties && !hasProperty(node, 'id')) {
node.properties.id = slugs.slug(toString(node))
node.properties.id = `${prefix}${slugs.slug(toString(node))}`
}
})
}
Expand Down
36 changes: 35 additions & 1 deletion test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import {rehype} from 'rehype'
import rehypeSlug from './index.js'

test('rehypeSlug', (t) => {
t.plan(2)
t.plan(4)

rehype()
.data('settings', {fragment: true})
Expand Down Expand Up @@ -38,4 +38,38 @@ test('rehypeSlug', (t) => {
)
}
)

rehype()
.data('settings', {fragment: true})
.use(rehypeSlug, { prefix: 'test-'})
.process(
[
'<section>',
' <h1>Lorem ipsum 😪</h1>',
' <h2>dolor—sit—amet</h2>',
' <h3>consectetur &amp; adipisicing</h3>',
' <h4>elit</h4>',
' <h5>elit</h5>',
' <p>sed</p>',
'</section>'
].join('\n'),
(error, file) => {
t.ifErr(error, 'shouldn’t throw')

t.equal(
String(file),
[
'<section>',
' <h1 id="test-lorem-ipsum-">Lorem ipsum 😪</h1>',
' <h2 id="test-dolorsitamet">dolor—sit—amet</h2>',
' <h3 id="test-consectetur--adipisicing">consectetur &#x26; adipisicing</h3>',
' <h4 id="test-elit">elit</h4>',
' <h5 id="test-elit-1">elit</h5>',
' <p>sed</p>',
'</section>'
].join('\n'),
'should match'
)
}
)
})

0 comments on commit 82d837c

Please sign in to comment.