blob: ca61e2c25ec0820e9c414f39302d5e3bc44aa7d2 [file] [log] [blame]
/**
* @license
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export function queryAll<E extends Element = Element>(
el: Element,
selector: string
): NodeListOf<E> {
if (!el) throw new Error('element not defined');
const root = el.shadowRoot ?? el;
return root.querySelectorAll<E>(selector);
}
export function query<E extends Element = Element>(
el: Element | undefined,
selector: string
): E | undefined {
if (!el) return undefined;
const root = el.shadowRoot ?? el;
return root.querySelector<E>(selector) ?? undefined;
}
export function queryAndAssert<E extends Element = Element>(
el: Element | undefined,
selector: string
): E {
const found = query<E>(el, selector);
if (!found) throw new Error(`selector '${selector}' did not match anything'`);
return found;
}
export function waitUntil(
predicate: () => boolean,
maxMillis = 100
): Promise<void> {
const start = Date.now();
let sleep = 1;
return new Promise((resolve, reject) => {
const waiter = () => {
if (predicate()) {
return resolve();
}
if (Date.now() - start >= maxMillis) {
return reject(new Error('Took to long to waitUntil'));
}
setTimeout(waiter, sleep);
sleep *= 2;
};
waiter();
});
}