Skip to content

Commit

Permalink
Fixes #6
Browse files Browse the repository at this point in the history
  • Loading branch information
zachleat authored and MonikaJassova committed Jun 4, 2022
1 parent 8b4e7eb commit c1c1fb9
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 0 deletions.
5 changes: 5 additions & 0 deletions _src/AbsoluteUrl.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
const { URL } = require("url");

module.exports = function(url, base) {
return (new URL(url, base)).toString()
};
20 changes: 20 additions & 0 deletions _src/HtmlToAbsoluteUrls.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
const posthtml = require('posthtml');
const urls = require('posthtml-urls')
const absoluteUrl = require("./AbsoluteUrl");

module.exports = function(htmlContent, base) {
let options = {
eachURL: function(url, attr, element) {
// #anchor in-page
if( url.trim().indexOf("#") === 0 ) {
return url;
}

return absoluteUrl(url, base);
}
};

let modifier = posthtml().use(urls(options));

return modifier.process(htmlContent);
};
9 changes: 9 additions & 0 deletions _src/test/HtmlToAbsoluteUrlsTest.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import test from "ava";
import htmlToAbsUrls from "../HtmlToAbsoluteUrls.js";

test("Changes a link href", async t => {
t.is((await htmlToAbsUrls(`<a href="#testanchor">Hello</a>`, "http://example.com/")).html, `<a href="#testanchor">Hello</a>`);
t.is((await htmlToAbsUrls(`<a href="/test.html">Hello</a>`, "http://example.com/")).html, `<a href="http://example.com/test.html">Hello</a>`);
t.is((await htmlToAbsUrls(`<img src="/test.png">`, "http://example.com/")).html, `<img src="http://example.com/test.png">`);
t.is((await htmlToAbsUrls(`<a href="http://someotherdomain/">Hello</a>`, "http://example.com/")).html, `<a href="http://someotherdomain/">Hello</a>`);
});

0 comments on commit c1c1fb9

Please sign in to comment.