|
| 1 | +/* eslint-disable */ |
| 2 | +// External URL (Protocol URL) |
| 3 | +const TEST_URL = /^\w+:\/\//; |
| 4 | +// TODO(michael-ciniawsky) |
| 5 | +// extend with custom matchers |
| 6 | +// e.g <custom-element custom-src=""> |
| 7 | +// (`options.url.filter`) (#159) |
| 8 | +const MATCH_ATTRS = [ |
| 9 | + { attrs: { src: true } }, |
| 10 | + { attrs: { href: true } }, |
| 11 | + { attrs: { srcset: true } } |
| 12 | +]; |
| 13 | + |
| 14 | +// TODO(michael-ciniawsky) |
| 15 | +// add filter method for urls (e.g `options.url.filter`) (#158) |
| 16 | +const filter = (url, options) => { |
| 17 | + return TEST_URL.test(url) || url.startsWith('//'); |
| 18 | +} |
| 19 | + |
| 20 | +export default function (options = {}) { |
| 21 | + return function (tree) { |
| 22 | + let idx = 0; |
| 23 | + const urls = {}; |
| 24 | + |
| 25 | + tree.match(MATCH_ATTRS, (node) => { |
| 26 | + // <tag src="path/to/file.ext"> |
| 27 | + if (node.attrs.src) { |
| 28 | + // Ignore <import>/<include |
| 29 | + if (node.tag === 'import' || node.tag === 'include') return node; |
| 30 | + // Ignore external && filtered urls |
| 31 | + if (filter(node.attrs.src, options)) return node; |
| 32 | + // Add url to messages.urls |
| 33 | + urls[`HTML__URL__${idx}`] = node.attrs.src; |
| 34 | + // Add content placeholders to HTML |
| 35 | + node.attrs.src = '${' + `HTML__URL__${idx}` + '}'; |
| 36 | + |
| 37 | + idx++; |
| 38 | + |
| 39 | + return node; |
| 40 | + } |
| 41 | + // <tag href="path/to/file.ext"> |
| 42 | + if (node.attrs.href) { |
| 43 | + // Ignore external && filtered urls |
| 44 | + if (filter(node.attrs.href, options)) return node; |
| 45 | + // Add url to messages.urls |
| 46 | + urls[`HTML__URL__${idx}`] = node.attrs.href; |
| 47 | + // Add content placeholder to HTML |
| 48 | + node.attrs.href = '${' + `HTML__URL__${idx}` + '}'; |
| 49 | + |
| 50 | + idx++; |
| 51 | + |
| 52 | + return node; |
| 53 | + } |
| 54 | + // <tag srcset="path/to/file.ext"> |
| 55 | + if (node.attrs.srcset) { |
| 56 | + // Ignore external && filtered urls |
| 57 | + if (filter(node.attrs.srcset, options)) return node; |
| 58 | + // Add url to messages.urls |
| 59 | + urls[`HTML__URL__${idx}`] = node.attrs.srcset; |
| 60 | + // Add content placeholder to HTML |
| 61 | + node.attrs.srcset = '${' + `HTML__URL__${idx}` + '}'; |
| 62 | + |
| 63 | + idx++; |
| 64 | + |
| 65 | + return node; |
| 66 | + } |
| 67 | + }); |
| 68 | + |
| 69 | + // Add urls to result.messages |
| 70 | + tree.messages.push(urls); |
| 71 | + |
| 72 | + return tree; |
| 73 | + }; |
| 74 | +} |
0 commit comments