"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = exports.Toolbar = void 0;

var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));

var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));

var _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized"));

var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));

var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));

var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

var _react = _interopRequireDefault(require("react"));

var _slate = require("slate");

var _Delete = _interopRequireDefault(require("@material-ui/icons/Delete"));

var _IconButton = _interopRequireDefault(require("@material-ui/core/IconButton"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var _classnames = _interopRequireDefault(require("classnames"));

var _debug = _interopRequireDefault(require("debug"));

var _slatePropTypes = _interopRequireDefault(require("slate-prop-types"));

var _debounce = _interopRequireDefault(require("lodash/debounce"));

var _doneButton = require("./done-button");

var _utils = require("../utils");

var _styles = require("@material-ui/core/styles");

var _defaultToolbar = _interopRequireDefault(require("./default-toolbar"));

var _characters = require("../characters");

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { (0, _defineProperty2["default"])(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

var log = (0, _debug["default"])('@pie-lib:editable-html:plugins:toolbar');

var getCustomToolbar = function getCustomToolbar(plugin, node, value, handleDone, onDataChange) {
  if (!plugin) {
    return;
  }

  if (!plugin.toolbar) {
    return;
  }

  if (plugin.toolbar.CustomToolbarComp) {
    /**
     * Using a pre-defined Component should be preferred
     * as the rendering of it (and it's children) can be optimized by React.
     * If you keep re-defining the comp with an inline function
     * then react will have to re-render.
     */
    return plugin.toolbar.CustomToolbarComp;
  } else if (typeof plugin.toolbar.customToolbar === 'function') {
    log('deprecated - use CustomToolbarComp');
    return plugin.toolbar.customToolbar(node, value, handleDone, onDataChange);
  }
};

var Toolbar = /*#__PURE__*/function (_React$Component) {
  (0, _inherits2["default"])(Toolbar, _React$Component);

  var _super = _createSuper(Toolbar);

  function Toolbar(props) {
    var _this;

    (0, _classCallCheck2["default"])(this, Toolbar);
    _this = _super.call(this, props);
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "hasMark", function (type) {
      var value = _this.props.value;
      return value.marks.some(function (mark) {
        return mark.type == type;
      });
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "hasBlock", function (type) {
      var value = _this.props.value;
      return value.blocks.some(function (node) {
        return node.type == type;
      });
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onToggle", function (plugin) {
      var _this$props = _this.props,
          value = _this$props.value,
          onChange = _this$props.onChange;
      if (!plugin.onToggle) return;
      var change = plugin.onToggle(value.change());
      onChange(change);
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onClick", function (e) {
      log('[onClick]');
      e.preventDefault();
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onButtonClick", function (fn) {
      return function (e) {
        e.preventDefault();
        fn();
      };
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onToolbarDone", function (change, finishEditing) {
      log('[onToolbarDone] change: ', change, 'finishEditing: ', finishEditing);
      var _this$props2 = _this.props,
          onChange = _this$props2.onChange,
          onDone = _this$props2.onDone; // use handler only if this is an actual Slate Change

      if (change instanceof _slate.Change) {
        onChange(change, function () {
          if (finishEditing) {
            onDone();
          }
        });
      } else {
        if (finishEditing) {
          log('[onToolbarChange] call onDone');
          onDone();
        }
      }
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onDeleteClick", (0, _debounce["default"])(function (e, plugin, node, value, onChange) {
      return plugin.deleteNode(e, node, value, onChange);
    }, 500));
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onDeleteMouseDown", function (e, plugin, node, value, onChange) {
      e.persist();

      _this.onDeleteClick(e, plugin, node, value, onChange);
    });
    _this.state = {
      change: null
    };
    return _this;
  }

  (0, _createClass2["default"])(Toolbar, [{
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      (0, _characters.removeDialogs)();
    }
  }, {
    key: "render",
    value: function render() {
      var _this2 = this,
          _classNames;

      var _this$props3 = this.props,
          classes = _this$props3.classes,
          plugins = _this$props3.plugins,
          pluginProps = _this$props3.pluginProps,
          toolbarOpts = _this$props3.toolbarOpts,
          value = _this$props3.value,
          autoWidth = _this$props3.autoWidth,
          onChange = _this$props3.onChange,
          getFocusedValue = _this$props3.getFocusedValue,
          isFocused = _this$props3.isFocused,
          onDone = _this$props3.onDone,
          toolbarRef = _this$props3.toolbarRef;
      var node = (0, _utils.findSingleNode)(value);
      var parentNode = (0, _utils.findParentNode)(value, node);
      log(' --------------> [render] node: ', node);
      log('[render] node: ', node);
      var plugin = plugins.find(function (p) {
        if (!node) {
          return;
        }

        if (p.toolbar) {
          return p.toolbar.supports && p.toolbar.supports(node, value);
        }
      });
      var parentPlugin = plugins.find(function (p) {
        if (!parentNode) {
          return;
        }

        if (p.toolbar) {
          return p.toolbar.supports && p.toolbar.supports(parentNode, value);
        }
      });
      log('[render] plugin: ', plugin);

      var handleDone = function handleDone(change, done) {
        var handler = onDone;

        if (plugin && plugin.toolbar && plugin.toolbar.customToolbar) {
          handler = _this2.onToolbarDone;
        }

        handler(change, done);

        if (parentPlugin && parentPlugin.handleDone) {
          parentPlugin.handleDone(value, node, plugin, onChange);
        }
      };

      var handleDataChange = function handleDataChange(key, data) {
        _this2.props.onDataChange(key, data);
      };

      var CustomToolbar = getCustomToolbar(plugin, node, value, handleDone, this.props.onDataChange);
      var filteredPlugins = plugin && plugin.filterPlugins ? plugin.filterPlugins(node, plugins) : plugins;
      log('[render] CustomToolbar: ', CustomToolbar);
      var parentExtraStyles = parentPlugin && parentPlugin.pluginStyles ? parentPlugin.pluginStyles(node, parentNode, plugin) : {};
      var pluginExtraStyles = plugin && plugin.pluginStyles ? plugin.pluginStyles(node, parentNode, plugin) : {};

      var extraStyles = _objectSpread(_objectSpread({}, pluginExtraStyles), parentExtraStyles);

      var deletable = node && plugin && plugin.deleteNode;
      var customToolbarShowDone = node && plugin && plugin.toolbar && plugin.toolbar.showDone && !toolbarOpts.alwaysVisible; // If there is a toolbarOpts we check if the showDone is not equal to false

      var defaultToolbarShowDone = !toolbarOpts || toolbarOpts.showDone !== false;
      var hasDoneButton = defaultToolbarShowDone || customToolbarShowDone;
      var names = (0, _classnames["default"])(classes.toolbar, (_classNames = {}, (0, _defineProperty2["default"])(_classNames, classes.toolbarWithNoDone, !hasDoneButton), (0, _defineProperty2["default"])(_classNames, classes.toolbarTop, toolbarOpts.position === 'top'), (0, _defineProperty2["default"])(_classNames, classes.toolbarRight, toolbarOpts.alignment === 'right'), (0, _defineProperty2["default"])(_classNames, classes.focused, toolbarOpts.alwaysVisible || isFocused), (0, _defineProperty2["default"])(_classNames, classes.autoWidth, autoWidth), (0, _defineProperty2["default"])(_classNames, classes.fullWidth, !autoWidth), _classNames));
      return /*#__PURE__*/_react["default"].createElement("div", {
        className: names,
        style: extraStyles,
        onClick: this.onClick,
        ref: toolbarRef
      }, CustomToolbar ? /*#__PURE__*/_react["default"].createElement(CustomToolbar, {
        node: node,
        value: value,
        onToolbarDone: this.onToolbarDone,
        onDataChange: handleDataChange,
        pluginProps: pluginProps
      }) : /*#__PURE__*/_react["default"].createElement(_defaultToolbar["default"], {
        plugins: filteredPlugins,
        pluginProps: pluginProps,
        value: value,
        onChange: onChange,
        getFocusedValue: getFocusedValue,
        showDone: defaultToolbarShowDone,
        onDone: handleDone,
        deletable: deletable,
        isHtmlMode: toolbarOpts.isHtmlMode
      }), /*#__PURE__*/_react["default"].createElement("div", {
        className: classes.shared
      }, deletable && /*#__PURE__*/_react["default"].createElement(_IconButton["default"], {
        "aria-label": "Delete",
        className: classes.iconRoot,
        onMouseDown: function onMouseDown(e) {
          return _this2.onDeleteMouseDown(e, plugin, node, value, onChange);
        },
        classes: {
          root: classes.iconRoot
        }
      }, /*#__PURE__*/_react["default"].createElement(_Delete["default"], null)), customToolbarShowDone && /*#__PURE__*/_react["default"].createElement(_doneButton.DoneButton, {
        onClick: handleDone
      })));
    }
  }]);
  return Toolbar;
}(_react["default"].Component);

