"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = TextEditor;
var _react = _interopRequireWildcard(require("react"));
var _classnames = _interopRequireDefault(require("classnames"));
var _isEqual = _interopRequireDefault(require("lodash-es/isEqual"));
var _slateHistory = require("slate-history");
var _formField = require("../form-field");
var _chat = require("../chat");
var _textEditorToolbar = require("./text-editor-toolbar");
var _textEditorContext = _interopRequireDefault(require("./text-editor-context"));
var _textEditorHeader = _interopRequireDefault(require("./text-editor-header"));
var _textEditorContent = _interopRequireWildcard(require("./text-editor-content"));
var _withLinks = _interopRequireDefault(require("./hooks/with-links"));
var _textEditorLoader = _interopRequireDefault(require("./text-editor-loader"));
var _textEditorConstants = require("./text-editor-constants");
var _textEditorHooks = require("./text-editor-hooks");
var _textEditorHelpers = require("./text-editor-helpers");
var _useTranslation = require("../hooks/use-translation");
var _jsxRuntime = require("react/jsx-runtime");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
function TextEditorComponent({
  name,
  type,
  header,
  value = null,
  initialValue = null,
  label = '',
  toolbarLabels,
  toolbarPosition = _textEditorConstants.TOOLBAR_POSITION.TOP,
  onCancel,
  onSave,
  onFocus,
  onBlur,
  validity = null,
  placeholder = '',
  autoFocus = false,
  readOnly = false,
  height = 250,
  contentTestId = 'text-editor-content',
  contentAriaLabel,
  enabledTools = _textEditorConstants.TEXT_EDITOR_DEFAULT_TOOLS,
  elementRender = _textEditorContent.Element,
  leafRender = _textEditorContent.Leaf,
  onChange = () => {},
  deleteEditorContentButtonAriaLabel,
  id = '',
  maxLength,
  getCharactersCounterString
}) {
  const {
    t
  } = (0, _useTranslation.useTranslation)();
  const {
    slate,
    slateReact
  } = (0, _react.useContext)(_textEditorContext.default);
  const validationValues = (0, _formField.useDefaultValidationValues)();
  const {
    Editor,
    Transforms,
    createEditor
  } = slate;
  const {
    withReact,
    Slate
  } = slateReact;
  const getCharactersCounterStringText = (0, _react.useCallback)(count => {
    if (getCharactersCounterString) {
      return getCharactersCounterString(count);
    }
    return t('{{count}} characters remaining', {
      count
    });
  }, [getCharactersCounterString]);
  const editor = (0, _react.useMemo)(() => (0, _chat.withMaxLength)(maxLength)((0, _withLinks.default)((0, _slateHistory.withHistory)(withReact(createEditor())))), [maxLength]);
  const selection = (0, _react.useRef)(null);
  const slateValue = value || initialValue || _textEditorConstants.TEXT_EDITOR_DEFAULT_VALUE;
  (0, _react.useEffect)(() => {
    if (!(0, _isEqual.default)(editor.children, slateValue)) {
      // Update the cached value inside the editor
      (0, _chat.resetNodes)(editor, slateValue);
    }
  }, [slateValue, editor]);
  function saveSelection() {
    selection.current = editor.selection;
    setTimeout(() => onBlur?.(), 0);
  }
  function recoverSelection() {
    if (!editor.selection && editor.children.length > 0) {
      Transforms.select(editor, selection.current || Editor.end(editor, []));
    }
    setTimeout(() => onFocus?.(), 0);
  }
  const errorAttr = (0, _formField.getErrorAriaAttributes)({
    validity,
    id,
    validationValues
  });
  const ariaLabel = contentAriaLabel || label;
  const ariaAttrs = {
    ...errorAttr,
    ...(ariaLabel && {
      'aria-label': ariaLabel
    })
  };
  const toolbarMemo = (0, _react.useMemo)(() => /*#__PURE__*/(0, _jsxRuntime.jsx)(_textEditorToolbar.TextEditorToolbar, {
    enabledTools: enabledTools,
    labels: toolbarLabels,
    position: toolbarPosition,
    onCancel: onCancel,
    onSave: onSave
  }), [enabledTools, toolbarLabels, toolbarPosition, onCancel, onSave]);
  const isFlex = type === _textEditorConstants.INLINE_EDITOR_TYPES.FLEX;
  const styleHeight = header?.title === 'string' || header?.hasDeleteButton ? height + _textEditorConstants.HEADER_HEIGHT : height;
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
    children: [label && /*#__PURE__*/(0, _jsxRuntime.jsx)("label", {
      htmlFor: name,
      className: "text-editor-label",
      children: label
    }), /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
      className: (0, _classnames.default)('text-editor-wrapper', isFlex && 'is-flex'),
      "test-id": "text-editor-wrapper"
      /* eslint-disable-next-line react/forbid-dom-props */,
      style: {
        height: !isFlex ? styleHeight : undefined
      },
      children: /*#__PURE__*/(0, _jsxRuntime.jsxs)(Slate, {
        editor: editor,
        initialValue: slateValue,
        onChange: newValue => onChange(newValue),
        onBlur: saveSelection,
        children: [!!header && /*#__PURE__*/(0, _jsxRuntime.jsx)(_textEditorHeader.default, {
          title: header.title,
          titlePlaceholder: header.titlePlaceholder,
          onChangeTitle: header.onChangeTitle,
          isEditable: !!header.isEditable,
          hasDeleteButton: header.hasDeleteButton,
          onDelete: header.onDelete,
          deleteEditorContentButtonAriaLabel: deleteEditorContentButtonAriaLabel,
          inputAriaLabel: header.inputAriaLabel,
          maxLength: header.maxLength
        }), toolbarPosition === _textEditorConstants.TOOLBAR_POSITION.TOP && toolbarMemo, /*#__PURE__*/(0, _jsxRuntime.jsx)(_textEditorContent.default, {
          placeholder: placeholder,
          readOnly: readOnly,
          autoFocus: autoFocus,
          testId: contentTestId,
          elementRender: elementRender,
          leafRender: leafRender,
          onBlur: saveSelection,
          onFocus: recoverSelection,
          ariaAttrs: ariaAttrs,
          maxLength: maxLength
        }), toolbarPosition === _textEditorConstants.TOOLBAR_POSITION.BOTTOM && toolbarMemo]
      })
    }), maxLength && /*#__PURE__*/(0, _jsxRuntime.jsx)(_chat.CharactersCounter, {
      currLength: (0, _textEditorHelpers.getTextEditorValueLength)(slateValue),
      maxLength: maxLength,
      getCharactersCounterString: getCharactersCounterStringText
    }), validity && /*#__PURE__*/(0, _jsxRuntime.jsx)(_formField.ValidityMessages, {
      validity: validity,
      validationTestId: `${name}-validity`,
      fieldId: id
    })]
  });
}
/**
 * @midnight-gray-supported
 * @alpine-light-supported
 * */
