Skip to content

Commit

Permalink
fix: htmx extension meta tag merge
Browse files Browse the repository at this point in the history
  • Loading branch information
ncpa0cpl committed Aug 9, 2024
1 parent ec28f06 commit 78d548b
Showing 1 changed file with 23 additions and 7 deletions.
30 changes: 23 additions & 7 deletions src/htmx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,10 @@ htmx.defineExtension("merge-meta", {
) {
var serverResponse = evt.detail.xhr.response;
if (
api.triggerEvent(document.body, "htmx:beforeHeadMerge", evt.detail)
api.triggerEvent(document.body, "htmx:beforeMetaMerge", evt.detail)
) {
mergeHead(serverResponse);
api.triggerEvent(document.body, "htmx:afterMetaMerge", evt.detail);
}
},
);
Expand All @@ -36,13 +37,14 @@ htmx.defineExtension("merge-meta", {
>,
) {
if (
api.triggerEvent(document.body, "htmx:beforeHeadMerge", evt.detail)
api.triggerEvent(document.body, "htmx:beforeMetaMerge", evt.detail)
) {
if (evt.detail.cacheMiss) {
mergeHead(evt.detail.serverResponse);
} else {
mergeHead(evt.detail.item.head);
}
api.triggerEvent(document.body, "htmx:afterMetaMerge", evt.detail);
}
},
);
Expand All @@ -62,17 +64,22 @@ function mergeHead(newContent: string) {
const headStart = newContent.indexOf("<head>");
if (headStart !== -1) {
const headEnd = newContent.indexOf("</head>", headStart);
const headHtml = newContent.substring(headStart, headEnd);
const headHtml = newContent.substring(headStart, headEnd + 7);
const parsed = new DOMParser().parseFromString(headHtml, "text/html");
const metaTags = parsed.head.querySelectorAll("meta");
const existingTags = Array.from(
document.head.querySelectorAll("meta"),
) as HTMLMetaElement[];

const presentNames: string[] = [];
for (let i = 0; i < metaTags.length; i++) {
const newTag = metaTags[i]!;
const name = newTag.getAttribute("name");
const newTag = metaTags[i]! as HTMLMetaElement;
const name = newTag.name;
if (!name) continue;
presentNames.push(name);

const existingTag = document.head.querySelector(
`meta[name="${name}"]`,
const existingTag = existingTags.find(
(tag) => tag.name === name,
);
if (existingTag) {
if (existingTag.outerHTML !== newTag.outerHTML) {
Expand All @@ -82,5 +89,14 @@ function mergeHead(newContent: string) {
document.head.appendChild(newTag);
}
}

for (let i = 0; i < existingTags.length; i++) {
const existingTag = existingTags[i]!;
const name = existingTag.name;
if (!name) continue;
if (!presentNames.includes(name)) {
existingTag.remove();
}
}
}
}

0 comments on commit 78d548b

Please sign in to comment.