Skip to content

Commit

Permalink
fix: fix memory leak affecting components using conditionally-rendere…
Browse files Browse the repository at this point in the history
…d slots (#9208)

**Related Issue:** #9177

## Summary

Fixes an issue caused by `conditionalSlot` implementing `unobserve` on
top of `ExtendedMutationObserver`, which already implements it.
  • Loading branch information
jcfranco committed Apr 27, 2024
1 parent 23eb3a4 commit 28701b6
Showing 1 changed file with 3 additions and 14 deletions.
17 changes: 3 additions & 14 deletions packages/calcite-components/src/utils/conditionalSlot.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import { forceUpdate } from "@stencil/core";
import { createObserver } from "./observers";

const observed = new Set<HTMLElement>();
import { createObserver, ExtendedMutationObserver } from "./observers";

/**
* Defines interface for components with a dynamically changing slot.
Expand All @@ -19,7 +17,7 @@ export interface ConditionalSlotComponent {
readonly el: HTMLElement;
}

let mutationObserver: MutationObserver;
let mutationObserver: ExtendedMutationObserver;
const observerOptions: Pick<Parameters<MutationObserver["observe"]>[1], "childList"> = { childList: true };

/**
Expand Down Expand Up @@ -51,16 +49,7 @@ export function connectConditionalSlotComponent(component: ConditionalSlotCompon
* ```
*/
export function disconnectConditionalSlotComponent(component: ConditionalSlotComponent): void {
observed.delete(component.el);

// we explicitly process queued mutations and disconnect and reconnect
// the observer until MutationObserver gets an `unobserve` method
// see https://github.com/whatwg/dom/issues/126
processMutations(mutationObserver.takeRecords());
mutationObserver.disconnect();
for (const [element] of observed.entries()) {
mutationObserver.observe(element, observerOptions);
}
mutationObserver.unobserve(component.el);
}

function processMutations(mutations: MutationRecord[]): void {
Expand Down

0 comments on commit 28701b6

Please sign in to comment.