exports.Toolbar = Toolbar;
(0, _defineProperty2["default"])(Toolbar, "propTypes", {
  zIndex: _propTypes["default"].number,
  value: _slatePropTypes["default"].value.isRequired,
  plugins: _propTypes["default"].array,
  plugin: _propTypes["default"].object,
  onImageClick: _propTypes["default"].func,
  onDone: _propTypes["default"].func.isRequired,
  toolbarRef: _propTypes["default"].func.isRequired,
  classes: _propTypes["default"].object.isRequired,
  isFocused: _propTypes["default"].bool,
  autoWidth: _propTypes["default"].bool,
  onChange: _propTypes["default"].func.isRequired,
  getFocusedValue: _propTypes["default"].func.isRequired,
  pluginProps: _propTypes["default"].object,
  toolbarOpts: _propTypes["default"].shape({
    position: _propTypes["default"].oneOf(['bottom', 'top']),
    alignment: _propTypes["default"].oneOf(['left', 'right']),
    alwaysVisible: _propTypes["default"].bool,
    ref: _propTypes["default"].func,
    showDone: _propTypes["default"].bool
  }),
  onDataChange: _propTypes["default"].func
});
var style = {
  toolbar: {
    position: 'absolute',
    zIndex: 10,
    cursor: 'pointer',
    justifyContent: 'space-between',
    background: 'var(--editable-html-toolbar-bg, #efefef)',
    minWidth: '280px',
    margin: '5px 0 0 0',
    padding: '2px',
    boxShadow: '0px 1px 5px 0px rgba(0, 0, 0, 0.2), 0px 2px 2px 0px rgba(0, 0, 0, 0.14), 0px 3px 1px -2px rgba(0, 0, 0, 0.12)',
    boxSizing: 'border-box',
    display: 'none'
  },
  toolbarWithNoDone: {
    minWidth: '265px'
  },
  toolbarTop: {
    top: '-45px'
  },
  toolbarRight: {
    right: 0
  },
  fullWidth: {
    width: '100%'
  },
  autoWidth: {
    width: 'auto'
  },
  focused: {
    display: 'flex'
  },
  iconRoot: {
    width: '28px',
    height: '28px',
    padding: '4px',
    verticalAlign: 'top'
  },
  label: {
    color: 'var(--editable-html-toolbar-check, #00bb00)'
  },
  shared: {
    display: 'flex'
  }
};

var _default = (0, _styles.withStyles)(style, {
  index: 1000
})(Toolbar);

exports["default"] = _default;
//# sourceMappingURL=toolbar.js.map