Skip to content

Commit

Permalink
fix: fix inline scripts potentially breaking
Browse files Browse the repository at this point in the history
fix the issue which breaks scripts split in different chunks in the input stream
by applying them only after the scripts has been fully visited

resolves marko-js#1
  • Loading branch information
dario-piotrowicz committed Sep 15, 2022
1 parent 51650e1 commit 1014665
Showing 1 changed file with 30 additions and 4 deletions.
34 changes: 30 additions & 4 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,13 @@ export = function writableDOM(
let scanNode: Node | null = null;
let resolve: void | (() => void);
let isBlocked = false;
let hostScriptNode: Node | null = null;

return {
write(chunk: string) {
doc.write(chunk);

if (pendingText) {
if (pendingText && !hostScriptNode) {
// When we left on text, it's possible more text was written to the same node.
// here we copy in the final text content from the detached dom to the live dom.
(targetNodes.get(pendingText) as Text).data = pendingText.data;
Expand All @@ -42,6 +43,8 @@ export = function writableDOM(
}
},
close() {
appendPendingScriptTextIfNeeded(pendingText, hostScriptNode);

return isBlocked
? new Promise<void>((_) => (resolve = _))
: Promise.resolve();
Expand All @@ -68,6 +71,7 @@ export = function writableDOM(
} else {
while ((node = walker.nextNode())) {
const clone = document.importNode(node, false);
const previousPendingText = pendingText;
if (node.nodeType === Node.TEXT_NODE) {
pendingText = node as Text;
} else {
Expand All @@ -86,10 +90,16 @@ export = function writableDOM(
const parentNode = targetNodes.get(node.parentNode!)!;
targetNodes.set(node, clone);

if (parentNode === target) {
target.insertBefore(clone, nextSibling);
if (isScript(parentNode)) {
hostScriptNode = parentNode;
} else {
parentNode.appendChild(clone);
appendPendingScriptTextIfNeeded(previousPendingText, hostScriptNode);

if (parentNode === target) {
target.insertBefore(clone, nextSibling);
} else {
parentNode.appendChild(clone);
}
}

// Start walking for preloads.
Expand Down Expand Up @@ -178,3 +188,19 @@ function getPreloadLink(node: any) {

return link;
}

function appendPendingScriptTextIfNeeded(
pendingText: Text | null,
hostScriptNode: Node | null
) {
if (pendingText && hostScriptNode) {
hostScriptNode.appendChild(pendingText);
}
}

function isScript(node: Node) {
return (
node.nodeType === Node.ELEMENT_NODE &&
(node as Element).tagName === "SCRIPT"
);
}

0 comments on commit 1014665

Please sign in to comment.