Skip to content

Fix memory leaks #102

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ export function Header({
}`}
placeholder="What needs to be done?"
autoFocus
autoComplete="off"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe that this attribute makes no difference. Can you please confirm and remove?

spellCheck={false}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you please add a comment with a reference to the chrome big we filed? Thanks

value={newTodoDetails.text}
onInput={(event: ChangeEvent<HTMLInputElement>) => {
const text = event.target.value;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ export class GenericMessageBus implements MessageBus {
}

dispatch(eventName: string, value: JSONValue) {
value = JSON.parse(JSON.stringify(value));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you please add a comment to explain what's going on here?

Also could we use https://developer.mozilla.org/en-US/docs/Web/API/structuredClone instead? (structuredClone feels less hacky)

this._state[eventName] = value;
const callbacksForEvent = this._callbacksMap.get(eventName) ?? [];
setTimeout(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,28 @@ export class PiercingFragmentOutlet extends HTMLElement {

disconnectedCallback() {
if (this.fragmentHost) {
unmountedFragmentIds.add(this.fragmentHost.fragmentId);
const fragmentId = this.fragmentHost.fragmentId;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add a comment before this block explaining what we are doing here? Thanks

unmountedFragmentIds.add(fragmentId);

const fragmentFunctionConstructor =
fragmentRegistrationMap.get(fragmentId)!;
if (fragmentFunctionConstructor) {
fragmentRegistrationMap.delete(fragmentId);

const listenerRegistrations = fragmentListenerMap.get(
fragmentFunctionConstructor
)!;
fragmentListenerMap.delete(fragmentFunctionConstructor);

for (const listenerRegistration of listenerRegistrations) {
listenerRegistration.target.removeEventListener(
listenerRegistration.name,
listenerRegistration.listener,
listenerRegistration.options
);
}
}

this.fragmentHost = null;
}
}
Expand Down
34 changes: 33 additions & 1 deletion productivity-suite/piercing-library/src/piercing-gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
// for debugging replace `qwikloader.js` with `qwikloader.debug.js` to have the code non-minified
import qwikloader from "@builder.io/qwik/qwikloader.js?raw";
import reframedClient from "./reframed-client?raw";
import reframedHost from "./reframed-host?raw";
import { MessageBusState } from "./message-bus/message-bus";
import { getMessageBusState } from "./message-bus/server-side-message-bus";

Expand Down Expand Up @@ -327,6 +328,7 @@ export class PiercingGateway<Env> {
"</head>",
`${getMessageBusInlineScript(stateHeaderStr ?? "{}")}\n` +
`${piercingFragmentHostInlineScript}\n` +
`${getReframedHostCode()}\n` +
"</head>"
);

Expand Down Expand Up @@ -372,12 +374,13 @@ export class PiercingGateway<Env> {
if (this.config.isolateFragments?.(env)) {
// Quotes must be escaped from srcdoc contents
template = `
${prePiercingStyles}
<piercing-fragment-host fragment-id=${fragmentConfig.fragmentId}>
</piercing-fragment-host>
${prePiercingStyles}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ahh... I see. This explains the FOUC

<iframe id="iframe_${fragmentId}" style="display: none" srcdoc="
<body>
--FRAGMENT_CONTENT--
${getEmbeddedStyleScript(fragmentId)}
${getEscapedReframedClientCode(fragmentId)}
${(framework === "qwik" && escapeQuotes(qwikloaderScript)) || ""}
</body>
Expand Down Expand Up @@ -463,6 +466,35 @@ function getEscapedReframedClientCode(fragmentId: string) {
</script>`;
}

function getEmbeddedStyleScript(fragmentId: string) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you please document the purpose of this fn. thank you

return `<script>
${escapeQuotes(
`
const stylesheets = document.querySelectorAll(
'link[href][rel="stylesheet"]'
);

stylesheets.forEach((styleLink) => {
if (styleLink.sheet) {
let rulesText = "";
for (const { cssText } of styleLink.sheet.cssRules) {
rulesText += cssText + "\\n";
}

const styleElement = document.createElement("style");
styleElement.textContent = rulesText;
styleLink.replaceWith(styleElement);
}
});
`
)}
</script>`;
}

function getReframedHostCode() {
return `<script> ${reframedHost}</script>`;
}

const escapeQuotes = (str: string) => str.replaceAll('"', `&quot;`);

const qwikloaderScript = `<script id="qwikloader">${qwikloader}</script>`;
15 changes: 13 additions & 2 deletions productivity-suite/piercing-library/src/reframed-client.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,21 @@
const reframedContainer = window.parent.document.querySelector(
__FRAGMENT_SELECTOR__
);

if (!reframedContainer) {
console.error("Container element couldn't be found");
}

const fragmentId = reframedContainer.getAttribute("fragment-id");

const reframedDocument = reframedContainer.ownerDocument;
const reframedWindow = reframedDocument.defaultView;
const reframedRegistrationSymbol = Symbol.for("reframedRegistration");
const reframedRegistration = Reflect.get(
reframedWindow,
reframedRegistrationSymbol
);
reframedRegistration(fragmentId, Function);

const htmlToReframe = [];
const nodesToRemove = [];
Expand Down Expand Up @@ -42,6 +51,8 @@ document.body.childNodes.forEach((node) => {
});

nodesToRemove.forEach((node) => node.remove());

console.log("reframing iframe nodes");
reframedContainer.innerHTML = htmlToReframe.join("");

document.addEventListener("DOMContentLoaded", () => {
Expand Down Expand Up @@ -111,8 +122,8 @@ for (const listenerProperty of domListenerProperties) {
);
};

window[listenerProperty] = function reframedListenerFn(...args) {
return reframedWindow[listenerProperty].apply(reframedWindow, args);
window[listenerProperty] = function reframedListenerFn() {
return reframedWindow[listenerProperty].apply(reframedWindow, arguments);
};
}

Expand Down
54 changes: 54 additions & 0 deletions productivity-suite/piercing-library/src/reframed-host.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// Maps that allow us to keep track of registered fragments and their listeners.
// We use FunctionConstructor as a way to identify the origin of a registered listener and map it back to its fragment.
const fragmentRegistrationMap = new Map();
const fragmentListenerMap = new Map();

// monkey patch global addEventListner on window and document so that we can automatically unregister
// any listeners created from within a registered fragment.
const addEventListenerTargets = [window, document];
// const addEventListenerTargets = [Node.prototype];
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove?

for (const addEventListenerTarget of addEventListenerTargets) {
const originalDocumentAddEventListener =
addEventListenerTarget.addEventListener;
addEventListenerTarget.addEventListener =
function reframedHostAddEventListener(name, listener, options) {
let listenerFnConstructor;
if (listener.handleEvent) {
listenerFnConstructor = listener.handleEvent.constructor;
} else {
listenerFnConstructor = listener.constructor;
}

const listenerFns = fragmentListenerMap.get(listenerFnConstructor);

// if this listener comes from a registered fragment, then keep track of it so that we can unregister it
if (listenerFns) {
listenerFns.push({
target: addEventListenerTarget,
// target: this,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove

name,
listener,
options,
});
}

return originalDocumentAddEventListener.call(
addEventListenerTarget,
// this,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove

name,
listener,
options
);
};
}

const reframedRegistrationSymbol = Symbol.for("reframedRegistration");

Reflect.set(
window,
reframedRegistrationSymbol,
function reframedRegistration(fragmentId, clientFunctionConstructor) {
fragmentRegistrationMap.set(fragmentId, clientFunctionConstructor);
fragmentListenerMap.set(clientFunctionConstructor, []);
}
);