"use strict";

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

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

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

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

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

var _reactDom = _interopRequireDefault(require("react-dom"));

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

var _get = _interopRequireDefault(require("lodash/get"));

var _mathToolbar = require("@pie-lib/math-toolbar");

var _customPopper = _interopRequireDefault(require("./custom-popper"));

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

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

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

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; }

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

var removePopOvers = function removePopOvers() {
  var prevPopOvers = document.querySelectorAll('#mouse-over-popover');
  log('[characters:removePopOvers]');
  prevPopOvers.forEach(function (s) {
    return s.remove();
  });
};

var removeDialogs = function removeDialogs() {
  var prevDialogs = document.querySelectorAll('.insert-character-dialog');
  log('[characters:removeDialogs]');
  prevDialogs.forEach(function (s) {
    return s.remove();
  });
  removePopOvers();
};

exports.removeDialogs = removeDialogs;

var insertDialog = function insertDialog(_ref) {
  var editorDOM = _ref.editorDOM,
      value = _ref.value,
      callback = _ref.callback,
      opts = _ref.opts;
  var newEl = document.createElement('div');
  log('[characters:insertDialog]');
  removeDialogs();
  newEl.className = 'insert-character-dialog';
  var configToUse;

  switch (true) {
    case opts.language === 'spanish':
      configToUse = _utils2.spanishConfig;
      break;

    case opts.language === 'special':
      configToUse = _utils2.specialConfig;
      break;

    default:
      configToUse = opts;
  }

  if (!configToUse.characters) {
    (0, _utils.insertSnackBar)('No characters provided or language not recognized');
    return;
  }

  var layoutForCharacters = configToUse.characters.reduce(function (obj, arr) {
    if (arr.length >= obj.columns) {
      obj.columns = arr.length;
    }

    return obj;
  }, {
    rows: configToUse.characters.length,
    columns: 0
  });
  var popoverEl;

  var closePopOver = function closePopOver() {
    if (popoverEl) {
      popoverEl.remove();
    }

    removePopOvers();
  };

  var renderPopOver = function renderPopOver(event, el) {
    if (!event) {
      return;
    }

    var infoStyle = {
      fontSize: '20px',
      lineHeight: '20px'
    };
    closePopOver();
    popoverEl = document.createElement('div');

    _reactDom["default"].render( /*#__PURE__*/_react["default"].createElement(_customPopper["default"], {
      onClose: closePopOver,
      anchorEl: event.currentTarget
    }, /*#__PURE__*/_react["default"].createElement("div", null, el.label), /*#__PURE__*/_react["default"].createElement("div", {
      style: infoStyle
    }, el.description), /*#__PURE__*/_react["default"].createElement("div", {
      style: infoStyle
    }, el.unicode)), popoverEl);

    document.body.appendChild(newEl);
  };

  var firstCallMade = false;

  var listener = function listener(e) {
    // this will be triggered right after setting it because
    // this toolbar is added on the mousedown event
    // so right after mouseup, the click will be triggered
    if (firstCallMade) {
      var focusIsInModals = newEl.contains(e.target) || popoverEl && popoverEl.contains(e.target);
      var focusIsInEditor = editorDOM.contains(e.target);

      if (!(focusIsInModals || focusIsInEditor)) {
        handleClose();
      }
    } else {
      firstCallMade = true;
    }
  };

  var handleClose = function handleClose() {
    callback(undefined, true);
    newEl.remove();
    closePopOver();
    document.body.removeEventListener('click', listener);
  };

  var handleChange = function handleChange(val) {
    if (typeof val === 'string') {
      callback(val, true);
    }
  };

  var el = /*#__PURE__*/_react["default"].createElement(_mathToolbar.PureToolbar, {
    keyPadCharacterRef: opts.keyPadCharacterRef,
    setKeypadInteraction: opts.setKeypadInteraction,
    autoFocus: true,
    noDecimal: true,
    hideInput: true,
    noLatexHandling: true,
    hideDoneButtonBackground: true,
    layoutForKeyPad: layoutForCharacters,
    additionalKeys: configToUse.characters.reduce(function (arr, n) {
      arr = [].concat((0, _toConsumableArray2["default"])(arr), (0, _toConsumableArray2["default"])(n.map(function (k) {
        return _objectSpread({
          name: (0, _get["default"])(k, 'name') || k,
          write: (0, _get["default"])(k, 'write') || k,
          label: (0, _get["default"])(k, 'label') || k,
          category: 'character',
          extraClass: 'character',
          extraProps: _objectSpread(_objectSpread({}, k.extraProps || {}), {}, {
            style: _objectSpread(_objectSpread({}, (k.extraProps || {}).style), {}, {
              border: '1px solid #000'
            })
          })
        }, configToUse.hasPreview ? {
          actions: {
            onMouseEnter: function onMouseEnter(ev) {
              return renderPopOver(ev, k);
            },
            onMouseLeave: closePopOver
          }
        } : {});
      })));
      return arr;
    }, []),
    keypadMode: "language",
    onChange: handleChange,
    onDone: handleClose
  });

  _reactDom["default"].render(el, newEl, function () {
    var cursorItem = document.querySelector("[data-key=\"".concat(value.anchorKey, "\"]"));

    if (cursorItem) {
      var bodyRect = document.body.getBoundingClientRect();
      var boundRect = cursorItem.getBoundingClientRect();
      document.body.appendChild(newEl); // when height of toolbar exceeds screen - can happen in scrollable contexts

      var additionalTopOffset = 0;

      if (boundRect.y < newEl.offsetHeight) {
        additionalTopOffset = newEl.offsetHeight - boundRect.y + 10;
      }

      newEl.style.maxWidth = '500px';
      newEl.style.position = 'absolute';
      newEl.style.top = "".concat(boundRect.top + Math.abs(bodyRect.top) - newEl.offsetHeight - 10 + additionalTopOffset, "px");
      newEl.style.zIndex = 99999;
      var leftValue = "".concat(boundRect.left + Math.abs(bodyRect.left) + cursorItem.offsetWidth + 10, "px");
      var rightValue = "".concat(boundRect.x, "px");
      newEl.style.left = leftValue;
      var leftAlignedWidth = newEl.offsetWidth;
      newEl.style.left = 'unset';
      newEl.style.right = rightValue;
      var rightAlignedWidth = newEl.offsetWidth;
      newEl.style.left = 'unset';
      newEl.style.right = 'unset';

      if (leftAlignedWidth >= rightAlignedWidth) {
        newEl.style.left = leftValue;
      } else {
        newEl.style.right = rightValue;
      }

      document.body.addEventListener('click', listener);
    }
  });
};

