/**
 * Waits for an element to appear
 *
 * In normal circumstances *please* use the mutation observer for these kinds of tasks.
 * However, shadowDom attachment is **not** covered by the mutation observer,
 * so a solution like this is required.
 */
export async function waitForElement(query: () => HTMLElement, maxAttempts = 10, retryAfterMs = 10) {
  let tries = 0;
  return new Promise<void>(resolve => {
    const interval = setInterval(() => {
      if (tries > maxAttempts) {
        clearInterval(interval);
        throw new Error('Element not found');
      }
      if (query()) {
        clearInterval(interval);
        resolve();
      }
      tries++;
    }, retryAfterMs);
  });
}
