File size: 1,123 Bytes
57aa51e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import { useEffect, useState } from "react";

/**
 * useWaitForClass
 *
 * Watches the DOM for the presence of a CSS class and resolves when found.
 *
 * @param className - The class to wait for (without the dot, e.g. "my-element")
 * @param root - The root node to observe (defaults to document.body)
 * @returns A boolean indicating if the class is currently present
 */
export function useWaitForClass(className: string, root: HTMLElement | null = null): boolean {
  const [found, setFound] = useState(false);

  useEffect(() => {
    const target = root ?? document.body;

    if (!target) return;

    // Check immediately in case the element is already present
    if (target.querySelector(`.${className}`)) {
      setFound(true);
      return;
    }

    const observer = new MutationObserver(() => {
      if (target.querySelector(`.${className}`)) {
        setFound(true);
        observer.disconnect();
      }
    });

    observer.observe(target, {
      childList: true,
      subtree: true,
      attributes: true,
    });

    return () => observer.disconnect();
  }, [className, root]);

  return found;
}