Debian Codegraph @

src/ext/hx-head.js

raw symbols SCIP
1 //==========================================================
2 // head-support.js
3 //
4 // An extension to add head tag merging.
5 //==========================================================
6 (function () {
7
8 let api
9
10 function log() {
11 //console.log(arguments)
12 }
13
14 // Appends a new head node, returning a promise for render-critical resources
15 // (blocking scripts, stylesheets) or null for fire-and-forget resources.
16 function appendNode(newNode) {
17 let newElt = document.createElement(newNode.tagName)
18 for (const attr of newNode.attributes) newElt.setAttribute(attr.name, attr.value)
19 newElt.textContent = newNode.textContent
20
21 // stylesheet — await CSSOM or content will flash unstyled
22 if (newNode.tagName === "LINK" && newNode.rel === "stylesheet") {
23 return new Promise(resolve => {
24 newElt.onload = resolve
25 newElt.onerror = resolve // failed stylesheet shouldn't block swap
26 document.head.appendChild(newElt)
27 })
28 }
29
30 // blocking external script (no async/defer) — must init before swap
31 if (newNode.tagName === "SCRIPT" && newNode.src && !newNode.async && !newNode.defer) {
32 return new Promise((resolve, reject) => {
33 newElt.onload = resolve
34 newElt.onerror = reject
35 document.head.appendChild(newElt)
36 })
37 }
38
39 // meta, title, base, preload/prefetch/icon links, async scripts — fire-and-forget
40 document.head.appendChild(newElt)
41 if (newNode._preloadHint) newElt.addEventListener("load", () => newNode._preloadHint.remove(), {once: true})
42 return null
43 }
44
45 async function mergeHead(newContent, defaultMergeStrategy) {
46
47 if (newContent && newContent.indexOf('<head') > -1) {
48 const htmlDoc = document.createElement("html")
49 // remove svgs to avoid conflicts
50 let contentWithSvgsRemoved = newContent.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim, '')
51 // extract head tag
52 let headTag = contentWithSvgsRemoved.match(/(<head(\s[^>]*>|>)([\s\S]*?)<\/head>)/im)
53
54 // if the head tag exists...
55 if (headTag) {
56
57 let added = []
58 let removed = []
59 let preserved = []
60 let nodesToAppend = []
61 let deferred = []
62
63 htmlDoc.innerHTML = headTag
64 let newHeadTag = htmlDoc.querySelector("head")
65 let currentHead = document.head
66
67 if (newHeadTag == null) {
68 return []
69 }
70
71 // put all new head elements into a Map, by their outerHTML
72 let srcToNewHeadNodes = new Map()
73 for (const newHeadChild of newHeadTag.children) {
74 srcToNewHeadNodes.set(newHeadChild.outerHTML, newHeadChild)
75 }
76
77 // determine merge strategy
78 let mergeStrategy = api.attributeValue(newHeadTag, "hx-head") || defaultMergeStrategy
79
80 // get the current head
81 for (const currentHeadElt of currentHead.children) {
82
83 // If the current head element is in the map
84 let inNewContent = srcToNewHeadNodes.has(currentHeadElt.outerHTML)
85 let isReAppended = currentHeadElt.getAttribute("hx-head") === "re-eval"
86 let isPreserved = api.attributeValue(currentHeadElt, "hx-preserve") === "true"
87 if (inNewContent || isPreserved) {
88 if (isReAppended) {
89 // remove the current version and let the new version replace it and re-execute
90 removed.push(currentHeadElt)
91 } else {
92 // this element already exists and should not be re-appended, so remove it from
93 // the new content map, preserving it in the DOM
94 srcToNewHeadNodes.delete(currentHeadElt.outerHTML)
95 preserved.push(currentHeadElt)
96 }
97 } else {
98 if (mergeStrategy === "append") {
99 // we are appending and this existing element is not new content
100 // so if and only if it is marked for re-append do we do anything
101 if (isReAppended) {
102 removed.push(currentHeadElt)
103 nodesToAppend.push(currentHeadElt)
104 }
105 } else {
106 // if this is a merge, we remove this content since it is not in the new head
107 if (htmx.trigger(document.body, "htmx:before:head:remove", {headElement: currentHeadElt}) !== false) {
108 removed.push(currentHeadElt)
109 }
110 }
111 }
112 }
113
114 // Push the remaining new head elements in the Map into the
115 // nodes to append to the head tag
116 nodesToAppend.push(...srcToNewHeadNodes.values())
117 log("to append: ", nodesToAppend)
118
119 // defer scripts need the swapped DOM to exist — split them out
120 for (const newNode of nodesToAppend) {
121 if (newNode.tagName === "SCRIPT" && newNode.defer) {
122 deferred.push(newNode)
123 if (newNode.src) {
124 let hint = document.createElement("link")
125 hint.rel = newNode.type === "module" ? "modulepreload" : "preload"
126 hint.as = "script"
127 hint.href = newNode.src
128 document.head.appendChild(hint)
129 newNode._preloadHint = hint
130 }
131 } else {
132 log("adding: ", newNode)
133 if (htmx.trigger(document.body, "htmx:before:head:add", {headElement: newNode}) !== false) {
134 await appendNode(newNode)
135 added.push(newNode)
136 }
137 }
138 }
139
140 // remove all removed elements, after we have appended the new elements to avoid
141 // additional network requests for things like style sheets
142 for (const removedElement of removed) {
143 if (htmx.trigger(document.body, "htmx:before:head:remove", {headElement: removedElement}) !== false) {
144 currentHead.removeChild(removedElement)
145 }
146 }
147
148 htmx.trigger(document.body, "htmx:after:head:merge", {
149 added: added,
150 kept: preserved,
151 removed: removed
152 })
153
154 return deferred
155 }
156 }
157 return []
158 }
159
160 htmx.registerExtension("hx-head", {
161 init: (internalAPI) => {
162 api = internalAPI;
163 },
164 htmx_before_response: (elt, detail) => {
165 let ctx = detail.ctx
166 let target = ctx.target
167 // TODO - is there a better way to handle this? it used to be based on if the element was boosted
168 let defaultMergeStrategy = target === document.body ? "merge" : "append";
169 if (htmx.trigger(document.body, "htmx:before:head:merge", detail)) {
170 let realText = ctx.response.raw.text.bind(ctx.response.raw)
171 ctx.response.raw.text = async () => {
172 let text = await realText()
173 ctx._deferredHeadScripts = await mergeHead(text, defaultMergeStrategy)
174 return text
175 }
176 }
177 },
178 htmx_after_swap: (elt, detail) => {
179 for (const node of detail.ctx._deferredHeadScripts || []) appendNode(node)
180 },
181 htmx_history_cache_before_restore: (elt, detail) => {
182 if (detail.head) {
183 // mergeHead awaits stylesheets/blocking scripts, returns deferred scripts.
184 // Set detail.ready so history-cache awaits before swapping body.
185 // Stash deferred scripts on detail — history-cache copies them onto the swap ctx
186 // so htmx_after_swap picks them up.
187 detail.ready = mergeHead(detail.head, 'merge').then(deferred => {
188 detail._deferredHeadScripts = deferred;
189 });
190 }
191 }
192 })
193
194 })();