'use strict';

var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
var React = require('react');
var neetoAtoms = require('@bigbinary/neeto-atoms');
var formik$1 = require('@bigbinary/neeto-atoms/formik');
var classnames = require('classnames');
var formik = require('formik');
var neetoCist = require('@bigbinary/neeto-cist');
var FormikEditor = require('@bigbinary/neeto-editor/v2/FormikEditor');
var ramda = require('ramda');
var reactI18next = require('react-i18next');
var injectCss = require('../inject-css-B6qYtOJe.js');
var useHotkeys = require('@bigbinary/neeto-hotkeys');
var ImageUploader = require('@bigbinary/neeto-image-uploader-frontend/ImageUploader');
var jsxRuntime = require('react/jsx-runtime');
var i18next = require('i18next');
var createLucideIcon = require('../createLucideIcon-DBDhE7kE.js');
var ellipsis = require('../ellipsis-BcfLTtl5.js');

/**
 * @license lucide-react v1.7.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */


const __iconNode = [
  ["rect", { width: "18", height: "18", x: "3", y: "3", rx: "2", ry: "2", key: "1m3agn" }],
  ["circle", { cx: "9", cy: "9", r: "2", key: "af1f0g" }],
  ["path", { d: "m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21", key: "1xmnt7" }]
];
const Image = createLucideIcon.createLucideIcon("image", __iconNode);

var EDITOR_ADDONS = ["highlight", "emoji", "video-upload", "code-block", "block-quote", "image-upload", "image-upload-unsplash", "divider", "video-embed", "undo", "redo", "table", "callout"];
var DEFAULT_EDITOR_PROPS = {
  isMenuIndependent: true,
  addons: [],
  size: "medium"
};
var IMAGE_UPLOAD_CONFIG = {
  maxImageSize: 1,
  allowedImageTypes: {
    "image/jpg": [".jpg", ".jpeg"],
    "image/png": [".png"],
    "image/svg": [".svg"]
  }
};

var css = ".nm-document-editor__wrapper{color:var(--foreground);height:100%}@media screen and (max-width:768px){.nm-document-editor__wrapper{width:100%}}.nm-document-editor__container{margin:0 auto;max-width:48rem!important;width:100%}.nm-document-editor__menubar{background-color:var(--background);position:sticky;top:0;width:100%;z-index:20}.nm-document-editor__menubar .neeto-editor-fixed-menu,.nm-document-editor__menubar.neeto-editor-fixed-menu{width:100%}.nm-document-editor__title{margin-top:1.5rem;width:100%}.nm-document-editor__title textarea{field-sizing:content!important;background-color:transparent;color:var(--foreground);font-size:2.625rem;font-weight:700;line-height:1.15;max-height:none;min-height:1lh!important;overflow:hidden!important;padding:0;resize:none}.nm-document-editor__title textarea,.nm-document-editor__title textarea:focus-visible,.nm-document-editor__title textarea[aria-invalid=true],.nm-document-editor__title textarea[aria-invalid=true]:focus-visible{border-color:transparent!important;box-shadow:none!important}.nm-document-editor__title textarea::-moz-placeholder{color:var(--muted-foreground);opacity:.5}.nm-document-editor__title textarea::placeholder{color:var(--muted-foreground);opacity:.5}@media screen and (max-width:1024px){.nm-document-editor__title textarea{font-size:2rem;line-height:1.25}}.nm-document-editor__error{margin:.75rem auto}.nm-document-editor__thumbnail{background-color:var(--muted);border-radius:.5rem;overflow:hidden;padding-bottom:56.25%;position:relative;width:100%}.nm-document-editor__thumbnail img{height:100%;inset-inline-start:0;-o-object-fit:cover;object-fit:cover;position:absolute;top:0;width:100%}.nm-document-editor__wrapper .neeto-editor-fixed-menu{border-inline-end:0!important;border-inline-start:0!important;border-radius:0!important}.nm-document-editor__wrapper .neeto-editor-fixed-menu__wrapper{margin:0 auto;max-width:46.875rem;padding-block:.375rem}.nm-document-editor__wrapper button.ne-toolbar-item{border-radius:.5rem!important}@media screen and (max-width:768px){.nm-document-editor__wrapper .neeto-editor-fixed-menu__wrapper{overflow-x:auto}}.nm-document-editor__wrapper .ProseMirror{flex-grow:1;height:auto;max-height:none;outline:none;overflow-y:hidden}.nm-document-editor__wrapper .ProseMirror p.is-editor-empty:first-child:before{color:var(--muted-foreground);content:attr(data-placeholder);float:left;height:0;opacity:.5;pointer-events:none}.nm-document-editor__wrapper .editor-content__wrapper{border:none!important;padding:.75rem 1.5rem 2rem!important;width:100%!important}.nm-document-editor__wrapper .editor-content-attachments{border:none;margin:.75rem auto 0;max-width:48rem!important;padding-inline-end:1rem;padding-inline-start:1rem}.nm-document-editor__wrapper .editor-content-attachments--no-attachments{display:none!important}.nm-document-editor__wrapper .neeto-editor-character-count{color:var(--muted-foreground);font-size:.75rem;margin:0 auto;max-width:48rem!important;padding-inline-end:1rem;padding-inline-start:1rem}.nm-document-editor__wrapper .ne-attachments__wrapper{width:100%}.nm-document-editor__wrapper ins{background-color:#c1f4cb!important;text-decoration:none!important}.nm-document-editor__wrapper del{background-color:#faa!important}";
injectCss.n(css,{});

