Skip to content

Commit

Permalink
fix: allow options as object
Browse files Browse the repository at this point in the history
  • Loading branch information
dword-design committed Jun 9, 2023
1 parent 24a7eff commit c1a1e1b
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 3 deletions.
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,14 @@ Which will transform it into:
</article>
```

You can also pass in an object:

```js
rehype()
.use(urls, { transform: removeBaseUrl })
.process(input, handleOutput)
```

### Mutate nodes

It's also possible to mutate the URL nodes directly. This example will add `target="_blank"` to any external links:
Expand Down
9 changes: 6 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,11 @@ var url = require('url')
var opt = require('stdopt')
var visit = require('unist-util-visit')

module.exports = function transform (fn) {
fn = fn || function () {}
module.exports = function transform (options) {
if (typeof options === 'function') {
options = { transform: options }
}
options.transform = options.transform || function () {}

return function transformer (tree) {
visit(tree, 'element', function (node) {
Expand All @@ -16,7 +19,7 @@ module.exports = function transform (fn) {
function modify (node, prop) {
if (has(node, prop)) {
var obj = url.parse(node.properties[prop])
var res = opt(fn(obj, node)).or(obj).value()
var res = opt(options.transform(obj, node)).or(obj).value()
node.properties[prop] = url.format(res)
}
}
Expand Down
10 changes: 10 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,16 @@ tape('mutate', t => {
t.end()
})

tape('option object', t => {
var href = '<a href="http://example.com/page.html">text</a>'
var src = '<img src="http://example.com/image.jpg">'
var p = rehype().use(urls, { transform: url => url.path }).freeze()

t.equal(p.processSync(href).contents, wrap('<a href="/page.html">text</a>'), 'return href string')
t.equal(p.processSync(src).contents, wrap('<img src="/image.jpg">'), 'return src string')
t.end()
})

function wrap (html) {
return `<html><head></head><body>${html}</body></html>`
}

0 comments on commit c1a1e1b

Please sign in to comment.