'use strict';

var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
var _objectWithoutProperties = require('@babel/runtime/helpers/objectWithoutProperties');
var formik = require('formik');
var ramda = require('ramda');
var _asyncToGenerator = require('@babel/runtime/helpers/asyncToGenerator');
var React = require('react');
var neetoAtoms = require('@bigbinary/neeto-atoms');
var classnames = require('classnames');
var neetoCist = require('@bigbinary/neeto-cist');
var useOnClickOutside = require('@bigbinary/neeto-commons-frontend/v2/react-utils/useOnClickOutside');
var useStateWithDependency = require('@bigbinary/neeto-commons-frontend/v2/react-utils/useStateWithDependency');
var useHotkeys = require('@bigbinary/neeto-hotkeys');
var reactI18next = require('react-i18next');
var i18next = require('i18next');
var jsxRuntime = require('react/jsx-runtime');
var check = require('../check-VgZf0qTr.js');
var x = require('../x-B38UX0_0.js');
require('../createLucideIcon-DBDhE7kE.js');

var TOOLTIP_PROPS = {
  save: {
    content: i18next.t("neetoMolecules.common.actions.save"),
    position: "top",
    delay: 300
  },
  cancel: {
    content: i18next.t("neetoMolecules.common.actions.cancel"),
    position: "top",
    delay: 300
  }
};
var BUTTON_SIZE_BY_INPUT_SIZE = {
  small: "icon-xs",
  medium: "icon-sm",
  large: "icon"
};

// Used only when `textClassName` is set, to keep size baseline while letting
// the box grow with bigger fonts. Mirrors atoms Input's h-* per size.
var INPUT_MIN_HEIGHT_BY_SIZE = {
  small: "min-h-8 md:min-h-7",
  medium: "min-h-8",
  large: "min-h-10"
};

// Descendant selector targeting the inner <textarea> (atoms applies its own
// min-h-20/28 directly to the element; consumer className lands on outer div).
var TEXTAREA_DESCENDANT_MIN_H_BY_SIZE = {
  small: "[&_textarea]:!min-h-8 md:[&_textarea]:!min-h-7",
  medium: "[&_textarea]:!min-h-8",
  large: "[&_textarea]:!min-h-10"
};

var mergeRefs = function mergeRefs() {
  for (var _len = arguments.length, refs = new Array(_len), _key = 0; _key < _len; _key++) {
    refs[_key] = arguments[_key];
  }
  return function (node) {
    return refs.forEach(function (ref) {
      return typeof ref === "function" ? ref(node) : ref.current = node;
    });
  };
};