function TextEditor({
  name,
  header,
  type,
  value = null,
  initialValue = null,
  validity = null,
  label = '',
  placeholder = '',
  autoFocus = false,
  readOnly = false,
  testId = 'text-editor',
  contentTestId = 'text-editor-content',
  contentAriaLabel,
  className = '',
  height = 250,
  enabledTools = _textEditorConstants.TEXT_EDITOR_DEFAULT_TOOLS,
  toolbarPosition = _textEditorConstants.TOOLBAR_POSITION.TOP,
  elementRender = _textEditorContent.Element,
  leafRender = _textEditorContent.Leaf,
  onChange = () => {},
  onCancel,
  onSave,
  tooltipTextBold,
  tooltipTextItalic,
  tooltipTextUnderline,
  tooltipTextSuperscript,
  tooltipTextLink,
  tooltipTextRemoveLink,
  tooltipTextBulletedList,
  tooltipTextNumberedList,
  tooltipTextClearFormatting,
  tooltipTextCode,
  urlIsRequiredMessage,
  enterValidUrlMessage,
  saveButtonText,
  headingLargeText,
  headingMediumText,
  headingSmallText,
  regularText,
  validationErrorWarningMessage,
  linkInputLabelText,
  deleteEditorContentButtonAriaLabel,
  id = '',
  maxLength,
  getCharactersCounterString
}) {
  const [isFocused, setIsFocused] = (0, _react.useState)(false);
  const defaultTranslations = (0, _textEditorHooks.useTextEditorDefaultTranslations)();
  const consumerTranslations = {
    tooltipTextBold,
    tooltipTextItalic,
    tooltipTextUnderline,
    tooltipTextSuperscript,
    tooltipTextLink,
    tooltipTextRemoveLink,
    tooltipTextBulletedList,
    tooltipTextNumberedList,
    tooltipTextClearFormatting,
    tooltipTextCode,
    urlIsRequiredMessage,
    enterValidUrlMessage,
    saveButtonText,
    headingLargeText,
    headingMediumText,
    headingSmallText,
    regularText,
    validationErrorWarningMessage,
    linkInputLabelText
  };
  const toolbarLabels = {
    ...defaultTranslations,
    ...Object.fromEntries(Object.entries(consumerTranslations).filter(([, v]) => typeof v !== 'undefined'))
  };
  return /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
    className: (0, _classnames.default)('text-editor', isFocused && 'is-focused', className),
    "test-id": testId,
    children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_textEditorLoader.default, {
      children: /*#__PURE__*/(0, _jsxRuntime.jsx)(TextEditorComponent, {
        type: type,
        name: name,
        header: header,
        value: value,
        onFocus: () => setIsFocused(true),
        onBlur: () => setIsFocused(false),
        initialValue: initialValue,
        validity: validity,
        label: label,
        toolbarLabels: toolbarLabels,
        toolbarPosition: toolbarPosition,
        onCancel: onCancel,
        onSave: onSave,
        placeholder: placeholder,
        autoFocus: autoFocus,
        readOnly: readOnly,
        height: height,
        contentTestId: contentTestId,
        contentAriaLabel: contentAriaLabel,
        enabledTools: enabledTools,
        elementRender: elementRender,
        leafRender: leafRender,
        onChange: onChange,
        deleteEditorContentButtonAriaLabel: deleteEditorContentButtonAriaLabel,
        id: id,
        maxLength: maxLength,
        getCharactersCounterString: getCharactersCounterString
      })
    })
  });
}