Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: allow options as object #3

Merged
merged 1 commit into from
Jul 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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>`
}