var _excluded$1 = ["saveOnBlur", "clearOnSave", "nullable", "value", "isSaving", "className", "handleSubmit", "handleCancel", "submitButtonProps", "cancelButtonProps", "dirty", "onInlineInputBlur", "size", "multiline", "textClassName"];
function ownKeys$1(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread$1(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$1(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$1(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _regenerator() { /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */ var e, t, r = "function" == typeof Symbol ? Symbol : {}, n = r.iterator || "@@iterator", o = r.toStringTag || "@@toStringTag"; function i(r, n, o, i) { var c = n && n.prototype instanceof Generator ? n : Generator, u = Object.create(c.prototype); return _regeneratorDefine2(u, "_invoke", function (r, n, o) { var i, c, u, f = 0, p = o || [], y = false, G = { p: 0, n: 0, v: e, a: d, f: d.bind(e, 4), d: function d(t, r) { return i = t, c = 0, u = e, G.n = r, a; } }; function d(r, n) { for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) { var o, i = p[t], d = G.p, l = i[2]; r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0)); } if (o || r > 1) return a; throw y = true, n; } return function (o, p, l) { if (f > 1) throw TypeError("Generator is already running"); for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) { i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u); try { if (f = 2, i) { if (c || (o = "next"), t = i[o]) { if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object"); if (!t.done) return t; u = t.value, c < 2 && (c = 0); } else 1 === c && (t = i["return"]) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1); i = e; } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break; } catch (t) { i = e, c = 1, u = t; } finally { f = 1; } } return { value: t, done: y }; }; }(r, o, i), true), u; } var a = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} t = Object.getPrototypeOf; var c = [][n] ? t(t([][n]())) : (_regeneratorDefine2(t = {}, n, function () { return this; }), t), u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c); function f(e) { return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine2(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine2(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine2(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine2(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine2(u), _regeneratorDefine2(u, o, "Generator"), _regeneratorDefine2(u, n, function () { return this; }), _regeneratorDefine2(u, "toString", function () { return "[object Generator]"; }), (_regenerator = function _regenerator() { return { w: i, m: f }; })(); }
function _regeneratorDefine2(e, r, n, t) { var i = Object.defineProperty; try { i({}, "", {}); } catch (e) { i = 0; } _regeneratorDefine2 = function _regeneratorDefine(e, r, n, t) { function o(r, n) { _regeneratorDefine2(e, r, function (e) { return this._invoke(r, n, e); }); } r ? i ? i(e, r, { value: n, enumerable: !t, configurable: !t, writable: !t }) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2)); }, _regeneratorDefine2(e, r, n, t); }
var InlineInput = /*#__PURE__*/React.forwardRef(function (props, ref) {
  var _BUTTON_SIZE_BY_INPUT, _INPUT_MIN_HEIGHT_BY_, _TEXTAREA_DESCENDANT_;
  var _useTranslation = reactI18next.useTranslation(),
    t = _useTranslation.t;
  var _props$saveOnBlur = props.saveOnBlur,
    saveOnBlur = _props$saveOnBlur === void 0 ? false : _props$saveOnBlur,
    _props$clearOnSave = props.clearOnSave,
    clearOnSave = _props$clearOnSave === void 0 ? false : _props$clearOnSave,
    _props$nullable = props.nullable,
    nullable = _props$nullable === void 0 ? false : _props$nullable,
    _props$value = props.value,
    value = _props$value === void 0 ? "" : _props$value,
    isSaving = props.isSaving,
    _props$className = props.className,
    className = _props$className === void 0 ? "" : _props$className,
    _props$handleSubmit = props.handleSubmit,
    handleSubmit = _props$handleSubmit === void 0 ? neetoCist.noop : _props$handleSubmit,
    _props$handleCancel = props.handleCancel,
    handleCancel = _props$handleCancel === void 0 ? neetoCist.noop : _props$handleCancel,
    _props$submitButtonPr = props.submitButtonProps,
    submitButtonProps = _props$submitButtonPr === void 0 ? {} : _props$submitButtonPr,
    _props$cancelButtonPr = props.cancelButtonProps,
    cancelButtonProps = _props$cancelButtonPr === void 0 ? {} : _props$cancelButtonPr,
    dirty = props.dirty,
    _props$onInlineInputB = props.onInlineInputBlur,
    onInlineInputBlur = _props$onInlineInputB === void 0 ? neetoCist.noop : _props$onInlineInputB,
    _props$size = props.size,
    size = _props$size === void 0 ? "medium" : _props$size,
    _props$multiline = props.multiline,
    multiline = _props$multiline === void 0 ? false : _props$multiline,
    _props$textClassName = props.textClassName,
    textClassName = _props$textClassName === void 0 ? "" : _props$textClassName,
    otherProps = _objectWithoutProperties(props, _excluded$1);
  var _useState = React.useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    isSubmitting = _useState2[0],
    setIsSubmitting = _useState2[1];
  var _useStateWithDependen = useStateWithDependency(String(value !== null && value !== void 0 ? value : "")),
    _useStateWithDependen2 = _slicedToArray(_useStateWithDependen, 2),
    internalValue = _useStateWithDependen2[0],
    setInternalValue = _useStateWithDependen2[1];
  var inputRef = React.useRef(null);
  var inputWrapperRef = React.useRef(null);
  var trimmedValue = internalValue.trim();
  var isValidValue = nullable || neetoCist.isNotEmpty(trimmedValue) && ramda.isNotNil(trimmedValue);
  var isDirty = internalValue !== value || dirty;
  var saveDisabled = !isValidValue || isSubmitting || isSaving || submitButtonProps.disabled || !isDirty;
  var buttonSize = (_BUTTON_SIZE_BY_INPUT = BUTTON_SIZE_BY_INPUT_SIZE[size]) !== null && _BUTTON_SIZE_BY_INPUT !== void 0 ? _BUTTON_SIZE_BY_INPUT : "icon";
  var hasCustomText = neetoCist.isNotEmpty(textClassName);
  var inputMinHeight = (_INPUT_MIN_HEIGHT_BY_ = INPUT_MIN_HEIGHT_BY_SIZE[size]) !== null && _INPUT_MIN_HEIGHT_BY_ !== void 0 ? _INPUT_MIN_HEIGHT_BY_ : INPUT_MIN_HEIGHT_BY_SIZE.medium;
  var textareaDescendantMinH = (_TEXTAREA_DESCENDANT_ = TEXTAREA_DESCENDANT_MIN_H_BY_SIZE[size]) !== null && _TEXTAREA_DESCENDANT_ !== void 0 ? _TEXTAREA_DESCENDANT_ : TEXTAREA_DESCENDANT_MIN_H_BY_SIZE.medium;
  var handleFocusOut = function handleFocusOut() {
    if (!isValidValue || isSubmitting) return;
    onInlineInputBlur(trimmedValue);
    if (saveOnBlur && isDirty) {
      onSubmit();
      return;
    }
    onCancel();
  };
  useOnClickOutside(inputWrapperRef, handleFocusOut);
  var onSubmit = /*#__PURE__*/function () {
    var _ref = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee() {
      return _regenerator().w(function (_context) {
        while (1) switch (_context.p = _context.n) {
          case 0:
            setIsSubmitting(true);
            _context.p = 1;
            _context.n = 2;
            return handleSubmit(trimmedValue);
          case 2:
            clearOnSave && setInternalValue("");
          case 3:
            _context.p = 3;
            setIsSubmitting(false);
            return _context.f(3);
          case 4:
            return _context.a(2);
        }
      }, _callee, null, [[1,, 3, 4]]);
    }));
    return function onSubmit() {
      return _ref.apply(this, arguments);
    };
  }();
  var onCancel = function onCancel() {
    handleCancel(trimmedValue);
  };
  var closeRef = useHotkeys("escape", function (event) {
    event.stopPropagation();
    onCancel();
  }, {
    mode: "scoped"
  });
  var submitHotkey = multiline ? "command+return" : ["command+return", "return"];
  var submitRef = useHotkeys(submitHotkey, function () {
    return onSubmit();
  }, {
    mode: "scoped",
    enabled: isValidValue
  });
  React.useLayoutEffect(function () {
    var _inputWrapperRef$curr;
    var selector = multiline ? "textarea" : "input";
    var inputElement = (_inputWrapperRef$curr = inputWrapperRef.current) === null || _inputWrapperRef$curr === void 0 ? void 0 : _inputWrapperRef$curr.querySelector(selector);
    mergeRefs(inputRef, closeRef, submitRef)(inputElement);
  }, [multiline]);
  React.useEffect(function () {
    return inputRef.current && inputRef.current.focus();
  }, [isSubmitting]);
  var suffixContent = /*#__PURE__*/jsxRuntime.jsxs(jsxRuntime.Fragment, {
    children: [/*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Tooltip, _objectSpread$1(_objectSpread$1({}, TOOLTIP_PROPS.save), {}, {
      children: /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Button, _objectSpread$1(_objectSpread$1({
        "aria-label": t("neetoMolecules.common.actions.save"),
        "data-testid": "neeto-molecules-autosave-input-save",
        icon: check.Check,
        loading: isSubmitting || isSaving,
        size: buttonSize,
        variant: "ghost",
        onClick: onSubmit
      }, submitButtonProps), {}, {
        disabled: saveDisabled
      }))
    })), /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Tooltip, _objectSpread$1(_objectSpread$1({}, TOOLTIP_PROPS.cancel), {}, {
      children: /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Button, _objectSpread$1(_objectSpread$1({
        ref: ref,
        "aria-label": t("neetoMolecules.common.actions.cancel"),
        "data-testid": "neeto-molecules-autosave-input-cancel",
        icon: x.X,
        size: buttonSize,
        variant: "ghost",
        onClick: onCancel
      }, cancelButtonProps), {}, {
        disabled: isSubmitting || isSaving || cancelButtonProps.disabled
      }))
    }))]
  });
  var wrapperClassName = classnames("flex flex-grow", "[&_[data-slot=input-group-addon]>span]:!gap-0.5 [&_[data-slot=input-group-addon]>span]:!text-foreground", _defineProperty(_defineProperty(_defineProperty(_defineProperty({}, className, className), textClassName, hasCustomText), "[&_input]:![font-size:inherit] [&_input]:![font-weight:inherit] [&_input]:![font-family:inherit] [&_input]:![line-height:inherit]", hasCustomText && !multiline), "[&_textarea]:![field-sizing:content] [&_textarea]:![font-size:inherit] [&_textarea]:![font-weight:inherit] [&_textarea]:![font-family:inherit] [&_textarea]:![line-height:inherit]", hasCustomText && multiline), hasCustomText && multiline && textareaDescendantMinH);
  var inputCustomClassName = hasCustomText && !multiline ? classnames("h-auto py-1.5", inputMinHeight) : "";
  var inheritFontStyle = hasCustomText ? {
    fontSize: "inherit",
    fontWeight: "inherit",
    fontFamily: "inherit",
    lineHeight: "inherit"
  } : undefined;
  var SharedProps = {
    "aria-label": t("neetoMolecules.inlineInput.editableField"),
    "data-testid": "neeto-molecules-autosave-input",
    disabled: isSubmitting,
    disableTrimOnBlur: true,
    size: size,
    suffix: suffixContent,
    value: internalValue,
    onChange: function onChange(e) {
      var _otherProps$onChange;
      otherProps === null || otherProps === void 0 || (_otherProps$onChange = otherProps.onChange) === null || _otherProps$onChange === void 0 || _otherProps$onChange.call(otherProps, e);
      setInternalValue(e.target.value);
    }
  };
  return /*#__PURE__*/jsxRuntime.jsx("div", {
    className: wrapperClassName,
    ref: inputWrapperRef,
    children: multiline ? /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Textarea, _objectSpread$1(_objectSpread$1(_objectSpread$1({}, SharedProps), otherProps), {}, {
      resize: "none",
      style: inheritFontStyle ? _objectSpread$1(_objectSpread$1({}, inheritFontStyle), otherProps.style || {}) : otherProps.style
    })) : /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Input, _objectSpread$1(_objectSpread$1(_objectSpread$1({}, SharedProps), otherProps), {}, {
      className: classnames(inputCustomClassName, otherProps.className),
      style: inheritFontStyle ? _objectSpread$1(_objectSpread$1({}, inheritFontStyle), otherProps.style || {}) : otherProps.style
    }))
  });
});
InlineInput.displayName = "InlineInput";

var _excluded = ["name"];
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var FormikInlineInput = function FormikInlineInput(_ref) {
  var name = _ref.name,
    props = _objectWithoutProperties(_ref, _excluded);
  var _useField = formik.useField(name),
    _useField2 = _slicedToArray(_useField, 3),
    field = _useField2[0],
    meta = _useField2[1],
    _useField2$ = _useField2[2],
    setValue = _useField2$.setValue,
    setTouched = _useField2$.setTouched;
  var _useFormikContext = formik.useFormikContext(),
    submitForm = _useFormikContext.submitForm,
    isSubmitting = _useFormikContext.isSubmitting,
    resetForm = _useFormikContext.resetForm,
    dirty = _useFormikContext.dirty;
  var handleSubmit = function handleSubmit(value) {
    var _props$handleSubmit;
    setValue(value);
    (_props$handleSubmit = props.handleSubmit) === null || _props$handleSubmit === void 0 || _props$handleSubmit.call(props, value);
    return submitForm();
  };
  return /*#__PURE__*/jsxRuntime.jsx(InlineInput, _objectSpread(_objectSpread(_objectSpread({
    error: meta.touched ? meta.error : "",
    isSaving: isSubmitting
  }, props), {}, {
    handleCancel: function handleCancel() {
      var _props$handleCancel;
      resetForm();
      (_props$handleCancel = props.handleCancel) === null || _props$handleCancel === void 0 || _props$handleCancel.call(props);
    }
  }, _objectSpread(_objectSpread({
    handleSubmit: handleSubmit
  }, ramda.omit(["onBlur"], field)), {}, {
    dirty: dirty
  })), {}, {
    onInlineInputBlur: function onInlineInputBlur(trimmedValue) {
      setValue(trimmedValue);
      setTouched(true);
    }
  }));
};

exports.FormikInlineInput = FormikInlineInput;
exports.InlineInput = InlineInput;
//# sourceMappingURL=InlineInput.js.map
