"use strict";

exports.__esModule = true;
exports.exportSequenceToFile = exports["default"] = exports.connectToEditor = void 0;
exports.fakeActionOverrides = fakeActionOverrides;
exports.getCombinedActions = getCombinedActions;
exports.getShowGCContent = getShowGCContent;
exports.importSequenceFromFile = exports.handleSave = exports.handleInverse = void 0;
exports.mapDispatchToActions = mapDispatchToActions;
exports.withEditorPropsNoRedux = exports.updateCircular = void 0;
var _sequenceUtils = require("@teselagen/sequence-utils");
var _bioParsers = require("@teselagen/bio-parsers");
var _fileSaver = _interopRequireDefault(require("file-saver"));
var _redux = require("redux");
var _reactRedux = require("react-redux");
var _recompose = require("recompose");
var _reduxForm = require("redux-form");
var _teselagenReactComponents = require("teselagen-react-components");
var _lodash = require("lodash");
var _core = require("@blueprintjs/core");
var _rangeUtils = require("@teselagen/range-utils");
var _shortid = _interopRequireDefault(require("shortid"));
var _addMetaToActionCreators = _interopRequireDefault(require("../redux/utils/addMetaToActionCreators"));
var _redux2 = require("../redux");
var _selectors = _interopRequireDefault(require("../selectors"));
var _annotationTypes = require("../utils/annotationTypes");
var _findToolConstants = require("../constants/findToolConstants");
var _reselect = require("reselect");
var _domToImage = _interopRequireDefault(require("dom-to-image"));
var _GlobalDialogUtils = require("../GlobalDialogUtils");
var _updateEditor = _interopRequireDefault(require("../updateEditor"));
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 _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); }
// import { getStartEndFromBases } from "../utils/editorUtils";

var getUpperOrLowerSeq = (0, _reselect.defaultMemoize)(function (uppercaseSequenceMapFont, sequence) {
  if (sequence === void 0) {
    sequence = "";
  }
  return uppercaseSequenceMapFont === "uppercase" ? sequence.toUpperCase() : uppercaseSequenceMapFont === "lowercase" ? sequence.toLowerCase() : sequence;
});
var getTypesToOmit = function getTypesToOmit(annotationsToSupport) {
  var typesToOmit = {};
  _annotationTypes.allTypes.forEach(function (type) {
    if (!annotationsToSupport[type]) typesToOmit[type] = false;
  });
  return typesToOmit;
};
var getVisibilities = (0, _reselect.createSelector)(function (ed) {
  return ed.annotationVisibility;
}, function (ed) {
  return ed.annotationLabelVisibility;
}, function (ed) {
  return ed.annotationsToSupport;
}, function (annotationVisibility, annotationLabelVisibility, annotationsToSupport) {
  var typesToOmit = getTypesToOmit(annotationsToSupport);
  var annotationVisibilityToUse = _extends({}, annotationVisibility, typesToOmit);
  var annotationLabelVisibilityToUse = _extends({}, annotationLabelVisibility, typesToOmit);
  return {
    annotationVisibilityToUse: annotationVisibilityToUse,
    annotationLabelVisibilityToUse: annotationLabelVisibilityToUse,
    typesToOmit: typesToOmit
  };
});
function getSaveDialogEl() {
  return _getSaveDialogEl.apply(this, arguments);
}
/**
 * Function to generate a png
 *
 * @return {object} - Blob (png) | Error
 */
