"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var useEditableText_exports = {};
__export(useEditableText_exports, {
  useEditableText: () => useEditableText
});
module.exports = __toCommonJS(useEditableText_exports);
var import_editor = require("@tldraw/editor");
var import_react = require("react");
var import_TextHelpers = require("./TextHelpers");
function useEditableText(id, type, text) {
  const editor = (0, import_editor.useEditor)();
  const rInput = (0, import_react.useRef)(null);
  const rSelectionRanges = (0, import_react.useRef)();
  const isEditing = (0, import_editor.useValue)("isEditing", () => editor.getEditingShapeId() === id, [editor]);
  const isEditingAnything = (0, import_editor.useValue)("isEditingAnything", () => !!editor.getEditingShapeId(), [
    editor
  ]);
  (0, import_react.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]);
  (0, import_react.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 = (0, import_react.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 = (0, import_react.useCallback)(
    (e) => {
      if (editor.getEditingShapeId() !== id)
        return;
      switch (e.key) {
        case "Enter": {
          if (e.ctrlKey || e.metaKey) {
            editor.complete();
          }
          break;
        }
      }
    },
    [editor, id]
  );
  const handleChange = (0, import_react.useCallback)(
    (e) => {
      if (editor.getEditingShapeId() !== id)
        return;
      let text2 = import_TextHelpers.TextHelpers.normalizeText(e.currentTarget.value);
      const untabbedText = text2.replace(/\t/g, import_TextHelpers.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 = (0, import_react.useCallback)(
    (e) => {
      if (!isEditing)
        return;
      editor.dispatch({
        ...(0, import_editor.getPointerInfo)(e),
        type: "pointer",
        name: "pointer_down",
        target: "shape",
        shape: editor.getShape(id)
      });
      (0, import_editor.stopEventPropagation)(e);
    },
    [editor, id, isEditing]
  );
  return {
    rInput,
    handleFocus: noop,
    handleBlur,
    handleKeyDown,
    handleChange,
    handleInputPointerDown,
    handleDoubleClick: import_editor.stopEventPropagation,
    isEmpty: text.trim().length === 0,
    isEditing,
    isEditingAnything
  };
}
function noop() {
  return;
}
//# sourceMappingURL=useEditableText.js.map
