text: "use strict";
  
  Object.defineProperty(exports, "__esModule", {
    value: true
  });
  exports.default = void 0;
  
  var _default2 = _interopRequireDefault(require("part:@sanity/components/formfields/default"));
  
  var _default3 = _interopRequireDefault(require("part:@sanity/components/snackbar/default"));
  
  var _react = _interopRequireWildcard(require("react"));
  
  var _portableTextEditor = require("@sanity/portable-text-editor");
  
  var _rxjs = require("rxjs");
  
  var _PatchEvent = _interopRequireDefault(require("../../PatchEvent"));
  
  var _withPatchSubscriber = _interopRequireDefault(require("../../utils/withPatchSubscriber"));
  
  var _path = require("../../typedefs/path");
  
  var _Input = _interopRequireDefault(require("./Input"));
  
  var _InvalidValue = _interopRequireDefault(require("./InvalidValue"));
  
  var _PortableTextInput = _interopRequireDefault(require("./PortableTextInput.css"));
  
  var _temp;
  
  function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
  
  function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
  
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  
  function _extends() { _extends = Object.assign || 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 _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
  
  function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
  
  function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
  
  function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
  
  function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
  
  function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
  
  function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
  
  var PortableTextInputWithRef = /*#__PURE__*/_react.default.forwardRef(function PortableTextInput(props, ref) {
    var focusPath = props.focusPath,
        hotkeys = props.hotkeys,
        level = props.level,
        markers = props.markers,
        onBlur = props.onBlur,
        onChange = props.onChange,
        onCopy = props.onCopy,
        onFocus = props.onFocus,
        onPaste = props.onPaste,
        presence = props.presence,
        readOnly = props.readOnly,
        renderBlockActions = props.renderBlockActions,
        renderCustomMarkers = props.renderCustomMarkers,
        type = props.type,
        value = props.value; // The PortableTextEditor will not re-render unless the value is changed (which is good).
    // But, we want to re-render it when the markers changes too,
    // (we render error indicators directly in the editor nodes)
  
    var validationHash = markers.map(marker => JSON.stringify(marker.path).concat(marker.type).concat(marker.level)).sort().join('');
  
    var _useState = (0, _react.useState)(value),
        _useState2 = _slicedToArray(_useState, 2),
        valueTouchedByMarkers = _useState2[0],
        setValueTouchedByMarkers = _useState2[1];
  
    (0, _react.useEffect)(() => {
      setValueTouchedByMarkers(value ? [...value] : value);
    }, [validationHash, value]);
  
    var _useState3 = (0, _react.useState)(undefined),
        _useState4 = _slicedToArray(_useState3, 2),
        editorErrorNotification = _useState4[0],
        setEditorErrorNotification = _useState4[1]; // Reset invalidValue if new value is coming in from props
  
  
    var _useState5 = (0, _react.useState)(null),
        _useState6 = _slicedToArray(_useState5, 2),
        invalidValue = _useState6[0],
        setInvalidValue = _useState6[1];
  
    (0, _react.useEffect)(() => {
      if (invalidValue && value !== invalidValue.value) {
        setInvalidValue(null);
      }
    }, [value]); // Subscribe to incoming patches
  
    var unsubscribe;
    (0, _react.useEffect)(() => {
      unsubscribe = props.subscribe(handleDocumentPatches);
      return () => {
        unsubscribe();
      };
    }, []); // Memoized patch stream
  
    var patche$ = (0, _react.useMemo)(() => new _rxjs.Subject(), []); // Handle incoming patches from withPatchSubscriber HOC
  
    function handleDocumentPatches(_ref) {
      var patches = _ref.patches;
      var patchSelection = patches && patches.length > 0 && patches.filter(patch => patch.origin !== 'local');
  
      if (patchSelection) {
        patchSelection.map(patch => patche$.next(patch));
      }
    } // Handle editor changes
    // eslint-disable-next-line complexity
  
  
    var _useState7 = (0, _react.useState)(false),
        _useState8 = _slicedToArray(_useState7, 2),
        hasFocus = _useState8[0],
        setHasFocus = _useState8[1];
  
    function handleEditorChange(change) {
      switch (change.type) {
        case 'mutation':
          // Don't wait for the result
          setTimeout(() => {
            onChange(_PatchEvent.default.from(change.patches));
          });
          break;
  
        case 'focus':
          setHasFocus(true);
          break;
  
        case 'blur':
          setHasFocus(false);
          break;
  
        case 'undo':
        case 'redo':
          onChange(_PatchEvent.default.from(change.patches));
          break;
  
        case 'invalidValue':
          setInvalidValue(change);
          break;
  
        case 'error':
          setEditorErrorNotification(change);
          break;
        // case 'selection':
        // case 'value':
        // case 'ready':
        // case 'patch':
        // case 'unset':
        // case 'loading':
        //   break
        // default:
        //   throw new Error(`Unhandled editor change ${JSON.stringify(change)}`)
  
        default:
      }
    }
  
    var _useState9 = (0, _react.useState)(false),
        _useState10 = _slicedToArray(_useState9, 2),
        ignoreValidationError = _useState10[0],
        setIgnoreValidationError = _useState10[1];
  
    function handleIgnoreValidation() {
      setIgnoreValidationError(true);
    }
  
    var handleFocusSkipper = () => {
      if (ref.current) {
        _portableTextEditor.PortableTextEditor.focus(ref.current);
      }
    };
  
    var formField = (0, _react.useMemo)(() => /*#__PURE__*/_react.default.createElement(_default2.default, {
      description: type.description,
      label: type.title,
      level: level,
      markers: markers,
      presence: presence
    }), [markers, presence]); // Render error message and resolution
  
    var respondToInvalidContent = null;
  
    if (invalidValue) {
      respondToInvalidContent = /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, formField, /*#__PURE__*/_react.default.createElement(_InvalidValue.default, {
        onChange: handleEditorChange,
        onIgnore: handleIgnoreValidation,
        resolution: invalidValue.resolution,
        value: value
      }));
    }
  
    var _useState11 = (0, _react.useState)(false),
        _useState12 = _slicedToArray(_useState11, 2),
        isFullscreen = _useState12[0],
        setIsFullscreen = _useState12[1];
  
    var handleToggleFullscreen = () => setIsFullscreen(!isFullscreen);
  
    var editorInput = (0, _react.useMemo)(() => /*#__PURE__*/_react.default.createElement(_portableTextEditor.PortableTextEditor, {
      ref: ref,
      incomingPatche$: patche$.asObservable(),
      onChange: handleEditorChange,
      maxBlocks: undefined // TODO: from schema?
      ,
      readOnly: readOnly,
      type: type,
      value: valueTouchedByMarkers
    }, formField, !readOnly && /*#__PURE__*/_react.default.createElement("button", {
      type: "button",
      tabIndex: 0,
      className: _PortableTextInput.default.focusSkipper,
      onClick: handleFocusSkipper
    }, "Jump to editor"), /*#__PURE__*/_react.default.createElement(_Input.default, {
      focusPath: focusPath,
      hasFocus: hasFocus,
      hotkeys: hotkeys,
      isFullscreen: isFullscreen,
      markers: markers,
      onBlur: onBlur,
      onChange: onChange,
      onCopy: onCopy,
      onFocus: onFocus,
      onPaste: onPaste,
      onToggleFullscreen: handleToggleFullscreen,
      patche$: patche$,
      presence: presence,
      readOnly: readOnly,
      renderBlockActions: renderBlockActions,
      renderCustomMarkers: renderCustomMarkers,
      type: props.type,
      value: valueTouchedByMarkers
    })), [focusPath, hasFocus, isFullscreen, presence, readOnly, valueTouchedByMarkers]);
    return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, editorErrorNotification &&
    /*#__PURE__*/
    // Display intended editor errors to the user
    _react.default.createElement(_default3.default, {
      kind: editorErrorNotification.level,
      isPersisted: true,
      onAction: () => setEditorErrorNotification(undefined),
      subtitle: /*#__PURE__*/_react.default.createElement("div", null, editorErrorNotification.description)
    }), invalidValue && !ignoreValidationError && respondToInvalidContent, (!invalidValue || ignoreValidationError) && editorInput);
  });
  
  var _default = (0, _withPatchSubscriber.default)((_temp = class PortableTextInputWithFocusAndBlur extends _react.default.Component {
    constructor() {
      super(...arguments);
  
      _defineProperty(this, "editorRef", /*#__PURE__*/_react.default.createRef());
    }
  
    focus() {
      if (this.editorRef.current) {
        _portableTextEditor.PortableTextEditor.focus(this.editorRef.current);
      }
    }
  
    blur() {
      if (this.editorRef.current) {
        _portableTextEditor.PortableTextEditor.blur(this.editorRef.current);
      }
    }
  
    render() {
      return /*#__PURE__*/_react.default.createElement(PortableTextInputWithRef, _extends({}, this.props, {
        ref: this.editorRef
      }));
    }
  
  }, _temp));
  
  exports.default = _default;