var CharacterIcon = function CharacterIcon(_ref2) {
  var letter = _ref2.letter;
  return /*#__PURE__*/_react["default"].createElement("div", {
    style: {
      fontSize: '24px',
      lineHeight: '24px'
    }
  }, letter);
};

CharacterIcon.propTypes = {
  letter: _propTypes["default"].string
};

function CharactersPlugin(opts) {
  removeDialogs();
  return {
    name: 'characters',
    toolbar: {
      icon: /*#__PURE__*/_react["default"].createElement(CharacterIcon, {
        letter: opts.characterIcon || _utils2.characterIcons[opts.language] || 'ñ'
      }),
      ariaLabel: "".concat(opts.language, " characters Toolbar"),
      onClick: function onClick(value, onChange, getFocusedValue) {
        var editorDOM = document.querySelector("[data-key=\"".concat(value.document.key, "\"]"));
        var valueToUse = value;

        var callback = function callback(_char, focus) {
          if (getFocusedValue) {
            valueToUse = getFocusedValue() || valueToUse;
          }

          if (_char) {
            var change = valueToUse.change().insertTextByKey(valueToUse.anchorKey, valueToUse.anchorOffset, _char);
            valueToUse = change.value;
            log('[characters:insert]: ', value);
            onChange(change);
          }

          log('[characters:click]');

          if (focus) {
            if (editorDOM) {
              editorDOM.focus();
            }
          }
        };

        insertDialog({
          editorDOM: editorDOM,
          value: valueToUse,
          callback: callback,
          opts: opts
        });
      }
    },
    pluginStyles: function pluginStyles(node, parentNode, p) {
      if (p) {
        return {
          position: 'absolute',
          top: 'initial'
        };
      }
    }
  };
}
//# sourceMappingURL=index.js.map