function _getSaveDialogEl() {
  _getSaveDialogEl = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7() {
    return _regeneratorRuntime().wrap(function _callee7$(_context7) {
      while (1) {
        switch (_context7.prev = _context7.next) {
          case 0:
            return _context7.abrupt("return", new Promise(function (resolve) {
              (0, _GlobalDialogUtils.showDialog)({
                dialogType: "PrintDialog",
                props: {
                  dialogProps: {
                    title: "Generating Image to Save...",
                    isCloseButtonShown: false
                  },
                  addPaddingBottom: true,
                  hideLinearCircularToggle: true,
                  hidePrintButton: true
                }
              });
              var id = setInterval(function () {
                var componentToPrint = document.querySelector(".bp3-dialog");
                if (componentToPrint) {
                  clearInterval(id);
                  resolve(componentToPrint);
                }
              }, 1000);
            }));
          case 1:
          case "end":
            return _context7.stop();
        }
      }
    }, _callee7);
  }));
  return _getSaveDialogEl.apply(this, arguments);
}
var generatePngFromPrintDialog = /*#__PURE__*/function () {
  var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(props) {
    var saveDialog, printArea, result;
    return _regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            _context.next = 2;
            return getSaveDialogEl(props);
          case 2:
            saveDialog = _context.sent;
            printArea = saveDialog.querySelector(".bp3-dialog-body");
            _context.next = 6;
            return _domToImage["default"].toBlob(printArea).then(function (blob) {
              return blob;
            })["catch"](function (error) {
              console.error(error);
              return error;
            });
          case 6:
            result = _context.sent;
            (0, _GlobalDialogUtils.hideDialog)();
            return _context.abrupt("return", result);
          case 9:
          case "end":
            return _context.stop();
        }
      }
    }, _callee);
  }));
  return function generatePngFromPrintDialog(_x) {
    return _ref.apply(this, arguments);
  };
}();
var handleSave = function handleSave(props) {
  return /*#__PURE__*/function () {
    var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(opts) {
      var onSave, onSaveAs, generatePng, readOnly, alwaysAllowSave, sequenceData, lastSavedIdUpdate, saveHandler, updateLastSavedIdToCurrent, promiseOrVal;
      return _regeneratorRuntime().wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              if (opts === void 0) {
                opts = {};
              }
              onSave = props.onSave, onSaveAs = props.onSaveAs, generatePng = props.generatePng, readOnly = props.readOnly, alwaysAllowSave = props.alwaysAllowSave, sequenceData = props.sequenceData, lastSavedIdUpdate = props.lastSavedIdUpdate;
              saveHandler = opts.isSaveAs ? onSaveAs || onSave : onSave;
              updateLastSavedIdToCurrent = function updateLastSavedIdToCurrent() {
                lastSavedIdUpdate(sequenceData.stateTrackingId);
              }; // Optionally generate png
              if (!generatePng) {
                _context2.next = 8;
                break;
              }
              _context2.next = 7;
              return generatePngFromPrintDialog(props);
            case 7:
              opts.pngFile = _context2.sent;
            case 8:
              // TODO: pass additionalProps (blob or error) to the user
              promiseOrVal = (!readOnly || alwaysAllowSave || opts.isSaveAs) && saveHandler && saveHandler(opts, (0, _sequenceUtils.tidyUpSequenceData)(sequenceData, {
                annotationsAsObjects: true
              }), props, updateLastSavedIdToCurrent);
              if (!(promiseOrVal && promiseOrVal.then)) {
                _context2.next = 11;
                break;
              }
              return _context2.abrupt("return", promiseOrVal.then(updateLastSavedIdToCurrent));
            case 11:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2);
    }));
    return function (_x2) {
      return _ref2.apply(this, arguments);
    };
  }();
};
exports.handleSave = handleSave;
var handleInverse = function handleInverse(props) {
  return function () {
    var sequenceLength = props.sequenceLength,
      selectionLayer = props.selectionLayer,
      caretPosition = props.caretPosition,
      selectionLayerUpdate = props.selectionLayerUpdate,
      caretPositionUpdate = props.caretPositionUpdate;
    if (sequenceLength <= 0) {
      return false;
    }
    if (selectionLayer.start > -1) {
      if ((0, _rangeUtils.getRangeLength)(selectionLayer, sequenceLength) === sequenceLength) {
        caretPositionUpdate(selectionLayer.start);
      } else {
        selectionLayerUpdate((0, _rangeUtils.invertRange)(selectionLayer, sequenceLength));
      }
    } else {
      if (caretPosition > -1) {
        selectionLayerUpdate((0, _rangeUtils.normalizeRange)({
          start: caretPosition,
          end: caretPosition - 1
        }, sequenceLength));
      } else {
        selectionLayerUpdate({
          start: 0,
          end: sequenceLength - 1
        });
      }
    }
  };
};
exports.handleInverse = handleInverse;
var updateCircular = function updateCircular(props) {
  return /*#__PURE__*/function () {
    var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(isCircular) {
      var _updateCircular, updateSequenceData, sequenceData, doAction;
      return _regeneratorRuntime().wrap(function _callee3$(_context3) {
        while (1) {
          switch (_context3.prev = _context3.next) {
            case 0:
              _updateCircular = props._updateCircular, updateSequenceData = props.updateSequenceData, sequenceData = props.sequenceData;
              if (!(!isCircular && hasAnnotationThatSpansOrigin(sequenceData))) {
                _context3.next = 8;
                break;
              }
              _context3.next = 4;
              return (0, _teselagenReactComponents.showConfirmationDialog)({
                intent: _core.Intent.DANGER,
                //applied to the right most confirm button
                confirmButtonText: "Truncate Annotations",
                canEscapeKeyCancel: true,
                //this is false by default
                text: "Careful! Origin spanning annotations will be truncated. Are you sure you want to make the sequence linear?"
              });
            case 4:
              doAction = _context3.sent;
              if (doAction) {
                _context3.next = 7;
                break;
              }
              return _context3.abrupt("return");
            case 7:
              //stop early
              updateSequenceData(truncateOriginSpanningAnnotations(sequenceData), {
                batchUndoStart: true
              });
            case 8:
              _updateCircular(isCircular, {
                batchUndoEnd: true
              });
            case 9:
            case "end":
              return _context3.stop();
          }
        }
      }, _callee3);
    }));
    return function (_x3) {
      return _ref3.apply(this, arguments);
    };
  }();
};
exports.updateCircular = updateCircular;
var importSequenceFromFile = function importSequenceFromFile(props) {
  return /*#__PURE__*/function () {
    var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(file, opts) {
      var onImport, result, failed, messages, finishDisplayingSeq, _finishDisplayingSeq;
      return _regeneratorRuntime().wrap(function _callee5$(_context5) {
        while (1) {
          switch (_context5.prev = _context5.next) {
            case 0:
              _finishDisplayingSeq = function _finishDisplayingSeq3() {
                _finishDisplayingSeq = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(seqData) {
                  return _regeneratorRuntime().wrap(function _callee4$(_context4) {
                    while (1) {
                      switch (_context4.prev = _context4.next) {
                        case 0:
                          if (!onImport) {
                            _context4.next = 4;
                            break;
                          }
                          _context4.next = 3;
                          return onImport(seqData);
                        case 3:
                          seqData = _context4.sent;
                        case 4:
                          if (seqData) {
                            seqData.stateTrackingId = (0, _shortid["default"])();
                            (0, _updateEditor["default"])({
                              getState: function getState() {
                                var _VectorEditor;
                                return {
                                  VectorEditor: (_VectorEditor = {}, _VectorEditor[props.editorName] = props, _VectorEditor)
                                };
                              },
                              dispatch: props.dispatch
                            }, props.editorName, {
                              sequenceData: seqData
                            });
                            props.flipActiveTabFromLinearOrCircularIfNecessary(seqData.circular);
                            window.toastr.success("Sequence Imported");
                          }
                        case 5:
                        case "end":
                          return _context4.stop();
                      }
                    }
                  }, _callee4);
                }));
                return _finishDisplayingSeq.apply(this, arguments);
              };
              finishDisplayingSeq = function _finishDisplayingSeq2(_x6) {
                return _finishDisplayingSeq.apply(this, arguments);
              };
              if (opts === void 0) {
                opts = {};
              }
              onImport = props.onImport;
              _context5.next = 6;
              return (0, _bioParsers.anyToJson)(file, _extends({
                acceptParts: true
              }, opts));
            case 6:
              result = _context5.sent;
              // TODO maybe handle import errors/warnings better
              failed = !result[0].success;
              messages = result[0].messages;
              if ((0, _lodash.isArray)(messages)) {
                messages.forEach(function (msg) {
                  var type = msg.substr(0, 20).toLowerCase().includes("error") ? failed ? "error" : "warning" : "info";
                  window.toastr[type](msg);
                });
              }
              if (failed) {
                window.toastr.error("Error importing sequence(s). See console for more errors");
                console.error("Seq import results:", result);
              } else if (result.length > 1) {
                (0, _GlobalDialogUtils.showDialog)({
                  dialogType: "MultipleSeqsDetectedOnImportDialog",
                  props: {
                    finishDisplayingSeq: finishDisplayingSeq,
                    results: result
                  }
                });
              } else {
                finishDisplayingSeq(result[0].parsedSequence);
              }
            case 11:
            case "end":
              return _context5.stop();
          }
        }
      }, _callee5);
    }));
    return function (_x4, _x5) {
      return _ref4.apply(this, arguments);
    };
  }();
};
exports.importSequenceFromFile = importSequenceFromFile;
var exportSequenceToFile = function exportSequenceToFile(props) {
  return function (format) {
    var sequenceData = props.sequenceData;
    var convert, fileExt;
    if (format === "genbank") {
      convert = _bioParsers.jsonToGenbank;
      fileExt = "gb";
    } else if (format === "genpept") {
      convert = _bioParsers.jsonToGenbank;
      fileExt = "gp";
    } else if (format === "teselagenJson") {
      convert = jsonToJson;
      fileExt = "json";
    } else if (format === "fasta") {
      convert = _bioParsers.jsonToFasta;
      fileExt = "fasta";
    } else {
      console.error("Invalid export format: '" + format + "'"); // dev error
      return;
    }
    var blob = new Blob([convert(sequenceData)], {
      type: "text/plain"
    });
    var filename = (sequenceData.name || "Untitled_Sequence") + "." + fileExt;
    _fileSaver["default"].saveAs(blob, filename);
    window.toastr.success("File Downloaded Successfully");
  };
};

