Skip to content

Commit

Permalink
Merge pull request #1215 from Patternslib/mockup-inject
Browse files Browse the repository at this point in the history
fix(pat-inject): Fix pat-inject to not break complex JSON pattern options.
  • Loading branch information
thet authored Jan 7, 2025
2 parents 622bf54 + c3e4a68 commit 3191eba
Showing 1 changed file with 19 additions and 15 deletions.
34 changes: 19 additions & 15 deletions src/pat/inject/inject.js
Original file line number Diff line number Diff line change
Expand Up @@ -839,10 +839,10 @@ const inject = {
_rebaseAttrs: {
a: "href",
form: "action",
img: "data-pat-inject-rebase-src",
img: "src",
object: "data",
source: "data-pat-inject-rebase-src",
video: "data-pat-inject-rebase-src",
source: "src",
video: "src",
},

_rebaseOptions: {
Expand All @@ -867,13 +867,17 @@ const inject = {
return "";
}

// Create temporary DOM node and store the html contents on it where
// the original src attribute is kept.
const node = document.createElement("div");
node.innerHTML = html.replace(/(\s)(src\s*)=/gi, '$1src="" data-pat-inject-rebase-$2=').trim();

const selector = Object.keys(this._rebaseAttrs).join(",");
for (const el_ of node.querySelectorAll(selector)) {
// Parse the html string into a DOM tree.
const page = document.createElement("div");
page.innerHTML = html;

// Create efficient selector for any tag with it's corresponding
// attribute from _rebaseAttrs. Note: the current data structure allows
// only for one attribute to be rebased per tag.
const rebase_selector = Object.entries(this._rebaseAttrs)
.map(([tag, attr]) => `${tag}[${attr}]`)
.join(", ");
for (const el_ of page.querySelectorAll(rebase_selector)) {
const attr = this._rebaseAttrs[el_.tagName.toLowerCase()];
let value = el_.getAttribute(attr);

Expand All @@ -895,7 +899,10 @@ const inject = {
}

for (const [pattern_name, opts] of Object.entries(this._rebaseOptions)) {
for (const el_ of node.querySelectorAll(`[data-pat-${pattern_name}]`)) {
for (const el_ of dom.querySelectorAllAndMe(
page,
`[data-pat-${pattern_name}]`
)) {
const pattern = registry.patterns?.[pattern_name];
const pattern_parser = pattern?.parser;
if (!pattern_parser) {
Expand Down Expand Up @@ -927,10 +934,7 @@ const inject = {
}
}

return node
.innerHTML
.replace(/src="" data-pat-inject-rebase-/g, "")
.trim();
return page.innerHTML.trim();
},

_parseRawHtml(html, url = "") {
Expand Down

0 comments on commit 3191eba

Please sign in to comment.