var useEditor = function useEditor(_ref) {
  var onContentChange = _ref.onContentChange,
    editorContentFieldName = _ref.editorContentFieldName,
    onAttachmentChange = _ref.onAttachmentChange,
    onTitleChange = _ref.onTitleChange,
    titleFieldName = _ref.titleFieldName,
    editorRef = _ref.editorRef,
    titleRef = _ref.titleRef;
  var _useFormikContext = formik.useFormikContext(),
    setFieldValue = _useFormikContext.setFieldValue,
    errors = _useFormikContext.errors;
  var handleContentChange = React.useCallback(function (content) {
    setFieldValue(editorContentFieldName, content);
    onContentChange === null || onContentChange === void 0 || onContentChange(content);
  }, [editorContentFieldName, onContentChange, setFieldValue]);
  var handleAttachmentChange = React.useCallback(function (attachments) {
    setFieldValue("attachments", attachments);
    onAttachmentChange === null || onAttachmentChange === void 0 || onAttachmentChange(attachments);
  }, [onAttachmentChange, setFieldValue]);
  var handleTitleChange = function handleTitleChange(event) {
    var title = event.target.value;
    setFieldValue(titleFieldName, title);
    onTitleChange === null || onTitleChange === void 0 || onTitleChange(title);
  };
  var handleEditorBackspaceKeypress = function handleEditorBackspaceKeypress() {
    var _editorRef$current, _editor$state;
    var editor = (_editorRef$current = editorRef.current) === null || _editorRef$current === void 0 ? void 0 : _editorRef$current.editor;
    var selection = editor === null || editor === void 0 || (_editor$state = editor.state) === null || _editor$state === void 0 ? void 0 : _editor$state.selection;
    if (editor !== null && editor !== void 0 && editor.isFocused && neetoCist.isPresent(titleRef.current) && (selection === null || selection === void 0 ? void 0 : selection.anchor) === 1) {
      var title = titleRef.current.value;
      titleRef.current.focus();
      titleRef.current.setSelectionRange(title === null || title === void 0 ? void 0 : title.length, title === null || title === void 0 ? void 0 : title.length);
    }
  };
  var titleHotkeyRef = useHotkeys("return", function () {
    var _editorRef$current2, _editorRef$current3;
    (_editorRef$current2 = editorRef.current) === null || _editorRef$current2 === void 0 || (_editorRef$current2 = _editorRef$current2.editor) === null || _editorRef$current2 === void 0 || (_editorRef$current2 = _editorRef$current2.commands) === null || _editorRef$current2 === void 0 || _editorRef$current2.insertContentAt(0, "<p />");
    (_editorRef$current3 = editorRef.current) === null || _editorRef$current3 === void 0 || (_editorRef$current3 = _editorRef$current3.editor) === null || _editorRef$current3 === void 0 || (_editorRef$current3 = _editorRef$current3.commands) === null || _editorRef$current3 === void 0 || _editorRef$current3.focus("start");
  }, {
    mode: "scoped"
  });
  var editorHotkeyRef = useHotkeys("backspace", handleEditorBackspaceKeypress, {
    mode: "scoped"
  });
  return {
    handleContentChange: handleContentChange,
    handleAttachmentChange: handleAttachmentChange,
    handleTitleChange: handleTitleChange,
    editorHotkeyRef: editorHotkeyRef,
    titleHotkeyRef: titleHotkeyRef,
    errors: errors
  };
};

