Skip to content

Commit

Permalink
feat(index): add asset resolving (HTML URLs) support (options.url)
Browse files Browse the repository at this point in the history
  • Loading branch information
michael-ciniawsky committed Feb 6, 2018
1 parent b8ec2d4 commit 82e094b
Showing 1 changed file with 74 additions and 0 deletions.
74 changes: 74 additions & 0 deletions src/lib/plugins/url.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/* eslint-disable */
// External URL (Protocol URL)
const TEST_URL = /^\w+:\/\//;
// TODO(michael-ciniawsky)
// extend with custom matchers
// e.g <custom-element custom-src="">
// (`options.url.filter`) (#159)
const MATCH_ATTRS = [
{ attrs: { src: true } },
{ attrs: { href: true } },
{ attrs: { srcset: true } }
];

// TODO(michael-ciniawsky)
// add filter method for urls (e.g `options.url.filter`) (#158)
const filter = (url, options) => {
return TEST_URL.test(url) || url.startsWith('//');
}

export default function (options = {}) {
return function (tree) {
let idx = 0;
const urls = {};

tree.match(MATCH_ATTRS, (node) => {
// <tag src="path/to/file.ext">
if (node.attrs.src) {
// Ignore <import>/<include
if (node.tag === 'import' || node.tag === 'include') return node;
// Ignore external && filtered urls
if (filter(node.attrs.src, options)) return node;
// Add url to messages.urls
urls[`HTML__URL__${idx}`] = node.attrs.src;
// Add content placeholders to HTML
node.attrs.src = '${' + `HTML__URL__${idx}` + '}';

idx++;

return node;
}
// <tag href="path/to/file.ext">
if (node.attrs.href) {
// Ignore external && filtered urls
if (filter(node.attrs.href, options)) return node;
// Add url to messages.urls
urls[`HTML__URL__${idx}`] = node.attrs.href;
// Add content placeholder to HTML
node.attrs.href = '${' + `HTML__URL__${idx}` + '}';

idx++;

return node;
}
// <tag srcset="path/to/file.ext">
if (node.attrs.srcset) {
// Ignore external && filtered urls
if (filter(node.attrs.srcset, options)) return node;
// Add url to messages.urls
urls[`HTML__URL__${idx}`] = node.attrs.srcset;
// Add content placeholder to HTML
node.attrs.srcset = '${' + `HTML__URL__${idx}` + '}';

idx++;

return node;
}
});

// Add urls to result.messages
tree.messages.push(urls);

return tree;
};
}

0 comments on commit 82e094b

Please sign in to comment.