Skip to content
This repository has been archived by the owner on Oct 1, 2024. It is now read-only.

Commit

Permalink
Add support for using existing ids
Browse files Browse the repository at this point in the history
Closes GH-10.
  • Loading branch information
Hypercubed authored and wooorm committed Aug 13, 2018
1 parent 9818c30 commit 6259b7f
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 18 deletions.
16 changes: 6 additions & 10 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,13 @@ function transformer(ast) {
visit(ast, 'heading', visitor)

function visitor(node) {
var id = slugs.slug(toString(node))
var data = node.data || (node.data = {})
var props = data.hProperties || (data.hProperties = {})
var id = props.id

if (!node.data) {
node.data = {}
}
id = id ? slugs.slug(id, true) : slugs.slug(toString(node))

if (!node.data.hProperties) {
node.data.hProperties = {}
}

node.data.id = id
node.data.hProperties.id = id
data.id = id
props.id = id
}
}
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
"browserify": "^16.0.0",
"nyc": "^12.0.0",
"remark": "^9.0.0",
"remark-attr": "^0.6.2",
"remark-cli": "^5.0.0",
"remark-preset-wooorm": "^4.0.0",
"tape": "^4.0.0",
Expand Down
37 changes: 29 additions & 8 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,15 @@

var test = require('tape')
var remark = require('remark')
var attr = require('remark-attr')
var u = require('unist-builder')
var removePosition = require('unist-util-remove-position')
var slug = require('.')

function process(doc, options) {
var processor = remark().use(slug, options)
var processor = remark()
.use(attr)
.use(slug, options)

return removePosition(processor.runSync(processor.parse(doc)), true)
}
Expand Down Expand Up @@ -50,9 +53,7 @@ test('remark-slug', function(t) {

ast = processor.parse('# Normal', {position: false})

ast.children[0].data = {
hProperties: {className: 'bar'}
}
ast.children[0].data = {hProperties: {className: 'bar'}}

processor.run(ast)

Expand Down Expand Up @@ -129,16 +130,36 @@ test('remark-slug', function(t) {
'should create GitHub slugs'
)

ast = process(
[
'## Something',
'',
'## Something here',
'{ #here }',
'',
'## Something there',
'',
'## Something also',
'{ #something }',
''
].join('\n')
)

t.deepEqual(
ast.children.map(function(d) {
return d.data.id
}),
['something', 'here', 'something-there', 'something-1'],
'should use existing ids as slugs'
)

t.end()
})

function heading(label, id) {
return u(
'heading',
{
depth: 2,
data: {id: id, hProperties: {id: id}}
},
{depth: 2, data: {id: id, hProperties: {id: id}}},
label ? [u('text', label)] : []
)
}

0 comments on commit 6259b7f

Please sign in to comment.