/**
 * This function basically connects the wrapped component with all of the state stored in a given editor instance
 * and then some extra goodies like computed properties and namespace bound action handlers
 */
exports.exportSequenceToFile = exportSequenceToFile;
var _default = (0, _recompose.compose)((0, _reactRedux.connect)(mapStateToProps, mapDispatchToActions, function (mapProps, dispatchProps, ownProps) {
  var toSpread = {};
  if (mapProps.annotationToAdd) {
    toSpread.original_selectionLayerUpdate = dispatchProps.selectionLayerUpdate;
    toSpread.selectionLayerUpdate = function (sel) {
      dispatchProps.dispatch({
        type: "@@redux-form/CHANGE",
        meta: {
          form: mapProps.annotationToAdd.formName,
          field: "start",
          touch: false,
          persistentSubmitErrors: false
        },
        payload: sel.start + 1
      });
      dispatchProps.dispatch({
        type: "@@redux-form/CHANGE",
        meta: {
          form: mapProps.annotationToAdd.formName,
          field: "end",
          touch: false,
          persistentSubmitErrors: false
        },
        payload: sel.end + 1
      });
    };
    toSpread.caretPositionUpdate = function () {};
  }
  return _extends({}, ownProps, mapProps, dispatchProps, toSpread);
}), (0, _recompose.withHandlers)({
  wrappedInsertSequenceDataAtPositionOrRange: function wrappedInsertSequenceDataAtPositionOrRange(props) {
    return function (_sequenceDataToInsert, _existingSequenceData, _caretPositionOrRange, _options) {
      var _ref5 = props.beforeSequenceInsertOrDelete ? props.beforeSequenceInsertOrDelete((0, _sequenceUtils.tidyUpSequenceData)(_sequenceDataToInsert), (0, _sequenceUtils.tidyUpSequenceData)(_existingSequenceData), _caretPositionOrRange, _options) || {} : {},
        sequenceDataToInsert = _ref5.sequenceDataToInsert,
        existingSequenceData = _ref5.existingSequenceData,
        caretPositionOrRange = _ref5.caretPositionOrRange,
        options = _ref5.options;
      return [(0, _sequenceUtils.insertSequenceDataAtPositionOrRange)(sequenceDataToInsert || _sequenceDataToInsert, existingSequenceData || _existingSequenceData, caretPositionOrRange || _caretPositionOrRange, options || _options), options || _options || {}];
    };
  },
  upsertTranslation: function upsertTranslation(props) {
    return /*#__PURE__*/function () {
      var _ref6 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(translationToUpsert) {
        var _upsertTranslation, sequenceData, doAction;
        return _regeneratorRuntime().wrap(function _callee6$(_context6) {
          while (1) {
            switch (_context6.prev = _context6.next) {
              case 0:
                if (translationToUpsert) {
                  _context6.next = 2;
                  break;
                }
                return _context6.abrupt("return");
              case 2:
                _upsertTranslation = props._upsertTranslation, sequenceData = props.sequenceData;
                if (!(!translationToUpsert.id && (0, _lodash.some)(sequenceData.translations || [], function (existingTranslation) {
                  if (
                  //check if an identical existingTranslation exists already
                  existingTranslation.translationType === "User Created" && existingTranslation.start === translationToUpsert.start && existingTranslation.end === translationToUpsert.end && !!translationToUpsert.forward === !!existingTranslation.forward) {
                    return true;
                  }
                }))) {
                  _context6.next = 9;
                  break;
                }
                _context6.next = 6;
                return (0, _teselagenReactComponents.showConfirmationDialog)({
                  // intent: Intent.DANGER, //applied to the right most confirm button
                  confirmButtonText: "Create Translation",
                  canEscapeKeyCancel: true,
                  //this is false by default
                  text: "This region has already been translated. Are you sure you want to make another translation for it?"
                });
              case 6:
                doAction = _context6.sent;
                if (doAction) {
                  _context6.next = 9;
                  break;
                }
                return _context6.abrupt("return");
              case 9:
                _upsertTranslation(translationToUpsert);
              case 10:
              case "end":
                return _context6.stop();
            }
          }
        }, _callee6);
      }));
      return function (_x7) {
        return _ref6.apply(this, arguments);
      };
    }();
  }
}), (0, _recompose.withHandlers)(_extends({
  handleSave: handleSave,
  importSequenceFromFile: importSequenceFromFile,
  exportSequenceToFile: exportSequenceToFile,
  updateCircular: updateCircular,
  //add additional "computed handlers here"
  selectAll: function selectAll(props) {
    return function () {
      var sequenceLength = props.sequenceLength,
        selectionLayerUpdate = props.selectionLayerUpdate;
      sequenceLength > 0 && selectionLayerUpdate({
        start: 0,
        end: sequenceLength - 1
      });
    };
  }
}, ["Part", "Feature", "Primer"].reduce(function (acc, key) {
  acc["handleNew" + key] = function (props) {
    return function () {
      var readOnly = props.readOnly,
        selectionLayer = props.selectionLayer,
        caretPosition = props.caretPosition,
        sequenceData = props.sequenceData;
      if (readOnly) {
        window.toastr.warning("Sorry, Can't Create New " + key + "s in Read-Only Mode");
      } else {
        var rangeToUse = selectionLayer.start > -1 ? _extends({}, selectionLayer, {
          id: undefined
        }) : caretPosition > -1 ? {
          start: caretPosition,
          end: sequenceData.isProtein ? caretPosition + 2 : caretPosition
        } : {
          start: 0,
          end: sequenceData.isProtein ? 2 : 0
        };
        (0, _GlobalDialogUtils.showAddOrEditAnnotationDialog)({
          type: key.toLowerCase(),
          annotation: _extends({}, rangeToUse, {
            forward: !(selectionLayer.forward === false)
          })
        });
      }
    };
  };
  return acc;
}, {}), {
  handleRotateToCaretPosition: function handleRotateToCaretPosition(props) {
    return function () {
      var caretPosition = props.caretPosition,
        readOnly = props.readOnly,
        sequenceData = props.sequenceData,
        updateSequenceData = props.updateSequenceData,
        caretPositionUpdate = props.caretPositionUpdate;
      if (readOnly) {
        return;
      }
      if (caretPosition < 0) return;
      updateSequenceData((0, _sequenceUtils.rotateSequenceDataToPosition)(sequenceData, caretPosition));
      caretPositionUpdate(0);
    };
  },
  handleReverseComplementSelection: function handleReverseComplementSelection(props) {
    return function () {
      var sequenceData = props.sequenceData,
        updateSequenceData = props.updateSequenceData,
        wrappedInsertSequenceDataAtPositionOrRange = props.wrappedInsertSequenceDataAtPositionOrRange,
        selectionLayer = props.selectionLayer;
      if (!(selectionLayer.start > -1)) {
        return; //return early
      }

      var reversedSeqData = (0, _sequenceUtils.getReverseComplementSequenceAndAnnotations)(sequenceData, {
        range: selectionLayer
      });
      var _wrappedInsertSequenc = wrappedInsertSequenceDataAtPositionOrRange(reversedSeqData, sequenceData, selectionLayer, {
          maintainOriginSplit: true
        }),
        newSeqData = _wrappedInsertSequenc[0];
      updateSequenceData(newSeqData);
    };
  },
  handleComplementSelection: function handleComplementSelection(props) {
    return function () {
      var sequenceData = props.sequenceData,
        updateSequenceData = props.updateSequenceData,
        selectionLayer = props.selectionLayer,
        wrappedInsertSequenceDataAtPositionOrRange = props.wrappedInsertSequenceDataAtPositionOrRange;
      if (!(selectionLayer.start > -1)) {
        return; //return early
      }

      var comp = (0, _sequenceUtils.getComplementSequenceAndAnnotations)(sequenceData, {
        range: selectionLayer
      });
      var _wrappedInsertSequenc2 = wrappedInsertSequenceDataAtPositionOrRange(comp, sequenceData, selectionLayer, {
          maintainOriginSplit: true
        }),
        newSeqData = _wrappedInsertSequenc2[0];
      updateSequenceData(newSeqData);
    };
  },
  handleReverseComplementSequence: function handleReverseComplementSequence(props) {
    return function () {
      var sequenceData = props.sequenceData,
        updateSequenceData = props.updateSequenceData;
      updateSequenceData((0, _sequenceUtils.getReverseComplementSequenceAndAnnotations)(sequenceData));
      window.toastr.success("Reverse Complemented Sequence Successfully");
    };
  },
  handleComplementSequence: function handleComplementSequence(props) {
    return function () {
      var sequenceData = props.sequenceData,
        updateSequenceData = props.updateSequenceData;
      updateSequenceData((0, _sequenceUtils.getComplementSequenceAndAnnotations)(sequenceData));
      window.toastr.success("Complemented Sequence Successfully");
    };
  },
  handleInverse: handleInverse
})));
exports["default"] = _default;
var getEditorState = (0, _reselect.createSelector)(function (state) {
  return state.VectorEditor;
}, function (state, editorName) {
  return editorName;
}, function (VectorEditor, editorName) {
  return VectorEditor[editorName];
});
function mapStateToProps(state, ownProps) {
  var editorName = ownProps.editorName,
    sequenceDataFromProps = ownProps.sequenceData,
    allowSeqDataOverride = ownProps.allowSeqDataOverride,
    allowMultipleFeatureDirections = ownProps.allowMultipleFeatureDirections;
  var editorState = getEditorState(state, editorName);
  var meta = {
    editorName: editorName
  };
  var VectorEditor = state.VectorEditor;
  var __allEditorsOptions = VectorEditor.__allEditorsOptions;
  var uppercaseSequenceMapFont = __allEditorsOptions.uppercaseSequenceMapFont;
  if (!editorState) {
    return (0, _redux2.editorReducer)({}, {});
  }
  var findTool = editorState.findTool,
    _editorState$annotati = editorState.annotationsToSupport,
    annotationsToSupport = _editorState$annotati === void 0 ? {} : _editorState$annotati;
  var visibilities = getVisibilities(editorState);
  var annotationToAdd;
  [["AddOrEditFeatureDialog", "filteredFeatures", "features"], ["AddOrEditPrimerDialog", "filteredPrimers", "primers"], ["AddOrEditPartDialog", "filteredParts", "parts"]].forEach(function (_ref7) {
    var n = _ref7[0],
      type = _ref7[1],
      annotationTypePlural = _ref7[2];
    var vals = (0, _reduxForm.getFormValues)(n)(state);
    if (vals) {
      annotationToAdd = getAnnToAdd(vals, n, type, annotationTypePlural);
    }
  });
  var toReturn = _extends({}, editorState, {
    meta: meta,
    annotationToAdd: annotationToAdd
  });
  if (sequenceDataFromProps && allowSeqDataOverride) {
    //return early here because we don't want to override the sequenceData being passed in
    //this is a little hacky but allows us to track selectionLayer/caretIndex using redux but on a sequence that isn't being stored alongside that info
    return toReturn;
  }
  var filteredCutsites = _selectors["default"].filteredCutsitesSelector(editorState, ownProps.additionalEnzymes, ownProps.enzymeGroupsOverride);
  var cutsites = filteredCutsites.cutsitesArray;
  var filteredRestrictionEnzymes = _selectors["default"].filteredRestrictionEnzymesSelector(editorState);
  var isEnzymeFilterAnd = _selectors["default"].isEnzymeFilterAndSelector(editorState);
  // const orfs = s.orfsSelector(editorState);
  var selectedCutsites = _selectors["default"].selectedCutsitesSelector(editorState);
  var allCutsites = _selectors["default"].cutsitesSelector(editorState, ownProps.additionalEnzymes);
  var sequenceLength = _selectors["default"].sequenceLengthSelector(editorState);
  var _getSearchLayersAndMa = getSearchLayersAndMatch(editorState),
    matchedSearchLayer = _getSearchLayersAndMa.matchedSearchLayer,
    searchLayers = _getSearchLayersAndMa.searchLayers,
    matchesTotal = _getSearchLayersAndMa.matchesTotal;
  var annotationSearchMatches = _selectors["default"].annotationSearchSelector(editorState);
  var _sequenceDataToUse = getSequenceDataToUse(editorState, cutsites, __allEditorsOptions);
  var _getSeqDataWithAnnToA = getSeqDataWithAnnToAdd(_sequenceDataToUse, annotationToAdd, allowMultipleFeatureDirections),
    sequenceDataToUse = _getSeqDataWithAnnToA[0],
    newSelection = _getSeqDataWithAnnToA[1];
  var f = getFindTool(findTool, matchesTotal);
  return _extends({}, editorState, {
    meta: meta,
    annotationToAdd: annotationToAdd
  }, newSelection && {
    selectionLayer: newSelection
  }, {
    selectedCutsites: selectedCutsites,
    sequenceLength: sequenceLength,
    allCutsites: allCutsites,
    filteredCutsites: filteredCutsites,
    filteredRestrictionEnzymes: filteredRestrictionEnzymes,
    isEnzymeFilterAnd: isEnzymeFilterAnd,
    annotationSearchMatches: annotationSearchMatches,
    searchLayers: searchLayers,
    matchedSearchLayer: matchedSearchLayer,
    findTool: f,
    annotationsToSupport: annotationsToSupport,
    annotationVisibility: visibilities.annotationVisibilityToUse,
    typesToOmit: visibilities.typesToOmit,
    annotationLabelVisibility: visibilities.annotationLabelVisibilityToUse,
    sequenceData: sequenceDataToUse,
    uppercaseSequenceMapFont: uppercaseSequenceMapFont,
    showGCContent: getShowGCContent(state, ownProps)
  });
}
function mapDispatchToActions(dispatch, ownProps) {
  var editorName = ownProps.editorName;
  var _ownProps$actionOverr = ownProps.actionOverrides,
    actionOverrides = _ownProps$actionOverr === void 0 ? fakeActionOverrides : _ownProps$actionOverr;
  var actionsToPass = getCombinedActions(editorName, _redux2.actions, actionOverrides, dispatch);
  var updateSel = ownProps.selectionLayerUpdate || actionsToPass.selectionLayerUpdate;
  var updateCar = ownProps.caretPositionUpdate || actionsToPass.caretPositionUpdate;
  return _extends({}, actionsToPass, {
    selectionLayerUpdate: ownProps.onSelectionOrCaretChanged ? function (selectionLayer) {
      ownProps.onSelectionOrCaretChanged({
        selectionLayer: selectionLayer,
        caretPosition: -1
      });
      updateSel(selectionLayer);
    } : updateSel,
    caretPositionUpdate: ownProps.onSelectionOrCaretChanged ? function (caretPosition) {
      ownProps.onSelectionOrCaretChanged({
        caretPosition: caretPosition,
        selectionLayer: {
          start: -1,
          end: -1
        }
      });
      updateCar(caretPosition);
    } : updateCar,
    dispatch: dispatch
  });
}
var defaultOverrides = {};
function fakeActionOverrides() {
  return defaultOverrides;
}
function getCombinedActions(editorName, actions, actionOverrides, dispatch) {
  var meta = {
    editorName: editorName
  };
  var metaActions = (0, _addMetaToActionCreators["default"])(actions, meta);
  // let overrides = addMetaToActionCreators(actionOverrides(metaActions), meta);
  var overrides = {};
  metaActions = _extends({
    undo: function undo() {
      window.toastr.success("Undo Successful");
      return {
        type: "VE_UNDO",
        meta: {
          editorName: editorName
        }
      };
    },
    redo: function redo() {
      window.toastr.success("Redo Successful");
      return {
        type: "VE_REDO",
        meta: {
          editorName: editorName
        }
      };
    }
  }, metaActions, overrides);
  //add meta to all action creators before passing them to the override function
  // var metaActions = addMetaToActionCreators(actions, meta)
  // let metaOverrides = addMetaToActionCreators(
  //   actionOverrides(metaActions),
  //   meta
  // );

  //rebind the actions with dispatch and meta
  var actionsToPass = _extends({}, metaActions);
  return (0, _redux.bindActionCreators)(actionsToPass, dispatch);
}
function truncateOriginSpanningAnnotations(seqData) {
  var _seqData$features = seqData.features,
    features = _seqData$features === void 0 ? [] : _seqData$features,
    _seqData$parts = seqData.parts,
    parts = _seqData$parts === void 0 ? [] : _seqData$parts,
    _seqData$translations = seqData.translations,
    translations = _seqData$translations === void 0 ? [] : _seqData$translations,
    _seqData$primers = seqData.primers,
    primers = _seqData$primers === void 0 ? [] : _seqData$primers,
    sequence = seqData.sequence;
  return _extends({}, seqData, {
    features: truncateOriginSpanners(features, sequence.length),
    parts: truncateOriginSpanners(parts, sequence.length),
    translations: truncateOriginSpanners(translations, sequence.length),
    primers: truncateOriginSpanners(primers, sequence.length)
  });
}
function truncateOriginSpanners(annotations, sequenceLength) {
  return (0, _lodash.map)(annotations, function (annotation) {
    var _annotation$start = annotation.start,
      start = _annotation$start === void 0 ? 0 : _annotation$start,
      _annotation$end = annotation.end,
      end = _annotation$end === void 0 ? 0 : _annotation$end;
    if (start > end) {
      return _extends({}, annotation, {
        end: sequenceLength - 1
      });
    } else {
      return annotation;
    }
  });
}
function hasAnnotationThatSpansOrigin(_ref8) {
  var _ref8$features = _ref8.features,
    features = _ref8$features === void 0 ? [] : _ref8$features,
    _ref8$parts = _ref8.parts,
    parts = _ref8$parts === void 0 ? [] : _ref8$parts,
    _ref8$translations = _ref8.translations,
    translations = _ref8$translations === void 0 ? [] : _ref8$translations,
    _ref8$primers = _ref8.primers,
    primers = _ref8$primers === void 0 ? [] : _ref8$primers;
  return doAnySpanOrigin(features) || doAnySpanOrigin(parts) || doAnySpanOrigin(translations) || doAnySpanOrigin(primers);
}
function doAnySpanOrigin(annotations) {
  return (0, _lodash.some)(annotations, function (_ref9) {
    var _ref9$start = _ref9.start,
      start = _ref9$start === void 0 ? 0 : _ref9$start,
      _ref9$end = _ref9.end,
      end = _ref9$end === void 0 ? 0 : _ref9$end;
    if (start > end) return true;
  });
}
var connectToEditor = function connectToEditor(fn) {
  return (0, _reactRedux.connect)(function (state, ownProps) {
    var editor = state.VectorEditor[ownProps.editorName] || {};
    editor.sequenceData = editor.sequenceData || {};
    editor.sequenceData.sequence = getUpperOrLowerSeq(state.VectorEditor.__allEditorsOptions.uppercaseSequenceMapFont, editor.sequenceData.sequence);
    for (var _len = arguments.length, rest = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
      rest[_key - 2] = arguments[_key];
    }
    return fn ? fn.apply(void 0, [editor, ownProps].concat(rest, [state])) : {};
  }, mapDispatchToActions
  // function mergeProps(propsFromState, propsFromDispatch) {
  //   return {
  //     ...propsFromState,
  //     ...propsFromDispatch
  //   };
  // }
  );
};

