Skip to content

Commit 3191eba

Browse files
authored
Merge pull request #1215 from Patternslib/mockup-inject
fix(pat-inject): Fix pat-inject to not break complex JSON pattern options.
2 parents 622bf54 + c3e4a68 commit 3191eba

File tree

1 file changed

+19
-15
lines changed

1 file changed

+19
-15
lines changed

src/pat/inject/inject.js

+19-15
Original file line numberDiff line numberDiff line change
@@ -839,10 +839,10 @@ const inject = {
839839
_rebaseAttrs: {
840840
a: "href",
841841
form: "action",
842-
img: "data-pat-inject-rebase-src",
842+
img: "src",
843843
object: "data",
844-
source: "data-pat-inject-rebase-src",
845-
video: "data-pat-inject-rebase-src",
844+
source: "src",
845+
video: "src",
846846
},
847847

848848
_rebaseOptions: {
@@ -867,13 +867,17 @@ const inject = {
867867
return "";
868868
}
869869

870-
// Create temporary DOM node and store the html contents on it where
871-
// the original src attribute is kept.
872-
const node = document.createElement("div");
873-
node.innerHTML = html.replace(/(\s)(src\s*)=/gi, '$1src="" data-pat-inject-rebase-$2=').trim();
874-
875-
const selector = Object.keys(this._rebaseAttrs).join(",");
876-
for (const el_ of node.querySelectorAll(selector)) {
870+
// Parse the html string into a DOM tree.
871+
const page = document.createElement("div");
872+
page.innerHTML = html;
873+
874+
// Create efficient selector for any tag with it's corresponding
875+
// attribute from _rebaseAttrs. Note: the current data structure allows
876+
// only for one attribute to be rebased per tag.
877+
const rebase_selector = Object.entries(this._rebaseAttrs)
878+
.map(([tag, attr]) => `${tag}[${attr}]`)
879+
.join(", ");
880+
for (const el_ of page.querySelectorAll(rebase_selector)) {
877881
const attr = this._rebaseAttrs[el_.tagName.toLowerCase()];
878882
let value = el_.getAttribute(attr);
879883

@@ -895,7 +899,10 @@ const inject = {
895899
}
896900

897901
for (const [pattern_name, opts] of Object.entries(this._rebaseOptions)) {
898-
for (const el_ of node.querySelectorAll(`[data-pat-${pattern_name}]`)) {
902+
for (const el_ of dom.querySelectorAllAndMe(
903+
page,
904+
`[data-pat-${pattern_name}]`
905+
)) {
899906
const pattern = registry.patterns?.[pattern_name];
900907
const pattern_parser = pattern?.parser;
901908
if (!pattern_parser) {
@@ -927,10 +934,7 @@ const inject = {
927934
}
928935
}
929936

930-
return node
931-
.innerHTML
932-
.replace(/src="" data-pat-inject-rebase-/g, "")
933-
.trim();
937+
return page.innerHTML.trim();
934938
},
935939

936940
_parseRawHtml(html, url = "") {

0 commit comments

Comments
 (0)