"use strict";
(self["webpackChunkxircuits"] = self["webpackChunkxircuits"] || []).push([["lib_index_js"],{

/***/ "./node_modules/css-loader/dist/cjs.js!./node_modules/rc-dialog/assets/bootstrap.css":
/*!*******************************************************************************************!*\
  !*** ./node_modules/css-loader/dist/cjs.js!./node_modules/rc-dialog/assets/bootstrap.css ***!
  \*******************************************************************************************/
/***/ ((module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_cssWithMappingToString_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../css-loader/dist/runtime/cssWithMappingToString.js */ "./node_modules/css-loader/dist/runtime/cssWithMappingToString.js");
/* harmony import */ var _css_loader_dist_runtime_cssWithMappingToString_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_cssWithMappingToString_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../css-loader/dist/runtime/api.js */ "./node_modules/css-loader/dist/runtime/api.js");
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_cssWithMappingToString_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, ".rc-dialog {\n  position: relative;\n  width: auto;\n  margin: 10px;\n}\n.rc-dialog-wrap {\n  position: fixed;\n  overflow: auto;\n  top: 0;\n  right: 0;\n  bottom: 0;\n  left: 0;\n  z-index: 1050;\n  -webkit-overflow-scrolling: touch;\n  outline: 0;\n}\n.rc-dialog-content {\n  position: relative;\n  background-color: #fff;\n  border: 1px solid #999;\n  border: 1px solid rgba(0, 0, 0, 0.2);\n  border-radius: 6px;\n  box-shadow: 0 3px 9px rgba(0, 0, 0, 0.5);\n  background-clip: padding-box;\n  outline: 0;\n}\n.rc-dialog-header {\n  padding: 15px;\n  border-bottom: 1px solid #e5e5e5;\n}\n.rc-dialog-close {\n  cursor: pointer;\n  border: 0;\n  background: transparent;\n  font-size: 21px;\n  position: absolute;\n  right: 20px;\n  top: 12px;\n  font-weight: 700;\n  line-height: 1;\n  color: #000;\n  text-shadow: 0 1px 0 #fff;\n  filter: alpha(opacity=20);\n  opacity: 0.2;\n  text-decoration: none;\n}\n.rc-dialog-close-x:after {\n  content: '×';\n}\n.rc-dialog-close:hover {\n  opacity: 1;\n  filter: alpha(opacity=100);\n  text-decoration: none;\n}\n.rc-dialog-title {\n  margin: 0;\n  line-height: 1.42857143;\n}\n.rc-dialog-body {\n  position: relative;\n  padding: 15px;\n}\n.rc-dialog-footer {\n  padding: 15px;\n  text-align: right;\n  border-top: 1px solid #e5e5e5;\n}\n.rc-dialog-footer .btn + .btn {\n  margin-left: 5px;\n  margin-bottom: 0;\n}\n.rc-dialog-footer .btn-group .btn + .btn {\n  margin-left: -1px;\n}\n.rc-dialog-footer .btn-block + .btn-block {\n  margin-left: 0;\n}\n@media (min-width: 768px) {\n  .rc-dialog {\n    width: 600px;\n    margin: 30px auto;\n  }\n  .rc-dialog-content {\n    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.5);\n  }\n}\n.rc-dialog-slide-fade-enter,\n.rc-dialog-slide-fade-appear {\n  transform: translate(0, -25%);\n}\n.rc-dialog-slide-fade-enter,\n.rc-dialog-slide-fade-appear,\n.rc-dialog-slide-fade-leave {\n  animation-duration: 0.3s;\n  animation-fill-mode: both;\n  animation-timing-function: ease-out;\n  animation-play-state: paused;\n}\n.rc-dialog-slide-fade-enter.rc-dialog-slide-fade-enter-active,\n.rc-dialog-slide-fade-appear.rc-dialog-slide-fade-appear-active {\n  animation-name: rcDialogSlideFadeIn;\n  animation-play-state: running;\n}\n.rc-dialog-slide-fade-leave.rc-dialog-slide-fade-leave-active {\n  animation-name: rcDialogSlideFadeOut;\n  animation-play-state: running;\n}\n@keyframes rcDialogSlideFadeIn {\n  0% {\n    transform: translate(0, -25%);\n  }\n  100% {\n    transform: translate(0, 0);\n  }\n}\n@keyframes rcDialogSlideFadeOut {\n  0% {\n    transform: translate(0, 0);\n  }\n  100% {\n    transform: translate(0, -25%);\n  }\n}\n.rc-dialog-mask {\n  position: fixed;\n  top: 0;\n  right: 0;\n  left: 0;\n  bottom: 0;\n  background-color: #373737;\n  background-color: rgba(55, 55, 55, 0.6);\n  height: 100%;\n  filter: alpha(opacity=50);\n  z-index: 1050;\n}\n.rc-dialog-mask-hidden {\n  display: none;\n}\n.rc-dialog-fade-enter,\n.rc-dialog-fade-appear {\n  opacity: 0;\n  animation-duration: 0.3s;\n  animation-fill-mode: both;\n  animation-timing-function: cubic-bezier(0.55, 0, 0.55, 0.2);\n  animation-play-state: paused;\n}\n.rc-dialog-fade-leave {\n  animation-duration: 0.3s;\n  animation-fill-mode: both;\n  animation-timing-function: cubic-bezier(0.55, 0, 0.55, 0.2);\n  animation-play-state: paused;\n}\n.rc-dialog-fade-enter.rc-dialog-fade-enter-active,\n.rc-dialog-fade-appear.rc-dialog-fade-appear-active {\n  animation-name: rcDialogFadeIn;\n  animation-play-state: running;\n}\n.rc-dialog-fade-leave.rc-dialog-fade-leave-active {\n  animation-name: rcDialogFadeOut;\n  animation-play-state: running;\n}\n@keyframes rcDialogFadeIn {\n  0% {\n    opacity: 0;\n  }\n  100% {\n    opacity: 1;\n  }\n}\n@keyframes rcDialogFadeOut {\n  0% {\n    opacity: 1;\n  }\n  100% {\n    opacity: 0;\n  }\n}\n", "",{"version":3,"sources":["webpack://./node_modules/rc-dialog/assets/bootstrap.css"],"names":[],"mappings":"AAAA;EACE,kBAAkB;EAClB,WAAW;EACX,YAAY;AACd;AACA;EACE,eAAe;EACf,cAAc;EACd,MAAM;EACN,QAAQ;EACR,SAAS;EACT,OAAO;EACP,aAAa;EACb,iCAAiC;EACjC,UAAU;AACZ;AACA;EACE,kBAAkB;EAClB,sBAAsB;EACtB,sBAAsB;EACtB,oCAAoC;EACpC,kBAAkB;EAClB,wCAAwC;EACxC,4BAA4B;EAC5B,UAAU;AACZ;AACA;EACE,aAAa;EACb,gCAAgC;AAClC;AACA;EACE,eAAe;EACf,SAAS;EACT,uBAAuB;EACvB,eAAe;EACf,kBAAkB;EAClB,WAAW;EACX,SAAS;EACT,gBAAgB;EAChB,cAAc;EACd,WAAW;EACX,yBAAyB;EACzB,yBAAyB;EACzB,YAAY;EACZ,qBAAqB;AACvB;AACA;EACE,YAAY;AACd;AACA;EACE,UAAU;EACV,0BAA0B;EAC1B,qBAAqB;AACvB;AACA;EACE,SAAS;EACT,uBAAuB;AACzB;AACA;EACE,kBAAkB;EAClB,aAAa;AACf;AACA;EACE,aAAa;EACb,iBAAiB;EACjB,6BAA6B;AAC/B;AACA;EACE,gBAAgB;EAChB,gBAAgB;AAClB;AACA;EACE,iBAAiB;AACnB;AACA;EACE,cAAc;AAChB;AACA;EACE;IACE,YAAY;IACZ,iBAAiB;EACnB;EACA;IACE,yCAAyC;EAC3C;AACF;AACA;;EAEE,6BAA6B;AAC/B;AACA;;;EAGE,wBAAwB;EACxB,yBAAyB;EACzB,mCAAmC;EACnC,4BAA4B;AAC9B;AACA;;EAEE,mCAAmC;EACnC,6BAA6B;AAC/B;AACA;EACE,oCAAoC;EACpC,6BAA6B;AAC/B;AACA;EACE;IACE,6BAA6B;EAC/B;EACA;IACE,0BAA0B;EAC5B;AACF;AACA;EACE;IACE,0BAA0B;EAC5B;EACA;IACE,6BAA6B;EAC/B;AACF;AACA;EACE,eAAe;EACf,MAAM;EACN,QAAQ;EACR,OAAO;EACP,SAAS;EACT,yBAAyB;EACzB,uCAAuC;EACvC,YAAY;EACZ,yBAAyB;EACzB,aAAa;AACf;AACA;EACE,aAAa;AACf;AACA;;EAEE,UAAU;EACV,wBAAwB;EACxB,yBAAyB;EACzB,2DAA2D;EAC3D,4BAA4B;AAC9B;AACA;EACE,wBAAwB;EACxB,yBAAyB;EACzB,2DAA2D;EAC3D,4BAA4B;AAC9B;AACA;;EAEE,8BAA8B;EAC9B,6BAA6B;AAC/B;AACA;EACE,+BAA+B;EAC/B,6BAA6B;AAC/B;AACA;EACE;IACE,UAAU;EACZ;EACA;IACE,UAAU;EACZ;AACF;AACA;EACE;IACE,UAAU;EACZ;EACA;IACE,UAAU;EACZ;AACF","sourcesContent":[".rc-dialog {\n  position: relative;\n  width: auto;\n  margin: 10px;\n}\n.rc-dialog-wrap {\n  position: fixed;\n  overflow: auto;\n  top: 0;\n  right: 0;\n  bottom: 0;\n  left: 0;\n  z-index: 1050;\n  -webkit-overflow-scrolling: touch;\n  outline: 0;\n}\n.rc-dialog-content {\n  position: relative;\n  background-color: #fff;\n  border: 1px solid #999;\n  border: 1px solid rgba(0, 0, 0, 0.2);\n  border-radius: 6px;\n  box-shadow: 0 3px 9px rgba(0, 0, 0, 0.5);\n  background-clip: padding-box;\n  outline: 0;\n}\n.rc-dialog-header {\n  padding: 15px;\n  border-bottom: 1px solid #e5e5e5;\n}\n.rc-dialog-close {\n  cursor: pointer;\n  border: 0;\n  background: transparent;\n  font-size: 21px;\n  position: absolute;\n  right: 20px;\n  top: 12px;\n  font-weight: 700;\n  line-height: 1;\n  color: #000;\n  text-shadow: 0 1px 0 #fff;\n  filter: alpha(opacity=20);\n  opacity: 0.2;\n  text-decoration: none;\n}\n.rc-dialog-close-x:after {\n  content: '×';\n}\n.rc-dialog-close:hover {\n  opacity: 1;\n  filter: alpha(opacity=100);\n  text-decoration: none;\n}\n.rc-dialog-title {\n  margin: 0;\n  line-height: 1.42857143;\n}\n.rc-dialog-body {\n  position: relative;\n  padding: 15px;\n}\n.rc-dialog-footer {\n  padding: 15px;\n  text-align: right;\n  border-top: 1px solid #e5e5e5;\n}\n.rc-dialog-footer .btn + .btn {\n  margin-left: 5px;\n  margin-bottom: 0;\n}\n.rc-dialog-footer .btn-group .btn + .btn {\n  margin-left: -1px;\n}\n.rc-dialog-footer .btn-block + .btn-block {\n  margin-left: 0;\n}\n@media (min-width: 768px) {\n  .rc-dialog {\n    width: 600px;\n    margin: 30px auto;\n  }\n  .rc-dialog-content {\n    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.5);\n  }\n}\n.rc-dialog-slide-fade-enter,\n.rc-dialog-slide-fade-appear {\n  transform: translate(0, -25%);\n}\n.rc-dialog-slide-fade-enter,\n.rc-dialog-slide-fade-appear,\n.rc-dialog-slide-fade-leave {\n  animation-duration: 0.3s;\n  animation-fill-mode: both;\n  animation-timing-function: ease-out;\n  animation-play-state: paused;\n}\n.rc-dialog-slide-fade-enter.rc-dialog-slide-fade-enter-active,\n.rc-dialog-slide-fade-appear.rc-dialog-slide-fade-appear-active {\n  animation-name: rcDialogSlideFadeIn;\n  animation-play-state: running;\n}\n.rc-dialog-slide-fade-leave.rc-dialog-slide-fade-leave-active {\n  animation-name: rcDialogSlideFadeOut;\n  animation-play-state: running;\n}\n@keyframes rcDialogSlideFadeIn {\n  0% {\n    transform: translate(0, -25%);\n  }\n  100% {\n    transform: translate(0, 0);\n  }\n}\n@keyframes rcDialogSlideFadeOut {\n  0% {\n    transform: translate(0, 0);\n  }\n  100% {\n    transform: translate(0, -25%);\n  }\n}\n.rc-dialog-mask {\n  position: fixed;\n  top: 0;\n  right: 0;\n  left: 0;\n  bottom: 0;\n  background-color: #373737;\n  background-color: rgba(55, 55, 55, 0.6);\n  height: 100%;\n  filter: alpha(opacity=50);\n  z-index: 1050;\n}\n.rc-dialog-mask-hidden {\n  display: none;\n}\n.rc-dialog-fade-enter,\n.rc-dialog-fade-appear {\n  opacity: 0;\n  animation-duration: 0.3s;\n  animation-fill-mode: both;\n  animation-timing-function: cubic-bezier(0.55, 0, 0.55, 0.2);\n  animation-play-state: paused;\n}\n.rc-dialog-fade-leave {\n  animation-duration: 0.3s;\n  animation-fill-mode: both;\n  animation-timing-function: cubic-bezier(0.55, 0, 0.55, 0.2);\n  animation-play-state: paused;\n}\n.rc-dialog-fade-enter.rc-dialog-fade-enter-active,\n.rc-dialog-fade-appear.rc-dialog-fade-appear-active {\n  animation-name: rcDialogFadeIn;\n  animation-play-state: running;\n}\n.rc-dialog-fade-leave.rc-dialog-fade-leave-active {\n  animation-name: rcDialogFadeOut;\n  animation-play-state: running;\n}\n@keyframes rcDialogFadeIn {\n  0% {\n    opacity: 0;\n  }\n  100% {\n    opacity: 1;\n  }\n}\n@keyframes rcDialogFadeOut {\n  0% {\n    opacity: 1;\n  }\n  100% {\n    opacity: 0;\n  }\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ "./style/icons/breakpoint.svg":
/*!************************************!*\
  !*** ./style/icons/breakpoint.svg ***!
  \************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ("<svg height='100px' width='100px' class=\"jp-icon3\" fill=\"#616161\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" \n     version=\"1.1\" x=\"0px\" y=\"0px\" viewBox=\"0 0 99 100\" enable-background=\"new 0 0 99 100\" xml:space=\"preserve\">\n    <circle class=\"jp-icon3\" stroke=\"#000000\" stroke-miterlimit=\"10\" cx=\"50.5\" cy=\"50\" r=\"30.167\"></circle>\n    <circle class=\"jp-icon3\" fill=\"#616161\" stroke=\"#000000\" stroke-miterlimit=\"10\" cx=\"50.573\" cy=\"50\" r=\"27.973\"></circle>\n</svg>");

/***/ }),

/***/ "./style/icons/component-library.svg":
/*!*******************************************!*\
  !*** ./style/icons/component-library.svg ***!
  \*******************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ("<svg class=\"jp-icon3\"  fill=\"#616161\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" version=\"1.1\" x=\"-50px\" y=\"0px\" \n     viewBox=\"15 0 70 100\" enable-background=\"new 0 0 100 100\" xml:space=\"preserve\">\n    <g class=\"jp-icon3\" fill=\"#616161\" >\n        <path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M80,70H20V33h9v-7h16v7h12v-7h16v7h7V70z\"></path>\n    </g>\n</svg>");

/***/ }),

/***/ "./style/icons/debugger.svg":
/*!**********************************!*\
  !*** ./style/icons/debugger.svg ***!
  \**********************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ("<svg height='100px' width='100px' class=\"jp-icon3\"  fill=\"#616161\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" version=\"1.1\" x=\"0px\" y=\"0px\" \n     viewBox=\"0 0 100 100\" enable-background=\"new 0 0 100 100\" xml:space=\"preserve\">\n    <path d=\"M87,15H13c-3.314,0-6,2.686-6,6v58c0,3.314,2.686,6,6,6h74c3.314,0,6-2.686,6-6V21C93,17.686,90.314,15,87,15z M80,19  c1.657,0,3,1.343,3,3s-1.343,3-3,3s-3-1.343-3-3S78.343,19,80,19z M68,19c1.657,0,3,1.343,3,3s-1.343,3-3,3s-3-1.343-3-3  S66.343,19,68,19z M56,19c1.657,0,3,1.343,3,3s-1.343,3-3,3s-3-1.343-3-3S54.343,19,56,19z M87,78c0,0.552-0.448,1-1,1H14  c-0.552,0-1-0.448-1-1V30c0-0.552,0.448-1,1-1h72c0.552,0,1,0.448,1,1V78z\"></path>\n    <path d=\"M71,56h-5.678c-0.249,0-0.454-0.186-0.488-0.433c-0.142-1.026-0.374-2.016-0.693-2.961  c-0.076-0.225,0.012-0.469,0.218-0.587l4.828-2.787c2.293-1.324,0.288-4.785-2-3.464l-4.69,2.708  c-0.215,0.124-0.484,0.067-0.637-0.129c-0.993-1.267-2.208-2.356-3.632-3.213c-0.141-0.085-0.227-0.234-0.232-0.398  c-0.041-1.252-0.375-2.428-0.929-3.47c-0.103-0.195-0.075-0.43,0.081-0.585l2.266-2.266c1.869-1.869-0.958-4.699-2.828-2.828  l-2.267,2.267c-0.155,0.155-0.391,0.183-0.586,0.08c-2.344-1.244-5.123-1.244-7.467,0c-0.194,0.103-0.43,0.075-0.586-0.08  l-2.267-2.267c-1.869-1.869-4.699,0.958-2.828,2.828l2.266,2.266c0.156,0.156,0.184,0.391,0.081,0.585  c-0.553,1.042-0.887,2.218-0.929,3.47c-0.005,0.164-0.091,0.314-0.232,0.398c-1.425,0.857-2.64,1.946-3.632,3.213  c-0.153,0.196-0.422,0.253-0.637,0.129l-4.69-2.708c-2.288-1.321-4.292,2.141-2,3.464l4.828,2.787  c0.206,0.119,0.294,0.363,0.218,0.587c-0.319,0.944-0.552,1.935-0.693,2.961C35.132,55.814,34.927,56,34.678,56H29  c-2.643,0-2.646,4,0,4h5.724c0.245,0,0.447,0.179,0.486,0.421c0.161,0.998,0.415,1.964,0.763,2.886c0.086,0.228,0,0.482-0.211,0.604  l-4.948,2.857c-2.289,1.321-0.291,4.787,2,3.464l4.958-2.863c0.211-0.122,0.475-0.069,0.63,0.12C41.152,70.848,45.32,73,50,73  s8.848-2.152,11.598-5.511c0.155-0.189,0.418-0.242,0.63-0.12l4.958,2.863c2.289,1.321,4.291-2.141,2-3.464l-4.948-2.857  c-0.211-0.122-0.298-0.376-0.211-0.604c0.347-0.922,0.602-1.888,0.763-2.886C64.828,60.179,65.031,60,65.276,60H71  C73.643,60,73.646,56,71,56z M44,66c-1.657,0-3-1.343-3-3s1.343-3,3-3s3,1.343,3,3S45.657,66,44,66z M44,56c-1.657,0-3-1.343-3-3  s1.343-3,3-3s3,1.343,3,3S45.657,56,44,56z M56,66c-1.657,0-3-1.343-3-3s1.343-3,3-3s3,1.343,3,3S57.657,66,56,66z M56,56  c-1.657,0-3-1.343-3-3s1.343-3,3-3s3,1.343,3,3S57.657,56,56,56z\"></path>\n</svg>");

/***/ }),

/***/ "./style/icons/lock.svg":
/*!******************************!*\
  !*** ./style/icons/lock.svg ***!
  \******************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ("\n<svg viewBox=\"0 0 512 512\"  xmlns=\"http://www.w3.org/2000/svg\"> \n    <g class=\"jp-icon3\" fill=\"#616161\">\n        <path d=\"m426.67 426.67v-213.34c0-23.465-19.199-42.668-42.668-42.668l-256 0.003907c-23.465 0-42.668 19.199-42.668 42.668v213.33c0 23.465 19.199 42.668 42.668 42.668h256c23.465-0.003907 42.668-19.203 42.668-42.668zm-128-106.67c0 23.465-19.199 42.668-42.668 42.668-23.465 0-42.668-19.199-42.668-42.668 0-23.465 19.199-42.668 42.668-42.668 23.465 0 42.668 19.203 42.668 42.668z\"/>\n        <path transform=\"scale(21.333)\" d=\"m17 12v-5.0001c0-2.8-2.2-5.0001-5.0001-5.0001-2.8 1.83e-4 -5.0001 2.2002-5.0001 5.0001v5.0001\" fill=\"none\" stroke=\"#616161\" stroke-miterlimit=\"10\" stroke-width=\"2\"/>\n    </g>\n</svg>\n");

/***/ }),

/***/ "./style/icons/low-power.svg":
/*!***********************************!*\
  !*** ./style/icons/low-power.svg ***!
  \***********************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ("<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n\r<!-- Uploaded to: SVG Repo, www.svgrepo.com, Transformed by: SVG Repo Mixer Tools -->\n<svg fill=\"#646464\" height=\"175px\" width=\"175px\" version=\"1.1\" id=\"Layer_1\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" viewBox=\"-51.2 -51.2 614.40 614.40\" xml:space=\"preserve\" stroke=\"#646464\" stroke-width=\"0.00512\">\n\r<g id=\"SVGRepo_bgCarrier\" stroke-width=\"0\"/>\n\r<g id=\"SVGRepo_tracerCarrier\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>\n\r<g id=\"SVGRepo_iconCarrier\"> <g> <g> <path d=\"M422.957,478.609h-16.696v-50.087c0-72.583-59.046-121.466-121.703-166.956c62.642-45.478,121.703-94.366,121.703-166.957 V33.391h16.696c9.217,0,16.696-7.473,16.696-16.696C439.652,7.473,432.174,0,422.957,0C414.155,0,98.294,0,89.044,0 c-9.217,0-16.696,7.473-16.696,16.696c0,9.223,7.479,16.696,16.696,16.696h16.696v61.217c0,72.592,59.063,121.481,121.707,166.959 c-62.647,45.478-121.707,94.365-121.707,166.954v50.087H89.044c-9.217,0-16.696,7.473-16.696,16.696 c0,9.223,7.479,16.696,16.696,16.696c11.105,0,320.455,0,333.913,0c9.217,0,16.696-7.473,16.696-16.696 C439.652,486.082,432.174,478.609,422.957,478.609z M222.609,139.132c-6.446,0-12.326-3.718-15.087-9.543 c-2.76-5.831-1.924-12.733,2.163-17.723l50.087-61.217c5.848-7.141,16.348-8.19,23.5-2.353c7.13,5.842,8.185,16.358,2.347,23.494 l-27.782,33.951h42.685c6.446,0,12.326,3.718,15.087,9.543c2.76,5.831,1.924,12.733-2.163,17.723l-50.087,61.217 c-3.305,4.038-8.097,6.125-12.935,6.125c-3.718,0-7.456-1.233-10.565-3.772c-7.13-5.842-8.185-16.358-2.347-23.494l27.783-33.951 H222.609z M339.478,478.609H172.522v-11.13c0-36.397,35.25-68.359,73.337-97.478c6-4.576,14.283-4.576,20.283,0 c38.086,29.119,73.336,61.082,73.336,97.478V478.609z\"/> </g> </g> </g>\n\r</svg>");

/***/ }),

/***/ "./style/icons/next.svg":
/*!******************************!*\
  !*** ./style/icons/next.svg ***!
  \******************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ("<svg stroke=\"black\" stroke-width=\"5\" class=\"jp-icon3\" fill=\"#616161\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" version=\"1.1\" x=\"0px\" y=\"0px\" viewBox=\"17 9 50 70\" enable-background=\"new 0 0 50 50\" xml:space=\"preserve\">\n    <polygon points=\"47.003,25 44.003,28.006 58.001,42 22,42 22,46 57.996,46 44,59.996 47,62.996 66.005,44.002 \"></polygon>\n</svg>");

/***/ }),

/***/ "./style/icons/reload-all.svg":
/*!************************************!*\
  !*** ./style/icons/reload-all.svg ***!
  \************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ("<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n\r<!-- Uploaded to: SVG Repo, www.svgrepo.com, Transformed by: SVG Repo Mixer Tools -->\n<svg width=\"800px\" height=\"800px\" viewBox=\"0 0 48 48\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\" transform=\"rotate(-45)\">\n\r<g id=\"SVGRepo_bgCarrier\" stroke-width=\"0\"/>\n\r<g id=\"SVGRepo_tracerCarrier\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>\n\r<g id=\"SVGRepo_iconCarrier\"> <rect x=\"17\" y=\"24.0711\" width=\"10\" height=\"10\" rx=\"2\" transform=\"rotate(-45 17 24.0711)\" fill=\"#FFFFFF\" stroke=\"#616161\" stroke-width=\"3.168\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/> <path d=\"M40.1201 16C37.1747 10.0731 31.0586 6 23.9912 6C16.9237 6 10.9454 10.0731 8 16\" stroke=\"#616161\" stroke-width=\"3.168\" stroke-linecap=\"round\"/> <path d=\"M8 8V16\" stroke=\"#616161\" stroke-width=\"3.168\" stroke-linecap=\"round\"/> <path d=\"M14.7803 16L8.00013 16\" stroke=\"#616161\" stroke-width=\"3.168\" stroke-linecap=\"round\"/> <path d=\"M8 32C10.9454 37.9269 17.0615 42 24.129 42C31.1964 42 37.1747 37.9269 40.1201 32\" stroke=\"#616161\" stroke-width=\"3.168\" stroke-linecap=\"round\"/> <path d=\"M40.1201 40V32\" stroke=\"#616161\" stroke-width=\"3.168\" stroke-linecap=\"round\"/> <path d=\"M33.3398 32L40.12 32\" stroke=\"#616161\" stroke-width=\"3.168\" stroke-linecap=\"round\"/> </g>\n\r</svg>");

/***/ }),

/***/ "./style/icons/revert.svg":
/*!********************************!*\
  !*** ./style/icons/revert.svg ***!
  \********************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<svg class=\"jp-icon3\" fill=\"#616161\" version=\"1.1\" viewBox=\"0 -55 1350 1350\" xmlns=\"http://www.w3.org/2000/svg\">\n <path d=\"m610.36 114.64c19.523 19.527 19.523 51.184 0 70.711l-64.645 64.645h79.289c232.61 0 425 192.39 425 425s-192.39 425-425 425-425-192.39-425-425c0-27.613 22.387-50 50-50s50 22.387 50 50c0 177.39 147.61 325 325 325s325-147.61 325-325-147.61-325-325-325h-79.289l64.645 64.645c19.523 19.527 19.523 51.184 0 70.711-19.527 19.523-51.184 19.523-70.711 0l-150-150c-19.527-19.527-19.527-51.184 0-70.711l150-150c19.527-19.527 51.184-19.527 70.711 0z\"/>\n</svg>\n");

/***/ }),

/***/ "./style/icons/xpress-logo.svg":
/*!*************************************!*\
  !*** ./style/icons/xpress-logo.svg ***!
  \*************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!-- Generator: Adobe Illustrator 25.0.1, SVG Export Plug-In . SVG Version: 6.00 Build 0)  -->\n<svg version=\"1.1\" id=\"Layer_1\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" x=\"0px\" y=\"0px\"\n\t viewBox=\"0 0 270 250\" style=\"enable-background:new 0 0 270 250;\" xml:space=\"preserve\">\n<style type=\"text/css\">\n\t.st0{fill:#3EA5BD;}\n\t.st1{fill:#324057;}\n</style>\n<g>\n\t<g>\n\t\t<g>\n\t\t\t<path class=\"st0\" d=\"M27.6,5.6c-7.2,0-13,5.8-13,13s5.8,13,13,13s13-5.8,13-13S34.7,5.6,27.6,5.6z\"/>\n\t\t\t<path class=\"st0\" d=\"M63,5.6c-7.2,0-13,5.8-13,13s5.8,13,13,13s13-5.8,13-13S70.2,5.6,63,5.6z\"/>\n\t\t\t<path class=\"st0\" d=\"M27.6,41c-7.2,0-13,5.8-13,13s5.8,13,13,13s13-5.8,13-13S34.7,41,27.6,41z\"/>\n\t\t\t<path class=\"st0\" d=\"M63,41c-7.2,0-13,5.8-13,13s5.8,13,13,13s13-5.8,13-13S70.2,41,63,41z\"/>\n\t\t\t<path class=\"st0\" d=\"M27.6,76.5c-7.2,0-13,5.8-13,13s5.8,13,13,13s13-5.8,13-13C40.5,82.3,34.7,76.5,27.6,76.5z\"/>\n\t\t\t<path class=\"st0\" d=\"M63,76.5c-7.2,0-13,5.8-13,13s5.8,13,13,13s13-5.8,13-13C76,82.3,70.2,76.5,63,76.5z\"/>\n\t\t\t<path class=\"st0\" d=\"M63,112c-7.2,0-13,5.8-13,13c0,7.2,5.8,13,13,13s13-5.8,13-13S70.2,112,63,112z\"/>\n\t\t\t<path class=\"st0\" d=\"M27.6,147.5c-7.2,0-13,5.8-13,13s5.8,13,13,13s13-5.8,13-13C40.5,153.3,34.7,147.5,27.6,147.5z\"/>\n\t\t\t<path class=\"st0\" d=\"M63,147.5c-7.2,0-13,5.8-13,13s5.8,13,13,13s13-5.8,13-13C76,153.3,70.2,147.5,63,147.5z\"/>\n\t\t\t<path class=\"st0\" d=\"M27.6,183c-7.2,0-13,5.8-13,13s5.8,13,13,13s13-5.8,13-13S34.7,183,27.6,183z\"/>\n\t\t\t<path class=\"st0\" d=\"M63,183c-7.2,0-13,5.8-13,13s5.8,13,13,13s13-5.8,13-13S70.2,183,63,183z\"/>\n\t\t\t<path class=\"st0\" d=\"M27.6,218.5c-7.2,0-13,5.8-13,13s5.8,13,13,13s13-5.8,13-13S34.7,218.5,27.6,218.5z\"/>\n\t\t\t<path class=\"st0\" d=\"M63,218.5c-7.2,0-13,5.8-13,13s5.8,13,13,13s13-5.8,13-13S70.2,218.5,63,218.5z\"/>\n\t\t\t<path class=\"st0\" d=\"M98.5,41c-7.2,0-13,5.8-13,13s5.8,13,13,13s13-5.8,13-13C111.5,46.9,105.7,41,98.5,41z\"/>\n\t\t\t<path class=\"st0\" d=\"M98.5,76.5c-7.2,0-13,5.8-13,13s5.8,13,13,13s13-5.8,13-13C111.5,82.3,105.7,76.5,98.5,76.5z\"/>\n\t\t\t<path class=\"st0\" d=\"M98.5,147.5c-7.2,0-13,5.8-13,13s5.8,13,13,13s13-5.8,13-13C111.5,153.3,105.7,147.5,98.5,147.5z\"/>\n\t\t\t<path class=\"st0\" d=\"M98.5,183c-7.2,0-13,5.8-13,13s5.8,13,13,13s13-5.8,13-13C111.5,188.8,105.7,183,98.5,183z\"/>\n\t\t</g>\n\t\t<g>\n\t\t\t<path class=\"st1\" d=\"M240.5,244.4c7.2,0,13-5.8,13-13s-5.8-13-13-13s-13,5.8-13,13S233.3,244.4,240.5,244.4z\"/>\n\t\t\t<path class=\"st1\" d=\"M205,244.4c7.2,0,13-5.8,13-13s-5.8-13-13-13s-13,5.8-13,13S197.8,244.4,205,244.4z\"/>\n\t\t\t<path class=\"st1\" d=\"M240.5,208.9c7.2,0,13-5.8,13-13s-5.8-13-13-13s-13,5.8-13,13S233.3,208.9,240.5,208.9z\"/>\n\t\t\t<path class=\"st1\" d=\"M205,208.9c7.2,0,13-5.8,13-13s-5.8-13-13-13s-13,5.8-13,13C192,203.1,197.8,208.9,205,208.9z\"/>\n\t\t\t<path class=\"st1\" d=\"M240.5,173.5c7.2,0,13-5.8,13-13s-5.8-13-13-13s-13,5.8-13,13C227.5,167.6,233.3,173.5,240.5,173.5z\"/>\n\t\t\t<path class=\"st1\" d=\"M205,173.5c7.2,0,13-5.8,13-13s-5.8-13-13-13s-13,5.8-13,13C192,167.6,197.8,173.5,205,173.5z\"/>\n\t\t\t<path class=\"st1\" d=\"M205,138c7.2,0,13-5.8,13-13s-5.8-13-13-13s-13,5.8-13,13C192,132.2,197.8,138,205,138z\"/>\n\t\t\t<path class=\"st1\" d=\"M240.5,102.5c7.2,0,13-5.8,13-13c0-7.2-5.8-13-13-13s-13,5.8-13,13C227.5,96.7,233.3,102.5,240.5,102.5z\"/>\n\t\t\t<path class=\"st1\" d=\"M205,102.5c7.2,0,13-5.8,13-13c0-7.2-5.8-13-13-13s-13,5.8-13,13C192,96.7,197.8,102.5,205,102.5z\"/>\n\t\t\t<path class=\"st1\" d=\"M240.5,67c7.2,0,13-5.8,13-13s-5.8-13-13-13s-13,5.8-13,13S233.3,67,240.5,67z\"/>\n\t\t\t<path class=\"st1\" d=\"M205,67c7.2,0,13-5.8,13-13s-5.8-13-13-13s-13,5.8-13,13C192,61.2,197.8,67,205,67z\"/>\n\t\t\t<path class=\"st1\" d=\"M240.5,31.5c7.2,0,13-5.8,13-13s-5.8-13-13-13s-13,5.8-13,13S233.3,31.5,240.5,31.5z\"/>\n\t\t\t<path class=\"st1\" d=\"M205,31.5c7.2,0,13-5.8,13-13s-5.8-13-13-13s-13,5.8-13,13S197.8,31.5,205,31.5z\"/>\n\t\t\t<path class=\"st1\" d=\"M169.5,208.9c7.2,0,13-5.8,13-13s-5.8-13-13-13s-13,5.8-13,13S162.3,208.9,169.5,208.9z\"/>\n\t\t\t<path class=\"st1\" d=\"M169.5,173.5c7.2,0,13-5.8,13-13s-5.8-13-13-13s-13,5.8-13,13C156.5,167.6,162.3,173.5,169.5,173.5z\"/>\n\t\t\t<path class=\"st1\" d=\"M169.5,138c7.2,0,13-5.8,13-13s-5.8-13-13-13s-13,5.8-13,13S162.3,138,169.5,138z\"/>\n\t\t\t<path class=\"st1\" d=\"M169.5,102.5c7.2,0,13-5.8,13-13c0-7.2-5.8-13-13-13s-13,5.8-13,13C156.5,96.7,162.3,102.5,169.5,102.5z\"/>\n\t\t\t<path class=\"st1\" d=\"M169.5,67c7.2,0,13-5.8,13-13s-5.8-13-13-13s-13,5.8-13,13S162.3,67,169.5,67z\"/>\n\t\t\t<path class=\"st1\" d=\"M134,173.5c7.2,0,13-5.8,13-13s-5.8-13-13-13s-13,5.8-13,13C121,167.6,126.8,173.5,134,173.5z\"/>\n\t\t\t<path class=\"st1\" d=\"M134,138c7.2,0,13-5.8,13-13s-5.8-13-13-13s-13,5.8-13,13C121,132.2,126.8,138,134,138z\"/>\n\t\t\t<path class=\"st1\" d=\"M134,102.5c7.2,0,13-5.8,13-13c0-7.2-5.8-13-13-13s-13,5.8-13,13C121,96.7,126.8,102.5,134,102.5z\"/>\n\t\t\t<path class=\"st1\" d=\"M98.5,138c7.2,0,13-5.8,13-13s-5.8-13-13-13s-13,5.8-13,13C85.6,132.2,91.4,138,98.5,138z\"/>\n\t\t</g>\n\t</g>\n</g>\n</svg>\n");

/***/ }),

/***/ "./lib/commands/CustomActionEvent.js":
/*!*******************************************!*\
  !*** ./lib/commands/CustomActionEvent.js ***!
  \*******************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "CustomActionEvent": () => (/* binding */ CustomActionEvent)
/* harmony export */ });
/* harmony import */ var _projectstorm_react_canvas_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @projectstorm/react-canvas-core */ "webpack/sharing/consume/default/@projectstorm/react-canvas-core/@projectstorm/react-canvas-core?4a30");
/* harmony import */ var _projectstorm_react_canvas_core__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_projectstorm_react_canvas_core__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../components/xircuitBodyWidget */ "./lib/components/xircuitBodyWidget.js");


class CustomActionEvent extends _projectstorm_react_canvas_core__WEBPACK_IMPORTED_MODULE_0__.Action {
    constructor(options) {
        super({
            type: _projectstorm_react_canvas_core__WEBPACK_IMPORTED_MODULE_0__.InputType.KEY_DOWN,
            fire: (event) => {
                const app = options.app;
                const keyCode = event.event.key;
                const ctrlKey = event.event.ctrlKey;
                const executeIf = (condition, command) => {
                    if (condition) {
                        // @ts-ignore
                        event.event.stopImmediatePropagation();
                        app.commands.execute(command);
                    }
                };
                // @ts-ignore
                if (app.shell._tracker._activeWidget && app.shell._tracker._activeWidget.node.contains(event.event.target)) {
                    executeIf(ctrlKey && keyCode === 'z', _components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_1__.commandIDs.undo);
                    executeIf(ctrlKey && keyCode === 'y', _components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_1__.commandIDs.redo);
                    executeIf(ctrlKey && keyCode === 's', _components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_1__.commandIDs.saveXircuit);
                    executeIf(ctrlKey && keyCode === 'x', _components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_1__.commandIDs.cutNode);
                    executeIf(ctrlKey && keyCode === 'c', _components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_1__.commandIDs.copyNode);
                    executeIf(ctrlKey && keyCode === 'v', _components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_1__.commandIDs.pasteNode);
                    executeIf(keyCode == 'Delete' || keyCode == 'Backspace', _components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_1__.commandIDs.deleteEntity);
                }
            }
        });
    }
}


/***/ }),

/***/ "./lib/commands/NodeActionCommands.js":
/*!********************************************!*\
  !*** ./lib/commands/NodeActionCommands.js ***!
  \********************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "addNodeActionCommands": () => (/* binding */ addNodeActionCommands)
/* harmony export */ });
/* harmony import */ var _components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../components/xircuitBodyWidget */ "./lib/components/xircuitBodyWidget.js");
/* harmony import */ var _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @projectstorm/react-diagrams */ "webpack/sharing/consume/default/@projectstorm/react-diagrams/@projectstorm/react-diagrams");
/* harmony import */ var _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _components_CustomNodeModel__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../components/CustomNodeModel */ "./lib/components/CustomNodeModel.js");
/* harmony import */ var _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @jupyterlab/apputils */ "webpack/sharing/consume/default/@jupyterlab/apputils");
/* harmony import */ var _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @jupyterlab/ui-components */ "webpack/sharing/consume/default/@jupyterlab/ui-components");
/* harmony import */ var _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _tray_library_AdvanceComponentLib__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../tray_library/AdvanceComponentLib */ "./lib/tray_library/AdvanceComponentLib.js");
/* harmony import */ var _dialog_formDialogwidget__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../dialog/formDialogwidget */ "./lib/dialog/formDialogwidget.js");
/* harmony import */ var _dialog_CommentDialog__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../dialog/CommentDialog */ "./lib/dialog/CommentDialog.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _dialog_FormDialog__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../dialog/FormDialog */ "./lib/dialog/FormDialog.js");
/* harmony import */ var _components_link_CustomLinkModel__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../components/link/CustomLinkModel */ "./lib/components/link/CustomLinkModel.js");
/* harmony import */ var _projectstorm_geometry__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @projectstorm/geometry */ "./node_modules/@projectstorm/geometry/dist/index.js");
/* harmony import */ var _projectstorm_geometry__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_projectstorm_geometry__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _tray_library_GeneralComponentLib__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../tray_library/GeneralComponentLib */ "./lib/tray_library/GeneralComponentLib.js");
/* harmony import */ var _components_port_CustomDynaPortModel__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../components/port/CustomDynaPortModel */ "./lib/components/port/CustomDynaPortModel.js");

















/**
 * Add the commands for node actions.
 */
function addNodeActionCommands(app, tracker, translator) {
    const trans = translator.load('jupyterlab');
    const { commands, shell } = app;
    /**
     * Whether there is an active xircuits.
     */
    function isEnabled() {
        return (tracker.currentWidget !== null &&
            tracker.currentWidget === shell.currentWidget);
    }
    function getLastSelectedNode() {
        var _a;
        const widget = (_a = tracker.currentWidget) === null || _a === void 0 ? void 0 : _a.content;
        const selectedEntities = widget.xircuitsApp.getDiagramEngine().getModel().getSelectedEntities();
        let node;
        selectedEntities.map((x) => node = x);
        return node !== null && node !== void 0 ? node : null;
    }
    //Add command to open node's script at specific line
    commands.addCommand(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_5__.commandIDs.openScript, {
        execute: async (args) => {
            var _a, _b, _c;
            const node = getLastSelectedNode();
            const nodePath = (_a = args['nodePath']) !== null && _a !== void 0 ? _a : node.extras.path;
            const nodeName = (_b = args['nodeName']) !== null && _b !== void 0 ? _b : node.name;
            const nodeLineNo = (_c = args['nodeLineNo']) !== null && _c !== void 0 ? _c : node.extras.lineNo;
            if (nodeName.startsWith('Literal') || nodeName.startsWith('Argument')) {
                (0,_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_1__.showDialog)({
                    title: `${node.name} don't have its own script`,
                    buttons: [_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_1__.Dialog.warnButton({ label: 'OK' })]
                });
                return;
            }
            // Open node's file name
            const newWidget = await app.commands.execute(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_5__.commandIDs.openDocManager, {
                path: nodePath
            });
            newWidget.context.ready.then(() => {
                // Go to end of node's line first before go to its class
                app.commands.execute('codemirror:go-to-line', {
                    line: nodeLineNo[0].end_lineno
                }).then(() => {
                    app.commands.execute('codemirror:go-to-line', {
                        line: nodeLineNo[0].lineno
                    });
                });
            });
        }
    });
    //Add command to undo
    commands.addCommand(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_5__.commandIDs.undo, {
        execute: () => {
            var _a;
            const widget = (_a = tracker.currentWidget) === null || _a === void 0 ? void 0 : _a.content;
            const model = widget.context.model.sharedModel;
            model.undo();
        },
        label: trans.__('Undo'),
        icon: _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_2__.undoIcon,
        isEnabled: () => {
            var _a;
            const widget = (_a = tracker.currentWidget) === null || _a === void 0 ? void 0 : _a.content;
            const canUndo = widget.context.model.sharedModel.canUndo();
            return canUndo !== null && canUndo !== void 0 ? canUndo : false;
        }
    });
    //Add command to redo
    commands.addCommand(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_5__.commandIDs.redo, {
        execute: () => {
            var _a;
            const widget = (_a = tracker.currentWidget) === null || _a === void 0 ? void 0 : _a.content;
            const model = widget.context.model.sharedModel;
            model.redo();
        },
        label: trans.__('Redo'),
        icon: _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_2__.redoIcon,
        isEnabled: () => {
            var _a;
            const widget = (_a = tracker.currentWidget) === null || _a === void 0 ? void 0 : _a.content;
            const canRedo = widget.context.model.sharedModel.canRedo();
            return canRedo !== null && canRedo !== void 0 ? canRedo : false;
        }
    });
    //Add command to cut node
    commands.addCommand(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_5__.commandIDs.cutNode, {
        execute: cutNode,
        label: trans.__('Cut'),
        icon: _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_2__.cutIcon,
        isEnabled: () => {
            var _a;
            const widget = (_a = tracker.currentWidget) === null || _a === void 0 ? void 0 : _a.content;
            const selectedEntities = widget.xircuitsApp.getDiagramEngine().getModel().getSelectedEntities();
            let isNodeSelected;
            if (selectedEntities.length > 0) {
                isNodeSelected = true;
            }
            return isNodeSelected !== null && isNodeSelected !== void 0 ? isNodeSelected : false;
        }
    });
    //Add command to copy node
    commands.addCommand(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_5__.commandIDs.copyNode, {
        execute: copyNode,
        label: trans.__('Copy'),
        icon: _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_2__.copyIcon,
        isEnabled: () => {
            var _a;
            const widget = (_a = tracker.currentWidget) === null || _a === void 0 ? void 0 : _a.content;
            const selectedEntities = widget.xircuitsApp.getDiagramEngine().getModel().getSelectedEntities();
            let isNodeSelected;
            if (selectedEntities.length > 0) {
                isNodeSelected = true;
            }
            return isNodeSelected !== null && isNodeSelected !== void 0 ? isNodeSelected : false;
        }
    });
    //Add command to paste node
    commands.addCommand(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_5__.commandIDs.pasteNode, {
        execute: pasteNode,
        label: trans.__('Paste'),
        icon: _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_2__.pasteIcon,
        isEnabled: () => {
            const clipboard = JSON.parse(localStorage.getItem('clipboard'));
            let isClipboardFilled;
            if (clipboard) {
                isClipboardFilled = true;
            }
            return isClipboardFilled !== null && isClipboardFilled !== void 0 ? isClipboardFilled : false;
        }
    });
    //Add command to edit literal component
    commands.addCommand(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_5__.commandIDs.editNode, {
        execute: editLiteral,
        label: trans.__('Edit'),
        isEnabled: () => {
            let isNodeSelected;
            const node = getLastSelectedNode();
            if (node.getOptions()["name"].startsWith("Literal")) {
                isNodeSelected = true;
            }
            return isNodeSelected !== null && isNodeSelected !== void 0 ? isNodeSelected : false;
        }
    });
    //Add command to delete entities
    commands.addCommand(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_5__.commandIDs.deleteEntity, {
        execute: deleteEntity,
        label: "Delete",
        isEnabled: () => {
            var _a;
            const widget = (_a = tracker.currentWidget) === null || _a === void 0 ? void 0 : _a.content;
            const selectedEntities = widget.xircuitsApp.getDiagramEngine().getModel().getSelectedEntities();
            let isNodeSelected;
            if (selectedEntities.length > 0) {
                isNodeSelected = true;
            }
            return isNodeSelected !== null && isNodeSelected !== void 0 ? isNodeSelected : false;
        }
    });
    // Add command to reload selected node
    commands.addCommand(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_5__.commandIDs.reloadNode, {
        execute: async () => {
            var _a;
            const widget = (_a = tracker.currentWidget) === null || _a === void 0 ? void 0 : _a.content;
            const engine = widget.xircuitsApp.getDiagramEngine();
            const model = engine.getModel();
            const selected_entities = model.getSelectedEntities();
            const selected_nodes = selected_entities.filter(entity => entity instanceof _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_0__.NodeModel);
            const nodesToRemove = [];
            const linksToRemove = [];
            const nodesToHighlight = [];
            for (let selected_node of selected_nodes) {
                if (selected_node.name.startsWith("Literal") ||
                    selected_node.name.startsWith("Argument") ||
                    selected_node.name.startsWith("Start") ||
                    selected_node.name.startsWith("Finish")) {
                    console.info(selected_node.name + " cannot be reloaded.");
                    continue;
                }
                let current_node = await (0,_tray_library_AdvanceComponentLib__WEBPACK_IMPORTED_MODULE_6__.fetchNodeByName)(selected_node.name);
                let node;
                try {
                    node = (0,_tray_library_AdvanceComponentLib__WEBPACK_IMPORTED_MODULE_6__.AdvancedComponentLibrary)({ model: current_node });
                }
                catch (error) {
                    let path = selected_node.getOptions()["extras"].path;
                    console.log(`Error reloading component from path: ${path}. Error: ${error.message}`);
                    selected_node.getOptions().extras["tip"] = `Component could not be loaded from path: \`${path}\`.\nPlease ensure that the component exists!`;
                    selected_node.getOptions().extras["borderColor"] = "red";
                    nodesToHighlight.push(selected_node);
                    continue;
                }
                let nodePositionX = selected_node.getX();
                let nodePositionY = selected_node.getY();
                // Add node at given position
                node.setPosition(nodePositionX, nodePositionY);
                engine.getModel().addNode(node);
                try {
                    // get the old ports
                    let ports = selected_node.getPorts();
                    for (let portName in ports) {
                        let port = ports[portName];
                        for (let linkID in port.links) {
                            let link = port.links[linkID];
                            if (link.getSourcePort() === port) {
                                let sourcePortName = link.getSourcePort().getName();
                                let newSourcePort = node.getPorts()[sourcePortName];
                                if (newSourcePort) {
                                    link.setSourcePort(newSourcePort);
                                }
                                else {
                                    console.log(`Source port '${sourcePortName}' not found in reloaded node '${node.name}'.`);
                                    linksToRemove.push(link);
                                    continue;
                                }
                            }
                            else if (link.getTargetPort() === port) {
                                let targetPort = link.getTargetPort();
                                let targetPortName = targetPort.getName();
                                let newTargetPort = node.getPorts()[targetPortName];
                                if (!newTargetPort) {
                                    console.log(`Target port '${targetPortName}' not found in reloaded node '${node.name}'.`);
                                    linksToRemove.push(link);
                                    continue;
                                }
                                if (targetPort instanceof _components_port_CustomDynaPortModel__WEBPACK_IMPORTED_MODULE_7__.CustomDynaPortModel) {
                                    const newPort = newTargetPort.spawnDynamicPort({ offset: 1 });
                                    newPort.previous = newTargetPort.getID();
                                    newTargetPort.next = newPort.getID();
                                }
                                link.setTargetPort(newTargetPort);
                            }
                            engine.getModel().addLink(link);
                        }
                    }
                }
                catch (error) {
                    // Code to handle the exception
                    console.log('An error occurred:', error.message);
                }
                finally {
                    // Add old node to nodesToRemove
                    nodesToRemove.push(selected_node);
                }
            }
            // Remove old nodes and links
            for (const nodeToRemove of nodesToRemove) {
                engine.getModel().removeNode(nodeToRemove);
            }
            for (const linkToRemove of linksToRemove) {
                engine.getModel().removeLink(linkToRemove);
            }
            // Repaint canvas
            selected_nodes.forEach(node => node.setSelected(false));
            nodesToHighlight.forEach(node => node.setSelected(true));
            pruneLooseLinks(model);
            engine.repaintCanvas();
        },
        label: trans.__('Reload node')
    });
    function pruneLooseLinks(model) {
        const links = model.getLinks();
        // Iterate over all links and prune those that do not have either a source or a target port
        Object.values(links).forEach(link => {
            if (!link.getSourcePort() || !link.getTargetPort()) {
                model.removeLink(link);
            }
        });
    }
    //Add command to add node given position
    commands.addCommand(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_5__.commandIDs.addNodeGivenPosition, {
        execute: (args) => {
            var _a;
            const node = args['node'];
            const nodePosition = args['nodePosition'];
            const widget = (_a = tracker.currentWidget) === null || _a === void 0 ? void 0 : _a.content;
            const canvasNodePosition = widget.xircuitsApp.getDiagramEngine().getRelativeMousePoint(nodePosition);
            node.setPosition(canvasNodePosition);
            widget.xircuitsApp.getDiagramEngine().getModel().addNode(node);
        },
        label: trans.__('Add node')
    });
    //Add command to connect node given link
    commands.addCommand(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_5__.commandIDs.connectNodeByLink, {
        execute: (args) => {
            var _a;
            const targetNode = args['targetNode'];
            const sourceLink = args['sourceLink'];
            const isParameterLink = args['isParameterLink'];
            const widget = (_a = tracker.currentWidget) === null || _a === void 0 ? void 0 : _a.content;
            // Create new link to connect to new node automatically
            let newLink = new _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_0__.DefaultLinkModel();
            let sourcePort;
            let targetPort;
            // Get source link node port
            const linkPort = sourceLink.sourcePort;
            // When '▶' of sourcePort from inPort, connect to '▶' outPort of target node
            if (linkPort.getOptions()['name'] == "in-0") {
                sourcePort = targetNode.getPorts()["out-0"];
                targetPort = linkPort;
            }
            else if (isParameterLink) {
                // When looseLink is connected to parameter node
                const parameterNodeName = targetNode.getOutPorts()[0].getOptions()['name'];
                sourcePort = targetNode.getPorts()[parameterNodeName];
                targetPort = linkPort;
            }
            else {
                // '▶' of sourcePort to '▶' of targetPort
                sourcePort = linkPort;
                targetPort = targetNode.getPorts()["in-0"];
                app.commands.execute(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_5__.commandIDs.connectLinkToObviousPorts, { droppedSourceLink: sourceLink, targetNode });
            }
            newLink.setSourcePort(sourcePort);
            newLink.setTargetPort(targetPort);
            widget.xircuitsApp.getDiagramEngine().getModel().addLink(newLink);
        },
        label: trans.__('Link node')
    });
    //Add command to connect link to obvious port given link and target node
    commands.addCommand(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_5__.commandIDs.connectLinkToObviousPorts, {
        execute: (args) => {
            var _a, _b;
            const widget = (_a = tracker.currentWidget) === null || _a === void 0 ? void 0 : _a.content;
            const draggedLink = args['draggedLink'];
            const droppedSourceLink = args['droppedSourceLink'];
            // Check whether link is dropped or dragged
            const sourcePort = droppedSourceLink == undefined ? draggedLink.getSourcePort() : droppedSourceLink.sourcePort;
            const targetPort = droppedSourceLink == undefined ? draggedLink.getTargetPort() : droppedSourceLink.link.getTargetPort();
            const sourceNode = sourcePort.getNode();
            const targetNode = (_b = args['targetNode']) !== null && _b !== void 0 ? _b : targetPort.getNode();
            const outPorts = sourceNode['portsOut'];
            const inPorts = targetNode['portsIn'];
            if ((sourcePort === null || sourcePort === void 0 ? void 0 : sourcePort.getOptions()['label']) != '▶' && (targetPort === null || targetPort === void 0 ? void 0 : targetPort.getOptions()['label']) != '▶') {
                // When it's not ▶ being linked, just return
                return;
            }
            if (sourceNode['portsOut'].length <= 1) {
                // When node got no outputPort, just return
                return;
            }
            for (let outPortIndex in outPorts) {
                const outPort = outPorts[outPortIndex];
                const outPortName = outPort.getOptions()['name'];
                const outPortLabel = outPort.getOptions()['label'];
                const outPortType = outPort.getOptions()['type'];
                const outPortLabelArr = outPortLabel.split('_');
                if (outPort.getOptions()['label'] == '▶') {
                    // Skip ▶ outPort
                    continue;
                }
                ;
                for (let inPortIndex in inPorts) {
                    const inPort = inPorts[inPortIndex];
                    const inPortName = inPort.getOptions()['name'];
                    const inPortLabel = inPort.getOptions()['label'];
                    const inPortType = inPort.getOptions()['type'];
                    const inPortLabelArr = inPortLabel.split('_');
                    // Compare if there is similarity for each word
                    const intersection = outPortLabelArr.filter(element => inPortLabelArr.includes(element));
                    if (outPortLabel == inPortLabel && outPortType == inPortType || intersection.length >= 1) {
                        // Create new link
                        const newLink = new _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_0__.DefaultLinkModel();
                        // Set sourcePort
                        const sourcePort = sourceNode.getPorts()[outPortName];
                        newLink.setSourcePort(sourcePort);
                        // Set targetPort
                        const targetPort = targetNode.getPorts()[inPortName];
                        newLink.setTargetPort(targetPort);
                        widget.xircuitsApp.getDiagramEngine().getModel().addLink(newLink);
                        break;
                    }
                }
            }
        },
        label: trans.__('Link obvious ports')
    });
    //Add command to add comment node at given position
    commands.addCommand(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_5__.commandIDs.addCommentNode, {
        execute: async (args) => {
            var _a;
            const widget = (_a = tracker.currentWidget) === null || _a === void 0 ? void 0 : _a.content;
            const dialogOptions = {
                body: (0,_dialog_formDialogwidget__WEBPACK_IMPORTED_MODULE_8__.formDialogWidget)(react__WEBPACK_IMPORTED_MODULE_3___default().createElement(_dialog_CommentDialog__WEBPACK_IMPORTED_MODULE_9__.CommentDialog, { commentInput: "" })),
                buttons: [_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_1__.Dialog.cancelButton(), _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_1__.Dialog.okButton({ label: ('Submit') })]
            };
            // Prompt the user to enter input for commenting
            const dialogResult = await (0,_dialog_FormDialog__WEBPACK_IMPORTED_MODULE_10__.showFormDialog)(dialogOptions);
            if (dialogResult["button"]["label"] == 'Cancel') {
                // When Cancel is clicked on the dialog, just return
                return false;
            }
            const commentVal = dialogResult["value"][''];
            let node = new _components_CustomNodeModel__WEBPACK_IMPORTED_MODULE_11__.CustomNodeModel({ name: 'Comment:', color: 'rgb(255,255,255)', extras: { "type": 'comment', 'commentInput': commentVal } });
            const nodePosition = args['nodePosition'];
            node.setPosition(nodePosition);
            widget.xircuitsApp.getDiagramEngine().getModel().addNode(node);
        },
        label: trans.__('Add Comment')
    });
    function cutNode() {
        var _a;
        const widget = (_a = tracker.currentWidget) === null || _a === void 0 ? void 0 : _a.content;
        if (!widget)
            return;
        const engine = widget.xircuitsApp.getDiagramEngine();
        const selected = widget.xircuitsApp.getDiagramEngine().getModel().getSelectedEntities();
        const copies = selected.map(entity => entity.serialize());
        selected.forEach(node => node.remove());
        engine.repaintCanvas();
        localStorage.setItem('clipboard', JSON.stringify(copies));
    }
    function copyNode() {
        var _a;
        const widget = (_a = tracker.currentWidget) === null || _a === void 0 ? void 0 : _a.content;
        if (!widget)
            return;
        const copies = widget.xircuitsApp.getDiagramEngine().getModel().getSelectedEntities().map(entity => entity.serialize());
        localStorage.setItem('clipboard', JSON.stringify(copies));
    }
    function pasteNode() {
        var _a;
        const widget = (_a = tracker.currentWidget) === null || _a === void 0 ? void 0 : _a.content;
        if (!widget)
            return;
        const engine = widget.xircuitsApp.getDiagramEngine();
        const model = engine.getModel();
        const clipboard = JSON.parse(localStorage.getItem('clipboard'));
        if (!clipboard)
            return;
        model.clearSelection();
        const newNodeModels = [];
        let idMap = {};
        const clipboardNodes = clipboard.filter(serialized => serialized.type.includes('node'));
        const clipboardLinks = clipboard.filter(serialized => serialized.type.includes('link'));
        let totalX = 0, totalY = 0, nodesCount = clipboardNodes.length;
        clipboardNodes.forEach(serializedNode => {
            if (serializedNode.name === 'Start' || serializedNode.name === 'Finish') {
                console.log(serializedNode.name, " cannot be copied!");
                return;
            }
            let originalNodeInstance = model.getNodes().find(node => node.getID() === serializedNode.id);
            let clonedNodeModelInstance;
            if (originalNodeInstance) {
                clonedNodeModelInstance = originalNodeInstance.clone();
            }
            else {
                clonedNodeModelInstance = createNewNodeInstance(model, engine, serializedNode);
            }
            newNodeModels.push(clonedNodeModelInstance);
            idMap = mapNodeAndPortIds(serializedNode, clonedNodeModelInstance, idMap);
            totalX += clonedNodeModelInstance.getX();
            totalY += clonedNodeModelInstance.getY();
        });
        // Calculate the center of the group of nodes.
        const centerX = totalX / nodesCount;
        const centerY = totalY / nodesCount;
        placeNodes(engine, model, newNodeModels, widget.mousePosition, centerX, centerY);
        recreateLinks(engine, model, clipboardLinks, idMap, widget.mousePosition, centerX, centerY);
        engine.repaintCanvas();
    }
    function createNewNodeInstance(model, engine, serializedNode) {
        const clonedNodeModelInstance = model.getActiveNodeLayer()
            .getChildModelFactoryBank(engine)
            .getFactory(serializedNode.type)
            .generateModel({ initialConfig: serializedNode });
        clonedNodeModelInstance.deserialize({
            engine: engine,
            data: serializedNode,
            registerModel: () => { },
            getModel: function (id) {
                throw new Error('Function not implemented.');
            }
        });
        return clonedNodeModelInstance;
    }
    function mapNodeAndPortIds(serializedNode, clonedNodeModelInstance, idMap) {
        // Map the ID of the serialized node to the ID of the cloned node instance.
        idMap[serializedNode.id] = clonedNodeModelInstance.getID();
        // For each serialized port in the serialized node...
        serializedNode.ports.forEach(serializedPort => {
            // ...find the corresponding port in the cloned node instance by comparing names.
            const correspondingNewPort = Object.values(clonedNodeModelInstance.getPorts()).find((newPort) => newPort.getName() === serializedPort.name);
            // If the corresponding port exists, map the ID of the serialized port to the ID of the cloned port.
            if (correspondingNewPort)
                idMap[serializedPort.id] = correspondingNewPort.getID();
        });
        // Return the updated ID map.
        return idMap;
    }
    function placeNodes(engine, model, newNodeModels, mousePosition, centerX, centerY) {
        let clientMouseEvent = { clientX: mousePosition.x, clientY: mousePosition.y };
        let relativeMousePosition = engine.getRelativeMousePoint(clientMouseEvent);
        newNodeModels.forEach((modelInstance) => {
            // Get the offset position of the node relative to the group's center
            let nodeOffsetX = modelInstance.getX() - centerX;
            let nodeOffsetY = modelInstance.getY() - centerY;
            modelInstance.setPosition(relativeMousePosition.x + nodeOffsetX, relativeMousePosition.y + nodeOffsetY);
            model.addNode(modelInstance);
            if (modelInstance.getOptions()['type'] === 'default') {
                model.removeNode(modelInstance);
            }
            modelInstance.setSelected(true);
        });
    }
    function recreateLinks(engine, model, clipboardLinks, idMap, mousePosition, centerX, centerY) {
        clipboardLinks.forEach(serializedLink => {
            const newSourceID = idMap[serializedLink.sourcePort];
            const newTargetID = idMap[serializedLink.targetPort];
            if (newSourceID && newTargetID) {
                const { sourcePort, targetPort } = getSourceAndTargetPorts(model, newSourceID, newTargetID);
                if (sourcePort && targetPort)
                    recreateLink(engine, model, serializedLink, sourcePort, targetPort, mousePosition, centerX, centerY);
            }
        });
    }
    function getSourceAndTargetPorts(model, newSourceID, newTargetID) {
        let sourcePort, targetPort;
        model.getSelectedEntities().forEach((entity) => {
            if (entity instanceof _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_0__.NodeModel) {
                if (entity.getPortFromID(newSourceID))
                    sourcePort = entity.getPortFromID(newSourceID);
                if (entity.getPortFromID(newTargetID))
                    targetPort = entity.getPortFromID(newTargetID);
            }
        });
        return { sourcePort, targetPort };
    }
    function recreateLink(engine, model, serializedLink, sourcePort, targetPort, mousePosition, centerX, centerY) {
        let originalLink = model.getLinks().find(link => link.getID() === serializedLink.id);
        let clonedLink;
        let points = [];
        let clientMouseEvent = { clientX: mousePosition.x, clientY: mousePosition.y };
        let relativeMousePosition = engine.getRelativeMousePoint(clientMouseEvent);
        if (originalLink) {
            clonedLink = originalLink.clone();
        }
        else {
            clonedLink = createNewLink(serializedLink);
            points = serializedLink.points.map(point => new _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_0__.PointModel({ id: point.id, link: clonedLink, position: new _projectstorm_geometry__WEBPACK_IMPORTED_MODULE_4__.Point(point.x, point.y) }));
        }
        clonedLink.setSourcePort(sourcePort);
        clonedLink.setTargetPort(targetPort);
        clonedLink.setSelected(true);
        if (points.length > 0)
            clonedLink.setPoints(points);
        clonedLink.getPoints().forEach((point) => {
            // Adjust each point's position relative to the group's center
            let pointOffsetX = point.getX() - centerX;
            let pointOffsetY = point.getY() - centerY;
            point.setPosition(relativeMousePosition.x + pointOffsetX, relativeMousePosition.y + pointOffsetY);
            point.setSelected(true);
        });
        model.addLink(clonedLink);
    }
    function createNewLink(serializedLink) {
        if (serializedLink.type === 'parameter-link')
            return new _components_link_CustomLinkModel__WEBPACK_IMPORTED_MODULE_12__.ParameterLinkModel(serializedLink);
        else if (serializedLink.type === 'triangle-link')
            return new _components_link_CustomLinkModel__WEBPACK_IMPORTED_MODULE_12__.TriangleLinkModel(serializedLink);
    }
    async function editLiteral() {
        var _a;
        const widget = (_a = tracker.currentWidget) === null || _a === void 0 ? void 0 : _a.content;
        if (widget) {
            const selected_node = getLastSelectedNode();
            if (!selected_node.getOptions()["name"].startsWith("Literal")) {
                (0,_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_1__.showDialog)({
                    title: 'Only Literal Node can be edited',
                    buttons: [_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_1__.Dialog.warnButton({ label: 'OK' })]
                });
                return;
            }
            let node = null;
            const links = widget.xircuitsApp.getDiagramEngine().getModel()["layers"][0]["models"];
            const literalType = selected_node["extras"]["type"];
            let oldValue = selected_node.getPorts()["out-0"].getOptions()["label"];
            if (literalType == "chat") {
                oldValue = JSON.parse(oldValue);
            }
            const updateTitle = `Update ${literalType}`;
            let updatedContent = await (0,_tray_library_GeneralComponentLib__WEBPACK_IMPORTED_MODULE_13__.handleLiteralInput)(selected_node["name"], { color: selected_node["color"], type: selected_node["extras"]["type"] }, oldValue, literalType, updateTitle);
            if (!updatedContent) {
                // handle case where Cancel was clicked or an error occurred
                return;
            }
            node = updatedContent;
            // Set new node to old node position
            let position = selected_node.getPosition();
            node.setPosition(position);
            widget.xircuitsApp.getDiagramEngine().getModel().addNode(node);
            // Update the links
            for (let linkID in links) {
                let link = links[linkID];
                if (link["sourcePort"] && link["targetPort"]) {
                    let newLink = new _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_0__.DefaultLinkModel();
                    let sourcePort = node.getPorts()["out-0"];
                    newLink.setSourcePort(sourcePort);
                    // This to make sure the new link came from the same literal node as previous link
                    let sourceLinkNodeId = link["sourcePort"].getParent().getID();
                    let sourceNodeId = selected_node.getOptions()["id"];
                    if (sourceLinkNodeId == sourceNodeId) {
                        newLink.setTargetPort(link["targetPort"]);
                    }
                    widget.xircuitsApp.getDiagramEngine().getModel().addLink(newLink);
                }
            }
            // Remove old node
            selected_node.remove();
            widget.xircuitsApp.getDiagramEngine().repaintCanvas();
        }
    }
    function deleteEntity() {
        var _a;
        const widget = (_a = tracker.currentWidget) === null || _a === void 0 ? void 0 : _a.content;
        if (widget) {
            const selectedEntities = widget.xircuitsApp.getDiagramEngine().getModel().getSelectedEntities();
            const model = widget.xircuitsApp.getDiagramEngine().getModel();
            // Separate collections for nodes and links
            let nodes = [];
            let links = [];
            let points = [];
            // Separating nodes and links
            selectedEntities.forEach((entity) => {
                if (entity instanceof _components_CustomNodeModel__WEBPACK_IMPORTED_MODULE_11__.CustomNodeModel) {
                    nodes.push(entity);
                }
                else if (entity instanceof _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_0__.LinkModel) {
                    links.push(entity);
                }
                else if (entity instanceof _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_0__.PointModel) {
                    points.push(entity);
                }
            });
            // Processing Links
            links.forEach((link) => {
                const port = link.getTargetPort();
                if (port instanceof _components_port_CustomDynaPortModel__WEBPACK_IMPORTED_MODULE_7__.CustomDynaPortModel) {
                    port.shiftPorts({ shouldShiftBack: true }); // delete
                }
                link.remove();
            });
            // Processing Points
            points.forEach((point) => {
                point.remove();
            });
            // Processing Nodes
            nodes.forEach((node) => {
                // Before deleting the node, Check each outPort's links and their targetPorts
                node.getOutPorts().forEach((outPort) => {
                    const outPortLinks = outPort.getLinks();
                    for (let linkId in outPortLinks) {
                        const link = model.getLink(linkId);
                        const targetPort = link.getTargetPort();
                        if (targetPort instanceof _components_port_CustomDynaPortModel__WEBPACK_IMPORTED_MODULE_7__.CustomDynaPortModel) {
                            targetPort.shiftPorts({ shouldShiftBack: true }); // delete
                        }
                    }
                });
                if (node.getOptions()["name"] !== "undefined") {
                    let modelName = node.getOptions()["name"];
                    const errorMsg = `${modelName} node cannot be deleted!`;
                    if (modelName !== 'Start' && modelName !== 'Finish') {
                        if (!node.isLocked()) {
                            node.remove();
                        }
                        else {
                            (0,_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_1__.showDialog)({
                                title: 'Locked Node',
                                body: errorMsg,
                                buttons: [_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_1__.Dialog.warnButton({ label: 'OK' })]
                            });
                        }
                    }
                    else {
                        (0,_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_1__.showDialog)({
                            title: 'Undeletable Node',
                            body: errorMsg,
                            buttons: [_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_1__.Dialog.warnButton({ label: 'OK' })]
                        });
                    }
                }
            });
            widget.xircuitsApp.getDiagramEngine().repaintCanvas();
        }
    }
}


/***/ }),

/***/ "./lib/components/CustomNodeFactory.js":
/*!*********************************************!*\
  !*** ./lib/components/CustomNodeFactory.js ***!
  \*********************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "CustomNodeFactory": () => (/* binding */ CustomNodeFactory)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _CustomNodeModel__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./CustomNodeModel */ "./lib/components/CustomNodeModel.js");
/* harmony import */ var _projectstorm_react_canvas_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @projectstorm/react-canvas-core */ "webpack/sharing/consume/default/@projectstorm/react-canvas-core/@projectstorm/react-canvas-core?4a30");
/* harmony import */ var _projectstorm_react_canvas_core__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_projectstorm_react_canvas_core__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _CustomNodeWidget__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./CustomNodeWidget */ "./lib/components/CustomNodeWidget.js");




class CustomNodeFactory extends _projectstorm_react_canvas_core__WEBPACK_IMPORTED_MODULE_1__.AbstractReactFactory {
    constructor(app, shell) {
        super('custom-node');
        this.app = app;
        this.shell = shell;
    }
    generateModel(initialConfig) {
        return new _CustomNodeModel__WEBPACK_IMPORTED_MODULE_2__.CustomNodeModel();
    }
    generateReactWidget(event) {
        return react__WEBPACK_IMPORTED_MODULE_0__.createElement(_CustomNodeWidget__WEBPACK_IMPORTED_MODULE_3__.CustomNodeWidget, { engine: this.engine, node: event.model, app: this.app, shell: this.shell });
    }
}


/***/ }),

/***/ "./lib/components/CustomNodeModel.js":
/*!*******************************************!*\
  !*** ./lib/components/CustomNodeModel.js ***!
  \*******************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "CustomNodeModel": () => (/* binding */ CustomNodeModel)
/* harmony export */ });
/* harmony import */ var _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @projectstorm/react-diagrams */ "webpack/sharing/consume/default/@projectstorm/react-diagrams/@projectstorm/react-diagrams");
/* harmony import */ var _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _port_CustomPortModel__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./port/CustomPortModel */ "./lib/components/port/CustomPortModel.js");
/* harmony import */ var _port_CustomDynaPortModel__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./port/CustomDynaPortModel */ "./lib/components/port/CustomDynaPortModel.js");



class CustomNodeModel extends _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_0__.DefaultNodeModel {
    constructor(options = {}) {
        super(Object.assign(Object.assign({}, options), { type: 'custom-node' }));
        this.color = options.color || 'red';
        this.name = options.name || '';
        this.extras = options.extras || {};
    }
    serialize() {
        return Object.assign(Object.assign({}, super.serialize()), { color: this.color, name: this.name, extras: this.extras });
    }
    deserialize(event) {
        super.deserialize(event);
        this.color = event.data.color;
        this.name = event.data.name;
        this.extras = event.data.extras;
    }
    addOutPortEnhance({ label, name, order = null, id, dataType }) {
        //check if portID is passed, if not SR will generate a new port ID
        const p = (id) ? new _port_CustomPortModel__WEBPACK_IMPORTED_MODULE_1__.CustomPortModel({ in: false, name: name, label: label, id: id, dataType: dataType }) :
            new _port_CustomPortModel__WEBPACK_IMPORTED_MODULE_1__.CustomPortModel({ in: false, name: name, label: label, dataType: dataType });
        if (order !== null) {
            this.portsOut.splice(order, 0, p);
        }
        return this.addPort(p);
    }
    addInPortEnhance({ label, name, varName = label, order = null, id, dataType, dynaPortOrder = 0, dynaPortRef = { previous: null, next: null } }) {
        // // Check if portID is passed, if not SR will generate a new port ID
        let p;
        if (_port_CustomDynaPortModel__WEBPACK_IMPORTED_MODULE_2__.DYNAMIC_PARAMETER_NODE_TYPES.includes(dataType || '')) {
            p = (id)
                ? new _port_CustomDynaPortModel__WEBPACK_IMPORTED_MODULE_2__.CustomDynaPortModel({ in: true, name: name, varName: varName, label: label, id: id, dataType: dataType, dynaPortOrder, dynaPortRef })
                : new _port_CustomDynaPortModel__WEBPACK_IMPORTED_MODULE_2__.CustomDynaPortModel({ in: true, name: name, varName: varName, label: label, dataType: dataType, dynaPortOrder, dynaPortRef });
        }
        else {
            p = (id)
                ? new _port_CustomPortModel__WEBPACK_IMPORTED_MODULE_1__.CustomPortModel({ in: true, name: name, varName: varName, label: label, id: id, dataType: dataType })
                : new _port_CustomPortModel__WEBPACK_IMPORTED_MODULE_1__.CustomPortModel({ in: true, name: name, varName: varName, label: label, dataType: dataType });
        }
        if (order !== null) {
            this.portsIn.splice(order, 0, p);
        }
        return this.addPort(p);
    }
}


/***/ }),

/***/ "./lib/components/CustomNodeWidget.js":
/*!********************************************!*\
  !*** ./lib/components/CustomNodeWidget.js ***!
  \********************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "CustomNodeWidget": () => (/* binding */ CustomNodeWidget)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _emotion_styled__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @emotion/styled */ "webpack/sharing/consume/default/@emotion/styled/@emotion/styled?2715");
/* harmony import */ var _emotion_styled__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_emotion_styled__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var react_toggle__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! react-toggle */ "webpack/sharing/consume/default/react-toggle/react-toggle");
/* harmony import */ var react_toggle__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(react_toggle__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./xircuitBodyWidget */ "./lib/components/xircuitBodyWidget.js");
/* harmony import */ var _port_CustomPortLabel__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./port/CustomPortLabel */ "./lib/components/port/CustomPortLabel.js");
/* harmony import */ var _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @jupyterlab/apputils */ "webpack/sharing/consume/default/@jupyterlab/apputils");
/* harmony import */ var _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _dialog_formDialogwidget__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../dialog/formDialogwidget */ "./lib/dialog/formDialogwidget.js");
/* harmony import */ var _dialog_FormDialog__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../dialog/FormDialog */ "./lib/dialog/FormDialog.js");
/* harmony import */ var _dialog_CommentDialog__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../dialog/CommentDialog */ "./lib/dialog/CommentDialog.js");
/* harmony import */ var react_tooltip__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! react-tooltip */ "webpack/sharing/consume/default/react-tooltip/react-tooltip");
/* harmony import */ var react_tooltip__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(react_tooltip__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var marked__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! marked */ "webpack/sharing/consume/default/marked/marked");
/* harmony import */ var marked__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(marked__WEBPACK_IMPORTED_MODULE_6__);












var S;
(function (S) {
    S.Node = (_emotion_styled__WEBPACK_IMPORTED_MODULE_2___default().div) `
		background-color: ${(p) => p.background};
		border-radius: 5px;
		font-family: sans-serif;
		color: white;
		border: solid 2px black;
		overflow: visible;
		font-size: 11px;
		border: solid 2px ${(p) => (p.selected ? (p.borderColor == undefined ? 'rgb(0,192,255)' : p.borderColor) : 'black')};
	`;
    S.Title = (_emotion_styled__WEBPACK_IMPORTED_MODULE_2___default().div) `
		background: rgba(0, 0, 0, 0.3);
		display: flex;
		white-space: nowrap;
		justify-items: center;
	`;
    S.TitleName = (_emotion_styled__WEBPACK_IMPORTED_MODULE_2___default().div) `
		flex-grow: 1;
		padding: 5px 5px;
	`;
    S.CommentContainer = (_emotion_styled__WEBPACK_IMPORTED_MODULE_2___default().div) `
        background: rgba(0, 0, 0, 0.3);
        border-radius: 5px;
		font-family: sans-serif;
		color: rgb(255, 255, 255);
		border: solid 2px black;
		font-size: 12px;
        border: solid 2px ${(p) => p.selected ? 'rgb(0,192,255)' : 'black'};
        padding: 5px;
    `;
    S.DescriptionName = (_emotion_styled__WEBPACK_IMPORTED_MODULE_2___default().div) `
        color: ${(p) => { var _a; return (_a = p.color) !== null && _a !== void 0 ? _a : 'rgb(0, 0, 0)'; }};
        text-align: justify;
        font-family: 'Roboto', sans-serif;
        font-weight: 700;
        font-size: 13px;
	`;
    S.Ports = (_emotion_styled__WEBPACK_IMPORTED_MODULE_2___default().div) `
		display: flex;
		background-image: linear-gradient(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.2));
	`;
    S.PortsContainer = (_emotion_styled__WEBPACK_IMPORTED_MODULE_2___default().div) `
        max-width: 640px;
        white-space: pre;
		flex-grow: 1;
		display: flex;
		flex-direction: column;

		&:first-of-type {
			margin-right: 10px;
		}

		&:only-child {
			margin-right: 0px;
		}
	`;
})(S || (S = {}));
/**
 * Default node that models the DefaultNodeModel. It creates two columns
 * for both all the input ports on the left, and the output ports on the right.
 */
class CustomNodeWidget extends react__WEBPACK_IMPORTED_MODULE_0__.Component {
    constructor() {
        super(...arguments);
        this.generatePort = (port) => {
            return react__WEBPACK_IMPORTED_MODULE_0__.createElement(_port_CustomPortLabel__WEBPACK_IMPORTED_MODULE_7__.CustomPortLabel, { engine: this.props.engine, port: port, key: port.getID(), node: this.props.node });
        };
        this.state = {
            isTooltipActive: false,
            nodeDeletable: false,
            commentInput: this.props.node['extras']['commentInput'],
            showDescription: false,
            descriptionStr: "",
        };
        /**
         * load more data from server when page changed
         * @param e
         */
        this.onPageChanged = e => {
            console.log(e.currentPage);
        };
        this.dialogOptions = {
            body: (0,_dialog_formDialogwidget__WEBPACK_IMPORTED_MODULE_8__.formDialogWidget)(react__WEBPACK_IMPORTED_MODULE_0__.createElement(_dialog_CommentDialog__WEBPACK_IMPORTED_MODULE_9__.CommentDialog, { commentInput: this.state.commentInput })),
            buttons: [_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_4__.Dialog.cancelButton(), _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_4__.Dialog.okButton({ label: ('Submit') })],
            focusNodeSelector: 'textarea'
        };
        this.renderText = text => {
            var renderer = new marked__WEBPACK_IMPORTED_MODULE_6__.marked.Renderer();
            renderer.link = function (href, title, text) {
                var link = marked__WEBPACK_IMPORTED_MODULE_6__.marked.Renderer.prototype.link.apply(this, arguments);
                return link.replace("<a", "<a target='_blank'");
            };
            marked__WEBPACK_IMPORTED_MODULE_6__.marked.setOptions({
                renderer: renderer
            });
            const __html = (0,marked__WEBPACK_IMPORTED_MODULE_6__.marked)(text !== null && text !== void 0 ? text : '');
            return { __html };
        };
    }
    showTooltip() {
        this.setState({ isTooltipActive: true });
    }
    hideTooltip() {
        this.setState({ isTooltipActive: false });
    }
    handleClose() {
        this.hideTooltip();
    }
    ;
    handleDeletableNode(key, event) {
        this.setState({
            [key]: event.target.checked
                ? this.props.node.setLocked(true)
                : this.props.node.setLocked(false),
        });
    }
    handleOnChangeCanvas() {
        this.props.engine.fireEvent({}, 'onChange');
    }
    /**
     * Allow to edit Literal Component
     */
    handleEditLiteral() {
        if (!this.props.node.getOptions()["name"].startsWith("Literal")) {
            return;
        }
        this.props.app.commands.execute(_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_10__.commandIDs.editNode);
    }
    /**
     * Allow to edit Comment Component
     */
    async handleEditComment() {
        let dialogResult = await (0,_dialog_FormDialog__WEBPACK_IMPORTED_MODULE_11__.showFormDialog)(this.dialogOptions);
        if (dialogResult["button"]["label"] == 'Cancel') {
            // When Cancel is clicked on the dialog, just return
            return false;
        }
        const newVal = dialogResult["value"][''];
        //  update value both in internal component state
        this.setState({ commentInput: newVal });
        // and in model object
        this.props.node['extras']['commentInput'] = newVal;
        this.handleOnChangeCanvas();
    }
    /**
     * Show/Hide Component's Description Tooltip
     */
    async handleDescription() {
        await this.setState({ showDescription: !this.state.showDescription });
        this.getDescriptionStr();
        react_tooltip__WEBPACK_IMPORTED_MODULE_5___default().show(this.element);
    }
    getDescriptionStr() {
        var _a;
        let dscrptStr = (_a = this.props.node['extras']['description']) !== null && _a !== void 0 ? _a : '***No description provided***';
        this.setState({ descriptionStr: dscrptStr });
    }
    // Hide Error Tooltip
    hideErrorTooltip() {
        delete this.props.node.getOptions().extras["tip"];
        this.props.node.getOptions().extras["borderColor"] = "rgb(0,192,255)";
    }
    render() {
        if (this.props.node['extras']['type'] == 'comment') {
            return (react__WEBPACK_IMPORTED_MODULE_0__.createElement(S.CommentContainer, { onDoubleClick: this.handleEditComment.bind(this), selected: this.props.node.isSelected() },
                react__WEBPACK_IMPORTED_MODULE_0__.createElement(S.TitleName, null,
                    react__WEBPACK_IMPORTED_MODULE_0__.createElement("b", null, this.props.node.getOptions().name)),
                react__WEBPACK_IMPORTED_MODULE_0__.createElement("div", { className: 'comment-component-content' }, this.state.commentInput)));
        }
        else if (this.props.node.getOptions()["name"].startsWith('Literal')) {
            return (react__WEBPACK_IMPORTED_MODULE_0__.createElement(S.Node, { borderColor: this.props.node.getOptions().extras["borderColor"], "data-default-node-name": this.props.node.getOptions().name, selected: this.props.node.isSelected(), background: this.props.node.getOptions().color, onDoubleClick: this.handleEditLiteral.bind(this) },
                react__WEBPACK_IMPORTED_MODULE_0__.createElement(S.Title, null,
                    react__WEBPACK_IMPORTED_MODULE_0__.createElement(S.TitleName, null, this.props.node.getOptions().name)),
                react__WEBPACK_IMPORTED_MODULE_0__.createElement(S.Ports, null,
                    react__WEBPACK_IMPORTED_MODULE_0__.createElement(S.PortsContainer, null, lodash__WEBPACK_IMPORTED_MODULE_1__.map(this.props.node.getInPorts(), this.generatePort)),
                    react__WEBPACK_IMPORTED_MODULE_0__.createElement(S.PortsContainer, null, lodash__WEBPACK_IMPORTED_MODULE_1__.map(this.props.node.getOutPorts(), this.generatePort)))));
        }
        else if (this.props.node.getOptions()["name"] !== 'Start' && this.props.node.getOptions()["name"] !== 'Finish') {
            return (react__WEBPACK_IMPORTED_MODULE_0__.createElement(react__WEBPACK_IMPORTED_MODULE_0__.Fragment, null,
                react__WEBPACK_IMPORTED_MODULE_0__.createElement(S.Node, { onMouseEnter: this.showTooltip.bind(this), onMouseLeave: this.hideTooltip.bind(this), ref: (element) => { this.element = element; }, "data-tip": true, "data-for": this.props.node.getOptions().id, borderColor: this.props.node.getOptions().extras["borderColor"], "data-default-node-name": this.props.node.getOptions().name, selected: this.props.node.isSelected(), background: this.props.node.getOptions().color, onDoubleClick: this.handleEditLiteral.bind(this) },
                    react__WEBPACK_IMPORTED_MODULE_0__.createElement(S.Title, null,
                        react__WEBPACK_IMPORTED_MODULE_0__.createElement(S.TitleName, null, this.props.node.getOptions().name),
                        react__WEBPACK_IMPORTED_MODULE_0__.createElement("label", { "data-no-drag": true },
                            react__WEBPACK_IMPORTED_MODULE_0__.createElement((react_toggle__WEBPACK_IMPORTED_MODULE_3___default()), { className: 'lock', checked: this.props.node.isLocked(), onChange: this.handleDeletableNode.bind(this, 'nodeDeletable') }),
                            react__WEBPACK_IMPORTED_MODULE_0__.createElement((react_toggle__WEBPACK_IMPORTED_MODULE_3___default()), { className: 'description', name: 'Description', checked: this.state.showDescription, onChange: this.handleDescription.bind(this) }))),
                    react__WEBPACK_IMPORTED_MODULE_0__.createElement(S.Ports, null,
                        react__WEBPACK_IMPORTED_MODULE_0__.createElement(S.PortsContainer, null, lodash__WEBPACK_IMPORTED_MODULE_1__.map(this.props.node.getInPorts(), this.generatePort)),
                        react__WEBPACK_IMPORTED_MODULE_0__.createElement(S.PortsContainer, null, lodash__WEBPACK_IMPORTED_MODULE_1__.map(this.props.node.getOutPorts(), this.generatePort)))),
                this.state.showDescription && react__WEBPACK_IMPORTED_MODULE_0__.createElement((react_tooltip__WEBPACK_IMPORTED_MODULE_5___default()), { id: this.props.node.getOptions().id, className: 'description-tooltip', arrowColor: 'rgb(255, 255, 255)', clickable: true, afterShow: () => { this.setState({ showDescription: true }); }, afterHide: () => { this.setState({ showDescription: false }); }, delayHide: 60000, delayUpdate: 5000, getContent: () => react__WEBPACK_IMPORTED_MODULE_0__.createElement("div", { "data-no-drag": true, style: { cursor: 'default' } },
                        react__WEBPACK_IMPORTED_MODULE_0__.createElement("button", { type: "button", className: "close", "data-dismiss": "modal", "aria-label": "Close", onClick: () => { this.setState({ showDescription: false }); } },
                            react__WEBPACK_IMPORTED_MODULE_0__.createElement("span", { "aria-hidden": "true" }, "\u00D7")),
                        react__WEBPACK_IMPORTED_MODULE_0__.createElement(S.DescriptionName, { color: this.props.node.getOptions().color }, this.props.node.getOptions()["name"]),
                        react__WEBPACK_IMPORTED_MODULE_0__.createElement("p", { className: 'description-title' }, "Description:"),
                        react__WEBPACK_IMPORTED_MODULE_0__.createElement("div", { onWheel: (e) => e.stopPropagation(), className: 'description-container' },
                            react__WEBPACK_IMPORTED_MODULE_0__.createElement("div", { className: 'markdown-body', dangerouslySetInnerHTML: this.renderText(this.state.descriptionStr) }))), overridePosition: ({ left, top }, currentEvent, currentTarget, node, refNode) => {
                        const currentNode = this.props.node;
                        const nodeDimension = { x: currentNode.width, y: currentNode.height };
                        const nodePosition = { x: currentNode.getX(), y: currentNode.getY() };
                        let newPositionX = nodePosition.x;
                        let newPositionY = nodePosition.y;
                        let offset = 0;
                        if (!this.props.shell.leftCollapsed) {
                            // Some weird offset happened when left sidebar opened, need to add this
                            let leftSidebar = document.getElementById('jp-left-stack');
                            offset = leftSidebar.clientWidth + 2;
                        }
                        if (refNode == 'top') {
                            newPositionX = newPositionX - 208 + offset + (nodeDimension.x / 2);
                            newPositionY = newPositionY - 220;
                        }
                        else if (refNode == 'bottom') {
                            newPositionX = newPositionX - 208 + offset + (nodeDimension.x / 2);
                            newPositionY = newPositionY + 85 + nodeDimension.y;
                        }
                        else if (refNode == 'right') {
                            newPositionX = newPositionX + 40 + offset + nodeDimension.x;
                            newPositionY = newPositionY - 66 + (nodeDimension.y / 2);
                        }
                        else if (refNode == 'left') {
                            newPositionX = newPositionX - 450 + offset;
                            newPositionY = newPositionY - 66 + (nodeDimension.y / 2);
                        }
                        const tooltipPosition = this.props.engine.getRelativePoint(newPositionX, newPositionY);
                        left = tooltipPosition.x;
                        top = tooltipPosition.y;
                        return { top, left };
                    } }),
                (this.props.node.getOptions().extras["tip"] != undefined && this.props.node.getOptions().extras["tip"] != "") ?
                    react__WEBPACK_IMPORTED_MODULE_0__.createElement((react_tooltip__WEBPACK_IMPORTED_MODULE_5___default()), { id: this.props.node.getOptions().id, clickable: true, place: 'bottom', className: 'error-tooltip', arrowColor: 'rgba(255, 0, 0, .9)', delayHide: 100, delayUpdate: 50, getContent: () => react__WEBPACK_IMPORTED_MODULE_0__.createElement("div", { "data-no-drag": true, className: 'error-container' },
                            react__WEBPACK_IMPORTED_MODULE_0__.createElement("p", { className: 'error-title' }, "Error"),
                            react__WEBPACK_IMPORTED_MODULE_0__.createElement("div", { className: 'markdown-body', dangerouslySetInnerHTML: this.renderText(this.props.node.getOptions().extras["tip"]) }),
                            react__WEBPACK_IMPORTED_MODULE_0__.createElement("button", { type: "button", className: "close", "data-dismiss": "modal", "aria-label": "Close", onClick: this.hideErrorTooltip.bind(this) },
                                react__WEBPACK_IMPORTED_MODULE_0__.createElement("span", { "aria-hidden": "true" }, "\u00D7"))), overridePosition: ({ left, top }) => {
                            const currentNode = this.props.node;
                            const nodeDimension = { x: currentNode.width, y: currentNode.height };
                            const nodePosition = { x: currentNode.getX(), y: currentNode.getY() };
                            let newPositionX = nodePosition.x;
                            let newPositionY = nodePosition.y;
                            let offset = 0;
                            if (!this.props.shell.leftCollapsed) {
                                // Some weird offset happened when left sidebar opened, need to add this
                                let leftSidebar = document.getElementById('jp-left-stack');
                                offset = leftSidebar.clientWidth + 2;
                            }
                            newPositionX = newPositionX - 184 + offset + (nodeDimension.x / 2);
                            newPositionY = newPositionY + 90 + nodeDimension.y;
                            const tooltipPosition = this.props.engine.getRelativePoint(newPositionX, newPositionY);
                            left = tooltipPosition.x;
                            top = tooltipPosition.y;
                            return { top, left };
                        } })
                    : null));
        }
        return (react__WEBPACK_IMPORTED_MODULE_0__.createElement(S.Node, { borderColor: this.props.node.getOptions().extras["borderColor"], "data-default-node-name": this.props.node.getOptions().name, selected: this.props.node.isSelected(), background: this.props.node.getOptions().color },
            react__WEBPACK_IMPORTED_MODULE_0__.createElement(S.Title, null,
                react__WEBPACK_IMPORTED_MODULE_0__.createElement(S.TitleName, null, this.props.node.getOptions().name)),
            react__WEBPACK_IMPORTED_MODULE_0__.createElement(S.Ports, null,
                react__WEBPACK_IMPORTED_MODULE_0__.createElement(S.PortsContainer, null, lodash__WEBPACK_IMPORTED_MODULE_1__.map(this.props.node.getInPorts(), this.generatePort)),
                react__WEBPACK_IMPORTED_MODULE_0__.createElement(S.PortsContainer, null, lodash__WEBPACK_IMPORTED_MODULE_1__.map(this.props.node.getOutPorts(), this.generatePort)))));
    }
}


/***/ }),

/***/ "./lib/components/RunSwitcher.js":
/*!***************************************!*\
  !*** ./lib/components/RunSwitcher.js ***!
  \***************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "RunSwitcher": () => (/* binding */ RunSwitcher)
/* harmony export */ });
/* harmony import */ var _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @jupyterlab/apputils */ "webpack/sharing/consume/default/@jupyterlab/apputils");
/* harmony import */ var _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @jupyterlab/ui-components */ "webpack/sharing/consume/default/@jupyterlab/ui-components");
/* harmony import */ var _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_2__);



/**
 * A toolbar widget that switches output types.
 */
class RunSwitcher extends _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_0__.ReactWidget {
    /**
     * Construct a new output type switcher.
     */
    constructor(widget) {
        super();
        /**
         * Handle `change` events for the HTMLSelect component.
         */
        this.handleChange = (event) => {
            let runType = event.target.value;
            this._output.runTypeXircuitSignal.emit({ runType });
            this.update();
        };
        this._output = widget;
    }
    render() {
        let value;
        return (react__WEBPACK_IMPORTED_MODULE_2___default().createElement(_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_0__.UseSignal, { signal: this._output.runTypeXircuitSignal }, (_, args) => {
            if (args !== undefined) {
                let runType = args["runType"];
                return (react__WEBPACK_IMPORTED_MODULE_2___default().createElement(_jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_1__.HTMLSelect, { onChange: this.handleChange, value: runType, "aria-label": 'Run type', title: 'Select the run type' },
                    react__WEBPACK_IMPORTED_MODULE_2___default().createElement("option", { value: "run" }, "Local Run"),
                    react__WEBPACK_IMPORTED_MODULE_2___default().createElement("option", { value: "run-dont-compile" }, "Local Run w/o Compile"),
                    react__WEBPACK_IMPORTED_MODULE_2___default().createElement("option", { value: "remote-run" }, "Remote Run")));
            }
            // Only for rendering the first time
            return (react__WEBPACK_IMPORTED_MODULE_2___default().createElement(_jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_1__.HTMLSelect, { onChange: this.handleChange, value: value, "aria-label": 'Run type', title: 'Select the run type' },
                react__WEBPACK_IMPORTED_MODULE_2___default().createElement("option", { value: "run" }, "Local Run"),
                react__WEBPACK_IMPORTED_MODULE_2___default().createElement("option", { value: "run-dont-compile" }, "Run w/o Compile"),
                react__WEBPACK_IMPORTED_MODULE_2___default().createElement("option", { value: "remote-run" }, "Remote Run")));
        }));
    }
}


/***/ }),

/***/ "./lib/components/XircuitsApp.js":
/*!***************************************!*\
  !*** ./lib/components/XircuitsApp.js ***!
  \***************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "XircuitsApplication": () => (/* binding */ XircuitsApplication)
/* harmony export */ });
/* harmony import */ var _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @projectstorm/react-diagrams */ "webpack/sharing/consume/default/@projectstorm/react-diagrams/@projectstorm/react-diagrams");
/* harmony import */ var _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _CustomNodeFactory__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./CustomNodeFactory */ "./lib/components/CustomNodeFactory.js");
/* harmony import */ var _CustomNodeModel__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./CustomNodeModel */ "./lib/components/CustomNodeModel.js");
/* harmony import */ var _projectstorm_react_canvas_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @projectstorm/react-canvas-core */ "webpack/sharing/consume/default/@projectstorm/react-canvas-core/@projectstorm/react-canvas-core?4a30");
/* harmony import */ var _projectstorm_react_canvas_core__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_projectstorm_react_canvas_core__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _commands_CustomActionEvent__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../commands/CustomActionEvent */ "./lib/commands/CustomActionEvent.js");
/* harmony import */ var _state_CustomDiagramState__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./state/CustomDiagramState */ "./lib/components/state/CustomDiagramState.js");
/* harmony import */ var _link_CustomLinkModel__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./link/CustomLinkModel */ "./lib/components/link/CustomLinkModel.js");
/* harmony import */ var _link_CustomLinkFactory__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./link/CustomLinkFactory */ "./lib/components/link/CustomLinkFactory.js");
/* harmony import */ var _projectstorm_geometry__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @projectstorm/geometry */ "./node_modules/@projectstorm/geometry/dist/index.js");
/* harmony import */ var _projectstorm_geometry__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_projectstorm_geometry__WEBPACK_IMPORTED_MODULE_2__);










class XircuitsApplication {
    constructor(app, shell) {
        this.customDeserializeModel = (modelContext, initialRender) => {
            var _a, _b;
            if (modelContext == null) {
                // When context empty, just return
                return;
            }
            let tempModel = new _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_0__.DiagramModel({ id: modelContext.id });
            let links = modelContext["layers"][0]["models"];
            let nodes = modelContext["layers"][1]["models"];
            let offsetX = modelContext["offsetX"];
            let offsetY = modelContext["offsetY"];
            let zoom = modelContext["zoom"];
            for (let nodeID in nodes) {
                let node = nodes[nodeID];
                let newNode = new _CustomNodeModel__WEBPACK_IMPORTED_MODULE_3__.CustomNodeModel({
                    id: node.id, type: node.type, name: node.name, locked: node.locked,
                    color: node.color, extras: node.extras
                });
                newNode.setPosition(node.x, node.y);
                newNode.setSelected(node.selected);
                for (let portID of node.portsInOrder) {
                    const port = node.ports.find(p => p.id === portID);
                    newNode.addInPortEnhance({ label: port.label, name: port.name, varName: port.varName, id: port.id, dataType: port.dataType, dynaPortOrder: port.dynaPortOrder, dynaPortRef: port.dynaPortRef });
                }
                for (let portID of node.portsOutOrder) {
                    const port = node.ports.find(p => p.id === portID);
                    newNode.addOutPortEnhance({ label: port.label, name: port.name, id: port.id });
                }
                tempModel.addNode(newNode);
            }
            for (let linkID in links) {
                let link = links[linkID];
                if (link.sourcePort && link.targetPort) {
                    let newLink = new _link_CustomLinkModel__WEBPACK_IMPORTED_MODULE_4__.ParameterLinkModel({ id: link.id });
                    const newTriangleLink = new _link_CustomLinkModel__WEBPACK_IMPORTED_MODULE_4__.TriangleLinkModel({ id: link.id });
                    const sourceNode = tempModel.getNode(link.source);
                    const targetNode = tempModel.getNode(link.target);
                    if (!sourceNode || !targetNode) {
                        const missingNodeId = !sourceNode ? link.source : link.target;
                        const missingNodeType = !sourceNode ? 'Source' : 'Target';
                        console.error(`${missingNodeType} node with id ${missingNodeId} not found!`);
                        continue; // Skip to the next iteration of the loop.
                    }
                    const linkPoints = link.points;
                    const sourcePort = sourceNode.getPortFromID(link.sourcePort);
                    const sourcePortName = sourcePort.getOptions()['name'];
                    const sourcePortOptions = (_a = sourceNode.getPorts()[sourcePortName]) === null || _a === void 0 ? void 0 : _a.getOptions();
                    if (!sourcePortOptions) {
                        console.error(`${sourcePortName} port not found!`);
                        continue;
                    }
                    const sourcePortLabel = sourcePortOptions['label'];
                    if (sourcePortLabel == '▶' || sourcePortName.includes('out-flow')) {
                        // When source port is '▶', use triangle animation link
                        // Also, use triangle animation link when the source port is a flowport
                        newLink = newTriangleLink;
                    }
                    const targetPort = targetNode.getPortFromID(link.targetPort);
                    const targetPortName = targetPort.getOptions()['name'];
                    const targetPortOptions = (_b = targetNode.getPorts()[targetPortName]) === null || _b === void 0 ? void 0 : _b.getOptions();
                    if (!targetPortOptions) {
                        console.error(`${targetPortName} port not found!`);
                        continue;
                    }
                    const targetPortLabel = targetPortOptions['label'];
                    if (targetPortLabel == '▶') {
                        // When target port is '▶', use triangle animation link
                        newLink = newTriangleLink;
                    }
                    // Set points on link if exist
                    const points = [];
                    linkPoints.map((point) => {
                        let newPoint = new _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_0__.PointModel({ id: point.id, link: link, position: new _projectstorm_geometry__WEBPACK_IMPORTED_MODULE_2__.Point(point.x, point.y) });
                        if (point.selected) {
                            newPoint.setSelected(true);
                        }
                        ;
                        points.push(newPoint);
                    });
                    newLink.setSourcePort(sourcePort);
                    newLink.setTargetPort(targetPort);
                    newLink.setSelected(link.selected);
                    if (initialRender) {
                        // When initial rendering of xircuits, 
                        // delay the rendering of points.
                        setTimeout(() => {
                            newLink.setPoints(points);
                        }, 10);
                    }
                    else {
                        newLink.setPoints(points);
                    }
                    tempModel.addLink(newLink);
                }
            }
            tempModel.setOffsetX(offsetX);
            tempModel.setOffsetY(offsetY);
            tempModel.setZoomLevel(zoom);
            return tempModel;
        };
        this.diagramEngine = _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_0___default()({ registerDefaultZoomCanvasAction: false, registerDefaultDeleteItemsAction: false });
        this.activeModel = new _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_0__.DiagramModel();
        this.diagramEngine.getNodeFactories().registerFactory(new _CustomNodeFactory__WEBPACK_IMPORTED_MODULE_5__.CustomNodeFactory(app, shell));
        this.diagramEngine.getLinkFactories().registerFactory(new _link_CustomLinkFactory__WEBPACK_IMPORTED_MODULE_6__.ParameterLinkFactory());
        this.diagramEngine.getLinkFactories().registerFactory(new _link_CustomLinkFactory__WEBPACK_IMPORTED_MODULE_6__.TriangleLinkFactory());
        this.diagramEngine.getActionEventBus().registerAction(new _projectstorm_react_canvas_core__WEBPACK_IMPORTED_MODULE_1__.ZoomCanvasAction({ inverseZoom: true }));
        this.diagramEngine.getActionEventBus().registerAction(new _commands_CustomActionEvent__WEBPACK_IMPORTED_MODULE_7__.CustomActionEvent({ app }));
        this.diagramEngine.getStateMachine().pushState(new _state_CustomDiagramState__WEBPACK_IMPORTED_MODULE_8__.CustomDiagramState());
        let startNode = new _CustomNodeModel__WEBPACK_IMPORTED_MODULE_3__.CustomNodeModel({ name: 'Start', color: 'rgb(255,102,102)', extras: { "type": "Start" } });
        startNode.addOutPortEnhance({ label: '▶', name: 'out-0' });
        startNode.setPosition(100, 100);
        let finishedNode = new _CustomNodeModel__WEBPACK_IMPORTED_MODULE_3__.CustomNodeModel({ name: 'Finish', color: 'rgb(255,102,102)', extras: { "type": "Finish" } });
        finishedNode.addInPortEnhance({ label: '▶', name: 'in-0' });
        finishedNode.setPosition(700, 100);
        this.activeModel.addAll(startNode, finishedNode);
        this.diagramEngine.setModel(this.activeModel);
    }
    getActiveDiagram() {
        return this.activeModel;
    }
    getDiagramEngine() {
        return this.diagramEngine;
    }
}


/***/ }),

/***/ "./lib/components/link/CustomLinkFactory.js":
/*!**************************************************!*\
  !*** ./lib/components/link/CustomLinkFactory.js ***!
  \**************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "ParameterLinkFactory": () => (/* binding */ ParameterLinkFactory),
/* harmony export */   "TriangleLinkFactory": () => (/* binding */ TriangleLinkFactory)
/* harmony export */ });
/* harmony import */ var _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @projectstorm/react-diagrams */ "webpack/sharing/consume/default/@projectstorm/react-diagrams/@projectstorm/react-diagrams");
/* harmony import */ var _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _CustomLinkModel__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./CustomLinkModel */ "./lib/components/link/CustomLinkModel.js");
/* harmony import */ var _emotion_styled__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @emotion/styled */ "webpack/sharing/consume/default/@emotion/styled/@emotion/styled?2715");
/* harmony import */ var _emotion_styled__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_emotion_styled__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _emotion_react__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @emotion/react */ "webpack/sharing/consume/default/@emotion/react/@emotion/react?9405");
/* harmony import */ var _emotion_react__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_emotion_react__WEBPACK_IMPORTED_MODULE_3__);





var S;
(function (S) {
    S.Keyframes = _emotion_react__WEBPACK_IMPORTED_MODULE_3__.keyframes `
		from {
			stroke-dashoffset: 24;
		}
		to {
			stroke-dashoffset: 0;
		}
	`;
    const selected = _emotion_react__WEBPACK_IMPORTED_MODULE_3__.css `
		stroke-dasharray: 10, 2;
		animation: ${S.Keyframes} 1s steps(24) infinite;
	`;
    S.Path = (_emotion_styled__WEBPACK_IMPORTED_MODULE_2___default().path) `
		${(p) => p.selected && selected};

		fill: none;
		pointer-events: auto;
		
		body.low-powered-mode & {
			animation: none !important;
		}
	`;
})(S || (S = {}));
class ParameterLinkFactory extends _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_0__.DefaultLinkFactory {
    constructor() {
        super('parameter-link');
    }
    generateModel() {
        return new _CustomLinkModel__WEBPACK_IMPORTED_MODULE_4__.ParameterLinkModel();
    }
    generateLinkSegment(model, selected, path) {
        return (react__WEBPACK_IMPORTED_MODULE_1__.createElement(S.Path, { selected: selected, stroke: selected ? 'yellow' : model.getOptions().color, strokeWidth: model.getOptions().width, d: path }));
    }
}
class TriangleLinkFactory extends _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_0__.DefaultLinkFactory {
    constructor() {
        super('triangle-link');
    }
    generateModel() {
        return new _CustomLinkModel__WEBPACK_IMPORTED_MODULE_4__.TriangleLinkModel();
    }
    generateLinkSegment(model, selected, path) {
        return (react__WEBPACK_IMPORTED_MODULE_1__.createElement(S.Path, { selected: !selected, stroke: !selected ? model.getOptions().selectedColor : 'yellow', strokeWidth: model.getOptions().width, d: path }));
    }
}


/***/ }),

/***/ "./lib/components/link/CustomLinkModel.js":
/*!************************************************!*\
  !*** ./lib/components/link/CustomLinkModel.js ***!
  \************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "CustomLinkModel": () => (/* binding */ CustomLinkModel),
/* harmony export */   "CustomLinkPortModel": () => (/* binding */ CustomLinkPortModel),
/* harmony export */   "ParameterLinkModel": () => (/* binding */ ParameterLinkModel),
/* harmony export */   "ParameterLinkPortModel": () => (/* binding */ ParameterLinkPortModel),
/* harmony export */   "TriangleLinkModel": () => (/* binding */ TriangleLinkModel),
/* harmony export */   "TrianglePortModel": () => (/* binding */ TrianglePortModel)
/* harmony export */ });
/* harmony import */ var _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @projectstorm/react-diagrams */ "webpack/sharing/consume/default/@projectstorm/react-diagrams/@projectstorm/react-diagrams");
/* harmony import */ var _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _port_CustomPortModel__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../port/CustomPortModel */ "./lib/components/port/CustomPortModel.js");


class CustomLinkModel extends _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_0__.DefaultLinkModel {
    constructor(options = {}) {
        super(Object.assign({ type: 'custom-link', width: 3 }, options));
    }
    getOptions() {
        return super.getOptions();
    }
    serialize() {
        return Object.assign({}, super.serialize());
    }
}
class CustomLinkPortModel extends _port_CustomPortModel__WEBPACK_IMPORTED_MODULE_1__.CustomPortModel {
    createLinkModel() {
        return new CustomLinkModel();
    }
}
class ParameterLinkModel extends CustomLinkModel {
    constructor(options = {}) {
        super(Object.assign({ type: 'parameter-link' }, options));
    }
    getOptions() {
        return super.getOptions();
    }
}
class ParameterLinkPortModel extends _port_CustomPortModel__WEBPACK_IMPORTED_MODULE_1__.CustomPortModel {
    createLinkModel() {
        return new ParameterLinkModel();
    }
}
class TriangleLinkModel extends CustomLinkModel {
    constructor(options = {}) {
        super(Object.assign({ type: 'triangle-link' }, options));
    }
    getOptions() {
        return super.getOptions();
    }
}
class TrianglePortModel extends _port_CustomPortModel__WEBPACK_IMPORTED_MODULE_1__.CustomPortModel {
    createLinkModel() {
        return new TriangleLinkModel();
    }
}


/***/ }),

/***/ "./lib/components/port/CustomDynaPortModel.js":
/*!****************************************************!*\
  !*** ./lib/components/port/CustomDynaPortModel.js ***!
  \****************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "CustomDynaPortModel": () => (/* binding */ CustomDynaPortModel),
/* harmony export */   "DYNAMIC_PARAMETER_NODE_TYPES": () => (/* binding */ DYNAMIC_PARAMETER_NODE_TYPES)
/* harmony export */ });
/* harmony import */ var _CustomPortModel__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./CustomPortModel */ "./lib/components/port/CustomPortModel.js");

const DYNAMIC_PARAMETER_NODE_TYPES = [
    'dynalist', 'dynadict', 'dynatuple'
];
class CustomDynaPortModel extends _CustomPortModel__WEBPACK_IMPORTED_MODULE_0__.CustomPortModel {
    constructor(options) {
        super(Object.assign({}, options));
        this.dynaPortOrder = options.dynaPortOrder || 0;
        this.dynaPortRef = options.dynaPortRef || { previous: null, next: null };
    }
    serialize() {
        return Object.assign(Object.assign({}, super.serialize()), { dynaPortOrder: this.dynaPortOrder, dynaPortRef: this.dynaPortRef });
    }
    deserialize(event) {
        super.deserialize(event);
        this.dynaPortOrder = event.data.dynaPortOrder;
        this.dynaPortRef = event.data.dynaPortRef;
    }
    isTypeCompatible(thisNodeModelType, thisLinkedPortType) {
        // if thisLinkedPortType is dynalist or dynatuple, treat it as any
        if (['dynalist', 'dynatuple'].includes(thisLinkedPortType)) {
            return true; // Accepts anything
        }
        // if thisLinkedPortType is dynadict, accept only dict
        if (thisLinkedPortType === 'dynadict' && thisNodeModelType !== 'dict') {
            return false;
        }
        // default check
        return super.isTypeCompatible(thisNodeModelType, thisLinkedPortType);
    }
    canLinkToLinkedPort() {
        return true;
    }
    spawnDynamicPort(options) {
        let { offset = 1, node = null, port = this, absolutePortOrder = null, newDynamicPortOrder = null } = options;
        node = node !== null ? node : port.parent;
        absolutePortOrder = absolutePortOrder !== null ? absolutePortOrder : port.getPortOrder() + offset;
        newDynamicPortOrder = newDynamicPortOrder !== null ? newDynamicPortOrder : port.dynaPortOrder + offset;
        let newDynamicPortName;
        let newDynamicPortLabel;
        if (newDynamicPortOrder == 0) {
            newDynamicPortName = `parameter-${port.dataType}-${port.varName}`;
            newDynamicPortLabel = `${port.varName}`;
        }
        else {
            newDynamicPortName = `parameter-${port.dataType}-${port.varName}-${newDynamicPortOrder}`;
            newDynamicPortLabel = `${port.varName}[${newDynamicPortOrder}]`;
        }
        let newPort = node.addInPortEnhance({
            label: newDynamicPortLabel,
            name: newDynamicPortName,
            varName: port.varName,
            dataType: port.dataType,
            order: absolutePortOrder,
            dynaPortOrder: newDynamicPortOrder
        });
        return newPort;
    }
    shiftPorts({ shouldShiftBack = false } = {}) {
        let node = this.parent;
        let currentPort = this;
        let previousPort = node.getPortFromID(currentPort.previous);
        const currentPortProps = currentPort.getCustomProps();
        // Store each subsequent port and its link in the array
        let portsAndLinks = [];
        while (currentPort) {
            let link = Object.values(currentPort.getLinks())[0] || null;
            portsAndLinks.push({ port: currentPort, link });
            currentPort = currentPort.next ? node.getPortFromID(currentPort.next) : null;
        }
        // Disconnect links and remove corresponding ports
        portsAndLinks.forEach(({ port, link }) => {
            if (link)
                link.setTargetPort(null);
            node.removePort(port);
        });
        // If shouldShiftBack flag is true, remove the first element from portsAndLinks array
        if (shouldShiftBack)
            portsAndLinks.shift();
        // Spawn a new port using properties from either the previous port or the current port
        let newPort = previousPort ? previousPort.spawnDynamicPort({ offset: 1, port: previousPort })
            : this.spawnDynamicPort({ node, newDynamicPortOrder: currentPortProps.dynaPortOrder, absolutePortOrder: currentPortProps.absolutePortOrder });
        if (previousPort) {
            newPort.previous = previousPort.getID();
            previousPort.next = newPort.getID();
        }
        // Initialize a variable to keep track of the last created port
        let lastCreatedPort = newPort;
        // Loop over the portsAndLinks array to recreate each port and reconnect the links
        portsAndLinks.forEach(({ link }) => {
            let recreatedPort = lastCreatedPort.spawnDynamicPort({ offset: 1, port: lastCreatedPort });
            recreatedPort.previous = lastCreatedPort.getID();
            lastCreatedPort.next = recreatedPort.getID();
            // If a link exists, connect it to lastCreatedPort when shifting backwards and deleting, 
            // to maintain the connection with the existing port.
            // Otherwise, connect to the recreatedPort to link with the newly spawned port.
            if (link)
                link.setTargetPort(shouldShiftBack ? lastCreatedPort : recreatedPort);
            // Update the lastCreatedPort to point to the newly recreated port
            lastCreatedPort = recreatedPort;
        });
        // If shouldShiftBack flag is true, remove the last created port
        if (shouldShiftBack)
            node.removePort(lastCreatedPort);
        return newPort;
    }
    get previous() {
        return this.dynaPortRef.previous;
    }
    get next() {
        return this.dynaPortRef.next;
    }
    set previous(value) {
        this.dynaPortRef.previous = value;
    }
    set next(value) {
        this.dynaPortRef.next = value;
    }
    getCustomProps() {
        const baseProps = super.getCustomProps();
        const { dynaPortOrder, dynaPortRef } = this;
        const absolutePortOrder = this.getPortOrder();
        return Object.assign(Object.assign({}, baseProps), { dynaPortOrder,
            dynaPortRef,
            absolutePortOrder });
    }
}


/***/ }),

/***/ "./lib/components/port/CustomPortLabel.js":
/*!************************************************!*\
  !*** ./lib/components/port/CustomPortLabel.js ***!
  \************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "CustomPortLabel": () => (/* binding */ CustomPortLabel)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _projectstorm_react_diagrams_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @projectstorm/react-diagrams-core */ "./node_modules/@projectstorm/react-diagrams-core/dist/index.js");
/* harmony import */ var _projectstorm_react_diagrams_core__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_projectstorm_react_diagrams_core__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _emotion_styled__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @emotion/styled */ "webpack/sharing/consume/default/@emotion/styled/@emotion/styled?2715");
/* harmony import */ var _emotion_styled__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_emotion_styled__WEBPACK_IMPORTED_MODULE_2__);



var S;
(function (S) {
    S.PortLabel = (_emotion_styled__WEBPACK_IMPORTED_MODULE_2___default().div) `
		display: flex;
		margin-top: 1px;
		align-items: center;
	`;
    S.Label = (_emotion_styled__WEBPACK_IMPORTED_MODULE_2___default().div) `
		padding: 0 5px;
		flex-grow: 1;
		white-space: pre-wrap; // Preserve line breaks and wrap text to the next line
		overflow:hidden;
		max-width: 40ch;
	`;
    S.SymbolContainer = (_emotion_styled__WEBPACK_IMPORTED_MODULE_2___default().div) `
        width: 17px;
		height: 15px;
		border: 5px hidden;
		background: ${(p) => (p.selected ? 'white' : 'rgba(0, 0, 0, 0.2)')};
		border-radius: ${(p) => (p.isOutPort ? '20px 0px 0px 20px' : '0px 20px 20px 0px')} ;
		display: ${(p) => p.symbolType == null ? 'none' : 'visible'};
		text-align: center;
	`;
    S.Symbol = (_emotion_styled__WEBPACK_IMPORTED_MODULE_2___default().div) `
		color: black;
		font-weight: bold;
		font-size: 9px;
		font-family: Helvetica, Arial, sans-serif;
		padding:${(p) => (p.isOutPort ? '2px 0px 0px 2px' : '2px 2px 0px 0px')};
	`;
    S.Port = (_emotion_styled__WEBPACK_IMPORTED_MODULE_2___default().div) `
		width: 15px;
		height: 15px;
		background: rgba(255, 255, 255, 0.2);
		&:hover {
			background: rgb(192, 255, 0);
		}
	`;
})(S || (S = {}));
class CustomPortLabel extends react__WEBPACK_IMPORTED_MODULE_0__.Component {
    render() {
        let portName = this.props.port.getOptions().name;
        let portType;
        let symbolLabel;
        let isOutPort;
        if (portName.includes('parameter-out')) {
            portType = portName.split("-")[2];
            isOutPort = true;
        }
        else {
            portType = portName.split("-")[1];
        }
        if (portType.includes(',')) {
            portType = 'union';
        }
        const symbolMap = {
            "string": '" "',
            "int": ' 1',
            "float": '1.0',
            "boolean": '⊤⊥',
            "time.time": '𝘵',
            "list": '[ ]',
            "tuple": '( )',
            "dict": '{ }',
            "dynalist": '«[]»',
            "dynatuple": '«()»',
            "dynadict": '«{}»',
            "union": ' U',
            "secret": '🗝️',
            "chat": '🗨',
            "any": '[_]',
            "0": null,
            "flow": null
        };
        if (portType in symbolMap) {
            symbolLabel = symbolMap[portType];
        }
        else {
            symbolLabel = '◎';
        }
        const port = (react__WEBPACK_IMPORTED_MODULE_0__.createElement(_projectstorm_react_diagrams_core__WEBPACK_IMPORTED_MODULE_1__.PortWidget, { engine: this.props.engine, port: this.props.port },
            react__WEBPACK_IMPORTED_MODULE_0__.createElement(S.Port, null)));
        const propLinks = this.props.port.links;
        let portHasLink = false;
        if (Object.keys(propLinks).length != 0) {
            portHasLink = true;
        }
        const symbol = (react__WEBPACK_IMPORTED_MODULE_0__.createElement(S.SymbolContainer, { symbolType: symbolLabel, selected: portHasLink, isOutPort: isOutPort },
            react__WEBPACK_IMPORTED_MODULE_0__.createElement(S.Symbol, { isOutPort: isOutPort }, symbolLabel)));
        const nodeType = this.props.node.getOptions().name;
        const label = (react__WEBPACK_IMPORTED_MODULE_0__.createElement(S.Label, { style: { textAlign: (!this.props.port.getOptions().in && this.props.port.getOptions().label === '▶') ? 'right' : 'left' } }, nodeType === "Literal Secret" ? "*****" : this.props.port.getOptions().label));
        return (react__WEBPACK_IMPORTED_MODULE_0__.createElement(S.PortLabel, null,
            this.props.port.getOptions().in ? port : label,
            symbol,
            this.props.port.getOptions().in ? label : port));
    }
}


/***/ }),

/***/ "./lib/components/port/CustomPortModel.js":
/*!************************************************!*\
  !*** ./lib/components/port/CustomPortModel.js ***!
  \************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "CustomPortModel": () => (/* binding */ CustomPortModel),
/* harmony export */   "PARAMETER_NODE_TYPES": () => (/* binding */ PARAMETER_NODE_TYPES)
/* harmony export */ });
/* harmony import */ var _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @projectstorm/react-diagrams */ "webpack/sharing/consume/default/@projectstorm/react-diagrams/@projectstorm/react-diagrams");
/* harmony import */ var _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_0__);

/**
 * @author wenfeng xu
 * custom port model enable it can execute some rule
 * before it can link to another
 */
const PARAMETER_NODE_TYPES = [
    'boolean', 'int', 'float', 'string', 'list', 'tuple',
    'dict', 'secret', 'chat'
];
class CustomPortModel extends _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_0__.DefaultPortModel {
    constructor(options) {
        super(Object.assign({}, options));
        /**
         * the qty of ports of parameter node link to the same port in other node can
         * not be more than one
         * @param thisPort
         * @param port
         */
        this.canParameterLinkToPort = (thisPort, targetPort) => {
            const thisNode = this.getNode();
            const thisNodeModelType = thisNode.getOptions()["extras"]["type"];
            const thisName = targetPort.getName();
            const thisLabel = "**" + targetPort.getOptions()["label"] + "**";
            if (this.isParameterNode(thisNodeModelType) == true) {
                if (!thisName.startsWith("parameter")) {
                    targetPort.getNode().getOptions().extras["borderColor"] = "red";
                    targetPort.getNode().getOptions().extras["tip"] = `Port ${thisLabel} linked is not a parameter, please link a non parameter node to it.`;
                    targetPort.getNode().setSelected(true);
                    return false;
                }
                let dataType = targetPort.dataType;
                if (!targetPort.isTypeCompatible(thisNodeModelType, dataType)) {
                    // if a list of types is provided for the port, parse it a bit to display it nicer
                    if (dataType.includes(',')) {
                        dataType = this.parsePortType(dataType);
                    }
                    targetPort.getNode().getOptions().extras["borderColor"] = "red";
                    targetPort.getNode().getOptions().extras["tip"] = `Incorrect data type. Port ${thisLabel} is of type ` + "*`" + dataType + "`*.";
                    targetPort.getNode().setSelected(true);
                    return false;
                }
            }
            this.removeErrorTooltip(this, targetPort);
            return true;
        };
        this.isParameterNode = (nodeModelType) => {
            return PARAMETER_NODE_TYPES.includes(nodeModelType);
        };
        this.canTriangleLinkToTriangle = (thisPort, port) => {
            let portLabel = port.getOptions()["label"];
            let thisPortLabel = this.options["label"];
            let thisNode = this.getNode();
            let node = port.getNode();
            let thisNodeModelType = thisNode.getOptions()["extras"]["type"];
            if (this.isParameterNode(thisNodeModelType)) {
                this.removeErrorTooltip(this, port);
                return true;
            }
            if (!(thisPortLabel.endsWith('▶')) && portLabel != '▶') {
                this.removeErrorTooltip(this, port);
                return true;
            }
            else if (thisPortLabel.includes('▶')) {
                this.removeErrorTooltip(this, port);
                return (portLabel === '▶' && thisPortLabel.includes('▶') && !(Object.keys(thisPort.getLinks()).length > 1));
            }
            else {
                return (portLabel === '▶' && thisPortLabel.endsWith('▶') && !(Object.keys(thisPort.getLinks()).length > 1));
            }
        };
        this.removeErrorTooltip = (thisPort, port) => {
            port.getNode().getOptions().extras["borderColor"] = "rgb(0,192,255)";
            delete port.getNode().getOptions().extras["tip"];
            thisPort.getNode().getOptions().extras["borderColor"] = "rgb(0,192,255)";
            delete thisPort.getNode().getOptions().extras["tip"];
        };
        this.getCircularReplacer = () => {
            var seen = [];
            return (key, value) => {
                if (typeof value === "object" && value !== null) {
                    if (seen.indexOf(value) >= 0) {
                        return;
                    }
                    seen.push(value);
                }
                return value;
            };
        };
        this.checkLinkDirection = (thisPort, port) => {
            // currently only checking if it is an in or out port from its alignment
            return ((thisPort.getOptions()["alignment"] === "right") &&
                (port.getOptions()["alignment"] === "left"));
        };
        this.checkExecutionLoop = (thisPort, port) => {
            let nodeIDList = [];
            let sourceNode = thisPort.getParent();
            let targetNode = port.getParent();
            let nodeType = sourceNode.getOptions()["extras"]["type"];
            nodeIDList.push(sourceNode.getID(), targetNode.getID());
            //console.log("sourceNode is:", sourceNode.getOptions()["name"], "\ntargetNode is:", targetNode.getOptions()["name"]);
            while (sourceNode != null && nodeType != 'Start' && !PARAMETER_NODE_TYPES.includes(nodeType)) {
                //console.log("Curent sourceNode:", sourceNode.getOptions()["name"]);
                let inPorts = sourceNode.getInPorts();
                // a node may have multiple ports. Iterate and find "▶"
                for (let i = 0; i <= inPorts.length; i++) {
                    let portLabel = inPorts[i].getOptions()["label"];
                    if (portLabel === "▶") {
                        let portLink = inPorts[i].getLinks();
                        //check if port has any links
                        if (Object.keys(portLink).length !== 1) {
                            if (Object.keys(portLink).length > 1) {
                                console.log("zombie link detected");
                            }
                            //console.log("sourceNode:", sourceNode.getOptions()["name"], "has no in-links!");
                            sourceNode = null;
                            break;
                        }
                        else {
                            let portLinkKey = Object.keys(portLink).toString();
                            sourceNode = portLink[portLinkKey].getSourcePort().getParent();
                            nodeType = sourceNode.getOptions()["extras"]["type"];
                            if (nodeIDList.includes(sourceNode.getID())) {
                                console.log("Loop detected at", sourceNode.getOptions()["name"]);
                                return false;
                            }
                            nodeIDList.push(sourceNode.getID());
                            break;
                        }
                    }
                }
            }
            while ((targetNode != null) && targetNode.getOptions()["name"] != "Finish") {
                //console.log("Curent targetNode:", targetNode.getOptions()["name"]);
                let outPorts = targetNode.getOutPorts();
                // a node may have multiple ports. Iterate and find "▶"
                for (let i = 0; i <= outPorts.length; i++) {
                    let portLabel = outPorts[i].getOptions()["label"];
                    if (portLabel === "▶") {
                        let portLink = outPorts[i].getLinks();
                        //check if port has any links
                        if (Object.keys(portLink).length !== 1) {
                            if (Object.keys(portLink).length > 1) {
                                console.log("zombie link detected");
                            }
                            //console.log("targetNode:", targetNode.getOptions()["name"], "has no out-links!");
                            targetNode = null;
                            break;
                        }
                        else {
                            let portLinkKey = Object.keys(portLink).toString();
                            targetNode = portLink[portLinkKey].getTargetPort().getParent();
                            if (nodeIDList.includes(targetNode.getID())) {
                                console.log("Loop detected at", targetNode.getOptions()["name"]);
                                return false;
                            }
                            nodeIDList.push(targetNode.getID());
                            break;
                        }
                    }
                }
            }
            return true;
        };
        /**
         * When a port supports multiple types, parse them to display them nicer
         * Parsed type looks like: type1 or type2
         * @param portType - unparsed port type (looks like: "Union[type1, type2]")
         */
        this.parsePortType = (portType) => {
            // port type is of form: Union[type1, type2]
            portType = portType.replace('Union', ''); // remove Union word
            portType = portType.replace(/[\[\]]/g, ''); // remove square brackets
            portType = portType.replace(',', ' or ');
            return portType;
        };
        this.getPortOrder = () => {
            let port = this; // CustomPortModel
            const inPorts = port.parent.getInPorts();
            const portId = this.getID();
            return inPorts.findIndex(p => p.options.id === portId);
        };
        this.varName = options.varName || options.label;
        this.portType = options.portType || "";
        this.dataType = options.dataType || "";
        this.extras = options.extras || {};
    }
    serialize() {
        return Object.assign(Object.assign({}, super.serialize()), { varName: this.varName, portType: this.portType, dataType: this.dataType, extras: this.extras });
    }
    deserialize(event) {
        super.deserialize(event);
        this.varName = event.data.varName;
        this.portType = event.data.portType;
        this.dataType = event.data.dataType;
        this.extras = event.data.extras;
    }
    canLinkToPort(port) {
        if (port instanceof _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_0__.DefaultPortModel) {
            if (this.options.in === port.getOptions().in) {
                port.getNode().getOptions().extras["borderColor"] = "red";
                port.getNode().getOptions().extras["tip"] = "in not connected to in";
                port.getNode().setSelected(true);
                console.log("in not connected to in");
                return false;
            }
        }
        // Multiple link check
        if (!port.canLinkToLinkedPort()) {
            return false;
        }
        let canParameterLinkToPort = this.canParameterLinkToPort(this, port);
        if (canParameterLinkToPort == false) {
            console.log("Parameter Link To Port failed.");
            return false;
        }
        let canTriangleLinkToTriangle = this.canTriangleLinkToTriangle(this, port);
        if (canTriangleLinkToTriangle == false) {
            port.getNode().getOptions().extras["borderColor"] = "red";
            port.getNode().getOptions().extras["tip"] = "Triangle must be linked to triangle.";
            port.getNode().setSelected(true);
            console.log("triangle to triangle failed.");
            //tested
            return false;
        }
        let checkLinkDirection = this.checkLinkDirection(this, port);
        if (checkLinkDirection == false) {
            port.getNode().getOptions().extras["borderColor"] = "red";
            port.getNode().getOptions().extras["tip"] = "Port should be created from outPort [right] to inPort [left].";
            port.getNode().setSelected(true);
            console.log("Port should be created from outPort [right] to inPort [left]");
            return false;
        }
        let checkExecutionLoop = this.checkExecutionLoop(this, port);
        if (checkExecutionLoop == false) {
            //console.log("Loop detected.");
            return false;
        }
        this.removeErrorTooltip(this, port);
        return true;
    }
    isTypeCompatible(thisNodeModelType, dataType) {
        if (thisNodeModelType !== dataType) {
            // Skip 'any' type check
            if (dataType === 'any') {
                return true;
            }
            // if multiple types are accepted by target node port, check if source port type is among them
            if (dataType.includes(thisNodeModelType)) {
                return true;
            }
            return false; // types are incompatible
        }
        return true;
    }
    canLinkToLinkedPort() {
        let port = this;
        if (Object.keys(port.getLinks()).length > 0) {
            port.getNode().getOptions().extras["borderColor"] = "red";
            port.getNode().getOptions().extras["tip"] = "Xircuits only allows 1 link per InPort! Please delete the current link to proceed.";
            port.getNode().setSelected(true);
            return false;
        }
        return true;
    }
    getCustomProps() {
        const { name, varName, portType, dataType } = this;
        const id = this.getID();
        const label = this.getOptions()['label'];
        const props = { name, varName, label, id, dataType, portType };
        return props;
    }
}


/***/ }),

/***/ "./lib/components/state/CustomDiagramState.js":
/*!****************************************************!*\
  !*** ./lib/components/state/CustomDiagramState.js ***!
  \****************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "CustomDiagramState": () => (/* binding */ CustomDiagramState)
/* harmony export */ });
/* harmony import */ var _projectstorm_react_canvas_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @projectstorm/react-canvas-core */ "webpack/sharing/consume/default/@projectstorm/react-canvas-core/@projectstorm/react-canvas-core?4a30");
/* harmony import */ var _projectstorm_react_canvas_core__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_projectstorm_react_canvas_core__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _DragNewLinkState__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./DragNewLinkState */ "./lib/components/state/DragNewLinkState.js");
/* harmony import */ var _port_CustomPortModel__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../port/CustomPortModel */ "./lib/components/port/CustomPortModel.js");
/* harmony import */ var _DragDiagramItemsState__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./DragDiagramItemsState */ "./lib/components/state/DragDiagramItemsState.js");




class CustomDiagramState extends _projectstorm_react_canvas_core__WEBPACK_IMPORTED_MODULE_0__.State {
    constructor() {
        super({
            name: 'custom-diagrams'
        });
        this.childStates = [new _projectstorm_react_canvas_core__WEBPACK_IMPORTED_MODULE_0__.SelectingState()];
        this.dragCanvas = new _projectstorm_react_canvas_core__WEBPACK_IMPORTED_MODULE_0__.DragCanvasState();
        this.dragNewLink = new _DragNewLinkState__WEBPACK_IMPORTED_MODULE_1__.DragNewLinkState({ allowLooseLinks: false });
        this.dragItems = new _DragDiagramItemsState__WEBPACK_IMPORTED_MODULE_2__.DragDiagramItemsState();
        // determine what was clicked on
        this.registerAction(new _projectstorm_react_canvas_core__WEBPACK_IMPORTED_MODULE_0__.Action({
            type: _projectstorm_react_canvas_core__WEBPACK_IMPORTED_MODULE_0__.InputType.MOUSE_DOWN,
            fire: (event) => {
                const element = this.engine.getActionEventBus().getModelForEvent(event);
                // the canvas was clicked on, transition to the dragging canvas state
                if (!element) {
                    this.transitionWithEvent(this.dragCanvas, event);
                }
                // initiate dragging a new link
                else if (element instanceof _port_CustomPortModel__WEBPACK_IMPORTED_MODULE_3__.CustomPortModel) {
                    this.transitionWithEvent(this.dragNewLink, event);
                }
                // move the items (and potentially link points)
                else {
                    this.transitionWithEvent(this.dragItems, event);
                }
            }
        }));
    }
}


/***/ }),

/***/ "./lib/components/state/DragDiagramItemsState.js":
/*!*******************************************************!*\
  !*** ./lib/components/state/DragDiagramItemsState.js ***!
  \*******************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "DragDiagramItemsState": () => (/* binding */ DragDiagramItemsState)
/* harmony export */ });
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _projectstorm_react_canvas_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @projectstorm/react-canvas-core */ "webpack/sharing/consume/default/@projectstorm/react-canvas-core/@projectstorm/react-canvas-core?4a30");
/* harmony import */ var _projectstorm_react_canvas_core__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_projectstorm_react_canvas_core__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @projectstorm/react-diagrams */ "webpack/sharing/consume/default/@projectstorm/react-diagrams/@projectstorm/react-diagrams");
/* harmony import */ var _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _MoveItemsState__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./MoveItemsState */ "./lib/components/state/MoveItemsState.js");




class DragDiagramItemsState extends _MoveItemsState__WEBPACK_IMPORTED_MODULE_3__.MoveItemsState {
    constructor() {
        super();
        this.registerAction(new _projectstorm_react_canvas_core__WEBPACK_IMPORTED_MODULE_1__.Action({
            type: _projectstorm_react_canvas_core__WEBPACK_IMPORTED_MODULE_1__.InputType.MOUSE_UP,
            fire: event => {
                try {
                    const item = this.engine.getMouseElement(event.event);
                    if (item instanceof _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_2__.PortModel) {
                        lodash__WEBPACK_IMPORTED_MODULE_0__.forEach(this.initialPositions, position => {
                            if (position.item instanceof _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_2__.PointModel) {
                                const link = position.item.getParent();
                                // only care about the last links
                                if (link.getLastPoint() !== position.item) {
                                    return;
                                }
                                if (link.getSourcePort().canLinkToPort(item)) {
                                    link.setTargetPort(item);
                                    item.reportPosition();
                                    this.engine.repaintCanvas();
                                }
                            }
                        });
                    }
                }
                catch (e) {
                    // No-op
                }
            }
        }));
    }
}


/***/ }),

/***/ "./lib/components/state/DragNewLinkState.js":
/*!**************************************************!*\
  !*** ./lib/components/state/DragNewLinkState.js ***!
  \**************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "DragNewLinkState": () => (/* binding */ DragNewLinkState)
/* harmony export */ });
/* harmony import */ var _projectstorm_react_canvas_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @projectstorm/react-canvas-core */ "webpack/sharing/consume/default/@projectstorm/react-canvas-core/@projectstorm/react-canvas-core?4a30");
/* harmony import */ var _projectstorm_react_canvas_core__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_projectstorm_react_canvas_core__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _port_CustomPortModel__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../port/CustomPortModel */ "./lib/components/port/CustomPortModel.js");
/* harmony import */ var _port_CustomDynaPortModel__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../port/CustomDynaPortModel */ "./lib/components/port/CustomDynaPortModel.js");



class DragNewLinkState extends _projectstorm_react_canvas_core__WEBPACK_IMPORTED_MODULE_0__.AbstractDisplacementState {
    constructor(options = {}) {
        super({ name: 'drag-new-link' });
        this.fireEvent = (linkEvent, sourcePort) => {
            //@ts-ignore
            this.engine.fireEvent({ link: this.link, linkEvent, sourcePort }, 'droppedLink');
        };
        this.config = Object.assign({ allowLooseLinks: true, allowLinksFromLockedPorts: false }, options);
        this.registerAction(new _projectstorm_react_canvas_core__WEBPACK_IMPORTED_MODULE_0__.Action({
            type: _projectstorm_react_canvas_core__WEBPACK_IMPORTED_MODULE_0__.InputType.MOUSE_DOWN,
            fire: (event) => {
                this.port = this.engine.getMouseElement(event.event);
                if (!this.config.allowLinksFromLockedPorts && this.port.isLocked()) {
                    this.eject();
                    return;
                }
                this.link = this.port.createLinkModel();
                // if no link is given, just eject the state
                if (!this.link) {
                    this.eject();
                    return;
                }
                this.link.setSelected(true);
                this.link.setSourcePort(this.port);
                this.engine.getModel().addLink(this.link);
                this.port.reportPosition();
            }
        }));
        this.registerAction(new _projectstorm_react_canvas_core__WEBPACK_IMPORTED_MODULE_0__.Action({
            type: _projectstorm_react_canvas_core__WEBPACK_IMPORTED_MODULE_0__.InputType.MOUSE_UP,
            fire: (event) => {
                const model = this.engine.getMouseElement(event.event);
                if (!(model instanceof _port_CustomPortModel__WEBPACK_IMPORTED_MODULE_1__.CustomPortModel)) {
                    this.handleLooseLink(event);
                    return;
                }
                if (!this.port.canLinkToPort(model)) {
                    this.link.remove();
                    this.engine.repaintCanvas();
                    return;
                }
                this.handleConnectedPort(model);
                this.engine.repaintCanvas();
            }
        }));
    }
    handleConnectedPort(model) {
        if (model instanceof _port_CustomDynaPortModel__WEBPACK_IMPORTED_MODULE_2__.CustomDynaPortModel) {
            this.handleDynamicPort(model);
        }
        else {
            this.link.setTargetPort(model);
        }
        model.reportPosition();
    }
    handleDynamicPort(model) {
        // if the dynamic port has  an existing link, shift
        if (Object.keys(model.links).length > 0) {
            const newPort = model.shiftPorts();
            this.link.setTargetPort(newPort);
        }
        else {
            // otherwise spawn a new one at the end
            const newPort = model.spawnDynamicPort({ offset: 1 });
            newPort.previous = model.getID();
            model.next = newPort.getID();
            this.link.setTargetPort(model);
        }
    }
    handleLooseLink(event) {
        if (!this.config.allowLooseLinks) {
            // Weird behaviour where sourcePort's data is missing
            // For now just pass the port's data itself
            this.fireEvent(event.event, this.port);
            this.link.remove();
            this.engine.repaintCanvas();
        }
    }
    /**
     * Calculates the link's far-end point position on mouse move.
     * In order to be as precise as possible the mouse initialXRelative & initialYRelative are taken into account as well
     * as the possible engine offset
     */
    fireMouseMoved(event) {
        const portPos = this.port.getPosition();
        const zoomLevelPercentage = this.engine.getModel().getZoomLevel() / 100;
        const engineOffsetX = this.engine.getModel().getOffsetX() / zoomLevelPercentage;
        const engineOffsetY = this.engine.getModel().getOffsetY() / zoomLevelPercentage;
        const initialXRelative = this.initialXRelative / zoomLevelPercentage;
        const initialYRelative = this.initialYRelative / zoomLevelPercentage;
        const linkNextX = portPos.x - engineOffsetX + (initialXRelative - portPos.x) + event.virtualDisplacementX;
        const linkNextY = portPos.y - engineOffsetY + (initialYRelative - portPos.y) + event.virtualDisplacementY;
        this.link.getLastPoint().setPosition(linkNextX, linkNextY);
        this.engine.repaintCanvas();
    }
}


/***/ }),

/***/ "./lib/components/state/MoveItemsState.js":
/*!************************************************!*\
  !*** ./lib/components/state/MoveItemsState.js ***!
  \************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "MoveItemsState": () => (/* binding */ MoveItemsState)
/* harmony export */ });
/* harmony import */ var _projectstorm_react_canvas_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @projectstorm/react-canvas-core */ "webpack/sharing/consume/default/@projectstorm/react-canvas-core/@projectstorm/react-canvas-core?4a30");
/* harmony import */ var _projectstorm_react_canvas_core__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_projectstorm_react_canvas_core__WEBPACK_IMPORTED_MODULE_0__);

class MoveItemsState extends _projectstorm_react_canvas_core__WEBPACK_IMPORTED_MODULE_0__.AbstractDisplacementState {
    constructor() {
        super({
            name: 'move-items'
        });
        this.initialPositions = {};
        this.fireEvent = () => {
            this.engine.fireEvent({}, 'onChange');
        };
        this.registerAction(new _projectstorm_react_canvas_core__WEBPACK_IMPORTED_MODULE_0__.Action({
            type: _projectstorm_react_canvas_core__WEBPACK_IMPORTED_MODULE_0__.InputType.MOUSE_DOWN,
            fire: event => {
                const target = event.event.target;
                // find the first parent element that is allowed to be dragged (an element can be marked as non-draggable by specifying the "data-no-drag" attribute)
                let parentElement = target;
                while (parentElement && !parentElement.hasAttribute('data-no-drag')) {
                    parentElement = parentElement.parentElement;
                }
                // if we could not find any draggable parent element then reject the drag
                if (parentElement && parentElement.hasAttribute('data-no-drag')) {
                    this.eject();
                    return;
                }
                const element = this.engine.getActionEventBus().getModelForEvent(event);
                if (!element) {
                    return;
                }
                if (!element.isSelected()) {
                    this.engine.getModel().clearSelection();
                }
                element.setSelected(true);
                this.engine.repaintCanvas();
                this.initialPosition = element['position'];
                this.finalPosition = element['position'];
            }
        }));
        this.registerAction(new _projectstorm_react_canvas_core__WEBPACK_IMPORTED_MODULE_0__.Action({
            type: _projectstorm_react_canvas_core__WEBPACK_IMPORTED_MODULE_0__.InputType.MOUSE_UP,
            fire: () => {
                var _a, _b, _c, _d;
                // When node in the same position, just return
                if (((_a = this.initialPosition) === null || _a === void 0 ? void 0 : _a.x) === ((_b = this.finalPosition) === null || _b === void 0 ? void 0 : _b.x) &&
                    ((_c = this.initialPosition) === null || _c === void 0 ? void 0 : _c.y) === ((_d = this.finalPosition) === null || _d === void 0 ? void 0 : _d.y)) {
                    return;
                }
                this.fireEvent();
            }
        }));
    }
    activated(previous) {
        super.activated(previous);
        this.initialPositions = {};
    }
    fireMouseMoved(event) {
        const items = this.engine.getModel().getSelectedEntities();
        const model = this.engine.getModel();
        for (const item of items) {
            if (item instanceof _projectstorm_react_canvas_core__WEBPACK_IMPORTED_MODULE_0__.BasePositionModel) {
                if (item.isLocked()) {
                    continue;
                }
                if (!this.initialPositions[item.getID()]) {
                    this.initialPositions[item.getID()] = {
                        point: item.getPosition(),
                        item: item
                    };
                }
                const pos = this.initialPositions[item.getID()].point;
                item.setPosition(model.getGridPosition(pos.x + event.virtualDisplacementX), model.getGridPosition(pos.y + event.virtualDisplacementY));
                this.finalPosition = item.getPosition();
            }
        }
        this.engine.repaintCanvas();
    }
}


/***/ }),

/***/ "./lib/components/state/powerModeState.js":
/*!************************************************!*\
  !*** ./lib/components/state/powerModeState.js ***!
  \************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "lowPowerMode": () => (/* binding */ lowPowerMode),
/* harmony export */   "setLowPowerMode": () => (/* binding */ setLowPowerMode)
/* harmony export */ });
let lowPowerMode = false;
function setLowPowerMode(value) {
    lowPowerMode = value;
    if (value) {
        document.body.classList.add('low-powered-mode');
    }
    else {
        document.body.classList.remove('low-powered-mode');
    }
}


/***/ }),

/***/ "./lib/components/xircuitBodyWidget.js":
/*!*********************************************!*\
  !*** ./lib/components/xircuitBodyWidget.js ***!
  \*********************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "Body": () => (/* binding */ Body),
/* harmony export */   "BodyWidget": () => (/* binding */ BodyWidget),
/* harmony export */   "Content": () => (/* binding */ Content),
/* harmony export */   "Layer": () => (/* binding */ Layer),
/* harmony export */   "commandIDs": () => (/* binding */ commandIDs)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _projectstorm_react_canvas_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @projectstorm/react-canvas-core */ "webpack/sharing/consume/default/@projectstorm/react-canvas-core/@projectstorm/react-canvas-core?4a30");
/* harmony import */ var _projectstorm_react_canvas_core__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_projectstorm_react_canvas_core__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @jupyterlab/apputils */ "webpack/sharing/consume/default/@jupyterlab/apputils");
/* harmony import */ var _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _helpers_DemoCanvasWidget__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../helpers/DemoCanvasWidget */ "./lib/helpers/DemoCanvasWidget.js");
/* harmony import */ var _log_LogPlugin__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../log/LogPlugin */ "./lib/log/LogPlugin.js");
/* harmony import */ var _dialog_formDialogwidget__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../dialog/formDialogwidget */ "./lib/dialog/formDialogwidget.js");
/* harmony import */ var _dialog_FormDialog__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../dialog/FormDialog */ "./lib/dialog/FormDialog.js");
/* harmony import */ var _dialog_LiteralInputDialog__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../dialog/LiteralInputDialog */ "./lib/dialog/LiteralInputDialog.js");
/* harmony import */ var _dialog_input_dialogues_VariableInput__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../dialog/input-dialogues/VariableInput */ "./lib/dialog/input-dialogues/VariableInput.js");
/* harmony import */ var _dialog_RunDialog__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../dialog/RunDialog */ "./lib/dialog/RunDialog.js");
/* harmony import */ var _server_handler__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../server/handler */ "./lib/server/handler.js");
/* harmony import */ var _context_menu_ComponentsPanel__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../context-menu/ComponentsPanel */ "./lib/context-menu/ComponentsPanel.js");
/* harmony import */ var _context_menu_NodeActionsPanel__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../context-menu/NodeActionsPanel */ "./lib/context-menu/NodeActionsPanel.js");
/* harmony import */ var _tray_library_GeneralComponentLib__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../tray_library/GeneralComponentLib */ "./lib/tray_library/GeneralComponentLib.js");
/* harmony import */ var _tray_library_AdvanceComponentLib__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../tray_library/AdvanceComponentLib */ "./lib/tray_library/AdvanceComponentLib.js");
/* harmony import */ var _state_powerModeState__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./state/powerModeState */ "./lib/components/state/powerModeState.js");
/* harmony import */ var _emotion_styled__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @emotion/styled */ "webpack/sharing/consume/default/@emotion/styled/@emotion/styled?2715");
/* harmony import */ var _emotion_styled__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_emotion_styled__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var rc_dialog_assets_bootstrap_css__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! rc-dialog/assets/bootstrap.css */ "./node_modules/rc-dialog/assets/bootstrap.css");


















const Body = (_emotion_styled__WEBPACK_IMPORTED_MODULE_3___default().div) `
		flex-grow: 1;
		display: flex;
		flex-direction: column;
		min-height: 100%;
		height: 800px;
	`;
const Content = (_emotion_styled__WEBPACK_IMPORTED_MODULE_3___default().div) `
		display: flex;
		flex-grow: 1;
	`;
const Layer = (_emotion_styled__WEBPACK_IMPORTED_MODULE_3___default().div) `
		position: relative;
		flex-grow: 1;
	`;
const commandIDs = {
    openDocManager: 'docmanager:open',
    newDocManager: 'docmanager:new-untitled',
    saveDocManager: 'docmanager:save',
    reloadDocManager: 'docmanager:reload',
    createNewXircuit: 'Xircuit-editor:create-new',
    saveXircuit: 'Xircuit-editor:save-node',
    compileXircuit: 'Xircuit-editor:compile-node',
    runXircuit: 'Xircuit-editor:run-node',
    lockXircuit: 'Xircuit-editor:lock-node',
    openScript: 'Xircuit-editor:open-node-script',
    undo: 'Xircuit-editor:undo',
    redo: 'Xircuit-editor:redo',
    cutNode: 'Xircuit-editor:cut-node',
    copyNode: 'Xircuit-editor:copy-node',
    pasteNode: 'Xircuit-editor:paste-node',
    reloadNode: 'Xircuit-editor:reload-node',
    reloadAllNodes: 'Xircuit-editor:reload-all-nodes',
    toggleAllLinkAnimation: 'Xircuit-editor:toggle-all-link-animation',
    editNode: 'Xircuit-editor:edit-node',
    deleteEntity: 'Xircuit-editor:delete-entities',
    addNodeGivenPosition: 'Xircuit-editor:add-node',
    connectNodeByLink: 'Xircuit-editor:connect-node',
    connectLinkToObviousPorts: 'Xircuit-editor:connect-obvious-link',
    addCommentNode: 'Xircuit-editor:add-comment-node',
    compileFile: 'Xircuit-editor:compile-file',
    nextNode: 'Xircuit-editor:next-node',
    outputMsg: 'Xircuit-log:logOutputMessage',
    executeToOutputPanel: 'Xircuit-output-panel:execute'
};
const BodyWidget = ({ context, xircuitsApp, app, shell, commands, widgetId, fetchComponentsSignal, saveXircuitSignal, compileXircuitSignal, runXircuitSignal, runTypeXircuitSignal, lockNodeSignal, reloadAllNodesSignal, toggleAllLinkAnimationSignal, }) => {
    const xircuitLogger = new _log_LogPlugin__WEBPACK_IMPORTED_MODULE_5__.Log(app);
    const [saved, setSaved] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(false);
    const [compiled, setCompiled] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(false);
    const [initialize, setInitialize] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(true);
    const [runConfigs, setRunConfigs] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)("");
    const [lastConfig, setLastConfigs] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)("");
    const [stringNodes, setStringNodes] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)([]);
    const [intNodes, setIntNodes] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)([]);
    const [floatNodes, setFloatNodes] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)([]);
    const [boolNodes, setBoolNodes] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)([]);
    const [componentList, setComponentList] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)([]);
    const [inDebugMode, setInDebugMode] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(false);
    const [currentIndex, setCurrentIndex] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(-1);
    const [runType, setRunType] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)("run");
    const [runTypesCfg, setRunTypesCfg] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)("");
    const initialRender = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(true);
    const contextRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(context);
    const notInitialRender = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(false);
    const onChange = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)(() => {
        if (contextRef.current.isReady) {
            let currentModel = xircuitsApp.getDiagramEngine().getModel().serialize();
            contextRef.current.model.fromString(JSON.stringify(currentModel, replacer, 4));
            setSaved(false);
        }
    }, []);
    function replacer(key, value) {
        if (key == "x" || key == "y")
            return Math.round((value + Number.EPSILON) * 1000) / 1000;
        return value;
    }
    (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
        const currentContext = contextRef.current;
        const changeHandler = () => {
            const modelStr = currentContext.model.toString();
            if (!isJSON(modelStr)) {
                // When context can't be parsed, just return
                return;
            }
            try {
                if (notInitialRender.current) {
                    const model = currentContext.model.toJSON();
                    let deserializedModel = xircuitsApp.customDeserializeModel(model, initialRender.current);
                    deserializedModel.registerListener({
                        // Detect changes when node is dropped or deleted
                        nodesUpdated: () => {
                            // Add delay for links to disappear 
                            const timeout = setTimeout(() => {
                                onChange();
                                setInitialize(false);
                            }, 10);
                            return () => clearTimeout(timeout);
                        },
                        linksUpdated: (event) => {
                            const timeout = setTimeout(() => {
                                event.link.registerListener({
                                    /**
                                     * sourcePortChanged
                                     * Detect changes when link is connected
                                     */
                                    sourcePortChanged: e => {
                                        onChange();
                                    },
                                    /**
                                     * targetPortChanged
                                     * Detect changes when link is connected
                                     */
                                    targetPortChanged: e => {
                                        const sourceLink = e.entity;
                                        app.commands.execute(commandIDs.connectLinkToObviousPorts, { draggedLink: sourceLink });
                                        onChange();
                                    },
                                    /**
                                     * entityRemoved
                                     * Detect changes when new link is removed
                                     */
                                    entityRemoved: e => {
                                        onChange();
                                    }
                                });
                            }, 100); // You can adjust the delay as needed
                            // Don’t forget to clear the timeout when unmounting or when the component is destroyed.
                            return () => clearTimeout(timeout);
                        }
                    });
                    xircuitsApp.getDiagramEngine().setModel(deserializedModel);
                    initialRender.current = false;
                }
                else {
                    // Clear undo history when first time rendering
                    notInitialRender.current = true;
                    currentContext.model.sharedModel.clearUndoHistory();
                    // Register engine listener just once
                    xircuitsApp.getDiagramEngine().registerListener({
                        droppedLink: event => showComponentPanelFromLink(event),
                        hidePanel: () => hidePanel(),
                        onChange: () => onChange()
                    });
                }
            }
            catch (e) {
                (0,_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_2__.showErrorMessage)('Error', react__WEBPACK_IMPORTED_MODULE_0___default().createElement("pre", null, e));
            }
        };
        currentContext.ready.then(changeHandler);
        currentContext.model.contentChanged.connect(changeHandler);
        return () => {
            currentContext.model.contentChanged.disconnect(changeHandler);
        };
    }, []);
    const isJSON = (str) => {
        try {
            return (JSON.parse(str) && !!str);
        }
        catch (e) {
            return false;
        }
    };
    const getTargetNodeModelId = (linkModels, sourceId) => {
        for (let i = 0; i < linkModels.length; i++) {
            let linkModel = linkModels[i];
            if (linkModel.getSourcePort().getNode().getID() === sourceId && linkModel.getTargetPort().getOptions()["label"] == '▶') {
                return linkModel.getTargetPort().getNode().getID();
            }
        }
        return null;
    };
    const getNodeModelByName = (nodeModels, name) => {
        for (let i = 0; i < nodeModels.length; i++) {
            let nodeModel = nodeModels[i];
            if (nodeModel.getOptions()["name"] === name) {
                return nodeModel;
            }
        }
        return null;
    };
    const getNodeModelById = (nodeModels, id) => {
        for (let i = 0; i < nodeModels.length; i++) {
            let nodeModel = nodeModels[i];
            if (nodeModel.getID() === id) {
                return nodeModel;
            }
        }
        return null;
    };
    const getAllNodesFromStartToFinish = () => {
        let model = xircuitsApp.getDiagramEngine().getModel();
        let nodeModels = model.getNodes();
        let branchNodes = [];
        let finishedNodes = [];
        let startNodeModel = getNodeModelByName(nodeModels, 'Start');
        if (startNodeModel == null) {
            startNodeModel = getNodeModelByName(nodeModels, '🔴Start');
        }
        if (startNodeModel) {
            let sourceNodeModelId = startNodeModel.getID();
            let retNodeModels = [];
            retNodeModels.push(startNodeModel);
            while (getTargetNodeModelId(model.getLinks(), sourceNodeModelId) != null || finishedNodes.length != 0) {
                let getTargetNode = getTargetNodeModelId(model.getLinks(), sourceNodeModelId);
                const nodeModel = getNodeModelById(nodeModels, getTargetNode);
                // When the next node is Finish, set its previous node extras's nextNode properties as null
                if (getTargetNode != null && nodeModel.getOptions()['name'] == 'Finish') {
                    const beforeFinishNode = getNodeModelById(nodeModels, sourceNodeModelId);
                    beforeFinishNode['extras']['nextNode'] = 'None';
                }
                // This will go to the next node of branch node given its source branch node ID
                const branchWorkflow = (nodeId) => {
                    let branchNode = branchNodes.find(x => x.currentNode.getID() == nodeId);
                    if (branchNode == undefined) {
                        //When no flowPorts connected, skip to finish port's Node
                        finishedNodes.forEach((node) => {
                            if (nodeId === node.currentNode.getID())
                                finishWorkflow(node);
                        });
                    }
                    else {
                        let checkIfNodeIsBranchNode = checkIfNodeHasBranchFlowport(branchNode.nextNode);
                        if (checkIfNodeIsBranchNode) {
                            // This will check if the next node of the branch node is another branch node
                            checkIfNextNodeHasBranchFlowport(branchNode.nextNode);
                        }
                        else {
                            sourceNodeModelId = branchNode.nextNode.getID();
                        }
                        retNodeModels.push(branchNode.nextNode);
                        branchNodes.forEach((node, index) => {
                            // Remove it from the the list to indicate we already go through its workflow
                            if (branchNode.nextNode === node.nextNode)
                                branchNodes.splice(index, 1);
                        });
                    }
                };
                // This will go to the next node of finish workflow's node given its source branch node ID
                const finishWorkflow = (latestFinishedNode) => {
                    var _a;
                    let checkIfNodeIsBranchNode = checkIfNodeHasBranchFlowport(latestFinishedNode === null || latestFinishedNode === void 0 ? void 0 : latestFinishedNode.finishNode);
                    if (checkIfNodeIsBranchNode) {
                        // This will check if the finish node of the branch node is another branch node
                        checkIfNextNodeHasBranchFlowport(latestFinishedNode === null || latestFinishedNode === void 0 ? void 0 : latestFinishedNode.finishNode);
                    }
                    else {
                        sourceNodeModelId = (_a = latestFinishedNode === null || latestFinishedNode === void 0 ? void 0 : latestFinishedNode.finishNode) === null || _a === void 0 ? void 0 : _a.getID();
                    }
                    retNodeModels.push(latestFinishedNode === null || latestFinishedNode === void 0 ? void 0 : latestFinishedNode.finishNode);
                    finishedNodes.forEach((node, index) => {
                        // Remove it from the the list 
                        // to indicate we already finish going through all of this branch node's workflow
                        if ((latestFinishedNode === null || latestFinishedNode === void 0 ? void 0 : latestFinishedNode.finishNode) === node.finishNode)
                            finishedNodes.splice(index, 1);
                    });
                };
                // This will check if the next node of the branch node is another branch node
                const checkIfNextNodeHasBranchFlowport = (branchNode) => {
                    let tempNextNodeOfBranch = branchNodes.find(x => x.currentNode.getID() == branchNode.getID()).nextNode;
                    checkIfNodeHasBranchFlowport(tempNextNodeOfBranch);
                    sourceNodeModelId = tempNextNodeOfBranch.getID();
                    retNodeModels.push(tempNextNodeOfBranch);
                    branchNodes.forEach((node, index) => {
                        // Remove it from the the list to indicate we already go through its workflow
                        if (tempNextNodeOfBranch === node.nextNode)
                            branchNodes.splice(index, 1);
                    });
                };
                // This will check if the node have branch flowports
                const checkIfNodeHasBranchFlowport = (currentNode) => {
                    var _a;
                    const currentBranchNodesLength = branchNodes.length;
                    if (currentNode == undefined || currentNode == null) {
                        return;
                    }
                    (_a = currentNode['portsOut']) === null || _a === void 0 ? void 0 : _a.map((p) => {
                        if (p.getName().includes('out-flow')) {
                            const branchFlowportLinks = p.links;
                            const sameBranchNode = finishedNodes.find(x => x.currentNode.getID() == currentNode.getID());
                            const finishedLink = currentNode.getPorts()['out-0'].links;
                            let getFinishNode;
                            if (Object.keys(finishedLink).length != 0) {
                                for (let linkID in finishedLink) {
                                    let link = finishedLink[linkID];
                                    if (Object.keys(finishedLink).length != 0) {
                                        getFinishNode = link.getTargetPort().getParent();
                                        currentNode['extras']['finishNodeId'] = getFinishNode.getID();
                                    }
                                }
                            }
                            else {
                                // When there is no finish node, set finishNodeId to None
                                getFinishNode = null;
                                currentNode['extras']['finishNodeId'] = 'None';
                            }
                            if (finishedNodes.length == 0 || !sameBranchNode) {
                                // When there is no branch node or the same branch node,
                                // Get the branch node and its next node of finish port
                                finishedNodes.push({
                                    'currentNode': currentNode,
                                    'finishNode': getFinishNode
                                });
                                currentNode['extras']['isBranchNode'] = true; // To indicate it's a branch component
                            }
                            for (let linkID in branchFlowportLinks) {
                                let link = branchFlowportLinks[linkID];
                                if (Object.keys(link).length != 0) {
                                    const nextBranchFlowportNode = link.getTargetPort().getParent();
                                    branchNodes.push({
                                        // Get the branch node and its next node of its branch flowports
                                        'currentNode': currentNode,
                                        'nextNode': nextBranchFlowportNode
                                    });
                                    // Save the source branch Id and its port Id at each next node of the branch node
                                    nextBranchFlowportNode['extras']['sourceBranchId'] = currentNode.getID();
                                    nextBranchFlowportNode['extras']['portId'] = p.getID();
                                }
                            }
                        }
                    });
                    if (currentBranchNodesLength !== branchNodes.length) {
                        // If the next node is branch node, return true
                        return true;
                    }
                    return false;
                };
                // When next node is empty check if there's any branch component,
                // continue to finish port where its branches using the saved node Id.
                if (getTargetNode == null) {
                    const getCurrentNode = getNodeModelById(nodeModels, sourceNodeModelId);
                    getCurrentNode['extras']['nextNode'] = 'None';
                    if (branchNodes.length != 0) {
                        // When there still a branch flowports, iterate through branch workflow again
                        let latestBranchNode = branchNodes[branchNodes.length - 1];
                        branchWorkflow(latestBranchNode.currentNode.getID());
                        continue;
                    }
                    // When there is no more branch workflow to iterate, continue with the finish port workflow
                    const latestFinishedNode = finishedNodes[finishedNodes.length - 1];
                    if (latestFinishedNode.finishNode == null) {
                        // When there's no next node, remove from list
                        finishedNodes.forEach((node, index) => {
                            // Remove it from the the list 
                            // to indicate we already finish going through all of this branch node's workflow
                            if ((latestFinishedNode === null || latestFinishedNode === void 0 ? void 0 : latestFinishedNode.currentNode) === node.currentNode)
                                finishedNodes.splice(index, 1);
                        });
                        continue;
                    }
                    finishWorkflow(latestFinishedNode); // Every finish node branch workflow
                    continue;
                }
                if (getTargetNode) {
                    checkIfNodeHasBranchFlowport(nodeModel); // This will check if the node have branch flowports
                    if (nodeModel) {
                        // If there are branch flowports, get its node Id.
                        if (finishedNodes.length != 0) {
                            const latestBranchNode = finishedNodes[finishedNodes.length - 1].currentNode;
                            if (latestBranchNode.getID() == nodeModel.getID()) {
                                // Get the branch node's Id and iterate through it branch workflow.
                                retNodeModels.push(nodeModel);
                                branchWorkflow(nodeModel.getID());
                                continue;
                            }
                        }
                        sourceNodeModelId = nodeModel.getID();
                        retNodeModels.push(nodeModel);
                    }
                }
            }
            return retNodeModels;
        }
        return null;
    };
    const showErrorDialog = (title, errorMsg) => {
        (0,_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_2__.showDialog)({
            title,
            body: (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("pre", null, errorMsg)),
            buttons: [_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_2__.Dialog.warnButton({ label: 'OK' })]
        });
    };
    const checkAllNodesConnected = () => {
        let allNodes = getAllNodesFromStartToFinish();
        let lastNode = allNodes[allNodes.length - 1];
        if (lastNode['name'] != 'Finish') {
            // When last node is not Finish node, check failed and show error tooltip
            lastNode.getOptions().extras["borderColor"] = "red";
            lastNode.getOptions().extras["tip"] = `Please make sure this **${lastNode['name']}** node end with **Finish** node`;
            lastNode.setSelected(true);
            return false;
        }
        return true;
    };
    const checkAllCompulsoryInPortsConnected = () => {
        let allNodes = getAllNodesFromStartToFinish();
        for (let i = 0; i < allNodes.length; i++) {
            for (let k = 0; k < allNodes[i]["portsIn"].length; k++) {
                let node = allNodes[i]["portsIn"][k];
                if (node.getOptions()["label"].startsWith("★") && Object.keys(node.getLinks()).length == 0) {
                    allNodes[i].getOptions().extras["borderColor"] = "red";
                    allNodes[i].getOptions().extras["tip"] = "Please make sure the [★]COMPULSORY InPorts are connected ";
                    allNodes[i].setSelected(true);
                    return false;
                }
            }
        }
        return true;
    };
    const handleSaveClick = async () => {
        var _a;
        // Only save xircuit if it is currently in focus
        // This must be first to avoid unnecessary complication
        if (((_a = shell.currentWidget) === null || _a === void 0 ? void 0 : _a.id) !== widgetId) {
            return;
        }
        onChange();
        setInitialize(true);
        setSaved(true);
        await commands.execute(commandIDs.saveDocManager);
    };
    const handleCompileClick = () => {
        var _a;
        // Only compile xircuit if it is currently in focus
        // This must be first to avoid unnecessary complication
        if (((_a = shell.currentWidget) === null || _a === void 0 ? void 0 : _a.id) !== widgetId) {
            return;
        }
        let allNodesConnected = checkAllNodesConnected();
        if (!saved) {
            alert("Please save before compiling.");
            return;
        }
        if (!allNodesConnected) {
            alert("Please connect all the nodes before compiling.");
            return;
        }
        let showOutput = true;
        setCompiled(true);
        commands.execute(commandIDs.compileFile, { showOutput, componentList });
    };
    const saveAndCompileAndRun = async () => {
        //This is to avoid running xircuits while in dirty state
        if (contextRef.current.model.dirty) {
            const dialogResult = await (0,_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_2__.showDialog)({
                title: 'This xircuits contains unsaved changes.',
                body: 'To run the xircuits the changes need to be saved.',
                buttons: [
                    _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_2__.Dialog.cancelButton(),
                    _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_2__.Dialog.okButton({ label: 'Save and Run' })
                ]
            });
            if (dialogResult.button && dialogResult.button.accept === true) {
                await handleSaveClick();
            }
            else {
                // Don't proceed if cancel button pressed
                return;
            }
        }
        // compile
        let allNodesConnected = checkAllNodesConnected();
        let allCompulsoryNodesConnected = checkAllCompulsoryInPortsConnected();
        if (!allNodesConnected) {
            alert("Please connect all the nodes before running.");
        }
        if (!allCompulsoryNodesConnected) {
            alert("Please connect all [★]COMPULSORY InPorts.");
            return;
        }
        let showOutput = false;
        // Only compile when 'Run' is chosen
        if (runType == 'run') {
            commands.execute(commandIDs.compileFile, { showOutput, componentList });
            setCompiled(true);
        }
        // Run Mode
        context.ready.then(async () => {
            let runArgs = await handleRunDialog();
            let runCommand = runArgs["commandStr"];
            let config = runArgs["config"];
            if (runArgs) {
                commands.execute(commandIDs.executeToOutputPanel, { runCommand, runType, config });
            }
        });
    };
    const handleRunClick = async () => {
        var _a;
        // Only run xircuit if it is currently in focus
        // This must be first to avoid unnecessary complication
        if (((_a = shell.currentWidget) === null || _a === void 0 ? void 0 : _a.id) !== widgetId) {
            return;
        }
        saveAndCompileAndRun();
    };
    const handleLockClick = () => {
        var _a;
        // Only lock node if xircuits is currently in focus
        // This must be first to avoid unnecessary complication
        if (((_a = shell.currentWidget) === null || _a === void 0 ? void 0 : _a.id) !== widgetId) {
            return;
        }
        let allNodes = getAllNodesFromStartToFinish();
        allNodes.forEach((node) => {
            const compulsaryNodes = node.getOptions()["name"];
            if (!node.isLocked()) {
                if (compulsaryNodes !== 'Start' && compulsaryNodes !== 'Finish') {
                    node.setSelected(true);
                    node.setLocked(true);
                }
            }
        });
    };
    const handleReloadAll = () => {
        var _a;
        // This must be first to avoid unnecessary complication
        if (((_a = shell.currentWidget) === null || _a === void 0 ? void 0 : _a.id) !== widgetId) {
            return;
        }
        let allNodes = xircuitsApp.getDiagramEngine().getModel().getNodes();
        allNodes.forEach(node => node.setSelected(true));
        app.commands.execute(commandIDs.reloadNode);
    };
    const handleToggleAllLinkAnimation = () => {
        var _a;
        // This must be first to avoid unnecessary complication
        if (((_a = shell.currentWidget) === null || _a === void 0 ? void 0 : _a.id) !== widgetId) {
            return;
        }
        let powerMode = _state_powerModeState__WEBPACK_IMPORTED_MODULE_6__.lowPowerMode;
        (0,_state_powerModeState__WEBPACK_IMPORTED_MODULE_6__.setLowPowerMode)(!powerMode);
    };
    async function getRunTypesFromConfig(request) {
        const dataToSend = { "config_request": request };
        try {
            const server_reply = await (0,_server_handler__WEBPACK_IMPORTED_MODULE_7__.requestAPI)('config/run', {
                body: JSON.stringify(dataToSend),
                method: 'POST',
            });
            return server_reply;
        }
        catch (reason) {
            console.error(`Error on POST config/run ${dataToSend}.\n${reason}`);
        }
    }
    const getRunTypeFromConfig = async () => {
        const configuration = await getRunTypesFromConfig("RUN_TYPES");
        const error_msg = configuration["err_msg"];
        if (error_msg) {
            (0,_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_2__.showDialog)({
                title: 'Failed parsing data from config.ini',
                body: (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("pre", null, error_msg)),
                buttons: [_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_2__.Dialog.warnButton({ label: 'OK' })]
            });
        }
        setRunTypesCfg(configuration["run_types"]);
        setRunConfigs(configuration["run_types_config"]);
    };
    (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
        // Get run configuration when in 'Remote Run' mode only
        if (runType == 'remote-run') {
            getRunTypeFromConfig();
        }
        else {
            setRunConfigs("");
        }
        context.ready.then(() => {
            const setterByType = {
                'string': setStringNodes,
                'int': setIntNodes,
                'float': setFloatNodes,
                'boolean': setBoolNodes
            };
            if (initialize) {
                let allNodes = xircuitsApp.getDiagramEngine().getModel().getNodes();
                let nodesCount = allNodes.length;
                for (let i = 0; i < nodesCount; i++) {
                    let nodeName = allNodes[i].getOptions()["name"];
                    if (nodeName.startsWith("Argument")) {
                        let regEx = /\(([^)]+)\)/;
                        let result = nodeName.match(regEx);
                        let nodeText = nodeName.split(": ");
                        setterByType[result[1]](nodes => ([...nodes, nodeText[nodeText.length - 1]].sort()));
                    }
                }
            }
            else {
                Object.values(setterByType).forEach(set => set([]));
            }
        });
    }, [initialize, runType]);
    const handleRunDialog = async () => {
        var _a, _b;
        let title = 'Run';
        const dialogOptions = {
            title,
            body: (0,_dialog_formDialogwidget__WEBPACK_IMPORTED_MODULE_8__.formDialogWidget)(react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_dialog_RunDialog__WEBPACK_IMPORTED_MODULE_9__.RunDialog, { runTypes: runTypesCfg, runConfigs: runConfigs, lastConfig: lastConfig, childStringNodes: stringNodes, childBoolNodes: boolNodes, childIntNodes: intNodes, childFloatNodes: floatNodes })),
            buttons: [_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_2__.Dialog.cancelButton(), _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_2__.Dialog.okButton({ label: ('Start') })],
            defaultButton: 1,
            focusNodeSelector: '#name'
        };
        const dialogResult = await (0,_dialog_FormDialog__WEBPACK_IMPORTED_MODULE_10__.showFormDialog)(dialogOptions);
        if (dialogResult["button"]["label"] == 'Cancel') {
            // When Cancel is clicked on the dialog, just return
            return false;
        }
        // Remember the last config chose and set the chosen config to output
        let config;
        let runType = (_a = dialogResult["value"]['runType']) !== null && _a !== void 0 ? _a : "";
        let runConfig = (_b = dialogResult["value"]['runConfig']) !== null && _b !== void 0 ? _b : "";
        if (runConfigs.length != 0) {
            runConfigs.map(cfg => {
                if (cfg.run_type == runType && cfg.run_config_name == runConfig) {
                    config = cfg;
                    setLastConfigs(cfg);
                }
            });
        }
        const date = new Date();
        xircuitLogger.info(`experiment name: ${date.toLocaleString()}`);
        const commandStr = [
            stringNodes.filter(param => param != "experiment name"),
            boolNodes, intNodes, floatNodes
        ].filter(it => !!it).reduce((s, nodes) => {
            return nodes
                .filter(param => !!dialogResult.value[param])
                .reduce((cmd, param) => {
                xircuitLogger.info(param + ": " + dialogResult.value[param]);
                let filteredParam = param.replace(/\s+/g, "_");
                filteredParam = filteredParam.toLowerCase();
                return `${cmd} --${filteredParam} ${dialogResult.value[param]}`;
            }, s);
        }, "");
        return { commandStr, config };
    };
    const connectSignal = ([signal, handler]) => {
        (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
            signal.connect(handler);
            return () => {
                signal.disconnect(handler);
            };
        }, [signal, handler]);
    };
    const signalConnections = [
        [saveXircuitSignal, handleSaveClick],
        [compileXircuitSignal, handleCompileClick],
        [runXircuitSignal, handleRunClick],
        [lockNodeSignal, handleLockClick],
        [reloadAllNodesSignal, handleReloadAll],
        [toggleAllLinkAnimationSignal, handleToggleAllLinkAnimation]
    ];
    signalConnections.forEach(connectSignal);
    (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
        fetchComponentsSignal.connect((_, args) => {
            setComponentList(args);
        });
    }, [fetchComponentsSignal]);
    (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
        let runType;
        runTypeXircuitSignal.connect((_, args) => {
            runType = args["runType"];
            setRunType(runType);
        });
    }, [runTypeXircuitSignal]);
    const connectLinkToItsLiteral = async (linkName, event) => {
        let portType = linkName.split("-")[1];
        // if multiple types provided, Use the first type.
        if (portType.includes(',')) {
            portType = portType.replace('Union', '');
            portType = portType.replace(/[\[\]]/g, '');
            portType = portType.split(',')[0];
        }
        let nodeType = portType;
        let varInput = '';
        let errorMsg;
        switch (portType) {
            case 'int':
                nodeType = 'Integer';
                break;
            case 'boolean':
                let boolTitle = 'Enter boolean value: ';
                const dialogOptions = (0,_dialog_LiteralInputDialog__WEBPACK_IMPORTED_MODULE_11__.inputDialog)({ title: boolTitle, oldValue: "", type: 'boolean' });
                const dialogResult = await (0,_dialog_FormDialog__WEBPACK_IMPORTED_MODULE_10__.showFormDialog)(dialogOptions);
                if ((0,_tray_library_GeneralComponentLib__WEBPACK_IMPORTED_MODULE_12__.cancelDialog)(dialogResult))
                    return;
                let boolValue = dialogResult["value"][boolTitle];
                if (boolValue == false) {
                    nodeType = 'False';
                }
                else {
                    nodeType = 'True';
                }
                break;
            case 'any':
                // When inPort is 'any' type, get the correct literal type based on the first character inputed
                let portAnyType = await (0,_dialog_input_dialogues_VariableInput__WEBPACK_IMPORTED_MODULE_13__.getItsLiteralType)();
                if (portAnyType == undefined)
                    return;
                nodeType = portAnyType.nodeType;
                varInput = portAnyType.varInput;
                break;
            default:
                nodeType = portType.charAt(0).toUpperCase() + portType.slice(1);
                break;
        }
        let current_node = await (0,_tray_library_AdvanceComponentLib__WEBPACK_IMPORTED_MODULE_14__.fetchNodeByName)('Literal ' + nodeType);
        let node = await (0,_tray_library_GeneralComponentLib__WEBPACK_IMPORTED_MODULE_12__.GeneralComponentLibrary)({ model: current_node, variableValue: varInput });
        if (node == undefined)
            return;
        let nodePosition = event.linkEvent;
        let sourceLink = { link: event.link, sourcePort: event.sourcePort };
        await app.commands.execute(commandIDs.addNodeGivenPosition, { node, nodePosition });
        await app.commands.execute(commandIDs.connectNodeByLink, { targetNode: node, sourceLink, isParameterLink: true });
    };
    /**Component Panel & Node Action Panel Context Menu */
    const [isComponentPanelShown, setIsComponentPanelShown] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(false);
    const [actionPanelShown, setActionPanelShown] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(false);
    const [dontHidePanel, setDontHidePanel] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(false);
    const [componentPanelPosition, setComponentPanelPosition] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)({ x: 0, y: 0 });
    const [actionPanelPosition, setActionPanelPosition] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)({ x: 0, y: 0 });
    const [nodePosition, setNodePosition] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)();
    const [looseLinkData, setLooseLinkData] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)({});
    const [isParameterLink, setIsParameterLink] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(false);
    // Component & Action panel position
    const panelPosition = (event) => {
        let newPanelPosition = {
            x: event.pageX,
            y: event.pageY,
        };
        const canvas = event.view;
        const newCenterPosition = {
            x: canvas.innerWidth / 2,
            y: canvas.innerHeight / 2,
        };
        console.log(newCenterPosition.x, newPanelPosition.x, newCenterPosition.y, newPanelPosition.y);
        const menuDimension = {
            x: 105,
            y: 290
        };
        const fileBrowserWidth = document.getElementsByClassName("p-SplitPanel-child")[1].clientWidth;
        const tabWidth = document.getElementsByClassName("lm-TabBar")[0].clientWidth;
        const yOffset = 84;
        if (newPanelPosition.x > newCenterPosition.x && newPanelPosition.y > newCenterPosition.y) {
            // Bottom right
            newPanelPosition.x = newPanelPosition.x - fileBrowserWidth - tabWidth - menuDimension.x;
            newPanelPosition.y = newPanelPosition.y - menuDimension.y - yOffset;
        }
        else if (newPanelPosition.x > newCenterPosition.x && newPanelPosition.y < newCenterPosition.y) {
            // Top right
            newPanelPosition.x = newPanelPosition.x - fileBrowserWidth - tabWidth - menuDimension.x;
            newPanelPosition.y = newPanelPosition.y - yOffset;
        }
        else if (newPanelPosition.x < newCenterPosition.x && newPanelPosition.y > newCenterPosition.y) {
            // Bottom left
            newPanelPosition.x = newPanelPosition.x - fileBrowserWidth - tabWidth;
            newPanelPosition.y = newPanelPosition.y - menuDimension.y - yOffset;
        }
        else {
            // Top left
            newPanelPosition.x = newPanelPosition.x - fileBrowserWidth - tabWidth;
            newPanelPosition.y = newPanelPosition.y - yOffset;
        }
        setComponentPanelPosition(newPanelPosition);
        setActionPanelPosition(newPanelPosition);
    };
    // Show the component panel context menu
    const showComponentPanel = (event) => {
        setActionPanelShown(false);
        setIsComponentPanelShown(false);
        const node_position = xircuitsApp.getDiagramEngine().getRelativeMousePoint(event);
        setNodePosition(node_position);
        panelPosition(event);
        setIsComponentPanelShown(true);
    };
    // Show the component panel from dropped link
    const showComponentPanelFromLink = async (event) => {
        setActionPanelShown(false);
        setIsComponentPanelShown(false);
        const linkName = event.link.sourcePort.options.name;
        if (linkName.startsWith("parameter")) {
            // Don't show panel when loose link from parameter outPorts
            if (linkName.includes("parameter-out")) {
                return;
            }
            // When loose link from type InPort, connect to its respective literal node
            connectLinkToItsLiteral(linkName, event);
            return;
        }
        setLooseLinkData({ link: event.link, sourcePort: event.sourcePort });
        setNodePosition(event.linkEvent);
        panelPosition(event.linkEvent);
        setIsComponentPanelShown(true);
    };
    // Hide component and node action panel
    const hidePanel = () => {
        setIsComponentPanelShown(false);
        setActionPanelShown(false);
        setLooseLinkData(null);
        setIsParameterLink(false);
    };
    // Show the nodeActionPanel context menu
    const showNodeActionPanel = (event) => {
        // Disable the default context menu
        event.preventDefault();
        setActionPanelShown(false);
        setIsComponentPanelShown(false);
        const node_position = xircuitsApp.getDiagramEngine().getRelativeMousePoint(event);
        setNodePosition(node_position);
        panelPosition(event);
        setActionPanelShown(true);
    };
    const preventDefault = (event) => {
        event.preventDefault();
    };
    const handleDropEvent = async (event) => {
        let data = JSON.parse(event.dataTransfer.getData("storm-diagram-node"));
        let component_task = componentList.map(x => x["task"]);
        let drop_node = component_task.indexOf(data.name);
        let current_node;
        let node = null;
        if (drop_node != -1) {
            current_node = componentList[drop_node];
        }
        if (current_node != undefined) {
            if (current_node.header == "GENERAL") {
                node = await (0,_tray_library_GeneralComponentLib__WEBPACK_IMPORTED_MODULE_12__.GeneralComponentLibrary)({ model: current_node });
            }
            else if (current_node.header == "ADVANCED") {
                node = (0,_tray_library_AdvanceComponentLib__WEBPACK_IMPORTED_MODULE_14__.AdvancedComponentLibrary)({ model: current_node });
            }
        }
        // note:  can not use the same port name in the same node,or the same name port can not link to other ports
        // you can use shift + click and then use delete to delete link
        if (node != null) {
            let point = xircuitsApp.getDiagramEngine().getRelativeMousePoint(event);
            node.setPosition(point);
            xircuitsApp.getDiagramEngine().getModel().addNode(node);
            if (node["name"].startsWith("Argument")) {
                setInitialize(true);
            }
            setSaved(false);
            setCompiled(false);
        }
    };
    const handleClick = (event) => {
        if (event.ctrlKey || event.metaKey) {
            showComponentPanel(event);
            return;
        }
        if (dontHidePanel) {
            return;
        }
        hidePanel();
    };
    return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement(Body, null,
        react__WEBPACK_IMPORTED_MODULE_0___default().createElement(Content, null,
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement(Layer, { onDrop: handleDropEvent, onDragOver: preventDefault, onMouseOver: preventDefault, onMouseUp: preventDefault, onMouseDown: preventDefault, onContextMenu: showNodeActionPanel, onClick: handleClick },
                react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_helpers_DemoCanvasWidget__WEBPACK_IMPORTED_MODULE_15__.DemoCanvasWidget, null,
                    react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_projectstorm_react_canvas_core__WEBPACK_IMPORTED_MODULE_1__.CanvasWidget, { engine: xircuitsApp.getDiagramEngine() }),
                    isComponentPanelShown && (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { onMouseEnter: () => setDontHidePanel(true), onMouseLeave: () => setDontHidePanel(false), id: 'component-panel', style: {
                            top: componentPanelPosition.y,
                            left: componentPanelPosition.x
                        }, className: "add-component-panel" },
                        react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_context_menu_ComponentsPanel__WEBPACK_IMPORTED_MODULE_16__["default"], { lab: app, eng: xircuitsApp.getDiagramEngine(), nodePosition: nodePosition, linkData: looseLinkData, isParameter: isParameterLink, key: "component-panel" }))),
                    actionPanelShown && (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { id: 'context-menu', style: {
                            top: actionPanelPosition.y,
                            left: actionPanelPosition.x
                        }, className: "node-action-context-menu" },
                        react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_context_menu_NodeActionsPanel__WEBPACK_IMPORTED_MODULE_17__.NodeActionsPanel, { app: app, eng: xircuitsApp.getDiagramEngine(), nodePosition: nodePosition }))))))));
};


/***/ }),

/***/ "./lib/context-menu/ComponentsPanel.js":
/*!*********************************************!*\
  !*** ./lib/context-menu/ComponentsPanel.js ***!
  \*********************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "Body": () => (/* binding */ Body),
/* harmony export */   "Content": () => (/* binding */ Content),
/* harmony export */   "default": () => (/* binding */ ComponentsPanel)
/* harmony export */ });
/* harmony import */ var _tray_library_Component__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../tray_library/Component */ "./lib/tray_library/Component.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _emotion_styled__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @emotion/styled */ "webpack/sharing/consume/default/@emotion/styled/@emotion/styled?2715");
/* harmony import */ var _emotion_styled__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_emotion_styled__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var react_accessible_accordion__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! react-accessible-accordion */ "webpack/sharing/consume/default/react-accessible-accordion/react-accessible-accordion");
/* harmony import */ var react_accessible_accordion__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(react_accessible_accordion__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _TrayPanel__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./TrayPanel */ "./lib/context-menu/TrayPanel.js");
/* harmony import */ var _TrayItemPanel__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./TrayItemPanel */ "./lib/context-menu/TrayItemPanel.js");






const Body = (_emotion_styled__WEBPACK_IMPORTED_MODULE_1___default().div) `
  display: flex;
  flex-wrap: wrap;
  background-color: black;
  height: 270px;
  border-top: 10px;
  border-radius: 12px;
  overflow-y: auto;
`;
const Content = (_emotion_styled__WEBPACK_IMPORTED_MODULE_1___default().div) `
    display: flex;
    flex-grow: 1;
    flex-wrap: wrap;
    max-height: auto;
    'border-top': '4px solid #dfe2e5'
`;
async function fetchComponent(componentList) {
    let component_root = componentList.map(x => x["category"]);
    let headers = Array.from(new Set(component_root));
    let headerList = [];
    let headerList2 = [];
    let displayHeaderList = [];
    for (let headerIndex = 0; headerIndex < headers.length; headerIndex++) {
        if (headers[headerIndex] == 'ADVANCED' || headers[headerIndex] == 'GENERAL') {
            headerList.push(headers[headerIndex]);
        }
        else {
            headerList2.push(headers[headerIndex]);
        }
    }
    if (headerList.length != 0) {
        headerList = headerList.sort((a, b) => a < b ? 1 : a > b ? -1 : 0);
        headers = [...headerList, ...headerList2];
        for (let headerIndex2 = 0; headerIndex2 < headers.length; headerIndex2++) {
            displayHeaderList.push({
                "task": headers[headerIndex2],
                "id": headerIndex2 + 1
            });
        }
    }
    return displayHeaderList;
}
function fetchAllowableComponents(props, componentList, headerList) {
    let allowComponentList = [];
    let allowHeaderList = [];
    // Get allowable components
    componentList.map((val) => {
        if (props.linkData != null) {
            if (props.isParameter == true) {
                // Only allow GENERAL components for parameter inPort
                if (val["category"].toString() == "GENERAL") {
                    allowComponentList.push(val);
                }
            }
            // Only allow ADVANCED components for '▶' port
            else if (val["category"].toString() != "GENERAL") {
                allowComponentList.push(val);
            }
        }
        // Allow all Components when right-clicking
        else {
            allowComponentList.push(val);
        }
    });
    // Get allowable components's header
    headerList.map((val) => {
        if (props.linkData != null) {
            if (props.isParameter == true) {
                // Only allow GENERAL components for parameter inPort
                if (val["task"].toString() == "GENERAL") {
                    allowHeaderList.push(val);
                }
            }
            // Only allow ADVANCED components for '▶' port
            else if (val["task"].toString() != "GENERAL") {
                allowHeaderList.push(val);
            }
        }
        // Allow all Components when right-clicking
        else {
            allowHeaderList.push(val);
        }
    });
    return { allowComponentList, allowHeaderList };
}
function ComponentsPanel(props) {
    const [componentList, setComponentList] = react__WEBPACK_IMPORTED_MODULE_0___default().useState([]);
    const [category, setCategory] = react__WEBPACK_IMPORTED_MODULE_0___default().useState([]);
    const [searchTerm, setSearchTerm] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)('');
    const [runOnce, setRunOnce] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(false);
    const [allowableComponents, setAllowableComponents] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)([]);
    let handleOnChange = (event) => {
        setSearchTerm("");
        setSearchTerm(event.target.value);
    };
    const fetchComponentList = async () => {
        // get the component list
        const response_1 = await (0,_tray_library_Component__WEBPACK_IMPORTED_MODULE_3__["default"])();
        // get the header from the components
        const response_2 = await fetchComponent(response_1);
        const response_3 = await fetchAllowableComponents(props, response_1, response_2);
        // to ensure the component list is empty before setting the component list
        if (response_1.length > 0) {
            setAllowableComponents([]);
            setComponentList([]);
            setCategory([]);
        }
        setComponentList(response_1);
        setCategory(response_3.allowHeaderList);
        setAllowableComponents(response_3.allowComponentList);
    };
    (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
        if (!runOnce) {
            fetchComponentList();
            setRunOnce(true);
        }
    }, [category, componentList]);
    function focusInput() {
        document.getElementById("add-component-input").focus();
    }
    return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement(Body, null,
        react__WEBPACK_IMPORTED_MODULE_0___default().createElement(Content, { onBlur: focusInput },
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_TrayPanel__WEBPACK_IMPORTED_MODULE_4__.TrayPanel, null,
                react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", null,
                    react__WEBPACK_IMPORTED_MODULE_0___default().createElement("p", { className: 'title-panel' }, "Add Component"),
                    react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "search-input-panel" },
                        react__WEBPACK_IMPORTED_MODULE_0___default().createElement("input", { id: 'add-component-input', type: "text", name: "", value: searchTerm, placeholder: "SEARCH", className: "search-input__text-input-panel", autoFocus: true, onChange: handleOnChange })),
                    allowableComponents.filter((val) => {
                        if (searchTerm != "" && val.task.toLowerCase().includes(searchTerm.toLowerCase())) {
                            return val;
                        }
                    }).map((val, i) => {
                        return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { key: `index-3-${i}`, className: "tray-search" },
                            react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_TrayItemPanel__WEBPACK_IMPORTED_MODULE_5__.TrayItemPanel, { currentNode: val, app: props.lab, eng: props.eng, nodePosition: props.nodePosition, linkData: props.linkData, isParameter: props.isParameter })));
                    })),
                react__WEBPACK_IMPORTED_MODULE_0___default().createElement(react_accessible_accordion__WEBPACK_IMPORTED_MODULE_2__.Accordion, { allowZeroExpanded: true }, category.filter((val) => {
                    if (searchTerm == "") {
                        return val;
                    }
                }).map((val) => {
                    return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement(react_accessible_accordion__WEBPACK_IMPORTED_MODULE_2__.AccordionItem, { key: `index-1-${val["task"].toString()}`, className: 'accordion__item_panel' },
                        react__WEBPACK_IMPORTED_MODULE_0___default().createElement(react_accessible_accordion__WEBPACK_IMPORTED_MODULE_2__.AccordionItemHeading, null,
                            react__WEBPACK_IMPORTED_MODULE_0___default().createElement(react_accessible_accordion__WEBPACK_IMPORTED_MODULE_2__.AccordionItemButton, { className: 'accordion__button_panel' }, val["task"])),
                        react__WEBPACK_IMPORTED_MODULE_0___default().createElement(react_accessible_accordion__WEBPACK_IMPORTED_MODULE_2__.AccordionItemPanel, null, componentList.filter((componentVal) => {
                            if (searchTerm == "") {
                                return componentVal;
                            }
                        }).map((componentVal, i2) => {
                            if (componentVal["category"].toString().toUpperCase() == val["task"].toString()) {
                                return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { key: `index-1-${i2}` },
                                    react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_TrayItemPanel__WEBPACK_IMPORTED_MODULE_5__.TrayItemPanel, { currentNode: componentVal, app: props.lab, eng: props.eng, nodePosition: props.nodePosition, linkData: props.linkData, isParameter: props.isParameter })));
                            }
                        }))));
                }))))));
}
;


/***/ }),

/***/ "./lib/context-menu/NodeActionsPanel.js":
/*!**********************************************!*\
  !*** ./lib/context-menu/NodeActionsPanel.js ***!
  \**********************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "ActionPanel": () => (/* binding */ ActionPanel),
/* harmony export */   "NodeActionsPanel": () => (/* binding */ NodeActionsPanel)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _emotion_styled__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @emotion/styled */ "webpack/sharing/consume/default/@emotion/styled/@emotion/styled?2715");
/* harmony import */ var _emotion_styled__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_emotion_styled__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../components/xircuitBodyWidget */ "./lib/components/xircuitBodyWidget.js");



const ActionPanel = (_emotion_styled__WEBPACK_IMPORTED_MODULE_1___default().div) `
	border-color: #000;
	border-radius: 25px;
	border-top: 10px;
	z-index: 10;
`;
class NodeActionsPanel extends react__WEBPACK_IMPORTED_MODULE_0__.Component {
    hideNodeActionPanel() {
        //@ts-ignore
        this.props.eng.fireEvent({}, 'hidePanel');
    }
    ;
    render() {
        return (react__WEBPACK_IMPORTED_MODULE_0__.createElement(ActionPanel, { onClick: this.hideNodeActionPanel.bind(this) },
            react__WEBPACK_IMPORTED_MODULE_0__.createElement("div", { className: "option", onClick: () => {
                    this.props.app.commands.execute(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_2__.commandIDs.cutNode);
                } }, "Cut"),
            react__WEBPACK_IMPORTED_MODULE_0__.createElement("div", { className: "option", onClick: () => {
                    this.props.app.commands.execute(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_2__.commandIDs.copyNode);
                } }, "Copy"),
            react__WEBPACK_IMPORTED_MODULE_0__.createElement("div", { className: "option", onClick: () => {
                    this.props.app.commands.execute(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_2__.commandIDs.pasteNode);
                } }, "Paste"),
            react__WEBPACK_IMPORTED_MODULE_0__.createElement("div", { className: "option", onClick: () => {
                    this.props.app.commands.execute(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_2__.commandIDs.reloadNode);
                } }, "Reload Node"),
            react__WEBPACK_IMPORTED_MODULE_0__.createElement("div", { className: "option", onClick: () => {
                    this.props.app.commands.execute(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_2__.commandIDs.editNode);
                } }, "Edit"),
            react__WEBPACK_IMPORTED_MODULE_0__.createElement("div", { className: "option", onClick: () => {
                    this.props.app.commands.execute(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_2__.commandIDs.openScript);
                } }, "Open Script"),
            react__WEBPACK_IMPORTED_MODULE_0__.createElement("div", { className: "option", onClick: () => {
                    this.props.app.commands.execute(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_2__.commandIDs.deleteEntity);
                } }, "Delete"),
            react__WEBPACK_IMPORTED_MODULE_0__.createElement("div", { className: "option", onClick: () => {
                    this.props.app.commands.execute(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_2__.commandIDs.undo);
                } }, "Undo"),
            react__WEBPACK_IMPORTED_MODULE_0__.createElement("div", { className: "option", onClick: () => {
                    this.props.app.commands.execute(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_2__.commandIDs.redo);
                } }, "Redo"),
            react__WEBPACK_IMPORTED_MODULE_0__.createElement("div", { className: "option", onClick: () => {
                    this.props.app.commands.execute(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_2__.commandIDs.addCommentNode, { nodePosition: this.props.nodePosition });
                } }, "Add Comment")));
    }
}


/***/ }),

/***/ "./lib/context-menu/TrayItemPanel.js":
/*!*******************************************!*\
  !*** ./lib/context-menu/TrayItemPanel.js ***!
  \*******************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "Tray": () => (/* binding */ Tray),
/* harmony export */   "TrayItemPanel": () => (/* binding */ TrayItemPanel)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _emotion_styled__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @emotion/styled */ "webpack/sharing/consume/default/@emotion/styled/@emotion/styled?2715");
/* harmony import */ var _emotion_styled__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_emotion_styled__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _tray_library_GeneralComponentLib__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../tray_library/GeneralComponentLib */ "./lib/tray_library/GeneralComponentLib.js");
/* harmony import */ var _components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../components/xircuitBodyWidget */ "./lib/components/xircuitBodyWidget.js");
/* harmony import */ var _tray_library_AdvanceComponentLib__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../tray_library/AdvanceComponentLib */ "./lib/tray_library/AdvanceComponentLib.js");





const Tray = (_emotion_styled__WEBPACK_IMPORTED_MODULE_1___default().div) `
	color: white;
	font-family: Helvetica, Arial;
	padding: 2px;
	width: auto;
	margin: 2px;
	border: solid 1px ${(p) => p.color};
	border-radius: 2px;
	margin-bottom: 2px;
	cursor: pointer;
`;
class TrayItemPanel extends react__WEBPACK_IMPORTED_MODULE_0__.Component {
    async selectedNode() {
        let current_node = this.props.currentNode;
        let node;
        if (current_node != undefined) {
            if (current_node.header == "GENERAL") {
                node = await (0,_tray_library_GeneralComponentLib__WEBPACK_IMPORTED_MODULE_2__.GeneralComponentLibrary)({ model: current_node });
            }
            else {
                node = (0,_tray_library_AdvanceComponentLib__WEBPACK_IMPORTED_MODULE_3__.AdvancedComponentLibrary)({ model: current_node });
            }
        }
        return node;
    }
    addNode(node) {
        const nodePosition = this.props.nodePosition;
        this.props.app.commands.execute(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_4__.commandIDs.addNodeGivenPosition, { node, nodePosition });
    }
    connectLink(node) {
        if (this.props.linkData == null) {
            return;
        }
        const targetNode = node;
        const sourceLink = this.props.linkData;
        const isParameterLink = this.props.isParameter;
        this.props.app.commands.execute(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_4__.commandIDs.connectNodeByLink, { targetNode, sourceLink, isParameterLink });
    }
    hidePanelEvent() {
        //@ts-ignore
        this.props.eng.fireEvent({}, 'hidePanel');
    }
    ;
    render() {
        return (react__WEBPACK_IMPORTED_MODULE_0__.createElement(Tray, { color: this.props.currentNode["color"] || "white", onClick: async (event) => {
                if (event.ctrlKey || event.metaKey) {
                    const { commands } = this.props.app;
                    commands.execute(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_4__.commandIDs.openScript, {
                        nodePath: this.props.currentNode["file_path"],
                        nodeName: this.props.currentNode["class"],
                        nodeLineNo: this.props.currentNode["lineno"]
                    });
                    return;
                }
                let node = await this.selectedNode();
                this.addNode(node);
                this.connectLink(node);
                this.hidePanelEvent();
                this.forceUpdate();
            }, className: "tray-item" }, this.props.currentNode["task"]));
    }
}


/***/ }),

/***/ "./lib/context-menu/TrayPanel.js":
/*!***************************************!*\
  !*** ./lib/context-menu/TrayPanel.js ***!
  \***************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "Tray": () => (/* binding */ Tray),
/* harmony export */   "TrayPanel": () => (/* binding */ TrayPanel)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _emotion_styled__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @emotion/styled */ "webpack/sharing/consume/default/@emotion/styled/@emotion/styled?2715");
/* harmony import */ var _emotion_styled__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_emotion_styled__WEBPACK_IMPORTED_MODULE_1__);


const Tray = (_emotion_styled__WEBPACK_IMPORTED_MODULE_1___default().div) `
	min-width: 150px;
	border-radius: 11px;
	background: rgb(35, 35, 35);
	flex-grow: 1;
	width: 100px;
	flex-shrink: 1;
	max-height: auto;
`;
class TrayPanel extends react__WEBPACK_IMPORTED_MODULE_0__.Component {
    render() {
        return react__WEBPACK_IMPORTED_MODULE_0__.createElement(Tray, null, this.props.children);
    }
}


/***/ }),

/***/ "./lib/dialog/CommentDialog.js":
/*!*************************************!*\
  !*** ./lib/dialog/CommentDialog.js ***!
  \*************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "CommentDialog": () => (/* binding */ CommentDialog)
/* harmony export */ });
/* harmony import */ var react_textarea_autosize__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react-textarea-autosize */ "webpack/sharing/consume/default/react-textarea-autosize/react-textarea-autosize");
/* harmony import */ var react_textarea_autosize__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react_textarea_autosize__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);


const CommentDialog = ({ commentInput }) => {
    return (react__WEBPACK_IMPORTED_MODULE_1___default().createElement("form", null,
        react__WEBPACK_IMPORTED_MODULE_1___default().createElement("h3", { style: { marginTop: 0, marginBottom: 5 } }, "Comment Input:"),
        react__WEBPACK_IMPORTED_MODULE_1___default().createElement("div", null,
            react__WEBPACK_IMPORTED_MODULE_1___default().createElement((react__WEBPACK_IMPORTED_MODULE_1___default().Fragment), null,
                react__WEBPACK_IMPORTED_MODULE_1___default().createElement("div", null,
                    react__WEBPACK_IMPORTED_MODULE_1___default().createElement("div", null,
                        react__WEBPACK_IMPORTED_MODULE_1___default().createElement((react_textarea_autosize__WEBPACK_IMPORTED_MODULE_0___default()), { placeholder: 'Add your message here', minRows: 15, defaultValue: commentInput, style: { width: 500, height: 250, fontSize: 14, whiteSpace: 'pre' }, autoFocus: true }))))),
        react__WEBPACK_IMPORTED_MODULE_1___default().createElement("div", null)));
};


/***/ }),

/***/ "./lib/dialog/FormDialog.js":
/*!**********************************!*\
  !*** ./lib/dialog/FormDialog.js ***!
  \**********************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "disableButton": () => (/* binding */ disableButton),
/* harmony export */   "enableButton": () => (/* binding */ enableButton),
/* harmony export */   "showFormDialog": () => (/* binding */ showFormDialog)
/* harmony export */ });
/* harmony import */ var _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @jupyterlab/apputils */ "webpack/sharing/consume/default/@jupyterlab/apputils");
/* harmony import */ var _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _lumino_widgets__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @lumino/widgets */ "webpack/sharing/consume/default/@lumino/widgets");
/* harmony import */ var _lumino_widgets__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_lumino_widgets__WEBPACK_IMPORTED_MODULE_1__);


/*
 * Validate required dialog fields upon display
 * - Provides a generic validation by checking if required form fields are populated
 * - Expect required fields in dialog body to contain attribute: data-form-required
 *
 * @params
 *
 * options - The dialog setup options
 * formValidationFunction - Optional custom validation function
 *
 * returns a call to dialog display
 */
const showFormDialog = async (options, formValidationFunction) => {
    const dialogBody = options.body;
    const dialog = new _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_0__.Dialog(options);
    // Get dialog default action button
    const defaultButton = getDefaultButton(options, dialog.node);
    if (formValidationFunction) {
        formValidationFunction(dialog);
    }
    else {
        if (dialogBody instanceof _lumino_widgets__WEBPACK_IMPORTED_MODULE_1__.Widget) {
            const fieldsToBeValidated = new Set();
            const validateDialogButton = () => isFormValid(fieldsToBeValidated)
                ? enableButton(defaultButton)
                : disableButton(defaultButton);
            // Get elements that require validation and add event listeners
            dialogBody.node
                .querySelectorAll('select, input, textarea')
                .forEach((element) => {
                if (element.hasAttribute('data-form-required') ||
                    element.type === 'number') {
                    const elementTagName = element.tagName.toLowerCase();
                    if (elementTagName === 'select' || element.type === 'number') {
                        element.addEventListener('change', (event) => validateDialogButton());
                    }
                    if (['input', 'textarea'].includes(elementTagName)) {
                        element.addEventListener('keyup', (event) => validateDialogButton());
                    }
                    fieldsToBeValidated.add(element);
                }
            });
            preventDefaultDialogHandler(() => isFormValid(fieldsToBeValidated), dialog);
            validateDialogButton();
        }
    }
    return dialog.launch();
};
const disableButton = (button) => {
    button.setAttribute('disabled', 'disabled');
};
const enableButton = (button) => {
    button.removeAttribute('disabled');
};
const getDefaultButton = (options, node) => {
    var _a, _b, _c, _d;
    const defaultButtonIndex = (_a = options.defaultButton) !== null && _a !== void 0 ? _a : ((_c = (_b = options.buttons) === null || _b === void 0 ? void 0 : _b.length) !== null && _c !== void 0 ? _c : 0) - 1;
    return (_d = node
        .querySelector('.jp-Dialog-footer')) === null || _d === void 0 ? void 0 : _d.getElementsByTagName('button')[defaultButtonIndex];
};
// Prevent user from bypassing validation upon pressing the 'Enter' key
const preventDefaultDialogHandler = (isFormValidFn, dialog) => {
    var _a;
    const dialogHandleEvent = dialog.handleEvent;
    // Get dialog default action button
    const defaultButton = (_a = dialog.node.querySelector('.jp-Dialog-footer')) === null || _a === void 0 ? void 0 : _a.getElementsByTagName('button')[1];
    dialog.handleEvent = async (event) => {
        if (event instanceof KeyboardEvent &&
            event.type === 'keydown' &&
            event.key === 'Enter') {
            // Prevent action when form dialog is not valid
            if (!isFormValidFn()) {
                event.stopPropagation();
                event.preventDefault();
            }
            // When 'Enter' key is pressed while on input field, force focus to default button
            if (dialog.node.getElementsByTagName('input')[0]) {
                await defaultButton.focus();
            }
        }
        else {
            dialogHandleEvent.call(dialog, event);
        }
    };
};
// Returns true if given element is valid
const isFieldValid = (element) => {
    if (element.type === 'number') {
        // Allow any number or an empty string for number inputs
        return element.value === '' || !isNaN(Number(element.value.trim()))
            ? true
            : false;
    }
    // For other input types, continue to check whether the input is not an empty string
    return element.value.trim() ? true : false;
};
// Returns true if form dialog has all fields validated
const isFormValid = (fieldToBeValidated) => {
    for (const field of fieldToBeValidated.values()) {
        if (!isFieldValid(field)) {
            return false;
        }
    }
    return true;
};


/***/ }),

/***/ "./lib/dialog/LiteralInputDialog.js":
/*!******************************************!*\
  !*** ./lib/dialog/LiteralInputDialog.js ***!
  \******************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "LiteralInputDialog": () => (/* binding */ LiteralInputDialog),
/* harmony export */   "inputDialog": () => (/* binding */ inputDialog)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _formDialogwidget__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./formDialogwidget */ "./lib/dialog/formDialogwidget.js");
/* harmony import */ var _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @jupyterlab/apputils */ "webpack/sharing/consume/default/@jupyterlab/apputils");
/* harmony import */ var _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _input_dialogues_BooleanInput__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./input-dialogues/BooleanInput */ "./lib/dialog/input-dialogues/BooleanInput.js");
/* harmony import */ var _input_dialogues_TextAreaInput__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./input-dialogues/TextAreaInput */ "./lib/dialog/input-dialogues/TextAreaInput.js");
/* harmony import */ var _input_dialogues_NumberInput__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./input-dialogues/NumberInput */ "./lib/dialog/input-dialogues/NumberInput.js");
/* harmony import */ var _input_dialogues_DictInput__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./input-dialogues/DictInput */ "./lib/dialog/input-dialogues/DictInput.js");
/* harmony import */ var _input_dialogues_TupleInput__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./input-dialogues/TupleInput */ "./lib/dialog/input-dialogues/TupleInput.js");
/* harmony import */ var _input_dialogues_ListInput__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./input-dialogues/ListInput */ "./lib/dialog/input-dialogues/ListInput.js");
/* harmony import */ var _input_dialogues_ChatInput__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./input-dialogues/ChatInput */ "./lib/dialog/input-dialogues/ChatInput.js");
/* harmony import */ var _input_dialogues_SecretInput__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./input-dialogues/SecretInput */ "./lib/dialog/input-dialogues/SecretInput.js");
/* harmony import */ var _input_dialogues_VariableInput__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./input-dialogues/VariableInput */ "./lib/dialog/input-dialogues/VariableInput.js");
/* harmony import */ var _input_dialogues_ArgumentInput__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./input-dialogues/ArgumentInput */ "./lib/dialog/input-dialogues/ArgumentInput.js");













function inputDialog({ title, oldValue, type, inputType }) {
    const dialogOptions = {
        title,
        body: (0,_formDialogwidget__WEBPACK_IMPORTED_MODULE_2__.formDialogWidget)(react__WEBPACK_IMPORTED_MODULE_0___default().createElement(LiteralInputDialog, { title: title, oldValue: oldValue, type: type, inputType: inputType })),
        buttons: [_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_1__.Dialog.cancelButton(), _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_1__.Dialog.okButton({ label: ('Submit') })],
        defaultButton: 1,
        focusNodeSelector: inputType == 'textarea' ? 'textarea' : 'input'
    };
    return dialogOptions;
}
const LiteralInputDialog = ({ title, oldValue, type, inputType }) => {
    const inputComponents = {
        textarea: _input_dialogues_TextAreaInput__WEBPACK_IMPORTED_MODULE_3__.TextAreaInput,
        int: _input_dialogues_NumberInput__WEBPACK_IMPORTED_MODULE_4__.NumberInput,
        integer: _input_dialogues_NumberInput__WEBPACK_IMPORTED_MODULE_4__.NumberInput,
        float: _input_dialogues_NumberInput__WEBPACK_IMPORTED_MODULE_4__.NumberInput,
        boolean: _input_dialogues_BooleanInput__WEBPACK_IMPORTED_MODULE_5__.BooleanInput,
        string: _input_dialogues_TextAreaInput__WEBPACK_IMPORTED_MODULE_3__.TextAreaInput,
        dict: _input_dialogues_DictInput__WEBPACK_IMPORTED_MODULE_6__.DictInput,
        list: _input_dialogues_ListInput__WEBPACK_IMPORTED_MODULE_7__.ListInput,
        tuple: _input_dialogues_TupleInput__WEBPACK_IMPORTED_MODULE_8__.TupleInput,
        variable: _input_dialogues_VariableInput__WEBPACK_IMPORTED_MODULE_9__.VariableInput,
        secret: _input_dialogues_SecretInput__WEBPACK_IMPORTED_MODULE_10__.SecretInput,
        chat: _input_dialogues_ChatInput__WEBPACK_IMPORTED_MODULE_11__.ChatInput,
        argument: _input_dialogues_ArgumentInput__WEBPACK_IMPORTED_MODULE_12__.ArgumentInput,
    };
    const InputValueDialog = () => {
        const InputComponent = inputComponents[inputType === 'textarea' ? inputType.toLowerCase() : type.toLowerCase()];
        // The `type` prop is now passed to all components
        const extraProps = { type, inputType };
        return InputComponent ? react__WEBPACK_IMPORTED_MODULE_0___default().createElement(InputComponent, Object.assign({ title: title, oldValue: oldValue }, extraProps)) : null;
    };
    return react__WEBPACK_IMPORTED_MODULE_0___default().createElement(InputValueDialog, null);
};


/***/ }),

/***/ "./lib/dialog/RunDialog.js":
/*!*********************************!*\
  !*** ./lib/dialog/RunDialog.js ***!
  \*********************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "RunDialog": () => (/* binding */ RunDialog)
/* harmony export */ });
/* harmony import */ var react_numeric_input__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react-numeric-input */ "webpack/sharing/consume/default/react-numeric-input/react-numeric-input");
/* harmony import */ var react_numeric_input__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react_numeric_input__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var react_textarea_autosize__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react-textarea-autosize */ "webpack/sharing/consume/default/react-textarea-autosize/react-textarea-autosize");
/* harmony import */ var react_textarea_autosize__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react_textarea_autosize__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var react_switch__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! react-switch */ "webpack/sharing/consume/default/react-switch/react-switch");
/* harmony import */ var react_switch__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(react_switch__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @jupyterlab/ui-components */ "webpack/sharing/consume/default/@jupyterlab/ui-components");
/* harmony import */ var _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_4__);





const RunDialog = ({ runTypes, runConfigs, lastConfig, childStringNodes, childBoolNodes, childIntNodes, childFloatNodes }) => {
    const [checked, setChecked] = (0,react__WEBPACK_IMPORTED_MODULE_2__.useState)([false]);
    const [runType, setRunType] = (0,react__WEBPACK_IMPORTED_MODULE_2__.useState)("");
    const [runConfig, setRunConfig] = (0,react__WEBPACK_IMPORTED_MODULE_2__.useState)("");
    const [command, setCommand] = (0,react__WEBPACK_IMPORTED_MODULE_2__.useState)("");
    const handleChecked = (e, i) => {
        let newChecked = [...checked];
        newChecked[i] = e;
        setChecked(newChecked);
        console.log("Boolean change: ", checked);
    };
    /**
     * Handle `change` events for the HTMLSelect component of run type.
     */
    const handleTypeChange = (event) => {
        let type = event.target.value;
        setRunType(type);
        setRunConfig("-");
        setCommand("");
    };
    /**
     * Handle `change` events for the HTMLSelect component for run config.
     */
    const handleConfigChange = (event) => {
        let configName = event.target.value;
        setRunConfig(configName);
        if (configName == "-") {
            setCommand("");
        }
    };
    (0,react__WEBPACK_IMPORTED_MODULE_2__.useEffect)(() => {
        if (runTypes.length != 0) {
            setRunType(runTypes[0].run_type);
        }
        if (lastConfig.length != 0) {
            setRunType(lastConfig.run_type);
            setRunConfig(lastConfig.run_config_name);
            setCommand(lastConfig.command);
        }
    }, []);
    (0,react__WEBPACK_IMPORTED_MODULE_2__.useEffect)(() => {
        if (runConfigs.length != 0) {
            runConfigs.map(c => {
                if (c.run_config_name == runConfig)
                    setCommand(c.command);
            });
        }
    }, [runConfig]);
    return (react__WEBPACK_IMPORTED_MODULE_2___default().createElement("form", null,
        childStringNodes.length > 0 ? react__WEBPACK_IMPORTED_MODULE_2___default().createElement("h3", { style: { marginTop: 0, marginBottom: 5 } }, "Arguments:") : null,
        react__WEBPACK_IMPORTED_MODULE_2___default().createElement("div", null, runConfigs.length != 0 ?
            react__WEBPACK_IMPORTED_MODULE_2___default().createElement((react__WEBPACK_IMPORTED_MODULE_2___default().Fragment), null,
                react__WEBPACK_IMPORTED_MODULE_2___default().createElement("h4", { style: { marginTop: 2, marginBottom: 0 } }, "Remote Execution"),
                react__WEBPACK_IMPORTED_MODULE_2___default().createElement("div", null,
                    "Available Run Type:",
                    react__WEBPACK_IMPORTED_MODULE_2___default().createElement(_jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_4__.HTMLSelect, { onChange: (e) => handleTypeChange(e), value: runType, "aria-label": 'Available Run Types', title: 'Select the run type', name: 'runType' }, runTypes.map((type, i) => (react__WEBPACK_IMPORTED_MODULE_2___default().createElement("option", { id: type.id, key: `index-type-${i}`, value: type.run_type }, (type.run_type)))))),
                react__WEBPACK_IMPORTED_MODULE_2___default().createElement("div", null,
                    "Available Run Config:",
                    react__WEBPACK_IMPORTED_MODULE_2___default().createElement(_jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_4__.HTMLSelect, { onChange: (e) => handleConfigChange(e), value: runConfig, "aria-label": 'Run Configuration', title: 'Select which config to run', name: 'runConfig' },
                        react__WEBPACK_IMPORTED_MODULE_2___default().createElement("option", { value: "-" }, "-"),
                        runConfigs.map((c, i) => ((c.run_type == runType) ?
                            react__WEBPACK_IMPORTED_MODULE_2___default().createElement("option", { id: c.id, key: `index-config-${i}`, value: c.run_config_name }, (c.run_config_name)) : null)))),
                "Configuration:",
                react__WEBPACK_IMPORTED_MODULE_2___default().createElement("div", null,
                    react__WEBPACK_IMPORTED_MODULE_2___default().createElement((react_textarea_autosize__WEBPACK_IMPORTED_MODULE_1___default()), { value: command, minRows: 10, name: 'command', style: { width: 350, fontSize: 12 }, readOnly: true })))
            : null),
        react__WEBPACK_IMPORTED_MODULE_2___default().createElement("div", null),
        childStringNodes.map((stringNode, i) => react__WEBPACK_IMPORTED_MODULE_2___default().createElement("div", { key: `index-${i}` },
            stringNode,
            react__WEBPACK_IMPORTED_MODULE_2___default().createElement("div", null,
                react__WEBPACK_IMPORTED_MODULE_2___default().createElement("input", { type: "text", name: stringNode })))),
        react__WEBPACK_IMPORTED_MODULE_2___default().createElement("div", null, childBoolNodes.length != 0 ?
            react__WEBPACK_IMPORTED_MODULE_2___default().createElement((react__WEBPACK_IMPORTED_MODULE_2___default().Fragment), null,
                react__WEBPACK_IMPORTED_MODULE_2___default().createElement("br", null),
                react__WEBPACK_IMPORTED_MODULE_2___default().createElement("h4", { style: { marginTop: 2, marginBottom: 0 } }, "Boolean")) : null),
        childBoolNodes.map((boolNode, i) => {
            var _a;
            return react__WEBPACK_IMPORTED_MODULE_2___default().createElement("div", { key: `index-${i}` },
                boolNode,
                react__WEBPACK_IMPORTED_MODULE_2___default().createElement("div", null,
                    react__WEBPACK_IMPORTED_MODULE_2___default().createElement((react_switch__WEBPACK_IMPORTED_MODULE_3___default()), { checked: (_a = checked[i]) !== null && _a !== void 0 ? _a : true, name: boolNode, onChange: (e) => handleChecked(e, i), handleDiameter: 25, height: 20, width: 48 })));
        }),
        react__WEBPACK_IMPORTED_MODULE_2___default().createElement("div", null, childIntNodes.length != 0 ?
            react__WEBPACK_IMPORTED_MODULE_2___default().createElement((react__WEBPACK_IMPORTED_MODULE_2___default().Fragment), null,
                react__WEBPACK_IMPORTED_MODULE_2___default().createElement("br", null),
                react__WEBPACK_IMPORTED_MODULE_2___default().createElement("h4", { style: { marginTop: 2, marginBottom: 0 } }, "Integer")) : null),
        childIntNodes.map((intNode, i) => react__WEBPACK_IMPORTED_MODULE_2___default().createElement("div", { key: `index-${i}` },
            intNode,
            react__WEBPACK_IMPORTED_MODULE_2___default().createElement("div", null,
                react__WEBPACK_IMPORTED_MODULE_2___default().createElement(react_numeric_input__WEBPACK_IMPORTED_MODULE_0__, { className: "form-control", name: intNode, value: '0', min: 0, step: 1, precision: 0, mobile: true, style: {
                        wrap: {
                            boxShadow: '0 0 1px 1px #fff inset, 1px 1px 5px -1px #000',
                            padding: '2px 2.26ex 2px 2px',
                            borderRadius: '6px 3px 3px 6px',
                            fontSize: 20,
                            width: '60%'
                        },
                        input: {
                            borderRadius: '6px 3px 3px 6px',
                            padding: '0.1ex 1ex',
                            border: '#ccc',
                            marginRight: 4,
                            display: 'block',
                            fontWeight: 100,
                            width: '100%'
                        },
                        plus: {
                            background: 'rgba(255, 255, 255, 100)'
                        },
                        minus: {
                            background: 'rgba(255, 255, 255, 100)'
                        },
                        btnDown: {
                            background: 'rgba(0, 0, 0)'
                        },
                        btnUp: {
                            background: 'rgba(0, 0, 0)'
                        }
                    } })))),
        react__WEBPACK_IMPORTED_MODULE_2___default().createElement("div", null, childFloatNodes.length != 0 ?
            react__WEBPACK_IMPORTED_MODULE_2___default().createElement((react__WEBPACK_IMPORTED_MODULE_2___default().Fragment), null,
                react__WEBPACK_IMPORTED_MODULE_2___default().createElement("br", null),
                react__WEBPACK_IMPORTED_MODULE_2___default().createElement("h4", { style: { marginTop: 2, marginBottom: 0 } }, "Float")) : null),
        childFloatNodes.map((floatNode, i) => react__WEBPACK_IMPORTED_MODULE_2___default().createElement("div", { className: "p-col-12", key: `index-${i}` },
            floatNode,
            react__WEBPACK_IMPORTED_MODULE_2___default().createElement("div", null,
                react__WEBPACK_IMPORTED_MODULE_2___default().createElement(react_numeric_input__WEBPACK_IMPORTED_MODULE_0__, { className: "form-control", name: floatNode, value: '0.00', min: 0, step: 0.1, precision: 2, mobile: true, style: {
                        wrap: {
                            boxShadow: '0 0 1px 1px #fff inset, 1px 1px 5px -1px #000',
                            padding: '2px 2.26ex 2px 2px',
                            borderRadius: '6px 3px 3px 6px',
                            fontSize: 20,
                            width: '60%'
                        },
                        input: {
                            borderRadius: '6px 3px 3px 6px',
                            padding: '0.1ex 1ex',
                            border: '#ccc',
                            marginRight: 4,
                            display: 'block',
                            fontWeight: 100,
                            width: '100%'
                        },
                        plus: {
                            background: 'rgba(255, 255, 255, 100)'
                        },
                        minus: {
                            background: 'rgba(255, 255, 255, 100)'
                        },
                        btnDown: {
                            background: 'rgba(0, 0, 0)'
                        },
                        btnUp: {
                            background: 'rgba(0, 0, 0)'
                        }
                    } }))))));
};


/***/ }),

/***/ "./lib/dialog/formDialogwidget.js":
/*!****************************************!*\
  !*** ./lib/dialog/formDialogwidget.js ***!
  \****************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "formDialogWidget": () => (/* binding */ formDialogWidget)
/* harmony export */ });
/* harmony import */ var _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @jupyterlab/apputils */ "webpack/sharing/consume/default/@jupyterlab/apputils");
/* harmony import */ var _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _lumino_messaging__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @lumino/messaging */ "webpack/sharing/consume/default/@lumino/messaging");
/* harmony import */ var _lumino_messaging__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_lumino_messaging__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _lumino_widgets__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @lumino/widgets */ "webpack/sharing/consume/default/@lumino/widgets");
/* harmony import */ var _lumino_widgets__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_lumino_widgets__WEBPACK_IMPORTED_MODULE_2__);



const formDialogWidget = (dialogComponent) => {
    const widget = _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_0__.ReactWidget.create(dialogComponent);
    // Immediately update the body even though it has not yet attached in
    // order to trigger a render of the DOM nodes from the React element.
    _lumino_messaging__WEBPACK_IMPORTED_MODULE_1__.MessageLoop.sendMessage(widget, _lumino_widgets__WEBPACK_IMPORTED_MODULE_2__.Widget.Msg.UpdateRequest);
    widget.getValue = () => {
        var _a;
        const form = widget.node.querySelector('form');
        let formValues = {};
        for (const element of Object.values((_a = form === null || form === void 0 ? void 0 : form.elements) !== null && _a !== void 0 ? _a : [])) {
            switch (element.name) {
                case 'messages':
                    formValues = JSON.parse(element.value);
                    break;
                case 'checkbox':
                    formValues[element.name] = element.checked;
                    break;
                default:
                    formValues[element.name] = element.value;
                    break;
            }
        }
        return formValues;
    };
    return widget;
};


/***/ }),

/***/ "./lib/dialog/input-dialogues/ArgumentInput.js":
/*!*****************************************************!*\
  !*** ./lib/dialog/input-dialogues/ArgumentInput.js ***!
  \*****************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "ArgumentInput": () => (/* binding */ ArgumentInput)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);

const ArgumentInput = ({ title, oldValue, inputType }) => {
    return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("form", null,
        react__WEBPACK_IMPORTED_MODULE_0___default().createElement("h3", { style: { marginTop: 0, marginBottom: 5 } },
            "Enter ",
            inputType,
            " Argument Name:"),
        react__WEBPACK_IMPORTED_MODULE_0___default().createElement("input", { name: title, style: { width: 350 }, defaultValue: oldValue })));
};


/***/ }),

/***/ "./lib/dialog/input-dialogues/BooleanInput.js":
/*!****************************************************!*\
  !*** ./lib/dialog/input-dialogues/BooleanInput.js ***!
  \****************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "BooleanInput": () => (/* binding */ BooleanInput)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var react_switch__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react-switch */ "webpack/sharing/consume/default/react-switch/react-switch");
/* harmony import */ var react_switch__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react_switch__WEBPACK_IMPORTED_MODULE_1__);


const BooleanInput = ({ title, oldValue }) => {
    // Explicitly compare to 'true' as JS treats non-empty strings as truthy.
    const [checked, setChecked] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(oldValue.toLowerCase() === 'true');
    const handleChecked = () => {
        setChecked(!checked);
    };
    return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("form", null,
        react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { style: { paddingLeft: 5, paddingTop: 5 } },
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement((react_switch__WEBPACK_IMPORTED_MODULE_1___default()), { checked: checked, name: title, onChange: handleChecked, boxShadow: "0px 1px 5px rgba(0, 0, 0, 0.6)", handleDiameter: 25, height: 20, width: 48 }),
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement("input", { type: "hidden", name: title, value: checked ? 'True' : 'False' }))));
};


/***/ }),

/***/ "./lib/dialog/input-dialogues/ChatInput.js":
/*!*************************************************!*\
  !*** ./lib/dialog/input-dialogues/ChatInput.js ***!
  \*************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "ChatInput": () => (/* binding */ ChatInput)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var react_textarea_autosize__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react-textarea-autosize */ "webpack/sharing/consume/default/react-textarea-autosize/react-textarea-autosize");
/* harmony import */ var react_textarea_autosize__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react_textarea_autosize__WEBPACK_IMPORTED_MODULE_1__);


const ChatInput = ({ title, oldValue = [], onSubmit }) => {
    const [messages, setMessages] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(oldValue || [{ role: '', content: '' }]);
    const [hiddenMessagesValue, setHiddenMessagesValue] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)('');
    (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
        setHiddenMessagesValue(JSON.stringify(messages));
    }, [messages]);
    const addMessage = () => {
        setMessages([...messages, { role: '', content: '' }]);
    };
    const removeMessage = (index) => {
        setMessages(messages.filter((_, i) => i !== index));
    };
    const updateMessage = (index, field, value) => {
        let newMessages = [...messages];
        newMessages[index][field] = value;
        setMessages(newMessages);
    };
    const gridContainer = {
        display: 'grid',
        gridTemplateColumns: '1fr',
        gridGap: '10px',
        padding: '20px',
        width: '400px',
        marginLeft: 'auto',
        marginRight: 'auto',
    };
    const flexContainer = {
        display: 'flex',
        marginBottom: '10px',
    };
    const selectStyle = {
        flex: '1',
    };
    return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("form", null,
        react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { style: gridContainer, className: "jp-mod-styled" },
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement("label", null, "Messages"),
            messages.map((message, index) => (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { key: index, className: "jp-mod-styled" },
                react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { style: flexContainer },
                    react__WEBPACK_IMPORTED_MODULE_0___default().createElement("select", { name: "role", value: message.role, onChange: (e) => updateMessage(index, 'role', e.target.value), style: selectStyle, className: "jp-mod-styled" },
                        react__WEBPACK_IMPORTED_MODULE_0___default().createElement("option", { value: "" }, "Select a role"),
                        react__WEBPACK_IMPORTED_MODULE_0___default().createElement("option", { value: "system" }, "system"),
                        react__WEBPACK_IMPORTED_MODULE_0___default().createElement("option", { value: "user" }, "user"),
                        react__WEBPACK_IMPORTED_MODULE_0___default().createElement("option", { value: "assistant" }, "assistant"),
                        react__WEBPACK_IMPORTED_MODULE_0___default().createElement("option", { value: "function" }, "function")),
                    react__WEBPACK_IMPORTED_MODULE_0___default().createElement("button", { type: "button", onClick: () => removeMessage(index), className: "jp-mod-styled" }, "Remove")),
                react__WEBPACK_IMPORTED_MODULE_0___default().createElement((react_textarea_autosize__WEBPACK_IMPORTED_MODULE_1___default()), { minRows: 4, name: "content", style: { width: '100%', fontSize: 12 }, value: message.content, onChange: (e) => updateMessage(index, 'content', e.target.value), autoFocus: true })))),
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement("button", { type: "button", onClick: addMessage, style: { gridColumn: 'span 1' }, className: "jp-mod-styled" }, "Add Message")),
        react__WEBPACK_IMPORTED_MODULE_0___default().createElement("input", { type: "hidden", name: "messages", value: hiddenMessagesValue })));
};


/***/ }),

/***/ "./lib/dialog/input-dialogues/DictInput.js":
/*!*************************************************!*\
  !*** ./lib/dialog/input-dialogues/DictInput.js ***!
  \*************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "DictInput": () => (/* binding */ DictInput)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);

const DictInput = ({ title, oldValue }) => {
    return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("form", null,
        react__WEBPACK_IMPORTED_MODULE_0___default().createElement("h3", { style: { marginTop: 0, marginBottom: 5 } }, "Enter Dict Value (Without Brackets):"),
        react__WEBPACK_IMPORTED_MODULE_0___default().createElement("h5", { style: { marginTop: 0, marginBottom: 5 } }, "For Example: \"a\": \"apple\", \"b\": \"banana\", \"c\": 2022"),
        react__WEBPACK_IMPORTED_MODULE_0___default().createElement("input", { name: title, style: { width: 350 }, defaultValue: oldValue })));
};


/***/ }),

/***/ "./lib/dialog/input-dialogues/ListInput.js":
/*!*************************************************!*\
  !*** ./lib/dialog/input-dialogues/ListInput.js ***!
  \*************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "ListInput": () => (/* binding */ ListInput)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);

const ListInput = ({ title, oldValue }) => {
    return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("form", null,
        react__WEBPACK_IMPORTED_MODULE_0___default().createElement("h3", { style: { marginTop: 0, marginBottom: 5 } }, "Enter List Value (Without Brackets):"),
        react__WEBPACK_IMPORTED_MODULE_0___default().createElement("h5", { style: { marginTop: 0, marginBottom: 5 } }, "For Example: \"a\", \"b\", \"c\""),
        react__WEBPACK_IMPORTED_MODULE_0___default().createElement("input", { name: title, style: { width: 350 }, defaultValue: oldValue })));
};


/***/ }),

/***/ "./lib/dialog/input-dialogues/NumberInput.js":
/*!***************************************************!*\
  !*** ./lib/dialog/input-dialogues/NumberInput.js ***!
  \***************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "NumberInput": () => (/* binding */ NumberInput)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);

const NumberInput = ({ title, oldValue, type }) => {
    return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("form", null,
        react__WEBPACK_IMPORTED_MODULE_0___default().createElement("h3", { style: { marginTop: 0, marginBottom: 5 } },
            "Enter ",
            type == 'float' ? "Float" : "Integer",
            " Value:"),
        react__WEBPACK_IMPORTED_MODULE_0___default().createElement("input", { name: title, type: "number", step: type == 'float' ? "0.01" : "1", placeholder: type == 'float' ? "0.00" : "0", style: { width: 350 }, defaultValue: oldValue })));
};


/***/ }),

/***/ "./lib/dialog/input-dialogues/SecretInput.js":
/*!***************************************************!*\
  !*** ./lib/dialog/input-dialogues/SecretInput.js ***!
  \***************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "SecretInput": () => (/* binding */ SecretInput)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);

const SecretInput = ({ title, oldValue }) => {
    return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("form", null,
        react__WEBPACK_IMPORTED_MODULE_0___default().createElement("h3", { style: { marginTop: 0, marginBottom: 5 } }, "Enter Secret Value (Without Quotes):"),
        react__WEBPACK_IMPORTED_MODULE_0___default().createElement("h5", { style: { marginTop: 0, marginBottom: 5 } },
            "Warning: Literal Secrets are masked in the frontend only. ",
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement("br", null),
            "They can still be accessed in the raw .xircuits file or appear as strings in the compiled script."),
        react__WEBPACK_IMPORTED_MODULE_0___default().createElement("input", { name: title, type: "password", style: { width: 480 }, defaultValue: oldValue })));
};


/***/ }),

/***/ "./lib/dialog/input-dialogues/TextAreaInput.js":
/*!*****************************************************!*\
  !*** ./lib/dialog/input-dialogues/TextAreaInput.js ***!
  \*****************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "TextAreaInput": () => (/* binding */ TextAreaInput)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var react_textarea_autosize__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react-textarea-autosize */ "webpack/sharing/consume/default/react-textarea-autosize/react-textarea-autosize");
/* harmony import */ var react_textarea_autosize__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react_textarea_autosize__WEBPACK_IMPORTED_MODULE_1__);


const TextAreaInput = ({ title, oldValue }) => {
    const textAreaRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(null);
    // auto focus selector for text area
    (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
        const timer = setTimeout(() => {
            const textarea = textAreaRef.current;
            if (textarea) {
                textarea.focus();
                const length = textarea.value.length;
                textarea.selectionStart = length;
                textarea.selectionEnd = length;
            }
        }, 10); // Delay to ensure the component is fully mounted.
        return () => clearTimeout(timer);
    }, []);
    return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("form", null,
        react__WEBPACK_IMPORTED_MODULE_0___default().createElement("h3", { style: { marginTop: 0, marginBottom: 5 } }, "Enter String Value (Without Quotes):"),
        react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", null,
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement((react_textarea_autosize__WEBPACK_IMPORTED_MODULE_1___default()), { defaultValue: oldValue, minRows: 14, name: title, style: { width: 400, height: 200, fontSize: 12 }, ref: textAreaRef }))));
};


/***/ }),

/***/ "./lib/dialog/input-dialogues/TupleInput.js":
/*!**************************************************!*\
  !*** ./lib/dialog/input-dialogues/TupleInput.js ***!
  \**************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "TupleInput": () => (/* binding */ TupleInput)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);

const TupleInput = ({ title, oldValue }) => {
    return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("form", null,
        react__WEBPACK_IMPORTED_MODULE_0___default().createElement("h3", { style: { marginTop: 0, marginBottom: 5 } }, "Enter Tuple Value (Without Brackets):"),
        react__WEBPACK_IMPORTED_MODULE_0___default().createElement("h5", { style: { marginTop: 0, marginBottom: 5 } }, "For Example: \"a\", \"b\", \"c\""),
        react__WEBPACK_IMPORTED_MODULE_0___default().createElement("input", { name: title, style: { width: 350 }, defaultValue: oldValue })));
};


/***/ }),

/***/ "./lib/dialog/input-dialogues/VariableInput.js":
/*!*****************************************************!*\
  !*** ./lib/dialog/input-dialogues/VariableInput.js ***!
  \*****************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "VariableInput": () => (/* binding */ VariableInput),
/* harmony export */   "getItsLiteralType": () => (/* binding */ getItsLiteralType)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _helpers_InputSanitizer__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../helpers/InputSanitizer */ "./lib/helpers/InputSanitizer.js");
/* harmony import */ var _LiteralInputDialog__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../LiteralInputDialog */ "./lib/dialog/LiteralInputDialog.js");
/* harmony import */ var _FormDialog__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../FormDialog */ "./lib/dialog/FormDialog.js");
/* harmony import */ var _tray_library_GeneralComponentLib__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../tray_library/GeneralComponentLib */ "./lib/tray_library/GeneralComponentLib.js");





const VariableInput = ({ title, oldValue }) => {
    return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("form", null,
        react__WEBPACK_IMPORTED_MODULE_0___default().createElement("h5", { style: { marginTop: 0, marginBottom: 5 } },
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement("p", null, "Determine your variable type by inserting the first char as below: "),
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement("li", null, " \" : String"),
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement("li", null, " # : Integer or Float"),
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement("li", null, " [ : List"),
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement("li", null, " ( : Tuple"),
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement("li", null,
                " ",
                '{',
                " : Dict"),
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement("li", null, " !true / !True / !1 / !t : True"),
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement("li", null, " !false / !False / !0 / !nil : False"),
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement("p", null, "For Example: \"Hello World or #15 or !true")),
        react__WEBPACK_IMPORTED_MODULE_0___default().createElement("input", { name: title, style: { width: 350 }, defaultValue: oldValue })));
};
async function getItsLiteralType() {
    // When inPort is 'any' type, get the correct literal type based on the first character inputed
    let varOfAnyTypeTitle = 'Enter your variable value';
    let dialogOptions = (0,_LiteralInputDialog__WEBPACK_IMPORTED_MODULE_1__.inputDialog)({ title: varOfAnyTypeTitle, oldValue: "", type: 'variable' });
    const dialogResult = await (0,_FormDialog__WEBPACK_IMPORTED_MODULE_2__.showFormDialog)(dialogOptions);
    if ((0,_tray_library_GeneralComponentLib__WEBPACK_IMPORTED_MODULE_3__.cancelDialog)(dialogResult))
        return;
    let varValue = dialogResult["value"][varOfAnyTypeTitle];
    let varType = varValue.charAt(0);
    let varInput = varValue.slice(1);
    let nodeType = varTypeChecker(varType, varInput, varValue);
    while (!(0,_helpers_InputSanitizer__WEBPACK_IMPORTED_MODULE_4__.checkInput)(varInput, nodeType)) {
        let dialogOptions = (0,_LiteralInputDialog__WEBPACK_IMPORTED_MODULE_1__.inputDialog)({ title: varOfAnyTypeTitle, oldValue: "", type: 'Variable' });
        const dialogResult = await (0,_FormDialog__WEBPACK_IMPORTED_MODULE_2__.showFormDialog)(dialogOptions);
        if ((0,_tray_library_GeneralComponentLib__WEBPACK_IMPORTED_MODULE_3__.cancelDialog)(dialogResult))
            return;
        varValue = dialogResult["value"][varOfAnyTypeTitle];
        varType = varValue.charAt(0);
        varInput = varValue.slice(1);
        nodeType = varTypeChecker(varType, varInput, varValue);
    }
    return { nodeType, varInput };
}
function varTypeChecker(varType, varInput, varValue) {
    const typeCheckDict = {
        '"': () => 'String',
        '#': () => Number.isInteger(Number(varInput)) ? 'Integer' : 'Float',
        '[': () => 'List',
        '(': () => 'Tuple',
        '{': () => 'Dict',
        '!': () => {
            let boolValue = varValue.slice(1).toLowerCase();
            if (boolValue === 'true' || boolValue === '1' || boolValue === 't') {
                return 'True';
            }
            else if (boolValue === 'false' || boolValue === '0' || boolValue === 'nil') {
                return 'False';
            }
        }
    };
    let nodeType = typeCheckDict[varType] ? typeCheckDict[varType]() : 'undefined_any';
    if (nodeType == 'undefined_any') {
        console.error(`Type is undefined or not provided. Please insert the first character as shown in example.`);
    }
    return nodeType;
}


/***/ }),

/***/ "./lib/helpers/DemoCanvasWidget.js":
/*!*****************************************!*\
  !*** ./lib/helpers/DemoCanvasWidget.js ***!
  \*****************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "Container": () => (/* binding */ Container),
/* harmony export */   "DemoCanvasWidget": () => (/* binding */ DemoCanvasWidget)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _emotion_styled__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @emotion/styled */ "webpack/sharing/consume/default/@emotion/styled/@emotion/styled?2715");
/* harmony import */ var _emotion_styled__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_emotion_styled__WEBPACK_IMPORTED_MODULE_1__);


//namespace S {
const Container = (_emotion_styled__WEBPACK_IMPORTED_MODULE_1___default().div) `
		height: 100%;
		background-color: ${(p) => p.background};
		background-size: 50px 50px;
		display: flex;
		width : 15360px; // Prevent Dev tool effects on smaller monitors  

		> * {
			height: 100%;
			min-height: 100%;
			width: 100%;
		}
		background-image: linear-gradient(
				0deg,
				transparent 24%,
				${(p) => p.color} 25%,
				${(p) => p.color} 26%,
				transparent 27%,
				transparent 74%,
				${(p) => p.color} 75%,
				${(p) => p.color} 76%,
				transparent 77%,
				transparent
			),
			linear-gradient(
				90deg,
				transparent 24%,
				${(p) => p.color} 25%,
				${(p) => p.color} 26%,
				transparent 27%,
				transparent 74%,
				${(p) => p.color} 75%,
				${(p) => p.color} 76%,
				transparent 77%,
				transparent
			);
	`;
//}
class DemoCanvasWidget extends react__WEBPACK_IMPORTED_MODULE_0__.Component {
    render() {
        return (react__WEBPACK_IMPORTED_MODULE_0__.createElement(Container, { background: this.props.background || 'rgb(60, 60, 60)', color: this.props.color || 'rgba(255,255,255, 0.05)' }, this.props.children));
    }
}


/***/ }),

/***/ "./lib/helpers/InputSanitizer.js":
/*!***************************************!*\
  !*** ./lib/helpers/InputSanitizer.js ***!
  \***************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "checkInput": () => (/* binding */ checkInput)
/* harmony export */ });
function checkInput(input, dataType) {
    if (input === "") {
        alert("Input cannot be empty.");
        return false;
    }
    const normalizedDataType = dataType.toLowerCase();
    let processedInput = "";
    let errorDetails = "";
    let exampleInput = "";
    const formatError = (detail, example) => `Invalid ${dataType} input: ${detail} \nExample of a correct ${dataType} format: ${example}`;
    switch (normalizedDataType) {
        case "int":
        case "integer":
            // Regex: Matches possibly negative integers
            if (!/^\-?\d+$/.test(input)) {
                errorDetails = "Input is not an integer.";
                exampleInput = "e.g. 3";
                alert(formatError(errorDetails, exampleInput));
                return false;
            }
            processedInput = `${input}`;
            break;
        case "float":
            // Regex: Matches possibly negative floats
            if (!/^\-?\d*\.\d+$/.test(input)) {
                errorDetails = "Input is not a float.";
                exampleInput = "e.g. 3.14";
                alert(formatError(errorDetails, exampleInput));
                return false;
            }
            processedInput = `${input}`;
            break;
        case "string":
        case "secret":
        case "chat":
            processedInput = JSON.stringify(input);
            break;
        case "list":
        case "tuple": // validate tuple as list,as JS doesn't have native tuples
            processedInput = `[${input}]`;
            break;
        case "dict":
            processedInput = `{${input}}`;
            break;
        case "true":
        case "false":
        case "boolean":
            return true;
        case "undefined_any":
            //handler if called from any inputDialogue
            alert(`Type is undefined or not provided. Please insert the first character as shown in example.`);
            return false;
        default:
            alert("Invalid datatype: Please provide a valid datatype.");
            return false;
    }
    try {
        JSON.parse(processedInput);
    }
    catch (e) {
        if (processedInput.includes("'")) {
            errorDetails = "Please use double quotes instead of single quotes.";
        }
        else if (/(?:\{|\[|\()(?:\w+)/.test(processedInput)) {
            errorDetails = "Please ensure to use double quotes for your variables.";
        }
        else {
            errorDetails = "Please check the console log for details.";
            console.error("Parsing error:", e.message);
        }
        switch (normalizedDataType) {
            case "string":
            case "secret":
                exampleInput = '"example_string"';
                break;
            case "tuple":
            case "list":
                exampleInput = '"item1", "item2", 123';
                break;
            case "dict":
                exampleInput = '"key1": "value1", "key2": 123';
                break;
        }
        if (normalizedDataType !== "secret") {
            errorDetails += "\n\nYour input: " + input;
        }
        alert(formatError(errorDetails, exampleInput));
        return false;
    }
    return true;
}



/***/ }),

/***/ "./lib/index.js":
/*!**********************!*\
  !*** ./lib/index.js ***!
  \**********************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "IXircuitsDocTracker": () => (/* binding */ IXircuitsDocTracker),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _jupyterlab_application__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @jupyterlab/application */ "webpack/sharing/consume/default/@jupyterlab/application");
/* harmony import */ var _jupyterlab_application__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_application__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _jupyterlab_filebrowser__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @jupyterlab/filebrowser */ "webpack/sharing/consume/default/@jupyterlab/filebrowser");
/* harmony import */ var _jupyterlab_filebrowser__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_filebrowser__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./components/xircuitBodyWidget */ "./lib/components/xircuitBodyWidget.js");
/* harmony import */ var _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @jupyterlab/apputils */ "webpack/sharing/consume/default/@jupyterlab/apputils");
/* harmony import */ var _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _jupyterlab_launcher__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @jupyterlab/launcher */ "webpack/sharing/consume/default/@jupyterlab/launcher");
/* harmony import */ var _jupyterlab_launcher__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_launcher__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _xircuitFactory__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./xircuitFactory */ "./lib/xircuitFactory.js");
/* harmony import */ var _tray_library_Sidebar__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./tray_library/Sidebar */ "./lib/tray_library/Sidebar.js");
/* harmony import */ var _jupyterlab_docmanager__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @jupyterlab/docmanager */ "webpack/sharing/consume/default/@jupyterlab/docmanager");
/* harmony import */ var _jupyterlab_docmanager__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_docmanager__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _jupyterlab_translation__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @jupyterlab/translation */ "webpack/sharing/consume/default/@jupyterlab/translation");
/* harmony import */ var _jupyterlab_translation__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_translation__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _log_LogPlugin__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./log/LogPlugin */ "./lib/log/LogPlugin.js");
/* harmony import */ var _server_handler__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./server/handler */ "./lib/server/handler.js");
/* harmony import */ var _kernel_panel__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./kernel/panel */ "./lib/kernel/panel.js");
/* harmony import */ var _jupyterlab_rendermime__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @jupyterlab/rendermime */ "webpack/sharing/consume/default/@jupyterlab/rendermime");
/* harmony import */ var _jupyterlab_rendermime__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_rendermime__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @jupyterlab/ui-components */ "webpack/sharing/consume/default/@jupyterlab/ui-components");
/* harmony import */ var _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var _commands_NodeActionCommands__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./commands/NodeActionCommands */ "./lib/commands/NodeActionCommands.js");
/* harmony import */ var _lumino_coreutils__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @lumino/coreutils */ "webpack/sharing/consume/default/@lumino/coreutils");
/* harmony import */ var _lumino_coreutils__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_lumino_coreutils__WEBPACK_IMPORTED_MODULE_9__);
/* harmony import */ var _ui_components_icons__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./ui-components/icons */ "./lib/ui-components/icons.js");
/* harmony import */ var _kernel_RunOutput__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./kernel/RunOutput */ "./lib/kernel/RunOutput.js");



















const FACTORY = 'Xircuits editor';
// Export a token so other extensions can require it
const IXircuitsDocTracker = new _lumino_coreutils__WEBPACK_IMPORTED_MODULE_9__.Token('xircuitsDocTracker');
/**
 * Initialization data for the documents extension.
 */
const xircuits = {
    id: 'xircuits',
    autoStart: true,
    requires: [
        _jupyterlab_launcher__WEBPACK_IMPORTED_MODULE_4__.ILauncher,
        _jupyterlab_filebrowser__WEBPACK_IMPORTED_MODULE_2__.IFileBrowserFactory,
        _jupyterlab_application__WEBPACK_IMPORTED_MODULE_1__.ILayoutRestorer,
        _jupyterlab_rendermime__WEBPACK_IMPORTED_MODULE_7__.IRenderMimeRegistry,
        _jupyterlab_docmanager__WEBPACK_IMPORTED_MODULE_5__.IDocumentManager,
        _jupyterlab_translation__WEBPACK_IMPORTED_MODULE_6__.ITranslator
    ],
    provides: IXircuitsDocTracker,
    activate: async (app, launcher, browserFactory, restorer, rendermime, docmanager, translator) => {
        console.log('Xircuits is activated!');
        // Creating the widget factory to register it so the document manager knows about
        // our new DocumentWidget
        const widgetFactory = new _xircuitFactory__WEBPACK_IMPORTED_MODULE_10__.XircuitFactory({
            name: FACTORY,
            fileTypes: ['xircuits'],
            defaultFor: ['xircuits'],
            app: app,
            shell: app.shell,
            commands: app.commands,
            serviceManager: app.serviceManager
        });
        // register the filetype
        app.docRegistry.addFileType({
            name: 'xircuits',
            displayName: 'Xircuits',
            extensions: ['.xircuits'],
            icon: _ui_components_icons__WEBPACK_IMPORTED_MODULE_11__.xircuitsIcon
        });
        // Registering the widget factory
        app.docRegistry.addWidgetFactory(widgetFactory);
        const tracker = new _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_3__.WidgetTracker({
            namespace: "Xircuits Tracker"
        });
        // Add the widget to the tracker when it's created
        widgetFactory.widgetCreated.connect((sender, widget) => {
            // Notify the instance tracker if restore data needs to update.
            void tracker.add(widget);
            // Notify the widget tracker if restore data needs to update
            widget.context.pathChanged.connect(() => {
                void tracker.save(widget);
            });
        });
        // Handle state restoration
        void restorer.restore(tracker, {
            command: _components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_12__.commandIDs.openDocManager,
            args: widget => ({
                path: widget.context.path,
                factory: FACTORY
            }),
            name: widget => widget.context.path
        });
        // Find the MainLogo widget in the shell and replace it with the Xircuits Logo
        const widgets = app.shell.widgets('top');
        let widget = widgets.next();
        while (widget !== undefined) {
            if (widget.id === 'jp-MainLogo') {
                _ui_components_icons__WEBPACK_IMPORTED_MODULE_11__.xircuitsIcon.element({
                    container: widget.node,
                    justify: 'center',
                    height: 'auto',
                    width: '25px'
                });
                break;
            }
            widget = widgets.next();
        }
        // Change the favicon
        (0,_ui_components_icons__WEBPACK_IMPORTED_MODULE_11__.changeFavicon)(_ui_components_icons__WEBPACK_IMPORTED_MODULE_11__.xircuitsFaviconLink);
        // Creating the sidebar widget for the xai components
        const sidebarWidget = _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_3__.ReactWidget.create(react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_tray_library_Sidebar__WEBPACK_IMPORTED_MODULE_13__["default"], { lab: app, factory: widgetFactory }));
        sidebarWidget.id = 'xircuits-component-sidebar';
        sidebarWidget.title.icon = _ui_components_icons__WEBPACK_IMPORTED_MODULE_11__.componentLibIcon;
        sidebarWidget.title.caption = "Xircuits Component Library";
        restorer.add(sidebarWidget, sidebarWidget.id);
        app.shell.add(sidebarWidget, "left");
        // Additional commands for node action
        (0,_commands_NodeActionCommands__WEBPACK_IMPORTED_MODULE_14__.addNodeActionCommands)(app, tracker, translator);
        // Add a command for creating a new xircuits file.
        app.commands.addCommand(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_12__.commandIDs.createNewXircuit, {
            label: (args) => (args['isLauncher'] ? 'Xircuits File' : 'Create New Xircuits'),
            icon: _ui_components_icons__WEBPACK_IMPORTED_MODULE_11__.xircuitsIcon,
            caption: 'Create a new xircuits file',
            execute: () => {
                app.commands
                    .execute(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_12__.commandIDs.newDocManager, {
                    path: browserFactory.defaultBrowser.model.path,
                    type: 'file',
                    ext: '.xircuits'
                })
                    .then(async (model) => {
                    const newWidget = await app.commands.execute(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_12__.commandIDs.openDocManager, {
                        path: model.path,
                        factory: FACTORY
                    });
                    newWidget.context.ready.then(() => {
                        app.commands.execute(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_12__.commandIDs.saveXircuit, {
                            path: model.path
                        });
                    });
                });
            }
        });
        async function requestToGenerateCompileFile(path, python_paths) {
            const data = {
                "outPath": path.split(".xircuits")[0] + ".py",
                "filePath": path,
                "pythonPaths": python_paths
            };
            try {
                return await (0,_server_handler__WEBPACK_IMPORTED_MODULE_15__.requestAPI)('file/compile', {
                    body: JSON.stringify(data),
                    method: 'POST',
                });
            }
            catch (reason) {
                console.error('Error on POST /xircuits/file/compile', data, reason);
            }
        }
        app.commands.addCommand(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_12__.commandIDs.compileFile, {
            execute: async (args) => {
                const path = tracker.currentWidget.context.path;
                const showOutput = typeof args['showOutput'] === undefined ? false : args['showOutput'];
                const python_paths = {};
                (args['componentList'] === undefined ? [] : args['componentList']).filter(it => it['python_path']).forEach(it => {
                    python_paths[it['name']] = it['python_path'];
                });
                const request = await requestToGenerateCompileFile(path, python_paths);
                if (request["message"] == "completed") {
                    const model_path = path.split(".xircuits")[0] + ".py";
                    docmanager.closeFile(model_path);
                    if (showOutput) {
                        alert(`${model_path} successfully compiled!`);
                    }
                }
                else {
                    console.log(request["message"]);
                    alert("Failed to generate compiled code. Please check console logs for more details.");
                }
            }
        });
        let outputPanel;
        /**
          * Creates a output panel.
          *
          * @returns The panel
          */
        async function createPanel() {
            let splitMode = 'split-bottom'; // default value
            try {
                const data = await (0,_server_handler__WEBPACK_IMPORTED_MODULE_15__.requestAPI)('config/split_mode');
                splitMode = data.splitMode;
            }
            catch (err) {
                console.error('Error fetching split mode from server:', err);
            }
            outputPanel = new _kernel_panel__WEBPACK_IMPORTED_MODULE_16__.OutputPanel(app.serviceManager, rendermime, widgetFactory, translator);
            app.shell.add(outputPanel, 'main', { mode: splitMode });
            return outputPanel;
        }
        // Dispose the output panel when closing browser or tab
        window.addEventListener('beforeunload', function (e) {
            outputPanel.dispose();
        });
        async function requestToSparkSubmit(path, addCommand) {
            const dataToSend = { "currentPath": path, "addArgs": addCommand };
            try {
                const server_reply = await (0,_server_handler__WEBPACK_IMPORTED_MODULE_15__.requestAPI)('spark/submit', {
                    body: JSON.stringify(dataToSend),
                    method: 'POST',
                });
                return server_reply;
            }
            catch (reason) {
                console.error(`Error on POST /xircuits/spark/submit ${dataToSend}.\n${reason}`);
            }
        }
        ;
        function doRemoteRun(path, command, msg, url) {
            try {
                let command_str = command + " " + path;
                let code_str = "\nfrom subprocess import Popen, PIPE\n\n";
                code_str += `command_str= "${command_str}"\n`;
                code_str += "p=Popen(command_str, stdout=PIPE, stderr=PIPE, universal_newlines=True, shell=True)\n";
                code_str += "print('Remote Execution in process...\\n')\n";
                code_str += `print('Please go to ${url} for more details\\n')\n`;
                code_str += `print('${msg}\\n')\n`;
                code_str += "for line in p.stdout:\n";
                code_str += "    " + "print(line.rstrip())\n\n";
                code_str += "if p.returncode != 0:\n";
                code_str += "    " + "print(p.stderr.read())";
                return code_str;
            }
            catch (e) {
                console.log(e);
            }
        }
        // Execute xircuits python script and display at output panel
        app.commands.addCommand(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_12__.commandIDs.executeToOutputPanel, {
            execute: async (args) => {
                const xircuitsLogger = new _log_LogPlugin__WEBPACK_IMPORTED_MODULE_17__.Log(app);
                const current_path = tracker.currentWidget.context.path;
                const model_path = current_path.split(".xircuits")[0] + ".py";
                const message = typeof args['runCommand'] === 'undefined' ? '' : args['runCommand'];
                const runType = typeof args['runType'] === 'undefined' ? '' : args['runType'];
                const config = typeof args['config'] === 'undefined' ? '' : args['config'];
                // Create the panel if it does not exist
                if (!outputPanel || outputPanel.isDisposed) {
                    await createPanel();
                }
                outputPanel.session.ready.then(async () => {
                    let code = (0,_kernel_RunOutput__WEBPACK_IMPORTED_MODULE_18__.startRunOutputStr)();
                    if (runType == 'remote-run') {
                        // Run subprocess when run type is Remote Run
                        code += doRemoteRun(model_path, config['command'], config['msg'], config['url']);
                    }
                    else {
                        code += "%run " + model_path + message;
                    }
                    outputPanel.execute(code, xircuitsLogger);
                });
            },
        });
        // Add command signal to save xircuits
        app.commands.addCommand(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_12__.commandIDs.saveXircuit, {
            label: "Save",
            icon: _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_8__.saveIcon,
            execute: args => {
                widgetFactory.saveXircuitSignal.emit(args);
            }
        });
        // Add command signal to compile xircuits
        app.commands.addCommand(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_12__.commandIDs.compileXircuit, {
            execute: args => {
                widgetFactory.compileXircuitSignal.emit(args);
            }
        });
        // Add command signal to run xircuits
        app.commands.addCommand(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_12__.commandIDs.runXircuit, {
            label: "Run Xircuits",
            icon: _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_8__.runIcon,
            execute: args => {
                widgetFactory.runXircuitSignal.emit(args);
            }
        });
        // Add command signal to lock xircuits
        app.commands.addCommand(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_12__.commandIDs.lockXircuit, {
            execute: args => {
                widgetFactory.lockNodeSignal.emit(args);
            }
        });
        // Add command signal to reloadAllNodes
        app.commands.addCommand(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_12__.commandIDs.reloadAllNodes, {
            execute: args => {
                widgetFactory.reloadAllNodesSignal.emit(args);
            }
        });
        // Add command signal to toggle all link animations.
        app.commands.addCommand(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_12__.commandIDs.toggleAllLinkAnimation, {
            execute: args => {
                widgetFactory.toggleAllLinkAnimationSignal.emit(args);
            }
        });
        // Add a launcher item if the launcher is available.
        if (launcher) {
            launcher.add({
                command: _components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_12__.commandIDs.createNewXircuit,
                rank: 1,
                args: { isLauncher: true },
                category: 'Other'
            });
        }
    },
};
/**
 * Export the plugins as default.
 */
const plugins = [
    xircuits,
    _log_LogPlugin__WEBPACK_IMPORTED_MODULE_17__.logPlugin
];
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (plugins);


/***/ }),

/***/ "./lib/kernel/RunOutput.js":
/*!*********************************!*\
  !*** ./lib/kernel/RunOutput.js ***!
  \*********************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "startRunOutputStr": () => (/* binding */ startRunOutputStr)
/* harmony export */ });
function startRunOutputStr() {
    let code_str;
    code_str =
        `print(
"""
======================================
__   __  ___                _ _
\\ \\  \\ \\/ (_)_ __ ___ _   _(_) |_ ___
 \\ \\  \\  /| | '__/ __| | | | | __/ __|
 / /  /  \\| | | | (__| |_| | | |_\\__ \\\\
/_/  /_/\\_\\_|_|  \\___|\\__,_|_|\\__|___/

======================================
""")\n`;
    code_str += "print('Xircuits is running...\\n')\n";
    return code_str;
}


/***/ }),

/***/ "./lib/kernel/panel.js":
/*!*****************************!*\
  !*** ./lib/kernel/panel.js ***!
  \*****************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "OutputPanel": () => (/* binding */ OutputPanel)
/* harmony export */ });
/* harmony import */ var _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @jupyterlab/apputils */ "webpack/sharing/consume/default/@jupyterlab/apputils");
/* harmony import */ var _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _jupyterlab_outputarea__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @jupyterlab/outputarea */ "webpack/sharing/consume/default/@jupyterlab/outputarea");
/* harmony import */ var _jupyterlab_outputarea__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_outputarea__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _jupyterlab_translation__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @jupyterlab/translation */ "webpack/sharing/consume/default/@jupyterlab/translation");
/* harmony import */ var _jupyterlab_translation__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_translation__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _lumino_widgets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @lumino/widgets */ "webpack/sharing/consume/default/@lumino/widgets");
/* harmony import */ var _lumino_widgets__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_lumino_widgets__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _ui_components_icons__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../ui-components/icons */ "./lib/ui-components/icons.js");





/**
 * The class name added to the output panel.
 */
const PANEL_CLASS = 'jp-RovaPanel';
class CustomOutputArea extends _jupyterlab_outputarea__WEBPACK_IMPORTED_MODULE_1__.SimplifiedOutputArea {
    constructor(options) {
        super(options);
        // Listen to the content change signal of the output area model
        this.model.changed.connect(this._scrollToBottom, this);
    }
    _scrollToBottom() {
        // Scroll the output area to the bottom
        this.node.scrollTop = this.node.scrollHeight;
    }
}
class OutputPanel extends _lumino_widgets__WEBPACK_IMPORTED_MODULE_3__.StackedPanel {
    constructor(manager, rendermime, xircuitFactory, translator) {
        super();
        this._translator = translator || _jupyterlab_translation__WEBPACK_IMPORTED_MODULE_2__.nullTranslator;
        this._trans = this._translator.load('jupyterlab');
        this._xircuitFactory = xircuitFactory;
        this.addClass(PANEL_CLASS);
        this.id = 'xircuit-output-panel';
        this.title.label = this._trans.__('Xircuit Output');
        this.title.closable = true;
        this.title.icon = _ui_components_icons__WEBPACK_IMPORTED_MODULE_4__.xircuitsIcon;
        this._sessionContext = new _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_0__.SessionContext({
            sessionManager: manager.sessions,
            specsManager: manager.kernelspecs,
            name: 'Xircuit Output Process',
        });
        this._outputareamodel = new _jupyterlab_outputarea__WEBPACK_IMPORTED_MODULE_1__.OutputAreaModel();
        this._outputarea = new CustomOutputArea({
            model: this._outputareamodel,
            rendermime: rendermime,
        });
        this.addWidget(this._outputarea);
        void this._sessionContext
            .initialize()
            .then(async (value) => {
            if (value) {
                await _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_0__.sessionContextDialogs.selectKernel(this._sessionContext);
                // Dispose panel when no kernel selected
                if (this._sessionContext.hasNoKernel) {
                    super.dispose();
                }
            }
        })
            .catch((reason) => {
            console.error(`Failed to initialize the session in Xircuit Output.\n${reason}`);
        });
    }
    get session() {
        return this._sessionContext;
    }
    dispose() {
        this._sessionContext.sessionManager.shutdown(this._sessionContext.session.id);
        this._sessionContext.dispose();
        this._sessionContext.sessionManager.refreshRunning();
        super.dispose();
    }
    execute(code, xircuitLogger) {
        _jupyterlab_outputarea__WEBPACK_IMPORTED_MODULE_1__.SimplifiedOutputArea.execute(code, this._outputarea, this._sessionContext)
            .then((msg) => {
            if (this._outputarea.model.toJSON().length > 0) {
                for (let index = 0; index < this._outputarea.model.toJSON().length; index++) {
                    let is_error = this._outputarea.model.toJSON()[index].output_type == "error";
                    if (is_error) {
                        let ename = this._outputarea.model.toJSON()[index]["ename"];
                        let evalue = this._outputarea.model.toJSON()[index]["evalue"];
                        let traceback = this._outputarea.model.toJSON()[index]["traceback"];
                        if (evalue.includes("File") && evalue.includes("not found")) {
                            alert(ename + ": " + evalue + " Please compile first!");
                            xircuitLogger.error(ename + ": " + evalue);
                            console.log(evalue + " Please compile first!");
                            return;
                        }
                        for (let data of traceback) {
                            xircuitLogger.error(data);
                        }
                        return;
                    }
                    let text = this._outputarea.model.toJSON()[index]["text"];
                    for (let text_index = 0; text_index < text.split("\n").length; text_index++) {
                        if (text.split("\n")[text_index].trim() != "") {
                            xircuitLogger.info(text.split("\n")[text_index]);
                        }
                    }
                }
            }
        })
            .catch((reason) => console.error(reason));
    }
    onCloseRequest(msg) {
        super.onCloseRequest(msg);
        this.dispose();
    }
}


/***/ }),

/***/ "./lib/log/LogLevelSwitcher.js":
/*!*************************************!*\
  !*** ./lib/log/LogLevelSwitcher.js ***!
  \*************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ LogLevelSwitcher)
/* harmony export */ });
/* harmony import */ var _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @jupyterlab/apputils */ "webpack/sharing/consume/default/@jupyterlab/apputils");
/* harmony import */ var _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @jupyterlab/ui-components */ "webpack/sharing/consume/default/@jupyterlab/ui-components");
/* harmony import */ var _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _lumino_coreutils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @lumino/coreutils */ "webpack/sharing/consume/default/@lumino/coreutils");
/* harmony import */ var _lumino_coreutils__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_lumino_coreutils__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_3__);




/**
 * A toolbar widget that switches log levels.
 */
class LogLevelSwitcher extends _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_0__.ReactWidget {
    /**
     * Construct a new cell type switcher.
     *
     * @param widget The log console panel
     */
    constructor(widget) {
        super();
        /**
         * Handle `change` events for the HTMLSelect component.
         *
         * @param event The HTML select event.
         */
        this.handleChange = (event) => {
            if (this._logConsole.logger) {
                this._logConsole.logger.level = event.target.value;
            }
            this.update();
        };
        /**
         * Handle `keydown` events for the HTMLSelect component.
         *
         * @param event The keyboard event.
         */
        this.handleKeyDown = (event) => {
            if (event.keyCode === 13) {
                this._logConsole.activate();
            }
        };
        this._id = `level-${_lumino_coreutils__WEBPACK_IMPORTED_MODULE_2__.UUID.uuid4()}`;
        this.addClass('jp-LogConsole-toolbarLogLevel');
        this._logConsole = widget;
        this._logConsole.logger.level = 'debug';
        if (widget.source) {
            this.update();
        }
        widget.sourceChanged.connect(this._updateSource, this);
    }
    _updateSource(sender, { oldValue, newValue }) {
        // Transfer stateChanged handler to new source logger
        if (oldValue !== null) {
            const logger = sender.loggerRegistry.getLogger(oldValue);
            logger.stateChanged.disconnect(this.update, this);
        }
        if (newValue !== null) {
            const logger = sender.loggerRegistry.getLogger(newValue);
            logger.stateChanged.connect(this.update, this);
        }
        this.update();
    }
    render() {
        const logger = this._logConsole.logger;
        return (react__WEBPACK_IMPORTED_MODULE_3___default().createElement((react__WEBPACK_IMPORTED_MODULE_3___default().Fragment), null,
            react__WEBPACK_IMPORTED_MODULE_3___default().createElement("label", { htmlFor: this._id, className: logger === null
                    ? 'jp-LogConsole-toolbarLogLevel-disabled'
                    : undefined }, "Log Level:"),
            react__WEBPACK_IMPORTED_MODULE_3___default().createElement(_jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_1__.HTMLSelect, { id: this._id, className: "jp-LogConsole-toolbarLogLevelDropdown", onChange: this.handleChange, onKeyDown: this.handleKeyDown, value: logger === null || logger === void 0 ? void 0 : logger.level, "aria-label": "Log level", disabled: logger === null, options: logger === null
                    ? []
                    : ['Critical', 'Error', 'Warning', 'Info', 'Debug'].map((label) => ({ label, value: label.toLowerCase() })) })));
    }
}


/***/ }),

/***/ "./lib/log/LogPlugin.js":
/*!******************************!*\
  !*** ./lib/log/LogPlugin.js ***!
  \******************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "Log": () => (/* binding */ Log),
/* harmony export */   "LoggerCommandIDs": () => (/* binding */ LoggerCommandIDs),
/* harmony export */   "logPlugin": () => (/* binding */ logPlugin)
/* harmony export */ });
/* harmony import */ var _jupyterlab_application__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @jupyterlab/application */ "webpack/sharing/consume/default/@jupyterlab/application");
/* harmony import */ var _jupyterlab_application__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_application__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @jupyterlab/ui-components */ "webpack/sharing/consume/default/@jupyterlab/ui-components");
/* harmony import */ var _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _LogLevelSwitcher__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./LogLevelSwitcher */ "./lib/log/LogLevelSwitcher.js");
/* harmony import */ var _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @jupyterlab/apputils */ "webpack/sharing/consume/default/@jupyterlab/apputils");
/* harmony import */ var _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _jupyterlab_rendermime__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @jupyterlab/rendermime */ "webpack/sharing/consume/default/@jupyterlab/rendermime");
/* harmony import */ var _jupyterlab_rendermime__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_rendermime__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _jupyterlab_logconsole__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @jupyterlab/logconsole */ "webpack/sharing/consume/default/@jupyterlab/logconsole");
/* harmony import */ var _jupyterlab_logconsole__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_logconsole__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../components/xircuitBodyWidget */ "./lib/components/xircuitBodyWidget.js");
/* harmony import */ var _server_handler__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../server/handler */ "./lib/server/handler.js");









/**
 * The command IDs used by the log plugin.
 */
var LoggerCommandIDs;
(function (LoggerCommandIDs) {
    LoggerCommandIDs.addCheckpoint = 'Xircuit-log:add-checkpoint';
    LoggerCommandIDs.clear = 'Xircuit-log:clear';
    LoggerCommandIDs.openLog = 'Xircuit-log:open';
    LoggerCommandIDs.setLevel = 'Xircuit-log:set-level';
})(LoggerCommandIDs || (LoggerCommandIDs = {}));
/**
 * Initialization data for the log plugin.
 */
const logPlugin = {
    id: 'xircuit-log',
    autoStart: true,
    requires: [
        _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_2__.ICommandPalette,
        _jupyterlab_application__WEBPACK_IMPORTED_MODULE_0__.ILayoutRestorer,
        _jupyterlab_rendermime__WEBPACK_IMPORTED_MODULE_3__.IRenderMimeRegistry
    ],
    activate: (app, palette, restorer, rendermime) => {
        console.log('Xircuit-Log is activated!');
        let logConsolePanel = null;
        let logConsoleWidget = null;
        const loggertracker = new _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_2__.WidgetTracker({
            namespace: 'Xircuit-log',
        });
        if (restorer) {
            void restorer.restore(loggertracker, {
                command: LoggerCommandIDs.openLog,
                name: () => 'Xircuit-log'
            });
        }
        app.commands.addCommand(LoggerCommandIDs.addCheckpoint, {
            execute: () => { var _a; return (_a = logConsolePanel === null || logConsolePanel === void 0 ? void 0 : logConsolePanel.logger) === null || _a === void 0 ? void 0 : _a.checkpoint(); },
            icon: _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_1__.addIcon,
            isEnabled: () => !!logConsolePanel && logConsolePanel.source !== null,
            label: 'Add Checkpoint',
        });
        app.commands.addCommand(LoggerCommandIDs.clear, {
            execute: () => { var _a; return (_a = logConsolePanel === null || logConsolePanel === void 0 ? void 0 : logConsolePanel.logger) === null || _a === void 0 ? void 0 : _a.clear(); },
            icon: _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_1__.clearIcon,
            isEnabled: () => !!logConsolePanel && logConsolePanel.source !== null,
            label: 'Clear Log',
        });
        app.commands.addCommand(LoggerCommandIDs.setLevel, {
            execute: (args) => {
                if (logConsolePanel === null || logConsolePanel === void 0 ? void 0 : logConsolePanel.logger) {
                    logConsolePanel.logger.level = args.level;
                }
            },
            isEnabled: () => !!logConsolePanel && logConsolePanel.source !== null,
            label: (args) => `Set Log Level to ${args.level}`,
        });
        const createLogConsoleWidget = async () => {
            logConsolePanel = new _jupyterlab_logconsole__WEBPACK_IMPORTED_MODULE_4__.LogConsolePanel(new _jupyterlab_logconsole__WEBPACK_IMPORTED_MODULE_4__.LoggerRegistry({
                defaultRendermime: rendermime,
                maxLength: 1000,
            }));
            logConsolePanel.source = 'xircuit';
            logConsoleWidget = new _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_2__.MainAreaWidget({
                content: logConsolePanel,
            });
            logConsoleWidget.addClass('jp-LogConsole');
            logConsoleWidget.title.label = 'xircuits Log console';
            logConsoleWidget.title.icon = _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_1__.listIcon;
            logConsoleWidget.toolbar.addItem('checkpoint', new _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_2__.CommandToolbarButton({
                commands: app.commands,
                id: LoggerCommandIDs.addCheckpoint,
            }));
            logConsoleWidget.toolbar.addItem('clear', new _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_2__.CommandToolbarButton({
                commands: app.commands,
                id: LoggerCommandIDs.clear,
            }));
            logConsoleWidget.toolbar.addItem('level', new _LogLevelSwitcher__WEBPACK_IMPORTED_MODULE_5__["default"](logConsoleWidget.content));
            logConsoleWidget.disposed.connect(() => {
                logConsoleWidget = null;
                logConsolePanel = null;
                app.commands.notifyCommandChanged();
            });
            let splitMode = 'split-bottom'; // default value
            try {
                const data = await (0,_server_handler__WEBPACK_IMPORTED_MODULE_6__.requestAPI)('config/split_mode');
                splitMode = data.splitMode;
            }
            catch (err) {
                console.error('Error fetching split mode from server:', err);
            }
            app.shell.add(logConsoleWidget, 'main', { mode: splitMode });
            loggertracker.add(logConsoleWidget);
            logConsoleWidget.update();
            app.commands.notifyCommandChanged();
        };
        app.commands.addCommand(LoggerCommandIDs.openLog, {
            label: 'Open Xircuits Log Console',
            caption: 'Xircuits log console',
            icon: _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_1__.listIcon,
            isToggled: () => logConsoleWidget !== null,
            execute: () => {
                if (logConsoleWidget) {
                    logConsoleWidget.dispose();
                }
                else {
                    createLogConsoleWidget();
                }
            },
        });
        palette.addItem({
            command: LoggerCommandIDs.openLog,
            category: 'Examples',
        });
        app.commands.addCommand('jlab-examples/custom-log-console:logHTMLMessage', {
            label: 'HTML log message',
            caption: 'Custom HTML log message example.',
            execute: () => {
                var _a;
                const msg = {
                    type: 'html',
                    level: 'debug',
                    data: '<div>Hello world HTML!!</div>',
                };
                (_a = logConsolePanel === null || logConsolePanel === void 0 ? void 0 : logConsolePanel.logger) === null || _a === void 0 ? void 0 : _a.log(msg);
            },
        });
        app.commands.addCommand('jlab-examples/custom-log-console:logTextMessage', {
            label: 'Text log message',
            caption: 'Custom text log message example.',
            execute: () => {
                var _a;
                const msg = {
                    type: 'text',
                    level: 'info',
                    data: 'Hello world text!!',
                };
                (_a = logConsolePanel === null || logConsolePanel === void 0 ? void 0 : logConsolePanel.logger) === null || _a === void 0 ? void 0 : _a.log(msg);
            },
        });
        app.commands.addCommand(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_7__.commandIDs.outputMsg, {
            label: 'Output log message',
            caption: 'Output xircuits log message.',
            execute: args => {
                var _a;
                const outputMsg = typeof args['outputMsg'] === 'undefined' ? '' : args['outputMsg'];
                const setLevel = args['level'];
                const data = {
                    output_type: 'display_data',
                    data: {
                        'text/plain': outputMsg,
                    },
                };
                const msg = {
                    type: 'output',
                    level: setLevel,
                    data,
                };
                (_a = logConsolePanel === null || logConsolePanel === void 0 ? void 0 : logConsolePanel.logger) === null || _a === void 0 ? void 0 : _a.log(msg);
            },
        });
    },
};
/**
 * Emit output message to xircuit log based on severity level
 */
class Log {
    constructor(app) {
        this.app = app;
    }
    debug(msg, ...supportingDetailes) {
        this.emitLogMessage("debug", msg, supportingDetailes);
    }
    info(msg, ...supportingDetailes) {
        this.emitLogMessage("info", msg, supportingDetailes);
    }
    warn(msg, ...supportingDetailes) {
        this.emitLogMessage("warning", msg, supportingDetailes);
    }
    error(msg, ...supportingDetailes) {
        this.emitLogMessage("error", msg, supportingDetailes);
    }
    critical(msg, ...supportingDetailes) {
        this.emitLogMessage("critical", msg, supportingDetailes);
    }
    emitLogMessage(msgType, msg, supportingDetailes) {
        if (supportingDetailes.length > 0) {
            const logMsg = msg + supportingDetailes;
            this.app.commands.execute(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_7__.commandIDs.outputMsg, {
                outputMsg: logMsg,
                level: msgType
            });
        }
        else {
            this.app.commands.execute(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_7__.commandIDs.outputMsg, {
                outputMsg: msg,
                level: msgType
            });
        }
    }
}


/***/ }),

/***/ "./lib/server/handler.js":
/*!*******************************!*\
  !*** ./lib/server/handler.js ***!
  \*******************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "requestAPI": () => (/* binding */ requestAPI)
/* harmony export */ });
/* harmony import */ var _jupyterlab_coreutils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @jupyterlab/coreutils */ "webpack/sharing/consume/default/@jupyterlab/coreutils");
/* harmony import */ var _jupyterlab_coreutils__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_coreutils__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _jupyterlab_services__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @jupyterlab/services */ "webpack/sharing/consume/default/@jupyterlab/services");
/* harmony import */ var _jupyterlab_services__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_services__WEBPACK_IMPORTED_MODULE_1__);


/**
 * Call the API extension
 *
 * @param endPoint API REST end point for the extension
 * @param init Initial values for the request
 * @returns The response body interpreted as JSON
 */
async function requestAPI(endPoint = '', init = {}) {
    // Make request to Jupyter API
    const settings = _jupyterlab_services__WEBPACK_IMPORTED_MODULE_1__.ServerConnection.makeSettings();
    const requestUrl = _jupyterlab_coreutils__WEBPACK_IMPORTED_MODULE_0__.URLExt.join(settings.baseUrl, 'xircuits', // API Namespace
    endPoint);
    let response;
    try {
        response = await _jupyterlab_services__WEBPACK_IMPORTED_MODULE_1__.ServerConnection.makeRequest(requestUrl, init, settings);
    }
    catch (error) {
        throw new _jupyterlab_services__WEBPACK_IMPORTED_MODULE_1__.ServerConnection.NetworkError(error);
    }
    const data = await response.json();
    if (!response.ok) {
        throw new _jupyterlab_services__WEBPACK_IMPORTED_MODULE_1__.ServerConnection.ResponseError(response, data.message);
    }
    return data;
}


/***/ }),

/***/ "./lib/tray_library/AdvanceComponentLib.js":
/*!*************************************************!*\
  !*** ./lib/tray_library/AdvanceComponentLib.js ***!
  \*************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "AdvancedComponentLibrary": () => (/* binding */ AdvancedComponentLibrary),
/* harmony export */   "fetchNodeByName": () => (/* binding */ fetchNodeByName)
/* harmony export */ });
/* harmony import */ var _components_CustomNodeModel__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../components/CustomNodeModel */ "./lib/components/CustomNodeModel.js");
/* harmony import */ var _Component__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Component */ "./lib/tray_library/Component.js");


async function fetchNodeByName(name) {
    let componentList = [];
    // get the component list 
    const response_1 = await (0,_Component__WEBPACK_IMPORTED_MODULE_0__["default"])();
    componentList = response_1;
    let component_task = componentList.map(x => x["task"]);
    let drop_node = component_task.indexOf(name);
    let current_node;
    if (drop_node != -1) {
        current_node = componentList[drop_node];
    }
    return current_node;
}
function AdvancedComponentLibrary(props) {
    let node = null;
    const nodeData = props.model;
    node = new _components_CustomNodeModel__WEBPACK_IMPORTED_MODULE_1__.CustomNodeModel({
        name: nodeData.class,
        color: nodeData.color,
        extras: {
            "type": nodeData.type,
            "path": nodeData.file_path,
            "description": nodeData.docstring,
            "lineNo": nodeData.lineno,
            "template": nodeData.template,
            "options": nodeData.options
        }
    });
    node.addInPortEnhance({ label: '▶', name: 'in-0' });
    node.addOutPortEnhance({ label: '▶', name: 'out-0' });
    // TODO: Get rid of the remapping by using compatible type names everywhere
    let type_name_remappings = {
        "bool": "boolean",
        "str": "string"
    };
    nodeData["variables"].forEach(variable => {
        let name = variable["name"];
        let type = type_name_remappings[variable["type"]] || variable["type"];
        // if node type includes comma, then multiple types are accepted for that node (ex: str,float; str,int; etc.)
        if (type && type.includes(',')) {
            // take care of remapping, even when multiple types are accepted for the node
            for (let mapping in type_name_remappings) {
                type = type.replace(mapping, type_name_remappings[mapping]);
            }
        }
        else {
            type = type_name_remappings[type] || type;
        }
        switch (variable["kind"]) {
            case "InCompArg":
                node.addInPortEnhance({ label: `★${name}`, name: `parameter-${type}-${name}`, dataType: `${type}` });
                break;
            case "InArg":
                node.addInPortEnhance({ label: name, name: `parameter-${type}-${name}`, dataType: `${type}` });
                break;
            case "OutArg":
                node.addOutPortEnhance({ label: name, name: `parameter-out-${type}-${name}`, dataType: `${type}` });
                break;
            case "BaseComponent":
                node.addOutPortEnhance({ label: `${name} ▶`, name: `out-flow-${name}` });
                break;
            default:
                console.warn("Unknown variable kind for variable", variable);
                break;
        }
    });
    return node;
}


/***/ }),

/***/ "./lib/tray_library/Component.js":
/*!***************************************!*\
  !*** ./lib/tray_library/Component.js ***!
  \***************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ ComponentList)
/* harmony export */ });
/* harmony import */ var _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @jupyterlab/apputils */ "webpack/sharing/consume/default/@jupyterlab/apputils");
/* harmony import */ var _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _server_handler__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../server/handler */ "./lib/server/handler.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);



async function get_all_components_method() {
    const response = await (0,_server_handler__WEBPACK_IMPORTED_MODULE_2__.requestAPI)('components/');
    const components = response["components"];
    const error_msg = response["error_msg"];
    if (error_msg) {
        (0,_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_0__.showDialog)({
            title: 'Parse Component Failed',
            body: (react__WEBPACK_IMPORTED_MODULE_1___default().createElement("pre", null, error_msg)),
            buttons: [_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_0__.Dialog.warnButton({ label: 'OK' })]
        });
    }
    return components;
}
async function ComponentList() {
    let component_list_result = await get_all_components_method();
    return component_list_result;
}


/***/ }),

/***/ "./lib/tray_library/GeneralComponentLib.js":
/*!*************************************************!*\
  !*** ./lib/tray_library/GeneralComponentLib.js ***!
  \*************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "GeneralComponentLibrary": () => (/* binding */ GeneralComponentLibrary),
/* harmony export */   "cancelDialog": () => (/* binding */ cancelDialog),
/* harmony export */   "handleLiteralInput": () => (/* binding */ handleLiteralInput)
/* harmony export */ });
/* harmony import */ var _components_CustomNodeModel__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../components/CustomNodeModel */ "./lib/components/CustomNodeModel.js");
/* harmony import */ var _dialog_LiteralInputDialog__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../dialog/LiteralInputDialog */ "./lib/dialog/LiteralInputDialog.js");
/* harmony import */ var _dialog_FormDialog__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../dialog/FormDialog */ "./lib/dialog/FormDialog.js");
/* harmony import */ var _helpers_InputSanitizer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../helpers/InputSanitizer */ "./lib/helpers/InputSanitizer.js");




function cancelDialog(dialogResult) {
    if (dialogResult["button"]["label"] == 'Cancel') {
        // When Cancel is clicked on the dialog, just return
        return true;
    }
    return false;
}
const TYPE_LITERALS = ['string', 'int', 'float', 'boolean', 'list', 'tuple', 'dict', 'secret', 'chat'];
const TYPE_ARGUMENTS = ['string', 'int', 'float', 'boolean'];
const SPECIAL_LITERALS = ['chat'];
async function handleLiteralInput(nodeName, nodeData, inputValue = "", type, title = "New Literal Input") {
    do {
        let dialogOptions = (0,_dialog_LiteralInputDialog__WEBPACK_IMPORTED_MODULE_0__.inputDialog)({ title, oldValue: inputValue, type });
        let dialogResult = await (0,_dialog_FormDialog__WEBPACK_IMPORTED_MODULE_1__.showFormDialog)(dialogOptions);
        if (cancelDialog(dialogResult))
            return;
        if (SPECIAL_LITERALS.includes(type)) {
            // lit chat values accessed through dialogResult["value"]
            inputValue = dialogResult["value"];
        }
        else {
            inputValue = dialogResult["value"][title];
        }
    } while (!(0,_helpers_InputSanitizer__WEBPACK_IMPORTED_MODULE_2__.checkInput)(inputValue, type));
    if (SPECIAL_LITERALS.includes(type))
        inputValue = JSON.stringify(inputValue);
    if (nodeName === 'Literal True' || nodeName === 'Literal False')
        nodeName = 'Literal Boolean';
    const node = new _components_CustomNodeModel__WEBPACK_IMPORTED_MODULE_3__.CustomNodeModel({ name: nodeName, color: nodeData.color, extras: { "type": nodeData.type } });
    node.addOutPortEnhance({ label: inputValue, name: 'out-0', dataType: nodeData.type });
    return node;
}
async function handleArgumentInput(nodeData, argumentTitle) {
    const dialogOptions = (0,_dialog_LiteralInputDialog__WEBPACK_IMPORTED_MODULE_0__.inputDialog)({ title: argumentTitle, oldValue: "", type: 'argument', inputType: nodeData.type });
    const dialogResult = await (0,_dialog_FormDialog__WEBPACK_IMPORTED_MODULE_1__.showFormDialog)(dialogOptions);
    if (cancelDialog(dialogResult))
        return;
    const inputValue = dialogResult["value"][argumentTitle];
    const node = new _components_CustomNodeModel__WEBPACK_IMPORTED_MODULE_3__.CustomNodeModel({ name: `Argument (${nodeData.type}): ${inputValue}`, color: nodeData.color, extras: { "type": nodeData.type } });
    node.addOutPortEnhance({ label: '▶', name: 'parameter-out-0', dataType: nodeData.type });
    return node;
}
async function GeneralComponentLibrary(props) {
    let node = null;
    const nodeData = props.model;
    const variableValue = props.variableValue || '';
    const nodeName = nodeData.task;
    // handler for Boolean
    if (nodeData.type === 'boolean' && nodeName.startsWith("Literal")) {
        const portLabel = nodeData.task.split(' ').slice(-1)[0];
        node = new _components_CustomNodeModel__WEBPACK_IMPORTED_MODULE_3__.CustomNodeModel({ name: "Literal Boolean", color: nodeData.color, extras: { "type": nodeData.type } });
        node.addOutPortEnhance({ label: portLabel, name: 'out-0', dataType: nodeData.type });
        return node;
    }
    // handler for Any
    if (variableValue) {
        const node = new _components_CustomNodeModel__WEBPACK_IMPORTED_MODULE_3__.CustomNodeModel({ name: nodeName, color: nodeData.color, extras: { "type": nodeData.type } });
        node.addOutPortEnhance({ label: variableValue, name: 'out-0', dataType: nodeData.type });
        return node;
    }
    if (TYPE_LITERALS.includes(nodeData.type) && nodeName.startsWith("Literal")) {
        return handleLiteralInput(nodeName, nodeData, variableValue, nodeData.type);
    }
    if (TYPE_ARGUMENTS.includes(nodeData.type)) {
        return handleArgumentInput(nodeData, 'Please define parameter');
    }
    return null;
}


/***/ }),

/***/ "./lib/tray_library/Sidebar.js":
/*!*************************************!*\
  !*** ./lib/tray_library/Sidebar.js ***!
  \*************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "Body": () => (/* binding */ Body),
/* harmony export */   "Content": () => (/* binding */ Content),
/* harmony export */   "default": () => (/* binding */ Sidebar)
/* harmony export */ });
/* harmony import */ var _Component__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Component */ "./lib/tray_library/Component.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _emotion_styled__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @emotion/styled */ "webpack/sharing/consume/default/@emotion/styled/@emotion/styled?2715");
/* harmony import */ var _emotion_styled__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_emotion_styled__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _TrayItemWidget__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./TrayItemWidget */ "./lib/tray_library/TrayItemWidget.js");
/* harmony import */ var _TrayWidget__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./TrayWidget */ "./lib/tray_library/TrayWidget.js");
/* harmony import */ var react_accessible_accordion__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! react-accessible-accordion */ "webpack/sharing/consume/default/react-accessible-accordion/react-accessible-accordion");
/* harmony import */ var react_accessible_accordion__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(react_accessible_accordion__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _server_handler__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../server/handler */ "./lib/server/handler.js");







const Body = (_emotion_styled__WEBPACK_IMPORTED_MODULE_1___default().div) `
  flex-grow: 1;
  display: flex;
  flex-wrap: wrap;
  min-height: 100%;
  background-color: black;
  height: 100%;
  overflow-y: auto;
`;
const Content = (_emotion_styled__WEBPACK_IMPORTED_MODULE_1___default().div) `
    display: flex;
    flex-grow: 1;
    flex-wrap: wrap;
    max-height: auto;
    'border-top': '4px solid #dfe2e5'
`;
const headerList = [
    { task: 'GENERAL', id: 1 }
];
const advancedList = [
    { task: 'ADVANCED', id: 1 }
];
const colorList_adv = [
    { task: "rgb(192,255,0)", id: 1 },
    { task: "rgb(0,102,204)", id: 2 },
    { task: "rgb(255,153,102)", id: 3 },
    { task: "rgb(255,102,102)", id: 4 },
    { task: "rgb(15,255,255)", id: 5 },
    { task: "rgb(255,204,204)", id: 6 },
    { task: "rgb(153,204,51)", id: 7 },
    { task: "rgb(255,153,0)", id: 8 },
    { task: "rgb(255,204,0)", id: 9 },
    { task: "rgb(204,204,204)", id: 10 },
    { task: "rgb(153,204,204)", id: 11 },
    { task: "rgb(153,0,102)", id: 12 },
    { task: "rgb(102,51,102)", id: 13 },
    { task: "rgb(153,51,204)", id: 14 },
    { task: "rgb(102,102,102)", id: 15 },
    { task: "rgb(255,102,0)", id: 16 },
    { task: "rgb(51,51,51)", id: 17 },
];
const colorList_general = [
    { task: "rgb(21,21,51)", id: 1 }
];
async function fetchComponent(componentList) {
    let component_root = componentList.map(x => x["category"]);
    let headers = Array.from(new Set(component_root));
    let headerList = [];
    let headerList2 = [];
    let displayHeaderList = [];
    for (let headerIndex = 0; headerIndex < headers.length; headerIndex++) {
        if (headers[headerIndex] == 'ADVANCED' || headers[headerIndex] == 'GENERAL') {
            headerList.push(headers[headerIndex]);
        }
        else {
            headerList2.push(headers[headerIndex]);
        }
    }
    if (headerList.length != 0) {
        headerList = headerList.sort((a, b) => a < b ? 1 : a > b ? -1 : 0);
        headers = [...headerList, ...headerList2];
        for (let headerIndex2 = 0; headerIndex2 < headers.length; headerIndex2++) {
            displayHeaderList.push({
                "task": headers[headerIndex2],
                "id": headerIndex2 + 1
            });
        }
    }
    return displayHeaderList;
}
function Sidebar(props) {
    const [componentList, setComponentList] = react__WEBPACK_IMPORTED_MODULE_0___default().useState([]);
    const [category, setCategory] = react__WEBPACK_IMPORTED_MODULE_0___default().useState([]);
    const [searchTerm, setSearchTerm] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)('');
    const [runOnce, setRunOnce] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(false);
    let handleOnChange = (event) => {
        setSearchTerm("");
        setSearchTerm(event.target.value);
    };
    function handleSearchOnClick() {
        setSearchTerm("");
        setSearchTerm(searchTerm);
    }
    async function getConfig(request) {
        const dataToSend = { "config_request": request };
        try {
            const server_reply = await (0,_server_handler__WEBPACK_IMPORTED_MODULE_3__.requestAPI)('get/config', {
                body: JSON.stringify(dataToSend),
                method: 'POST',
            });
            return server_reply;
        }
        catch (reason) {
            console.error(`Error on POST get/config ${dataToSend}.\n${reason}`);
        }
    }
    ;
    const fetchComponentList = async () => {
        // get the component list 
        const response_1 = await (0,_Component__WEBPACK_IMPORTED_MODULE_4__["default"])();
        // get the header from the components
        const response_2 = await fetchComponent(response_1);
        // to ensure the component list is empty before setting the component list
        if (response_1.length > 0) {
            setComponentList([]);
            setCategory([]);
        }
        setComponentList(response_1);
        setCategory(response_2);
    };
    (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
        if (!runOnce) {
            fetchComponentList();
            setRunOnce(true);
        }
    }, [category, componentList]);
    function handleRefreshOnClick() {
        fetchComponentList();
    }
    (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
        const intervalId = setInterval(() => {
            fetchComponentList();
        }, 600000); // every 10 minutes should re-fetch the component list
        return () => clearInterval(intervalId);
    }, [category, componentList]);
    (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
        const intervalId = setInterval(async () => {
            await props.factory.fetchComponentsSignal.emit(componentList);
        }, 300); // Send component list to canvas once render or when refresh
        return () => clearInterval(intervalId);
    }, [componentList, handleRefreshOnClick]);
    return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement(Body, null,
        react__WEBPACK_IMPORTED_MODULE_0___default().createElement(Content, null,
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_TrayWidget__WEBPACK_IMPORTED_MODULE_5__.TrayWidget, null,
                react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", null,
                    react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "search-input" },
                        react__WEBPACK_IMPORTED_MODULE_0___default().createElement("input", { type: "text", name: "", value: searchTerm, placeholder: "SEARCH", className: "search-input__text-input", style: { width: "75%" }, onChange: handleOnChange }),
                        react__WEBPACK_IMPORTED_MODULE_0___default().createElement("a", { onClick: handleSearchOnClick, className: "search-input__button" },
                            react__WEBPACK_IMPORTED_MODULE_0___default().createElement("i", { className: "fa fa-search " })),
                        react__WEBPACK_IMPORTED_MODULE_0___default().createElement("a", { onClick: handleRefreshOnClick, className: "search-input__button" },
                            react__WEBPACK_IMPORTED_MODULE_0___default().createElement("i", { className: "fa fa-refresh " }))),
                    react__WEBPACK_IMPORTED_MODULE_0___default().createElement(react_accessible_accordion__WEBPACK_IMPORTED_MODULE_2__.Accordion, { allowZeroExpanded: true }, category.filter((val) => {
                        if (searchTerm == "") {
                            return val;
                        }
                    }).map((val, i) => {
                        return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement(react_accessible_accordion__WEBPACK_IMPORTED_MODULE_2__.AccordionItem, { key: `index-1-${val["task"].toString()}` },
                            react__WEBPACK_IMPORTED_MODULE_0___default().createElement(react_accessible_accordion__WEBPACK_IMPORTED_MODULE_2__.AccordionItemHeading, null,
                                react__WEBPACK_IMPORTED_MODULE_0___default().createElement(react_accessible_accordion__WEBPACK_IMPORTED_MODULE_2__.AccordionItemButton, null, val["task"])),
                            react__WEBPACK_IMPORTED_MODULE_0___default().createElement(react_accessible_accordion__WEBPACK_IMPORTED_MODULE_2__.AccordionItemPanel, null, componentList.filter((componentVal) => {
                                if (searchTerm == "") {
                                    return componentVal;
                                }
                            }).map((componentVal, i2) => {
                                if (componentVal["category"].toString().toUpperCase() == val["task"].toString()) {
                                    return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { key: `index-1-${i2}` },
                                        react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_TrayItemWidget__WEBPACK_IMPORTED_MODULE_6__.TrayItemWidget, { model: {
                                                type: componentVal.type,
                                                name: componentVal.task,
                                                color: componentVal.color,
                                                path: componentVal.file_path,
                                                docstring: componentVal.docstring,
                                                lineNo: componentVal.lineno
                                            }, name: componentVal.task, color: componentVal.color, app: props.lab, path: componentVal.file_path, lineNo: componentVal.lineno })));
                                }
                            }))));
                    })),
                    componentList.filter((val) => {
                        if (searchTerm != "" && val.task.toLowerCase().includes(searchTerm.toLowerCase())) {
                            return val;
                        }
                    }).map((val, i) => {
                        return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { key: `index-3-${i}` },
                            react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_TrayItemWidget__WEBPACK_IMPORTED_MODULE_6__.TrayItemWidget, { model: {
                                    type: val.type,
                                    name: val.task,
                                    color: val.color,
                                    path: val.file_path,
                                    docstring: val.docstring,
                                    lineNo: val.lineno
                                }, name: val.task, color: val.color, app: props.lab, path: val.file_path, lineNo: val.lineno })));
                    }))))));
}
;


/***/ }),

/***/ "./lib/tray_library/TrayItemWidget.js":
/*!********************************************!*\
  !*** ./lib/tray_library/TrayItemWidget.js ***!
  \********************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "Tray": () => (/* binding */ Tray),
/* harmony export */   "TrayItemWidget": () => (/* binding */ TrayItemWidget)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _emotion_styled__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @emotion/styled */ "webpack/sharing/consume/default/@emotion/styled/@emotion/styled?2715");
/* harmony import */ var _emotion_styled__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_emotion_styled__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../components/xircuitBodyWidget */ "./lib/components/xircuitBodyWidget.js");



const Tray = (_emotion_styled__WEBPACK_IMPORTED_MODULE_1___default().div) `
	color: black;
	font-family: Helvetica, Arial;
	padding: 7px;
	width: auto;
	margin: 7px;
	border: solid 1px ${(p) => p.color};
	border-radius: 5px;
	margin-bottom: 2px;
	cursor: pointer;
`;
class TrayItemWidget extends react__WEBPACK_IMPORTED_MODULE_0__.Component {
    render() {
        return (react__WEBPACK_IMPORTED_MODULE_0__.createElement(Tray, { color: this.props.color || "white", draggable: true, onDragStart: (event) => {
                event.dataTransfer.setData('storm-diagram-node', JSON.stringify(this.props.model));
                this.forceUpdate();
            }, onClick: (event) => {
                if (event.ctrlKey || event.metaKey) {
                    const { commands } = this.props.app;
                    commands.execute(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_2__.commandIDs.openScript, {
                        nodePath: this.props.path,
                        nodeName: this.props.name,
                        nodeLineNo: this.props.lineNo
                    });
                }
                this.forceUpdate();
            }, onDoubleClick: () => {
                if (this.props.path != "") {
                    const { commands } = this.props.app;
                    commands.execute(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_2__.commandIDs.openScript, {
                        nodePath: this.props.path,
                        nodeName: this.props.name,
                        nodeLineNo: this.props.lineNo
                    });
                }
                this.forceUpdate();
            }, className: "tray-item" }, this.props.name));
    }
}


/***/ }),

/***/ "./lib/tray_library/TrayWidget.js":
/*!****************************************!*\
  !*** ./lib/tray_library/TrayWidget.js ***!
  \****************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "Tray": () => (/* binding */ Tray),
/* harmony export */   "TrayWidget": () => (/* binding */ TrayWidget)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _emotion_styled__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @emotion/styled */ "webpack/sharing/consume/default/@emotion/styled/@emotion/styled?2715");
/* harmony import */ var _emotion_styled__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_emotion_styled__WEBPACK_IMPORTED_MODULE_1__);


const Tray = (_emotion_styled__WEBPACK_IMPORTED_MODULE_1___default().div) `
	min-width: 150px;
	background: rgb(255, 255, 255);
	flex-grow: 1;
	width: 150px;
	flex-shrink: 1;
	max-height: auto;
	overflow-y: auto;
`;
class TrayWidget extends react__WEBPACK_IMPORTED_MODULE_0__.Component {
    render() {
        return react__WEBPACK_IMPORTED_MODULE_0__.createElement(Tray, null, this.props.children);
    }
}


/***/ }),

/***/ "./lib/ui-components/icons.js":
/*!************************************!*\
  !*** ./lib/ui-components/icons.js ***!
  \************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "breakpointIcon": () => (/* binding */ breakpointIcon),
/* harmony export */   "changeFavicon": () => (/* binding */ changeFavicon),
/* harmony export */   "componentLibIcon": () => (/* binding */ componentLibIcon),
/* harmony export */   "debuggerIcon": () => (/* binding */ debuggerIcon),
/* harmony export */   "lockIcon": () => (/* binding */ lockIcon),
/* harmony export */   "nextIcon": () => (/* binding */ nextIcon),
/* harmony export */   "reloadAllIcon": () => (/* binding */ reloadAllIcon),
/* harmony export */   "revertIcon": () => (/* binding */ revertIcon),
/* harmony export */   "toggleAnimationIcon": () => (/* binding */ toggleAnimationIcon),
/* harmony export */   "xircuitsFaviconLink": () => (/* binding */ xircuitsFaviconLink),
/* harmony export */   "xircuitsIcon": () => (/* binding */ xircuitsIcon)
/* harmony export */ });
/* harmony import */ var _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @jupyterlab/ui-components */ "webpack/sharing/consume/default/@jupyterlab/ui-components");
/* harmony import */ var _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _style_icons_xpress_logo_svg__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../style/icons/xpress-logo.svg */ "./style/icons/xpress-logo.svg");
/* harmony import */ var _style_icons_debugger_svg__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../style/icons/debugger.svg */ "./style/icons/debugger.svg");
/* harmony import */ var _style_icons_lock_svg__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../style/icons/lock.svg */ "./style/icons/lock.svg");
/* harmony import */ var _style_icons_breakpoint_svg__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../style/icons/breakpoint.svg */ "./style/icons/breakpoint.svg");
/* harmony import */ var _style_icons_next_svg__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../style/icons/next.svg */ "./style/icons/next.svg");
/* harmony import */ var _style_icons_revert_svg__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../style/icons/revert.svg */ "./style/icons/revert.svg");
/* harmony import */ var _style_icons_component_library_svg__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../style/icons/component-library.svg */ "./style/icons/component-library.svg");
/* harmony import */ var _style_icons_reload_all_svg__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../../style/icons/reload-all.svg */ "./style/icons/reload-all.svg");
/* harmony import */ var _style_icons_low_power_svg__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../../style/icons/low-power.svg */ "./style/icons/low-power.svg");










const xircuitsFaviconLink = 'https://raw.githubusercontent.com/XpressAI/xircuits/master/style/icons/xpress-logo.ico';
const xircuitsIcon = new _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_0__.LabIcon({ name: 'xircuits:xircuits', svgstr: _style_icons_xpress_logo_svg__WEBPACK_IMPORTED_MODULE_1__["default"] });
const debuggerIcon = new _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_0__.LabIcon({ name: 'xircuits:debuggerIcon', svgstr: _style_icons_debugger_svg__WEBPACK_IMPORTED_MODULE_2__["default"] });
const lockIcon = new _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_0__.LabIcon({ name: 'xircuits:lockIcon', svgstr: _style_icons_lock_svg__WEBPACK_IMPORTED_MODULE_3__["default"] });
const breakpointIcon = new _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_0__.LabIcon({ name: 'xircuits:breakpointIcon', svgstr: _style_icons_breakpoint_svg__WEBPACK_IMPORTED_MODULE_4__["default"] });
const nextIcon = new _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_0__.LabIcon({ name: 'xircuits:nextIcon', svgstr: _style_icons_next_svg__WEBPACK_IMPORTED_MODULE_5__["default"] });
const revertIcon = new _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_0__.LabIcon({ name: 'xircuits:revertIcon', svgstr: _style_icons_revert_svg__WEBPACK_IMPORTED_MODULE_6__["default"] });
const componentLibIcon = new _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_0__.LabIcon({ name: 'xircuits:componentLibIcon', svgstr: _style_icons_component_library_svg__WEBPACK_IMPORTED_MODULE_7__["default"] });
const reloadAllIcon = new _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_0__.LabIcon({ name: 'xircuits:reloadAllIcon', svgstr: _style_icons_reload_all_svg__WEBPACK_IMPORTED_MODULE_8__["default"] });
const toggleAnimationIcon = new _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_0__.LabIcon({ name: 'xircuits:toggleAnimationIcon', svgstr: _style_icons_low_power_svg__WEBPACK_IMPORTED_MODULE_9__["default"] });
function changeFavicon(src) {
    let head = document.head || document.getElementsByTagName('head')[0];
    let link = document.createElement('link'), oldLink = document.getElementById('dynamic-favicon');
    link.id = 'dynamic-favicon';
    link.rel = 'icon';
    link.type = 'image/x-icon';
    link.href = src;
    if (oldLink) {
        head.removeChild(oldLink);
    }
    head.appendChild(link);
}


/***/ }),

/***/ "./lib/xircuitFactory.js":
/*!*******************************!*\
  !*** ./lib/xircuitFactory.js ***!
  \*******************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "XircuitFactory": () => (/* binding */ XircuitFactory)
/* harmony export */ });
/* harmony import */ var _jupyterlab_docregistry__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @jupyterlab/docregistry */ "webpack/sharing/consume/default/@jupyterlab/docregistry");
/* harmony import */ var _jupyterlab_docregistry__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_docregistry__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _lumino_signaling__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @lumino/signaling */ "webpack/sharing/consume/default/@lumino/signaling");
/* harmony import */ var _lumino_signaling__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_lumino_signaling__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _xircuitWidget__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./xircuitWidget */ "./lib/xircuitWidget.js");
/* harmony import */ var _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @jupyterlab/ui-components */ "webpack/sharing/consume/default/@jupyterlab/ui-components");
/* harmony import */ var _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @jupyterlab/apputils */ "webpack/sharing/consume/default/@jupyterlab/apputils");
/* harmony import */ var _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./components/xircuitBodyWidget */ "./lib/components/xircuitBodyWidget.js");
/* harmony import */ var _log_LogPlugin__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./log/LogPlugin */ "./lib/log/LogPlugin.js");
/* harmony import */ var _components_RunSwitcher__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./components/RunSwitcher */ "./lib/components/RunSwitcher.js");
/* harmony import */ var _ui_components_icons__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./ui-components/icons */ "./lib/ui-components/icons.js");









const XPIPE_CLASS = 'xircuits-editor';
class XircuitFactory extends _jupyterlab_docregistry__WEBPACK_IMPORTED_MODULE_0__.ABCWidgetFactory {
    constructor(options) {
        super(options);
        this.app = options.app;
        this.shell = options.shell;
        this.commands = options.commands;
        this.serviceManager = options.serviceManager;
        this.fetchComponentsSignal = new _lumino_signaling__WEBPACK_IMPORTED_MODULE_1__.Signal(this);
        this.saveXircuitSignal = new _lumino_signaling__WEBPACK_IMPORTED_MODULE_1__.Signal(this);
        this.compileXircuitSignal = new _lumino_signaling__WEBPACK_IMPORTED_MODULE_1__.Signal(this);
        this.runXircuitSignal = new _lumino_signaling__WEBPACK_IMPORTED_MODULE_1__.Signal(this);
        this.runTypeXircuitSignal = new _lumino_signaling__WEBPACK_IMPORTED_MODULE_1__.Signal(this);
        this.lockNodeSignal = new _lumino_signaling__WEBPACK_IMPORTED_MODULE_1__.Signal(this);
        this.reloadAllNodesSignal = new _lumino_signaling__WEBPACK_IMPORTED_MODULE_1__.Signal(this);
        this.toggleAllLinkAnimationSignal = new _lumino_signaling__WEBPACK_IMPORTED_MODULE_1__.Signal(this);
    }
    createNewWidget(context) {
        // Creates a blank widget with a DocumentWidget wrapper
        const props = {
            app: this.app,
            shell: this.shell,
            commands: this.commands,
            context: context,
            serviceManager: this.serviceManager,
            fetchComponentsSignal: this.fetchComponentsSignal,
            saveXircuitSignal: this.saveXircuitSignal,
            compileXircuitSignal: this.compileXircuitSignal,
            runXircuitSignal: this.runXircuitSignal,
            runTypeXircuitSignal: this.runTypeXircuitSignal,
            lockNodeSignal: this.lockNodeSignal,
            reloadAllNodesSignal: this.reloadAllNodesSignal,
            toggleAllLinkAnimationSignal: this.toggleAllLinkAnimationSignal,
        };
        const content = new _xircuitWidget__WEBPACK_IMPORTED_MODULE_4__.XPipePanel(props);
        const widget = new _jupyterlab_docregistry__WEBPACK_IMPORTED_MODULE_0__.DocumentWidget({ content, context });
        widget.addClass(XPIPE_CLASS);
        widget.title.icon = _ui_components_icons__WEBPACK_IMPORTED_MODULE_5__.xircuitsIcon;
        /**
         * Create a save button toolbar item.
         */
        let saveButton = new _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_3__.ToolbarButton({
            icon: _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_2__.saveIcon,
            tooltip: 'Save (Ctrl+S)',
            onClick: () => {
                this.commands.execute(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_6__.commandIDs.saveXircuit);
            }
        });
        /**
         * Create a undo button toolbar item.
         */
        let undoButton = new _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_3__.ToolbarButton({
            icon: _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_2__.undoIcon,
            tooltip: 'Undo (Ctrl+Z)',
            onClick: () => {
                this.commands.execute(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_6__.commandIDs.undo);
            }
        });
        /**
         * Create a redo button toolbar item.
         */
        let redoButton = new _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_3__.ToolbarButton({
            icon: _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_2__.redoIcon,
            tooltip: 'Redo (Ctrl+Y)',
            onClick: () => {
                this.commands.execute(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_6__.commandIDs.redo);
            }
        });
        /**
         * Create a reload button toolbar item.
         */
        let reloadButton = new _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_3__.ToolbarButton({
            icon: _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_2__.refreshIcon,
            tooltip: 'Reload Xircuits from Disk',
            onClick: () => {
                this.commands.execute(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_6__.commandIDs.reloadDocManager);
            }
        });
        /**
         * Create a cut button toolbar item.
         */
        let cutButton = new _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_3__.ToolbarButton({
            icon: _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_2__.cutIcon,
            tooltip: 'Cut selected nodes',
            onClick: () => {
                this.commands.execute(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_6__.commandIDs.cutNode);
            }
        });
        /**
         * Create a copy button toolbar item.
         */
        let copyButton = new _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_3__.ToolbarButton({
            icon: _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_2__.copyIcon,
            tooltip: 'Copy selected nodes',
            onClick: () => {
                this.commands.execute(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_6__.commandIDs.copyNode);
            }
        });
        /**
         * Create a paste button toolbar item.
         */
        let pasteButton = new _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_3__.ToolbarButton({
            icon: _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_2__.pasteIcon,
            tooltip: 'Paste nodes from the clipboard',
            onClick: () => {
                this.commands.execute(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_6__.commandIDs.pasteNode);
            }
        });
        /**
         * Create a debug button toolbar item.
         */
        // let debugButton = new ToolbarButton({
        //   icon:bugIcon,
        //   tooltip: 'Open Xircuits Debugger and enable Image Viewer',
        //   onClick: (): void => {
        //     this.commands.execute(commandIDs.debugXircuit);
        //   }
        // });
        /**
         * Create a lock button toolbar item.
         */
        let lockButton = new _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_3__.ToolbarButton({
            icon: _ui_components_icons__WEBPACK_IMPORTED_MODULE_5__.lockIcon,
            tooltip: "Lock all non-general nodes connected from start node",
            onClick: () => {
                this.commands.execute(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_6__.commandIDs.lockXircuit);
            }
        });
        /**
         * Create a log button toolbar item.
         */
        let logButton = new _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_3__.ToolbarButton({
            icon: _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_2__.listIcon,
            tooltip: 'Open log',
            onClick: () => {
                this.commands.execute(_log_LogPlugin__WEBPACK_IMPORTED_MODULE_7__.LoggerCommandIDs.openLog);
            }
        });
        /**
         * Create a reload all button toolbar item.
         */
        let reloadAllNodesButton = new _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_3__.ToolbarButton({
            icon: _ui_components_icons__WEBPACK_IMPORTED_MODULE_5__.reloadAllIcon,
            tooltip: 'Reload all nodes',
            onClick: () => {
                this.commands.execute(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_6__.commandIDs.reloadAllNodes);
            }
        });
        /**
         * Create a button to toggle all link animation toolbar item.
         */
        let toggleAllLinkAnimationButton = new _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_3__.ToolbarButton({
            icon: _ui_components_icons__WEBPACK_IMPORTED_MODULE_5__.toggleAnimationIcon,
            tooltip: 'Toggle low power mode by disabling link animation',
            onClick: () => {
                this.commands.execute(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_6__.commandIDs.toggleAllLinkAnimation);
            }
        });
        /**
         * Create a compile button toolbar item.
         */
        let compileButton = new _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_3__.ToolbarButton({
            icon: _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_2__.checkIcon,
            tooltip: 'Compile Xircuits',
            onClick: () => {
                this.commands.execute(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_6__.commandIDs.compileXircuit);
            }
        });
        /**
         * Create a compile and run button toolbar item.
         */
        let compileAndRunButton = new _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_3__.ToolbarButton({
            icon: _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_2__.runIcon,
            tooltip: 'Compile and Run Xircuits',
            onClick: () => {
                this.commands.execute(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_6__.commandIDs.runXircuit);
            }
        });
        widget.toolbar.insertItem(0, 'xircuits-add-undo', undoButton);
        widget.toolbar.insertItem(1, 'xircuits-add-redo', redoButton);
        widget.toolbar.insertItem(2, 'xircuits-add-reload', reloadButton);
        widget.toolbar.insertItem(3, 'xircuits-add-cut', cutButton);
        widget.toolbar.insertItem(4, 'xircuits-add-copy', copyButton);
        widget.toolbar.insertItem(5, 'xircuits-add-paste', pasteButton);
        widget.toolbar.insertItem(6, 'xircuits-add-lock', lockButton);
        widget.toolbar.insertItem(7, 'xircuits-add-log', logButton);
        widget.toolbar.insertItem(8, 'xircuits-add-toggle-all-link-animation', toggleAllLinkAnimationButton);
        widget.toolbar.insertItem(9, 'xircuits-add-reload-all', reloadAllNodesButton);
        widget.toolbar.insertItem(10, 'xircuits-add-save', saveButton);
        widget.toolbar.insertItem(11, 'xircuits-add-compile', compileButton);
        widget.toolbar.insertItem(12, 'xircuits-add-run', compileAndRunButton);
        widget.toolbar.insertItem(13, 'xircuits-run-type', new _components_RunSwitcher__WEBPACK_IMPORTED_MODULE_8__.RunSwitcher(this));
        // TODO: Fix debugger
        // widget.toolbar.insertItem(5,'xircuits-add-debug', debugButton);
        return widget;
    }
}


/***/ }),

/***/ "./lib/xircuitWidget.js":
/*!******************************!*\
  !*** ./lib/xircuitWidget.js ***!
  \******************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "XPipePanel": () => (/* binding */ XPipePanel)
/* harmony export */ });
/* harmony import */ var _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @jupyterlab/apputils */ "webpack/sharing/consume/default/@jupyterlab/apputils");
/* harmony import */ var _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./components/xircuitBodyWidget */ "./lib/components/xircuitBodyWidget.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _components_XircuitsApp__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./components/XircuitsApp */ "./lib/components/XircuitsApp.js");




/**
 * DocumentWidget: widget that represents the view or editor for a file type.
 */
class XPipePanel extends _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_0__.ReactWidget {
    constructor(options) {
        super(options);
        // Add mousePosition state
        this.mousePosition = { x: 0, y: 0 };
        this.app = options.app;
        this.shell = options.shell;
        this.commands = options.commands;
        this.context = options.context;
        this.serviceManager = options.serviceManager;
        this.fetchComponentsSignal = options.fetchComponentsSignal;
        this.saveXircuitSignal = options.saveXircuitSignal;
        this.compileXircuitSignal = options.compileXircuitSignal;
        this.runXircuitSignal = options.runXircuitSignal;
        this.runTypeXircuitSignal = options.runTypeXircuitSignal;
        this.lockNodeSignal = options.lockNodeSignal;
        this.reloadAllNodesSignal = options.reloadAllNodesSignal;
        this.toggleAllLinkAnimationSignal = options.toggleAllLinkAnimationSignal;
        this.xircuitsApp = new _components_XircuitsApp__WEBPACK_IMPORTED_MODULE_2__.XircuitsApplication(this.app, this.shell);
    }
    handleEvent(event) {
        if (event instanceof MouseEvent && event.type === 'mouseup') {
            // Update mousePosition state with current mouse position
            this.mousePosition = { x: event.clientX, y: event.clientY };
            this.node.focus();
            this.node.addEventListener('blur', this, true);
        }
        else if (event.type === 'blur') {
            const deactivate = x => x.setSelected(false);
            const model = this.xircuitsApp.getDiagramEngine().getModel();
            model.getNodes().forEach(deactivate);
            model.getLinks().forEach(deactivate);
        }
        else if (event.type === 'contextmenu') {
            this.node.removeEventListener('blur', this, true);
        }
    }
    onAfterAttach(msg) {
        this.node.addEventListener('mouseup', this, true);
        this.node.addEventListener('blur', this, true);
        this.node.addEventListener('contextmenu', this, true);
    }
    onBeforeDetach() {
        this.node.removeEventListener('mouseup', this, true);
        this.node.removeEventListener('blur', this, true);
        this.node.removeEventListener('contextmenu', this, true);
    }
    render() {
        var _a;
        return (react__WEBPACK_IMPORTED_MODULE_1___default().createElement(_components_xircuitBodyWidget__WEBPACK_IMPORTED_MODULE_3__.BodyWidget, { context: this.context, xircuitsApp: this.xircuitsApp, app: this.app, shell: this.shell, commands: this.commands, widgetId: (_a = this.parent) === null || _a === void 0 ? void 0 : _a.id, serviceManager: this.serviceManager, fetchComponentsSignal: this.fetchComponentsSignal, saveXircuitSignal: this.saveXircuitSignal, compileXircuitSignal: this.compileXircuitSignal, runXircuitSignal: this.runXircuitSignal, runTypeXircuitSignal: this.runTypeXircuitSignal, lockNodeSignal: this.lockNodeSignal, reloadAllNodesSignal: this.reloadAllNodesSignal, toggleAllLinkAnimationSignal: this.toggleAllLinkAnimationSignal }));
    }
}


/***/ }),

/***/ "./node_modules/rc-dialog/assets/bootstrap.css":
/*!*****************************************************!*\
  !*** ./node_modules/rc-dialog/assets/bootstrap.css ***!
  \*****************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! !../../style-loader/dist/runtime/injectStylesIntoStyleTag.js */ "./node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js");
/* harmony import */ var _style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_cjs_js_bootstrap_css__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! !!../../css-loader/dist/cjs.js!./bootstrap.css */ "./node_modules/css-loader/dist/cjs.js!./node_modules/rc-dialog/assets/bootstrap.css");

            

var options = {};

options.insert = "head";
options.singleton = false;

var update = _style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0___default()(_css_loader_dist_cjs_js_bootstrap_css__WEBPACK_IMPORTED_MODULE_1__["default"], options);



/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (_css_loader_dist_cjs_js_bootstrap_css__WEBPACK_IMPORTED_MODULE_1__["default"].locals || {});

/***/ })

}]);
//# sourceMappingURL=lib_index_js.bf70fbd402c2c10c1b4a.js.map