Created
November 18, 2024 00:26
-
-
Save ChrisShank/a970e58d240f7b02320b6c2eacf06ee5 to your computer and use it in GitHub Desktop.
Resize Observer Manager
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export type ResizeObserverEntryCallback = (entry: ResizeObserverEntry) => void; | |
export class ResizeObserverManager { | |
#elementMap = new WeakMap<Element, Set<ResizeObserverEntryCallback>>(); | |
#elementEntry = new WeakMap<Element, ResizeObserverEntry>(); | |
#vo = new ResizeObserver((entries) => { | |
for (const entry of entries) { | |
this.#elementEntry.set(entry.target, entry); | |
this.#elementMap.get(entry.target)?.forEach((callback) => callback(entry)); | |
} | |
}); | |
observe(target: Element, callback: ResizeObserverEntryCallback): void { | |
let callbacks = this.#elementMap.get(target); | |
if (callbacks === undefined) { | |
this.#vo.observe(target); | |
this.#elementMap.set(target, (callbacks = new Set())); | |
} else { | |
const entry = this.#elementEntry.get(target); | |
if (entry) { | |
callback(entry); | |
} | |
} | |
callbacks.add(callback); | |
} | |
unobserve(target: Element, callback: ResizeObserverEntryCallback): void { | |
const callbacks = this.#elementMap.get(target); | |
if (callbacks === undefined) return; | |
callbacks.delete(callback); | |
if (callbacks.size === 0) { | |
this.#vo.unobserve(target); | |
this.#elementMap.delete(target); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment