"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.ControlHint = void 0;
var _base = _interopRequireDefault(require("@emotion/styled/base"));
var _uniqueId2 = _interopRequireDefault(require("lodash/uniqueId"));
var _partial2 = _interopRequireDefault(require("lodash/partial"));
var _react = _interopRequireDefault(require("react"));
var _redux = require("redux");
var _propTypes = _interopRequireDefault(require("prop-types"));
var _reactImmutableProptypes = _interopRequireDefault(require("react-immutable-proptypes"));
var _reactPolyglot = require("react-polyglot");
var _react2 = require("@emotion/react");
var _reactRedux = require("react-redux");
var _decapCmsUiDefault = require("decap-cms-ui-default");
var _reactMarkdown = _interopRequireDefault(require("react-markdown"));
var _remarkGfm = _interopRequireDefault(require("remark-gfm"));
var _registry = require("../../../lib/registry");
var _entries = require("../../../actions/entries");
var _media = require("../../../actions/media");
var _medias = require("../../../reducers/medias");
var _search = require("../../../actions/search");
var _mediaLibrary = require("../../../actions/mediaLibrary");
var _Widget = _interopRequireDefault(require("./Widget"));
const _excluded = ["node"];
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
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), !0).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; }
function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _EMOTION_STRINGIFIED_CSS_ERROR__() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; } /**
 * This is a necessary bridge as we are still passing classnames to widgets
 * for styling. Once that changes we can stop storing raw style strings like
 * this.
 */
const styleStrings = {
  widget: `
    display: block;
    width: 100%;
    padding: ${_decapCmsUiDefault.lengths.inputPadding};
    margin: 0;
    border: ${_decapCmsUiDefault.borders.textField};
    border-radius: ${_decapCmsUiDefault.lengths.borderRadius};
    border-top-left-radius: 0;
    outline: 0;
    box-shadow: none;
    background-color: ${_decapCmsUiDefault.colors.inputBackground};
    color: #444a57;
    transition: border-color ${_decapCmsUiDefault.transitions.main};
    position: relative;
    font-size: 15px;
    line-height: 1.5;

    select& {
      text-indent: 14px;
      height: 58px;
    }
  `,
  widgetActive: `
    border-color: ${_decapCmsUiDefault.colors.active};
  `,
  widgetError: `
    border-color: ${_decapCmsUiDefault.colors.errorText};
  `,
  disabled: `
    pointer-events: none;
    opacity: 0.5;
    background: #ccc;
  `,
  hidden: `
    visibility: hidden;
  `
};
const ControlContainer = /*#__PURE__*/(0, _base.default)("div", {
  target: "ec1nk3l2",
  label: "ControlContainer"
})(process.env.NODE_ENV === "production" ? {
  name: "gpgisz",
  styles: "margin-top:16px;&:first-of-type{margin-top:36px;}"
} : {
  name: "gpgisz",
  styles: "margin-top:16px;&:first-of-type{margin-top:36px;}",
  map: "/*# sourceMappingURL=data:application/json;charset=utf-8;base64,[encoded data, 18612 characters] */",
  toString: _EMOTION_STRINGIFIED_CSS_ERROR__
});
const ControlErrorsList = /*#__PURE__*/(0, _base.default)("ul", {
  target: "ec1nk3l1",
  label: "ControlErrorsList"
})("list-style-type:none;font-size:12px;color:", _decapCmsUiDefault.colors.errorText, ";margin-bottom:8px;text-align:right;font-weight:600;" + (process.env.NODE_ENV === "production" ? "" : "/*# sourceMappingURL=data:application/json;charset=utf-8;base64,[encoded data, 18612 characters] */"));
const ControlHint = exports.ControlHint = /*#__PURE__*/(0, _base.default)("p", {
  target: "ec1nk3l0",
  label: "ControlHint"
})("margin-bottom:0;padding:3px 0;font-size:12px;color:", props => props.error ? _decapCmsUiDefault.colors.errorText : props.active ? _decapCmsUiDefault.colors.active : _decapCmsUiDefault.colors.controlLabel, ";transition:color ", _decapCmsUiDefault.transitions.main, ";" + (process.env.NODE_ENV === "production" ? "" : "/*# sourceMappingURL=data:application/json;charset=utf-8;base64,[encoded data, 18612 characters] */"));
function LabelComponent({
  field,
  isActive,
  hasErrors,
  uniqueFieldId,
  isFieldOptional,
  t
}) {
  const label = `${field.get('label', field.get('name'))}`;
  const labelComponent = (0, _react2.jsx)(_decapCmsUiDefault.FieldLabel, {
    isActive: isActive,
    hasErrors: hasErrors,
    htmlFor: uniqueFieldId
  }, isFieldOptional ? (0, _react2.jsx)(_react.default.Fragment, null, label, (0, _react2.jsx)("span", null, ` (${t('editor.editorControl.field.optional')})`)) : label);
  return labelComponent;
}
class EditorControl extends _react.default.Component {
  constructor(...args) {
    super(...args);
    _defineProperty(this, "state", {
      activeLabel: false
    });
    _defineProperty(this, "uniqueFieldId", (0, _uniqueId2.default)(`${this.props.field.get('name')}-field-`));
    _defineProperty(this, "isAncestorOfFieldError", () => {
      const {
        fieldsErrors
      } = this.props;
      if (fieldsErrors && fieldsErrors.size > 0) {
        return Object.values(fieldsErrors.toJS()).some(arr => arr.some(err => err.parentIds && err.parentIds.includes(this.uniqueFieldId)));
      }
      return false;
    });
  }
  render() {
    const {
      value,
      entry,
      collection,
      config,
      field,
      fieldsMetaData,
      fieldsErrors,
      mediaPaths,
      boundGetAsset,
      onChange,
      openMediaLibrary,
      clearMediaControl,
      removeMediaControl,
      addAsset,
      removeInsertedMedia,
      persistMedia,
      onValidate,
      processControlRef,
      controlRef,
      query,
      queryHits,
      isFetching,
      clearSearch,
      clearFieldErrors,
      loadEntry,
      className,
      isSelected,
      isEditorComponent,
      isNewEditorComponent,
      parentIds,
      t,
      validateMetaField,
      isLoadingAsset,
      isDisabled,
      isHidden,
      isFieldDuplicate,
      isFieldHidden,
      locale,
      isParentListCollapsed
    } = this.props;
    const widgetName = field.get('widget');
    const widget = (0, _registry.resolveWidget)(widgetName);
    const fieldName = field.get('name');
    const fieldHint = field.get('hint');
    const isFieldOptional = field.get('required') === false;
    const onValidateObject = onValidate;
    const metadata = fieldsMetaData && fieldsMetaData.get(fieldName);
    const errors = fieldsErrors && fieldsErrors.get(this.uniqueFieldId);
    const childErrors = this.isAncestorOfFieldError();
    const hasErrors = !!errors || childErrors;
    return (0, _react2.jsx)(_react2.ClassNames, null, ({
      css,
      cx
    }) => (0, _react2.jsx)(ControlContainer, {
      className: className,
      css: css`
              ${isHidden && styleStrings.hidden};
            `
    }, widget.globalStyles && (0, _react2.jsx)(_react2.Global, {
      styles: /*#__PURE__*/(0, _react2.css)(widget.globalStyles, ";;label:EditorControl;" + (process.env.NODE_ENV === "production" ? "" : "/*# sourceMappingURL=data:application/json;charset=utf-8;base64,[encoded data, 18612 characters] */"))
    }), errors && (0, _react2.jsx)(ControlErrorsList, null, errors.map(error => error.message && typeof error.message === 'string' && (0, _react2.jsx)("li", {
      key: error.message.trim().replace(/[^a-z0-9]+/gi, '-')
    }, error.message))), (0, _react2.jsx)(LabelComponent, {
      field: field,
      isActive: isSelected || this.state.styleActive,
      hasErrors: hasErrors,
      uniqueFieldId: this.uniqueFieldId,
      isFieldOptional: isFieldOptional,
      t: t
    }), (0, _react2.jsx)(_Widget.default, {
      classNameWrapper: cx(css`
                  ${styleStrings.widget};
                `, {
        [css`
                    ${styleStrings.widgetActive};
                  `]: isSelected || this.state.styleActive
      }, {
        [css`
                    ${styleStrings.widgetError};
                  `]: hasErrors
      }, {
        [css`
                    ${styleStrings.disabled}
                  `]: isDisabled
      }),
      classNameWidget: css`
                ${styleStrings.widget};
              `,
      classNameWidgetActive: css`
                ${styleStrings.widgetActive};
              `,
      classNameLabel: css`
                ${styleStrings.label};
              `,
      classNameLabelActive: css`
                ${styleStrings.labelActive};
              `,
      controlComponent: widget.control,
      entry: entry,
      collection: collection,
      config: config,
      field: field,
      uniqueFieldId: this.uniqueFieldId,
      value: value,
      mediaPaths: mediaPaths,
      metadata: metadata,
      onChange: (newValue, newMetadata) => onChange(field, newValue, newMetadata),
      onValidate: onValidate && (0, _partial2.default)(onValidate, this.uniqueFieldId),
      onOpenMediaLibrary: openMediaLibrary,
      onClearMediaControl: clearMediaControl,
      onRemoveMediaControl: removeMediaControl,
      onRemoveInsertedMedia: removeInsertedMedia,
      onPersistMedia: persistMedia,
      onAddAsset: addAsset,
      getAsset: boundGetAsset,
      hasActiveStyle: isSelected || this.state.styleActive,
      setActiveStyle: () => this.setState({
        styleActive: true
      }),
      setInactiveStyle: () => this.setState({
        styleActive: false
      }),
      resolveWidget: _registry.resolveWidget,
      widget: widget,
      getEditorComponents: _registry.getEditorComponents,
      ref: processControlRef && (0, _partial2.default)(processControlRef, field),
      controlRef: controlRef,
      editorControl: ConnectedEditorControl,
      query: query,
      loadEntry: loadEntry,
      queryHits: queryHits[this.uniqueFieldId] || [],
      clearSearch: clearSearch,
      clearFieldErrors: clearFieldErrors,
      isFetching: isFetching,
      fieldsErrors: fieldsErrors,
      onValidateObject: onValidateObject,
      isEditorComponent: isEditorComponent,
      isNewEditorComponent: isNewEditorComponent,
      parentIds: parentIds,
      t: t,
      validateMetaField: validateMetaField,
      isDisabled: isDisabled,
      isFieldDuplicate: isFieldDuplicate,
      isFieldHidden: isFieldHidden,
      isLoadingAsset: isLoadingAsset,
      locale: locale,
      isParentListCollapsed: isParentListCollapsed
    }), fieldHint && (0, _react2.jsx)(ControlHint, {
      active: isSelected || this.state.styleActive,
      error: hasErrors
    }, (0, _react2.jsx)(_reactMarkdown.default, {
      remarkPlugins: [_remarkGfm.default],
      allowedElements: ['a', 'strong', 'em', 'del'],
      unwrapDisallowed: true,
      components: {
        // eslint-disable-next-line no-unused-vars
        a: _ref => {
          let {
              node
            } = _ref,
            props = _objectWithoutProperties(_ref, _excluded);
          return (0, _react2.jsx)("a", _extends({}, props, {
            target: "_blank",
            rel: "noopener noreferrer",
            style: {
              color: 'inherit'
            }
          }));
        }
      }
    }, fieldHint))));
  }
}
_defineProperty(EditorControl, "propTypes", {
  value: _propTypes.default.oneOfType([_propTypes.default.node, _propTypes.default.object, _propTypes.default.string, _propTypes.default.bool]),
  field: _reactImmutableProptypes.default.map.isRequired,
  fieldsMetaData: _reactImmutableProptypes.default.map,
  fieldsErrors: _reactImmutableProptypes.default.map,
  mediaPaths: _reactImmutableProptypes.default.map.isRequired,
  boundGetAsset: _propTypes.default.func.isRequired,
  onChange: _propTypes.default.func.isRequired,
  openMediaLibrary: _propTypes.default.func.isRequired,
  addAsset: _propTypes.default.func.isRequired,
  removeInsertedMedia: _propTypes.default.func.isRequired,
  persistMedia: _propTypes.default.func.isRequired,
  onValidate: _propTypes.default.func,
  processControlRef: _propTypes.default.func,
  controlRef: _propTypes.default.func,
  query: _propTypes.default.func.isRequired,
  queryHits: _propTypes.default.object,
  isFetching: _propTypes.default.bool,
  clearSearch: _propTypes.default.func.isRequired,
  clearFieldErrors: _propTypes.default.func.isRequired,
  loadEntry: _propTypes.default.func.isRequired,
  t: _propTypes.default.func.isRequired,
  isEditorComponent: _propTypes.default.bool,
  isNewEditorComponent: _propTypes.default.bool,
  parentIds: _propTypes.default.arrayOf(_propTypes.default.string),
  entry: _reactImmutableProptypes.default.map.isRequired,
  collection: _reactImmutableProptypes.default.map.isRequired,
  isDisabled: _propTypes.default.bool,
  isHidden: _propTypes.default.bool,
  isFieldDuplicate: _propTypes.default.func,
  isFieldHidden: _propTypes.default.func,
  locale: _propTypes.default.string,
  isParentListCollapsed: _propTypes.default.bool
});
_defineProperty(EditorControl, "defaultProps", {
  parentIds: []
});
function mapStateToProps(state) {
  const {
    collections,
    entryDraft
  } = state;
  const entry = entryDraft.get('entry');
  const collection = collections.get(entryDraft.getIn(['entry', 'collection']));
  const isLoadingAsset = (0, _medias.selectIsLoadingAsset)(state.medias);
  async function loadEntry(collectionName, slug) {
    const targetCollection = collections.get(collectionName);
    if (targetCollection) {
      const loadedEntry = await (0, _entries.tryLoadEntry)(state, targetCollection, slug);
      return loadedEntry;
    } else {
      throw new Error(`Can't find collection '${collectionName}'`);
    }
  }
  return {
    mediaPaths: state.mediaLibrary.get('controlMedia'),
    isFetching: state.search.isFetching,
    queryHits: state.search.queryHits,
    config: state.config,
    entry,
    collection,
    isLoadingAsset,
    loadEntry,
    validateMetaField: (field, value, t) => (0, _entries.validateMetaField)(state, collection, field, value, t)
  };
}
function mapDispatchToProps(dispatch) {
  const creators = (0, _redux.bindActionCreators)({
    openMediaLibrary: _mediaLibrary.openMediaLibrary,
    clearMediaControl: _mediaLibrary.clearMediaControl,
    removeMediaControl: _mediaLibrary.removeMediaControl,
    removeInsertedMedia: _mediaLibrary.removeInsertedMedia,
    persistMedia: _mediaLibrary.persistMedia,
    addAsset: _media.addAsset,
    query: _search.query,
    clearSearch: _search.clearSearch,
    clearFieldErrors: _entries.clearFieldErrors
  }, dispatch);
  return _objectSpread(_objectSpread({}, creators), {}, {
    boundGetAsset: (collection, entry) => (0, _media.boundGetAsset)(dispatch, collection, entry)
  });
}
function mergeProps(stateProps, dispatchProps, ownProps) {
  return _objectSpread(_objectSpread(_objectSpread(_objectSpread({}, stateProps), dispatchProps), ownProps), {}, {
    boundGetAsset: dispatchProps.boundGetAsset(stateProps.collection, stateProps.entry)
  });
}
const ConnectedEditorControl = (0, _reactRedux.connect)(mapStateToProps, mapDispatchToProps, mergeProps)((0, _reactPolyglot.translate)()(EditorControl));
var _default = exports.default = ConnectedEditorControl;