import {
  getPointerInfo,
  stopEventPropagation,
  useEditor,
  useValue
} from "@tldraw/editor";
import { useCallback, useEffect, useRef } from "react";
import { INDENT, TextHelpers } from "./TextHelpers.mjs";
function useEditableText(id, type, text) {
  const editor = useEditor();
  const rInput = useRef(null);
  const rSelectionRanges = useRef();
  const isEditing = useValue("isEditing", () => editor.getEditingShapeId() === id, [editor]);
  const isEditingAnything = useValue("isEditingAnything", () => !!editor.getEditingShapeId(), [
    editor
  ]);
  useEffect(() => {
    function selectAllIfEditing({ shapeId }) {
      requestAnimationFrame(() => {
        if (shapeId === id) {
          const elm = rInput.current;
          if (elm) {
            if (document.activeElement !== elm) {
              elm.focus();
            }
            elm.select();
          }
        }
      });
    }
    editor.on("select-all-text", selectAllIfEditing);
    return () => {
      editor.off("select-all-text", selectAllIfEditing);
    };
  }, [editor, id]);
  useEffect(() => {
    if (!isEditing)
      return;
    const elm = rInput.current;
    if (!elm)
      return;
    if (document.activeElement !== elm) {
      elm.focus();
      if (editor.getInstanceState().isCoarsePointer) {
        elm.select();
      }
    } else {
      if (editor.environment.isSafari) {
        elm.blur();
        elm.focus();
      }
    }
    function updateSelection() {
      const selection = window.getSelection?.();
      if (selection && selection.type !== "None") {
        const ranges = [];
        for (let i = 0; i < selection.rangeCount; i++) {
          ranges.push(selection.getRangeAt?.(i));
        }
        rSelectionRanges.current = ranges;
      }
    }
    document.addEventListener("selectionchange", updateSelection);
    return () => {
      document.removeEventListener("selectionchange", updateSelection);
    };
  }, [editor, isEditing]);
  const handleBlur = useCallback(() => {
    const ranges = rSelectionRanges.current;
    requestAnimationFrame(() => {
      const elm = rInput.current;
      const editingShapeId = editor.getEditingShapeId();
      if (editingShapeId) {
        if (elm && editingShapeId === id) {
          elm.focus();
          if (ranges && ranges.length) {
            const selection = window.getSelection();
            if (selection) {
              ranges.forEach((range) => selection.addRange(range));
            }
          }
        }
      } else {
        window.getSelection()?.removeAllRanges();
      }
    });
  }, [editor, id]);
  const handleKeyDown = useCallback(
    (e) => {
      if (editor.getEditingShapeId() !== id)
        return;
      switch (e.key) {
        case "Enter": {
          if (e.ctrlKey || e.metaKey) {
            editor.complete();
          }
          break;
        }
      }
    },
    [editor, id]
  );
  const handleChange = useCallback(
    (e) => {
      if (editor.getEditingShapeId() !== id)
        return;
      let text2 = TextHelpers.normalizeText(e.currentTarget.value);
      const untabbedText = text2.replace(/\t/g, INDENT);
      if (untabbedText !== text2) {
        const selectionStart = e.currentTarget.selectionStart;
        e.currentTarget.value = untabbedText;
        e.currentTarget.selectionStart = selectionStart + (untabbedText.length - text2.length);
        e.currentTarget.selectionEnd = selectionStart + (untabbedText.length - text2.length);
        text2 = untabbedText;
      }
      editor.updateShape({
        id,
        type,
        props: { text: text2 }
      });
    },
    [editor, id, type]
  );
  const handleInputPointerDown = useCallback(
    (e) => {
      if (!isEditing)
        return;
      editor.dispatch({
        ...getPointerInfo(e),
        type: "pointer",
        name: "pointer_down",
        target: "shape",
        shape: editor.getShape(id)
      });
      stopEventPropagation(e);
    },
    [editor, id, isEditing]
  );
  return {
    rInput,
    handleFocus: noop,
    handleBlur,
    handleKeyDown,
    handleChange,
    handleInputPointerDown,
    handleDoubleClick: stopEventPropagation,
    isEmpty: text.trim().length === 0,
    isEditing,
    isEditingAnything
  };
}
function noop() {
  return;
}
export {
  useEditableText
};
//# sourceMappingURL=useEditableText.mjs.map
