// packages/block-editor/src/components/writing-flow/use-drag-selection.js
import { useSelect, useDispatch } from "@wordpress/data";
import { useRefEffect } from "@wordpress/compose";
import { store as blockEditorStore } from "../../store";
function setContentEditableWrapper(node, value) {
  node.contentEditable = value;
  if (value) {
    node.focus();
  }
}
function useDragSelection() {
  const { startMultiSelect, stopMultiSelect } = useDispatch(blockEditorStore);
  const {
    isSelectionEnabled,
    hasSelectedBlock,
    isDraggingBlocks,
    isMultiSelecting
  } = useSelect(blockEditorStore);
  return useRefEffect(
    (node) => {
      const { ownerDocument } = node;
      const { defaultView } = ownerDocument;
      let anchorElement;
      let rafId;
      function onMouseUp() {
        stopMultiSelect();
        defaultView.removeEventListener("mouseup", onMouseUp);
        rafId = defaultView.requestAnimationFrame(() => {
          if (!hasSelectedBlock()) {
            return;
          }
          setContentEditableWrapper(node, false);
          const selection = defaultView.getSelection();
          if (selection.rangeCount) {
            const range = selection.getRangeAt(0);
            const { commonAncestorContainer } = range;
            const clonedRange = range.cloneRange();
            if (anchorElement.contains(commonAncestorContainer)) {
              anchorElement.focus();
              selection.removeAllRanges();
              selection.addRange(clonedRange);
            }
          }
        });
      }
      let lastMouseDownTarget;
      function onMouseDown({ target }) {
        lastMouseDownTarget = target;
      }
      function onMouseLeave({ buttons, target, relatedTarget }) {
        if (!target.contains(lastMouseDownTarget)) {
          return;
        }
        if (target.contains(relatedTarget)) {
          return;
        }
        if (isDraggingBlocks()) {
          return;
        }
        if (buttons !== 1) {
          return;
        }
        if (isMultiSelecting()) {
          return;
        }
        if (node === target) {
          return;
        }
        if (target.getAttribute("contenteditable") !== "true") {
          return;
        }
        if (!isSelectionEnabled()) {
          return;
        }
        anchorElement = target;
        startMultiSelect();
        defaultView.addEventListener("mouseup", onMouseUp);
        setContentEditableWrapper(node, true);
      }
      node.addEventListener("mouseout", onMouseLeave);
      node.addEventListener("mousedown", onMouseDown);
      return () => {
        node.removeEventListener("mouseout", onMouseLeave);
        defaultView.removeEventListener("mouseup", onMouseUp);
        defaultView.cancelAnimationFrame(rafId);
      };
    },
    [
      startMultiSelect,
      stopMultiSelect,
      isSelectionEnabled,
      hasSelectedBlock
    ]
  );
}
export {
  useDragSelection as default
};
//# sourceMappingURL=use-drag-selection.js.map
