"use strict";

exports.__esModule = true;
exports["default"] = void 0;
var _sequenceUtils = require("@teselagen/sequence-utils");
var _rangeUtils = require("@teselagen/range-utils");
var _clipboard = _interopRequireDefault(require("clipboard"));
var _redux = require("redux");
var _lodash = require("lodash");
var _core = require("@blueprintjs/core");
var _recompose = require("recompose");
var _react = _interopRequireDefault(require("react"));
var _combokeys = _interopRequireDefault(require("combokeys"));
var _teselagenReactComponents = require("teselagen-react-components");
var _bioParsers = require("@teselagen/bio-parsers");
var _withEditorProps = _interopRequireDefault(require("../withEditorProps"));
var _commands = _interopRequireDefault(require("../commands"));
var _moveCaret = _interopRequireDefault(require("./moveCaret"));
var _createSequenceInputPopup = _interopRequireDefault(require("./createSequenceInputPopup"));
var _Keyboard = _interopRequireDefault(require("./Keyboard"));
var _clickAndDragUtils = require("./clickAndDragUtils");
var _getBpsPerRow = _interopRequireDefault(require("./getBpsPerRow"));
var _defaultConfig = require("../MenuBar/defaultConfig");
var _viewSubmenu = require("../MenuBar/viewSubmenu");
var _editorUtils = require("../utils/editorUtils");
var _GlobalDialogUtils = require("../GlobalDialogUtils");
var _excluded = ["event"],
  _excluded2 = ["children", "vectorInteractionWrapperStyle", "disableEditorClickAndDrag"];
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return defineProperty(generator, "_invoke", { value: makeInvokeMethod(innerFn, self, context) }), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == typeof value && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; defineProperty(this, "_invoke", { value: function value(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; } function maybeInvokeDelegate(delegate, context) { var methodName = context.method, method = delegate.iterator[methodName]; if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel; var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal", delete record.arg, entry.completion = record; } function Context(tryLocsList) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) { if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; } return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), defineProperty(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (val) { var object = Object(val), keys = []; for (var key in object) { keys.push(key); } return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) { "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); } }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, abrupt: function abrupt(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; } }, "catch": function _catch(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; }
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
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 _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 _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
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(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
var annotationClickHandlers = ["orfClicked", "primerClicked", "lineageAnnotationClicked", "assemblyPieceClicked", "translationClicked", "primaryProteinSequenceClicked", "cutsiteClicked", "translationDoubleClicked", "deletionLayerClicked", "replacementLayerClicked", "featureClicked", "warningClicked", "partClicked", "searchLayerClicked"];
//tnr: because this menu is being rendered outside the main render tree (by blueprint)
//we need to make sure it re-renders whenever the redux state changes (so things like tick-marks will toggle properly etc..)
var ConnectedMenu = (0, _withEditorProps["default"])(function (_ref) {
  var children = _ref.children;
  return /*#__PURE__*/_react["default"].createElement(_core.Menu, null, children.map(_react["default"].cloneElement));
});

//withEditorInteractions is meant to give "interaction" props like "onDrag, onCopy, onKeydown" to the circular/row/linear views
function VectorInteractionHOC(Component /* options */) {
  return /*#__PURE__*/function (_React$Component) {
    _inheritsLoose(VectorInteractionWrapper, _React$Component);
    function VectorInteractionWrapper(props) {
      var _this;
      _this = _React$Component.call(this, props) || this;
      _defineProperty(_assertThisInitialized(_this), "updateSelectionOrCaret", function (shiftHeld, newRangeOrCaret) {
        var _this$props = _this.props,
          selectionLayer = _this$props.selectionLayer,
          caretPosition = _this$props.caretPosition,
          _this$props$sequenceD = _this$props.sequenceData,
          sequenceData = _this$props$sequenceD === void 0 ? {
            sequence: ""
          } : _this$props$sequenceD;
        var sequenceLength = sequenceData.sequence.length;
        (0, _clickAndDragUtils.updateSelectionOrCaret)({
          doNotWrapOrigin: !sequenceData.circular,
          shiftHeld: shiftHeld,
          sequenceLength: sequenceLength,
          newRangeOrCaret: newRangeOrCaret,
          caretPosition: caretPosition,
          selectionLayer: selectionLayer,
          selectionLayerUpdate: _this.selectionLayerUpdate,
          caretPositionUpdate: _this.caretPositionUpdate
        });
      });
      _defineProperty(_assertThisInitialized(_this), "handlePaste", function (e) {
        var _this$props2 = _this.props,
          _this$props2$caretPos = _this$props2.caretPosition,
          caretPosition = _this$props2$caretPos === void 0 ? -1 : _this$props2$caretPos,
          _this$props2$selectio = _this$props2.selectionLayer,
          selectionLayer = _this$props2$selectio === void 0 ? {
            start: -1,
            end: -1
          } : _this$props2$selectio,
          readOnly = _this$props2.readOnly,
          onPaste = _this$props2.onPaste;
        if (readOnly) {
          return window.toastr.warning("Sorry the sequence is Read-Only");
        }
        if (!(caretPosition > -1 || selectionLayer.start > -1)) {
          return window.toastr.warning("Please place the cursor before pasting");
        }
        var seqDataToInsert;
        if (onPaste) {
          seqDataToInsert = onPaste(e, _this.props);
        } else {
          var clipboardData = e.clipboardData;
          var jsonData = clipboardData.getData("application/json");
          if (jsonData) {
            jsonData = JSON.parse(jsonData);
          }
          seqDataToInsert = jsonData || {
            sequence: clipboardData.getData("text/plain") || e.target.value
          };
        }
        seqDataToInsert = (0, _sequenceUtils.tidyUpSequenceData)(seqDataToInsert, {
          provideNewIdsForAnnotations: true,
          annotationsAsObjects: true,
          removeUnwantedChars: true,
          noCdsTranslations: true
        });
        if (!seqDataToInsert.sequence.length) return window.toastr.warning("Sorry no valid base pairs to paste");
        insertAndSelectHelper({
          seqDataToInsert: seqDataToInsert,
          props: _this.props
        });
        window.toastr.success("Sequence Pasted Successfully");
        e.preventDefault();
      });
      _defineProperty(_assertThisInitialized(_this), "handleCutOrCopy", function (isCut) {
        return function (e) {
          var _this$props3 = _this.props,
            _this$props3$onCopy = _this$props3.onCopy,
            onCopy = _this$props3$onCopy === void 0 ? function () {} : _this$props3$onCopy,
            sequenceData = _this$props3.sequenceData,
            selectionLayer = _this$props3.selectionLayer,
            copyOptions = _this$props3.copyOptions,
            readOnly = _this$props3.readOnly;
          var onCut = _this.props.onCut || _this.props.onCopy || function () {};
          var seqData = (0, _sequenceUtils.tidyUpSequenceData)(_this.sequenceDataToCopy || (0, _sequenceUtils.getSequenceDataBetweenRange)(sequenceData, (0, _editorUtils.getSelFromWrappedAddon)(selectionLayer, sequenceData.sequence.length), {
            excludePartial: {
              features: !copyOptions.partialFeatures,
              parts: !copyOptions.partialParts
            },
            exclude: {
              features: !copyOptions.features,
              parts: !copyOptions.parts
            }
          }), {
            annotationsAsObjects: true
          });
          if (!(_this.sequenceDataToCopy || {}).textToCopy && !seqData.sequence.length) return window.toastr.warning("No Sequence Selected To " + (isCut && !readOnly ? "Cut" : "Copy"));
          var clipboardData = e.clipboardData;
          var textToCopy = (_this.sequenceDataToCopy || {}).textToCopy !== undefined ? _this.sequenceDataToCopy.textToCopy : seqData.isProtein ? seqData.proteinSequence : seqData.sequence;
          seqData.textToCopy = textToCopy;
          clipboardData.setData("text/plain", textToCopy);
          clipboardData.setData("application/json", JSON.stringify(seqData));
          e.preventDefault();
          if (isCut && !readOnly) {
            _this.handleDnaDelete(false);
            onCut(e, (0, _sequenceUtils.tidyUpSequenceData)(seqData, {
              annotationsAsObjects: true
            }), _this.props);
            document.body.removeEventListener("cut", _this.handleCut);
          } else {
            onCopy(e, seqData, _this.props);
            document.body.removeEventListener("copy", _this.handleCopy);
          }
          window.toastr.success("Selection " + (isCut && !readOnly ? "Cut" : "Copied"));
          _this.sequenceDataToCopy = undefined;
        };
      });
      _defineProperty(_assertThisInitialized(_this), "handleCut", _this.handleCutOrCopy(true));
      _defineProperty(_assertThisInitialized(_this), "handleCopy", _this.handleCutOrCopy());
      _defineProperty(_assertThisInitialized(_this), "handleDnaInsert", function (_ref2) {
        var useEventPositioning = _ref2.useEventPositioning;
        var _this$props4 = _this.props,
          _this$props4$caretPos = _this$props4.caretPosition,
          caretPosition = _this$props4$caretPos === void 0 ? -1 : _this$props4$caretPos,
          _this$props4$selectio = _this$props4.selectionLayer,
          selectionLayer = _this$props4$selectio === void 0 ? {
            start: -1,
            end: -1
          } : _this$props4$selectio,
          _this$props4$sequence = _this$props4.sequenceData,
          sequenceData = _this$props4$sequence === void 0 ? {
            sequence: ""
          } : _this$props4$sequence,
          readOnly = _this$props4.readOnly;
        var sequenceLength = sequenceData.sequence.length;
        var isReplace = selectionLayer.start > -1;
        if (readOnly) {
          window.toastr.warning("Sorry the sequence is Read-Only");
        } else {
          (0, _createSequenceInputPopup["default"])({
            useEventPositioning: useEventPositioning,
            isReplace: isReplace,
            replaceChars: sequenceData.isRna ? {
              t: "u"
            } : undefined,
            acceptedChars: (0, _editorUtils.getAcceptedChars)(sequenceData),
            isProtein: sequenceData.isProtein,
            selectionLayer: selectionLayer,
            sequenceLength: sequenceLength,
            caretPosition: caretPosition,
            handleInsert: function handleInsert(seqDataToInsert) {
              insertAndSelectHelper({
                props: _this.props,
                seqDataToInsert: seqDataToInsert
              });
              window.toastr.success("Sequence Inserted Successfully");
            }
          });
        }
      });
      _defineProperty(_assertThisInitialized(_this), "handleDnaDelete", function (showToast) {
        if (showToast === void 0) {
          showToast = true;
        }
        var _this$props5 = _this.props,
          _this$props5$caretPos = _this$props5.caretPosition,
          caretPosition = _this$props5$caretPos === void 0 ? -1 : _this$props5$caretPos,
          _this$props5$selectio = _this$props5.selectionLayer,
          selectionLayer = _this$props5$selectio === void 0 ? {
            start: -1,
            end: -1
          } : _this$props5$selectio,
          _this$props5$sequence = _this$props5.sequenceData,
          sequenceData = _this$props5$sequence === void 0 ? {
            sequence: ""
          } : _this$props5$sequence,
          readOnly = _this$props5.readOnly,
          updateSequenceData = _this$props5.updateSequenceData,
          wrappedInsertSequenceDataAtPositionOrRange = _this$props5.wrappedInsertSequenceDataAtPositionOrRange,
          caretPositionUpdate = _this$props5.caretPositionUpdate;
        var sequenceLength = sequenceData.sequence.length;
        if (readOnly) {
          return window.toastr.warning("Sorry the sequence is Read-Only");
        }
        if (sequenceLength > 0) {
          var rangeToDelete = selectionLayer;
          var isCaretAtEndOfSeq;
          if (caretPosition > 0) {
            if (caretPosition === sequenceLength) {
              isCaretAtEndOfSeq = true;
            }
            rangeToDelete = {
              start: (0, _rangeUtils.normalizePositionByRangeLength)(caretPosition - (sequenceData.isProtein ? 3 : 1), sequenceLength),
              end: (0, _rangeUtils.normalizePositionByRangeLength)(caretPosition - 1, sequenceLength)
            };
          } else {
            if (rangeToDelete.end === sequenceLength - 1) {
              isCaretAtEndOfSeq = true;
            }
          }
          var _wrappedInsertSequenc = wrappedInsertSequenceDataAtPositionOrRange({}, sequenceData, rangeToDelete),
            newSeqData = _wrappedInsertSequenc[0];
          updateSequenceData(newSeqData);
          caretPositionUpdate(isCaretAtEndOfSeq ? newSeqData.sequence.length : rangeToDelete.start > newSeqData.sequence.length ?
          //we're deleting around the origin so set the cursor to the 0 position
          0 : (0, _rangeUtils.normalizePositionByRangeLength)(rangeToDelete.start, newSeqData.sequence.length));
          if (showToast) window.toastr.success("Sequence Deleted Successfully");
        }
      });
      _defineProperty(_assertThisInitialized(_this), "caretPositionUpdate", function (position) {
        var _this$props$caretPosi = _this.props.caretPosition,
          caretPosition = _this$props$caretPosi === void 0 ? -1 : _this$props$caretPosi;
        if (caretPosition === position) {
          return;
        }
        //we only call caretPositionUpdate if we're actually changing something
        _this.props.caretPositionUpdate(position);
      });
      _defineProperty(_assertThisInitialized(_this), "selectionLayerUpdate", function (newSelection) {
        var _this$props6 = _this.props,
          _this$props6$selectio = _this$props6.selectionLayer,
          selectionLayer = _this$props6$selectio === void 0 ? {
            start: -1,
            end: -1
          } : _this$props6$selectio,
          ignoreGapsOnHighlight = _this$props6.ignoreGapsOnHighlight;
        if (!newSelection) return;
        var start = newSelection.start,
          end = newSelection.end,
          forceUpdate = newSelection.forceUpdate;
        if (selectionLayer.start === start && selectionLayer.end === end && selectionLayer.forceUpdate === forceUpdate) {
          return;
        }
        //we only call selectionLayerUpdate if we're actually changing something
        _this.props.selectionLayerUpdate(_extends({}, newSelection, {
          start: start,
          end: end,
          ignoreGaps: ignoreGapsOnHighlight
        }));
      });
      _defineProperty(_assertThisInitialized(_this), "annotationClicked", function (_ref3) {
        var _event$target;
        var event = _ref3.event,
          annotation = _ref3.annotation;
        event.preventDefault && event.preventDefault();
        event.stopPropagation && event.stopPropagation();
        // if (hoveredAnnEasyStore.selectedAnn?.id === annotation?.id) {
        //   hoveredAnnEasyStore.selectedAnn = undefined;
        //   hoveredAnnEasyStore.hoveredAnn = undefined;
        // } else {
        //   hoveredAnnEasyStore.selectedAnn = annotation;
        // }

        var _this$props7 = _this.props,
          annotationSelect = _this$props7.annotationSelect,
          selectionLayer = _this$props7.selectionLayer,
          annotationDeselectAll = _this$props7.annotationDeselectAll,
          propertiesViewTabUpdate = _this$props7.propertiesViewTabUpdate;
        var forceUpdate;
        if (annotation.start > -1 &&
        // selectionLayer.start === annotation.start &&
        // selectionLayer.end === annotation.end &&
        event.altKey) {
          forceUpdate = selectionLayer.forceUpdate === "end" ? "start" : "end";
        }
        _this.updateSelectionOrCaret(event.shiftKey || event.metaKey, _extends({}, annotation, {
          isFromRowView: !!(event === null || event === void 0 ? void 0 : (_event$target = event.target) === null || _event$target === void 0 ? void 0 : _event$target.closest(".veRowView"))
        }, forceUpdate && {
          forceUpdate: forceUpdate
        }));
        !event.shiftKey && annotationDeselectAll(undefined);
        annotation.id && annotationSelect(annotation);
        annotation.annotationTypePlural && propertiesViewTabUpdate(annotation.annotationTypePlural, annotation);
      });
      _defineProperty(_assertThisInitialized(_this), "cutsiteClicked_localOverride", function (_ref4) {
        var event = _ref4.event,
          annotation = _ref4.annotation;
        event.preventDefault();
        event.stopPropagation();
        var _this$props8 = _this.props,
          annotationSelect = _this$props8.annotationSelect,
          annotationDeselectAll = _this$props8.annotationDeselectAll;
        _this.updateSelectionOrCaret(event.shiftKey, event.metaKey ? annotation : event.altKey ? annotation.bottomSnipPosition : annotation.topSnipPosition);
        annotationDeselectAll(undefined);
        annotationSelect(annotation);
      });
      _defineProperty(_assertThisInitialized(_this), "warningDoubleClicked", function (_ref5) {
        var event = _ref5.event,
          annotation = _ref5.annotation,
          doNotStopPropagation = _ref5.doNotStopPropagation;
        if (!doNotStopPropagation) {
          event.preventDefault();
          event.stopPropagation();
        }
        var _this$props9 = _this.props,
          annotationSelect = _this$props9.annotationSelect,
          annotationDeselectAll = _this$props9.annotationDeselectAll;
        (0, _teselagenReactComponents.showConfirmationDialog)({
          cancelButtonText: null,
          confirmButtonText: "OK",
          canEscapeKeyCancel: true,
          // intent: Intent.NONE,
          // onCancel: undefined,
          text: /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement("div", {
            style: {
              wordBreak: "break-word"
            }
          }, /*#__PURE__*/_react["default"].createElement("h3", null, annotation.name, ":"), annotation.message))
        });
        _this.updateSelectionOrCaret(event.shiftKey, annotation);
        annotationDeselectAll(undefined);
        annotationSelect(annotation);
      });
      _defineProperty(_assertThisInitialized(_this), "insertHelper", {
        onClick: function onClick(e, ctxInfo) {
          _this.handleDnaInsert({
            useEventPositioning: {
              e: e,
              nodeToReFocus: (0, _editorUtils.getNodeToRefocus)(ctxInfo.event.target)
            }
          });
        }
      });
      _defineProperty(_assertThisInitialized(_this), "getCopyOptions", function (annotation) {
        var _this$props10 = _this.props,
          sequenceData = _this$props10.sequenceData,
          readOnly = _this$props10.readOnly,
          selectionLayer = _this$props10.selectionLayer;
        var isProtein = sequenceData.isProtein;
        var makeTextCopyable = function makeTextCopyable(transformFunc, className, _action) {
          if (_action === void 0) {
            _action = "copy";
          }
          return new _clipboard["default"]("." + className, {
            action: function action() {
              return _action;
            },
            text: function text() {
              var _this$props11 = _this.props,
                selectionLayer = _this$props11.selectionLayer,
                editorName = _this$props11.editorName,
                store = _this$props11.store;
              var _store$getState$Vecto = store.getState().VectorEditor[editorName],
                sequenceData = _store$getState$Vecto.sequenceData,
                copyOptions = _store$getState$Vecto.copyOptions;
              var selectedSeqData = (0, _sequenceUtils.getSequenceDataBetweenRange)(sequenceData, (0, _editorUtils.getSelFromWrappedAddon)(selectionLayer, sequenceData.sequence.length), {
                excludePartial: {
                  features: !copyOptions.partialFeatures,
                  parts: !copyOptions.partialParts
                },
                exclude: {
                  features: !copyOptions.features,
                  parts: !copyOptions.parts
                }
              });
              var sequenceDataToCopy = transformFunc(selectedSeqData, sequenceData);
              _this.sequenceDataToCopy = sequenceDataToCopy;
              if (_action === "copy") {
                document.body.addEventListener("copy", _this.handleCopy);
              } else {
                document.body.addEventListener("cut", _this.handleCut);
              }
              if (window.Cypress) {
                window.Cypress.textToCopy = sequenceDataToCopy.textToCopy;
                window.Cypress.seqDataToCopy = sequenceDataToCopy;
              }
              return sequenceDataToCopy.textToCopy || sequenceDataToCopy.sequence;
            }
          });
        };
        var aaCopy = {
          text: "Copy AA Sequence",
          className: "openVeCopyAA",
          willUnmount: function willUnmount() {
            _this.openVeCopyAA && _this.openVeCopyAA.destroy();
          },
          didMount: function didMount(_ref6) {
            var className = _ref6.className;
            _this.openVeCopyAA = makeTextCopyable(function (selectedSeqData) {
              var textToCopy = isProtein ? selectedSeqData.proteinSequence.toUpperCase() : (0, _sequenceUtils.getAminoAcidStringFromSequenceString)(selectedSeqData.sequence);
              return _extends({}, selectedSeqData, {
                textToCopy: textToCopy
              });
            }, className);
          }
        };
        // TODO: maybe stop using Clipboard.js and unify clipboard handling with
        // a more versatile approach
        return [].concat(readOnly ? [] : [_extends({
          text: "Replace"
        }, _this.insertHelper), {
          text: "Cut",
          className: "openVeCut",
          willUnmount: function willUnmount() {
            _this.openVeCut && _this.openVeCut.destroy();
          },
          didMount: function didMount(_ref7) {
            var className = _ref7.className;
            // TODO: Maybe use a cut action instead
            _this.openVeCut = makeTextCopyable(function (s) {
              return _extends({}, s, {
                textToCopy: isProtein ? s.proteinSequence : s.sequence
              });
            }, className, "cut");
          }
        }], [{
          text: annotation.overlapsSelf || selectionLayer.overlapsSelf ? "Copy Wrapped Range" : "Copy",
          submenu: [].concat(isProtein ? [aaCopy] : [], [{
            text: isProtein ? "Copy DNA Bps" : "Copy",
            className: "openVeCopy2",
            willUnmount: function willUnmount() {
              _this.openVeCopy2 && _this.openVeCopy2.destroy();
            },
            didMount: function didMount(_ref8) {
              var className = _ref8.className;
              _this.openVeCopy2 = makeTextCopyable(function (s) {
                return _extends({}, s, {
                  textToCopy: s.sequence
                });
              }, className);
            }
          }, {
            text: "Copy Genbank For Selection",
            className: "openVeCopyGenbankForSelection",
            willUnmount: function willUnmount() {
              _this.openVeCopyGenbankForSelection && _this.openVeCopyGenbankForSelection.destroy();
            },
            didMount: function didMount(_ref9) {
              var className = _ref9.className;
              _this.openVeCopyGenbankForSelection = makeTextCopyable(getGenbankFromSelection, className);
            }
          }, {
            text: isProtein ? "Copy Reverse Complement DNA Bps" : "Copy Reverse Complement",
            className: "openVeCopyReverse",
            willUnmount: function willUnmount() {
              _this.openVeCopyReverse && _this.openVeCopyReverse.destroy();
            },
            didMount: function didMount(_ref10) {
              var className = _ref10.className;
              _this.openVeCopyReverse = makeTextCopyable(_sequenceUtils.getReverseComplementSequenceAndAnnotations, className);
            }
          }], isProtein ? [] : [aaCopy], [{
            text: "Copy Reverse Complement AA Sequence",
            className: "openVeCopyAAReverse",
            willUnmount: function willUnmount() {
              _this.openVeCopyAAReverse && _this.openVeCopyAAReverse.destroy();
            },
            didMount: function didMount(_ref11) {
              var className = _ref11.className;
              _this.openVeCopyAAReverse = makeTextCopyable(function (selectedSeqData) {
                var revSeqData = (0, _sequenceUtils.getReverseComplementSequenceAndAnnotations)(selectedSeqData);
                var textToCopy = isProtein ? revSeqData.proteinSequence.toUpperCase() : (0, _sequenceUtils.getAminoAcidStringFromSequenceString)(revSeqData.sequence);
                return _extends({}, revSeqData, {
                  textToCopy: textToCopy
                });
              }, className);
            }
          }, {
            text: isProtein ? "Copy Complement DNA Bps" : "Copy Complement",
            className: "openVeCopyComplement",
            willUnmount: function willUnmount() {
              _this.openVeCopyComplement && _this.openVeCopyComplement.destroy();
            },
            didMount: function didMount(_ref12) {
              var className = _ref12.className;
              _this.openVeCopyComplement = makeTextCopyable(_sequenceUtils.getComplementSequenceAndAnnotations, className);
            }
          }, _defaultConfig.copyOptionsMenu])
        }]);
      });
      _defineProperty(_assertThisInitialized(_this), "getSelectionMenuOptions", function (annotation) {
        var items = [].concat(_this.getCopyOptions(annotation), [_defaultConfig.createNewAnnotationMenu, "--", "selectInverse", "--", "reverseComplementSelection", "complementSelection", {
          cmd: "changeCaseCmd",
          text: "Change Case",
          submenu: [
          // "upperCaseSequence",
          // "lowerCaseSequence",
          "upperCaseSelection", "lowerCaseSelection"]
        }]);
        return items;
      });
      _defineProperty(_assertThisInitialized(_this), "normalizeAction", function (_ref13, handler) {
        var event = _ref13.event,
          rest = _objectWithoutPropertiesLoose(_ref13, _excluded);
        event.preventDefault();
        event.stopPropagation();
        return handler(_extends({
          event: event
        }, rest), _this.props);
      });
      _defineProperty(_assertThisInitialized(_this), "enhanceRightClickAction", function (action, key) {
        return function (opts) {
          var lastFocusedEl = document.activeElement;
          var _this$props$rightClic = _this.props.rightClickOverrides,
            rightClickOverrides = _this$props$rightClic === void 0 ? {} : _this$props$rightClic;
          var items = action(opts);
          var e = items && items._event || opts.event || opts;
          e.preventDefault && e.preventDefault();
          e.stopPropagation && e.stopPropagation();
          //override hook here
          var override = rightClickOverrides[key];
          (0, _teselagenReactComponents.showContextMenu)(override ? override(items, opts, _this.props) : items, [_this.commandEnhancer], e, function () {
            if (lastFocusedEl && document.activeElement && (document.activeElement.classList.contains("bp3-popover-enter-done") || document.activeElement.type === "textarea" &&
            //this is the clipboard textarea created by clipboardjs
            document.activeElement.offsetLeft === -9999)) {
              lastFocusedEl.focus();
            }
          }, opts,
          // context here
          _this.ConnectedMenu);
        };
      });
      _defineProperty(_assertThisInitialized(_this), "selectionLayerRightClicked", _this.enhanceRightClickAction(function (_ref14) {
        var annotation = _ref14.annotation;
        return _this.getSelectionMenuOptions({
          //manually only pluck off the start and end so that if the selection layer was generated from say a feature, those properties won't be carried into the create part/feature/primer dialogs
          isWrappedAddon: annotation.isWrappedAddon,
          overlapsSelf: annotation.overlapsSelf,
          start: annotation.start,
          end: annotation.end
        });
      }, "selectionLayerRightClicked"));
      _defineProperty(_assertThisInitialized(_this), "digestLaneRightClicked", _this.enhanceRightClickAction(function () {
        return ["newFeature", "newPart"];
      }, "digestLaneRightClicked"));
      _defineProperty(_assertThisInitialized(_this), "searchLayerRightClicked", _this.enhanceRightClickAction(function (_ref15) {
        var annotation = _ref15.annotation;
        _this.props.selectionLayerUpdate({
          start: annotation.start,
          end: annotation.end,
          forward: !annotation.bottomStrand
        });
        return _this.getSelectionMenuOptions({
          //manually only pluck off the start and end so that if the selection layer was generated from say a feature, those properties won't be carried into the create part/feature/primer dialogs
          start: annotation.start,
          end: annotation.end,
          forward: !annotation.bottomStrand
        });
      }, "searchLayerRightClicked"));
      _defineProperty(_assertThisInitialized(_this), "backgroundRightClicked", _this.enhanceRightClickAction(function (_ref16) {
        var nearestCaretPos = _ref16.nearestCaretPos,
          shiftHeld = _ref16.shiftHeld,
          event = _ref16.event;
        _this.updateSelectionOrCaret(shiftHeld, nearestCaretPos);
        var readOnly = _this.props.readOnly;
        var menu = [].concat(readOnly ? [] : [_extends({
          text: "Insert"
        }, _this.insertHelper)], ["rotateToCaretPosition", "createMenuHolder", _extends({}, _viewSubmenu.fullSequenceTranslationMenu, {
          text: "View Full Sequence Translations"
        })]);
        menu._event = event;
        return menu;
      }, "backgroundRightClicked"));
      _defineProperty(_assertThisInitialized(_this), "deletionLayerRightClicked", _this.enhanceRightClickAction(function (_ref17) {
        var annotation = _ref17.annotation;
        var _this$props12 = _this.props,
          editorName = _this$props12.editorName,
          dispatch = _this$props12.dispatch;
        return [{
          text: "Remove Deletion",
          // icon: "ion-plus-round",
          onClick: function onClick() {
            dispatch({
              type: "DELETION_LAYER_DELETE",
              meta: {
                editorName: editorName
              },
              payload: _extends({}, annotation)
            });
          }
        }];
      }, "deletionLayerRightClicked"));
      _defineProperty(_assertThisInitialized(_this), "partRightClicked", _this.enhanceRightClickAction(function (_ref18) {
        var _event$target2;
        var annotation = _ref18.annotation,
          event = _ref18.event;
        _this.props.selectionLayerUpdate({
          isFromRowView: !!(event === null || event === void 0 ? void 0 : (_event$target2 = event.target) === null || _event$target2 === void 0 ? void 0 : _event$target2.closest(".veRowView")),
          start: annotation.start,
          end: annotation.end,
          isWrappedAddon: annotation.isWrappedAddon,
          overlapsSelf: annotation.overlapsSelf
        });
        return ["editPart", "deletePart", "--"].concat(_this.getSelectionMenuOptions(annotation), ["--", "showRemoveDuplicatesDialogParts", "viewPartProperties"]);
      }, "partRightClicked"));
      _defineProperty(_assertThisInitialized(_this), "warningRightClicked", _this.enhanceRightClickAction(function (_ref19) {
        var _event$target3;
        var annotation = _ref19.annotation,
          event = _ref19.event;
        _this.props.selectionLayerUpdate({
          isFromRowView: !!(event === null || event === void 0 ? void 0 : (_event$target3 = event.target) === null || _event$target3 === void 0 ? void 0 : _event$target3.closest(".veRowView")),
          start: annotation.start,
          end: annotation.end
        });
        return [{
          text: "View Warning Details",
          onClick: function onClick(event) {
            _this.warningDoubleClicked({
              event: event,
              annotation: annotation,
              doNotStopPropagation: true
            });
          }
        }, "--"].concat(_this.getSelectionMenuOptions(annotation));
      }, "warningRightClicked"));
      _defineProperty(_assertThisInitialized(_this), "featureRightClicked", _this.enhanceRightClickAction(function (_ref20) {
        var _event$target4;
        var annotation = _ref20.annotation,
          event = _ref20.event;
        _this.props.selectionLayerUpdate({
          isFromRowView: !!(event === null || event === void 0 ? void 0 : (_event$target4 = event.target) === null || _event$target4 === void 0 ? void 0 : _event$target4.closest(".veRowView")),
          start: annotation.start,
          end: annotation.end
        });
        event.persist();
        var _this$props13 = _this.props,
          readOnly = _this$props13.readOnly,
          _this$props13$annotat = _this$props13.annotationsToSupport;
        _this$props13$annotat = _this$props13$annotat === void 0 ? {} : _this$props13$annotat;
        var parts = _this$props13$annotat.parts;
        return ["editFeature", "deleteFeature"].concat(_this.getSelectionMenuOptions(annotation), readOnly ? [] : [].concat(parts && ["--", {
          text: "Make a Part from Feature",
          onClick: function () {
            var _onClick = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
              var _this$props14, sequenceData, upsertPart, doAction;
              return _regeneratorRuntime().wrap(function _callee$(_context) {
                while (1) {
                  switch (_context.prev = _context.next) {
                    case 0:
                      _this$props14 = _this.props, sequenceData = _this$props14.sequenceData, upsertPart = _this$props14.upsertPart;
                      if (!(0, _lodash.some)(sequenceData.parts, function (part) {
                        if (part.start === annotation.start && part.end === annotation.end) {
                          return true;
                        }
                      })) {
                        _context.next = 7;
                        break;
                      }
                      _context.next = 4;
                      return (0, _teselagenReactComponents.showConfirmationDialog)({
                        text: "A part already exists that matches this feature's range. Do you want to make one anyways?",
                        confirmButtonText: "Create Part",
                        canEscapeKeyCancel: true //this is false by default
                      });
                    case 4:
                      doAction = _context.sent;
                      if (doAction) {
                        _context.next = 7;
                        break;
                      }
                      return _context.abrupt("return");
                    case 7:
                      upsertPart({
                        start: annotation.start,
                        end: annotation.end,
                        type: annotation.type,
                        forward: annotation.forward,
                        name: annotation.name
                      });
                    case 8:
                    case "end":
                      return _context.stop();
                  }
                }
              }, _callee);
            }));
            function onClick() {
              return _onClick.apply(this, arguments);
            }
            return onClick;
          }()
        }], [{
          text: "Merge With Another Feature",
          onClick: function onClick() {
            _this.annotationClicked({
              annotation: annotation,
              event: _extends({}, event, {
                shiftHeld: true
              })
            });
            // annotationSelect(annotation)
            (0, _GlobalDialogUtils.showDialog)({
              dialogType: "MergeFeaturesDialog"
            });
          }
        }, "showRemoveDuplicatesDialogFeatures", "--"]), ["toggleCdsFeatureTranslations", "--", "viewFeatureProperties"]);
      }, "featureRightClicked"));
      _defineProperty(_assertThisInitialized(_this), "cutsiteRightClicked", _this.enhanceRightClickAction(function () {
        return ["viewCutsiteProperties"];
      }, "cutsiteRightClicked"));
      _defineProperty(_assertThisInitialized(_this), "primerRightClicked", _this.enhanceRightClickAction(function (_ref21) {
        var _event$target5;
        var annotation = _ref21.annotation,
          event = _ref21.event;
        _this.props.selectionLayerUpdate({
          isFromRowView: !!(event === null || event === void 0 ? void 0 : (_event$target5 = event.target) === null || _event$target5 === void 0 ? void 0 : _event$target5.closest(".veRowView")),
          start: annotation.start,
          end: annotation.end
        });
        return ["editPrimer", "deletePrimer"].concat(_this.getSelectionMenuOptions(annotation), ["showRemoveDuplicatesDialogPrimers", "viewPrimerProperties"]);
      }, "primerRightClicked"));
      _defineProperty(_assertThisInitialized(_this), "orfRightClicked", _this.enhanceRightClickAction(function (_ref22) {
        var _event$target6;
        var annotation = _ref22.annotation,
          event = _ref22.event;
        _this.props.selectionLayerUpdate({
          isFromRowView: !!(event === null || event === void 0 ? void 0 : (_event$target6 = event.target) === null || _event$target6 === void 0 ? void 0 : _event$target6.closest(".veRowView")),
          start: annotation.start,
          end: annotation.end
        });
        return ["toggleOrfTranslations"].concat(_this.getSelectionMenuOptions(annotation), ["viewOrfProperties"]);
      }, "orfRightClicked"));
      _defineProperty(_assertThisInitialized(_this), "translationRightClicked", _this.enhanceRightClickAction(function (_ref23) {
        var _event$target7;
        var event = _ref23.event,
          annotation = _ref23.annotation;
        event.preventDefault();
        event.stopPropagation();
        var _this$props15 = _this.props,
          selectionLayerUpdate = _this$props15.selectionLayerUpdate,
          annotationVisibilityToggle = _this$props15.annotationVisibilityToggle;
        _this.props.selectionLayerUpdate({
          isFromRowView: !!(event === null || event === void 0 ? void 0 : (_event$target7 = event.target) === null || _event$target7 === void 0 ? void 0 : _event$target7.closest(".veRowView")),
          start: annotation.start,
          end: annotation.end
        });
        if (annotation.isOrf) {
          return [{
            text: "Hide ORF Translations",
            onClick: function onClick() {
              annotationVisibilityToggle("orfTranslations");
            }
          }, "viewOrfProperties"];
        }
        return ["deleteTranslation", {
          text: "Select Translation",
          onClick: function onClick() {
            selectionLayerUpdate({
              start: annotation.start,
              end: annotation.end
            });
          }
        }].concat(_this.getSelectionMenuOptions(annotation), ["viewTranslationProperties"]);
      }, "translationRightClicked"));
      _defineProperty(_assertThisInitialized(_this), "featureDoubleClicked", function (_ref24) {
        var annotation = _ref24.annotation;
        (0, _GlobalDialogUtils.showAddOrEditAnnotationDialog)({
          type: "feature",
          annotation: annotation
        });
      });
      _defineProperty(_assertThisInitialized(_this), "partDoubleClicked", function (_ref25) {
        var annotation = _ref25.annotation;
        (0, _GlobalDialogUtils.showAddOrEditAnnotationDialog)({
          type: "part",
          annotation: annotation
        });
      });
      _defineProperty(_assertThisInitialized(_this), "primerDoubleClicked", function (_ref26) {
        var annotation = _ref26.annotation;
        (0, _GlobalDialogUtils.showAddOrEditAnnotationDialog)({
          type: "primer",
          annotation: annotation
        });
      });
      _defineProperty(_assertThisInitialized(_this), "cutsiteDoubleClicked", function (_ref27) {
        var annotation = _ref27.annotation;
        (0, _GlobalDialogUtils.showDialog)({
          dialogType: "AdditionalCutsiteInfoDialog",
          props: {
            dialogProps: {
              title: annotation.name
            },
            cutsiteOrGroupKey: annotation.name
          }
        });
      });
      annotationClickHandlers.forEach(function (handler) {
        _this[handler] = function () {
          var _this$props$clickOver = _this.props.clickOverrides,
            clickOverrides = _this$props$clickOver === void 0 ? {} : _this$props$clickOver;
          var preventDefault;
          var defaultHandler = _this[handler + "_localOverride"] ? _this[handler + "_localOverride"] : _this.annotationClicked;
          if (clickOverrides[handler]) {
            preventDefault = clickOverrides[handler].apply(clickOverrides, arguments);
          }
          !preventDefault && defaultHandler.apply(void 0, arguments);
        };
      });
      _this.ConnectedMenu = function (p) {
        return /*#__PURE__*/_react["default"].createElement(ConnectedMenu, _extends({}, props, p));
      };
      return _this;
    }
    var _proto = VectorInteractionWrapper.prototype;
    _proto.componentWillUnmount = function componentWillUnmount() {
      this.combokeys && this.combokeys.detach();
    };
    _proto.componentDidMount = function componentDidMount() {
      var _this2 = this;
      if (!this.node) return;
      this.combokeys = new _combokeys["default"](this.node);

      // bind a bunch of this.combokeys shortcuts we're interested in catching
      // we're using the "combokeys" library which extends mousetrap (available thru npm: https://www.npmjs.com/package/br-mousetrap)
      // documentation: https://craig.is/killing/mice
      this.combokeys.bind("-.*ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""), function (event) {
        _this2.handleDnaInsert(event);
      });

      // TODO: move these into commands
      var moveCaretBindings = [{
        keyCombo: ["left", "shift+left"],
        type: "moveCaretLeftOne"
      }, {
        keyCombo: ["right", "shift+right"],
        type: "moveCaretRightOne"
      }, {
        keyCombo: ["up", "shift+up"],
        type: "moveCaretUpARow"
      }, {
        keyCombo: ["down", "shift+down"],
        type: "moveCaretDownARow"
      }, {
        keyCombo: ["alt+right", "alt+shift+right"],
        type: "moveCaretToEndOfRow"
      }, {
        keyCombo: ["alt+left", "alt+shift+left"],
        type: "moveCaretToStartOfRow"
      }, {
        keyCombo: ["alt+up", "alt+shift+up"],
        type: "moveCaretToStartOfSequence"
      }, {
        keyCombo: ["alt+down", "alt+shift+down"],
        type: "moveCaretToEndOfSequence"
      }];
      moveCaretBindings.forEach(function (_ref28) {
        var keyCombo = _ref28.keyCombo,
          type = _ref28.type;
        _this2.combokeys.bind(keyCombo, function (event) {
          var shiftHeld = event.shiftKey;
          var bpsPerRow = (0, _getBpsPerRow["default"])(_this2.props);
          var _this2$props = _this2.props,
            selectionLayer = _this2$props.selectionLayer,
            caretPosition = _this2$props.caretPosition,
            sequenceLength = _this2$props.sequenceLength,
            _this2$props$sequence = _this2$props.sequenceData;
          _this2$props$sequence = _this2$props$sequence === void 0 ? {} : _this2$props$sequence;
          var isProtein = _this2$props$sequence.isProtein,
            circular = _this2$props$sequence.circular,
            circular2 = _this2$props.circular,
            caretPositionUpdate = _this2$props.caretPositionUpdate,
            selectionLayerUpdate = _this2$props.selectionLayerUpdate;
          var moveBy = (0, _moveCaret["default"])({
            sequenceLength: sequenceLength,
            bpsPerRow: bpsPerRow,
            caretPosition: caretPosition,
            selectionLayer: selectionLayer,
            isProtein: isProtein,
            shiftHeld: shiftHeld,
            type: type
          });
          (0, _clickAndDragUtils.handleCaretMoved)({
            moveBy: moveBy,
            circular: circular || circular2,
            sequenceLength: sequenceLength,
            bpsPerRow: bpsPerRow,
            caretPosition: caretPosition,
            selectionLayer: selectionLayer,
            shiftHeld: shiftHeld,
            type: type,
            caretPositionUpdate: caretPositionUpdate,
            selectionLayerUpdate: selectionLayerUpdate
          });
          event.stopPropagation();
        });
      });
      this.combokeys.bind(["backspace", "del"], function (event) {
        // Handle shortcut
        _this2.handleDnaDelete(event);
      });
      this.commandEnhancer = (0, _teselagenReactComponents.commandMenuEnhancer)((0, _commands["default"])(this), {
        useTicks: true,
        omitIcons: true
      });
    };
    _proto.render = function render() {
      var _this3 = this;
      var _this$props16 = this.props,
        closePanelButton = _this$props16.closePanelButton,
        _this$props16$selecti = _this$props16.selectionLayer,
        selectionLayer = _this$props16$selecti === void 0 ? {
          start: -1,
          end: -1
        } : _this$props16$selecti,
        _this$props16$sequenc = _this$props16.sequenceData,
        sequenceData = _this$props16$sequenc === void 0 ? {
          sequence: ""
        } : _this$props16$sequenc,
        tabHeight = _this$props16.tabHeight;
      //do this in two steps to determine propsToPass

      var _this$props17 = this.props,
        children = _this$props17.children,
        _this$props17$vectorI = _this$props17.vectorInteractionWrapperStyle,
        vectorInteractionWrapperStyle = _this$props17$vectorI === void 0 ? {} : _this$props17$vectorI,
        _this$props17$disable = _this$props17.disableEditorClickAndDrag,
        disableEditorClickAndDrag = _this$props17$disable === void 0 ? false : _this$props17$disable,
        propsToPass = _objectWithoutPropertiesLoose(_this$props17, _excluded2);
      var _ref29 = this.props.dimensions || {},
        width = _ref29.width,
        height = _ref29.height;
      propsToPass.width = width;
      propsToPass.height = height - tabHeight;
      // if (fitHeight) {
      // }
      var selectedBps = (0, _rangeUtils.getSequenceWithinRange)(selectionLayer, sequenceData.sequence);
      if (!disableEditorClickAndDrag) {
        propsToPass = _extends({}, propsToPass, {
          selectionLayerRightClicked: this.selectionLayerRightClicked,
          digestLaneRightClicked: this.digestLaneRightClicked,
          searchLayerRightClicked: this.searchLayerRightClicked,
          backgroundRightClicked: this.backgroundRightClicked,
          featureRightClicked: this.featureRightClicked,
          partRightClicked: this.partRightClicked,
          primerRightClicked: this.primerRightClicked,
          featureDoubleClicked: this.featureDoubleClicked,
          partDoubleClicked: this.partDoubleClicked,
          primerDoubleClicked: this.primerDoubleClicked,
          warningDoubleClicked: this.warningDoubleClicked,
          warningRightClicked: this.warningRightClicked,
          orfRightClicked: this.orfRightClicked,
          deletionLayerRightClicked: this.deletionLayerRightClicked,
          cutsiteRightClicked: this.cutsiteRightClicked,
          cutsiteDoubleClicked: this.cutsiteDoubleClicked,
          translationRightClicked: this.translationRightClicked
        }, annotationClickHandlers.reduce(function (acc, handler) {
          acc[handler] = _this3[handler];
          return acc;
        }, {}), {
          editorClicked: function editorClicked(p) {
            (0, _clickAndDragUtils.editorClicked)(_extends({}, p, {
              updateSelectionOrCaret: _this3.updateSelectionOrCaret
            }));
          }
        });
      }
      // propsToPass.triggerClipboardCommand = this.triggerClipboardCommand;

      return /*#__PURE__*/_react["default"].createElement("div", {
        tabIndex: 0 //this helps with focusing using Keyboard's parentElement.focus()
        ,
        ref: function ref(c) {
          return _this3.node = c;
        },
        className: "veVectorInteractionWrapper",
        style: _extends({
          position: "relative"
        }, vectorInteractionWrapperStyle),
        onFocus: this.handleWrapperFocus
      }, closePanelButton, /*#__PURE__*/_react["default"].createElement(_Keyboard["default"], {
        value: selectedBps,
        onCopy: this.handleCopy,
        onPaste: this.handlePaste,
        onCut: this.handleCut
      }), /*#__PURE__*/_react["default"].createElement(Component, propsToPass));
    };
    return VectorInteractionWrapper;
  }(_react["default"].Component);
}
var withEditorInteractions = (0, _redux.compose)(_teselagenReactComponents.withStore, _withEditorProps["default"], (0, _recompose.branch)(function (_ref30) {
  var noInteractions = _ref30.noInteractions;
  return !noInteractions;
}, VectorInteractionHOC));
var _default = withEditorInteractions;
exports["default"] = _default;
function getGenbankFromSelection(selectedSeqData, sequenceData) {
  var spansEntireSeq = sequenceData.sequence.length === selectedSeqData.sequence.length;
  var feats = (0, _lodash.map)(selectedSeqData.features);
  var just1Feat = feats.length === 1;
  return _extends({}, selectedSeqData, {
    textToCopy: (0, _bioParsers.jsonToGenbank)(_extends({}, selectedSeqData, {
      name: spansEntireSeq ? selectedSeqData.name : just1Feat ? feats[0].name : selectedSeqData.name + "_partial",
      circular: spansEntireSeq ? selectedSeqData.circular : false
    }))
  });
}
var insertAndSelectHelper = function insertAndSelectHelper(_ref31) {
  var seqDataToInsert = _ref31.seqDataToInsert,
    props = _ref31.props;
  var updateSequenceData = props.updateSequenceData,
    wrappedInsertSequenceDataAtPositionOrRange = props.wrappedInsertSequenceDataAtPositionOrRange,
    sequenceData = props.sequenceData,
    selectionLayerUpdate = props.selectionLayerUpdate,
    caretPosition = props.caretPosition,
    selectionLayer = props.selectionLayer;

  // sequenceData,
  //             caretPosition,
  //             selectionLayer

  // updateSequenceData(
  //   wrappedInsertSequenceDataAtPositionOrRange(
  //     seqDataToInsert,
  //     sequenceData,
  //     caretPosition > -1 ? caretPosition : selectionLayer
  //   )
  // );

  // const newSelectionLayerStart =
  //   caretPosition > -1 ? caretPosition : (selectionLayer.start > selectionLayer.end ? 0 : selectionLayer.start);
  // selectionLayerUpdate({
  //   start: newSelectionLayerStart,
  //   end: newSelectionLayerStart + seqDataToInsert.sequence.length - 1
  // });
  var _wrappedInsertSequenc2 = wrappedInsertSequenceDataAtPositionOrRange(seqDataToInsert, sequenceData, caretPosition > -1 ? caretPosition : selectionLayer),
    newSeqData = _wrappedInsertSequenc2[0],
    maintainOriginSplit = _wrappedInsertSequenc2[1].maintainOriginSplit;
  updateSequenceData(newSeqData);
  var seqDataInsertLength = seqDataToInsert.sequence ? seqDataToInsert.sequence.length : null;
  var selectionStartDistanceFromEnd = Math.min(sequenceData.size - selectionLayer.start, seqDataInsertLength) || seqDataInsertLength;
  var newSelectionLayerStart = caretPosition > -1 ? caretPosition : selectionLayer.start > selectionLayer.end ? maintainOriginSplit ? newSeqData.size - selectionStartDistanceFromEnd : 0 : selectionLayer.start;
  var newSelectionLayerEnd = newSelectionLayerStart + (seqDataToInsert.sequence ? seqDataToInsert.sequence.length - 1 : seqDataToInsert.proteinSequence ? seqDataToInsert.proteinSequence.length * 3 - 1 : 0);
  selectionLayerUpdate({
    start: newSelectionLayerStart,
    end: newSelectionLayerEnd % newSeqData.sequence.length
  });
};
module.exports = exports.default;