import { useState, useLayoutEffect, useEffect } from 'react';

function getMentionNodes(root) {
  if (root) {
    const mentions = root.querySelectorAll("[data-sb-mention='true']");
    const mentionsArray = Array.from(mentions);
    return mentionsArray;
  }
  return [];
}

/**
 * This is a dirty way to get the mentions given DOM node
 */
function useDirtyGetMentions(_ref, _ref2) {
  let {
    ref
  } = _ref;
  let {
    logger
  } = _ref2;
  // Select the node that will be observed for mutations
  const targetNode = ref.current;
  const [mentionNodes, setMentionNodes] = useState([]);

  // to get the initial mentions
  useLayoutEffect(() => {
    if (targetNode) {
      const mentions = getMentionNodes(targetNode);
      setMentionNodes(mentions);
    }
  }, [targetNode]);
  useEffect(() => {
    // Options for the observer (which mutations to observe)
    const config = {
      childList: true,
      subtree: true
    };

    // Callback function to execute when mutations are observed
    const callback = mutationList => {
      const hasMutation = mutationList.length > 0;
      if (hasMutation) {
        setMentionNodes(getMentionNodes(targetNode));
      }
    };

    // Create an observer instance linked to the callback function
    const observer = new MutationObserver(callback);
    if (targetNode) {
      // Start observing the target node for configured mutations
      observer.observe(targetNode, config);
      logger.info('useDirtyGetMentions: observer started', {
        observer,
        config
      });
    }
    return () => {
      try {
        observer.disconnect();
        logger.info('useDirtyGetMentions: observer disconnected', {
          observer
        });
      } catch (error) {
        logger.error('useDirtyGetMentions: observer disconnect failed', {
          observer
        });
      }
    };
  }, [targetNode]);
  return mentionNodes;
}

export { useDirtyGetMentions as u };
//# sourceMappingURL=useDirtyGetMentions-5f675b6c.js.map