//this is to enhance non-redux connected views like LinearView, or CircularView or RowView
//so they can still render things like translations, ..etc

//Currently only supporting translations
exports.connectToEditor = connectToEditor;
var withEditorPropsNoRedux = (0, _recompose.withProps)(function (props) {
  var sequenceData = props.sequenceData,
    sequenceDataWithRefSeqCdsFeatures = props.sequenceDataWithRefSeqCdsFeatures,
    annotationVisibility = props.annotationVisibility,
    annotationVisibilityOverrides = props.annotationVisibilityOverrides;
  var translations = _selectors["default"].translationsSelector({
    sequenceData: sequenceDataWithRefSeqCdsFeatures || sequenceData,
    annotationVisibility: _extends({}, annotationVisibility, annotationVisibilityOverrides)
  });
  var toReturn = {
    sequenceData: _extends({}, sequenceData, {
      translations: translations
    })
  };
  return toReturn;
});
exports.withEditorPropsNoRedux = withEditorPropsNoRedux;
function getShowGCContent(state, ownProps) {
  var showGCContent = state.VectorEditor.__allEditorsOptions.showGCContent;
  var toRet = showGCContent === null ? ownProps.showGCContentByDefault //user hasn't yet set this option
  : showGCContent;
  return toRet;
}
function jsonToJson(incomingJson) {
  return JSON.stringify((0, _lodash.omit)((0, _bioParsers.cleanUpTeselagenJsonForExport)((0, _sequenceUtils.tidyUpSequenceData)(incomingJson, {
    annotationsAsObjects: false
  })), ["sequenceFragments", "sequenceFeatures", "cutsites", "orfs", "filteredParts", "filteredFeatures", "filteredPrimers"]));
}
var getSearchLayersAndMatch = (0, _reselect.createSelector)(function (ed) {
  return ed.findTool;
}, _selectors["default"].searchLayersSelector, function (findTool, _searchLayers) {
  var searchLayers;
  var matchedSearchLayer = {
    start: -1,
    end: -1
  };
  searchLayers = _searchLayers.map(function (item, index) {
    var itemToReturn = item;
    if (index === findTool.matchNumber) {
      itemToReturn = _extends({}, item, {
        className: item.className + " veSearchLayerActive"
      });
      matchedSearchLayer = itemToReturn;
    }
    return itemToReturn;
  });
  var matchesTotal = searchLayers.length;
  if (!findTool.highlightAll && searchLayers[findTool.matchNumber] || searchLayers.length > _findToolConstants.MAX_MATCHES_DISPLAYED) {
    searchLayers = [searchLayers[findTool.matchNumber]];
  }
  return {
    matchesTotal: matchesTotal,
    searchLayers: searchLayers,
    matchedSearchLayer: matchedSearchLayer
  };
});
var getSequenceDataToUse = (0, _reselect.createSelector)(function (a, b, __allEditorsOptions) {
  return __allEditorsOptions.uppercaseSequenceMapFont;
}, function (ed) {
  return ed.sequenceData;
}, function (ed, cutsites) {
  return cutsites;
}, _selectors["default"].translationsSelector, _selectors["default"].filteredFeaturesSelector, _selectors["default"].filteredPrimersSelector, _selectors["default"].filteredPartsSelector, _selectors["default"].orfsSelector, function (uppercaseSequenceMapFont, sequenceData, cutsites, translations, filteredFeatures, filteredPrimers, filteredParts, orfs) {
  return _extends({}, sequenceData, {
    sequence: getUpperOrLowerSeq(uppercaseSequenceMapFont, sequenceData.sequence),
    filteredParts: filteredParts,
    filteredFeatures: filteredFeatures,
    filteredPrimers: filteredPrimers,
    cutsites: cutsites,
    orfs: orfs,
    translations: translations
  });
});
var getFindTool = (0, _reselect.createSelector)(function (f) {
  return f;
}, function (f, m) {
  return m;
}, function (findTool, matchesTotal) {
  return _extends({}, findTool, {
    matchesTotal: matchesTotal
  });
});
var getAnnToAdd = (0, _reselect.defaultMemoize)(function (vals, n, type, annotationTypePlural) {
  var annToAdd = _extends({
    color: (0, _sequenceUtils.getFeatureToColorMap)({
      includeHidden: true
    })[vals.type || "primer_bind"]
  }, vals, {
    formName: n,
    type: type,
    annotationTypePlural: annotationTypePlural,
    name: vals.name || "Untitled"
  });
  if (!vals.useLinkedOligo) {
    delete annToAdd.bases;
  }
  return annToAdd;
});
var getSeqDataWithAnnToAdd = (0, _reselect.defaultMemoize)(function (seqData, ann, allowMultipleFeatureDirections) {
  if (ann) {
    var _extends2;
    var selectionLayer = (0, _rangeUtils.convertRangeTo0Based)(ann);
    delete selectionLayer.color;
    var id = ann.id || "tempId123";
    var name = ann.name || "";
    var anns = (0, _lodash.keyBy)(seqData[ann.type], "id");
    var toSpread = {};
    if (ann.annotationTypePlural === "features" && allowMultipleFeatureDirections && ann.arrowheadType !== undefined) {
      toSpread = {
        forward: ann.arrowheadType !== "BOTTOM",
        arrowheadType: ann.arrowheadType
      };
    }
    anns[id] = _extends({}, ann, {
      id: id,
      name: name
    }, selectionLayer, ann.bases && {
      // ...getStartEndFromBases({ ...ann, sequenceLength }),
      fullSeq: seqData.sequence
    }, toSpread, {
      locations: ann.locations ? ann.locations.map(_rangeUtils.convertRangeTo0Based) : undefined
    });
    return [_extends({}, seqData, (_extends2 = {}, _extends2[ann.type] = anns, _extends2)), selectionLayer];
  }
  return [seqData];
});