"use strict";

exports.__esModule = true;
exports["default"] = exports.commandDefs = void 0;
var _react = _interopRequireDefault(require("react"));
var _core = require("@blueprintjs/core");
var _rangeUtils = require("@teselagen/range-utils");
var _classnames = _interopRequireDefault(require("classnames"));
var _pluralize = _interopRequireDefault(require("pluralize"));
var _teselagenReactComponents = require("teselagen-react-components");
var _sequenceUtils = require("@teselagen/sequence-utils");
var _commandUtils = require("../utils/commandUtils");
var _lodash = require("lodash");
var _showFileDialog = _interopRequireDefault(require("../utils/showFileDialog"));
var _copyOptions = require("../redux/copyOptions");
var _proteinUtils = require("../utils/proteinUtils");
var _package = _interopRequireDefault(require("../../package.json"));
var _partTagSearch = require("../helperComponents/partTagSearch");
var _GlobalDialogUtils = require("../GlobalDialogUtils");
var _viewSubmenu = require("../MenuBar/viewSubmenu");
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); }
var isProtein = function isProtein(props) {
  return props.sequenceData && props.sequenceData.isProtein;
};
var isOligo = function isOligo(props) {
  return props.sequenceData && props.sequenceData.isOligo;
};
var isRna = function isRna(props) {
  return props.sequenceData && props.sequenceData.isRna;
};
var partsPrimersFeatures = ["Parts", "Features", "Primers"];
var getNewTranslationHandler = function getNewTranslationHandler(isReverse) {
  return {
    handler: function handler(props, state, ctxInfo) {
      var annotation = (0, _lodash.get)(ctxInfo, "context.annotation") || props.selectionLayer;
      if (!(annotation.start > -1)) {
        return window.toastr.warning("No region found to translate");
      }
      props.upsertTranslation({
        start: annotation.start,
        end: annotation.end,
        forward: !isReverse
      });
      props.annotationVisibilityShow("translations");
    },
    isHidden: function isHidden(props) {
      return isProtein(props) || !props.annotationsToSupport ||
      // props.readOnly ||
      !props.annotationsToSupport.translations;
    },
    isDisabled: function isDisabled(props) {
      return (/* (props.readOnly && readOnlyDisabledTooltip) ||  */props.sequenceLength === 0 || noSelection(props)
      );
    }
  };
};
var fileCommandDefs = _extends({
  newSequence: {
    isHidden: function isHidden(props) {
      return !props.onNew;
    },
    handler: function handler(props) {
      for (var _len = arguments.length, rest = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
        rest[_key - 1] = arguments[_key];
      }
      return props.onNew.apply(props, [props].concat(rest));
    }
  },
  renameSequence: {
    isHidden: function isHidden(props) {
      return props.readOnly;
    },
    isDisabled: function isDisabled(props) {
      return props.readOnly && readOnlyDisabledTooltip;
    },
    handler: function handler(props) {
      (0, _GlobalDialogUtils.showDialog)({
        dialogType: "RenameSequenceDialog",
        props: {
          initialValues: {
            newName: props.sequenceData.name
          },
          onSubmit: function onSubmit(values) {
            props.sequenceNameUpdate(values.newName);
            props.onRename && props.onRename(values.newName, props);
          }
        }
      });
    }
  },
  saveSequence: {
    name: "保存",
    isDisabled: function isDisabled(props) {
      return props.alwaysAllowSave ? false : props.readOnly && readOnlyDisabledTooltip || !props.sequenceData || props.sequenceData.stateTrackingId === "initialLoadId" || props.sequenceData.stateTrackingId === props.lastSavedId;
    },
    isHidden: function isHidden(props) {
      return props.readOnly || !props.handleSave;
    },
    handler: function handler(props) {
      return props.handleSave();
    },
    hotkey: "mod+s"
  },
  saveSequenceAs: {
    name: "另存为",
    // isDisabled: props =>
    //   (props.readOnly && readOnlyDisabledTooltip) ||
    //   !props.sequenceData ||
    //   (props.sequenceData.stateTrackingId === "initialLoadId" ||
    //     props.sequenceData.stateTrackingId === props.lastSavedId),
    isHidden: function isHidden(props) {
      return !props.onSaveAs;
    },
    handler: function handler(props) {
      return props.handleSave({
        isSaveAs: true
      });
    },
    hotkey: "mod+shift+s"
  },
  toolsCmd: {
    handler: function handler() {},
    isHidden: isProtein
  },
  deleteSequence: {
    isDisabled: function isDisabled(props) {
      return props.readOnly && readOnlyDisabledTooltip || !props.onDelete;
    },
    isHidden: function isHidden(props) {
      return !props.onDelete;
    },
    handler: function handler(props) {
      return props.onDelete(props.sequenceData);
    }
  },
  duplicateSequence: {
    name: "重复序列",
    isDisabled: function isDisabled(props) {
      return !props.onDuplicate;
    },
    isHidden: function isHidden(props) {
      return !props.onDuplicate;
    },
    handler: function handler(props) {
      for (var _len2 = arguments.length, rest = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
        rest[_key2 - 1] = arguments[_key2];
      }
      return props.onDuplicate.apply(props, [props.sequenceData, props].concat(rest));
    },
    hotkey: "alt+shift+d"
  },
  toggleReadOnlyMode: {
    toggle: [],
    isDisabled: function isDisabled(props) {
      return props.disableSetReadOnly || !props.onSave;
    },
    isHidden: function isHidden(props) {
      return !props.toggleReadOnlyMode;
    },
    isActive: function isActive(props) {
      return props.readOnly;
    },
    handler: function handler(props) {
      return props.toggleReadOnlyMode();
    }
  },
  importSequence: {
    isHidden: function isHidden(props) {
      return props.hideSingleImport;
    },
    isDisabled: function isDisabled(props) {
      return props.readOnly;
    },
    handler: function handler(props) {
      (0, _showFileDialog["default"])({
        multiple: false,
        onSelect: function onSelect(files) {
          props.importSequenceFromFile(files[0]);
        }
      });
    }
  },
  filterPartsByTagCmd: {
    isHidden: function isHidden(props) {
      return !props.allPartTags;
    },
    name: "Search Parts By Tag",
    component: function component(props) {
      return function () {
        return (
          /*#__PURE__*/
          // eslint-disable-next-line jsx-a11y/anchor-is-valid
          _react["default"].createElement("div", {
            className: "bp3-menu-item",
            style: {
              padding: 3,
              paddingLeft: 30
            },
            "data-test": "filter-parts-by-tag"
          }, /*#__PURE__*/_react["default"].createElement(_partTagSearch.PartTagSearch, _extends({
            dontAutoOpen: true
          }, props)))
        );
      };
    },
    handler: function handler() {}
  },
  filterFeatureLengthsCmd: getFilterByLengthCmd("feature"),
  filterPartLengthsCmd: getFilterByLengthCmd("part"),
  filterPrimerLengthsCmd: getFilterByLengthCmd("primer"),
  featureTypesCmd: {
    name: function name(props) {
      var total = Object.keys((0, _lodash.reduce)(props.sequenceData.features, function (acc, feat) {
        acc[feat.type] = true;
        return acc;
      }, {})).length;
      var toHideCount = Object.keys(props.annotationVisibility.featureTypesToHide).length;
      return /*#__PURE__*/_react["default"].createElement("span", null, "Filter By Type \xA0", /*#__PURE__*/_react["default"].createElement(_core.Tag, {
        className: "tg-smallTag",
        round: true,
        style: {
          marginLeft: 4
        }
      }, total - toHideCount, "/", total));
    },
    submenu: function submenu(props) {
      var types = {};
      (0, _lodash.forEach)(props.sequenceData.features, function (feat) {
        if (!feat.type) return;
        var checked = !props.annotationVisibility.featureTypesToHide[feat.type];
        if (types[feat.type]) {
          types[feat.type].count++;
        } else {
          types[feat.type] = {
            count: 1,
            shouldDismissPopover: false,
            onClick: function onClick() {
              return checked ? props.hideFeatureTypes([feat.type]) : props.showFeatureTypes([feat.type]);
            },
            checked: checked
          };
        }
        types[feat.type].text = /*#__PURE__*/_react["default"].createElement("span", null, feat.type, " \xA0", /*#__PURE__*/_react["default"].createElement(_core.Tag, {
          className: "tg-smallTag",
          round: true,
          style: {
            marginLeft: 4
          }
        }, types[feat.type].count));
      });
      var typeMenu = (0, _lodash.map)(types);
      return [{
        text: "取消全选",
        onClick: function onClick() {
          return props.hideFeatureTypes(Object.keys(types));
        },
        shouldDismissPopover: false
      }, {
        text: "全选",
        onClick: function onClick() {
          return props.resetFeatureTypesToHide();
        },
        shouldDismissPopover: false
      }, "--"].concat(typeMenu.length ? typeMenu : [{
        text: "No Features To Filter",
        disabled: true
      }]);
    }
    // isDisabled:
  },

  featureFilterIndividualCmd: getFilterIndividualCmd("feature"),
  partFilterIndividualCmd: getFilterIndividualCmd("part"),
  primerFilterIndividualCmd: getFilterIndividualCmd("primer"),
  exportSequenceAsGenbank: {
    name: function name(props) {
      return isProtein(props) ? "Download GenPept File" : "下载 Genbank 文件";
    },
    handler: function handler(props) {
      return props.exportSequenceToFile(isProtein(props) ? "genpept" : "genbank");
    }
  },
  exportSequenceAsFasta: {
    name: "下载 FASTA 文件",
    handler: function handler(props) {
      return props.exportSequenceToFile("fasta");
    }
  },
  exportSequenceAsTeselagenJson: {
    name: "下载 Teselagen JSON 文件",
    handler: function handler(props) {
      return props.exportSequenceToFile("teselagenJson");
    }
  },
  viewProperties: {
    handler: function handler(props) {
      return props.propertiesViewOpen();
    }
  },
  viewRevisionHistory: {
    handler: function handler(props) {
      return props.toggleViewVersionHistory();
    },
    isHidden: function isHidden(props) {
      return !props.getVersionList || !props.getSequenceAtVersion;
    }
  },
  print: {
    name: "打印",
    hotkeyProps: {
      preventDefault: true
    },
    handler: function handler(props) {
      return (0, _GlobalDialogUtils.showDialog)({
        dialogType: "PrintDialog",
        props: props
      });
    },
    hotkey: "mod+p"
  }
}, partsPrimersFeatures.reduce(function (acc, type) {
  //showRemoveDuplicatesDialogFeatures showRemoveDuplicatesDialogParts showRemoveDuplicatesDialogPrimers
  acc["showRemoveDuplicatesDialog" + type] = {
    name: "\u5220\u9664\u91CD\u590D\u7684 " + (0, _lodash.startCase)(type),
    isDisabled: function isDisabled(props) {
      return props.readOnly;
    },
    handler: function handler(props) {
      return (0, _GlobalDialogUtils.showDialog)({
        dialogType: "RemoveDuplicates",
        props: {
          type: (0, _lodash.camelCase)(type),
          editorName: props.editorName,
          dialogProps: {
            title: "\u5220\u9664\u91CD\u590D\u7684 " + type
          }
        }
      });
    }
  };
  return acc;
}, {}), {
  autoAnnotateHolder: {
    isHidden: function isHidden(props) {
      return !(0, _lodash.some)(partsPrimersFeatures, function (type) {
        return props["autoAnnotate" + type];
      });
    }
  },
  onConfigureFeatureTypesClick: {
    name: "Configure Feature Types",
    handler: function handler(p) {
      return p.onConfigureFeatureTypesClick();
    },
    isHidden: function isHidden(props) {
      return !props.onConfigureFeatureTypesClick;
    }
  }
}, partsPrimersFeatures.reduce(function (acc, type) {
  var handlerName = "autoAnnotate" + type;
  acc[handlerName] = {
    name: "Auto Annotate " + type,
    isDisabled: function isDisabled(props) {
      return props.readOnly;
    },
    isHidden: function isHidden(props) {
      return !props[handlerName];
    },
    handler: function () {
      var _handler = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(props) {
        var _extends2, lowerType, toAdd;
        return _regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                if (!props[handlerName]) {
                  _context.next = 8;
                  break;
                }
                lowerType = type.toLowerCase();
                _context.next = 4;
                return props[handlerName](props);
              case 4:
                toAdd = _context.sent;
                props.updateSequenceData(_extends({}, props.sequenceData, (_extends2 = {}, _extends2[lowerType] = _extends({}, props.sequenceData[lowerType], toAdd), _extends2)));
                _context.next = 9;
                break;
              case 8:
                console.warn("we shouldn't be here..");
              case 9:
              case "end":
                return _context.stop();
            }
          }
        }, _callee);
      }));
      function handler(_x) {
        return _handler.apply(this, arguments);
      }
      return handler;
    }()
  };
  return acc;
}, {}));
//copy options
var toggleCopyOptionCommandDefs = {};
Object.keys(_copyOptions.defaultCopyOptions).forEach(function (type) {
  var cmdId = "toggleCopy" + (0, _lodash.upperFirst)(type);
  toggleCopyOptionCommandDefs[cmdId] = {
    name: "Include " + (0, _lodash.startCase)(type),
    handler: function handler(props) {
      return props.toggleCopyOption(type);
    },
    isActive: function isActive(props) {
      return props.copyOptions && props.copyOptions[type];
    }
  };
});
var readOnlyDisabledTooltip = "Sorry this function is not allowed in Read-Only Mode";
var noSelection = function noSelection(_ref) {
  var _ref$selectionLayer = _ref.selectionLayer,
    selectionLayer = _ref$selectionLayer === void 0 ? {} : _ref$selectionLayer;
  return !(selectionLayer.start > -1 && selectionLayer.end > -1) && "Selection Required";
};
var triggerClipboardCommand = function triggerClipboardCommand(type) {
  var wrapper = document.querySelector(".veVectorInteractionWrapper");
  if (!wrapper) {
    return window.toastr.info("Cannot trigger a " + type + " in the current view");
  }
  var hiddenInput = wrapper.querySelector("input.clipboard");
  hiddenInput.focus();
  var worked = document.execCommand(type);
  wrapper.focus();
  if (!worked) {
    var keys = {
      paste: "Cmd/Ctrl+V",
      cut: "Cmd/Ctrl+X",
      copy: "Cmd/Ctrl+C"
    };
    if (keys[type]) {
      // TODO maybe improve msg with HTML
      window.toastr.info("Press " + keys[type] + " to " + type);
    } else {
      console.warn("The " + type + " command did not work. document.execCommand(" + type + ") didn't work");
    }
  }
};
var editCommandDefs = _extends({
  changeCaseCmd: {
    isHidden: isProtein,
    handler: function handler() {}
  },
  changeCircularityCmd: {
    isHidden: function isHidden(p) {
      return p.readOnly || isProtein(p) || isOligo(p) || isRna(p);
    },
    handler: function handler() {}
  },
  cut: {
    isDisabled: function isDisabled(props) {
      return props.readOnly && readOnlyDisabledTooltip || props.sequenceLength === 0;
    },
    isHidden: function isHidden(props) {
      return props.readOnly;
    },
    handler: function handler() {
      triggerClipboardCommand("cut");
    },
    hotkey: "mod+x"
  },
  createNewFromSubsequence: {
    name: "New Sequence From Selected Range",
    isDisabled: function isDisabled(props) {
      return props.sequenceLength === 0 || props.selectionLayer.start === -1;
    },
    isHidden: function isHidden(props) {
      return !props.onCreateNewFromSubsequence;
    },
    handler: function handler(props) {
      props.onCreateNewFromSubsequence((0, _sequenceUtils.getSequenceDataBetweenRange)(props.sequenceData, props.selectionLayer), props);
    }
    // hotkey: "mod+x"
  },

  copy: {
    isDisabled: function isDisabled(props) {
      return props.sequenceLength === 0;
    },
    handler: function handler() {
      return triggerClipboardCommand("copy");
    },
    hotkey: "mod+c"
  },
  paste: {
    isDisabled: function isDisabled(props) {
      return props.readOnly && readOnlyDisabledTooltip;
    },
    isHidden: function isHidden(props) {
      return props.readOnly;
    },
    handler: function handler() {
      return triggerClipboardCommand("paste");
    },
    hotkey: "mod+v"
  },
  undo: {
    name: "撤销",
    isHidden: function isHidden(props) {
      return props.readOnly;
    },
    isDisabled: function isDisabled(props) {
      return props.readOnly || !(props.sequenceDataHistory && props.sequenceDataHistory.past && props.sequenceDataHistory.past.length);
    },
    handler: function handler(props) {
      return props.undo();
    },
    hotkey: "mod+z"
  },
  redo: {
    name: "重做",
    isHidden: function isHidden(props) {
      return props.readOnly;
    },
    isDisabled: function isDisabled(props) {
      return props.readOnly || !(props.sequenceDataHistory && props.sequenceDataHistory.future && props.sequenceDataHistory.future.length);
    },
    handler: function handler(props) {
      return props.redo();
    },
    hotkey: "mod+shift+z"
  },
  find: {
    isDisabled: function isDisabled(props) {
      return props.sequenceLength === 0;
    },
    name: "查找...",
    handler: function handler(props) {
      if (props.findTool.isOpen) {
        var inputEl = document.querySelector("textarea.tg-find-tool-input") || document.querySelector(".tg-find-tool-input input");
        if (!inputEl) return;
        inputEl.focus && inputEl.focus();
        inputEl.select && inputEl.select();
      } else {
        props.toggleFindTool();
      }
    },
    hotkey: "mod+f",
    hotkeyProps: {
      preventDefault: true
    }
  },
  about: {
    isDisabled: function isDisabled(props) {
      return props.sequenceLength === 0;
    },
    name: "About",
    handler: function handler() {
      return (0, _teselagenReactComponents.showConfirmationDialog)({
        text: /*#__PURE__*/_react["default"].createElement("div", null, /*#__PURE__*/_react["default"].createElement("h5", null, "Open Vector Editor Version: ", _package["default"].version), "This editor is made by Teselagen.", /*#__PURE__*/_react["default"].createElement("br", null), /*#__PURE__*/_react["default"].createElement("br", null), "Issues can be logged here:", " ", /*#__PURE__*/_react["default"].createElement("a", {
          href: "https://github.com/TeselaGen/openVectorEditor/issues"
        }, "Open Vector Editor")),
        confirmButtonText: "Back",
        cancelButtonText: null,
        canEscapeKeyCancel: true //this is false by default
      });
    }
  },

  versionNumber: {
    name: "OVE Version:  " + _package["default"].version,
    handler: function handler() {
      var win = window.open("https://github.com/TeselaGen/openVectorEditor/commits/master", "_blank");
      win.focus();
    }
  },
  goTo: {
    isDisabled: function isDisabled(props) {
      return props.sequenceLength === 0;
    },
    name: "定位...",
    handler: function handler(props) {
      (0, _GlobalDialogUtils.showDialog)({
        dialogType: "GoToDialog",
        props: {
          extraProps: {
            sequencePosition: {
              min: 0,
              max: (0, _proteinUtils.divideBy3)(props.sequenceLength, isProtein(props))
            }
          },
          initialValues: {
            sequencePosition: (0, _proteinUtils.divideBy3)(props.caretPosition >= 0 ? props.caretPosition : 0, isProtein(props))
          },
          onSubmit: function onSubmit(values) {
            return props.caretPositionUpdate(values.sequencePosition * (isProtein(props) ? 3 : 1));
          }
        }
      });
    },
    hotkey: "mod+g",
    hotkeyProps: {
      preventDefault: true
    }
  },
  select: {
    isDisabled: function isDisabled(props) {
      return props.sequenceLength === 0;
    },
    name: "Select...",
    handler: function handler(props) {
      var _props$selectionLayer = props.selectionLayer,
        start = _props$selectionLayer.start,
        end = _props$selectionLayer.end;
      if (!(start > -1)) {
        start = props.caretPosition;
        end = props.caretPosition;
      }
      (0, _GlobalDialogUtils.showDialog)({
        dialogType: "SelectDialog",
        props: {
          extraProps: {
            circular: props.sequenceData && props.sequenceData.circular,
            from: {
              min: 1,
              max: (0, _proteinUtils.divideBy3)(props.sequenceLength || 1, isProtein(props))
            },
            to: {
              min: 1,
              max: (0, _proteinUtils.divideBy3)(props.sequenceLength || 1, isProtein(props))
            }
          },
          selectionLayerUpdate: props.selectionLayerUpdate,
          caretPositionUpdate: props.caretPositionUpdate,
          initialCaretPosition: props.caretPosition,
          initialValues: {
            from: Math.max(1, 1 + (0, _proteinUtils.divideBy3)(start >= 0 ? start : 0, isProtein(props))),
            to: Math.max(1, 1 + (0, _proteinUtils.divideBy3)(end >= 0 ? end : 0, isProtein(props)))
          },
          isProtein: isProtein(props),
          sequenceLength: (0, _proteinUtils.divideBy3)(props.sequenceLength || 1, isProtein(props)),
          onSubmit: function onSubmit(values) {
            var newRange = (0, _rangeUtils.convertRangeTo0Based)({
              start: isProtein(props) ? values.from * 3 : values.from,
              end: isProtein(props) ? values.to * 3 : values.to
            });
            return props.selectionLayerUpdate({
              start: isProtein(props) ? newRange.start - 2 : newRange.start,
              end: newRange.end
            });
          }
        }
      });
    }
  },
  selectAll: {
    handler: function handler(props, obj) {
      var _ref2 = obj || {},
        event = _ref2.event,
        viaHotkey = _ref2.viaHotkey;
      if (viaHotkey) {
        event.stopPropagation();
        event.preventDefault();
      }
      props.selectAll();
    },
    name: "全选",
    isDisabled: function isDisabled(props) {
      return props.sequenceLength === 0;
    },
    hotkey: "mod+a"
    //tnr: we can't pass the following because it will block inputs
    // hotkeyProps: { preventDefault: true, stopPropagation: true }
  },

  selectInverse: {
    isDisabled: function isDisabled(props) {
      return noSelection(props);
    },
    handler: function handler(props) {
      return props.handleInverse();
    },
    name: "选择反向",
    hotkey: "mod+i"
  },
  complementSelection: {
    isHidden: function isHidden(props) {
      return props.readOnly || isProtein(props);
    },
    isDisabled: function isDisabled(props) {
      return props.readOnly && readOnlyDisabledTooltip || noSelection(props);
    },
    handler: function handler(props) {
      return props.handleComplementSelection();
    }
  },
  complementEntireSequence: {
    isHidden: function isHidden(props) {
      return props.readOnly || isProtein(props);
    },
    isDisabled: function isDisabled(props) {
      return props.readOnly && readOnlyDisabledTooltip || props.sequenceLength === 0;
    },
    handler: function handler(props) {
      return props.handleComplementSequence();
    }
  },
  sequenceCase: {
    isHidden: isProtein
  },
  toggleCircular: {
    name: "Circular",
    isActive: function isActive(props) {
      return props.sequenceData.circular;
    },
    handler: function handler(props) {
      return props.updateCircular(true);
    }
  },
  toggleLinear: {
    name: "Linear",
    isActive: function isActive(props) {
      return !props.sequenceData.circular;
    },
    handler: function handler(props) {
      return props.updateCircular(false);
    }
  }
}, [
// { hotkey: "option + =", name: "切换序列大小写", type: "flipCaseSequence" },
// { hotkey: "option + plus", name: "大写序列", type: "upperCaseSequence" },
// { hotkey: "option + -", name: "小写序列", type: "lowerCaseSequence" },
{
  /* hotkey: "option+-", */type: "upperCaseSelection"
}, {
  /* hotkey: "option+-", */type: "lowerCaseSelection"
}].reduce(function (acc, _ref3) {
  var type = _ref3.type,
    hotkey = _ref3.hotkey;
  var isSelection = type.includes("Selection");
  acc[type] = {
    isHidden: isProtein,
    isDisabled: function isDisabled(props) {
      if (props.readOnly) {
        return "The sequence is read only. Try changing 'View > Sequence > Case'";
      }
      if (isSelection && !(props.selectionLayer.start > -1)) {
        return "No Selection to Replace";
      }
    },
    name: (0, _lodash.startCase)(type),
    hotkey: hotkey,
    handler: function handler(props) {
      var sequence = props.sequenceData.sequence;
      var selectionLayer = props.selectionLayer;
      var toastFired;
      if (props.uppercaseSequenceMapFont !== "noPreference") {
        toastFired = true;
        props.updateSequenceCase("noPreference");
        window.toastr.success("Sequence Case Edited Successfully. To avoid confusion we set: 'View > Sequence Case' to 'No Preference'", {
          timeout: 10000
        });
      }
      var func = type.includes("lower") ? "toLowerCase" : "toUpperCase";
      var newSeq;
      var orginalSeq = isSelection ? (0, _rangeUtils.getSequenceWithinRange)(selectionLayer, sequence) : sequence;
      if (type.includes("flip")) {
        newSeq = invertString(orginalSeq);
      } else {
        newSeq = orginalSeq[func]();
      }
      if (newSeq !== orginalSeq) {
        !toastFired && window.toastr.success("Sequence Case Edited Successfully");
        //don't trigger a mutation unless something has actually changed
        props.updateSequenceData(_extends({}, props.sequenceData, {
          sequence: isSelection ? (0, _sequenceUtils.adjustBpsToReplaceOrInsert)(sequence, newSeq, selectionLayer, false) : newSeq
        }));
      }
    }
  };
  return acc;
}, {}), {
  toggleShowGCContent: {
    isActive: function isActive(props) {
      return props.showGCContent;
    },
    handler: function handler(props) {
      props.toggleShowGCContent(!props.showGCContent);
    }
  },
  toggleSequenceMapFontUpper: {
    isActive: function isActive(props) {
      return props.uppercaseSequenceMapFont === "uppercase";
    },
    name: "切换整个序列为大写",
    handler: function handler(props) {
      props.updateSequenceCase("uppercase");
      window.toastr.success("Sequence Case View Changed");
    },
    hotkey: "ctrl+option+plus"
  },
  toggleSequenceMapFontRaw: {
    isActive: function isActive(props) {
      return props.uppercaseSequenceMapFont === "noPreference";
    },
    name: "还原序列大小写",
    handler: function handler(props) {
      props.updateSequenceCase("noPreference");
      window.toastr.success("Sequence Case View Changed");
    },
    hotkey: "ctrl+option+="
  },
  toggleSequenceMapFontLower: {
    isActive: function isActive(props) {
      return props.uppercaseSequenceMapFont === "lowercase";
    },
    name: "切换整个序列为小写",
    handler: function handler(props) {
      props.updateSequenceCase("lowercase");
      window.toastr.success("Sequence Case View Changed");
    },
    hotkey: "ctrl+option+-"
  },
  setRowViewSequenceSpacing: {
    handler: function handler() {},
    name: function name(props) {
      return /*#__PURE__*/_react["default"].createElement("div", {
        "data-test": "setRowViewSequenceSpacing"
      }, "Spacing (in Sequence Map)", /*#__PURE__*/_react["default"].createElement("div", {
        style: {
          paddingLeft: 11,
          paddingRight: 11,
          paddingTop: 3
        }
      }, /*#__PURE__*/_react["default"].createElement(_core.Slider, {
        stepSize: 1,
        onChange: function onChange(v) {
          props.updateSequenceSpacing(v);
        },
        value: Number(props.charWidth),
        max: 16,
        min: 8,
        labelStepSize: 1
      })));
    }
  },
  createMenuHolder: {
    name: "Create",
    isHidden: function isHidden(props) {
      return isProtein(props) && props.readOnly;
    },
    handler: function handler() {},
    submenu: function submenu(props) {
      return ["newFeature", "newPart", {
        cmd: "newTranslation",
        text: "翻译"
      }, {
        cmd: "newReverseTranslation",
        text: "反向翻译"
      }, {
        cmd: "newPrimer",
        text: "引物"
      }, "createNewFromSubsequence"].concat(props.getAdditionalCreateOpts ? props.getAdditionalCreateOpts(props) || [] : []);
    }
  },
  // toggleSequenceMapFontNoPreference: {
  //   isActive: props =>
  //     !props.uppercaseSequenceMapFont ||
  //     props.uppercaseSequenceMapFont === "noPreference",
  //   handler: props => {
  //     props.updateSequenceCase("noPreference");
  //   }
  // },
  reverseComplementSelection: {
    name: "翻转序列",
    isDisabled: function isDisabled(props) {
      return props.readOnly && readOnlyDisabledTooltip || noSelection(props);
    },
    isHidden: function isHidden(props) {
      return props.readOnly || isProtein(props);
    },
    handler: function handler(props) {
      return props.handleReverseComplementSelection();
    },
    hotkey: "mod+e"
  },
  reverseComplementEntireSequence: {
    isHidden: function isHidden(props) {
      return props.readOnly || isProtein(props);
    },
    isDisabled: function isDisabled(props) {
      return props.readOnly && readOnlyDisabledTooltip || props.sequenceLength === 0;
    },
    handler: function handler(props) {
      return props.handleReverseComplementSequence();
    }
  },
  fullSequenceTranslations: {
    isHidden: isProtein,
    handler: function handler() {}
  },
  sequenceAA_allFrames: {
    isActive: function isActive(props) {
      return props.frameTranslations["1"] && props.frameTranslations["2"] && props.frameTranslations["3"];
    },
    handler: function handler(props) {
      if (props.frameTranslations["1"] && props.frameTranslations["2"] && props.frameTranslations["3"]) {
        props.frameTranslationToggleOff("1");
        props.frameTranslationToggleOff("2");
        props.frameTranslationToggleOff("3");
      } else {
        props.annotationVisibilityShow("translations");
        props.frameTranslationToggleOn("1");
        props.frameTranslationToggleOn("2");
        props.frameTranslationToggleOn("3");
      }
    }
  },
  sequenceAAReverse_allFrames: {
    isHidden: isProtein,
    isActive: function isActive(props) {
      return props.frameTranslations["-1"] && props.frameTranslations["-2"] && props.frameTranslations["-3"];
    },
    handler: function handler(props) {
      if (props.frameTranslations["-1"] && props.frameTranslations["-2"] && props.frameTranslations["-3"]) {
        props.frameTranslationToggleOff("-1");
        props.frameTranslationToggleOff("-2");
        props.frameTranslationToggleOff("-3");
      } else {
        props.annotationVisibilityShow("translations");
        props.frameTranslationToggleOn("-1");
        props.frameTranslationToggleOn("-2");
        props.frameTranslationToggleOn("-3");
      }
    }
  },
  sequenceAA_frame1: {
    isActive: function isActive(props) {
      return props.frameTranslations["1"];
    },
    handler: function handler(props) {
      if (!props.frameTranslations["1"]) {
        props.annotationVisibilityShow("translations");
      }
      props.frameTranslationToggle("1");
    }
  },
  sequenceAA_frame2: {
    isActive: function isActive(props) {
      return props.frameTranslations["2"];
    },
    handler: function handler(props) {
      if (!props.frameTranslations["2"]) {
        props.annotationVisibilityShow("translations");
      }
      props.frameTranslationToggle("2");
    }
  },
  sequenceAA_frame3: {
    isActive: function isActive(props) {
      return props.frameTranslations["3"];
    },
    handler: function handler(props) {
      if (!props.frameTranslations["3"]) {
        props.annotationVisibilityShow("translations");
      }
      props.frameTranslationToggle("3");
    }
  },
  sequenceAAReverse_frame1: {
    isActive: function isActive(props) {
      return props.frameTranslations["-1"];
    },
    handler: function handler(props) {
      if (!props.frameTranslations["-1"]) {
        props.annotationVisibilityShow("translations");
      }
      props.frameTranslationToggle("-1");
    }
  },
  sequenceAAReverse_frame2: {
    isActive: function isActive(props) {
      return props.frameTranslations["-2"];
    },
    handler: function handler(props) {
      if (!props.frameTranslations["-2"]) {
        props.annotationVisibilityShow("translations");
      }
      props.frameTranslationToggle("-2");
    }
  },
  sequenceAAReverse_frame3: {
    isActive: function isActive(props) {
      return props.frameTranslations["-3"];
    },
    handler: function handler(props) {
      if (!props.frameTranslations["-3"]) {
        props.annotationVisibilityShow("translations");
      }
      props.frameTranslationToggle("-3");
    }
  },
  newTranslation: getNewTranslationHandler(),
  newReverseTranslation: getNewTranslationHandler(true),
  newFeature: {
    name: "新建Feature",
    handler: function handler(props /* state, ctxInfo */) {
      props.handleNewFeature();
    },
    isHidden: function isHidden(props) {
      return props.readOnly || !props.annotationsToSupport || !props.annotationsToSupport.features;
    },
    isDisabled: function isDisabled(props) {
      return props.readOnly && readOnlyDisabledTooltip || props.sequenceLength === 0;
    },
    hotkey: "mod+k",
    hotkeyProps: {
      preventDefault: true
    }
  },
  useGtgAndCtgAsStartCodons: {
    isHidden: isProtein,
    name: "使用 GTG 和 CTG 作为起始密码子",
    isActive: function isActive(props) {
      return props.useAdditionalOrfStartCodons;
    },
    handler: function handler(props) {
      return props.useAdditionalOrfStartCodonsToggle();
    }
  },
  minOrfSizeCmd: {
    name: function name(props) {
      return /*#__PURE__*/_react["default"].createElement("div", {
        "data-test": "min-orf-size",
        style: {
          display: "flex"
        }
      }, "\u6700\u5C0F ORF \u5927\u5C0F:", /*#__PURE__*/_react["default"].createElement("input", {
        type: "number",
        className: (0, _classnames["default"])(_core.Classes.INPUT, "minOrfSizeInput"),
        onChange: function onChange(event) {
          var minimumOrfSize = parseInt(event.target.value, 10);
          if (!minimumOrfSize) {
            minimumOrfSize = 0;
          }
          if (!(minimumOrfSize > -1)) minimumOrfSize = -minimumOrfSize;
          props.annotationVisibilityShow("orfs");
          props.minimumOrfSizeUpdate(minimumOrfSize);
        },
        value: props.minimumOrfSize
      }));
    },
    handler: function handler() {}
  },
  hotkeyDialog: {
    name: "View Editor Hotkeys",
    handler: function handler(props) {
      return props.openHotkeyDialog();
    }
  },
  newPart: {
    name: "新建Part",
    handler: function handler(props) {
      return props.handleNewPart();
    },
    isHidden: function isHidden(props) {
      return props.readOnly || !props.annotationsToSupport || !props.annotationsToSupport.parts;
    },
    isDisabled: function isDisabled(props) {
      return props.readOnly && readOnlyDisabledTooltip || props.sequenceLength === 0;
    },
    hotkey: "mod+l",
    hotkeyProps: {
      preventDefault: true
    }
  },
  newPrimer: {
    handler: function handler(props) {
      return props.handleNewPrimer();
    },
    isHidden: function isHidden(props) {
      return props.readOnly || !props.annotationsToSupport || !props.annotationsToSupport.primers;
    },
    isDisabled: function isDisabled(props) {
      return props.readOnly && readOnlyDisabledTooltip || props.sequenceLength === 0;
    }
  },
  rotateToCaretPosition: {
    name: "旋转到定位符位置",
    isHidden: function isHidden(props) {
      return props.readOnly || isProtein(props);
    },
    isDisabled: function isDisabled(props) {
      return props.readOnly && readOnlyDisabledTooltip || props.caretPosition === -1 && "You must first place cursor" || !props.sequenceData.circular && "Disabled for Linear Sequences" || props.sequenceLength === 0;
    },
    handler: function handler(props) {
      return props.handleRotateToCaretPosition();
    },
    hotkey: "mod+b"
  }
}, toggleCopyOptionCommandDefs);
var cirularityCommandDefs = {
  circular: {
    isHidden: function isHidden(props) {
      return props.readOnly || isProtein(props);
    },
    isDisabled: function isDisabled(props) {
      return props.readOnly && readOnlyDisabledTooltip;
    },
    handler: function handler(props) {
      return props.updateCircular(true);
    },
    isActive: function isActive(props) {
      return props && props.sequenceData.circular;
    }
  },
  linear: {
    isHidden: function isHidden(props) {
      return props.readOnly;
    },
    isDisabled: function isDisabled(props) {
      return props.readOnly && readOnlyDisabledTooltip;
    },
    handler: function handler(props) {
      return props.updateCircular(false);
    },
    isActive: function isActive(props) {
      return props && !props.sequenceData.circular;
    }
  }
};
var nicheAnnotations = [{
  type: "warnings",
  isHidden: function isHidden(p) {
    return !(0, _lodash.map)(p.sequenceData["warnings"]).length;
  }
}, {
  type: "assemblyPieces",
  isHidden: function isHidden(p) {
    return !(0, _lodash.map)(p.sequenceData["assemblyPieces"]).length;
  }
}, {
  type: "lineageAnnotations",
  isHidden: function isHidden(p) {
    return !(0, _lodash.map)(p.sequenceData["lineageAnnotations"]).length;
  }
}];
var labelToggleCommandDefs = {};
["feature", "part", "cutsite", "primer"].concat(nicheAnnotations).forEach(function (_type) {
  var rest = {};
  var type = _type;
  if (_type.type) {
    type = _type.type.slice(0, -1);
    rest = _type;
  }
  var cmdId = "toggle" + (0, _lodash.upperFirst)(type) + "Labels";
  var plural = type + "s";
  labelToggleCommandDefs[cmdId] = _extends({
    toggle: ["show", "hide"],
    handler: function handler(props) {
      return props.annotationLabelVisibilityToggle(plural);
    },
    isHidden: function isHidden(props) {
      return props && props.typesToOmit && props.typesToOmit[plural] === false;
    }
  }, rest, {
    isActive: function isActive(props) {
      return props && props.annotationLabelVisibility[plural];
    }
  });
});
var editAnnotationCommandDefs = ["feature", "part", "primer"].reduce(function (acc, key) {
  acc["edit" + (0, _lodash.upperFirst)(key)] = {
    name: function name(props) {
      return props.readOnly ? "View " + (0, _lodash.upperFirst)(key) + " Details" : "Edit " + (0, _lodash.upperFirst)(key);
    },
    handler: function handler(props, state, ctxInfo) {
      var annotation = (0, _lodash.get)(ctxInfo, "context.annotation");
      (0, _GlobalDialogUtils.showAddOrEditAnnotationDialog)({
        annotation: annotation,
        type: key
      });
    }
    // isHidden: (props) => props.readOnly
  };

  return acc;
}, {});
var deleteAnnotationCommandDefs = ["feature", "part", "primer", "translation"].reduce(function (acc, key) {
  acc["delete" + (0, _lodash.upperFirst)(key)] = {
    name: "Delete " + (0, _lodash.upperFirst)(key),
    handler: function handler(props, state, ctxInfo) {
      var annotation = (0, _lodash.get)(ctxInfo, "context.annotation");
      props["delete" + (0, _lodash.upperFirst)(key)](annotation);
    },
    isHidden: function isHidden(props) {
      return props.readOnly;
    }
  };
  return acc;
}, {});
var viewPropertiesCommandDefs = ["general", "genbank", "features", "parts", "orfs", "cutsites", "primers", "translations"].reduce(function (acc, key) {
  var singularKey = _pluralize["default"].singular(key);
  var upperKey = (0, _lodash.upperFirst)(singularKey);
  var name = function () {
    if (singularKey === "cutsite") {
      return "View Cut Site Properties";
    }
    if (singularKey === "orf") {
      return "View ORF Properties";
    }
    return "View " + (0, _lodash.upperFirst)(singularKey) + " Properties";
  }();
  acc["view" + upperKey + "Properties"] = {
    name: name,
    handler: function handler(props, state, ctxInfo) {
      var annotation = (0, _lodash.get)(ctxInfo, "context.annotation");
      props.propertiesViewOpen();
      //we need to clear the properties tab first in case the same item has already been selected
      props.propertiesViewTabUpdate(key, undefined);
      setTimeout(function () {
        //then shortly after we can update it with the correct annotation
        props.propertiesViewTabUpdate(key, annotation);
      }, 0);
    }
  };
  return acc;
}, {});
var annotationToggleCommandDefs = {};
["features", "parts"].concat(nicheAnnotations, [{
  type: "cutsites",
  isHidden: isProtein
}, "axis", {
  type: "orfs",
  text: "ORFs",
  isHidden: isProtein
}, {
  type: "primers",
  isHidden: isProtein
}, {
  type: "chromatogram",
  isHidden: function isHidden(p) {
    return !p.sequenceData.chromatogramData;
  }
}, "translations", {
  type: "orfTranslations",
  text: "ORF 翻译",
  isHidden: isProtein,
  isDisabled: function isDisabled(props) {
    return !props.annotationVisibility.orfs && "ORFs 必须是可见的，以便查看它们翻译" || !props.annotationVisibility.translations && "翻译必须是可见的，才能查看ORF翻译";
  }
}, {
  type: "cdsFeatureTranslations",
  text: "CDS Feature Translations",
  isHidden: isProtein,
  isDisabled: function isDisabled(props) {
    return !props.annotationVisibility.features && "Features must be visible to view their translations" || !props.annotationVisibility.translations && "Translations must be visible to view CDS feature translations";
  }
},
// {
//   type: "aminoAcidNumbers",
//   isHidden: (p, c) =>
//     (c.isDnaMenu && p.isProtein) || (!c.isDnaMenu && !p.isProtein)
// },
{
  type: "aminoAcidNumbers"
}, "axisNumbers", {
  type: "sequence",
  name: "DNA Sequence",
  noCount: true,
  isHidden: function isHidden(props) {
    return !isProtein(props);
  }
}, {
  type: "reverseSequence",
  name: function name(props) {
    return isProtein(props) ? "DNA Reverse Sequence" : "Reverse Sequence";
  }
}, {
  type: "fivePrimeThreePrimeHints",
  name: function name() {
    return "5' 3' Hints";
  }
}, {
  type: "dnaColors",
  name: function name() {
    return "DNA Colors";
  },
  isDisabled: function isDisabled(props) {
    return !props.annotationVisibility.sequence && !props.annotationVisibility.reverseSequence && "The DNA sequence must be visible in order to color it";
  }
}]).forEach(function (typeOrObj) {
  var type = typeOrObj;
  var obj = {};
  if (typeOrObj.type) {
    type = typeOrObj.type;
    obj = typeOrObj;
  }
  var cmdId = "toggle" + (0, _lodash.upperFirst)(type);
  annotationToggleCommandDefs[cmdId] = _extends({
    toggle: ["show", "hide"],
    name: function name(props) {
      var sequenceData = props.sequenceData || {};
      var count;
      var hasCount = false;
      var annotations = props[type] || sequenceData[type];
      if (annotations && !obj.noCount) {
        hasCount = true;
        count = annotations.length || Object.keys(annotations).length || 0;
      }
      if (type === "cdsFeatureTranslations") {
        hasCount = true;
        count = (0, _lodash.filter)(props.features || sequenceData.features || [], function (_ref4) {
          var type = _ref4.type;
          return type === "CDS";
        }).length;
      }
      if (type === "orfTranslations") {
        hasCount = true;
        count = (0, _lodash.filter)(props.orfs || sequenceData.orfs || [], function (_ref5) {
          var isOrf = _ref5.isOrf;
          return isOrf;
        }).length;
      }
      return /*#__PURE__*/_react["default"].createElement("span", null, obj.text || (0, _lodash.startCase)(type === "cutsites" ? "Cut Sites" : type), "\xA0", hasCount && /*#__PURE__*/_react["default"].createElement(_core.Tag, {
        className: "tg-smallTag",
        round: true,
        style: {
          marginLeft: 4
        }
      }, count));
    },
    handler: function handler(props) {
      return props.annotationVisibilityToggle(type);
    },
    isActive: function isActive(props) {
      return props && props.annotationVisibility && props.annotationVisibility[type];
    }
  }, obj, {
    //spread this here to override the above props if necessary
    isHidden: function isHidden(props) {
      return props && props.typesToOmit && props.typesToOmit[type] === false || obj.isHidden && obj.isHidden(props);
    }
  });
});
var additionalAnnotationCommandsDefs = {
  limitsMenu: {
    isHidden: function isHidden(props) {
      return props.maxAnnotationsToDisplay;
    }
  },
  showAll: {
    handler: function handler(props) {
      _sequenceUtils.annotationTypes.forEach(function (type) {
        if (props.isProtein) {
          if (type === "translations" || type === "cutsites") return props.annotationVisibilityHide(type);
        }
        props.annotationVisibilityShow(type);
      });
    }
  },
  hideAll: {
    handler: function handler(props) {
      _sequenceUtils.annotationTypes.forEach(function (type) {
        props.annotationVisibilityHide(type);
      });
    }
  },
  showAllLabels: {
    handler: function handler(props) {
      _sequenceUtils.annotationTypes.forEach(function (type) {
        // if (props.isProtein) {
        //   if (type === "translations" || type === "cutsites")
        //     return props.annotationVisibilityHide(type);
        // }
        props.annotationLabelVisibilityShow(type);
      });
    }
  },
  hideAllLabels: {
    handler: function handler(props) {
      _sequenceUtils.annotationTypes.forEach(function (type) {
        props.annotationLabelVisibilityHide(type);
      });
    }
  },
  toggleAminoAcidNumbers_dna: _extends({}, annotationToggleCommandDefs.toggleAminoAcidNumbers, {
    isHidden: function isHidden(props) {
      return isProtein(props);
    }
  }),
  toggleAminoAcidNumbers_protein: _extends({}, annotationToggleCommandDefs.toggleAminoAcidNumbers, {
    isHidden: function isHidden(props) {
      return isProtein(props);
    }
  })
};
var toolCommandDefs = {
  simulateDigestion: {
    name: "新建酶切方案",
    handler: function handler(props) {
      return props.createNewDigest();
    },
    hotkey: "mod+shift+d",
    hotkeyProps: {
      preventDefault: true
    },
    isHidden: function isHidden(props) {
      return isProtein(props);
    }
  },
  simulatePCR: {
    name: "新建PCR",
    handler: function handler(props) {
      return props.createNewPCR();
    },
    hotkey: "mod+shift+p",
    hotkeyProps: {
      preventDefault: true
    },
    isHidden: function isHidden(props) {
      return isProtein(props);
    }
  },
  // TODO: enzyme manager (?)
  restrictionEnzymesManager: {
    name: "Manage Enzymes",
    handler: function handler(props) {
      if (props.enzymeManageOverride) {
        props.enzymeManageOverride(props);
      } else {
        props.createYourOwnEnzymeReset();
        (0, _GlobalDialogUtils.showDialog)({
          dialogType: "EnzymesDialog",
          props: {
            inputSequenceToTestAgainst: props.sequenceData ? props.sequenceData.sequence : ""
          }
        });
      }
    },
    isHidden: function isHidden(props) {
      return isProtein(props);
    }
  },
  openFilterCutsites: {
    name: "Filter Cut Sites",
    handler: function handler(props) {
      props.openToolbarItemUpdate("cutsiteTool");
    },
    isHidden: function isHidden(props) {
      return isProtein(props);
    }
  },
  openCreateCustomEnzyme: {
    name: "Create Custom Enzyme",
    handler: function handler() {
      (0, _GlobalDialogUtils.showDialog)({
        dialogType: "CreateCustomEnzyme"
      });
    },
    isHidden: function isHidden(props) {
      return props.overrideManageEnzymes;
    }
  }
};
var labelIntensities = {
  Low: 0.1,
  Medium: 0.4,
  High: 0.9
};
var labelSizes = {
  "33%": 3,
  "50%": 4,
  "75%": 6,
  "100%": 8,
  "125%": 10,
  "150%": 12,
  "200%": 16
};
var labelCommandDefs = {
  adjustLabelLineIntensity: {
    name: "Label Line Intensity",
    submenu: function submenu(props) {
      return (0, _lodash.map)(Object.keys(labelIntensities), function (key) {
        return {
          text: key == 'Low' ? '细' : key == 'Medium' ? '中' : '粗',
          checked: props.labelLineIntensity === labelIntensities[key],
          onClick: function onClick() {
            return props.changeLabelLineIntensity(labelIntensities[key]);
          }
        };
      });
    }
  },
  adjustLabelSize: {
    name: "Circular Label Size",
    submenu: function submenu(props) {
      return (0, _lodash.map)(Object.keys(labelSizes), function (key) {
        return {
          text: key,
          checked: props.labelSize === labelSizes[key],
          onClick: function onClick() {
            return props.changeLabelSize(labelSizes[key]);
          }
        };
      });
    }
  }
};
var commandDefs = _extends({
  showChromQualScoresMenu: {
    isHidden: function isHidden(props) {
      return !props.sequenceData.chromatogramData || !props.sequenceData.chromatogramData.baseTraces;
    }
  },
  togglePartsWithSubmenu: _extends({}, annotationToggleCommandDefs.toggleParts, {
    submenu: _viewSubmenu.partsSubmenu
  })
}, additionalAnnotationCommandsDefs, fileCommandDefs, cirularityCommandDefs, annotationToggleCommandDefs, viewPropertiesCommandDefs, editAnnotationCommandDefs, deleteAnnotationCommandDefs, labelToggleCommandDefs, editCommandDefs, toolCommandDefs, labelCommandDefs);
exports.commandDefs = commandDefs;
var _default = function _default(instance) {
  return (0, _commandUtils.oveCommandFactory)(instance, commandDefs);
};
exports["default"] = _default;
var invertString = function invertString(str) {
  var s = "";
  var i = 0;
  while (i < str.length) {
    var n = str.charAt(i);
    if (n === n.toUpperCase()) {
      // *Call* toLowerCase
      n = n.toLowerCase();
    } else {
      // *Call* toUpperCase
      n = n.toUpperCase();
    }
    i += 1;
    s += n;
  }
  return s;
};
function getFilterByLengthCmd(type) {
  return {
    name: function name(props) {
      return /*#__PURE__*/_react["default"].createElement("div", {
        "data-test": "filter-" + type + "-length"
      }, "\u6309\u957F\u5EA6\u8FC7\u6EE4", /*#__PURE__*/_react["default"].createElement("div", {
        onClick: function onClick(e) {
          return e.stopPropagation();
        }
      }, /*#__PURE__*/_react["default"].createElement(_core.NumericInput, {
        onValueChange: function onValueChange(valueAsNumber) {
          var minimumFilterLength = parseInt(valueAsNumber, 10);
          if (!(minimumFilterLength > -1)) return;
          if (minimumFilterLength > props.sequenceLength) return;
          props["update" + (0, _lodash.startCase)(type) + "LengthsToHide"]({
            enabled: true,
            min: minimumFilterLength
          });
        },
        value: props[type + "LengthsToHide"].min,
        min: 0
        // max={props[`${type}LengthsToHide`].max} //tnr: I think it is better to not bound the max
        ,
        fill: true,
        clampValueOnBlur: true,
        "data-test": "min-" + type + "-length"
      }), /*#__PURE__*/_react["default"].createElement(_core.NumericInput, {
        onValueChange: function onValueChange(valueAsNumber) {
          var maximumFilterLength = parseInt(valueAsNumber, 10);
          if (!(maximumFilterLength > -1)) return;
          // if (maximumFilterLength > props.sequenceLength) return; //tnr: I think it is better not to bound the max
          props["update" + (0, _lodash.startCase)(type) + "LengthsToHide"]({
            enabled: true,
            max: maximumFilterLength
          });
        },
        value: props[type + "LengthsToHide"].max,
        min: 0
        // max={props.sequenceLength} //tnr: I think it is better to not bound the max
        ,
        fill: true,
        clampValueOnBlur: true,
        "data-test": "max-" + type + "-length"
      })));
    },
    isActive: function isActive(props) {
      return props[type + "LengthsToHide"].enabled;
    },
    handler: function handler(props) {
      props["toggle" + (0, _lodash.startCase)(type) + "LengthsToHide"]();
    }
  };
}
function getFilterIndividualCmd(type) {
  var pluralType = (0, _pluralize["default"])(type);
  var upperType = (0, _lodash.startCase)(type);
  return {
    isHidden: function isHidden(props) {
      var total = Object.keys((0, _lodash.reduce)(props.sequenceData[pluralType], function (acc, feat) {
        acc[feat.id] = true;
        return acc;
      }, {})).length;
      return total > 500;
    },
    name: function name(props) {
      var total = Object.keys((0, _lodash.reduce)(props.sequenceData[pluralType], function (acc, feat) {
        acc[feat.id] = true;
        return acc;
      }, {})).length;
      var toHideCount = Object.keys(props.annotationVisibility[type + "IndividualToHide"]).length;
      return /*#__PURE__*/_react["default"].createElement("span", null, "Filter Individually \xA0", /*#__PURE__*/_react["default"].createElement(_core.Tag, {
        className: "tg-smallTag",
        round: true,
        style: {
          marginLeft: 4
        }
      }, total - toHideCount, "/", total));
    },
    submenu: function submenu(props) {
      var individualAnns = {};
      (0, _lodash.forEach)((0, _lodash.sortBy)(props.sequenceData[pluralType], function (_ref6) {
        var start = _ref6.start;
        return start + 1;
      }), function (ann) {
        if (!ann.id) return;
        var checked = !props.annotationVisibility[type + "IndividualToHide"][ann.id];
        if (individualAnns[ann.id]) {
          console.error("ann.id:", ann.id);
          console.error("we should not be here!");
        } else {
          individualAnns[ann.id] = {
            shouldDismissPopover: false,
            onClick: function onClick() {
              return checked ? props["hide" + upperType + "Individual"]([ann.id]) : props["show" + upperType + "Individual"]([ann.id]);
            },
            checked: checked
          };
        }
        individualAnns[ann.id].text = /*#__PURE__*/_react["default"].createElement("span", {
          style: {
            display: "flex",
            justifyContent: "space-between"
          }
        }, ann.name, " \xA0", " ", /*#__PURE__*/_react["default"].createElement("span", {
          style: {
            fontSize: 10
          }
        }, "(", ann.start + 1, "-", ann.end + 1, ")"));
      });
      var menu = (0, _lodash.map)(individualAnns);
      return [{
        text: "取消全选",
        onClick: function onClick() {
          return props["hide" + upperType + "Individual"](Object.keys(individualAnns));
        },
        shouldDismissPopover: false
      }, {
        text: "全选",
        onClick: function onClick() {
          return props["reset" + upperType + "IndividualToHide"]();
        },
        shouldDismissPopover: false
      }, "--"].concat(menu.length ? menu : [{
        text: "No " + upperType + "s To Filter",
        disabled: true
      }]);
    }
  };
}