var MediaUploader = function MediaUploader(_ref) {
  var setIsThumbnailImageModalOpen = _ref.setIsThumbnailImageModalOpen;
  var _useFormikContext = formik.useFormikContext(),
    thumbnailImageUrl = _useFormikContext.values.thumbnailImageUrl,
    setFieldValue = _useFormikContext.setFieldValue,
    initialValues = _useFormikContext.initialValues,
    submitForm = _useFormikContext.submitForm;
  var handleUpload = function handleUpload(file) {
    var url = file.url,
      signedId = file.signedId;
    setFieldValue("thumbnailImage", signedId);
    setFieldValue("thumbnailImageUrl", url);
    setTimeout(function () {
      setIsThumbnailImageModalOpen(false);
      submitForm();
    });
  };
  if (ramda.isEmpty(initialValues)) {
    return /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Spinner, {});
  }
  return /*#__PURE__*/jsxRuntime.jsx(ImageUploader, {
    className: "h-auto w-full",
    src: thumbnailImageUrl,
    uploadConfig: IMAGE_UPLOAD_CONFIG,
    onUploadComplete: handleUpload
  }, thumbnailImageUrl);
};

var getThumbnailAddon = function getThumbnailAddon(command) {
  return {
    label: i18next.t("neetoMolecules.documentEditor.thumbnailImage"),
    optionName: "thumbnail-image",
    command: command,
    icon: Image,
    isEnabled: true,
    "data-testid": "thumbnail-image-addon"
  };
};

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 Editor = function Editor(_ref) {
  var attachments = _ref.attachments,
    onContentChange = _ref.onContentChange,
    onAttachmentChange = _ref.onAttachmentChange,
    onTitleChange = _ref.onTitleChange,
    _ref$getTitleRef = _ref.getTitleRef,
    getTitleRef = _ref$getTitleRef === void 0 ? neetoCist.noop : _ref$getTitleRef,
    _ref$getEditorRef = _ref.getEditorRef,
    getEditorRef = _ref$getEditorRef === void 0 ? neetoCist.noop : _ref$getEditorRef,
    menuClassName = _ref.menuClassName,
    _ref$editorContentFie = _ref.editorContentFieldName,
    editorContentFieldName = _ref$editorContentFie === void 0 ? "htmlContent" : _ref$editorContentFie,
    _ref$titleFieldName = _ref.titleFieldName,
    titleFieldName = _ref$titleFieldName === void 0 ? "title" : _ref$titleFieldName,
    _ref$editorProps = _ref.editorProps,
    customEditorProps = _ref$editorProps === void 0 ? {} : _ref$editorProps,
    _ref$titleProps = _ref.titleProps,
    titleProps = _ref$titleProps === void 0 ? {} : _ref$titleProps,
    _ref$hasThumbnailImag = _ref.hasThumbnailImage,
    hasThumbnailImage = _ref$hasThumbnailImag === void 0 ? false : _ref$hasThumbnailImag,
    children = _ref.children;
  var _useTranslation = reactI18next.useTranslation(),
    t = _useTranslation.t;
  var _useFormikContext = formik.useFormikContext(),
    values = _useFormikContext.values,
    setFieldValue = _useFormikContext.setFieldValue,
    submitForm = _useFormikContext.submitForm;
  var thumbnailImageUrl = values.thumbnailImageUrl;
  var titleRef = React.useRef();
  var editorRef = React.useRef();
  var _useState = React.useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    isThumbnailImageModalOpen = _useState2[0],
    setIsThumbnailImageModalOpen = _useState2[1];
  var editorProps = React.useMemo(function () {
    var baseProps = ramda.mergeRight(DEFAULT_EDITOR_PROPS, customEditorProps);
    if (!hasThumbnailImage) return baseProps;
    var thumbnailAddon = getThumbnailAddon(function () {
      return setIsThumbnailImageModalOpen(true);
    });
    return ramda.mergeRight(baseProps, {
      addonCommands: [thumbnailAddon]
    });
  }, [customEditorProps, hasThumbnailImage]);
  var _useEditor = useEditor({
      onContentChange: onContentChange,
      editorContentFieldName: editorContentFieldName,
      onAttachmentChange: onAttachmentChange,
      onTitleChange: onTitleChange,
      titleFieldName: titleFieldName,
      editorRef: editorRef,
      titleRef: titleRef
    }),
    handleContentChange = _useEditor.handleContentChange,
    handleAttachmentChange = _useEditor.handleAttachmentChange,
    handleTitleChange = _useEditor.handleTitleChange,
    editorHotkeyRef = _useEditor.editorHotkeyRef,
    titleHotkeyRef = _useEditor.titleHotkeyRef,
    errors = _useEditor.errors;
  var setTitleRef = function setTitleRef(node) {
    titleHotkeyRef.current = node;
    getTitleRef(node);
    titleRef.current = node;
  };
  var setEditorRef = React.useCallback(function (node) {
    editorRef.current = node;
    getEditorRef(node);
  }, []);
  var addons = React.useMemo(function () {
    return EDITOR_ADDONS.concat(editorProps.addons || []);
  }, [editorProps.addons]);
  var handleTab = function handleTab() {
    var _editorRef$current, _editorRef$current2;
    var isListActive = ((_editorRef$current = editorRef.current) === null || _editorRef$current === void 0 || (_editorRef$current = _editorRef$current.editor) === null || _editorRef$current === void 0 ? void 0 : _editorRef$current.isActive("orderedList")) || ((_editorRef$current2 = editorRef.current) === null || _editorRef$current2 === void 0 || (_editorRef$current2 = _editorRef$current2.editor) === null || _editorRef$current2 === void 0 ? void 0 : _editorRef$current2.isActive("bulletList"));
    if (isListActive) {
      var _editorRef$current3;
      (_editorRef$current3 = editorRef.current) === null || _editorRef$current3 === void 0 || (_editorRef$current3 = _editorRef$current3.editor) === null || _editorRef$current3 === void 0 || (_editorRef$current3 = _editorRef$current3.commands) === null || _editorRef$current3 === void 0 || _editorRef$current3.sinkListItem("listItem");
      return true;
    }
    return true;
  };
  var handleDeleteThumbnail = function handleDeleteThumbnail() {
    setFieldValue("thumbnailImage", "");
    setFieldValue("thumbnailImageUrl", "");
    setTimeout(submitForm);
  };
  return /*#__PURE__*/jsxRuntime.jsxs("div", {
    className: "nm-document-editor__wrapper",
    "data-testid": "document-editor-container",
    ref: editorHotkeyRef,
    children: [/*#__PURE__*/jsxRuntime.jsxs(FormikEditor, _objectSpread(_objectSpread({
      attachmentsClassName: "editor-content-attachments w-full flex-shrink-0",
      className: "h-full w-full",
      contentClassName: "editor-content__wrapper nm-document-editor__container",
      "data-testid": "neeto-molecules-document-content-text-area",
      error: undefined,
      errorWrapperClassName: "w-full min-h-full flex flex-col items-center",
      hideSlashCommands: false,
      menuClassName: classnames("nm-document-editor__menubar", menuClassName),
      name: editorContentFieldName,
      ref: setEditorRef
    }, _objectSpread(_objectSpread({
      attachments: attachments
    }, editorProps), {}, {
      addons: addons
    })), {}, {
      contentWrapperClassName: "w-full flex flex-col flex-grow",
      keyboardShortcuts: _objectSpread({
        Tab: handleTab
      }, editorProps.keyboardShortcuts),
      onChange: handleContentChange,
      onChangeAttachments: handleAttachmentChange,
      children: [children, /*#__PURE__*/jsxRuntime.jsxs("div", {
        className: "nm-document-editor__container px-6",
        children: [/*#__PURE__*/jsxRuntime.jsx(formik$1.Textarea, _objectSpread({
          nakedTextarea: true,
          className: "nm-document-editor__title",
          "data-testid": "neeto-molecules-document-title-text-field",
          name: titleFieldName,
          ref: setTitleRef,
          rows: 1,
          placeholder: titleProps.placeholder || t("neetoMolecules.documentEditor.title"),
          onChange: handleTitleChange,
          onKeyDown: function onKeyDown(e) {
            return e.key === "Enter" && !e.shiftKey && e.preventDefault();
          }
        }, titleProps)), thumbnailImageUrl && /*#__PURE__*/jsxRuntime.jsxs("div", {
          className: "group relative mt-4",
          children: [/*#__PURE__*/jsxRuntime.jsx("div", {
            className: "nm-document-editor__thumbnail",
            children: /*#__PURE__*/jsxRuntime.jsx("img", {
              alt: "Cover",
              src: thumbnailImageUrl
            })
          }), /*#__PURE__*/jsxRuntime.jsx("div", {
            className: "absolute end-2 top-2",
            children: /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.DropdownMenu, {
              buttonProps: {
                variant: "secondary",
                size: "icon-sm"
              },
              icon: ellipsis.Ellipsis,
              children: /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.DropdownMenu.MenuItem, {
                onClick: handleDeleteThumbnail,
                children: t("neetoMolecules.documentEditor.delete")
              })
            })
          })]
        }), errors[editorContentFieldName] && /*#__PURE__*/jsxRuntime.jsx("p", {
          className: "text-destructive nm-document-editor__error text-sm font-normal",
          "data-slot": "field-error",
          "data-testid": "articles-content-input-error",
          role: "alert",
          children: errors[editorContentFieldName]
        })]
      })]
    })), /*#__PURE__*/jsxRuntime.jsxs(neetoAtoms.Dialog, {
      "data-testid": "thumbnail-image-modal",
      isOpen: isThumbnailImageModalOpen,
      size: "medium",
      onClose: function onClose() {
        return setIsThumbnailImageModalOpen(false);
      },
      children: [/*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Dialog.Header, {
        children: /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Dialog.Title, {
          children: t("neetoMolecules.documentEditor.uploadThumbnailImage")
        })
      }), /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Dialog.Body, {
        children: /*#__PURE__*/jsxRuntime.jsx(MediaUploader, {
          setIsThumbnailImageModalOpen: setIsThumbnailImageModalOpen
        })
      })]
    })]
  });
};
Editor.displayName = "DocumentEditor";
var index = /*#__PURE__*/React.memo(Editor);

module.exports = index;
//# sourceMappingURL=DocumentEditor.js.map
