Skip to content

Commit

Permalink
utils.js: add options to waitForChildAdd()
Browse files Browse the repository at this point in the history
By default, waitForChildAdd() will no longer check the predicate on
attribute changes. None of its callers depended on this behavior, so the
callback and predicate were running hundreds of times unnecessarily.

If you want to use the old behavior, set checkAttrs to true in the new
options argument.

The abortSignal argument has also been moved into options.
  • Loading branch information
throwaway96 committed Mar 27, 2024
1 parent 559e95f commit 46e7e38
Showing 1 changed file with 17 additions and 5 deletions.
22 changes: 17 additions & 5 deletions src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,14 +87,22 @@ export function handleLaunch(params) {
}

/**
* Wait for a child element to be added that holds true for a predicate
* Wait for a child element to be added for which a predicate is true.
*
* Note that by default, the predicate is checked only when the node is added.
* If you want the predicate to run every time an attribute is modified, set
* `options.checkAttrs` to true.
* @template T
* @param {Element} parent
* @param {(node: Node) => node is T} predicate
* @param {AbortSignal=} abortSignal
* @param {(node: Node) => node is T} predicate Function that checks whether its argument is the desired element
* @param {Object=} options
* @param {AbortSignal=} options.abortSignal Signal that can be used to stop waiting
* @param {boolean} [options.checkAttrs=false] Also run predicate on attribute changes
* @return {Promise<T>}
*/
export async function waitForChildAdd(parent, predicate, abortSignal) {
export async function waitForChildAdd(parent, predicate, options) {
const { abortSignal, checkAttrs = false } = options ?? {};

return new Promise((resolve, reject) => {
const obs = new MutationObserver((mutations) => {
for (const mut of mutations) {
Expand Down Expand Up @@ -128,6 +136,10 @@ export async function waitForChildAdd(parent, predicate, abortSignal) {
});
}

obs.observe(parent, { subtree: true, attributes: true, childList: true });
obs.observe(parent, {
subtree: true,
attributes: checkAttrs,
childList: true
});
});
}

0 comments on commit 46e7e38

Please sign in to comment.