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

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

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   XircuitsFactory: () => (/* binding */ XircuitsFactory)
/* 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 _XircuitsWidget__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./XircuitsWidget */ "./lib/XircuitsWidget.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 _log_LogPlugin__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./log/LogPlugin */ "./lib/log/LogPlugin.js");
/* harmony import */ var _components_runner_RunSwitcher__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./components/runner/RunSwitcher */ "./lib/components/runner/RunSwitcher.js");
/* harmony import */ var _ui_components_icons__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./ui-components/icons */ "./lib/ui-components/icons.js");
/* harmony import */ var _commands_CommandIDs__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./commands/CommandIDs */ "./lib/commands/CommandIDs.js");
/* harmony import */ var _siteUtils__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./siteUtils */ "./lib/siteUtils.js");









const XIRCUITS_CLASS = 'xircuits-editor';

class XircuitsFactory 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.fetchRemoteRunConfigSignal = 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.triggerLoadingAnimationSignal = 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);
        this.refreshComponentsSignal = new _lumino_signaling__WEBPACK_IMPORTED_MODULE_1__.Signal(this);
        this.toggleDisplayNodesInLibrary = 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,
            fetchRemoteRunConfigSignal: this.fetchRemoteRunConfigSignal,
            saveXircuitSignal: this.saveXircuitSignal,
            compileXircuitSignal: this.compileXircuitSignal,
            runXircuitSignal: this.runXircuitSignal,
            runTypeXircuitSignal: this.runTypeXircuitSignal,
            lockNodeSignal: this.lockNodeSignal,
            triggerLoadingAnimationSignal: this.triggerLoadingAnimationSignal,
            reloadAllNodesSignal: this.reloadAllNodesSignal,
            toggleAllLinkAnimationSignal: this.toggleAllLinkAnimationSignal,
            refreshComponentsSignal: this.refreshComponentsSignal,
            toggleDisplayNodesInLibrary: this.toggleDisplayNodesInLibrary
        };
        const content = new _XircuitsWidget__WEBPACK_IMPORTED_MODULE_4__.XircuitsPanel(props);
        const widget = new _jupyterlab_docregistry__WEBPACK_IMPORTED_MODULE_0__.DocumentWidget({ content, context });
        widget.addClass(XIRCUITS_CLASS);
        widget.title.icon = _ui_components_icons__WEBPACK_IMPORTED_MODULE_5__.xircuitsIcon;
        const CommandButton = (commandId, icon, tooltip) => new _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_3__.ToolbarButton({
            icon, tooltip,
            onClick: () => {
                this.commands.execute(commandId);
            }
        });
        let saveButton = CommandButton(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_6__.commandIDs.saveXircuit, _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_2__.saveIcon, 'Save (Ctrl+S)');
        let undoButton = CommandButton(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_6__.commandIDs.undo, _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_2__.undoIcon, 'Undo (Ctrl+Z)');
        let redoButton = CommandButton(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_6__.commandIDs.redo, _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_2__.redoIcon, 'Redo (Ctrl+Y)');
        let reloadButton = CommandButton(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_6__.commandIDs.reloadDocManager, _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_2__.refreshIcon, 'Reload Xircuits from Disk');
        let cutButton = CommandButton(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_6__.commandIDs.cutNode, _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_2__.cutIcon, 'Cut selected nodes');
        let copyButton = CommandButton(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_6__.commandIDs.copyNode, _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_2__.copyIcon, 'Copy selected nodes');
        let pasteButton = CommandButton(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_6__.commandIDs.pasteNode, _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_2__.pasteIcon, 'Paste nodes from the clipboard');
        let lockButton = CommandButton(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_6__.commandIDs.lockXircuit, _ui_components_icons__WEBPACK_IMPORTED_MODULE_5__.lockIcon, "Lock all non-general nodes connected from start node");
        let logButton = CommandButton(_log_LogPlugin__WEBPACK_IMPORTED_MODULE_7__.LoggerCommandIDs.openLog, _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_2__.listIcon, 'Open log');
        let reloadAllNodesButton = CommandButton(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_6__.commandIDs.reloadAllNodes, _ui_components_icons__WEBPACK_IMPORTED_MODULE_5__.reloadAllIcon, 'Reload all nodes');
        let toggleAllLinkAnimationButton = CommandButton(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_6__.commandIDs.toggleAllLinkAnimation, _ui_components_icons__WEBPACK_IMPORTED_MODULE_5__.toggleAnimationIcon, 'Toggle low power mode by disabling link animation');
        let compileButton = CommandButton(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_6__.commandIDs.compileXircuit, _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_2__.checkIcon, 'Compile Xircuits');
        let compileAndRunButton = CommandButton(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_6__.commandIDs.runXircuit, _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_2__.runIcon, 'Compile and Run Xircuits');
        // TODO: Create a CommandButton as well
        /**
     * Create an HPC monitoring button toolbar item.
     */
        let monitoringButton = new _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_3__.ToolbarButton({
            label: 'Monitor HPC',
            tooltip: 'Monitor your HPC jobs with tvb-ext-unicore',
            onClick: () => {
                this.commands.execute(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_6__.commandIDs.openTvbExtUnicore, {
                    defaultSite: (0,_siteUtils__WEBPACK_IMPORTED_MODULE_8__.readDefaultSite)()
                });
            }
        });
        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_runner_RunSwitcher__WEBPACK_IMPORTED_MODULE_9__.RunSwitcher(this));
        widget.toolbar.insertItem(14, 'xircuits-add-monitor', monitoringButton);
        return widget;
    }
}


/***/ }),

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

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   XircuitsPanel: () => (/* binding */ XircuitsPanel)
/* 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_XircuitsBodyWidget__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./components/XircuitsBodyWidget */ "./lib/components/XircuitsBodyWidget.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_3__ = __webpack_require__(/*! ./components/XircuitsApp */ "./lib/components/XircuitsApp.js");
/* harmony import */ var _server_handler__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./server/handler */ "./lib/server/handler.js");
/* harmony import */ var _components_node_CustomNodeModel__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./components/node/CustomNodeModel */ "./lib/components/node/CustomNodeModel.js");
/* 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__);







/**
 * DocumentWidget: widget that represents the view or editor for a file type.
 */
class XircuitsPanel extends _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_0__.ReactWidget {
    constructor(options) {
        super();
        // 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.fetchRemoteRunConfigSignal = options.fetchRemoteRunConfigSignal;
        this.saveXircuitSignal = options.saveXircuitSignal;
        this.compileXircuitSignal = options.compileXircuitSignal;
        this.runXircuitSignal = options.runXircuitSignal;
        this.runTypeXircuitSignal = options.runTypeXircuitSignal;
        this.lockNodeSignal = options.lockNodeSignal;
        this.triggerLoadingAnimationSignal = options.triggerLoadingAnimationSignal;
        this.reloadAllNodesSignal = options.reloadAllNodesSignal;
        this.toggleAllLinkAnimationSignal = options.toggleAllLinkAnimationSignal;
        this.xircuitsApp = new _components_XircuitsApp__WEBPACK_IMPORTED_MODULE_3__.XircuitsApplication(this.app, this.shell, () => { var _a; return (_a = this.parent) === null || _a === void 0 ? void 0 : _a.id; });
    }
    handleEvent(event) {
        if (event instanceof MouseEvent && event.type === 'mouseup') {
            // force focus on the editor in order stop key event propagation (e.g. "Delete" key) into unintended
            // parts of jupyter lab.
            this.node.focus();
            // Just to enable back the loses focus event
            this.node.addEventListener('blur', this, true);
        }
        else if (event.type === 'blur') {
            // Unselect any selected nodes when the editor loses focus
            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') {
            // Disable loses focus event when opening context menu
            this.node.removeEventListener('blur', this, true);
        }
        else if (event.type === 'focus') {
            this.focusHandler();
        }
    }
    onAfterAttach(msg) {
        this.node.addEventListener('focus', this, true);
        this.node.addEventListener('mouseup', this, true);
        this.node.addEventListener('blur', this, true);
        this.node.addEventListener('contextmenu', this, true);
    }
    onBeforeDetach() {
        this.node.removeEventListener('focus', this, true);
        this.node.removeEventListener('mouseup', this, true);
        this.node.removeEventListener('blur', this, true);
        this.node.removeEventListener('contextmenu', this, true);
    }
    getDiagramModel() {
        return this.xircuitsApp.getDiagramEngine().getModel();
    }
    async focusHandler() {
        const modelDiagram = this.xircuitsApp.getDiagramEngine().getModel();
        const dataToSend = { 'xircuits_id': modelDiagram.getOptions().id };
        const response = await (0,_server_handler__WEBPACK_IMPORTED_MODULE_4__.requestAPI)('components_edit/', {
            body: JSON.stringify(dataToSend),
            method: 'POST'
        });
        if (!response['models_exist']) {
            return;
        }
        Object.values(response['models']).map((modelConfig, idx) => {
            const tvbModelNode = modelDiagram.getNode(modelConfig['id']);
            this.updateModelComponentParameters(tvbModelNode, modelConfig['params']);
        });
    }
    updateModelComponentParameters(modelNode, modelParams) {
        const position_x = modelNode.getX() - 150;
        const position_y = modelNode.getY();
        let position_y_offset = -50;
        Object.values(modelParams).map(param => {
            const param_type = param['type'];
            const param_name = param['name'];
            const ports = modelNode.getPorts();
            for (const port_name in ports) {
                const targetPort = ports[port_name];
                // @ts-ignore
                if (targetPort.getOptions().label === param_name) {
                    this.removeLiteralNodesForPort(targetPort);
                    position_y_offset += 50;
                    const sourcePort = this.createLiteralNodeForParam(param_type, param['value'].toString(), position_x, position_y + position_y_offset);
                    this.addNewLink(sourcePort, targetPort);
                    break;
                }
            }
        });
    }
    removeLiteralNodesForPort(targetPort) {
        const diagramModel = this.getDiagramModel();
        const targetPortLinks = targetPort.getLinks();
        if (targetPortLinks) {
            Object.values(targetPortLinks).map(link => {
                const sourceNode = link.getSourcePort().getParent();
                sourceNode.getPorts()['out-0'].removeLink(link);
                diagramModel.removeLink(link);
                diagramModel.removeNode(sourceNode);
            });
        }
    }
    createLiteralNodeForParam(type, value, position_x, position_y) {
        const out_port_name = 'out-0';
        const node = new _components_node_CustomNodeModel__WEBPACK_IMPORTED_MODULE_5__.CustomNodeModel({
            name: 'Literal ' + type.charAt(0).toUpperCase() + type.slice(1),
            color: 'green',
            extras: { type: type }
        });
        node.addOutPortEnhance({ label: value, name: out_port_name });
        node.setPosition(position_x, position_y);
        this.getDiagramModel().addNode(node);
        return node.getPorts()[out_port_name];
    }
    addNewLink(source, target) {
        const newLink = new _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_2__.DefaultLinkModel();
        newLink.setSourcePort(source);
        newLink.setTargetPort(target);
        this.getDiagramModel().addLink(newLink);
    }
    render() {
        var _a;
        return (react__WEBPACK_IMPORTED_MODULE_1___default().createElement(_components_XircuitsBodyWidget__WEBPACK_IMPORTED_MODULE_6__.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, fetchRemoteRunConfigSignal: this.fetchRemoteRunConfigSignal, saveXircuitSignal: this.saveXircuitSignal, compileXircuitSignal: this.compileXircuitSignal, runXircuitSignal: this.runXircuitSignal, runTypeXircuitSignal: this.runTypeXircuitSignal, lockNodeSignal: this.lockNodeSignal, triggerLoadingAnimationSignal: this.triggerLoadingAnimationSignal, reloadAllNodesSignal: this.reloadAllNodesSignal, toggleAllLinkAnimationSignal: this.toggleAllLinkAnimationSignal }));
    }
}


/***/ }),

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

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   commandIDs: () => (/* binding */ commandIDs)
/* harmony export */ });
const commandIDs = {
    openDocManager: "docmanager:open",
    newDocManager: "docmanager:new-untitled",
    saveDocManager: "docmanager:save",
    reloadDocManager: "docmanager:reload",
    createNewXircuit: "Xircuit-editor:create-new",
    copyXircuitsToRoot: "Xircuit-editor:copy-to-root",
    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",
    openXircuitsWorkflow: "Xircuit-editor:open-xircuits-workflow",
    undo: "Xircuit-editor:undo",
    redo: "Xircuit-editor:redo",
    cutNode: "Xircuit-editor:cut-node",
    copyNode: "Xircuit-editor:copy-node",
    pasteNode: "Xircuit-editor:paste-node",
    attachNode: "Xircuit-editor:attach-node",
    attachAllNodes: "Xircuit-editor:attach-all-nodes",
    detachAllNodes: "Xircuit-editor:detach-all-nodes",
    triggerLoadingAnimation: "Xircuit-editor:trigger-loading-animation",
    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",
    createNewComponentLibrary: "Xircuit-editor:new-component-library",
    refreshComponentList: "xircuits-sidebar:refresh-component-list",
    toggleDisplayNodesInLibrary: "xircuits-sidebar:toggle-display-nodes-in-library",
    helpOpenResource: "xircuits-help:open-resource",
    openXircuitsConfiguration: "xircuits-config:open-config",
    fetchRemoteRunConfig: "xircuits-config:fetch-remote-config",
    openTvbExtUnicore: 'tvb_ext_unicore:open',
    openViewer: 'Xircuit-editor:open-node-viewer'
};


/***/ }),

/***/ "./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 */ "./node_modules/@projectstorm/react-canvas-core/dist/index.js");
/* harmony import */ var _CommandIDs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./CommandIDs */ "./lib/commands/CommandIDs.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;
                // @ts-ignore
                if (app.shell._tracker._activeWidget && options.getWidgetId() === app.shell._tracker._activeWidget.id) {
                    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);
                        }
                    };
                    executeIf(ctrlKey && keyCode === 'z', _CommandIDs__WEBPACK_IMPORTED_MODULE_1__.commandIDs.undo);
                    executeIf(ctrlKey && keyCode === 'y', _CommandIDs__WEBPACK_IMPORTED_MODULE_1__.commandIDs.redo);
                    executeIf(ctrlKey && keyCode === 's', _CommandIDs__WEBPACK_IMPORTED_MODULE_1__.commandIDs.saveXircuit);
                    executeIf(ctrlKey && keyCode === 'x', _CommandIDs__WEBPACK_IMPORTED_MODULE_1__.commandIDs.cutNode);
                    executeIf(ctrlKey && keyCode === 'c', _CommandIDs__WEBPACK_IMPORTED_MODULE_1__.commandIDs.copyNode);
                    executeIf(ctrlKey && keyCode === 'v', _CommandIDs__WEBPACK_IMPORTED_MODULE_1__.commandIDs.pasteNode);
                    executeIf(keyCode == 'Delete' || keyCode == 'Backspace', _CommandIDs__WEBPACK_IMPORTED_MODULE_1__.commandIDs.deleteEntity);
                }
            }
        });
    }
}


/***/ }),

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

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   addLibraryActionCommands: () => (/* binding */ addLibraryActionCommands)
/* harmony export */ });
/* harmony import */ var _dialog_FormDialog__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../dialog/FormDialog */ "./lib/dialog/FormDialog.js");
/* harmony import */ var _tray_library_GeneralComponentLib__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../tray_library/GeneralComponentLib */ "./lib/tray_library/GeneralComponentLib.js");
/* harmony import */ var _tray_library_ComponentLibraryConfig__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../tray_library/ComponentLibraryConfig */ "./lib/tray_library/ComponentLibraryConfig.js");
/* harmony import */ var _dialog_NewLibraryDialog__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../dialog/NewLibraryDialog */ "./lib/dialog/NewLibraryDialog.js");
/* harmony import */ var _server_handler__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../server/handler */ "./lib/server/handler.js");
/* harmony import */ var _helpers_InputSanitizer__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../helpers/InputSanitizer */ "./lib/helpers/InputSanitizer.js");
/* harmony import */ var _CommandIDs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./CommandIDs */ "./lib/commands/CommandIDs.js");
/* 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__);








/**
 * Add the commands for node actions.
 */
function addLibraryActionCommands(app, tracker, translator, factory) {
    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);
    }
    commands.addCommand(_CommandIDs__WEBPACK_IMPORTED_MODULE_1__.commandIDs.refreshComponentList, {
        label: "Refresh Component Library",
        icon: _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_0__.refreshIcon,
        execute: async (args) => {
            factory.refreshComponentsSignal.emit(args);
        }
    });
    commands.addCommand(_CommandIDs__WEBPACK_IMPORTED_MODULE_1__.commandIDs.toggleDisplayNodesInLibrary, {
        label: "Toggle Display Nodes in Library",
        icon: _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_0__.listIcon,
        execute: async (args) => {
            factory.toggleDisplayNodesInLibrary.emit(args);
        }
    });
    commands.addCommand(_CommandIDs__WEBPACK_IMPORTED_MODULE_1__.commandIDs.createNewComponentLibrary, {
        label: "Create New Component",
        icon: _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_0__.addIcon,
        execute: async (args) => {
            let componentCode = args['componentCode'];
            let libraries = await (0,_tray_library_ComponentLibraryConfig__WEBPACK_IMPORTED_MODULE_2__.ComponentLibraryConfig)();
            let inputValue = "";
            let dialogResult;
            let type = "libraryname";
            do {
                let dialogOptions = (0,_dialog_NewLibraryDialog__WEBPACK_IMPORTED_MODULE_3__.newLibraryInputDialog)({
                    title: 'Create New Component',
                    oldValue: inputValue,
                    libraries: libraries,
                    oldComponentCode: componentCode
                });
                dialogResult = await (0,_dialog_FormDialog__WEBPACK_IMPORTED_MODULE_4__.showFormDialog)(dialogOptions);
                if ((0,_tray_library_GeneralComponentLib__WEBPACK_IMPORTED_MODULE_5__.cancelDialog)(dialogResult))
                    return;
                componentCode = dialogResult.value['component-code'];
                if (dialogResult.value['library-select'] === 'custom-option') {
                    inputValue = dialogResult.value['customLibrary']; // For custom library name
                }
                else {
                    inputValue = dialogResult.value['library-select']; // For selected predefined library
                }
            } while (!(0,_helpers_InputSanitizer__WEBPACK_IMPORTED_MODULE_6__.checkInput)(inputValue, type));
            const dataToSend = { "libraryName": inputValue, "componentCode": componentCode };
            try {
                const server_reply = await (0,_server_handler__WEBPACK_IMPORTED_MODULE_7__.requestAPI)('library/new', {
                    body: JSON.stringify(dataToSend),
                    method: 'POST',
                });
                await app.commands.execute(_CommandIDs__WEBPACK_IMPORTED_MODULE_1__.commandIDs.refreshComponentList);
                return server_reply;
            }
            catch (reason) {
                console.error(`Error on POST library/new ${dataToSend}.\n${reason}`);
            }
        }
    });
}


/***/ }),

/***/ "./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 _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_node_CustomNodeModel__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../components/node/CustomNodeModel */ "./lib/components/node/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_9__ = __webpack_require__(/*! ../tray_library/AdvanceComponentLib */ "./lib/tray_library/AdvanceComponentLib.js");
/* harmony import */ var _dialog_formDialogwidget__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../dialog/formDialogwidget */ "./lib/dialog/formDialogwidget.js");
/* harmony import */ var _dialog_CommentDialog__WEBPACK_IMPORTED_MODULE_12__ = __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_13__ = __webpack_require__(/*! ../dialog/FormDialog */ "./lib/dialog/FormDialog.js");
/* harmony import */ var _components_link_CustomLinkModel__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../components/link/CustomLinkModel */ "./lib/components/link/CustomLinkModel.js");
/* harmony import */ var _projectstorm_geometry__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @projectstorm/geometry */ "webpack/sharing/consume/default/@projectstorm/geometry/@projectstorm/geometry?2db1");
/* 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_16__ = __webpack_require__(/*! ../tray_library/GeneralComponentLib */ "./lib/tray_library/GeneralComponentLib.js");
/* harmony import */ var _components_port_CustomDynaPortModel__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../components/port/CustomDynaPortModel */ "./lib/components/port/CustomDynaPortModel.js");
/* harmony import */ var _tray_library_Component__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../tray_library/Component */ "./lib/tray_library/Component.js");
/* harmony import */ var _tray_library_BaseComponentLib__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../tray_library/BaseComponentLib */ "./lib/tray_library/BaseComponentLib.js");
/* harmony import */ var _CommandIDs__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./CommandIDs */ "./lib/commands/CommandIDs.js");
/* harmony import */ var _server_handler__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../server/handler */ "./lib/server/handler.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;
    }
    function gatherNodeInPortValues(node) {
        const nodePorts = node.getInPorts();
        const model_params_dict = {};
        Object.values(nodePorts).map(port => {
            // @ts-ignore
            const targetPortLinks = port.getLinks();
            if (targetPortLinks) {
                Object.values(targetPortLinks).map(link => {
                    // @ts-ignore
                    const sourceNode = link.getSourcePort().getParent();
                    if (sourceNode.name.includes('Literal')) {
                        const model_param = sourceNode.getOutPorts()[0].getOptions();
                        // @ts-ignore
                        const label = port.getOptions().label[0] === "★" ? port.getOptions().label.slice(1) : port.getOptions().label;
                        model_params_dict[label] = model_param.label;
                    }
                });
            }
        });
        return model_params_dict;
    }
    //Add command to open node's viewer in notebook
    commands.addCommand(_CommandIDs__WEBPACK_IMPORTED_MODULE_5__.commandIDs.openViewer, {
        execute: async (args) => {
            const node = getLastSelectedNode();
            if (node.extras["has_widget"] === false) {
                (0,_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_1__.showDialog)({
                    title: `${node.name} does not have a widget assigned!`,
                    buttons: [_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_1__.Dialog.warnButton({ label: 'OK' })]
                });
                return;
            }
            const dataToSend = {
                'component': node.name,
                'component_id': node.options.id,
                'component_inputs': gatherNodeInPortValues(node),
                'path': node.extras.path,
                'xircuits_id': node.parent.parent.options.id
            };
            const response = await (0,_server_handler__WEBPACK_IMPORTED_MODULE_6__.requestAPI)('components/', {
                body: JSON.stringify(dataToSend),
                method: 'POST',
            });
            // Open node's file name
            await app.commands.execute(_CommandIDs__WEBPACK_IMPORTED_MODULE_5__.commandIDs.openDocManager, {
                path: response['widget'],
                factory: 'Notebook',
                kernel: { name: 'python3' },
                options: { mode: 'split-right' }
            });
        }
    });
    //Add command to open node's script at specific line
    commands.addCommand(_CommandIDs__WEBPACK_IMPORTED_MODULE_5__.commandIDs.openScript, {
        execute: async (args) => {
            var _a, _b, _c;
            let node, nodePath, nodeName, nodeLineNo;
            // call getLastSelectedNode() if opened from Xircuits canvas
            if (args['nodePath'] === undefined && args['nodeName'] === undefined && args['nodeLineNo'] === undefined) {
                node = getLastSelectedNode();
            }
            // Assign values based on whether args were provided or derived from getLastSelectedNode()
            nodePath = (_a = args['nodePath']) !== null && _a !== void 0 ? _a : node === null || node === void 0 ? void 0 : node.extras.path;
            nodeName = (_b = args['nodeName']) !== null && _b !== void 0 ? _b : node === null || node === void 0 ? void 0 : node.name;
            nodeLineNo = (_c = args['nodeLineNo']) !== null && _c !== void 0 ? _c : node === null || node === void 0 ? void 0 : 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(_CommandIDs__WEBPACK_IMPORTED_MODULE_5__.commandIDs.openDocManager, { path: nodePath });
            await newWidget.context.ready;
            // Go to end of node's line first before go to its class
            await app.commands.execute('fileeditor:go-to-line', { line: nodeLineNo[0].end_lineno });
            await new Promise(resolve => setTimeout(resolve, 10));
            // Then go to the specific line
            await app.commands.execute('fileeditor:go-to-line', { line: nodeLineNo[0].lineno });
        }
    });
    //Add command to open sub xircuits
    commands.addCommand(_CommandIDs__WEBPACK_IMPORTED_MODULE_5__.commandIDs.openXircuitsWorkflow, {
        execute: async (args) => {
            var _a;
            let node, nodePath;
            // call getLastSelectedNode() if opened from Xircuits canvas
            if (args['nodePath'] === undefined && args['nodeName'] === undefined && args['nodeLineNo'] === undefined) {
                node = getLastSelectedNode();
            }
            // Assign values based on whether args were provided or derived from getLastSelectedNode()
            nodePath = (_a = args['nodePath']) !== null && _a !== void 0 ? _a : node === null || node === void 0 ? void 0 : node.extras.path;
            let xircuitsPath = nodePath.replace(/\.py$/, '.xircuits');
            try {
                await app.commands.execute('docmanager:open', { path: xircuitsPath });
            }
            catch (error) {
                alert('Failed to Open Xircuits Workflow: ' + error);
            }
        }
    });
    //Add command to undo
    commands.addCommand(_CommandIDs__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(_CommandIDs__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(_CommandIDs__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(_CommandIDs__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(_CommandIDs__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(_CommandIDs__WEBPACK_IMPORTED_MODULE_5__.commandIDs.editNode, {
        execute: editParameter,
        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(_CommandIDs__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(_CommandIDs__WEBPACK_IMPORTED_MODULE_5__.commandIDs.reloadNode, {
        execute: async () => {
            var _a;
            await (0,_tray_library_Component__WEBPACK_IMPORTED_MODULE_7__.fetchComponents)();
            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 == "Start") {
                    console.info(selected_node.name + " cannot be reloaded.");
                    continue;
                }
                let node;
                if (selected_node.name == "Finish") {
                    node = (0,_tray_library_BaseComponentLib__WEBPACK_IMPORTED_MODULE_8__.BaseComponentLibrary)('Finish');
                }
                else {
                    // For other nodes, fetch from AdvancedComponentLibrary
                    try {
                        let current_node = await (0,_tray_library_AdvanceComponentLib__WEBPACK_IMPORTED_MODULE_9__.fetchNodeByName)(selected_node.name);
                        node = (0,_tray_library_AdvanceComponentLib__WEBPACK_IMPORTED_MODULE_9__.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_10__.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(_CommandIDs__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(_CommandIDs__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(_CommandIDs__WEBPACK_IMPORTED_MODULE_5__.commandIDs.connectLinkToObviousPorts, { droppedSourceLink: sourceLink, targetNode });
            }
            newLink.setSourcePort(sourcePort);
            newLink.setTargetPort(targetPort);
            if (targetPort instanceof _components_port_CustomDynaPortModel__WEBPACK_IMPORTED_MODULE_10__.CustomDynaPortModel) {
                const newPort = targetPort.spawnDynamicPort({ offset: 1 });
                newPort.previous = targetPort.getID();
                targetPort.next = newPort.getID();
                widget.xircuitsApp.getDiagramEngine().getModel().addNode(targetPort.getParent());
            }
            widget.xircuitsApp.getDiagramEngine().getModel().addLink(newLink);
            widget.xircuitsApp.getDiagramEngine().repaintCanvas();
        },
        label: trans.__('Link node')
    });
    //Add command to connect link to obvious port given link and target node
    commands.addCommand(_CommandIDs__WEBPACK_IMPORTED_MODULE_5__.commandIDs.connectLinkToObviousPorts, {
        execute: (args) => {
            var _a, _b, _c;
            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;
            }
            // Helper function to parse Union types
            const parseUnionType = (type) => {
                const unionMatch = type.match(/^Union\[(.*)\]$/);
                if (unionMatch) {
                    return unionMatch[1].split(/[\|,]/).map(t => t.trim());
                }
                return [type];
            };
            for (let outPortIndex in outPorts) {
                const outPort = outPorts[outPortIndex];
                const outPortName = outPort.getOptions()['name'];
                const outPortLabel = outPort.getOptions()['label'];
                const outPortType = outPort.getOptions()['dataType'];
                const outPortLabelArr = outPortLabel.split('_');
                const outPortTypes = parseUnionType(outPortType);
                if (outPort.getOptions()['label'] == '▶') {
                    // Skip ▶ outPort
                    continue;
                }
                // Check if there are existing links from the target port
                if (Object.keys(outPort.getLinks()).length > 0) {
                    continue;
                }
                for (let inPortIndex in inPorts) {
                    const inPort = inPorts[inPortIndex];
                    const inPortName = inPort.getOptions()['name'];
                    // handler for compulsory [★] ports
                    const inPortLabel = inPort.getOptions()['label'].replace(/★/g, '');
                    const inPortType = (_c = inPort.getOptions()['dataType']) !== null && _c !== void 0 ? _c : '';
                    const inPortLabelArr = inPortLabel.split('_');
                    const inPortTypes = parseUnionType(inPortType);
                    // Compare if there is similarity for each word
                    const intersection = outPortLabelArr.filter(element => inPortLabelArr.includes(element));
                    // Check if there are existing links from the source port
                    if (Object.keys(inPort.getLinks()).length > 0) {
                        continue;
                    }
                    // Check datatype compatibility
                    const typesCompatible = outPortTypes.some(outType => inPortTypes.includes(outType) || inPortTypes.includes('any'));
                    if (!typesCompatible) {
                        continue;
                    }
                    // Check label compatibility or intersection
                    if ((outPortLabel === inPortLabel && typesCompatible) || intersection.length >= 1) {
                        const newLink = new _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_0__.DefaultLinkModel();
                        const sourcePort = sourceNode.getPorts()[outPortName];
                        newLink.setSourcePort(sourcePort);
                        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(_CommandIDs__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_11__.formDialogWidget)(react__WEBPACK_IMPORTED_MODULE_3___default().createElement(_dialog_CommentDialog__WEBPACK_IMPORTED_MODULE_12__.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_13__.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_node_CustomNodeModel__WEBPACK_IMPORTED_MODULE_14__.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 selectAllRelevantNodes(widget) {
        widget.xircuitsApp.getDiagramEngine().getModel().getSelectedEntities().forEach(entity => {
            if (entity.getType() === 'custom-node') {
                const node = entity;
                // Find links to attached node and copy them too
                Object.values(node.getPorts()).forEach(port => {
                    Object.values(port.getLinks()).forEach(link => {
                        var _a, _b;
                        const parentNode = link.getSourcePort().getParent();
                        if ((_b = (_a = parentNode.getOptions()) === null || _a === void 0 ? void 0 : _a.extras) === null || _b === void 0 ? void 0 : _b.attached) {
                            parentNode.setSelected(true);
                            link.setSelected(true);
                        }
                    });
                });
            }
        });
        return widget.xircuitsApp.getDiagramEngine().getModel().getSelectedEntities();
    }
    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 = selectAllRelevantNodes(widget);
        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 = selectAllRelevantNodes(widget).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_15__.ParameterLinkModel(serializedLink);
        else if (serializedLink.type === 'triangle-link')
            return new _components_link_CustomLinkModel__WEBPACK_IMPORTED_MODULE_15__.TriangleLinkModel(serializedLink);
    }
    async function editParameter() {
        var _a;
        const widget = (_a = tracker.currentWidget) === null || _a === void 0 ? void 0 : _a.content;
        if (widget) {
            const selected_node = getLastSelectedNode();
            const nodeName = selected_node.getOptions()["name"];
            let updatedNode = null;
            if (nodeName.startsWith("Literal ")) {
                updatedNode = await editLiteral(widget, selected_node);
            }
            else if (nodeName.startsWith("Argument ")) {
                updatedNode = await editArgument(widget, selected_node);
            }
            else {
                (0,_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_1__.showDialog)({
                    title: 'Only Literal or Argument Node can be edited',
                    buttons: [_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_1__.Dialog.warnButton({ label: 'OK' })]
                });
                return;
            }
            if (updatedNode) {
                // Set new node to old node position
                let position = selected_node.getPosition();
                updatedNode.setPosition(position);
                widget.xircuitsApp.getDiagramEngine().getModel().addNode(updatedNode);
                // Update the links
                const links = widget.xircuitsApp.getDiagramEngine().getModel()["layers"][0]["models"];
                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();
                        // a parameter node will have only 1 outPort
                        let sourcePort = Object.values(updatedNode.getPorts())[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();
            }
        }
    }
    async function editLiteral(widget, selected_node) {
        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 null;
        }
        const connections = Object.values(selected_node.ports)
            .map((p) => Object.keys(p.links).length)
            .reduce((a, b) => a + b);
        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 nodeData = { color: selected_node["color"], type: selected_node["extras"]["type"], extras: { attached: selected_node["extras"]["attached"] } };
        let updatedContent = await (0,_tray_library_GeneralComponentLib__WEBPACK_IMPORTED_MODULE_16__.handleLiteralInput)(selected_node["name"], nodeData, oldValue, literalType, updateTitle, connections);
        if (!updatedContent) {
            // handle case where Cancel was clicked or an error occurred
            return null;
        }
        return updatedContent;
    }
    async function editArgument(widget, selected_node) {
        if (!selected_node.getOptions()["name"].startsWith("Argument ")) {
            (0,_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_1__.showDialog)({
                title: 'Only Argument Node can be edited',
                buttons: [_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_1__.Dialog.warnButton({ label: 'OK' })]
            });
            return null;
        }
        // Expected Format: Argument (datatype): ArgumentVarName
        let oldValue = selected_node.name.split(':')[1].trim();
        ;
        const updateTitle = `Update Argument`;
        let nodeData = { color: selected_node["color"], type: selected_node["extras"]["type"] };
        let updatedContent = await (0,_tray_library_GeneralComponentLib__WEBPACK_IMPORTED_MODULE_16__.handleArgumentInput)(nodeData, updateTitle, oldValue);
        if (!updatedContent) {
            // handle case where Cancel was clicked or an error occurred
            return null;
        }
        return updatedContent;
    }
    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_node_CustomNodeModel__WEBPACK_IMPORTED_MODULE_14__.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_10__.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_10__.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();
        }
    }
    // Add command to attach selected node
    commands.addCommand(_CommandIDs__WEBPACK_IMPORTED_MODULE_5__.commandIDs.attachNode, {
        execute: async () => {
            var _a;
            const widget = (_a = tracker.currentWidget) === null || _a === void 0 ? void 0 : _a.content;
            const model = widget.xircuitsApp.getDiagramEngine().getModel();
            const selected_entities = model.getSelectedEntities();
            const connected_literals = selected_entities.filter((entity) => {
                return entity instanceof _components_node_CustomNodeModel__WEBPACK_IMPORTED_MODULE_14__.CustomNodeModel &&
                    entity.getOptions().name.startsWith("Literal ") &&
                    Object.keys(entity.getOutPorts()[0].getLinks()).length > 0;
            });
            connected_literals.forEach(node => {
                node.setSelected(false);
                node.getOptions().extras.attached = true;
                let parameterOutPort = node.getOutPorts()[0];
                let connectedNodes = parameterOutPort.getTargetNodes();
                connectedNodes.forEach((node) => node.setSelected(true));
            });
            widget.xircuitsApp.getDiagramEngine().repaintCanvas();
        },
        label: trans.__('attach node')
    });
    // Add command to attach all parameter nodes
    commands.addCommand(_CommandIDs__WEBPACK_IMPORTED_MODULE_5__.commandIDs.attachAllNodes, {
        execute: async () => {
            var _a;
            const widget = (_a = tracker.currentWidget) === null || _a === void 0 ? void 0 : _a.content;
            const model = widget.xircuitsApp.getDiagramEngine().getModel();
            const selected_entities = model.getSelectedEntities();
            const literal_nodes = [];
            const selected_nodes = selected_entities.filter(entity => entity instanceof _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_0__.NodeModel);
            selected_nodes.forEach(node => {
                node.setSelected(false);
                let inPorts = node.getInPorts();
                Object.values(inPorts).forEach((port) => {
                    let sourceNode = port.getSourceNodes()[0];
                    if (sourceNode && sourceNode['name'].startsWith('Literal ') && !sourceNode['extras']['attached']) {
                        sourceNode.getOptions().extras.attached = true;
                        sourceNode.setSelected(true);
                        literal_nodes.push(sourceNode);
                    }
                });
            });
            literal_nodes.forEach(node => {
                let parameterOutPort = node.getOutPorts()[0];
                let connectedNodes = parameterOutPort.getTargetNodes();
                connectedNodes.forEach((node) => node.setSelected(true));
            });
            widget.xircuitsApp.getDiagramEngine().repaintCanvas();
        },
        label: trans.__('attach all nodes')
    });
    // Add command to detach all parameter nodes
    commands.addCommand(_CommandIDs__WEBPACK_IMPORTED_MODULE_5__.commandIDs.detachAllNodes, {
        execute: async () => {
            var _a;
            const widget = (_a = tracker.currentWidget) === null || _a === void 0 ? void 0 : _a.content;
            const model = widget.xircuitsApp.getDiagramEngine().getModel();
            const selected_entities = model.getSelectedEntities();
            const literal_nodes = [];
            const selected_nodes = selected_entities.filter(entity => entity instanceof _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_0__.NodeModel);
            selected_nodes.forEach(node => {
                node.setSelected(false);
                let inPorts = node.getInPorts();
                Object.values(inPorts).forEach((port) => {
                    let sourceNode = port.getSourceNodes()[0];
                    if (sourceNode && sourceNode['name'].startsWith('Literal ') && sourceNode['extras']['attached']) {
                        sourceNode.getOptions().extras.attached = false;
                        sourceNode.setSelected(true);
                        literal_nodes.push(sourceNode);
                    }
                });
            });
            literal_nodes.forEach(node => {
                let parameterOutPort = node.getOutPorts()[0];
                let connectedNodes = parameterOutPort.getTargetNodes();
                connectedNodes.forEach((node) => node.setSelected(true));
            });
            widget.xircuitsApp.getDiagramEngine().repaintCanvas();
        },
        label: trans.__('detach all nodes')
    });
}


/***/ }),

/***/ "./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 _node_CustomNodeFactory__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./node/CustomNodeFactory */ "./lib/components/node/CustomNodeFactory.js");
/* harmony import */ var _node_CustomNodeModel__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./node/CustomNodeModel */ "./lib/components/node/CustomNodeModel.js");
/* 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_3__ = __webpack_require__(/*! ./link/CustomLinkModel */ "./lib/components/link/CustomLinkModel.js");
/* harmony import */ var _link_CustomLinkFactory__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./link/CustomLinkFactory */ "./lib/components/link/CustomLinkFactory.js");
/* harmony import */ var _projectstorm_geometry__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @projectstorm/geometry */ "webpack/sharing/consume/default/@projectstorm/geometry/@projectstorm/geometry?2db1");
/* harmony import */ var _projectstorm_geometry__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_projectstorm_geometry__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _tray_library_BaseComponentLib__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../tray_library/BaseComponentLib */ "./lib/tray_library/BaseComponentLib.js");
/* harmony import */ var _actions_CustomPanAndZoomCanvasAction__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./actions/CustomPanAndZoomCanvasAction */ "./lib/components/actions/CustomPanAndZoomCanvasAction.js");











class XircuitsApplication {
    constructor(app, shell, getWidgetId) {
        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 _node_CustomNodeModel__WEBPACK_IMPORTED_MODULE_2__.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);
                    const position = new _projectstorm_geometry__WEBPACK_IMPORTED_MODULE_1__.Point(port.x, port.y);
                    newNode.addInPortEnhance({ label: port.label, name: port.name, varName: port.varName, id: port.id, dataType: port.dataType, dynaPortOrder: port.dynaPortOrder, dynaPortRef: port.dynaPortRef, position });
                }
                for (let portID of node.portsOutOrder) {
                    const port = node.ports.find(p => p.id === portID);
                    const position = new _projectstorm_geometry__WEBPACK_IMPORTED_MODULE_1__.Point(port.x, port.y);
                    newNode.addOutPortEnhance({ label: port.label, name: port.name, id: port.id, position, dataType: port.dataType });
                }
                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_3__.ParameterLinkModel({ id: link.id });
                    const newTriangleLink = new _link_CustomLinkModel__WEBPACK_IMPORTED_MODULE_3__.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;
                        if (sourceNode['name'].startsWith("Argument ")) {
                            newLink.getOptions()['__sub-type__'] = 'argument';
                        }
                    }
                    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_1__.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 = new _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_0__.DiagramEngine({ registerDefaultZoomCanvasAction: false, registerDefaultDeleteItemsAction: false });
        // Default Factories
        this.diagramEngine.getLayerFactories().registerFactory(new _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_0__.NodeLayerFactory());
        this.diagramEngine.getLayerFactories().registerFactory(new _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_0__.LinkLayerFactory());
        this.diagramEngine.getLayerFactories().registerFactory(new _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_0__.SelectionBoxLayerFactory());
        this.diagramEngine.getLabelFactories().registerFactory(new _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_0__.DefaultLabelFactory());
        this.diagramEngine.getLinkFactories().registerFactory(new _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_0__.DefaultLinkFactory());
        this.diagramEngine.getPortFactories().registerFactory(new _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_0__.DefaultPortFactory());
        // Custom Factories, Actions & State
        this.diagramEngine.getNodeFactories().registerFactory(new _node_CustomNodeFactory__WEBPACK_IMPORTED_MODULE_4__.CustomNodeFactory(app, shell));
        this.diagramEngine.getLinkFactories().registerFactory(new _link_CustomLinkFactory__WEBPACK_IMPORTED_MODULE_5__.ParameterLinkFactory());
        this.diagramEngine.getLinkFactories().registerFactory(new _link_CustomLinkFactory__WEBPACK_IMPORTED_MODULE_5__.TriangleLinkFactory());
        this.diagramEngine.getActionEventBus().registerAction(new _actions_CustomPanAndZoomCanvasAction__WEBPACK_IMPORTED_MODULE_6__.CustomPanAndZoomCanvasAction());
        this.diagramEngine.getActionEventBus().registerAction(new _commands_CustomActionEvent__WEBPACK_IMPORTED_MODULE_7__.CustomActionEvent({ app, getWidgetId }));
        this.diagramEngine.getStateMachine().pushState(new _state_CustomDiagramState__WEBPACK_IMPORTED_MODULE_8__.CustomDiagramState());
        let startNode = (0,_tray_library_BaseComponentLib__WEBPACK_IMPORTED_MODULE_9__.BaseComponentLibrary)('Start');
        startNode.setPosition(100, 100);
        let finishNode = (0,_tray_library_BaseComponentLib__WEBPACK_IMPORTED_MODULE_9__.BaseComponentLibrary)('Finish');
        finishNode.setPosition(700, 100);
        this.activeModel = new _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_0__.DiagramModel();
        this.activeModel.addAll(startNode, finishNode);
        this.diagramEngine.setModel(this.activeModel);
    }
    getActiveDiagram() {
        return this.activeModel;
    }
    getDiagramEngine() {
        return this.diagramEngine;
    }
}


/***/ }),

/***/ "./lib/components/XircuitsBodyWidget.js":
/*!**********************************************!*\
  !*** ./lib/components/XircuitsBodyWidget.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 */ });
/* 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 */ "./node_modules/@projectstorm/react-canvas-core/dist/index.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 _helpers_XircuitsCanvasWidget__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ../helpers/XircuitsCanvasWidget */ "./lib/helpers/XircuitsCanvasWidget.js");
/* harmony import */ var _log_LogPlugin__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../log/LogPlugin */ "./lib/log/LogPlugin.js");
/* harmony import */ var _dialog_formDialogwidget__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../dialog/formDialogwidget */ "./lib/dialog/formDialogwidget.js");
/* harmony import */ var _dialog_FormDialog__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../dialog/FormDialog */ "./lib/dialog/FormDialog.js");
/* harmony import */ var _dialog_LiteralInputDialog__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../dialog/LiteralInputDialog */ "./lib/dialog/LiteralInputDialog.js");
/* harmony import */ var _dialog_input_dialogues_VariableInput__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../dialog/input-dialogues/VariableInput */ "./lib/dialog/input-dialogues/VariableInput.js");
/* harmony import */ var _dialog_LocalRunDialog__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../dialog/LocalRunDialog */ "./lib/dialog/LocalRunDialog.js");
/* harmony import */ var _dialog_RemoteRunDialog__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../dialog/RemoteRunDialog */ "./lib/dialog/RemoteRunDialog.js");
/* harmony import */ var _server_handler__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../server/handler */ "./lib/server/handler.js");
/* harmony import */ var _context_menu_ComponentsPanel__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ../context-menu/ComponentsPanel */ "./lib/context-menu/ComponentsPanel.js");
/* harmony import */ var _context_menu_CanvasContextMenu__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ../context-menu/CanvasContextMenu */ "./lib/context-menu/CanvasContextMenu.js");
/* harmony import */ var _tray_library_GeneralComponentLib__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../tray_library/GeneralComponentLib */ "./lib/tray_library/GeneralComponentLib.js");
/* harmony import */ var _tray_library_AdvanceComponentLib__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ../tray_library/AdvanceComponentLib */ "./lib/tray_library/AdvanceComponentLib.js");
/* harmony import */ var _state_powerModeState__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./state/powerModeState */ "./lib/components/state/powerModeState.js");
/* harmony import */ var _runner_RunOutput__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./runner/RunOutput */ "./lib/components/runner/RunOutput.js");
/* harmony import */ var _runner_RemoteRun__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./runner/RemoteRun */ "./lib/components/runner/RemoteRun.js");
/* harmony import */ var _siteUtils__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../siteUtils */ "./lib/siteUtils.js");
/* harmony import */ var _emotion_styled__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @emotion/styled */ "webpack/sharing/consume/default/@emotion/styled/@emotion/styled?1fc9");
/* harmony import */ var _emotion_styled__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_emotion_styled__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _commands_CommandIDs__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../commands/CommandIDs */ "./lib/commands/CommandIDs.js");






















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 BodyWidget = ({ context, xircuitsApp, app, shell, commands, widgetId, fetchComponentsSignal, fetchRemoteRunConfigSignal, saveXircuitSignal, compileXircuitSignal, runXircuitSignal, runTypeXircuitSignal, lockNodeSignal, triggerLoadingAnimationSignal, reloadAllNodesSignal, toggleAllLinkAnimationSignal, }) => {
    const xircuitLogger = new _log_LogPlugin__WEBPACK_IMPORTED_MODULE_4__.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 [remoteRunConfigs, setRemoteRunConfigs] = (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 [anyNodes, setAnyNodes] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)([]);
    const [componentList, setComponentList] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)([]);
    const [isLoading, setIsLoading] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(false);
    const [loadingMessage, setLoadingMessage] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)('Xircuits loading...');
    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 [prevRemoteConfiguration, setPrevRemoteConfiguration] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(null);
    const [remoteRunTypesCfg, setRemoteRunTypesCfg] = (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, null, 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(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_5__.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', `An error occurred: ${e.message}`);
            }
        };
        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 triggerLoadingAnimation = async (operationPromise, { loadingMessage = 'Xircuits loading...', loadingDisplayDuration = 1000, showLoadingAfter = 100 } = {}) => {
        var _a;
        if (((_a = shell.currentWidget) === null || _a === void 0 ? void 0 : _a.id) !== widgetId) {
            return;
        }
        let shouldSetLoading = false;
        setLoadingMessage(loadingMessage);
        // Start a timer that will check if the operation exceeds showLoadingAfter
        const startTimer = setTimeout(() => {
            shouldSetLoading = true;
            setIsLoading(true);
        }, showLoadingAfter);
        await operationPromise;
        // Clear the start timer as the operation has completed
        clearTimeout(startTimer);
        if (shouldSetLoading) {
            // If loading was started, ensure it stays for the minimum loading time
            const minTimer = setTimeout(() => setIsLoading(false), loadingDisplayDuration);
            // Clear the minimum timer to prevent memory leaks in case the component unmounts
            return () => clearTimeout(minTimer);
        }
        else {
            // If loading was not started, just ensure loading state is set to false
            setIsLoading(false);
        }
    };
    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(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_5__.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(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_5__.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-dont-compile') {
            commands.execute(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_5__.commandIDs.compileFile, { showOutput, componentList });
            setCompiled(true);
        }
        // Run Mode
        context.ready.then(async () => {
            const current_path = context.path;
            const model_path = current_path.split(".xircuits")[0] + ".py";
            let code = (0,_runner_RunOutput__WEBPACK_IMPORTED_MODULE_6__.startRunOutputStr)();
            let result;
            if (runType == 'run') {
                result = await handleLocalRunDialog();
                if (result.status === 'ok') {
                    code += "%run " + model_path + result.args;
                }
            }
            else if (runType == 'remote-run') {
                result = await handleRemoteRunDialog();
                if (result.status === 'ok') {
                    code += (0,_runner_RemoteRun__WEBPACK_IMPORTED_MODULE_7__.buildRemoteRunCommand)(model_path, result.args);
                }
            }
            if (result.status === 'ok') {
                commands.execute(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_5__.commandIDs.executeToOutputPanel, { code });
            }
            else if (result.status === 'cancelled') {
                console.log("Run operation cancelled by user.");
            }
        });
    };
    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;
        }
        if (runType == 'remote-run') {
            await getRemoteRunTypeFromConfig();
        }
        await 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 = async () => {
        var _a;
        if (((_a = shell.currentWidget) === null || _a === void 0 ? void 0 : _a.id) !== widgetId) {
            return;
        }
        await app.commands.execute(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_5__.commandIDs.refreshComponentList);
        let allNodes = xircuitsApp.getDiagramEngine().getModel().getNodes();
        allNodes.forEach(node => node.setSelected(true));
        const reloadPromise = app.commands.execute(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_5__.commandIDs.reloadNode);
        // Trigger loading animation
        await triggerLoadingAnimation(reloadPromise, { loadingMessage: 'Reloading all nodes...' });
        console.log("Reload all complete.");
    };
    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_8__.lowPowerMode;
        (0,_state_powerModeState__WEBPACK_IMPORTED_MODULE_8__.setLowPowerMode)(!powerMode);
    };
    async function getRunTypesFromConfig(request) {
        const dataToSend = { "config_request": request };
        try {
            const server_reply = await (0,_server_handler__WEBPACK_IMPORTED_MODULE_9__.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 getRemoteRunTypeFromConfig = 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' })]
            });
        }
        // Compare new configuration with previous
        if (JSON.stringify(configuration) !== JSON.stringify(prevRemoteConfiguration)) {
            // Configuration has changed, reset lastConfig
            setLastConfigs("");
            setPrevRemoteConfiguration(configuration);
        }
        setRemoteRunTypesCfg(configuration["run_types"]);
        setRemoteRunConfigs(configuration["run_types_config"]);
    };
    // fetch remote run config when toggling to remote run
    (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
        getRemoteRunTypeFromConfig();
    }, [runType]);
    (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
        const setterByType = {
            'string': setStringNodes,
            'int': setIntNodes,
            'float': setFloatNodes,
            'boolean': setBoolNodes,
            'any': setAnyNodes
        };
        Object.values(setterByType).forEach(set => set([]));
        context.ready.then(() => {
            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()));
                    }
                }
            }
        });
    }, [initialize]);
    const handleLocalRunDialog = async () => {
        let title = 'Execute Workflow';
        const dialogOptions = {
            title,
            body: (0,_dialog_formDialogwidget__WEBPACK_IMPORTED_MODULE_10__.formDialogWidget)(react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_dialog_LocalRunDialog__WEBPACK_IMPORTED_MODULE_11__.LocalRunDialog, { 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_12__.showFormDialog)(dialogOptions);
        if (dialogResult.button.label === 'Cancel') {
            // When Cancel is clicked on the dialog, just return
            return { status: 'cancelled' };
        }
        const date = new Date();
        xircuitLogger.info(`experiment name: ${date.toLocaleString()}`);
        const runCommand = [
            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, "_");
                return `${cmd} --${filteredParam} ${dialogResult.value[param]}`;
            }, s);
        }, "");
        return { status: 'ok', args: runCommand };
    };
    const handleRemoteRunDialog = async () => {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j;
        let title = 'Execute Workflow';
        const dialogOptions = {
            title,
            body: (0,_dialog_formDialogwidget__WEBPACK_IMPORTED_MODULE_10__.formDialogWidget)(react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_dialog_RemoteRunDialog__WEBPACK_IMPORTED_MODULE_13__.RemoteRunDialog, { remoteRunTypes: remoteRunTypesCfg, remoteRunConfigs: remoteRunConfigs, 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_12__.showFormDialog)(dialogOptions);
        if (dialogResult.button.label === 'Cancel') {
            // When Cancel is clicked on the dialog, just return
            return { status: 'cancelled' };
        }
        // Remember the last config chose and set the chosen config to output
        let config;
        let remoteRunType = (_a = dialogResult["value"]['remoteRunType']) !== null && _a !== void 0 ? _a : "";
        let runConfig = (_b = dialogResult["value"]['remoteRunConfig']) !== null && _b !== void 0 ? _b : "";
        let runProject = (_c = dialogResult["value"]['project']) !== null && _c !== void 0 ? _c : "";
        let runStageOut = (_d = dialogResult["value"]['stage_out']) !== null && _d !== void 0 ? _d : "";
        let runMonitoring = (_e = dialogResult["value"]['monitoring']) !== null && _e !== void 0 ? _e : "";
        let runFilesystem = (_f = dialogResult["value"]['filesystem']) !== null && _f !== void 0 ? _f : "";
        let runPython = (_g = dialogResult["value"]['python']) !== null && _g !== void 0 ? _g : "";
        let runModules = (_h = dialogResult["value"]['modules']) !== null && _h !== void 0 ? _h : "";
        let runLibraries = (_j = dialogResult["value"]['libraries']) !== null && _j !== void 0 ? _j : "";
        if (remoteRunConfigs.length != 0) {
            remoteRunConfigs.map(cfg => {
                if (cfg.run_type == remoteRunType && cfg.run_config_name == runConfig) {
                    config = Object.assign(Object.assign({}, cfg), dialogResult["value"]);
                    cfg['project'] = runProject.length > 0 ? runProject : 'NONE';
                    cfg['stage-out'] = runStageOut;
                    cfg['filesystem'] = runFilesystem.length > 0 ? runFilesystem : 'NONE';
                    cfg['python'] = runPython.length > 0 ? runPython : 'NONE';
                    cfg['modules'] = runModules.length > 0 ? runModules : 'NONE';
                    cfg['libraries'] = runLibraries.length > 0 ? runLibraries : 'NONE';
                    setLastConfigs(cfg);
                }
            });
        }
        if (runType !== '' && runMonitoring === 'on') {
            // It means a remote launch was started
            await app.commands.execute(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_5__.commandIDs.openTvbExtUnicore, {
                defaultSite: (0,_siteUtils__WEBPACK_IMPORTED_MODULE_14__.readDefaultSite)()
            });
        }
        return { status: 'ok', args: 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],
        [fetchRemoteRunConfigSignal, getRemoteRunTypeFromConfig],
        [lockNodeSignal, handleLockClick],
        [triggerLoadingAnimationSignal, triggerLoadingAnimation],
        [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) => {
        // this part is necessary for enum options that have "-" in them
        const firstDashIdx = linkName.indexOf("-");
        const lastDashIndex = linkName.lastIndexOf("-");
        let portType = linkName.substring(firstDashIdx + 1, lastDashIndex);
        // if multiple types provided, Use the first type.
        if (portType.startsWith("Union")) {
            portType = portType.replace('Union', '');
            portType = portType.replace(/[\[\]]/g, '');
            portType = portType.split(',')[0];
        }
        let nodeType = portType;
        let varInput = '';
        let errorMsg;
        if (portType.slice(0, 7) === "Literal") {
            let enumTitle = 'Select the value: ';
            const possibleValues = eval(portType.slice(7));
            const dialogOptions = (0,_dialog_LiteralInputDialog__WEBPACK_IMPORTED_MODULE_15__.inputDialog)({ title: enumTitle, oldValue: '', type: 'enum', inputType: null, possibleValues: possibleValues });
            const dialogResult = await (0,_dialog_FormDialog__WEBPACK_IMPORTED_MODULE_12__.showFormDialog)(dialogOptions);
            if ((0,_tray_library_GeneralComponentLib__WEBPACK_IMPORTED_MODULE_16__.cancelDialog)(dialogResult))
                return;
            nodeType = "String";
            varInput = dialogResult["value"][enumTitle];
        }
        else {
            switch (portType) {
                case 'int':
                    nodeType = 'Integer';
                    break;
                case 'boolean': {
                    let boolTitle = 'Enter boolean value: ';
                    const dialogOptions = (0,_dialog_LiteralInputDialog__WEBPACK_IMPORTED_MODULE_15__.inputDialog)({ title: boolTitle, oldValue: "", type: 'boolean' });
                    const dialogResult = await (0,_dialog_FormDialog__WEBPACK_IMPORTED_MODULE_12__.showFormDialog)(dialogOptions);
                    if ((0,_tray_library_GeneralComponentLib__WEBPACK_IMPORTED_MODULE_16__.cancelDialog)(dialogResult))
                        return;
                    let boolValue = dialogResult["value"][boolTitle].toLowerCase();
                    nodeType = boolValue === 'false' ? 'False' : 'True';
                    break;
                }
                case 'any':
                case 'dynalist':
                case 'dynatuple':
                    // 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_17__.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_18__.fetchNodeByName)('Literal ' + nodeType);
        let node = await (0,_tray_library_GeneralComponentLib__WEBPACK_IMPORTED_MODULE_16__.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(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_5__.commandIDs.addNodeGivenPosition, { node, nodePosition });
        await app.commands.execute(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_5__.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 [contextMenuShown, setContextMenuShown] = (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 [contextMenuPosition, setContextMenuPosition] = (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 getPanelPosition = (event, caller) => {
        let menuDimension;
        if (caller === "ContextMenu") {
            // For context menu, calculate dimension based on visible options
            const menuOptionHeight = 30;
            let visibleOptions = (0,_context_menu_CanvasContextMenu__WEBPACK_IMPORTED_MODULE_19__.getMenuOptionsVisibility)(xircuitsApp.getDiagramEngine().getModel().getSelectedEntities());
            let numVisibleOptions = (0,_context_menu_CanvasContextMenu__WEBPACK_IMPORTED_MODULE_19__.countVisibleMenuOptions)(visibleOptions);
            menuDimension = {
                x: 105,
                y: menuOptionHeight * numVisibleOptions,
            };
        }
        else {
            // For other callers, set a fixed dimension
            menuDimension = {
                x: 105,
                y: 290,
            };
        }
        let newPanelPosition = calculatePanelSpawn(event, menuDimension);
        return newPanelPosition;
    };
    const calculatePanelSpawn = (event, menuDimension) => {
        let newPanelPosition = {
            x: event.pageX,
            y: event.pageY,
        };
        const canvas = event.view;
        const newCenterPosition = {
            x: canvas.innerWidth / 2,
            y: canvas.innerHeight / 2,
        };
        let fileBrowserWidth = document.getElementsByClassName("jp-SidePanel")[0].parentElement.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;
        }
        return newPanelPosition;
    };
    // Show the component panel context menu
    const showComponentPanel = (event) => {
        setContextMenuShown(false);
        setIsComponentPanelShown(false);
        const node_position = xircuitsApp.getDiagramEngine().getRelativeMousePoint(event);
        setNodePosition(node_position);
        let newPanelPosition = getPanelPosition(event, "ComponentPanel");
        setComponentPanelPosition(newPanelPosition);
        setIsComponentPanelShown(true);
    };
    // Show the component panel from dropped link
    const showComponentPanelFromLink = async (event) => {
        setContextMenuShown(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;
            }
            // Don't allow linking to a literal if there is already an established connection
            // checking for > 1 because the link we are connecting also counts
            if (Object.keys(event.sourcePort.links).length > 1) {
                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);
        let newPanelPosition = getPanelPosition(event.linkEvent, "ComponentPanel");
        setComponentPanelPosition(newPanelPosition);
        setIsComponentPanelShown(true);
    };
    // Hide component and node action panel
    const hidePanel = () => {
        setIsComponentPanelShown(false);
        setContextMenuShown(false);
        setLooseLinkData(null);
        setIsParameterLink(false);
    };
    // Show the canvasContextMenu context menu
    const showCanvasContextMenu = (event) => {
        // Disable the default context menu
        event.preventDefault();
        setContextMenuShown(false);
        setIsComponentPanelShown(false);
        const node_position = xircuitsApp.getDiagramEngine().getRelativeMousePoint(event);
        setNodePosition(node_position);
        let newPanelPosition = getPanelPosition(event, "ContextMenu");
        setContextMenuPosition(newPanelPosition);
        setContextMenuShown(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_16__.GeneralComponentLibrary)({ model: current_node });
            }
            else if (current_node.header == "ADVANCED") {
                node = (0,_tray_library_AdvanceComponentLib__WEBPACK_IMPORTED_MODULE_18__.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
        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) && event.target['tagName'] != 'g') {
            showComponentPanel(event);
            return;
        }
        if (dontHidePanel) {
            return;
        }
        hidePanel();
    };
    (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
        const canvas = xircuitsApp.getDiagramEngine().getCanvas();
        canvas.addEventListener('wheel', preventDefault);
        return () => {
            canvas.removeEventListener('wheel', preventDefault);
        };
    }, [xircuitsApp.getDiagramEngine().getCanvas()]);
    return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement(Body, null,
        react__WEBPACK_IMPORTED_MODULE_0___default().createElement(Content, null,
            isLoading && (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "loading-indicator" },
                react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "loading-gif-wrapper" }),
                react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "loading-text" }, loadingMessage))),
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement(Layer, { onDrop: handleDropEvent, onDragOver: preventDefault, onMouseOver: preventDefault, onMouseUp: preventDefault, onMouseDown: preventDefault, onContextMenu: showCanvasContextMenu, onClick: handleClick },
                react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_helpers_XircuitsCanvasWidget__WEBPACK_IMPORTED_MODULE_20__.XircuitsCanvasWidget, 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_21__["default"], { lab: app, eng: xircuitsApp.getDiagramEngine(), nodePosition: nodePosition, linkData: looseLinkData, isParameter: isParameterLink, key: "component-panel" }))),
                    contextMenuShown && (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { id: 'context-menu', style: {
                            top: contextMenuPosition.y,
                            left: contextMenuPosition.x
                        }, className: "canvas-context-menu" },
                        react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_context_menu_CanvasContextMenu__WEBPACK_IMPORTED_MODULE_19__.CanvasContextMenu, { app: app, engine: xircuitsApp.getDiagramEngine(), nodePosition: nodePosition }))))))));
};


/***/ }),

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

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   CustomPanAndZoomCanvasAction: () => (/* binding */ CustomPanAndZoomCanvasAction)
/* harmony export */ });
/* harmony import */ var _projectstorm_react_canvas_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @projectstorm/react-canvas-core */ "./node_modules/@projectstorm/react-canvas-core/dist/index.js");

class CustomPanAndZoomCanvasAction extends _projectstorm_react_canvas_core__WEBPACK_IMPORTED_MODULE_0__.Action {
    constructor(options = {}) {
        super({
            type: _projectstorm_react_canvas_core__WEBPACK_IMPORTED_MODULE_0__.InputType.MOUSE_WHEEL,
            fire: (actionEvent) => {
                const { event } = actionEvent;
                // we can block layer rendering because we are only targeting the transforms
                for (let layer of this.engine.getModel().getLayers()) {
                    layer.allowRepaint(false);
                }
                const model = this.engine.getModel();
                event.stopPropagation();
                if (event.ctrlKey) {
                    // Pinch and zoom gesture
                    const oldZoomFactor = this.engine.getModel().getZoomLevel() / 100;
                    let scrollDelta = options.inverseZoom ? event.deltaY : -event.deltaY;
                    //check if it is pinch gesture
                    if (event.ctrlKey && scrollDelta % 1 !== 0) {
                        /*
                          Chrome and Firefox sends wheel event with deltaY that
                          have fractional part, also `ctrlKey` prop of the event is true
                          though ctrl isn't pressed
                        */
                        scrollDelta /= 3;
                    }
                    else {
                        scrollDelta /= 60;
                    }
                    if (model.getZoomLevel() + scrollDelta > 10) {
                        model.setZoomLevel(model.getZoomLevel() + scrollDelta);
                    }
                    const zoomFactor = model.getZoomLevel() / 100;
                    const boundingRect = event.currentTarget.getBoundingClientRect();
                    const clientWidth = boundingRect.width;
                    const clientHeight = boundingRect.height;
                    // compute difference between rect before and after scroll
                    const widthDiff = clientWidth * zoomFactor - clientWidth * oldZoomFactor;
                    const heightDiff = clientHeight * zoomFactor - clientHeight * oldZoomFactor;
                    // compute mouse coords relative to canvas
                    const clientX = event.clientX - boundingRect.left;
                    const clientY = event.clientY - boundingRect.top;
                    // compute width and height increment factor
                    const xFactor = (clientX - model.getOffsetX()) / oldZoomFactor / clientWidth;
                    const yFactor = (clientY - model.getOffsetY()) / oldZoomFactor / clientHeight;
                    model.setOffset(model.getOffsetX() - widthDiff * xFactor, model.getOffsetY() - heightDiff * yFactor);
                }
                else {
                    // Pan gesture
                    let yDelta = options.inverseZoom ? -event.deltaY : event.deltaY;
                    let xDelta = options.inverseZoom ? -event.deltaX : event.deltaX;
                    model.setOffset(model.getOffsetX() - xDelta, model.getOffsetY() - yDelta);
                }
                this.engine.repaintCanvas();
                // re-enable rendering
                for (let layer of this.engine.getModel().getLayers()) {
                    layer.allowRepaint(true);
                }
            }
        });
    }
}


/***/ }),

/***/ "./lib/components/common/Dropdown.js":
/*!*******************************************!*\
  !*** ./lib/components/common/Dropdown.js ***!
  \*******************************************/
/***/ ((__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 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__);

function Dropdown(props) {
    return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("select", { name: props.name }, props.types.map((type, index) => react__WEBPACK_IMPORTED_MODULE_0___default().createElement("option", { value: type, key: index }, type))));
}
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (Dropdown);


/***/ }),

/***/ "./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 _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 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 _CustomLinkModel__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./CustomLinkModel */ "./lib/components/link/CustomLinkModel.js");
/* harmony import */ var _emotion_styled__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @emotion/styled */ "webpack/sharing/consume/default/@emotion/styled/@emotion/styled?1fc9");
/* harmony import */ var _emotion_styled__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_emotion_styled__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _emotion_react__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @emotion/react */ "webpack/sharing/consume/default/@emotion/react/@emotion/react?f02c");
/* harmony import */ var _emotion_react__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_emotion_react__WEBPACK_IMPORTED_MODULE_4__);






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

		fill: none;
		pointer-events: auto;
		filter: drop-shadow(2px 2px 4px rgb(0 0 0 / 40%)) opacity(60%);
		
		body.low-powered-mode & {
			animation: none !important;
		}
	`;
    S.G = (_emotion_styled__WEBPACK_IMPORTED_MODULE_3___default().g) `
		g.hover & path {
			stroke: rgb(192, 255, 0);
		}
	`;
})(S || (S = {}));
function escapeSelector(selector) {
    return selector.replace(/([!"#$%&'()*+,.\/:;<=>?@[\\\]^`{|}~])/g, '\\$1');
}
function addHover(model) {
    return (() => {
        var _a, _b, _c, _d;
        const sourceNodeId = model.getSourcePort().getNode().getID();
        const sourcePortName = escapeSelector(model.getSourcePort().getName());
        const targetNodeId = model.getTargetPort().getNode().getID();
        const targetPortName = escapeSelector(model.getTargetPort().getName());
        (_b = (_a = document.querySelector(`div.port[data-nodeid='${sourceNodeId}'][data-name='${sourcePortName}']>div>div`)) === null || _a === void 0 ? void 0 : _a.classList) === null || _b === void 0 ? void 0 : _b.add("hover");
        (_d = (_c = document.querySelector(`div.port[data-nodeid="${targetNodeId}"][data-name='${targetPortName}']>div>div`)) === null || _c === void 0 ? void 0 : _c.classList) === null || _d === void 0 ? void 0 : _d.add("hover");
    });
}
function removeHover(model) {
    return () => {
        var _a, _b, _c, _d;
        const sourceNodeId = model.getSourcePort().getNode().getID();
        const sourcePortName = escapeSelector(model.getSourcePort().getName());
        const targetNodeId = model.getTargetPort().getNode().getID();
        const targetPortName = escapeSelector(model.getTargetPort().getName());
        (_b = (_a = document.querySelector(`div.port[data-nodeid='${sourceNodeId}'][data-name='${sourcePortName}']>div>div`)) === null || _a === void 0 ? void 0 : _a.classList) === null || _b === void 0 ? void 0 : _b.remove("hover");
        (_d = (_c = document.querySelector(`div.port[data-nodeid="${targetNodeId}"][data-name='${targetPortName}']>div>div`)) === null || _c === void 0 ? void 0 : _c.classList) === null || _d === void 0 ? void 0 : _d.remove("hover");
    };
}
class SelectOnClickLinkWidget extends _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_0__.DefaultLinkWidget {
    constructor(type) {
        super(type);
    }
    addPointToLink(event, index) {
        if (event.ctrlKey &&
            !this.props.link.isLocked() &&
            this.props.link.getPoints().length - 1 <= this.props.diagramEngine.getMaxNumberPointsPerLink()) {
            event.stopPropagation();
            const position = this.props.diagramEngine.getRelativeMousePoint(event);
            const point = this.props.link.point(position.x, position.y, index);
            event.persist();
            this.forceUpdate(() => {
                this.props.diagramEngine.getActionEventBus().fireAction({
                    event,
                    model: point
                });
            });
        }
    }
    render() {
        //ensure id is present for all points on the path
        var points = this.props.link.getPoints();
        var paths = [];
        this.refPaths = [];
        if (points.length === 2) {
            paths.push(this.generateLink(this.props.link.getSVGPath(), {
                onMouseDown: (event) => {
                    var _a, _b;
                    (_b = (_a = this.props).selected) === null || _b === void 0 ? void 0 : _b.call(_a, event);
                    this.addPointToLink(event, 1);
                }
            }, '0'));
            // draw the link as dangeling
            if (this.props.link.getTargetPort() == null) {
                paths.push(this.generatePoint(points[1]));
            }
        }
        else {
            //draw the multiple anchors and complex line instead
            for (let j = 0; j < points.length - 1; j++) {
                paths.push(this.generateLink(_projectstorm_react_diagrams_core__WEBPACK_IMPORTED_MODULE_1__.LinkWidget.generateLinePath(points[j], points[j + 1]), {
                    'data-linkid': this.props.link.getID(),
                    'data-point': j,
                    onMouseDown: (event) => {
                        var _a, _b;
                        (_b = (_a = this.props).selected) === null || _b === void 0 ? void 0 : _b.call(_a, event);
                        this.addPointToLink(event, j + 1);
                    }
                }, j));
            }
            if (this.renderPoints()) {
                //render the circles
                for (let i = 1; i < points.length - 1; i++) {
                    paths.push(this.generatePoint(points[i]));
                }
                if (this.props.link.getTargetPort() == null) {
                    paths.push(this.generatePoint(points[points.length - 1]));
                }
            }
        }
        return react__WEBPACK_IMPORTED_MODULE_2__.createElement(S.G, { "data-default-link-test": this.props.link.getOptions().testName }, paths);
    }
}
class SelectOnClickLinkFactory extends _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_0__.DefaultLinkFactory {
    generateReactWidget(event) {
        return react__WEBPACK_IMPORTED_MODULE_2__.createElement(SelectOnClickLinkWidget, { link: event.model, diagramEngine: this.engine });
    }
}
class ParameterLinkFactory extends SelectOnClickLinkFactory {
    constructor() {
        super('parameter-link');
    }
    generateModel() {
        return new _CustomLinkModel__WEBPACK_IMPORTED_MODULE_5__.ParameterLinkModel();
    }
    generateLinkSegment(model, selected, path) {
        return (react__WEBPACK_IMPORTED_MODULE_2__.createElement(S.Path, { onMouseOver: addHover(model), onMouseOut: removeHover(model), selected: selected, stroke: model.getOptions().color, strokeWidth: model.getOptions().width, d: path, isRegularLink: true }));
    }
}
class TriangleLinkFactory extends SelectOnClickLinkFactory {
    constructor() {
        super('triangle-link');
    }
    generateModel() {
        return new _CustomLinkModel__WEBPACK_IMPORTED_MODULE_5__.TriangleLinkModel();
    }
    generateLinkSegment(model, selected, path) {
        const isRegularLink = model.getOptions()['__sub-type__'] === 'argument';
        return (react__WEBPACK_IMPORTED_MODULE_2__.createElement(S.Path, { onMouseOver: addHover(model), onMouseOut: removeHover(model), isRegularLink: isRegularLink, selected: selected, stroke: isRegularLink ? model.getOptions().color : model.getOptions().selectedColor, 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/node/CustomNodeFactory.js":
/*!**************************************************!*\
  !*** ./lib/components/node/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/node/CustomNodeModel.js");
/* harmony import */ var _projectstorm_react_canvas_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @projectstorm/react-canvas-core */ "./node_modules/@projectstorm/react-canvas-core/dist/index.js");
/* harmony import */ var _CustomNodeWidget__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./CustomNodeWidget */ "./lib/components/node/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/node/CustomNodeModel.js":
/*!************************************************!*\
  !*** ./lib/components/node/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, description = "", position = null }) {
        //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 });
        p.description = description;
        if (order !== null) {
            this.portsOut.splice(order, 0, p);
        }
        if (position !== null) {
            p.setPosition(position);
        }
        return this.addPort(p);
    }
    addInPortEnhance({ label, name, varName = label, order = null, id, description = "", dataType, dynaPortOrder = 0, dynaPortRef = { previous: null, next: null }, position = 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 });
        }
        p.description = description;
        if (order !== null) {
            this.portsIn.splice(order, 0, p);
        }
        if (position !== null) {
            p.setPosition(position);
        }
        return this.addPort(p);
    }
}


/***/ }),

/***/ "./lib/components/node/CustomNodeWidget.js":
/*!*************************************************!*\
  !*** ./lib/components/node/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 */   S: () => (/* binding */ S),
/* harmony export */   getNodeIcon: () => (/* binding */ getNodeIcon)
/* 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?1fc9");
/* 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 _port_CustomPortLabel__WEBPACK_IMPORTED_MODULE_13__ = __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_11__ = __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_CommentDialog__WEBPACK_IMPORTED_MODULE_12__ = __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__);
/* harmony import */ var colorjs_io__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! colorjs.io */ "webpack/sharing/consume/default/colorjs.io/colorjs.io");
/* harmony import */ var colorjs_io__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(colorjs_io__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _commands_CommandIDs__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../../commands/CommandIDs */ "./lib/commands/CommandIDs.js");
/* harmony import */ var _ui_components_icons__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../../ui-components/icons */ "./lib/ui-components/icons.js");
/* harmony import */ var _style_icons_circuit_board_bg_svg__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../../../style/icons/circuit-board-bg.svg */ "./style/icons/circuit-board-bg.svg");
















var S;
(function (S) {
    S.Node = (_emotion_styled__WEBPACK_IMPORTED_MODULE_2___default().div) `
        box-shadow: 1px 1px 10px ${(p) => p.selected ? '3px rgb(0 192 255 / 0.5)' : '0px rgb(0 0 0 / 0.5)'};
        cursor: grab;
        border-radius: 5px;
        font-family: sans-serif;
        color: white;
        overflow: visible;
        font-size: 11px;
        border: solid 1px ${(p) => (p.selected ? (p.borderColor == undefined ? 'rgb(0,192,255)' : p.borderColor) : 'black')};
        & .grabbing {
            cursor: grabbing;
        }
    `;
    S.Title = (_emotion_styled__WEBPACK_IMPORTED_MODULE_2___default().div) `
        background-image: ${(p) => {
        const color = new (colorjs_io__WEBPACK_IMPORTED_MODULE_7___default())(p.background);
        color.alpha = 0.75;
        color.oklch.c *= 1.2;
        const color1 = color.to('oklch').toString();
        color.oklch.c *= 1.2;
        color.oklch.l /= 2;
        const color2 = color.to('oklch').toString();
        return `linear-gradient(${color1}, ${color2})`;
    }};
        font-weight: 500;
        letter-spacing: 0.025rem;
        display: flex;
        white-space: nowrap;
        justify-items: center;
        box-shadow: inset 0 -2px 4px 0 rgb(0 0 0 / 0.05);
        border-top-left-radius: 5px;
        border-top-right-radius: 5px;
    `;
    S.TitleName = (_emotion_styled__WEBPACK_IMPORTED_MODULE_2___default().div) `
        flex-grow: 1;
        padding: 5px 5px 5px 5px;
    `;
    S.IconContainer = (_emotion_styled__WEBPACK_IMPORTED_MODULE_2___default().div) `
        padding: 5px 5px 5px 5px;
        display: flex;
        align-items: center;
        justify-content: center;
        width: 15px;
        height: 15px;
        svg {
            width: 100%;
            height: 100%;
        }
    `;
    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(oklch(10% 0 0 / 0.7), oklch(10% 0 0 / 0.9));
        border-bottom-left-radius: 5px;
        border-bottom-right-radius: 5px;
        
        .workflow-node & {
            background: linear-gradient(oklch(10% 0 0 / 0.7), oklch(10% 0 0 / 0.9)), url("data:image/svg+xml;base64,${btoa(_style_icons_circuit_board_bg_svg__WEBPACK_IMPORTED_MODULE_8__)}") no-repeat right 10px;
        }
    `;
    S.PortsContainer = (_emotion_styled__WEBPACK_IMPORTED_MODULE_2___default().div) `
        max-width: 640px;
        min-width: 0;
        white-space: pre;
        flex-grow: 1;
        display: flex;
        flex-direction: column;

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

        &:only-child {
            margin-right: 0px;
        }
    `;
    S.WorkflowNode = _emotion_styled__WEBPACK_IMPORTED_MODULE_2___default()(S.Node) `
    `;
})(S || (S = {}));
const getNodeIcon = (type) => {
    switch (type) {
        case 'Start':
        case 'startFinish':
            return react__WEBPACK_IMPORTED_MODULE_0__.createElement(_ui_components_icons__WEBPACK_IMPORTED_MODULE_9__.startFinishComponentIcon.react, null);
        case 'workflow':
        case 'xircuits_workflow':
            return react__WEBPACK_IMPORTED_MODULE_0__.createElement(_ui_components_icons__WEBPACK_IMPORTED_MODULE_9__.workflowComponentIcon.react, null);
        case 'branch':
            return react__WEBPACK_IMPORTED_MODULE_0__.createElement(_ui_components_icons__WEBPACK_IMPORTED_MODULE_9__.branchComponentIcon.react, null);
        case 'function':
            return react__WEBPACK_IMPORTED_MODULE_0__.createElement(_ui_components_icons__WEBPACK_IMPORTED_MODULE_9__.functionComponentIcon.react, null);
        case 'context_set':
            return react__WEBPACK_IMPORTED_MODULE_0__.createElement(_ui_components_icons__WEBPACK_IMPORTED_MODULE_9__.setVariableComponentIcon.react, null);
        case 'context_get':
            return react__WEBPACK_IMPORTED_MODULE_0__.createElement(_ui_components_icons__WEBPACK_IMPORTED_MODULE_9__.getVariableComponentIcon.react, null);
        case 'variable':
            return react__WEBPACK_IMPORTED_MODULE_0__.createElement(_ui_components_icons__WEBPACK_IMPORTED_MODULE_9__.variableComponentIcon.react, null);
        // component libraries were typed as 'debug' before v1.12.
        case 'debug':
        case 'library_component':
            return react__WEBPACK_IMPORTED_MODULE_0__.createElement(_ui_components_icons__WEBPACK_IMPORTED_MODULE_9__.componentLibIcon.react, null);
        default:
            return null;
    }
};
function addGrabbing(e) {
    e.target.classList.add('grabbing');
}
function removeGrabbing(e) {
    e.target.classList.remove('grabbing');
}
const CommentNode = ({ node }) => {
    const [commentInput, setCommentInput] = react__WEBPACK_IMPORTED_MODULE_0__.useState(node['extras']['commentInput']);
    const handleEditComment = async () => {
        let dialogResult = await (0,_dialog_FormDialog__WEBPACK_IMPORTED_MODULE_10__.showFormDialog)({
            body: (0,_dialog_formDialogwidget__WEBPACK_IMPORTED_MODULE_11__.formDialogWidget)(react__WEBPACK_IMPORTED_MODULE_0__.createElement(_dialog_CommentDialog__WEBPACK_IMPORTED_MODULE_12__.CommentDialog, { commentInput: commentInput })),
            buttons: [_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_4__.Dialog.cancelButton(), _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_4__.Dialog.okButton({ label: 'Submit' })],
            focusNodeSelector: 'textarea'
        });
        if (dialogResult["button"]["label"] === 'Cancel') {
            return false;
        }
        const newVal = dialogResult["value"][''];
        setCommentInput(newVal);
        node['extras']['commentInput'] = newVal;
    };
    return (react__WEBPACK_IMPORTED_MODULE_0__.createElement(S.CommentContainer, { onDoubleClick: handleEditComment, selected: node.isSelected(), onMouseDown: addGrabbing, onMouseUp: removeGrabbing },
        react__WEBPACK_IMPORTED_MODULE_0__.createElement(S.TitleName, null,
            react__WEBPACK_IMPORTED_MODULE_0__.createElement("b", null, node.getOptions().name)),
        react__WEBPACK_IMPORTED_MODULE_0__.createElement("div", { className: 'comment-component-content' }, commentInput)));
};
const PortsComponent = ({ node, engine, app, showDescription, setShowDescription, setDescriptionStr, }) => {
    const renderPort = (port, index) => {
        const argumentDescriptions = node['extras']['argumentDescriptions'];
        // remove the ☆ from the beginning of the label
        const name = port.getOptions().label[0] === "★" ? port.getOptions().label.slice(1) : port.getOptions().label;
        const description = argumentDescriptions && (name in argumentDescriptions) ? argumentDescriptions[name] : "";
        const isOutPort = port.getOptions().name.includes('parameter-out');
        const idx = isOutPort ? index + node.getInPorts().length : index;
        return react__WEBPACK_IMPORTED_MODULE_0__.createElement(_port_CustomPortLabel__WEBPACK_IMPORTED_MODULE_13__.CustomPortLabel, { engine: engine, port: port, key: port.getID(), node: node, app: app, showDescription: (showDescription === null || showDescription === void 0 ? void 0 : showDescription[idx]) || false, setShowDescription: setShowDescription ? setShowDescription(idx) : () => { }, setDescriptionStr: setDescriptionStr || (() => { }), description: description });
    };
    return (react__WEBPACK_IMPORTED_MODULE_0__.createElement(S.Ports, null,
        react__WEBPACK_IMPORTED_MODULE_0__.createElement(S.PortsContainer, null, lodash__WEBPACK_IMPORTED_MODULE_1__.map(node.getInPorts(), renderPort)),
        react__WEBPACK_IMPORTED_MODULE_0__.createElement(S.PortsContainer, null, lodash__WEBPACK_IMPORTED_MODULE_1__.map(node.getOutPorts(), renderPort))));
};
const ParameterNode = ({ node, engine, app }) => {
    const handleEditParameter = () => {
        const nodeName = node.getOptions()["name"];
        if (!nodeName.startsWith("Literal ") && !nodeName.startsWith("Argument ")) {
            return;
        }
        app.commands.execute(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_14__.commandIDs.editNode);
    };
    if (node.getOptions().extras['attached']) {
        return react__WEBPACK_IMPORTED_MODULE_0__.createElement(react__WEBPACK_IMPORTED_MODULE_0__.Fragment, null);
    }
    return (react__WEBPACK_IMPORTED_MODULE_0__.createElement(S.Node, { onMouseDown: addGrabbing, onMouseUp: removeGrabbing, borderColor: node.getOptions().extras["borderColor"], "data-default-node-name": node.getOptions().name, selected: node.isSelected(), background: node.getOptions().color, onDoubleClick: handleEditParameter },
        react__WEBPACK_IMPORTED_MODULE_0__.createElement(S.Title, { background: node.getOptions().color },
            react__WEBPACK_IMPORTED_MODULE_0__.createElement(S.TitleName, null, node.getOptions().name)),
        react__WEBPACK_IMPORTED_MODULE_0__.createElement(PortsComponent, { node: node, engine: engine, app: app })));
};
const StartFinishNode = ({ node, engine, handleDeletableNode, app }) => {
    var _a;
    return (react__WEBPACK_IMPORTED_MODULE_0__.createElement(S.Node, { onMouseDown: addGrabbing, onMouseUp: removeGrabbing, borderColor: node.getOptions().extras["borderColor"], "data-default-node-name": node.getOptions().name, selected: node.isSelected(), background: node.getOptions().color },
        react__WEBPACK_IMPORTED_MODULE_0__.createElement(S.Title, { background: node.getOptions().color },
            react__WEBPACK_IMPORTED_MODULE_0__.createElement(S.IconContainer, null, getNodeIcon('startFinish')),
            react__WEBPACK_IMPORTED_MODULE_0__.createElement(S.TitleName, null, 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: (_a = node.isLocked()) !== null && _a !== void 0 ? _a : false, onChange: event => handleDeletableNode('nodeDeletable', event) }))),
        react__WEBPACK_IMPORTED_MODULE_0__.createElement(PortsComponent, { node: node, engine: engine, app: app })));
};
const WorkflowNode = ({ node, engine, app, handleDeletableNode }) => {
    var _a;
    return (react__WEBPACK_IMPORTED_MODULE_0__.createElement("div", { style: { position: "relative" } },
        react__WEBPACK_IMPORTED_MODULE_0__.createElement(S.WorkflowNode, { onMouseDown: addGrabbing, onMouseUp: removeGrabbing, "data-tip": true, "data-for": node.getOptions().id, borderColor: node.getOptions().extras["borderColor"], "data-default-node-name": node.getOptions().name, selected: node.isSelected(), background: node.getOptions().color, className: "workflow-node" },
            react__WEBPACK_IMPORTED_MODULE_0__.createElement(S.Title, { background: node.getOptions().color },
                react__WEBPACK_IMPORTED_MODULE_0__.createElement(S.IconContainer, null, getNodeIcon('workflow')),
                react__WEBPACK_IMPORTED_MODULE_0__.createElement(S.TitleName, null, 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: (_a = node.isLocked()) !== null && _a !== void 0 ? _a : false, onChange: event => handleDeletableNode('nodeDeletable', event) }))),
            react__WEBPACK_IMPORTED_MODULE_0__.createElement(PortsComponent, { node: node, engine: engine, app: app }))));
};
const ComponentLibraryNode = ({ node, engine, shell, app, handleDeletableNode }) => {
    var _a;
    const [showDescription, setShowDescription] = react__WEBPACK_IMPORTED_MODULE_0__.useState(false);
    const [descriptionStr, updateDescriptionStrState] = react__WEBPACK_IMPORTED_MODULE_0__.useState("");
    const elementRef = react__WEBPACK_IMPORTED_MODULE_0__.useRef(null);
    const portsNo = node.getInPorts().length + node.getOutPorts().length;
    const tooltipDescriptionRef = react__WEBPACK_IMPORTED_MODULE_0__.useRef(null);
    const [showParamDescriptionList, setShowParamDescriptionList] = react__WEBPACK_IMPORTED_MODULE_0__.useState(new Array(portsNo).fill(false));
    const [paramName, setParamName] = react__WEBPACK_IMPORTED_MODULE_0__.useState("");
    /**
     * creates a particular function for each component so that it can set only it's state
     * @param id
     */
    const setShowParamDescription = (id) => {
        return (newShowDescription) => {
            setShowParamDescriptionList(prevList => prevList.map((value, index) => index === id ? newShowDescription : false));
            setShowDescription(false);
        };
    };
    const setDescriptionStr = (paramName) => {
        return async (newDescriptionStr) => {
            updateDescriptionStrState(newDescriptionStr);
            setParamName(paramName);
            if (elementRef.current) {
                react_tooltip__WEBPACK_IMPORTED_MODULE_5___default().show(elementRef.current);
            }
        };
    };
    const handleDescription = async () => {
        setShowDescription(prevShowDescription => !prevShowDescription);
        setShowParamDescriptionList(new Array(portsNo).fill(false));
        setParamName("");
        getDescriptionStr();
        if (elementRef.current) {
            react_tooltip__WEBPACK_IMPORTED_MODULE_5___default().show(elementRef.current);
        }
    };
    // force MathJax to rescan DOM whenever the description changes and a description box is opened
    (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
        if (showDescription) {
            if (window.MathJax) {
                window.MathJax.typesetPromise()
                    .then(() => { })
                    .catch((err) => console.error("MathJax typeset failed: ", err));
            }
        }
    }, [showDescription]);
    const getDescriptionStr = () => {
        var _a;
        let dscrptStr = (_a = node['extras']['description']) !== null && _a !== void 0 ? _a : '***No description provided***';
        setDescriptionStr("")(dscrptStr);
    };
    const hideErrorTooltip = () => {
        delete node.getOptions().extras["tip"];
        node.getOptions().extras["borderColor"] = "rgb(0,192,255)";
    };
    return (react__WEBPACK_IMPORTED_MODULE_0__.createElement("div", { style: { position: "relative" } },
        (showDescription || showParamDescriptionList.reduce((prev, cur) => prev || cur, false)) && react__WEBPACK_IMPORTED_MODULE_0__.createElement("div", { className: "description-tooltip" },
            react__WEBPACK_IMPORTED_MODULE_0__.createElement("div", { "data-no-drag": true, style: { cursor: "default" }, ref: tooltipDescriptionRef },
                react__WEBPACK_IMPORTED_MODULE_0__.createElement("button", { type: "button", className: "close", "data-dismiss": "modal", "aria-label": "Close", onClick: async () => {
                        setShowDescription(false);
                        setShowParamDescriptionList(new Array(portsNo).fill(false));
                    } },
                    react__WEBPACK_IMPORTED_MODULE_0__.createElement("span", { "aria-hidden": "true" }, "\u00D7")),
                react__WEBPACK_IMPORTED_MODULE_0__.createElement(S.DescriptionName, { color: node.getOptions().color }, node.getOptions().name + " " + paramName),
                react__WEBPACK_IMPORTED_MODULE_0__.createElement("div", { className: "scrollable", onWheel: (e) => { e.stopPropagation(); e.currentTarget.scrollBy(e.deltaX, e.deltaY); } },
                    react__WEBPACK_IMPORTED_MODULE_0__.createElement("p", { className: "description-title" }, "Description:"),
                    react__WEBPACK_IMPORTED_MODULE_0__.createElement("div", { className: "description-container" },
                        react__WEBPACK_IMPORTED_MODULE_0__.createElement("div", { className: "markdown-body", dangerouslySetInnerHTML: { __html: (0,marked__WEBPACK_IMPORTED_MODULE_6__.marked)(descriptionStr !== null && descriptionStr !== void 0 ? descriptionStr : '') } }))))),
        react__WEBPACK_IMPORTED_MODULE_0__.createElement(S.Node, { onMouseDown: addGrabbing, onMouseUp: removeGrabbing, ref: elementRef, "data-tip": true, "data-for": node.getOptions().id, borderColor: node.getOptions().extras["borderColor"], "data-default-node-name": node.getOptions().name, selected: node.isSelected(), background: node.getOptions().color },
            react__WEBPACK_IMPORTED_MODULE_0__.createElement(S.Title, { background: node.getOptions().color },
                react__WEBPACK_IMPORTED_MODULE_0__.createElement(S.IconContainer, null, getNodeIcon(node['extras']['type'])),
                react__WEBPACK_IMPORTED_MODULE_0__.createElement(S.TitleName, null, 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: (_a = node.isLocked()) !== null && _a !== void 0 ? _a : false, onChange: event => handleDeletableNode('nodeDeletable', event) }),
                    react__WEBPACK_IMPORTED_MODULE_0__.createElement((react_toggle__WEBPACK_IMPORTED_MODULE_3___default()), { className: 'description', name: 'Description', checked: showDescription !== null && showDescription !== void 0 ? showDescription : false, onChange: handleDescription }))),
            react__WEBPACK_IMPORTED_MODULE_0__.createElement(PortsComponent, { node: node, engine: engine, app: app, showDescription: showParamDescriptionList, setShowDescription: setShowParamDescription, setDescriptionStr: setDescriptionStr })),
        (node.getOptions().extras["tip"] != undefined && node.getOptions().extras["tip"] != "") ?
            react__WEBPACK_IMPORTED_MODULE_0__.createElement((react_tooltip__WEBPACK_IMPORTED_MODULE_5___default()), { id: node.getOptions().id, clickable: true, place: "bottom", className: "error-tooltip", arrowColor: "rgba(255, 0, 0, .9)", delayHide: 100, delayUpdate: 50, getContent: () => {
                    var _a;
                    return 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: { __html: (0,marked__WEBPACK_IMPORTED_MODULE_6__.marked)((_a = node.getOptions().extras["tip"]) !== null && _a !== void 0 ? _a : '') } }),
                        react__WEBPACK_IMPORTED_MODULE_0__.createElement("button", { type: "button", className: "close", "data-dismiss": "modal", "aria-label": "Close", onClick: hideErrorTooltip },
                            react__WEBPACK_IMPORTED_MODULE_0__.createElement("span", { "aria-hidden": "true" }, "\u00D7")));
                }, overridePosition: ({ left, top }) => {
                    const currentNode = 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 (!shell.leftCollapsed) {
                        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 = engine.getRelativePoint(newPositionX, newPositionY);
                    left = tooltipPosition.x;
                    top = tooltipPosition.y;
                    return { top, left };
                } })
            : null));
};
class CustomNodeWidget extends react__WEBPACK_IMPORTED_MODULE_0__.Component {
    constructor() {
        super(...arguments);
        this.portsNo = this.props.node.getInPorts().length + this.props.node.getOutPorts().length;
        this.tooltipDescriptionRef = react__WEBPACK_IMPORTED_MODULE_0__.createRef();
        this.handleDeletableNode = (key, event) => {
            this.setState({
                [key]: event.target.checked ? this.props.node.setLocked(true) : this.props.node.setLocked(false),
            });
        };
        this.handleOnChangeCanvas = () => {
            this.props.engine.fireEvent({}, 'onChange');
        };
    }
    render() {
        const { node, engine, app, shell } = this.props;
        if (node['extras']['type'] === 'comment') {
            return react__WEBPACK_IMPORTED_MODULE_0__.createElement(CommentNode, { node: node });
        }
        if (node.getOptions()["name"].startsWith('Literal') || node.getOptions()["name"].startsWith('Argument')) {
            return react__WEBPACK_IMPORTED_MODULE_0__.createElement(ParameterNode, { node: node, engine: engine, app: app });
        }
        if (node['extras']['type'] === 'xircuits_workflow') {
            return react__WEBPACK_IMPORTED_MODULE_0__.createElement(WorkflowNode, { node: node, engine: engine, app: app, handleDeletableNode: this.handleDeletableNode });
        }
        if (node.getOptions()["name"] === 'Start' || node.getOptions()["name"] === 'Finish') {
            return react__WEBPACK_IMPORTED_MODULE_0__.createElement(StartFinishNode, { node: node, engine: engine, app: app, handleDeletableNode: this.handleDeletableNode });
        }
        return react__WEBPACK_IMPORTED_MODULE_0__.createElement(ComponentLibraryNode, { node: node, engine: engine, shell: shell, app: app, handleDeletableNode: this.handleDeletableNode });
    }
}


/***/ }),

/***/ "./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 _port_CustomPortModel__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../port/CustomPortModel */ "./lib/components/port/CustomPortModel.js");

const DYNAMIC_PARAMETER_NODE_TYPES = [
    'dynalist', 'dynatuple'
];
class CustomDynaPortModel extends _port_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
        }
        // 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 {
            // strip compulsory notation [★] if not first dynaport
            port.varName = port.varName.replace(/★/g, '');
            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 */   S: () => (/* binding */ S),
/* harmony export */   symbolMap: () => (/* binding */ symbolMap)
/* 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 _emotion_styled__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @emotion/styled */ "webpack/sharing/consume/default/@emotion/styled/@emotion/styled?1fc9");
/* harmony import */ var _emotion_styled__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_emotion_styled__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _commands_CommandIDs__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../commands/CommandIDs */ "./lib/commands/CommandIDs.js");
/* harmony import */ var colorjs_io__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! colorjs.io */ "webpack/sharing/consume/default/colorjs.io/colorjs.io");
/* harmony import */ var colorjs_io__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(colorjs_io__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _WithToggle__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./WithToggle */ "./lib/components/port/WithToggle.js");






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;
		text-overflow: ellipsis;
		max-width: 40ch;
	`;
    S.SymbolContainer = (_emotion_styled__WEBPACK_IMPORTED_MODULE_2___default().div) `
		width: 15px;
		height: 15px;
		background: ${(p) => (p.selected ? 'oklch(1 0 0 / 0.5)' : 'oklch(50% 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;
		box-shadow: inset 0 2px 4px ${(p) => (p.selected ? 'rgb(0 0 0 / 0.05)' : 'rgb(0 0 0 / 0.01)')} ;
		border: 1px solid oklch(0 0 0 / 0.2);
		padding: 0 2px;
		margin: 2px 0;
		&:hover, &.hover {
			background: rgb(192, 255, 0);
			box-shadow:  ${(p) => p.selected ? '' : 'inset'} 0 4px 8px rgb(0 0 0 / 0.5);
		}
		
		&.attached {
			padding: 0 2px 0 3px;
			border-radius: 20px;
			border: 0;
			background: ${(p) => p.attachedColor};
			
			&:hover, &.hover {
				background: rgb(192, 255, 0);
				box-shadow:  ${(p) => p.selected ? '' : 'inset'} 0 4px 8px rgb(0 0 0 / 0.5);
			}
		}
	`;
    S.Symbol = (_emotion_styled__WEBPACK_IMPORTED_MODULE_2___default().div) `
		color: ${(p) => (p.selected ? 'black' : 'grey')};
		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: ${(p) => p.hasLinks ? 'oklch(1 0 0 / 0.5)' : 'oklch(50% 0 0 / 0.2)'};
		color: ${(p) => p.hasLinks ? 'oklch(0% 0 0 / 0.8)' : 'oklch(1 0 0 / 0.8)'};
		border: 1px solid oklch(0 0 0 / 0.2);
		border-radius: ${(p) => (p.isOutPort ? '20px 0px 0px 20px' : '0px 20px 20px 0px')} ;
		box-shadow: ${(p) => p.hasLinks ? '' : 'inset'}  0 2px 4px ${(p) => (p.hasLinks ? 'rgb(0 0 0 / 0.1)' : 'rgb(0 0 0 / 0.05)')} ;
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 0 2px;
		margin: 2px 0;
		&:hover, &.hover {
			background: rgb(192, 255, 0);
			box-shadow:  ${(p) => p.hasLinks ? '' : 'inset'} 0 4px 8px rgb(0 0 0 / 0.5);
		}
		& svg {
			stroke-width: 3;
			stroke: currentColor;
			fill: none;
			stroke-linecap: round;
			stroke-linejoin: round;
		}
		&.attached {
			padding: 0 2px 0 3px;
			border-radius: 20px;
			border: 0;
			background: ${(p) => p.attachedColor};
			&:hover, &.hover {
				background: rgb(192, 255, 0);
				box-shadow:  ${(p) => p.hasLinks ? '' : 'inset'} 0 4px 8px rgb(0 0 0 / 0.5);
			}
		}
	`;
})(S || (S = {}));
const PortLabel = ({ nodeType, port, description, setDescriptionStr, showDescription, setShowDescription }) => {
    const LITERAL_SECRET = "Literal Secret";
    let labelText = port.getOptions().label.replace('▶', '').trim();
    let attached = false;
    if (port.getOptions().in) {
        Object.values(port.links).forEach(link => {
            if (link['sourcePort']['parent']['name'].startsWith('Literal ') && link['sourcePort']['parent']['extras']['attached']) {
                attached = true;
                const label = link['sourcePort']['parent']['name'] === LITERAL_SECRET ? "*****" : link['sourcePort']['options']['label'];
                labelText += ": " + (label.length > 18 ? label.substring(0, 15) + "..." : label);
            }
        });
    }
    return (react__WEBPACK_IMPORTED_MODULE_0__.createElement(S.Label, { style: { textAlign: (!port.getOptions().in && port.getOptions().label === '▶') ? 'right' : 'left', cursor: attached ? 'pointer' : 'inherit' } },
        react__WEBPACK_IMPORTED_MODULE_0__.createElement(_WithToggle__WEBPACK_IMPORTED_MODULE_4__["default"], { renderToggleBeforeChildren: !port.getOptions().in, showDescription: showDescription, setShowDescription: setShowDescription, description: description, setDescriptionStr: setDescriptionStr(port.getOptions().label) }, nodeType === LITERAL_SECRET ? "*****" : labelText)));
};
const symbolMap = {
    "string": '" "',
    "int": ' 1',
    "float": '1.0',
    "boolean": '⊤⊥',
    "time.time": '𝘵',
    "list": '[ ]',
    "tuple": '( )',
    "dict": '{ }',
    "dynalist": '«[]»',
    "dynatuple": '«()»',
    "union": ' U',
    "secret": '🗝️',
    "chat": '🗨',
    "any": '[_]',
    "0": null,
    "flow": null
};
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('Union')) {
            portType = 'union';
        }
        if (portType in symbolMap) {
            symbolLabel = symbolMap[portType];
        }
        else {
            symbolLabel = '◎';
        }
        const isIn = !!this.props.port.getOptions().in;
        const hasLinks = Object.keys(this.props.port.getLinks()).length > 0;
        const isTrianglePort = this.props.port.getOptions().label.indexOf('▶') >= 0 &&
            /* Workaround for Arguments being set up as triangle ports in other places */
            !this.props.node['name'].match('Argument \(.+?\):');
        let dblClickHandler = () => { };
        let attachedColor = null;
        if (this.props.port.getOptions().in) {
            Object.values(this.props.port.links).forEach(link => {
                if (link['sourcePort']['parent']['name'].startsWith('Literal ') && link['sourcePort']['parent']['extras']['attached']) {
                    attachedColor = link['sourcePort']['parent']['options']['color'];
                    dblClickHandler = () => {
                        this.props.engine.getModel().clearSelection();
                        link['sourcePort']['parent'].setSelected(true);
                        this.props.app.commands.execute(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_5__.commandIDs.editNode);
                    };
                }
            });
        }
        if (attachedColor != null) {
            const color = new (colorjs_io__WEBPACK_IMPORTED_MODULE_3___default())(attachedColor);
            color.alpha = 0.75;
            color.oklch.c *= 1.2;
            const color1 = color.to('oklch').toString();
            color.oklch.c *= 1.2;
            color.oklch.l /= 2;
            const color2 = color.to('oklch').toString();
            attachedColor = `linear-gradient(${color1}, ${color2})`;
        }
        const port = (react__WEBPACK_IMPORTED_MODULE_0__.createElement(S.Port, { isOutPort: !isIn, hasLinks: hasLinks, className: attachedColor ? 'attached' : null, attachedColor: attachedColor }, !isTrianglePort ? null : (isIn ?
            react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", width: "12", height: "12", viewBox: "0 0 24 24" },
                react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", { stroke: "none", d: "M0 0h24v24H0z", fill: "none" }),
                react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", { d: "M3 12h12" }),
                react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", { d: "M11 8l4 4l-4 4" }),
                react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", { d: "M12 21a9 9 0 0 0 0 -18" })) : react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", width: "12", height: "12", viewBox: "0 0 24 24" },
            react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", { stroke: "none", d: "M0 0h24v24H0z", fill: "none" }),
            react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", { d: "M9 12h12" }),
            react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", { d: "M17 16l4 -4l-4 -4" }),
            react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", { d: "M12 3a9 9 0 1 0 0 18" })))));
        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, className: attachedColor ? 'attached' : null, attachedColor: attachedColor },
            react__WEBPACK_IMPORTED_MODULE_0__.createElement(S.Symbol, { isOutPort: isOutPort, selected: portHasLink }, symbolLabel)));
        const nodeType = this.props.node.getOptions().name;
        function escapeSelector(selector) {
            return selector.replace(/([!"#$%&'()*+,.\/:;<=>?@[\\\]^`{|}~])/g, '\\$1');
        }
        function addHover(port) {
            return (() => {
                var _a, _b, _c;
                for (let linksKey in port.getLinks()) {
                    (_a = document.querySelector(`g[data-linkid='${linksKey}']`)) === null || _a === void 0 ? void 0 : _a.classList.add("hover");
                    const model = port.getLinks()[linksKey];
                    if (model.getSourcePort() != null) {
                        const sourceNodeId = model.getSourcePort().getNode().getID();
                        const sourcePortName = escapeSelector(model.getSourcePort().getName());
                        (_b = document.querySelector(`div.port[data-nodeid="${sourceNodeId}"][data-name='${sourcePortName}']>div>div`)) === null || _b === void 0 ? void 0 : _b.classList.add("hover");
                    }
                    if (model.getTargetPort() != null) {
                        const targetNodeId = model.getTargetPort().getNode().getID();
                        const targetPortName = escapeSelector(model.getTargetPort().getName());
                        (_c = document.querySelector(`div.port[data-nodeid="${targetNodeId}"][data-name='${targetPortName}']>div>div`)) === null || _c === void 0 ? void 0 : _c.classList.add("hover");
                    }
                    if (attachedColor != null) {
                        if (model.getSourcePort() != null) {
                            Object.values(model.getSourcePort().getNode().getPorts()).forEach(p => {
                                Object.values(p.getLinks()).forEach(l => {
                                    var _a;
                                    if (model.getTargetPort() != null) {
                                        const linkedTargetNodeId = l.getTargetPort().getNode().getID();
                                        const linkedTargetPortName = escapeSelector(l.getTargetPort().getName());
                                        (_a = document.querySelector(`div.port[data-nodeid="${linkedTargetNodeId}"][data-name='${linkedTargetPortName}']>div>div`)) === null || _a === void 0 ? void 0 : _a.classList.add("hover");
                                    }
                                });
                            });
                        }
                    }
                }
            });
        }
        function removeHover(port) {
            return () => {
                var _a, _b, _c;
                for (let linksKey in port.getLinks()) {
                    (_a = document.querySelector(`g[data-linkid='${linksKey}']`)) === null || _a === void 0 ? void 0 : _a.classList.remove("hover");
                    const model = port.getLinks()[linksKey];
                    if (model.getSourcePort() != null) {
                        const sourceNodeId = model.getSourcePort().getNode().getID();
                        const sourcePortName = escapeSelector(model.getSourcePort().getName());
                        (_b = document.querySelector(`div.port[data-nodeid="${sourceNodeId}"][data-name='${sourcePortName}']>div>div`)) === null || _b === void 0 ? void 0 : _b.classList.remove("hover");
                    }
                    if (model.getTargetPort() != null) {
                        const targetNodeId = model.getTargetPort().getNode().getID();
                        const targetPortName = escapeSelector(model.getTargetPort().getName());
                        (_c = document.querySelector(`div.port[data-nodeid="${targetNodeId}"][data-name='${targetPortName}']>div>div`)) === null || _c === void 0 ? void 0 : _c.classList.remove("hover");
                    }
                    if (attachedColor != null) {
                        if (model.getSourcePort() != null) {
                            Object.values(model.getSourcePort().getNode().getPorts()).forEach(p => {
                                Object.values(p.getLinks()).forEach(l => {
                                    var _a;
                                    if (model.getTargetPort() != null) {
                                        const linkedTargetNodeId = l.getTargetPort().getNode().getID();
                                        const linkedTargetPortName = escapeSelector(l.getTargetPort().getName());
                                        (_a = document.querySelector(`div.port[data-nodeid="${linkedTargetNodeId}"][data-name='${linkedTargetPortName}']>div>div`)) === null || _a === void 0 ? void 0 : _a.classList.remove("hover");
                                    }
                                });
                            });
                        }
                    }
                }
            };
        }
        const label = react__WEBPACK_IMPORTED_MODULE_0__.createElement(PortLabel, { port: this.props.port, nodeType: nodeType, showDescription: this.props.showDescription, setShowDescription: this.props.setShowDescription, setDescriptionStr: this.props.setDescriptionStr, description: this.props.description });
        return (react__WEBPACK_IMPORTED_MODULE_0__.createElement(S.PortLabel, { onMouseOver: addHover(this.props.port), onMouseOut: removeHover(this.props.port), onDoubleClick: dblClickHandler },
            this.props.port.getOptions().in ? null : label,
            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("div", null, symbolLabel == null ? port : symbol)),
            this.props.port.getOptions().in ? label : null));
    }
}


/***/ }),

/***/ "./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', 'any', 'numpy.ndarray'
];
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 - source port
         * @param port - target 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 ${thisLabel} node to it.`;
                    targetPort.getNode().setSelected(true);
                    return false;
                }
            }
            // Use thisNodeModelType if sourceDataType is an empty string due to old workflow
            let sourceDataType = thisPort.dataType || thisNodeModelType;
            let targetDataType = targetPort.dataType;
            if (!targetPort.isTypeCompatible(sourceDataType, targetDataType)) {
                // if a list of types is provided for the port, parse it a bit to display it nicer
                if (targetDataType.includes('Union')) {
                    targetDataType = this.parseUnionPortType(targetDataType);
                }
                targetPort.getNode().getOptions().extras["borderColor"] = "red";
                targetPort.getNode().getOptions().extras["tip"] = `Incorrect data type. Port ${thisLabel} is of type *\`${targetDataType}\`*. You have provided type *\`${sourceDataType}\`*.`;
                targetPort.getNode().setSelected(true);
                return false;
            }
            this.removeErrorTooltip(this, targetPort);
            return true;
        };
        this.isParameterNode = (nodeModelType) => {
            return PARAMETER_NODE_TYPES.includes(nodeModelType);
        };
        // Helper function to parse Union types
        this.parseUnionType = (type) => {
            const unionMatch = type.match(/^Union\[(.*)\]$/);
            if (unionMatch) {
                return unionMatch[1].split(/[\|,]/).map(t => t.trim());
            }
            return [type];
        };
        // Helper function to map common types
        this.mapCommonTypes = (type) => {
            const typeMapping = {
                "str": "string",
                "bool": "boolean",
                "int": "integer",
            };
            return typeMapping[type] || type;
        };
        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.parseUnionPortType = (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(/[,|]/g, ' or '); // replace all commas and pipes with ' 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.getTargetPorts = () => {
            let port = this;
            return Object.values(port.getLinks()).map((link) => link.getTargetPort());
        };
        this.getTargetNodes = () => {
            let port = this;
            return Object.values(port.getLinks()).map((link) => link.getTargetPort().getNode());
        };
        this.getSourcePorts = () => {
            let port = this;
            return Object.values(port.getLinks()).map((link) => link.getSourcePort());
        };
        this.getSourceNodes = () => {
            let port = this;
            return Object.values(port.getLinks()).map((link) => link.getSourcePort().getNode());
        };
        this.varName = options.varName || options.label;
        this.portType = options.portType || "";
        this.dataType = options.dataType || "";
        this.extras = options.extras || {};
    }
    get description() {
        return this._description;
    }
    set description(value) {
        this._description = value;
    }
    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) {
        // No self connections allowed
        if (port === this)
            return false;
        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;
        }
        // Check if it's a triangle-to-triangle link
        if (this.options.label.includes('▶') || port.getOptions().label.includes('▶')) {
            if (!this.canTriangleLinkToTriangle(this, port)) {
                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.");
                return false;
            }
        }
        else {
            // Then check if it's a parameter link
            if (!this.canParameterLinkToPort(this, port)) {
                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(sourceDataType, targetDataType) {
        // Helper function to check type compatibility including Union types
        const checkTypeCompatibility = (sourceDataTypes, targetDataTypes) => {
            for (const sourceDataType of sourceDataTypes) {
                for (const targetDataType of targetDataTypes) {
                    if (sourceDataType === targetDataType || sourceDataType === 'any' || targetDataType === 'any') {
                        return true;
                    }
                    // Check if the sourceDataType exists in the compatibility map
                    if (CustomPortModel.typeCompatibilityMap.hasOwnProperty(sourceDataType)) {
                        // Get the array of compatible data types for sourceDataType
                        const compatibleDataTypes = CustomPortModel.typeCompatibilityMap[sourceDataType];
                        // Check if targetDataType is in the array of compatible types
                        if (compatibleDataTypes.includes(targetDataType)) {
                            return true;
                        }
                    }
                }
            }
            return false;
        };
        // Parse and map Union types
        const sourceDataTypes = this.parseUnionType(sourceDataType).map(this.mapCommonTypes);
        const targetDataTypes = this.parseUnionType(targetDataType).map(this.mapCommonTypes);
        // Check for direct compatibility or 'any' type
        if (checkTypeCompatibility(sourceDataTypes, targetDataTypes)) {
            return true;
        }
        // If none of the above checks pass, the types are incompatible
        return false;
    }
    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;
    }
}
CustomPortModel.typeCompatibilityMap = {
    "chat": ["list"],
    "secret": ["string", "int", "float"],
};



/***/ }),

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

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ WithToggle)
/* 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_toggle__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react-toggle */ "webpack/sharing/consume/default/react-toggle/react-toggle");
/* harmony import */ var react_toggle__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react_toggle__WEBPACK_IMPORTED_MODULE_1__);



function WithToggle(props) {
    const ref = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(null);
    const changeHandler = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)(async () => {
        await props.setShowDescription(!props.showDescription);
        await props.setDescriptionStr(props.description);
    }, [props.description, props.showDescription]);
    return (react__WEBPACK_IMPORTED_MODULE_0__.createElement("div", { ref: ref, className: "alignToggle" }, props.renderToggleBeforeChildren ?
        react__WEBPACK_IMPORTED_MODULE_0__.createElement(react__WEBPACK_IMPORTED_MODULE_0__.Fragment, null,
            props.description &&
                react__WEBPACK_IMPORTED_MODULE_0__.createElement((react_toggle__WEBPACK_IMPORTED_MODULE_1___default()), { className: 'description', name: 'Description', checked: props.showDescription, onChange: changeHandler }),
            react__WEBPACK_IMPORTED_MODULE_0__.createElement("span", { style: { display: "inline-block", paddingLeft: "0.3rem" } }, props.children))
        :
            react__WEBPACK_IMPORTED_MODULE_0__.createElement(react__WEBPACK_IMPORTED_MODULE_0__.Fragment, null,
                react__WEBPACK_IMPORTED_MODULE_0__.createElement("span", { style: { display: "inline-block", paddingRight: "0.3rem" } }, props.children),
                props.description &&
                    react__WEBPACK_IMPORTED_MODULE_0__.createElement((react_toggle__WEBPACK_IMPORTED_MODULE_1___default()), { className: 'description', name: 'Description', checked: props.showDescription, onChange: changeHandler }))));
}


/***/ }),

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

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   buildRemoteRunCommand: () => (/* binding */ buildRemoteRunCommand)
/* harmony export */ });
function buildRemoteRunCommand(path, config) {
    try {
        const command = config.formattedCommand;
        if (!command) {
            throw new Error("Command is required for remote execution.");
        }
        const envVariables = {
            '$PYTHON_PATH': path,
            '$XIRCUITS_PATH': path
        };
        let command_str = command + " " + path + " " + config['run_config_name']
            + " " + config['project']
            + " " + config['stage_out']
            + " " + config['filesystem']
            + " " + config['python']
            + " " + config['modules']
            + " " + config['libraries'];
        Object.keys(envVariables).forEach(key => {
            command_str = command_str.replace(new RegExp(`\\${key}`, 'g'), envVariables[key]);
        });
        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 Run Mode.\\n')\n";
        code_str += `print(f'[COMMAND]\\n{command_str}\\n')\n`;
        if (config.url) {
            code_str += `print('[URL]\\nPlease go to ${config.url} for more details\\n')\n`;
        }
        if (config.msg) {
            code_str += `print('[MSG]\\n${config.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);
        throw e;
    }
}


/***/ }),

/***/ "./lib/components/runner/RunOutput.js":
/*!********************************************!*\
  !*** ./lib/components/runner/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/components/runner/RunSwitcher.js":
/*!**********************************************!*\
  !*** ./lib/components/runner/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: "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: "remote-run" }, "Remote Run")));
        }));
    }
}


/***/ }),

/***/ "./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 */ "./node_modules/@projectstorm/react-canvas-core/dist/index.js");
/* 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 */ "./node_modules/@projectstorm/react-canvas-core/dist/index.js");
/* 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 */ "./node_modules/@projectstorm/react-canvas-core/dist/index.js");
/* 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 */ "./node_modules/@projectstorm/react-canvas-core/dist/index.js");

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/context-menu/CanvasContextMenu.js":
/*!***********************************************!*\
  !*** ./lib/context-menu/CanvasContextMenu.js ***!
  \***********************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   CanvasContextMenu: () => (/* binding */ CanvasContextMenu),
/* harmony export */   countVisibleMenuOptions: () => (/* binding */ countVisibleMenuOptions),
/* harmony export */   getMenuOptionsVisibility: () => (/* binding */ getMenuOptionsVisibility)
/* 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__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @projectstorm/react-diagrams */ "webpack/sharing/consume/default/@projectstorm/react-diagrams/@projectstorm/react-diagrams");
/* harmony import */ var _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _style_ContextMenu_css__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../style/ContextMenu.css */ "./style/ContextMenu.css");
/* harmony import */ var _commands_CommandIDs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../commands/CommandIDs */ "./lib/commands/CommandIDs.js");




class CanvasContextMenu extends react__WEBPACK_IMPORTED_MODULE_0__.Component {
    hideCanvasContextMenu() {
        //@ts-ignore
        this.props.engine.fireEvent({}, 'hidePanel');
    }
    ;
    render() {
        let models = this.props.engine.getModel().getSelectedEntities();
        let visibility = getMenuOptionsVisibility(models);
        const handleReloadNode = async () => {
            await this.props.app.commands.execute(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_3__.commandIDs.refreshComponentList);
            let loadPromise = await this.props.app.commands.execute(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_3__.commandIDs.reloadNode);
            await this.props.app.commands.execute(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_3__.commandIDs.triggerLoadingAnimation, { loadPromise,
                loadingMessage: 'Reloading node...', loadingDisplayDuration: 10000, showLoadingAfter: 10
            });
        };
        const handleAttachNode = async () => {
            await this.props.app.commands.execute(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_3__.commandIDs.attachNode);
            await this.props.app.commands.execute(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_3__.commandIDs.reloadNode);
        };
        const handleAllAttachNodes = async () => {
            await this.props.app.commands.execute(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_3__.commandIDs.attachAllNodes);
            await this.props.app.commands.execute(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_3__.commandIDs.reloadNode);
        };
        const handleDetachAllNodes = async () => {
            await this.props.app.commands.execute(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_3__.commandIDs.detachAllNodes);
            await this.props.app.commands.execute(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_3__.commandIDs.reloadNode);
        };
        return (react__WEBPACK_IMPORTED_MODULE_0__.createElement("div", { className: "context-menu", onClick: this.hideCanvasContextMenu.bind(this) },
            visibility.showCutCopyPaste && (react__WEBPACK_IMPORTED_MODULE_0__.createElement(react__WEBPACK_IMPORTED_MODULE_0__.Fragment, null,
                react__WEBPACK_IMPORTED_MODULE_0__.createElement("div", { className: "context-menu-option", onClick: () => this.props.app.commands.execute(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_3__.commandIDs.cutNode) }, "Cut"),
                react__WEBPACK_IMPORTED_MODULE_0__.createElement("div", { className: "context-menu-option", onClick: () => this.props.app.commands.execute(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_3__.commandIDs.copyNode) }, "Copy"),
                react__WEBPACK_IMPORTED_MODULE_0__.createElement("div", { className: "context-menu-option", onClick: () => this.props.app.commands.execute(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_3__.commandIDs.pasteNode) }, "Paste"))),
            visibility.showAttachNode && (react__WEBPACK_IMPORTED_MODULE_0__.createElement("div", { className: "context-menu-option", onClick: handleAttachNode }, "Attach")),
            visibility.showAttachAllNodes && (react__WEBPACK_IMPORTED_MODULE_0__.createElement("div", { className: "context-menu-option", onClick: handleAllAttachNodes }, "Attach Literals")),
            visibility.showDetachAllNodes && (react__WEBPACK_IMPORTED_MODULE_0__.createElement("div", { className: "context-menu-option", onClick: handleDetachAllNodes }, "Detach Literals")),
            visibility.showReloadNode && (react__WEBPACK_IMPORTED_MODULE_0__.createElement("div", { className: "context-menu-option", onClick: handleReloadNode }, "Reload Node")),
            visibility.showEdit && (react__WEBPACK_IMPORTED_MODULE_0__.createElement("div", { className: "context-menu-option", onClick: () => this.props.app.commands.execute(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_3__.commandIDs.editNode) }, "Edit")),
            react__WEBPACK_IMPORTED_MODULE_0__.createElement("div", { className: "context-menu-option", onClick: () => this.props.app.commands.execute(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_3__.commandIDs.openViewer) }, "Open Viewer"),
            visibility.showOpenScript && (react__WEBPACK_IMPORTED_MODULE_0__.createElement("div", { className: "context-menu-option", onClick: () => this.props.app.commands.execute(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_3__.commandIDs.openScript) }, "Open Script")),
            visibility.showopenXircuitsWorkflow && (react__WEBPACK_IMPORTED_MODULE_0__.createElement("div", { className: "context-menu-option", onClick: () => this.props.app.commands.execute(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_3__.commandIDs.openXircuitsWorkflow) }, "Open Workflow")),
            visibility.showDelete && (react__WEBPACK_IMPORTED_MODULE_0__.createElement("div", { className: "context-menu-option", onClick: () => this.props.app.commands.execute(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_3__.commandIDs.deleteEntity) }, "Delete")),
            visibility.showUndoRedo && (react__WEBPACK_IMPORTED_MODULE_0__.createElement(react__WEBPACK_IMPORTED_MODULE_0__.Fragment, null,
                react__WEBPACK_IMPORTED_MODULE_0__.createElement("div", { className: "context-menu-option", onClick: () => this.props.app.commands.execute(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_3__.commandIDs.undo) }, "Undo"),
                react__WEBPACK_IMPORTED_MODULE_0__.createElement("div", { className: "context-menu-option", onClick: () => this.props.app.commands.execute(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_3__.commandIDs.redo) }, "Redo"))),
            visibility.showAddComment && (react__WEBPACK_IMPORTED_MODULE_0__.createElement("div", { className: "context-menu-option", onClick: () => this.props.app.commands.execute(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_3__.commandIDs.addCommentNode, { nodePosition: this.props.nodePosition }) }, "Add Comment"))));
    }
}
function getMenuOptionsVisibility(models) {
    function isLiteralNode(node) {
        var _a, _b, _c;
        return (_c = (_b = (_a = node.getOptions()) === null || _a === void 0 ? void 0 : _a.name) === null || _b === void 0 ? void 0 : _b.startsWith("Literal ")) !== null && _c !== void 0 ? _c : false;
    }
    function isArgumentNode(node) {
        var _a, _b, _c;
        return (_c = (_b = (_a = node.getOptions()) === null || _a === void 0 ? void 0 : _a.name) === null || _b === void 0 ? void 0 : _b.startsWith("Argument ")) !== null && _c !== void 0 ? _c : false;
    }
    function isComponentNode(node) {
        return node instanceof _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_1__.NodeModel && !isLiteralNode(node) && !isArgumentNode(node);
    }
    function isConnected(node) {
        let outPorts = node.getOutPorts();
        let inPorts = node.getInPorts();
        return outPorts.some(port => Object.keys(port.getLinks()).length > 0) ||
            inPorts.some(port => Object.keys(port.getLinks()).length > 0);
    }
    function canAttachAllNodes(node) {
        let ports = node.getInPorts();
        return ports.some((port) => {
            var _a, _b;
            let sourceNode = port.getSourceNodes()[0];
            return ((_b = (_a = sourceNode === null || sourceNode === void 0 ? void 0 : sourceNode.getOptions()) === null || _a === void 0 ? void 0 : _a.extras) === null || _b === void 0 ? void 0 : _b.attached) === false;
        });
    }
    function canDetachAllNodes(node) {
        let ports = node.getInPorts();
        return ports.some((port) => {
            var _a, _b;
            let sourceNode = port.getSourceNodes()[0];
            return ((_b = (_a = sourceNode === null || sourceNode === void 0 ? void 0 : sourceNode.getOptions()) === null || _a === void 0 ? void 0 : _a.extras) === null || _b === void 0 ? void 0 : _b.attached) === true;
        });
    }
    function isXircuitsWorkflow(node) {
        var _a, _b, _c;
        return (_c = ((_b = (_a = node.getOptions()) === null || _a === void 0 ? void 0 : _a.extras) === null || _b === void 0 ? void 0 : _b.type) == 'xircuits_workflow') !== null && _c !== void 0 ? _c : false;
    }
    let isNodeSelected = models.some(model => model instanceof _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_1__.NodeModel);
    let isLinkSelected = models.some(model => model instanceof _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_1__.LinkModel);
    let literalNodes = models.filter(model => isLiteralNode(model));
    let parameterNodes = models.filter(model => !isComponentNode(model));
    let componentNodes = models.filter(model => isComponentNode(model));
    let isSingleParameterNodeSelected = parameterNodes.length === 1;
    let isSingleComponentNodeSelected = componentNodes.length === 1;
    let showReloadNode = isNodeSelected && componentNodes.length > 0;
    let showopenXircuitsWorkflow = isSingleComponentNodeSelected && models.some(model => isXircuitsWorkflow(model));
    let showAttachNode = literalNodes.length > 0 && literalNodes.some(model => isConnected(model));
    let showAttachAllNodes = componentNodes.some(model => canAttachAllNodes(model));
    let showDetachAllNodes = componentNodes.some(model => canDetachAllNodes(model));
    return {
        showCutCopyPaste: !models.length || isNodeSelected || isLinkSelected,
        showReloadNode: showReloadNode,
        showEdit: isSingleParameterNodeSelected,
        showOpenScript: isSingleComponentNodeSelected,
        showopenXircuitsWorkflow: showopenXircuitsWorkflow,
        showDelete: isNodeSelected || isLinkSelected || parameterNodes.length > 0,
        showUndoRedo: !models.length,
        showAddComment: !models.length,
        showAttachNode: showAttachNode,
        showAttachAllNodes: showAttachAllNodes,
        showDetachAllNodes: showDetachAllNodes
    };
}
function countVisibleMenuOptions(visibility) {
    let count = Object.values(visibility).filter(isVisible => isVisible).length;
    // Adjusting the count for grouped options
    if (visibility.showCutCopyPaste) {
        // Cut, Copy, and Paste are grouped
        count += 2; // Adding for Copy and Paste
    }
    if (visibility.showUndoRedo) {
        // Undo and Redo are grouped
        count += 1; // Adding for Redo
    }
    return count;
}


/***/ }),

/***/ "./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 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?1fc9");
/* 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");
/* harmony import */ var _tray_library_Component__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../tray_library/Component */ "./lib/tray_library/Component.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 [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__.ComponentList)();
        // 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)(() => {
        fetchComponentList();
    }, []);
    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()) || (val.docstring && val.docstring.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/TrayContextMenu.js":
/*!*********************************************!*\
  !*** ./lib/context-menu/TrayContextMenu.js ***!
  \*********************************************/
/***/ ((__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 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_dom__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react-dom */ "webpack/sharing/consume/default/react-dom");
/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react_dom__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _server_handler__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../server/handler */ "./lib/server/handler.js");
/* harmony import */ var _components_runner_RunOutput__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../components/runner/RunOutput */ "./lib/components/runner/RunOutput.js");
/* harmony import */ var _style_ContextMenu_css__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../style/ContextMenu.css */ "./style/ContextMenu.css");
/* harmony import */ var _tray_library_ComponentLibraryConfig__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../tray_library/ComponentLibraryConfig */ "./lib/tray_library/ComponentLibraryConfig.js");
/* harmony import */ var _commands_CommandIDs__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../commands/CommandIDs */ "./lib/commands/CommandIDs.js");
/* harmony import */ var _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @jupyterlab/ui-components */ "webpack/sharing/consume/default/@jupyterlab/ui-components");
/* harmony import */ var _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_3__);








const TrayContextMenu = ({ app, x, y, visible, libraryName, status, refreshTrigger, onClose }) => {
    const trayContextMenuRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(null);
    const [validOptions, setValidOptions] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)({
        showInFileBrowser: false,
        showReadme: false,
        showExample: false,
        showPageInNewTab: false
    });
    (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
        // Initialize all options as invalid
        setValidOptions({
            showInFileBrowser: false,
            showReadme: false,
            showExample: false,
            showPageInNewTab: false
        });
        const validateOptions = async () => {
            try {
                const libraryConfig = await (0,_tray_library_ComponentLibraryConfig__WEBPACK_IMPORTED_MODULE_4__.fetchLibraryConfig)(libraryName);
                setValidOptions({
                    showInFileBrowser: !!libraryConfig.local_path,
                    showReadme: await (0,_tray_library_ComponentLibraryConfig__WEBPACK_IMPORTED_MODULE_4__.buildLocalFilePath)(libraryName, 'readme') !== null,
                    showExample: await (0,_tray_library_ComponentLibraryConfig__WEBPACK_IMPORTED_MODULE_4__.buildLocalFilePath)(libraryName, 'default_example_path') !== null,
                    showPageInNewTab: !!libraryConfig.repository
                });
            }
            catch (error) {
                console.error('Error validating context menu options:', error);
            }
        };
        if (visible) {
            validateOptions();
        }
    }, [libraryName, visible]);
    const handleClickOutside = (event) => {
        if (trayContextMenuRef.current && !trayContextMenuRef.current.contains(event.target)) {
            onClose();
        }
    };
    (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
        document.addEventListener('click', handleClickOutside, true);
        return () => {
            document.removeEventListener('click', handleClickOutside, true);
        };
    }, []);
    // Context menu action handlers
    const handleInstall = async (libraryName, refreshTrigger) => {
        const userResponse = confirm(`Do you want to proceed with ${libraryName} library installation?`);
        if (userResponse) {
            try {
                // clone the repository
                const response = await (0,_server_handler__WEBPACK_IMPORTED_MODULE_5__.requestAPI)("library/fetch", {
                    body: JSON.stringify({ libraryName }),
                    method: 'POST',
                });
                if (response.status !== 'OK') {
                    throw new Error(response.message || 'Failed to fetch the library.');
                }
                const libraryConfig = await (0,_tray_library_ComponentLibraryConfig__WEBPACK_IMPORTED_MODULE_4__.fetchLibraryConfig)(libraryName);
                if (libraryConfig && libraryConfig.local_path) {
                    let code = (0,_components_runner_RunOutput__WEBPACK_IMPORTED_MODULE_6__.startRunOutputStr)();
                    code += `!pip install -r ${libraryConfig.local_path}/requirements.txt`;
                    app.commands.execute(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_7__.commandIDs.executeToOutputPanel, { code });
                    console.log(`${libraryName} library successfully installed.`);
                }
                else {
                    alert(`Library configuration not found for: ${libraryName}`);
                }
                refreshTrigger();
            }
            catch (error) {
                alert(`Failed to install ${libraryName}. Please check the console for more details.`);
                console.error(`Failed to install ${libraryName}:`, error);
            }
        }
    };
    const handleShowInFileBrowser = async (libraryName) => {
        try {
            const libraryConfig = await (0,_tray_library_ComponentLibraryConfig__WEBPACK_IMPORTED_MODULE_4__.fetchLibraryConfig)(libraryName);
            if (libraryConfig && libraryConfig.local_path) {
                await app.commands.execute('filebrowser:go-to-path', { path: libraryConfig.local_path });
            }
        }
        catch (error) {
            alert(`Failed to Show in File Browser: ${error}`);
        }
    };
    const handleShowReadme = async (libraryName) => {
        try {
            const readmePath = await (0,_tray_library_ComponentLibraryConfig__WEBPACK_IMPORTED_MODULE_4__.buildLocalFilePath)(libraryName, 'readme');
            if (readmePath) {
                await app.commands.execute('markdownviewer:open', { path: readmePath, options: { mode: 'split-right' } });
            }
        }
        catch (error) {
            alert('Failed to Show Readme: ' + error);
        }
    };
    const handleShowExample = async (libraryName) => {
        try {
            const examplePath = await (0,_tray_library_ComponentLibraryConfig__WEBPACK_IMPORTED_MODULE_4__.buildLocalFilePath)(libraryName, 'default_example_path');
            if (examplePath) {
                await app.commands.execute('docmanager:open', { path: examplePath });
                await app.commands.execute('filebrowser:activate', { path: examplePath });
                await app.commands.execute('filebrowser:go-to-path', { path: examplePath });
            }
        }
        catch (error) {
            alert('Failed to Show Example: ' + error);
        }
    };
    const handleShowPageInNewTab = async (libraryName) => {
        try {
            const libraryConfig = await (0,_tray_library_ComponentLibraryConfig__WEBPACK_IMPORTED_MODULE_4__.fetchLibraryConfig)(libraryName);
            if (libraryConfig && libraryConfig.repository) {
                window.open(libraryConfig.repository, '_blank');
            }
        }
        catch (error) {
            alert(`Failed to Open Page: ${error}`);
        }
    };
    if (!visible) {
        return null;
    }
    function addHoverClass(e) {
        e.currentTarget.classList.add("lm-mod-active");
    }
    function removeHoverClass(e) {
        e.currentTarget.classList.remove("lm-mod-active");
    }
    function Option(props) {
        const { onClick, label, icon } = props;
        const Icon = icon ? icon : 'span';
        return react__WEBPACK_IMPORTED_MODULE_0___default().createElement("li", { className: "lm-Menu-item", role: "menuitem", onMouseEnter: addHoverClass, onMouseLeave: removeHoverClass, onClick: () => { onClick(); onClose(); } },
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "lm-Menu-itemIcon" },
                react__WEBPACK_IMPORTED_MODULE_0___default().createElement(Icon, null)),
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "lm-Menu-itemLabel" }, label));
    }
    return react_dom__WEBPACK_IMPORTED_MODULE_1___default().createPortal(react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "lm-Menu sidebar-context-menu", ref: trayContextMenuRef, style: { position: "absolute", left: `${x + 5}px`, top: `${y}px`, zIndex: 1000 } },
        react__WEBPACK_IMPORTED_MODULE_0___default().createElement("ul", { className: "lm-Menu-content", role: "menu" }, status === 'remote' ? (react__WEBPACK_IMPORTED_MODULE_0___default().createElement((react__WEBPACK_IMPORTED_MODULE_0___default().Fragment), null,
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement(Option, { icon: _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_3__.downloadIcon.react, label: `Install ${libraryName}`, onClick: () => handleInstall(libraryName, refreshTrigger) }),
            validOptions.showPageInNewTab && (react__WEBPACK_IMPORTED_MODULE_0___default().createElement(Option, { icon: _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_3__.linkIcon.react, label: "Open Repository", onClick: () => handleShowPageInNewTab(libraryName) })))) : (react__WEBPACK_IMPORTED_MODULE_0___default().createElement((react__WEBPACK_IMPORTED_MODULE_0___default().Fragment), null,
            validOptions.showInFileBrowser && (react__WEBPACK_IMPORTED_MODULE_0___default().createElement(Option, { icon: _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_3__.folderIcon.react, label: "Show in File Explorer", onClick: () => handleShowInFileBrowser(libraryName) })),
            validOptions.showReadme && (react__WEBPACK_IMPORTED_MODULE_0___default().createElement(Option, { icon: _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_3__.textEditorIcon.react, label: "See Readme", onClick: () => handleShowReadme(libraryName) })),
            validOptions.showExample && (react__WEBPACK_IMPORTED_MODULE_0___default().createElement(Option, { icon: _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_3__.kernelIcon.react, label: "Show Example", onClick: () => handleShowExample(libraryName) })),
            validOptions.showPageInNewTab && (react__WEBPACK_IMPORTED_MODULE_0___default().createElement(Option, { icon: _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_3__.linkIcon.react, label: "Open Repository", onClick: () => handleShowPageInNewTab(libraryName) })))))), document.body);
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (TrayContextMenu);


/***/ }),

/***/ "./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?1fc9");
/* 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 _tray_library_AdvanceComponentLib__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../tray_library/AdvanceComponentLib */ "./lib/tray_library/AdvanceComponentLib.js");
/* harmony import */ var _commands_CommandIDs__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../commands/CommandIDs */ "./lib/commands/CommandIDs.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(_commands_CommandIDs__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(_commands_CommandIDs__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(_commands_CommandIDs__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?1fc9");
/* 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 dialog and the input isn't Literal Chat or the attached checkbox, force focus to submit button
            const dialogInput = dialog.node.getElementsByTagName('input')[0];
            if (dialogInput && !['messages', 'attachNode'].includes(dialogInput.name)) {
                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_ChatInput__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./input-dialogues/ChatInput */ "./lib/dialog/input-dialogues/ChatInput.js");
/* harmony import */ var _input_dialogues_SecretInput__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./input-dialogues/SecretInput */ "./lib/dialog/input-dialogues/SecretInput.js");
/* harmony import */ var _input_dialogues_VariableInput__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./input-dialogues/VariableInput */ "./lib/dialog/input-dialogues/VariableInput.js");
/* harmony import */ var _input_dialogues_ArgumentInput__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./input-dialogues/ArgumentInput */ "./lib/dialog/input-dialogues/ArgumentInput.js");
/* harmony import */ var _input_dialogues_EnumInput__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./input-dialogues/EnumInput */ "./lib/dialog/input-dialogues/EnumInput.js");











function inputDialog({ title, oldValue, type, inputType, attached, showAttachOption, possibleValues }) {
    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, attached: attached, showAttachOption: showAttachOption, possibleValues: possibleValues })),
        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, attached, showAttachOption, possibleValues }) => {
    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_TextAreaInput__WEBPACK_IMPORTED_MODULE_3__.TextAreaInput,
        list: _input_dialogues_TextAreaInput__WEBPACK_IMPORTED_MODULE_3__.TextAreaInput,
        tuple: _input_dialogues_TextAreaInput__WEBPACK_IMPORTED_MODULE_3__.TextAreaInput,
        variable: _input_dialogues_VariableInput__WEBPACK_IMPORTED_MODULE_6__.VariableInput,
        secret: _input_dialogues_SecretInput__WEBPACK_IMPORTED_MODULE_7__.SecretInput,
        chat: _input_dialogues_ChatInput__WEBPACK_IMPORTED_MODULE_8__.ChatInput,
        argument: _input_dialogues_ArgumentInput__WEBPACK_IMPORTED_MODULE_9__.ArgumentInput,
        enum: _input_dialogues_EnumInput__WEBPACK_IMPORTED_MODULE_10__.EnumInput,
        numpy: _input_dialogues_TextAreaInput__WEBPACK_IMPORTED_MODULE_3__.TextAreaInput,
    };
    const InputValueDialog = () => {
        const [attach, setAttach] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(attached || false);
        const InputComponent = inputComponents[inputType === 'textarea' ? inputType.toLowerCase() : type.toLowerCase()];
        // The `type` prop is now passed to all components
        const extraProps = { type, inputType, possibleValues };
        return InputComponent ? (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("form", { style: { display: 'flex', flexDirection: "column", gap: "1em" } },
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement(InputComponent, Object.assign({ title: title, oldValue: oldValue }, extraProps)),
            InputComponent === _input_dialogues_ArgumentInput__WEBPACK_IMPORTED_MODULE_9__.ArgumentInput || !showAttachOption ? null : (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("label", null,
                react__WEBPACK_IMPORTED_MODULE_0___default().createElement("input", { type: "checkbox", name: "attachNode", checked: attach, value: attach ? "on" : "off", onChange: () => setAttach(!attach) }),
                "Attach Node?")))) : null;
    };
    return react__WEBPACK_IMPORTED_MODULE_0___default().createElement(InputValueDialog, null);
};


/***/ }),

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

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   LocalRunDialog: () => (/* binding */ LocalRunDialog)
/* 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 _RunDialogComponents__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./RunDialogComponents */ "./lib/dialog/RunDialogComponents.js");


const LocalRunDialog = ({ childStringNodes, childBoolNodes, childIntNodes, childFloatNodes }) => {
    const [checked, setChecked] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(childBoolNodes.map(() => false));
    const handleChecked = (value, index) => {
        let newChecked = [...checked];
        newChecked[index] = value;
        setChecked(newChecked);
        console.log("Boolean change: ", newChecked);
    };
    const hasAnyArguments = childStringNodes.length > 0 ||
        childBoolNodes.length > 0 ||
        childIntNodes.length > 0 ||
        childFloatNodes.length > 0;
    if (!hasAnyArguments) {
        return null;
    }
    return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("form", null,
        react__WEBPACK_IMPORTED_MODULE_0___default().createElement("h3", { style: { marginTop: 0, marginBottom: 5 } }, "Arguments:"),
        childStringNodes.map((stringNode, i) => (react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_RunDialogComponents__WEBPACK_IMPORTED_MODULE_1__.StringInput, { key: `string-${i}`, name: stringNode, title: stringNode, oldValue: "", onChange: () => { } }))),
        childBoolNodes.map((boolNode, i) => (react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_RunDialogComponents__WEBPACK_IMPORTED_MODULE_1__.BooleanInput, { key: `bool-${i}`, name: boolNode, title: boolNode, oldValue: checked[i] ? "true" : "false", onChange: (value) => handleChecked(value, i) }))),
        childIntNodes.map((intNode, i) => (react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_RunDialogComponents__WEBPACK_IMPORTED_MODULE_1__.NumberInput, { key: `int-${i}`, name: intNode, title: intNode, oldValue: "0", type: "int", onChange: () => { } }))),
        childFloatNodes.map((floatNode, i) => (react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_RunDialogComponents__WEBPACK_IMPORTED_MODULE_1__.NumberInput, { key: `float-${i}`, name: floatNode, title: floatNode, oldValue: "0.00", type: "float", onChange: () => { } })))));
};


/***/ }),

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

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   NewLibraryInput: () => (/* binding */ NewLibraryInput),
/* harmony export */   newLibraryInputDialog: () => (/* binding */ newLibraryInputDialog)
/* 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_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 _formDialogwidget__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./formDialogwidget */ "./lib/dialog/formDialogwidget.js");
/* harmony import */ var react_textarea_autosize__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! react-textarea-autosize */ "webpack/sharing/consume/default/react-textarea-autosize/react-textarea-autosize");
/* harmony import */ var react_textarea_autosize__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(react_textarea_autosize__WEBPACK_IMPORTED_MODULE_2__);




function newLibraryInputDialog(props) {
    const { title } = props;
    return {
        title,
        body: (0,_formDialogwidget__WEBPACK_IMPORTED_MODULE_3__.formDialogWidget)(react__WEBPACK_IMPORTED_MODULE_0___default().createElement(NewLibraryInput, Object.assign({}, props))),
        buttons: [_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_1__.Dialog.cancelButton(), _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_1__.Dialog.okButton({ label: 'Submit' })],
        defaultButton: 1,
    };
}
const NewLibraryInput = ({ title, oldValue, libraries, oldComponentCode }) => {
    const [selectedLibrary, setSelectedLibrary] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(oldValue || '');
    const [customLibrary, setCustomLibrary] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)('');
    const [componentCode, setComponentCode] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(oldComponentCode || '');
    const handleLibraryChange = (event) => {
        const value = event.target.value;
        setSelectedLibrary(value);
        if (value === 'custom-option') {
            setCustomLibrary('');
        }
    };
    const handleCustomLibraryChange = (event) => {
        const value = event.target.value;
        setCustomLibrary(value);
    };
    const installedLibraries = libraries.filter(library => library.status === 'installed');
    const gridContainer = {
        display: 'grid',
        gridTemplateColumns: '1fr',
        gridGap: '10px',
        padding: '20px',
        width: '500px',
        marginLeft: 'auto',
        marginRight: 'auto',
    };
    const selectStyle = {
        display: 'block',
        width: '100%',
        paddingTop: '5px',
        paddingBottom: '5px',
    };
    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", { htmlFor: "library-select" }, "Component Save Location"),
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement("select", { id: "library-select", name: "library-select", value: selectedLibrary, onChange: handleLibraryChange, style: selectStyle, className: "jp-mod-styled" },
                react__WEBPACK_IMPORTED_MODULE_0___default().createElement("option", { value: "", disabled: true }, "Select a library"),
                installedLibraries.map(library => (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("option", { key: library.library_id, value: library.library_id }, library.library_id))),
                react__WEBPACK_IMPORTED_MODULE_0___default().createElement("option", { value: "custom-option" }, "Other (Specify Below)")),
            selectedLibrary === 'custom-option' && (react__WEBPACK_IMPORTED_MODULE_0___default().createElement((react__WEBPACK_IMPORTED_MODULE_0___default().Fragment), null,
                react__WEBPACK_IMPORTED_MODULE_0___default().createElement("input", { type: "text", name: "customLibrary", value: customLibrary, onChange: handleCustomLibraryChange, placeholder: "Enter library name", style: { width: '100%', marginBottom: '10px' }, className: "jp-mod-styled" }),
                react__WEBPACK_IMPORTED_MODULE_0___default().createElement("input", { type: "hidden", name: "selectedLibrary", value: customLibrary }))),
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement("label", { htmlFor: "component-code" }, "Component Code"),
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement((react_textarea_autosize__WEBPACK_IMPORTED_MODULE_2___default()), { id: "component-code", name: "component-code", minRows: 12, style: { width: 500, height: 200, fontSize: 12, marginBottom: '10px' }, value: componentCode, onChange: (e) => setComponentCode(e.target.value), placeholder: "Enter component code here", className: "jp-mod-styled" }))));
};


/***/ }),

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

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   RemoteRunDialog: () => (/* binding */ RemoteRunDialog)
/* 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_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 _RunDialogComponents__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./RunDialogComponents */ "./lib/dialog/RunDialogComponents.js");
/* harmony import */ var react_collapsed__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! react-collapsed */ "webpack/sharing/consume/default/react-collapsed/react-collapsed");
/* harmony import */ var react_collapsed__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(react_collapsed__WEBPACK_IMPORTED_MODULE_2__);




const RemoteRunDialog = ({ remoteRunTypes, remoteRunConfigs, lastConfig, childStringNodes, childBoolNodes, childIntNodes, childFloatNodes }) => {
    const [checkedState, setCheckedState] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)({});
    const [inputValues, setInputValues] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)({});
    const [remoteRunType, setRemoteRunType] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)("");
    const [remoteRunConfig, setRemoteRunConfig] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)("");
    const [command, setCommand] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)("");
    const [project, setProject] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)("");
    const [isMonitoringEnabled, setIsMonitoringEnabled] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(false);
    const [isStageOutEnabled, setIsStageOutEnabled] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(false);
    const [filesystem, setFilesystem] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)('PROJECT');
    const [python, setPython] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)('python3.11');
    const [modules, setModules] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)('Python');
    const [placeholders, setPlaceholders] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)([]);
    const [formattedCommand, setFormattedCommand] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)("");
    const [sectionsCollapsed, setSectionsCollapsed] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)({
        runType: false,
        runConfig: false,
        commandTemplate: false,
        arguments: false,
        placeholders: false,
        finalCommand: false
    });
    (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
        if (remoteRunTypes.length > 0) {
            setRemoteRunType(remoteRunTypes[0].run_type);
        }
        if (lastConfig) {
            setRemoteRunType(lastConfig.run_type);
            setRemoteRunConfig(lastConfig.run_config_name);
            setCommand(lastConfig.command);
            setProject(lastConfig.project);
            setIsMonitoringEnabled(false);
            setIsStageOutEnabled(false);
            const extractedPlaceholders = extractPlaceholders(lastConfig.command);
            setPlaceholders(extractedPlaceholders);
            setInputValues(prefillInputValues(lastConfig, extractedPlaceholders));
        }
    }, []);
    const handleChecked = (name, value) => {
        setCheckedState(prev => {
            const newState = Object.assign(Object.assign({}, prev), { [name]: value });
            console.log("Boolean change for", name, ":", newState[name]);
            return newState;
        });
    };
    const handleTypeChange = (event) => {
        const type = event.target.value;
        setRemoteRunType(type);
        setRemoteRunConfig("-");
        setCommand("");
        setProject("");
        setIsMonitoringEnabled(false);
        setIsStageOutEnabled(false);
        setPlaceholders([]);
        setInputValues({});
    };
    const handleConfigChange = (event) => {
        const configName = event.target.value;
        setRemoteRunConfig(configName);
        if (configName === "-") {
            setCommand("");
            setProject("");
            setIsMonitoringEnabled(false);
            setIsStageOutEnabled(false);
            setPlaceholders([]);
            setInputValues({});
        }
        else {
            const selectedConfig = remoteRunConfigs.find(config => config.run_config_name === configName);
            if (selectedConfig) {
                setCommand(selectedConfig.command);
                const extractedPlaceholders = extractPlaceholders(selectedConfig.command);
                setPlaceholders(extractedPlaceholders);
                setInputValues(prefillInputValues(selectedConfig, extractedPlaceholders));
            }
            if (configName === 'JUWELS') {
                setPython('python3.11');
            }
            else {
                setPython('python3.10');
            }
            setFilesystem('PROJECT');
            setModules('Python');
        }
    };
    const extractPlaceholders = (cmd) => {
        const matches = cmd.match(/{[^}]+}/g) || [];
        return matches.map(match => match.replace(/[{}]/g, ''));
    };
    const prefillInputValues = (config, placeholders) => {
        const newInputValues = {};
        placeholders.forEach(placeholder => {
            newInputValues[placeholder] = config[placeholder] || "";
        });
        return newInputValues;
    };
    const substituteCommand = (cmd, values) => {
        let substitutedCmd = cmd.replace(/{([^}]+)}/g, (_, key) => values[key] || `{${key}}`);
        // Append argument values
        const argumentValues = [
            ...childStringNodes,
            ...childBoolNodes,
            ...childIntNodes,
            ...childFloatNodes
        ].map(name => {
            if (childBoolNodes.includes(name)) {
                return checkedState[name] ? `--${name}` : '';
            }
            return inputValues[name] ? `--${name} ${inputValues[name]}` : '';
        }).filter(Boolean);
        if (argumentValues.length > 0) {
            substitutedCmd += ' ' + argumentValues.join(' ');
        }
        return substitutedCmd;
    };
    (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
        setFormattedCommand(substituteCommand(command, inputValues));
    }, [command, inputValues, checkedState]);
    const handleInputChange = (name, value) => {
        const newInputValues = Object.assign(Object.assign({}, inputValues), { [name]: value });
        setInputValues(newInputValues);
    };
    const toggleSection = (section) => {
        setSectionsCollapsed(prev => (Object.assign(Object.assign({}, prev), { [section]: !prev[section] })));
    };
    const renderCollapsibleSection = (title, content, section) => (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { style: styles.collapsibleSection },
        react__WEBPACK_IMPORTED_MODULE_0___default().createElement("h3", { onClick: () => toggleSection(section), style: styles.sectionHeader, onMouseEnter: (e) => {
                e.currentTarget.style.backgroundColor = styles.sectionHeaderHover.backgroundColor;
            }, onMouseLeave: (e) => {
                e.currentTarget.style.backgroundColor = styles.sectionHeader.backgroundColor;
            } },
            title,
            " ",
            sectionsCollapsed[section] ? '▼' : '▲'),
        !sectionsCollapsed[section] && react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { style: styles.sectionContent }, content)));
    const hasArguments = childStringNodes.length > 0 || childBoolNodes.length > 0 ||
        childIntNodes.length > 0 || childFloatNodes.length > 0;
    function Collapsible() {
        const { getCollapseProps, getToggleProps, isExpanded } = (0,react_collapsed__WEBPACK_IMPORTED_MODULE_2__.useCollapse)();
        return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "collapsible" },
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", Object.assign({ className: "header" }, getToggleProps()),
                isExpanded ? 'Advanced setup' : 'Advanced setup',
                react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "icon" },
                    react__WEBPACK_IMPORTED_MODULE_0___default().createElement("i", { className: 'fas fa-chevron-circle-' + (isExpanded ? 'up' : 'down') }))),
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", Object.assign({}, getCollapseProps()),
                react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", null,
                    "Filesystem:",
                    react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", null,
                        react__WEBPACK_IMPORTED_MODULE_0___default().createElement("input", { name: 'filesystem', defaultValue: filesystem, title: 'Filesystem to use on HPC for preparing the environment', style: { width: 300, fontSize: 13 } })),
                    "Python dir:",
                    react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", null,
                        react__WEBPACK_IMPORTED_MODULE_0___default().createElement("input", { name: 'python', defaultValue: python, title: 'Python directory to use on HPC', style: { width: 300, fontSize: 13 } })),
                    "Modules to load:",
                    react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", null,
                        react__WEBPACK_IMPORTED_MODULE_0___default().createElement("input", { name: 'modules', defaultValue: modules, title: 'Modules to load on HPC', style: { width: 300, fontSize: 13 } })),
                    "Libraries to install:",
                    react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", null,
                        react__WEBPACK_IMPORTED_MODULE_0___default().createElement("input", { name: 'libraries', defaultValue: 'tvb-ext-xircuits,tvb-data', title: 'Libraries to install on HPC', style: { width: 300, fontSize: 13 } }))))));
    }
    return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("form", null,
        react__WEBPACK_IMPORTED_MODULE_0___default().createElement("h2", null, "Remote Run"),
        renderCollapsibleSection('Available Run Type', (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { style: styles.select },
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_1__.HTMLSelect, { onChange: (e) => handleTypeChange(e), value: remoteRunType, "aria-label": 'Available Run Types', title: 'Select the run type', name: 'remoteRunType' }, remoteRunTypes.map((type, i) => (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("option", { id: type.id, key: `index-type-${i}`, value: type.run_type }, type.run_type)))))), 'runType'),
        renderCollapsibleSection('Available Run Config', (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { style: styles.select },
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_1__.HTMLSelect, { onChange: (e) => handleConfigChange(e), value: remoteRunConfig, "aria-label": 'Run Configuration', title: 'Select which config to run', name: 'remoteRunConfig' },
                react__WEBPACK_IMPORTED_MODULE_0___default().createElement("option", { value: "-" }, "-"),
                remoteRunConfigs.map((c, i) => (c.run_type === remoteRunType && (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("option", { id: c.id, key: `index-config-${i}`, value: c.run_config_name }, c.run_config_name))))))), "runConfig"),
        renderCollapsibleSection("Project", (react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_RunDialogComponents__WEBPACK_IMPORTED_MODULE_3__.TextAreaInput, { name: "project", title: "", oldValue: project, onChange: () => { } })), "project"),
        renderCollapsibleSection("Launch Monitoring HPC", (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", null,
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement("input", { type: 'checkbox', title: 'If checked, the HPC monitoring widget is opened up automatically in a new tab. This can be accessed from the Monitor HPC button as well.', name: 'monitoring', checked: isMonitoringEnabled, value: isMonitoringEnabled ? 'on' : 'off', onChange: (e) => setIsMonitoringEnabled(e.target.checked) }))), "launchHPC"),
        renderCollapsibleSection("Stage-out results", (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", null,
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement("input", { type: 'checkbox', title: 'If checked, the workflow waits for all HPC jobs to finish and stages-out the results. Otherwise, they can be downloaded manually from the HPC monitoring widget.', name: 'stage_out', checked: isStageOutEnabled, value: isStageOutEnabled ? 'on' : 'off', onChange: (e) => setIsStageOutEnabled(e.target.checked) }))), "launchHPC"),
        react__WEBPACK_IMPORTED_MODULE_0___default().createElement(Collapsible, null),
        renderCollapsibleSection("Command Template", (react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_RunDialogComponents__WEBPACK_IMPORTED_MODULE_3__.TextAreaInput, { name: "commandTemplate", title: "", oldValue: command, onChange: () => { }, readOnly: true })), "commandTemplate"),
        hasArguments && renderCollapsibleSection("Arguments", (react__WEBPACK_IMPORTED_MODULE_0___default().createElement((react__WEBPACK_IMPORTED_MODULE_0___default().Fragment), null,
            childStringNodes.map((name, index) => (react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_RunDialogComponents__WEBPACK_IMPORTED_MODULE_3__.StringInput, { key: `string-${index}`, name: name, title: name, oldValue: inputValues[name] || "", onChange: (value) => handleInputChange(name, value) }))),
            childBoolNodes.map((name, index) => (react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_RunDialogComponents__WEBPACK_IMPORTED_MODULE_3__.BooleanInput, { key: `bool-${index}`, name: name, title: name, oldValue: checkedState[name] ? "true" : "false", onChange: (value) => handleChecked(name, value) }))),
            childIntNodes.map((name, index) => (react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_RunDialogComponents__WEBPACK_IMPORTED_MODULE_3__.NumberInput, { key: `int-${index}`, name: name, title: name, oldValue: inputValues[name] || "0", type: "int", onChange: (value) => handleInputChange(name, value) }))),
            childFloatNodes.map((name, index) => (react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_RunDialogComponents__WEBPACK_IMPORTED_MODULE_3__.NumberInput, { key: `float-${index}`, name: name, title: name, oldValue: inputValues[name] || "0.00", type: "float", onChange: (value) => handleInputChange(name, value) }))))), "arguments"),
        placeholders.length > 0 && renderCollapsibleSection("Placeholders", (react__WEBPACK_IMPORTED_MODULE_0___default().createElement((react__WEBPACK_IMPORTED_MODULE_0___default().Fragment), null, placeholders.map((name, index) => (react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_RunDialogComponents__WEBPACK_IMPORTED_MODULE_3__.StringInput, { key: `placeholder-${index}`, name: name, title: name, oldValue: inputValues[name] || "", onChange: (value) => handleInputChange(name, value) }))))), "placeholders"),
        renderCollapsibleSection("Final Command", (react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_RunDialogComponents__WEBPACK_IMPORTED_MODULE_3__.TextAreaInput, { name: "formattedCommand", title: "", oldValue: formattedCommand, onChange: () => { } })), "finalCommand")));
};
const styles = {
    select: {
        width: '100%',
        height: 'auto',
    },
    collapsibleSection: {
        marginBottom: '10px',
    },
    sectionHeader: {
        backgroundColor: '#f0f0f0',
        padding: '10px',
        marginBottom: '0',
        borderBottom: '1px solid #ddd',
        cursor: 'pointer',
        userSelect: 'none',
    },
    sectionHeaderHover: {
        backgroundColor: '#e0e0e0',
    },
    sectionContent: {
        padding: '10px',
        border: '1px solid #ddd',
        borderTop: 'none',
    },
};


/***/ }),

/***/ "./lib/dialog/RunDialogComponents.js":
/*!*******************************************!*\
  !*** ./lib/dialog/RunDialogComponents.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 */   NumberInput: () => (/* binding */ NumberInput),
/* harmony export */   StringInput: () => (/* binding */ StringInput),
/* 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_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__);
/* harmony import */ var react_textarea_autosize__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! react-textarea-autosize */ "webpack/sharing/consume/default/react-textarea-autosize/react-textarea-autosize");
/* harmony import */ var react_textarea_autosize__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(react_textarea_autosize__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var react_numeric_input__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! react-numeric-input */ "webpack/sharing/consume/default/react-numeric-input/react-numeric-input");
/* harmony import */ var react_numeric_input__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(react_numeric_input__WEBPACK_IMPORTED_MODULE_3__);




const StringInput = ({ title, name, oldValue, onChange }) => {
    return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", null,
        react__WEBPACK_IMPORTED_MODULE_0___default().createElement("h4", null, title),
        react__WEBPACK_IMPORTED_MODULE_0___default().createElement("input", { name: name, style: { width: 400 }, defaultValue: oldValue, onChange: (e) => onChange(e.target.value) })));
};
const BooleanInput = ({ title, name, oldValue, onChange }) => {
    const [checked, setChecked] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(oldValue.toLowerCase() === 'true');
    const handleChecked = () => {
        const newValue = !checked;
        setChecked(newValue);
        onChange(newValue);
    };
    return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", null,
        react__WEBPACK_IMPORTED_MODULE_0___default().createElement("h4", null, title),
        react__WEBPACK_IMPORTED_MODULE_0___default().createElement((react_switch__WEBPACK_IMPORTED_MODULE_1___default()), { checked: checked, name: name, 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: name, value: checked ? 'True' : 'False' })));
};
const NumberInput = ({ title, name, oldValue, type, onChange }) => {
    return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", null,
        react__WEBPACK_IMPORTED_MODULE_0___default().createElement("h4", null, title),
        react__WEBPACK_IMPORTED_MODULE_0___default().createElement(react_numeric_input__WEBPACK_IMPORTED_MODULE_3__, { className: "form-control", name: name, value: oldValue, min: 0, type: "number", step: type === 'float' ? 0.1 : 1, precision: type === 'float' ? 2 : 0, mobile: true, onChange: (valueAsNumber, valueAsString) => onChange(valueAsString), style: { input: { width: 400 } } })));
};
const TextAreaInput = ({ title, name, oldValue, onChange, readOnly = false }) => {
    return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", null,
        react__WEBPACK_IMPORTED_MODULE_0___default().createElement("h4", null, title),
        react__WEBPACK_IMPORTED_MODULE_0___default().createElement((react_textarea_autosize__WEBPACK_IMPORTED_MODULE_2___default()), { name: name, defaultValue: oldValue, minRows: 5, style: { width: 400, fontSize: 12 }, onChange: (e) => onChange(e.target.value), readOnly: readOnly })));
};


/***/ }),

/***/ "./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((react__WEBPACK_IMPORTED_MODULE_0___default().Fragment), 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((react__WEBPACK_IMPORTED_MODULE_0___default().Fragment), 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((react__WEBPACK_IMPORTED_MODULE_0___default().Fragment), 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/EnumInput.js":
/*!*************************************************!*\
  !*** ./lib/dialog/input-dialogues/EnumInput.js ***!
  \*************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   EnumInput: () => (/* binding */ EnumInput)
/* 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 _components_common_Dropdown__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../components/common/Dropdown */ "./lib/components/common/Dropdown.js");


const EnumInput = ({ title, possibleValues }) => {
    return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { style: {
            paddingLeft: 5,
            paddingTop: 5,
            height: '10rem'
        } },
        react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_components_common_Dropdown__WEBPACK_IMPORTED_MODULE_1__["default"], { name: title, types: possibleValues })));
};


/***/ }),

/***/ "./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((react__WEBPACK_IMPORTED_MODULE_0___default().Fragment), 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((react__WEBPACK_IMPORTED_MODULE_0___default().Fragment), 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 getHeaderContent = (type) => {
    switch (type) {
        case 'string':
            return react__WEBPACK_IMPORTED_MODULE_0___default().createElement("h3", { style: { marginTop: 0, marginBottom: 5 } }, "Enter String Value (Without Quotes):");
        case 'dict':
            return react__WEBPACK_IMPORTED_MODULE_0___default().createElement((react__WEBPACK_IMPORTED_MODULE_0___default().Fragment), 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"));
        case 'tuple':
            return react__WEBPACK_IMPORTED_MODULE_0___default().createElement((react__WEBPACK_IMPORTED_MODULE_0___default().Fragment), 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\""));
        case 'list':
            return react__WEBPACK_IMPORTED_MODULE_0___default().createElement((react__WEBPACK_IMPORTED_MODULE_0___default().Fragment), 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\""));
        case 'numpy':
            return react__WEBPACK_IMPORTED_MODULE_0___default().createElement((react__WEBPACK_IMPORTED_MODULE_0___default().Fragment), null,
                react__WEBPACK_IMPORTED_MODULE_0___default().createElement("h3", { style: { marginTop: 0, marginBottom: 5 } }, "Enter Numpy Array Value:"),
                react__WEBPACK_IMPORTED_MODULE_0___default().createElement("h5", { style: { marginTop: 0, marginBottom: 5 } }, "For Example: np.array([2,3])"));
        default:
            return react__WEBPACK_IMPORTED_MODULE_0___default().createElement("h3", { style: { marginTop: 0, marginBottom: 5 } }, "Enter Value:");
    }
};
const TextAreaInput = ({ title, oldValue, type, inputType }) => {
    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((react__WEBPACK_IMPORTED_MODULE_0___default().Fragment), null,
        getHeaderContent(type),
        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/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((react__WEBPACK_IMPORTED_MODULE_0___default().Fragment), 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/CanvasInitializer.js":
/*!******************************************!*\
  !*** ./lib/helpers/CanvasInitializer.js ***!
  \******************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   createInitXircuits: () => (/* binding */ createInitXircuits)
/* 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 _tray_library_BaseComponentLib__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../tray_library/BaseComponentLib */ "./lib/tray_library/BaseComponentLib.js");
/* harmony import */ var _components_link_CustomLinkFactory__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../components/link/CustomLinkFactory */ "./lib/components/link/CustomLinkFactory.js");
/* harmony import */ var _components_node_CustomNodeFactory__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../components/node/CustomNodeFactory */ "./lib/components/node/CustomNodeFactory.js");




function createInitXircuits(app, shell) {
    const diagramEngine = _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_0___default()({ registerDefaultZoomCanvasAction: false, registerDefaultDeleteItemsAction: false });
    // Create a new diagram model
    const activeModel = new _projectstorm_react_diagrams__WEBPACK_IMPORTED_MODULE_0__.DiagramModel();
    diagramEngine.getLinkFactories().registerFactory(new _components_link_CustomLinkFactory__WEBPACK_IMPORTED_MODULE_1__.ParameterLinkFactory());
    diagramEngine.getLinkFactories().registerFactory(new _components_link_CustomLinkFactory__WEBPACK_IMPORTED_MODULE_1__.TriangleLinkFactory());
    diagramEngine.getNodeFactories().registerFactory(new _components_node_CustomNodeFactory__WEBPACK_IMPORTED_MODULE_2__.CustomNodeFactory(app, shell));
    let startNode = (0,_tray_library_BaseComponentLib__WEBPACK_IMPORTED_MODULE_3__.BaseComponentLibrary)('Start');
    startNode.setPosition(100, 100);
    let finishNode = (0,_tray_library_BaseComponentLib__WEBPACK_IMPORTED_MODULE_3__.BaseComponentLibrary)('Finish');
    finishNode.setPosition(700, 100);
    activeModel.addAll(startNode, finishNode);
    diagramEngine.setModel(activeModel);
    let currentModel = diagramEngine.getModel().serialize();
    let jsonString = JSON.stringify(currentModel, null, 4);
    return jsonString;
}


/***/ }),

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

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   addHelpResources: () => (/* binding */ addHelpResources)
/* harmony export */ });
/* harmony import */ var _ui_components_icons__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../ui-components/icons */ "./lib/ui-components/icons.js");
/* harmony import */ var _commands_CommandIDs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../commands/CommandIDs */ "./lib/commands/CommandIDs.js");


function addHelpResources(app, mainMenu, translator) {
    const { commands } = app;
    const trans = translator.load('xircuits');
    const resources = [
        {
            text: trans.__('Xircuits Tutorials'),
            url: 'https://xircuits.io/docs/category/tutorials'
        },
        {
            text: trans.__('Xircuits Concepts'),
            url: 'https://xircuits.io/docs/category/explanations'
        },
        {
            text: trans.__('More Xircuits Documentation'),
            url: 'https://xircuits.io/docs/main/'
        },
    ];
    const xircuitsHelpGroup = [];
    resources.forEach((resource, index) => {
        const commandId = `${_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_0__.commandIDs.helpOpenResource}:${index}`;
        commands.addCommand(commandId, {
            label: resource.text,
            icon: _ui_components_icons__WEBPACK_IMPORTED_MODULE_1__.xircuitsIcon,
            execute: () => {
                window.open(resource.url);
            }
        });
        xircuitsHelpGroup.push({ command: commandId });
    });
    // Add the Xircuits help group to the beginning of the Help menu
    mainMenu.helpMenu.addGroup(xircuitsHelpGroup, -1);
}


/***/ }),

/***/ "./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) {
    const normalizedDataType = dataType.toLowerCase();
    let processedInput = "";
    let errorDetails = "";
    let exampleInput = "";
    let inputAsNumber;
    // Allow empty input for specific data types
    const allowedEmptyTypes = ["string", "secret", "chat", "list", "tuple", "dict"];
    if (input === "" && !allowedEmptyTypes.includes(normalizedDataType)) {
        alert("Input cannot be empty.");
        return false;
    }
    const formatError = (detail, example) => `Invalid ${dataType} input: ${detail} \nExample of a correct ${dataType} format: ${example}`;
    switch (normalizedDataType) {
        case "int":
        case "integer":
            inputAsNumber = Number(input); // Parse the input as a number which can handle scientific notation
            // Check if the parsed number is an integer and not NaN
            if (!Number.isInteger(inputAsNumber)) {
                errorDetails = `${input} is not an integer.`;
                exampleInput = "e.g. 3, -4, or 5e2 (which is 500 in scientific notation)";
                alert(formatError(errorDetails, exampleInput));
                return false;
            }
            processedInput = `${input}`;
            break;
        case "float":
            const floatVal = parseFloat(input);
            inputAsNumber = Number(input);
            // Check if the parsed float is a number and if it equals the input when also parsed as a number
            if (isNaN(floatVal) || floatVal !== inputAsNumber) {
                errorDetails = `${input} is not a float.`;
                exampleInput = "e.g. 3.14, 3.14e2, or 314e-2";
                alert(formatError(errorDetails, exampleInput));
                return false;
            }
            processedInput = `${input}`;
            break;
        case "string":
        case "numpy":
        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 === "" ? "[]" : `[${input}]`;
            break;
        case "dict":
            processedInput = input === "" ? "{}" : `{${input}}`;
            break;
        case "true":
        case "false":
        case "boolean":
            return true;
        case "libraryname":
            const validLibNameRegex = /^[a-zA-Z][_a-zA-Z0-9]*$/;
            if (!validLibNameRegex.test(input)) {
                errorDetails = `${input} is not a valid library name. It must start with a letter and can only contain letters, numbers, and underscores.`;
                exampleInput = "e.g., 'My_Library', 'dataCollection', 'Project1'";
                alert(formatError(errorDetails, exampleInput));
                return false;
            }
            processedInput = JSON.stringify(input);
            break;
        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/helpers/XircuitsCanvasWidget.js":
/*!*********************************************!*\
  !*** ./lib/helpers/XircuitsCanvasWidget.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 */   XircuitsCanvasWidget: () => (/* binding */ XircuitsCanvasWidget)
/* 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?1fc9");
/* 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};
		display: flex;
		width : 15360px; // Prevent Dev tool effects on smaller monitors  

		> * {
			height: 100%;
			min-height: 100%;
			width: 100%;
		}
		
    background-image: radial-gradient(oklch(40% 0% 0) 1px, transparent 0);
    background-size: 15px 15px;
    background-position: -19px -19px;
	`;
//}
class XircuitsCanvasWidget extends react__WEBPACK_IMPORTED_MODULE_0__.Component {
    render() {
        return (react__WEBPACK_IMPORTED_MODULE_0__.createElement(Container, { background: this.props.background || 'oklch(0.3 0.01 300 / 1)', color: this.props.color || 'rgba(255,255,255, 0.05)' }, this.props.children));
    }
}


/***/ }),

/***/ "./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 _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 _XircuitsFactory__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./XircuitsFactory */ "./lib/XircuitsFactory.js");
/* harmony import */ var _tray_library_Sidebar__WEBPACK_IMPORTED_MODULE_15__ = __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_22__ = __webpack_require__(/*! ./log/LogPlugin */ "./lib/log/LogPlugin.js");
/* harmony import */ var _server_handler__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./server/handler */ "./lib/server/handler.js");
/* harmony import */ var _kernel_panel__WEBPACK_IMPORTED_MODULE_21__ = __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_16__ = __webpack_require__(/*! ./commands/NodeActionCommands */ "./lib/commands/NodeActionCommands.js");
/* harmony import */ var _commands_LibraryActionCommands__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./commands/LibraryActionCommands */ "./lib/commands/LibraryActionCommands.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_13__ = __webpack_require__(/*! ./ui-components/icons */ "./lib/ui-components/icons.js");
/* harmony import */ var _helpers_CanvasInitializer__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./helpers/CanvasInitializer */ "./lib/helpers/CanvasInitializer.js");
/* harmony import */ var _helpers_HelpResources__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./helpers/HelpResources */ "./lib/helpers/HelpResources.js");
/* harmony import */ var _commands_CommandIDs__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./commands/CommandIDs */ "./lib/commands/CommandIDs.js");
/* harmony import */ var _jupyterlab_fileeditor__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @jupyterlab/fileeditor */ "webpack/sharing/consume/default/@jupyterlab/fileeditor");
/* harmony import */ var _jupyterlab_fileeditor__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_fileeditor__WEBPACK_IMPORTED_MODULE_10__);
/* harmony import */ var _jupyterlab_mainmenu__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! @jupyterlab/mainmenu */ "webpack/sharing/consume/default/@jupyterlab/mainmenu");
/* harmony import */ var _jupyterlab_mainmenu__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_mainmenu__WEBPACK_IMPORTED_MODULE_11__);























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_mainmenu__WEBPACK_IMPORTED_MODULE_11__.IMainMenu,
        _jupyterlab_translation__WEBPACK_IMPORTED_MODULE_6__.ITranslator,
        _jupyterlab_fileeditor__WEBPACK_IMPORTED_MODULE_10__.IEditorTracker,
    ],
    provides: IXircuitsDocTracker,
    activate: async (app, launcher, browserFactory, restorer, rendermime, docmanager, mainMenu, translator, editorTracker) => {
        console.log('Xircuits is activated!');
        // define MathJax configuration before loading the script
        if (!window.MathJax) {
            window.MathJax = {
                tex: {
                    inlineMath: [['$', '$'], ['\\(', '\\)']]
                },
                startup: {
                    typeset: false,
                    ready: () => {
                        console.log('MathJax is ready.');
                        window.MathJax.startup.defaultReady(); // ensure default settings are used in our custom ready method
                        window.MathJax.typesetPromise()
                            .then(() => { console.log('MathJax typesetting complete.'); })
                            .catch((err) => console.error('MathJax typeset failed: ', err));
                    }
                }
            };
        }
        // load MathJax from CDN
        const script = document.createElement('script');
        script.src = 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/3.2.2/es5/tex-mml-chtml.min.js';
        script.async = true;
        script.onload = () => { console.log('MathJax script loaded successfully.'); };
        script.onerror = () => { console.error('Failed to load MathJax.'); };
        document.head.appendChild(script);
        // Creating the widget factory to register it so the document manager knows about
        // our new DocumentWidget
        const widgetFactory = new _XircuitsFactory__WEBPACK_IMPORTED_MODULE_12__.XircuitsFactory({
            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_13__.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: _commands_CommandIDs__WEBPACK_IMPORTED_MODULE_14__.commandIDs.openDocManager,
            args: widget => ({
                path: widget.context.path,
                factory: FACTORY
            }),
            name: widget => widget.context.path
        });
        // 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_15__["default"], { app: app, factory: widgetFactory }));
        sidebarWidget.id = 'xircuits-component-sidebar';
        sidebarWidget.title.icon = _ui_components_icons__WEBPACK_IMPORTED_MODULE_13__.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_16__.addNodeActionCommands)(app, tracker, translator);
        // Additional commands for chat actions
        (0,_commands_LibraryActionCommands__WEBPACK_IMPORTED_MODULE_17__.addLibraryActionCommands)(app, tracker, translator, widgetFactory);
        // Additional main menu options for help resources
        (0,_helpers_HelpResources__WEBPACK_IMPORTED_MODULE_18__.addHelpResources)(app, mainMenu, translator);
        // Commands to emit WidgetFactory signals
        const emitSignal = (signal) => (args) => signal.emit(args);
        const signalConnections = [
            [_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_14__.commandIDs.saveXircuit,
                { label: "Save", icon: _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_8__.saveIcon, execute: emitSignal(widgetFactory.saveXircuitSignal) }],
            [_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_14__.commandIDs.runXircuit,
                { label: "Run Xircuits", icon: _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_8__.runIcon, execute: emitSignal(widgetFactory.runXircuitSignal) }],
            [_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_14__.commandIDs.compileXircuit,
                { execute: emitSignal(widgetFactory.compileXircuitSignal) }],
            [_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_14__.commandIDs.fetchRemoteRunConfig,
                { execute: emitSignal(widgetFactory.fetchRemoteRunConfigSignal) }],
            [_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_14__.commandIDs.lockXircuit,
                { execute: emitSignal(widgetFactory.lockNodeSignal) }],
            [_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_14__.commandIDs.triggerLoadingAnimation,
                { execute: emitSignal(widgetFactory.triggerLoadingAnimationSignal) }],
            [_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_14__.commandIDs.reloadAllNodes,
                { execute: emitSignal(widgetFactory.reloadAllNodesSignal) }],
            [_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_14__.commandIDs.toggleAllLinkAnimation,
                { execute: emitSignal(widgetFactory.toggleAllLinkAnimationSignal) }]
        ];
        signalConnections.forEach(([cmdId, def]) => app.commands.addCommand(cmdId, def));
        // Add a command for creating a new xircuits file.
        app.commands.addCommand(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_14__.commandIDs.createNewXircuit, {
            label: (args) => (args['isLauncher'] ? 'Xircuits File' : 'Create New Xircuits'),
            icon: _ui_components_icons__WEBPACK_IMPORTED_MODULE_13__.xircuitsIcon,
            caption: 'Create a new xircuits file',
            execute: async () => {
                const currentBrowser = browserFactory.tracker.currentWidget;
                if (!currentBrowser) {
                    console.error("No active file browser found.");
                    return;
                }
                const model = await app.commands
                    .execute(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_14__.commandIDs.newDocManager, {
                    path: currentBrowser.model.path,
                    type: "file",
                    ext: ".xircuits"
                });
                // get init SRD json
                const fileContent = (0,_helpers_CanvasInitializer__WEBPACK_IMPORTED_MODULE_19__.createInitXircuits)(app, app.shell);
                // Use the document manager to write to the file
                await app.serviceManager.contents.save(model.path, {
                    type: 'file',
                    format: 'text',
                    content: fileContent
                });
                await app.commands.execute(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_14__.commandIDs.openDocManager, {
                    path: model.path,
                    factory: FACTORY
                });
            }
        });
        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_20__.requestAPI)('file/compile', {
                    body: JSON.stringify(data),
                    method: 'POST',
                });
            }
            catch (reason) {
                console.error('Error on POST /xircuits/file/compile', data, reason);
            }
        }
        app.commands.addCommand(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_14__.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!`);
                    }
                    if (model_path.startsWith("xai_components/")) {
                        console.info(`File ${model_path} changed. Reloading components...`);
                        await app.commands.execute(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_14__.commandIDs.refreshComponentList);
                    }
                }
                else {
                    console.log(request["message"]);
                    alert("Failed to generate compiled code. Please check console logs for more details.");
                }
            }
        });
        // Auto-reload components when a component file changes
        editorTracker.widgetAdded.connect((sender, widget) => {
            const context = widget.context;
            if (context.path.endsWith('.py')) {
                context.fileChanged.connect(async () => {
                    if (context.path.startsWith("xai_components/")) {
                        console.info(`File ${context.path} changed. Reloading components...`);
                        await app.commands.execute(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_14__.commandIDs.refreshComponentList);
                    }
                });
            }
            if (context.path.endsWith('config.ini')) {
                context.fileChanged.connect(async () => {
                    if (context.path.startsWith(".xircuits/")) {
                        await app.commands.execute(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_14__.commandIDs.fetchRemoteRunConfig);
                    }
                });
            }
        });
        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_20__.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_21__.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();
        });
        // Execute command and display at output panel
        app.commands.addCommand(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_14__.commandIDs.executeToOutputPanel, {
            execute: async (args) => {
                const xircuitsLogger = new _log_LogPlugin__WEBPACK_IMPORTED_MODULE_22__.Log(app);
                // Create the panel if it does not exist
                if (!outputPanel || outputPanel.isDisposed) {
                    await createPanel();
                }
                outputPanel.session.ready.then(async () => {
                    const code = args['code'];
                    outputPanel.execute(code, xircuitsLogger);
                });
            },
        });
        app.commands.addCommand(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_14__.commandIDs.copyXircuitsToRoot, {
            label: 'Copy To Root Directory',
            isVisible: () => [...browserFactory.tracker.currentWidget.selectedItems()].length > 0,
            icon: _ui_components_icons__WEBPACK_IMPORTED_MODULE_13__.xircuitsIcon,
            execute: async () => {
                const selectedItems = Array.from(browserFactory.tracker.currentWidget.selectedItems());
                for (const xircuitsFile of selectedItems) {
                    const path = xircuitsFile.path;
                    const fileName = path.split('/').pop();
                    const rootPath = `/${fileName}`;
                    try {
                        await app.serviceManager.contents.copy(path, rootPath);
                        await app.commands.execute('filebrowser:go-to-path', { path: '/' });
                        // Open the file if needed, then prompt for renaming
                        const openedWidget = await app.commands.execute(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_14__.commandIDs.openDocManager, { path: rootPath, factory: FACTORY });
                        const fileContext = docmanager.contextForWidget(openedWidget);
                        if (fileContext) {
                            await (0,_jupyterlab_docmanager__WEBPACK_IMPORTED_MODULE_5__.renameDialog)(docmanager, fileContext);
                        }
                    }
                    catch (err) {
                        if (err.response && err.response.status === 400) {
                            alert(`Error: The file '${fileName}' already exists in the root directory.`);
                        }
                        else {
                            alert(`Error copying file '${fileName}': ${err.message || err}`);
                        }
                    }
                }
            }
        });
        app.contextMenu.addItem({
            command: _commands_CommandIDs__WEBPACK_IMPORTED_MODULE_14__.commandIDs.copyXircuitsToRoot,
            selector: '.jp-DirListing-item[data-file-type="xircuits"]',
        });
        app.commands.addCommand(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_14__.commandIDs.openXircuitsConfiguration, {
            label: 'Open Xircuits Configurations',
            icon: _ui_components_icons__WEBPACK_IMPORTED_MODULE_13__.xircuitsIcon,
            execute: async () => {
                const configPath = `.xircuits/config.ini`;
                try {
                    // Check if the file exists first
                    await app.serviceManager.contents.get(configPath);
                    // If we reach here, the file exists, so we can try to open it
                    await docmanager.openOrReveal(configPath);
                }
                catch (error) {
                    if (error.response && error.response.status === 404) {
                        alert('Xircuits configuration file not found. Check if it exists or enable hidden files when you launch Jupyter Lab.');
                    }
                    else {
                        alert(`Error accessing Xircuits configuration: ${error.message}`);
                    }
                }
            }
        });
        mainMenu.settingsMenu.addGroup([
            {
                command: _commands_CommandIDs__WEBPACK_IMPORTED_MODULE_14__.commandIDs.openXircuitsConfiguration,
            },
        ], -1);
        // Add a launcher item if the launcher is available.
        if (launcher) {
            launcher.add({
                command: _commands_CommandIDs__WEBPACK_IMPORTED_MODULE_14__.commandIDs.createNewXircuit,
                rank: 1,
                args: { isLauncher: true },
                category: 'Other'
            });
        }
    },
};
/**
 * Export the plugins as default.
 */
const plugins = [
    xircuits,
    _log_LogPlugin__WEBPACK_IMPORTED_MODULE_22__.logPlugin
];
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (plugins);


/***/ }),

/***/ "./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, XircuitsFactory, translator) {
        super();
        this._translator = translator || _jupyterlab_translation__WEBPACK_IMPORTED_MODULE_2__.nullTranslator;
        this._trans = this._translator.load('jupyterlab');
        this._XircuitsFactory = XircuitsFactory;
        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._sessionContextDialogs = new _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_0__.SessionContextDialogs();
        this.addWidget(this._outputarea);
        void this._sessionContext
            .initialize()
            .then(async (value) => {
            if (value) {
                await this._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 _server_handler__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../server/handler */ "./lib/server/handler.js");
/* harmony import */ var _commands_CommandIDs__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../commands/CommandIDs */ "./lib/commands/CommandIDs.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(_commands_CommandIDs__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(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_7__.commandIDs.outputMsg, {
                outputMsg: logMsg,
                level: msgType
            });
        }
        else {
            this.app.commands.execute(_commands_CommandIDs__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/siteUtils.js":
/*!**************************!*\
  !*** ./lib/siteUtils.js ***!
  \**************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   readDefaultSite: () => (/* binding */ readDefaultSite),
/* harmony export */   writeDefaultSite: () => (/* binding */ writeDefaultSite)
/* harmony export */ });
const defaultSiteKey = 'tvb-ext-xircuits:defaultSite';
function writeDefaultSite(site) {
    localStorage.setItem(defaultSiteKey, site);
}
function readDefaultSite() {
    return localStorage.getItem(defaultSiteKey);
}


/***/ }),

/***/ "./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_node_CustomNodeModel__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../components/node/CustomNodeModel */ "./lib/components/node/CustomNodeModel.js");
/* harmony import */ var _Component__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Component */ "./lib/tray_library/Component.js");


async function fetchNodeByName(name) {
    let componentList = [];
    componentList = await (0,_Component__WEBPACK_IMPORTED_MODULE_0__.ComponentList)();
    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_node_CustomNodeModel__WEBPACK_IMPORTED_MODULE_1__.CustomNodeModel({
        name: nodeData.class,
        color: nodeData.color,
        extras: {
            "type": nodeData.type,
            "path": nodeData.file_path,
            "description": nodeData["json_description"]["description"] || nodeData.docstring,
            "argumentDescriptions": nodeData["json_description"]["arguments"],
            "lineNo": nodeData.lineno,
            "has_widget": nodeData.has_widget,
            "template": nodeData.template,
            "options": nodeData.options
        }
    });
    if (node.extras.type != "Start") {
        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"
    };
    const argumentDescriptions = nodeData["json_description"]["arguments"];
    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;
        }
        const description = argumentDescriptions ? argumentDescriptions[name] || "" : "";
        switch (variable["kind"]) {
            case "InCompArg":
                node.addInPortEnhance({ label: `★${name}`, name: `parameter-${type}-${name}`, dataType: `${type}`, description: description });
                break;
            case "InArg":
                node.addInPortEnhance({ label: name, name: `parameter-${type}-${name}`, dataType: `${type}`, description: description });
                break;
            case "OutArg":
                node.addOutPortEnhance({ label: name, name: `parameter-out-${type}-${name}`, dataType: `${type}`, description: description });
                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/BaseComponentLib.js":
/*!**********************************************!*\
  !*** ./lib/tray_library/BaseComponentLib.js ***!
  \**********************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   BaseComponentLibrary: () => (/* binding */ BaseComponentLibrary)
/* harmony export */ });
/* harmony import */ var _components_node_CustomNodeModel__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../components/node/CustomNodeModel */ "./lib/components/node/CustomNodeModel.js");

function BaseComponentLibrary(nodeName) {
    if (nodeName === 'Start') {
        let node = new _components_node_CustomNodeModel__WEBPACK_IMPORTED_MODULE_0__.CustomNodeModel({ name: 'Start', color: 'rgb(255,102,102)', extras: { "type": "Start" } });
        node.addOutPortEnhance({ label: '▶', name: 'out-0' });
        return node;
    }
    if (nodeName === 'Finish') {
        let node = new _components_node_CustomNodeModel__WEBPACK_IMPORTED_MODULE_0__.CustomNodeModel({ name: 'Finish', color: 'rgb(255,102,102)', extras: { "type": "Finish" } });
        node.addInPortEnhance({ label: '▶', name: 'in-0' });
        node.addInPortEnhance({ label: 'outputs', name: 'parameter-dynalist-outputs', varName: 'outputs', dataType: 'dynalist' });
        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 */   ComponentList: () => (/* binding */ ComponentList),
/* harmony export */   fetchComponents: () => (/* binding */ fetchComponents),
/* harmony export */   refreshComponentListCache: () => (/* binding */ refreshComponentListCache)
/* 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__);



let componentsCache = {
    data: null
};
async function fetchComponents() {
    console.log("Fetching all components... this might take a while.");
    try {
        const componentsResponse = await (0,_server_handler__WEBPACK_IMPORTED_MODULE_2__.requestAPI)('components/');
        const components = componentsResponse["components"];
        const error_msg = componentsResponse["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' })]
            });
        }
        console.log("Fetch complete.");
        return components;
    }
    catch (error) {
        console.error('Failed to get components', error);
    }
}
async function ComponentList() {
    if (!componentsCache.data) {
        componentsCache.data = await fetchComponents();
    }
    return componentsCache.data;
}
async function refreshComponentListCache() {
    componentsCache.data = await fetchComponents();
}


/***/ }),

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

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ComponentLibraryConfig: () => (/* binding */ ComponentLibraryConfig),
/* harmony export */   buildLocalFilePath: () => (/* binding */ buildLocalFilePath),
/* harmony export */   fetchComponentLibraryConfig: () => (/* binding */ fetchComponentLibraryConfig),
/* harmony export */   fetchLibraryConfig: () => (/* binding */ fetchLibraryConfig),
/* harmony export */   refreshComponentLibraryConfigCache: () => (/* binding */ refreshComponentLibraryConfigCache),
/* harmony export */   reloadComponentLibraryConfig: () => (/* binding */ reloadComponentLibraryConfig)
/* harmony export */ });
/* harmony import */ var _server_handler__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../server/handler */ "./lib/server/handler.js");

let libraryConfigCache = {
    data: null
};
async function fetchComponentLibraryConfig() {
    try {
        const response = await (0,_server_handler__WEBPACK_IMPORTED_MODULE_0__.requestAPI)('library/get_config');
        if (response.status === 'OK' && response.config) {
            return response.config.libraries;
        }
        else {
            console.error('Failed to fetch remote libraries due to unexpected response:', response);
            return [];
        }
    }
    catch (error) {
        console.error('Failed to fetch remote libraries:', error);
        return [];
    }
}
async function reloadComponentLibraryConfig() {
    try {
        await (0,_server_handler__WEBPACK_IMPORTED_MODULE_0__.requestAPI)('library/reload_config', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            }
        });
    }
    catch (error) {
        console.error('Failed to reload config: ', error);
    }
}
async function ComponentLibraryConfig() {
    if (!libraryConfigCache.data) {
        libraryConfigCache.data = await fetchComponentLibraryConfig();
    }
    return libraryConfigCache.data;
}
async function refreshComponentLibraryConfigCache() {
    await reloadComponentLibraryConfig();
    libraryConfigCache.data = await fetchComponentLibraryConfig();
}
const fetchLibraryConfig = async (libName) => {
    try {
        let config = await ComponentLibraryConfig();
        const libraryConfig = config.find(library => library.library_id === libName.toUpperCase());
        if (!libraryConfig) {
            // console.log(`Library not found for: ${libName}`);
            return null;
        }
        return libraryConfig;
    }
    catch (error) {
        // console.log(`Failed to fetch library configuration: ${error}`);
        return null;
    }
};
const buildLocalFilePath = async (libName, fileKey) => {
    const libraryConfig = await fetchLibraryConfig(libName);
    if (libraryConfig && libraryConfig[fileKey]) {
        return `${libraryConfig.local_path}/${libraryConfig[fileKey]}`;
    }
    else if (libraryConfig) {
        // console.log(`File not found for: ${libName} (Key: ${fileKey})`);
    }
    return null;
};


/***/ }),

/***/ "./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 */   handleArgumentInput: () => (/* binding */ handleArgumentInput),
/* harmony export */   handleLiteralInput: () => (/* binding */ handleLiteralInput)
/* harmony export */ });
/* harmony import */ var _components_node_CustomNodeModel__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../components/node/CustomNodeModel */ "./lib/components/node/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', 'numpy.ndarray'];
const TYPE_ARGUMENTS = ['string', 'int', 'float', 'boolean', 'any'];
const SPECIAL_LITERALS = ['chat'];
async function handleLiteralInput(nodeName, nodeData, inputValue = "", type, title = "New Literal Input", nodeConnections = 0) {
    var _a;
    let attached = false;
    do {
        const isCreatingNewNode = nodeConnections === 0;
        type = type === 'numpy.ndarray' ? 'numpy' : type;
        let dialogOptions = (0,_dialog_LiteralInputDialog__WEBPACK_IMPORTED_MODULE_0__.inputDialog)({ title, oldValue: inputValue, type, attached: (((_a = nodeData.extras) === null || _a === void 0 ? void 0 : _a.attached) || false), showAttachOption: !isCreatingNewNode });
        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];
        }
        if (dialogResult.value.hasOwnProperty('attachNode')) {
            attached = dialogResult.value.attachNode == 'on';
        }
    } 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 extras = { "type": nodeData.type, attached };
    const node = new _components_node_CustomNodeModel__WEBPACK_IMPORTED_MODULE_3__.CustomNodeModel({ name: nodeName, color: nodeData.color, extras });
    node.addOutPortEnhance({ label: inputValue, name: 'out-0', dataType: nodeData.type });
    return node;
}
async function handleArgumentInput(nodeData, argumentTitle = "", oldValue = "", type = "argument") {
    const dialogOptions = (0,_dialog_LiteralInputDialog__WEBPACK_IMPORTED_MODULE_0__.inputDialog)({ title: argumentTitle, oldValue: oldValue, type: type, 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_node_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;
    let inputValue;
    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_node_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_node_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/NodePreview.js":
/*!*****************************************!*\
  !*** ./lib/tray_library/NodePreview.js ***!
  \*****************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   NodePreview: () => (/* binding */ NodePreview)
/* harmony export */ });
/* harmony import */ var _components_node_CustomNodeWidget__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../components/node/CustomNodeWidget */ "./lib/components/node/CustomNodeWidget.js");
/* harmony import */ var _components_port_CustomPortLabel__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../components/port/CustomPortLabel */ "./lib/components/port/CustomPortLabel.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__);



function NodePreview(props) {
    const { model } = props;
    let icon = (0,_components_node_CustomNodeWidget__WEBPACK_IMPORTED_MODULE_1__.getNodeIcon)(model.type === "xircuits_workflow" ? "workflow" : model.type);
    const PortComponent = (props) => {
        const isInPort = props.direction === "in";
        const isOutPort = props.direction === "out";
        const label = react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_components_port_CustomPortLabel__WEBPACK_IMPORTED_MODULE_2__.S.Label, { style: { textAlign: isInPort ? "left" : "right" } }, props.port.name);
        let port = null;
        let symbolLabel = null;
        if (["BaseComponent", "OutFlow"].includes(props.port.kind)) {
            port = react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_components_port_CustomPortLabel__WEBPACK_IMPORTED_MODULE_2__.S.Port, { isOutPort: isOutPort, hasLinks: false },
                react__WEBPACK_IMPORTED_MODULE_0___default().createElement("svg", { xmlns: "http://www.w3.org/2000/svg", width: "12", height: "12", viewBox: "0 0 24 24" },
                    react__WEBPACK_IMPORTED_MODULE_0___default().createElement("path", { stroke: "none", d: "M0 0h24v24H0z", fill: "none" }),
                    react__WEBPACK_IMPORTED_MODULE_0___default().createElement("path", { d: "M9 12h12" }),
                    react__WEBPACK_IMPORTED_MODULE_0___default().createElement("path", { d: "M17 16l4 -4l-4 -4" }),
                    react__WEBPACK_IMPORTED_MODULE_0___default().createElement("path", { d: "M12 3a9 9 0 1 0 0 18" })));
        }
        else if (props.port.kind === "InFlow") {
            port = react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_components_port_CustomPortLabel__WEBPACK_IMPORTED_MODULE_2__.S.Port, { isOutPort: isOutPort, hasLinks: false },
                react__WEBPACK_IMPORTED_MODULE_0___default().createElement("svg", { xmlns: "http://www.w3.org/2000/svg", width: "12", height: "12", viewBox: "0 0 24 24" },
                    react__WEBPACK_IMPORTED_MODULE_0___default().createElement("path", { stroke: "none", d: "M0 0h24v24H0z", fill: "none" }),
                    react__WEBPACK_IMPORTED_MODULE_0___default().createElement("path", { d: "M3 12h12" }),
                    react__WEBPACK_IMPORTED_MODULE_0___default().createElement("path", { d: "M11 8l4 4l-4 4" }),
                    react__WEBPACK_IMPORTED_MODULE_0___default().createElement("path", { d: "M12 21a9 9 0 0 0 0 -18" })));
        }
        else {
            // TODO: Get rid of the remapping by using compatible type names everywhere
            let type_name_remappings = {
                "bool": "boolean",
                "str": "string"
            };
            symbolLabel = _components_port_CustomPortLabel__WEBPACK_IMPORTED_MODULE_2__.symbolMap[type_name_remappings[props.port.type] || props.port.type] || "◎";
        }
        const symbol = react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_components_port_CustomPortLabel__WEBPACK_IMPORTED_MODULE_2__.S.SymbolContainer, { symbolType: symbolLabel, selected: false, isOutPort: isOutPort },
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_components_port_CustomPortLabel__WEBPACK_IMPORTED_MODULE_2__.S.Symbol, { isOutPort: isOutPort, selected: false }, symbolLabel));
        return react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_components_port_CustomPortLabel__WEBPACK_IMPORTED_MODULE_2__.S.PortLabel, null,
            isOutPort ? label : null,
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", null, port == null ? symbol : port),
            isInPort ? label : null);
    };
    const PortsComponent = () => {
        const inPorts = model.variables.filter(v => ["InArg", "InCompArg"].includes(v.kind));
        const outPorts = model.variables.filter(v => !["InArg", "InCompArg"].includes(v.kind));
        if (model.name.startsWith("Literal ") || model.name.startsWith("Get Argument ")) {
            let type = null;
            if (model.name.startsWith("Literal ")) {
                type = model.name.match(/^Literal (.+)$/)[1].toLowerCase();
            }
            else {
                type = model.name.match(/^Get Argument (.+) Name$/)[1].toLowerCase();
            }
            outPorts.unshift({ name: "", kind: "OutArg", type: type });
        }
        else {
            outPorts.unshift({ name: "", kind: "OutFlow" });
            if (model.type !== "Start") {
                inPorts.unshift({ name: "", kind: "InFlow" });
            }
        }
        return react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_components_node_CustomNodeWidget__WEBPACK_IMPORTED_MODULE_1__.S.Ports, null,
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_components_node_CustomNodeWidget__WEBPACK_IMPORTED_MODULE_1__.S.PortsContainer, null, inPorts.map(p => react__WEBPACK_IMPORTED_MODULE_0___default().createElement(PortComponent, { port: p, direction: "in", key: p.name }))),
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_components_node_CustomNodeWidget__WEBPACK_IMPORTED_MODULE_1__.S.PortsContainer, null, outPorts.map(p => react__WEBPACK_IMPORTED_MODULE_0___default().createElement(PortComponent, { port: p, direction: "out", key: p.name }))));
    };
    return react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { style: { maxWidth: "300px", margin: "auto" } },
        react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_components_node_CustomNodeWidget__WEBPACK_IMPORTED_MODULE_1__.S.Node, { borderColor: model.color, selected: false, background: null, className: model.type === "xircuits_workflow" ? "workflow-node" : null, style: { backgroundColor: "black" } },
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_components_node_CustomNodeWidget__WEBPACK_IMPORTED_MODULE_1__.S.Title, { background: model.color },
                icon ? react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_components_node_CustomNodeWidget__WEBPACK_IMPORTED_MODULE_1__.S.IconContainer, null, icon) : null,
                react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_components_node_CustomNodeWidget__WEBPACK_IMPORTED_MODULE_1__.S.TitleName, null, model.name)),
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement(PortsComponent, 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_9__ = __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 react_dom__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react-dom */ "webpack/sharing/consume/default/react-dom");
/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react_dom__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?1fc9");
/* harmony import */ var _emotion_styled__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_emotion_styled__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _TrayItemWidget__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./TrayItemWidget */ "./lib/tray_library/TrayItemWidget.js");
/* harmony import */ var _TrayWidget__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./TrayWidget */ "./lib/tray_library/TrayWidget.js");
/* harmony import */ var react_accessible_accordion__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! react-accessible-accordion */ "webpack/sharing/consume/default/react-accessible-accordion/react-accessible-accordion");
/* harmony import */ var react_accessible_accordion__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(react_accessible_accordion__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _context_menu_TrayContextMenu__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../context-menu/TrayContextMenu */ "./lib/context-menu/TrayContextMenu.js");
/* harmony import */ var _style_ContextMenu_css__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../style/ContextMenu.css */ "./style/ContextMenu.css");
/* harmony import */ var _ComponentLibraryConfig__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./ComponentLibraryConfig */ "./lib/tray_library/ComponentLibraryConfig.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__);
/* harmony import */ var _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @jupyterlab/ui-components */ "webpack/sharing/consume/default/@jupyterlab/ui-components");
/* harmony import */ var _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _commands_CommandIDs__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../commands/CommandIDs */ "./lib/commands/CommandIDs.js");
/* harmony import */ var _NodePreview__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./NodePreview */ "./lib/tray_library/NodePreview.js");
















const Body = (_emotion_styled__WEBPACK_IMPORTED_MODULE_2___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_2___default().div) `
    display: flex;
    flex-grow: 1;
    flex-wrap: wrap;
    max-height: auto;
    'border-top': '4px solid #dfe2e5'
`;
async function fetchComponent(componentList) {
    let headers = Array.from(new Set(componentList.map(x => x.category)));
    let parameterComponentList = [];
    let libraryComponentList = [];
    let displayHeaderList = [];
    for (let headerIndex = 0; headerIndex < headers.length; headerIndex++) {
        const currentHeader = headers[headerIndex];
        if (currentHeader === 'ADVANCED' || currentHeader === 'GENERAL') {
            parameterComponentList.push(currentHeader);
        }
        else {
            libraryComponentList.push(currentHeader);
        }
    }
    libraryComponentList.sort();
    if (parameterComponentList.length !== 0) {
        parameterComponentList.sort((a, b) => a < b ? 1 : a > b ? -1 : 0);
        headers = [...parameterComponentList, ...libraryComponentList];
    }
    for (const header of headers) {
        const componentsUnderHeader = componentList.filter(component => component.category === header);
        const headerDetails = componentsUnderHeader.map(component => ({
            category: component.category,
            file_path: component.file_path,
            package_name: component.package_name
        }));
        displayHeaderList.push({
            task: header,
            id: displayHeaderList.length + 1,
            components: headerDetails
        });
    }
    return displayHeaderList;
}
function Sidebar(props) {
    const app = props.app;
    const factory = props.factory;
    const [componentList, setComponentList] = react__WEBPACK_IMPORTED_MODULE_0___default().useState([]);
    const [category, setCategory] = react__WEBPACK_IMPORTED_MODULE_0___default().useState([]);
    const [remoteLibList, setRemoteLibList] = 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 [displayNodesInLibrary, setDisplayNodesInLibrary] = react__WEBPACK_IMPORTED_MODULE_0___default().useState(() => {
        const initial = localStorage.getItem("displayNodesInLibrary");
        if (initial) {
            return JSON.parse(initial);
        }
        else {
            return true;
        }
    });
    let searchDelay = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(null);
    let handleOnChange = (event) => {
        if (searchDelay.current != null) {
            clearTimeout(searchDelay.current);
        }
        searchDelay.current = setTimeout(() => {
            searchDelay.current = null;
            setSearchTerm(event.target.value);
        }, 150);
    };
    function handleSearchOnClick() {
        setSearchTerm(searchTerm);
    }
    const fetchComponentList = async () => {
        await (0,_ComponentLibraryConfig__WEBPACK_IMPORTED_MODULE_8__.refreshComponentLibraryConfigCache)();
        // get the component list
        let component_list = await (0,_Component__WEBPACK_IMPORTED_MODULE_9__.ComponentList)();
        // get the header from the components
        let component_library_name = await fetchComponent(component_list);
        // to ensure the component list is empty before setting the component list
        if (component_list.length > 0) {
            setComponentList([]);
            setCategory([]);
        }
        const comparisonFunction = (a, b) => a.task.toUpperCase() > b.task.toUpperCase() ? 1 : -1;
        // this is needed because the linter sees component_list as a string[], but it is not
        // @ts-ignore
        component_list = component_list.sort(comparisonFunction);
        component_library_name = component_library_name.sort(comparisonFunction);
        setComponentList(component_list);
        setCategory(component_library_name);
        const libraryConfig = await (0,_ComponentLibraryConfig__WEBPACK_IMPORTED_MODULE_8__.ComponentLibraryConfig)();
        const remoteLibraries = libraryConfig.filter(library => library.status === "remote");
        setRemoteLibList(remoteLibraries);
    };
    (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
        if (!runOnce) {
            fetchComponentList();
            setRunOnce(true);
        }
    }, [category, componentList]);
    function handleRefreshOnClick() {
        (0,_Component__WEBPACK_IMPORTED_MODULE_9__.refreshComponentListCache)();
        fetchComponentList();
    }
    (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
        const refreshComponents = () => {
            handleRefreshOnClick();
        };
        factory.refreshComponentsSignal.connect(refreshComponents);
        const toggleDisplayNodes = () => {
            setDisplayNodesInLibrary((prevState) => {
                const newState = !prevState;
                localStorage.setItem("displayNodesInLibrary", JSON.stringify(newState));
                return newState;
            });
        };
        factory.toggleDisplayNodesInLibrary.connect(toggleDisplayNodes);
        // Return a cleanup function to unsubscribe
        return () => {
            factory.refreshComponentsSignal.disconnect(refreshComponents);
            factory.toggleDisplayNodesInLibrary.disconnect(toggleDisplayNodes);
        };
    }, []);
    (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]);
    (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
        react_tooltip__WEBPACK_IMPORTED_MODULE_5___default().rebuild();
    }, [componentList, searchTerm, { displayNodesInLibrary }]);
    const menu = new _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_7__.MenuSvg({ commands: app.commands });
    // Add commands to the menu
    menu.addItem({ command: _commands_CommandIDs__WEBPACK_IMPORTED_MODULE_10__.commandIDs.refreshComponentList });
    menu.addItem({
        command: _commands_CommandIDs__WEBPACK_IMPORTED_MODULE_10__.commandIDs.createNewComponentLibrary,
        args: { componentCode: exampleComponent }
    });
    menu.addItem({ type: "separator" });
    menu.addItem({ command: _commands_CommandIDs__WEBPACK_IMPORTED_MODULE_10__.commandIDs.toggleDisplayNodesInLibrary });
    function showMenu(e) {
        const bbox = e.currentTarget.getBoundingClientRect();
        menu.open(bbox.x, bbox.bottom);
    }
    function matchesHeader(componentVal, searchTerm) {
        return componentVal.task.toLowerCase().includes(searchTerm.toLowerCase());
    }
    function matchesDocString(componentVal, searchTerm) {
        return componentVal.docstring && componentVal.docstring.toLowerCase().includes(searchTerm.toLowerCase());
    }
    // Function to map components
    const mapComponents = (components, searchTerm) => {
        let found = components;
        if (searchTerm !== "") {
            found = components.filter((componentVal) => {
                if (searchTerm === "") {
                    return componentVal;
                }
                else if (matchesHeader(componentVal, searchTerm) || matchesDocString(componentVal, searchTerm)) {
                    return componentVal;
                }
            });
            found.sort((a, b) => {
                const aHeader = matchesHeader(a, searchTerm);
                const bHeader = matchesHeader(b, searchTerm);
                if (aHeader && bHeader) {
                    return 0;
                }
                if (aHeader) {
                    return -1;
                }
                if (bHeader) {
                    return 1;
                }
                return 0;
            });
        }
        return found.map((componentVal, i) => (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { key: `component-${i}` },
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_TrayItemWidget__WEBPACK_IMPORTED_MODULE_11__.TrayItemWidget, { model: {
                    type: componentVal.type,
                    name: componentVal.task,
                    color: componentVal.color,
                    path: componentVal.file_path,
                    docstring: componentVal.docstring,
                    lineNo: componentVal.lineno,
                    variables: componentVal.variables
                }, name: componentVal.task, color: componentVal.color, app: props.app, path: componentVal.file_path, lineNo: componentVal.lineno, displayNode: displayNodesInLibrary }))));
    };
    // Function to map categories
    const mapCategories = (categories, components) => {
        return categories.map((libraryName, i) => (react__WEBPACK_IMPORTED_MODULE_0___default().createElement(react_accessible_accordion__WEBPACK_IMPORTED_MODULE_3__.AccordionItem, { key: `category-${i}` },
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement(react_accessible_accordion__WEBPACK_IMPORTED_MODULE_3__.AccordionItemHeading, null,
                react__WEBPACK_IMPORTED_MODULE_0___default().createElement(react_accessible_accordion__WEBPACK_IMPORTED_MODULE_3__.AccordionItemButton, null,
                    react__WEBPACK_IMPORTED_MODULE_0___default().createElement("span", null, libraryName["task"]),
                    libraryName['task'] !== 'GENERAL' && react__WEBPACK_IMPORTED_MODULE_0___default().createElement("a", { title: "More actions...", className: "button", onClick: (event) => showContextMenu(event, libraryName["task"], "installed") },
                        react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_7__.ellipsesIcon.react, null)))),
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement(react_accessible_accordion__WEBPACK_IMPORTED_MODULE_3__.AccordionItemPanel, null, mapComponents(components.filter(component => component["category"].toString().toUpperCase() === libraryName["task"].toString()), "")))));
    };
    const mapRemoteLibraries = () => {
        const sortedRemoteLibList = remoteLibList.sort((a, b) => a.library_id.localeCompare(b.library_id));
        return sortedRemoteLibList.map((lib, i) => (react__WEBPACK_IMPORTED_MODULE_0___default().createElement(react_accessible_accordion__WEBPACK_IMPORTED_MODULE_3__.AccordionItem, { key: `remote-lib-${i}` },
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement(react_accessible_accordion__WEBPACK_IMPORTED_MODULE_3__.AccordionItemHeading, null,
                react__WEBPACK_IMPORTED_MODULE_0___default().createElement(react_accessible_accordion__WEBPACK_IMPORTED_MODULE_3__.AccordionItemButton, { className: "accordion__button accordion__button--remote" },
                    react__WEBPACK_IMPORTED_MODULE_0___default().createElement("span", null, lib.library_id),
                    react__WEBPACK_IMPORTED_MODULE_0___default().createElement("a", { className: "button", title: "More actions...", onClick: (event) => showContextMenu(event, lib.library_id, 'remote') },
                        react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_7__.ellipsesIcon.react, null)))))));
    };
    const [contextMenuState, setContextMenuState] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)({
        visible: false,
        x: 0,
        y: 0,
        libraryName: null,
        status: 'installed'
    });
    const showContextMenu = (e, libraryName, status) => {
        e.preventDefault();
        e.stopPropagation();
        // Prevent context menu from appearing for GENERAL component library
        if (libraryName === 'GENERAL') {
            return;
        }
        const rect = e.target.getBoundingClientRect();
        setContextMenuState({
            visible: true,
            x: rect.right,
            y: rect.top,
            libraryName: libraryName,
            status: status
        });
    };
    const closeContextMenu = () => {
        setContextMenuState(Object.assign(Object.assign({}, contextMenuState), { visible: false }));
    };
    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_12__.TrayWidget, null,
                react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", null,
                    react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "sidebar-header" },
                        react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "search-input" },
                            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("input", { type: "text", name: "", placeholder: "SEARCH", className: "search-input__text-input", style: { width: "75%" }, onChange: handleOnChange })),
                        react__WEBPACK_IMPORTED_MODULE_0___default().createElement("a", { onClick: showMenu, className: "button", title: "More actions..." },
                            react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_7__.ellipsesIcon.react, null))),
                    searchTerm === "" ? (react__WEBPACK_IMPORTED_MODULE_0___default().createElement((react__WEBPACK_IMPORTED_MODULE_0___default().Fragment), null,
                        react__WEBPACK_IMPORTED_MODULE_0___default().createElement(react_accessible_accordion__WEBPACK_IMPORTED_MODULE_3__.Accordion, { allowMultipleExpanded: true, allowZeroExpanded: true }, mapCategories(category, componentList)),
                        react__WEBPACK_IMPORTED_MODULE_0___default().createElement("hr", { style: { marginTop: "10px", marginBottom: "10px" } }),
                        react__WEBPACK_IMPORTED_MODULE_0___default().createElement("h6", { style: { paddingLeft: "10px", margin: "0px", marginBottom: "8px" } }, "AVAILABLE FOR INSTALLATION"),
                        react__WEBPACK_IMPORTED_MODULE_0___default().createElement(react_accessible_accordion__WEBPACK_IMPORTED_MODULE_3__.Accordion, null, mapRemoteLibraries()))) : (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { style: { margin: "10px" } }, mapComponents(componentList, searchTerm)))))),
        react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_context_menu_TrayContextMenu__WEBPACK_IMPORTED_MODULE_13__["default"], { app: app, x: contextMenuState.x, y: contextMenuState.y, visible: contextMenuState.visible, libraryName: contextMenuState.libraryName, status: contextMenuState.status, refreshTrigger: handleRefreshOnClick, onClose: closeContextMenu }),
        react_dom__WEBPACK_IMPORTED_MODULE_1___default().createPortal(react__WEBPACK_IMPORTED_MODULE_0___default().createElement((react_tooltip__WEBPACK_IMPORTED_MODULE_5___default()), { id: "sidebar-tooltip", type: "dark", place: "right", effect: "solid", delayShow: 300, getContent: toolTipStr => {
                if (toolTipStr) {
                    const model = JSON.parse(toolTipStr).model;
                    if (!model.docstring && displayNodesInLibrary)
                        return null;
                    return react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { style: { maxWidth: "50vw", marginBottom: "20px" } },
                        model.docstring ?
                            react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { dangerouslySetInnerHTML: { __html: (0,marked__WEBPACK_IMPORTED_MODULE_6__.marked)(model.docstring) } }) : null,
                        displayNodesInLibrary ? null : react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_NodePreview__WEBPACK_IMPORTED_MODULE_14__.NodePreview, { model: model }));
                }
            } }), document.body)));
}
;
const exampleComponent = `from xai_components.base import InArg, OutArg, InCompArg, Component, BaseComponent, xai_component, dynalist

@xai_component(color='blue')
class ExampleComponent(Component):
    """Brief description of the component.
    
    ##### inPorts:
    - input_port (type): Description of input_port.

    ##### outPorts:
    - output_port (type): Description of output_port.

    """
    input_port: InArg[type]
    output_port: OutArg[type]
    
    def execute(self, ctx) -> None:
        input_port = self.input_port.value
        print(f'The input_port value is {input_port}.')
        self.output_port.value = input_port
`;


/***/ }),

/***/ "./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 */   TrayNode: () => (/* binding */ TrayNode)
/* 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?1fc9");
/* harmony import */ var _emotion_styled__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_emotion_styled__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _commands_CommandIDs__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../commands/CommandIDs */ "./lib/commands/CommandIDs.js");
/* harmony import */ var _ui_components_icons__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../ui-components/icons */ "./lib/ui-components/icons.js");
/* harmony import */ var _NodePreview__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./NodePreview */ "./lib/tray_library/NodePreview.js");
/* harmony import */ var react_tooltip__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! react-tooltip */ "webpack/sharing/consume/default/react-tooltip/react-tooltip");
/* harmony import */ var react_tooltip__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(react_tooltip__WEBPACK_IMPORTED_MODULE_2__);






const Tray = (_emotion_styled__WEBPACK_IMPORTED_MODULE_1___default().div) `
	color: var(--jp-ui-font-color0);
	font-family: Helvetica, Arial, sans-serif;
	padding: 7px;
	width: auto;
	margin: 7px;
	border: solid 1px ${(p) => p.color};
	border-radius: 5px;
	margin-bottom: 2px;
	cursor: pointer;
	display: flex;
	gap: 0.5em;
	overflow: hidden;
	align-items: center;
	
	& svg {
		height: 16px;
		width: 16px;
	}
	& > span {
		flex-grow: 1;
	}
`;
const TrayNode = (_emotion_styled__WEBPACK_IMPORTED_MODULE_1___default().div) `
	margin-bottom: 7px;
`;
class TrayItemWidget extends react__WEBPACK_IMPORTED_MODULE_0__.Component {
    render() {
        const getNodeIcon = (type) => {
            switch (type) {
                case 'Start':
                case 'startFinish':
                    return react__WEBPACK_IMPORTED_MODULE_0__.createElement(_ui_components_icons__WEBPACK_IMPORTED_MODULE_3__.startFinishComponentIcon.react, null);
                case 'workflow':
                case 'xircuits_workflow':
                    return react__WEBPACK_IMPORTED_MODULE_0__.createElement(_ui_components_icons__WEBPACK_IMPORTED_MODULE_3__.workflowComponentIcon.react, null);
                case 'branch':
                    return react__WEBPACK_IMPORTED_MODULE_0__.createElement(_ui_components_icons__WEBPACK_IMPORTED_MODULE_3__.branchComponentIcon.react, null);
                case 'function':
                    return react__WEBPACK_IMPORTED_MODULE_0__.createElement(_ui_components_icons__WEBPACK_IMPORTED_MODULE_3__.functionComponentIcon.react, null);
                case 'context_set':
                    return react__WEBPACK_IMPORTED_MODULE_0__.createElement(_ui_components_icons__WEBPACK_IMPORTED_MODULE_3__.setVariableComponentIcon.react, null);
                case 'context_get':
                    return react__WEBPACK_IMPORTED_MODULE_0__.createElement(_ui_components_icons__WEBPACK_IMPORTED_MODULE_3__.getVariableComponentIcon.react, null);
                case 'variable':
                    return react__WEBPACK_IMPORTED_MODULE_0__.createElement(_ui_components_icons__WEBPACK_IMPORTED_MODULE_3__.variableComponentIcon.react, null);
                // component libraries were typed as 'debug' before v1.12.
                case 'debug':
                case 'library_component':
                    return react__WEBPACK_IMPORTED_MODULE_0__.createElement(_ui_components_icons__WEBPACK_IMPORTED_MODULE_3__.componentLibIcon.react, null);
                default:
                    return null;
            }
        };
        const isComponent = !(this.props.model.name.startsWith("Literal ") || this.props.model.name.startsWith("Get Argument "));
        let toolTip = {};
        if (isComponent) {
            toolTip = {
                "data-for": "sidebar-tooltip",
                "data-tip": JSON.stringify({ model: this.props.model })
            };
        }
        let TrayComponent = Tray;
        if (this.props.displayNode) {
            TrayComponent = TrayNode;
        }
        return (react__WEBPACK_IMPORTED_MODULE_0__.createElement(TrayComponent, Object.assign({ color: this.props.color || "white", draggable: true, ref: ref => this.ref = ref, onDragStart: (event) => {
                react_tooltip__WEBPACK_IMPORTED_MODULE_2___default().hide(this.ref);
                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(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_4__.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(_commands_CommandIDs__WEBPACK_IMPORTED_MODULE_4__.commandIDs.openScript, {
                        nodePath: this.props.path,
                        nodeName: this.props.name,
                        nodeLineNo: this.props.lineNo
                    });
                }
                this.forceUpdate();
            }, className: "tray-item" }, toolTip), this.props.displayNode ? react__WEBPACK_IMPORTED_MODULE_0__.createElement(_NodePreview__WEBPACK_IMPORTED_MODULE_5__.NodePreview, { model: this.props.model }) : react__WEBPACK_IMPORTED_MODULE_0__.createElement(react__WEBPACK_IMPORTED_MODULE_0__.Fragment, null,
            getNodeIcon(this.props.model.type),
            react__WEBPACK_IMPORTED_MODULE_0__.createElement("span", null, 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?1fc9");
/* 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: var(--jp-layout-color0);
	color: var(--jp-ui-font-color0);
	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 */   branchComponentIcon: () => (/* binding */ branchComponentIcon),
/* harmony export */   breakpointIcon: () => (/* binding */ breakpointIcon),
/* harmony export */   changeFavicon: () => (/* binding */ changeFavicon),
/* harmony export */   componentLibIcon: () => (/* binding */ componentLibIcon),
/* harmony export */   debuggerIcon: () => (/* binding */ debuggerIcon),
/* harmony export */   functionComponentIcon: () => (/* binding */ functionComponentIcon),
/* harmony export */   getVariableComponentIcon: () => (/* binding */ getVariableComponentIcon),
/* harmony export */   infoIcon: () => (/* binding */ infoIcon),
/* harmony export */   lockIcon: () => (/* binding */ lockIcon),
/* harmony export */   nextIcon: () => (/* binding */ nextIcon),
/* harmony export */   reloadAllIcon: () => (/* binding */ reloadAllIcon),
/* harmony export */   revertIcon: () => (/* binding */ revertIcon),
/* harmony export */   setVariableComponentIcon: () => (/* binding */ setVariableComponentIcon),
/* harmony export */   startFinishComponentIcon: () => (/* binding */ startFinishComponentIcon),
/* harmony export */   toggleAnimationIcon: () => (/* binding */ toggleAnimationIcon),
/* harmony export */   variableComponentIcon: () => (/* binding */ variableComponentIcon),
/* harmony export */   workflowComponentIcon: () => (/* binding */ workflowComponentIcon),
/* 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_9__ = __webpack_require__(/*! ../../style/icons/component-library.svg */ "./style/icons/component-library.svg");
/* harmony import */ var _style_icons_reload_all_svg__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../style/icons/reload-all.svg */ "./style/icons/reload-all.svg");
/* harmony import */ var _style_icons_low_power_svg__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../../style/icons/low-power.svg */ "./style/icons/low-power.svg");
/* harmony import */ var _style_icons_branch_component_svg__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../../style/icons/branch-component.svg */ "./style/icons/branch-component.svg");
/* harmony import */ var _style_icons_workflow_component_svg__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../../style/icons/workflow-component.svg */ "./style/icons/workflow-component.svg");
/* harmony import */ var _style_icons_start_finish_component_svg__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../../style/icons/start-finish-component.svg */ "./style/icons/start-finish-component.svg");
/* harmony import */ var _style_icons_function_component_svg__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../../style/icons/function-component.svg */ "./style/icons/function-component.svg");
/* harmony import */ var _style_icons_set_variable_component_svg__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../../style/icons/set-variable-component.svg */ "./style/icons/set-variable-component.svg");
/* harmony import */ var _style_icons_get_variable_component_svg__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../../style/icons/get-variable-component.svg */ "./style/icons/get-variable-component.svg");
/* harmony import */ var _style_icons_variable_component_svg__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../../style/icons/variable-component.svg */ "./style/icons/variable-component.svg");
/* harmony import */ var _style_icons_info_svg__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../../style/icons/info.svg */ "./style/icons/info.svg?77f4");


















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__ });
const debuggerIcon = new _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_0__.LabIcon({ name: 'xircuits:debuggerIcon', svgstr: _style_icons_debugger_svg__WEBPACK_IMPORTED_MODULE_2__ });
const lockIcon = new _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_0__.LabIcon({ name: 'xircuits:lockIcon', svgstr: _style_icons_lock_svg__WEBPACK_IMPORTED_MODULE_3__ });
const breakpointIcon = new _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_0__.LabIcon({ name: 'xircuits:breakpointIcon', svgstr: _style_icons_breakpoint_svg__WEBPACK_IMPORTED_MODULE_4__ });
const nextIcon = new _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_0__.LabIcon({ name: 'xircuits:nextIcon', svgstr: _style_icons_next_svg__WEBPACK_IMPORTED_MODULE_5__ });
const revertIcon = new _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_0__.LabIcon({ name: 'xircuits:revertIcon', svgstr: _style_icons_revert_svg__WEBPACK_IMPORTED_MODULE_6__ });
const reloadAllIcon = new _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_0__.LabIcon({ name: 'xircuits:reloadAllIcon', svgstr: _style_icons_reload_all_svg__WEBPACK_IMPORTED_MODULE_7__ });
const toggleAnimationIcon = new _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_0__.LabIcon({ name: 'xircuits:toggleAnimationIcon', svgstr: _style_icons_low_power_svg__WEBPACK_IMPORTED_MODULE_8__ });
const componentLibIcon = new _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_0__.LabIcon({ name: 'xircuits:componentLibIcon', svgstr: _style_icons_component_library_svg__WEBPACK_IMPORTED_MODULE_9__ });
const branchComponentIcon = new _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_0__.LabIcon({ name: 'xircuits:BranchComponentIcon', svgstr: _style_icons_branch_component_svg__WEBPACK_IMPORTED_MODULE_10__ });
const workflowComponentIcon = new _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_0__.LabIcon({ name: 'xircuits:workflowComponentIcon', svgstr: _style_icons_workflow_component_svg__WEBPACK_IMPORTED_MODULE_11__ });
const startFinishComponentIcon = new _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_0__.LabIcon({ name: 'xircuits:startFinishComponentIcon', svgstr: _style_icons_start_finish_component_svg__WEBPACK_IMPORTED_MODULE_12__ });
const functionComponentIcon = new _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_0__.LabIcon({ name: 'xircuits:functionComponentIcon', svgstr: _style_icons_function_component_svg__WEBPACK_IMPORTED_MODULE_13__ });
const setVariableComponentIcon = new _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_0__.LabIcon({ name: 'xircuits:setVariableComponentIcon', svgstr: _style_icons_set_variable_component_svg__WEBPACK_IMPORTED_MODULE_14__ });
const getVariableComponentIcon = new _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_0__.LabIcon({ name: 'xircuits:getVariableComponentIcon', svgstr: _style_icons_get_variable_component_svg__WEBPACK_IMPORTED_MODULE_15__ });
const variableComponentIcon = new _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_0__.LabIcon({ name: 'xircuits:variableComponentIcon', svgstr: _style_icons_variable_component_svg__WEBPACK_IMPORTED_MODULE_16__ });
const infoIcon = new _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_0__.LabIcon({ name: 'xircuits:infoIcon', svgstr: _style_icons_info_svg__WEBPACK_IMPORTED_MODULE_17__ });
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);
}


/***/ }),

/***/ "./style/icons/branch-component.svg":
/*!******************************************!*\
  !*** ./style/icons/branch-component.svg ***!
  \******************************************/
/***/ ((module) => {

module.exports = "<svg  xmlns=\"http://www.w3.org/2000/svg\"  width=\"24\"  height=\"24\"  viewBox=\"0 0 24 24\"  fill=\"none\"  stroke=\"currentColor\"  stroke-width=\"2\"  stroke-linecap=\"round\"  stroke-linejoin=\"round\"  className=\"icon icon-tabler icons-tabler-outline icon-tabler-arrows-split\"><path stroke=\"none\" d=\"M0 0h24v24H0z\" fill=\"none\"/><path d=\"M21 17h-8l-3.5 -5h-6.5\" /><path d=\"M21 7h-8l-3.495 5\" /><path d=\"M18 10l3 -3l-3 -3\" /><path d=\"M18 20l3 -3l-3 -3\" /></svg>";

/***/ }),

/***/ "./style/icons/breakpoint.svg":
/*!************************************!*\
  !*** ./style/icons/breakpoint.svg ***!
  \************************************/
/***/ ((module) => {

module.exports = "<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/circuit-board-bg.svg":
/*!******************************************!*\
  !*** ./style/icons/circuit-board-bg.svg ***!
  \******************************************/
/***/ ((module) => {

module.exports = "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 304 304\" width=\"128\" height=\"128\">\n  <path\n     fill=\"oklch(100% 0 0 / 75%)\"\n     d=\"m 204.1,272 c 1.20825,-5.91917 9.89572,-5.01313 9.89572,1 0,6.01313 -8.68747,6.91917 -9.89572,1 H 82 v -2 z m 57.8,-46 c -1.20825,5.91917 -9.89572,5.01313 -9.89572,-1 0,-6.01313 8.68747,-6.91917 9.89572,-1 H 304 v 2 z m 0,16 c -1.20825,5.91917 -9.89572,5.01313 -9.89572,-1 0,-6.01313 8.68747,-6.91917 9.89572,-1 H 304 v 2 z m 6.2,-114 c 1.20825,-5.91917 9.89572,-5.01313 9.89572,1 0,6.01313 -8.68747,6.91917 -9.89572,1 h -86.2 c -1.20825,5.91917 -9.89572,5.01313 -9.89572,-1 0,-6.01313 8.68747,-6.91917 9.89572,-1 z m -70.2,-14 c -1.20825,5.91917 -9.89572,5.01313 -9.89572,-1 0,-6.01313 8.68747,-6.91917 9.89572,-1 h 86.2 c 1.20825,-5.91917 9.89572,-5.01313 9.89572,1 0,6.01313 -8.68747,6.91917 -9.89572,1 z M 194,220.1 c 5.91917,1.20825 5.01313,9.89572 -1,9.89572 -6.01313,0 -6.91917,-8.68747 -1,-9.89572 v -54.2 c -5.91917,-1.20825 -5.01313,-9.89572 1,-9.89572 6.01313,0 6.91917,8.68747 1,9.89572 z M 242,21.9 V 80 h 62 v 2 H 240 V 21.9 c -5.91917,-1.208245 -5.01313,-9.895719 1,-9.895719 6.01313,0 6.91917,8.687474 1,9.895719 z m 16,16 V 64 h 46 v 2 H 256 V 37.9 c -5.91917,-1.208245 -5.01313,-9.895719 1,-9.895719 6.01313,0 6.91917,8.687474 1,9.895719 z m -128,96 V 208 h 16 v 12.1 c 5.91917,1.20825 5.01313,9.89572 -1,9.89572 -6.01313,0 -6.91917,-8.68747 -1,-9.89572 V 210 h -16 v -76.1 c -5.91917,-1.20825 -5.01313,-9.89572 1,-9.89572 6.01313,0 6.91917,8.68747 1,9.89572 z M 124.1,112 c 1.20825,-5.91917 9.89572,-5.01313 9.89572,1 0,6.01313 -8.68747,6.91917 -9.89572,1 H 114 v 48 H 85.9 c -1.208245,5.91917 -9.895719,5.01313 -9.895719,-1 0,-6.01313 8.687474,-6.91917 9.895719,-1 H 112 v -48 z m -6.2,130 c -1.20825,5.91917 -9.89572,5.01313 -9.89572,-1 0,-6.01313 8.68747,-6.91917 9.89572,-1 H 176 v -74.1 c -5.91917,-1.20825 -5.01313,-9.89572 1,-9.89572 6.01313,0 6.91917,8.68747 1,9.89572 V 242 Z m -16,-64 c -1.20825,5.91917 -9.895719,5.01313 -9.895719,-1 0,-6.01313 8.687469,-6.91917 9.895719,-1 H 114 v 48 h 10.1 c 1.20825,-5.91917 9.89572,-5.01313 9.89572,1 0,6.01313 -8.68747,6.91917 -9.89572,1 H 112 V 178 Z M 66,284.1 c 5.919168,1.20825 5.013134,9.89572 -1,9.89572 -6.013134,0 -6.919168,-8.68747 -1,-9.89572 V 274 H 50 v 30 H 48 V 272 H 66 Z M 236.1,176 c 1.20825,-5.91917 9.89572,-5.01313 9.89572,1 0,6.01313 -8.68747,6.91917 -9.89572,1 H 226 v 94 h 48 v 32 h -2 v -30 h -48 v -98 z m 25.8,-30 c -1.20825,5.91917 -9.89572,5.01313 -9.89572,-1 0,-6.01313 8.68747,-6.91917 9.89572,-1 H 274 v 44.1 c 5.91917,1.20825 5.01313,9.89572 -1,9.89572 -6.01313,0 -6.91917,-8.68747 -1,-9.89572 V 146 Z m -64,96 c -1.20825,5.91917 -9.89572,5.01313 -9.89572,-1 0,-6.01313 8.68747,-6.91917 9.89572,-1 H 208 v -80 h 16 v -14 h -42.1 c -1.20825,5.91917 -9.89572,5.01313 -9.89572,-1 0,-6.01313 8.68747,-6.91917 9.89572,-1 H 226 v 18 h -16 v 80 z m 22.2,46 c 1.20825,-5.91917 9.89572,-5.01313 9.89572,1 0,6.01313 -8.68747,6.91917 -9.89572,1 H 98 v 14 H 96 V 288 Z M 242,149.9 V 160 h 16 v 34 h -16 v 62 h 48 v 48 h -2 v -46 h -48 v -66 h 16 v -30 h -16 v -12.1 c -5.91917,-1.20825 -5.01313,-9.89572 1,-9.89572 6.01313,0 6.91917,8.68747 1,9.89572 z M 117.9,98 c -1.20825,5.91917 -9.89572,5.01313 -9.89572,-1 0,-6.013134 8.68747,-6.919168 9.89572,-1 H 137 l 32,-32 h 39 V 21.9 c -5.91917,-1.208245 -5.01313,-9.895719 1,-9.895719 6.01313,0 6.91917,8.687474 1,9.895719 V 66 h -40.17 l -32,32 z m 28.1,90.1 c 5.91917,1.20825 5.01313,9.89572 -1,9.89572 -6.01313,0 -6.91917,-8.68747 -1,-9.89572 V 111.59 L 175.59,80 H 224 V 21.9 c -5.91917,-1.208245 -5.01313,-9.895719 1,-9.895719 6.01313,0 6.91917,8.687474 1,9.895719 V 82 H 176.41 L 146,112.41 Z m 16,32 c 5.91917,1.20825 5.01313,9.89572 -1,9.89572 -6.01313,0 -6.91917,-8.68747 -1,-9.89572 V 120.59 L 184.59,96 H 300.1 c 0.4006,-1.964289 1.93571,-3.499395 3.9,-3.9 v 2.07 c -2.67261,0.940174 -2.67261,4.719826 0,5.66 v 2.07 c -1.96429,-0.4006 -3.4994,-1.935711 -3.9,-3.9 H 185.41 L 162,121.41 Z M 277.9,50 c -1.20825,5.919168 -9.89572,5.013134 -9.89572,-1 0,-6.013134 8.68747,-6.919168 9.89572,-1 h 18.69 L 304,40.59 v 2.82 L 297.41,50 Z m -16,160 c -1.20825,5.91917 -9.89572,5.01313 -9.89572,-1 0,-6.01313 8.68747,-6.91917 9.89572,-1 H 288 v -71.41 l 16,-16 v 2.82 l -14,14 V 210 Z m -208,32 c -1.208245,5.91917 -9.895719,5.01313 -9.895719,-1 0,-6.01313 8.687474,-6.91917 9.895719,-1 H 64 V 217.41 L 40.59,194 H 21.9 c -1.208245,5.91917 -9.895719,5.01313 -9.895719,-1 0,-6.01313 8.687474,-6.91917 9.895719,-1 H 41.41 L 66,216.59 V 242 Z m 150.2,14 c 1.20825,-5.91917 9.89572,-5.01313 9.89572,1 0,6.01313 -8.68747,6.91917 -9.89572,1 H 96 V 201.4 L 56.6,162 H 37.9 c -1.208245,5.91917 -9.895719,5.01313 -9.895719,-1 0,-6.01313 8.687474,-6.91917 9.895719,-1 H 57.4 L 98,200.6 V 256 Z m -150.2,2 c -1.208245,5.91917 -9.895719,5.01313 -9.895719,-1 0,-6.01313 8.687474,-6.91917 9.895719,-1 H 80 V 209.41 L 48.59,178 H 21.9 c -1.208245,5.91917 -9.895719,5.01313 -9.895719,-1 0,-6.01313 8.687474,-6.91917 9.895719,-1 H 49.41 L 82,208.59 V 258 Z M 258,289 v 15 h -2 v -14 h -14 v 14 h -2 v -16 h 18 z M 80,272 h 2 v 32 h -2 z m 33,-172 c 4,0 4,-6 0,-6 -4,0 -4,6 0,6 z m 16,16 c 4,0 4,-6 0,-6 -4,0 -4,6 0,6 z m 0,16 c 4,0 4,-6 0,-6 -4,0 -4,6 0,6 z m -48,32 c 3.999998,0 3.999998,-6 0,-6 -3.999998,0 -3.999998,6 0,6 z m 16,16 c 4,0 4,-6 0,-6 -3.999998,0 -3.999998,6 0,6 z m 32,48 c 4,0 4,-6 0,-6 -4,0 -4,6 0,6 z m -16,16 c 4,0 4,-6 0,-6 -4,0 -4,6 0,6 z m 32,-16 c 4,0 4,-6 0,-6 -4,0 -4,6 0,6 z m 0,-32 c 4,0 4,-6 0,-6 -4,0 -4,6 0,6 z m 16,32 c 4,0 4,-6 0,-6 -4,0 -4,6 0,6 z m 32,16 c 4,0 4,-6 0,-6 -4,0 -4,6 0,6 z m 0,-16 c 4,0 4,-6 0,-6 -4,0 -4,6 0,6 z m -16,-64 c 4,0 4,-6 0,-6 -4,0 -4,6 0,6 z m 16,0 c 4,0 4,-6 0,-6 -4,0 -4,6 0,6 z m 16,96 c 4,0 4,-6 0,-6 -4,0 -4,6 0,6 z m 0,16 c 4,0 4,-6 0,-6 -4,0 -4,6 0,6 z m 16,16 c 4,0 4,-6 0,-6 -4,0 -4,6 0,6 z m 16,-144 c 4,0 4,-6 0,-6 -4,0 -4,6 0,6 z m 0,32 c 4,0 4,-6 0,-6 -4,0 -4,6 0,6 z m 16,-32 c 4,0 4,-6 0,-6 -4,0 -4,6 0,6 z m 16,-16 c 4,0 4,-6 0,-6 -4,0 -4,6 0,6 z m -96,0 c 4,0 4,-6 0,-6 -4,0 -4,6 0,6 z m 0,16 c 4,0 4,-6 0,-6 -4,0 -4,6 0,6 z m 16,-32 c 4,0 4,-6 0,-6 -4,0 -4,6 0,6 z m 96,0 c 4,0 4,-6 0,-6 -4,0 -4,6 0,6 z M 273,52 c 4,0 4,-6 0,-6 -4,0 -4,6 0,6 z M 257,36 c 4,0 4,-6 0,-6 -4,0 -4,6 0,6 z M 241,20 c 4,0 4,-6 0,-6 -4,0 -4,6 0,6 z m -16,0 c 4,0 4,-6 0,-6 -4,0 -4,6 0,6 z m -16,0 c 4,0 4,-6 0,-6 -4,0 -4,6 0,6 z M 49,260 c 3.999998,0 3.999998,-6 0,-6 -3.999998,0 -3.999998,6 0,6 z m 16,32 c 3.999998,0 3.999998,-6 0,-6 -3.999998,0 -3.999998,6 0,6 z M 49,244 c 3.999998,0 3.999998,-6 0,-6 -3.999998,0 -3.999998,6 0,6 z m 224,-48 c 4,0 4,-6 0,-6 -4,0 -4,6 0,6 z m -16,16 c 4,0 4,-6 0,-6 -4,0 -4,6 0,6 z m 0,16 c 4,0 4,-6 0,-6 -4,0 -4,6 0,6 z m 0,16 c 4,0 4,-6 0,-6 -4,0 -4,6 0,6 z M 17,180 c 3.999998,0 3.999998,-6 0,-6 -3.999998,0 -3.999998,6 0,6 z m 0,16 c 3.999998,0 3.999998,-6 0,-6 -3.999998,0 -3.999998,6 0,6 z m 16,-32 c 3.999998,0 3.999998,-6 0,-6 -3.999998,0 -3.999998,6 0,6 z\" />\n</svg>\n";

/***/ }),

/***/ "./style/icons/component-library.svg":
/*!*******************************************!*\
  !*** ./style/icons/component-library.svg ***!
  \*******************************************/
/***/ ((module) => {

module.exports = "<svg id=\"Layer_1\" data-name=\"Layer 1\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 60 70\"><defs><style>.cls-1{fill:#616161;}.cls-2{fill:none;stroke:#616161;stroke-linecap:round;stroke-miterlimit:10;stroke-width:2.73px;}</style></defs><rect class=\"cls-1\" y=\"48.18\" width=\"21.82\" height=\"21.82\"/><rect class=\"cls-1\" x=\"38.18\" width=\"21.82\" height=\"21.82\"/><path class=\"cls-2\" d=\"M8.18,75.45s18.17,6.59,29.51,0-12.37-23.72-7.1-35.58S53,24.05,62.22,26.69\" transform=\"translate(-5 -15)\"/></svg>";

/***/ }),

/***/ "./style/icons/debugger.svg":
/*!**********************************!*\
  !*** ./style/icons/debugger.svg ***!
  \**********************************/
/***/ ((module) => {

module.exports = "<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/function-component.svg":
/*!********************************************!*\
  !*** ./style/icons/function-component.svg ***!
  \********************************************/
/***/ ((module) => {

module.exports = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\" className=\"icon icon-tabler icons-tabler-outline icon-tabler-math-function\">\n  <path stroke=\"none\" d=\"M0 0h24v24H0z\" fill=\"none\" />\n  <path d=\"M3 19a2 2 0 0 0 2 2c2 0 2 -4 3 -9s1 -9 3 -9a2 2 0 0 1 2 2\" />\n  <path d=\"M5 12h6\" />\n  <path d=\"M15 12l6 6\" />\n  <path d=\"M15 18l6 -6\" />\n</svg>";

/***/ }),

/***/ "./style/icons/get-variable-component.svg":
/*!************************************************!*\
  !*** ./style/icons/get-variable-component.svg ***!
  \************************************************/
/***/ ((module) => {

module.exports = "<svg  xmlns=\"http://www.w3.org/2000/svg\"  width=\"24\"  height=\"24\"  viewBox=\"0 0 24 24\"  fill=\"none\"  stroke=\"currentColor\"  stroke-width=\"2\"  stroke-linecap=\"round\"  stroke-linejoin=\"round\"  className=\"icon icon-tabler icons-tabler-outline icon-tabler-world-download\"><path stroke=\"none\" d=\"M0 0h24v24H0z\" fill=\"none\"/><path d=\"M21 12a9 9 0 1 0 -9 9\" /><path d=\"M3.6 9h16.8\" /><path d=\"M3.6 15h8.4\" /><path d=\"M11.578 3a17 17 0 0 0 0 18\" /><path d=\"M12.5 3c1.719 2.755 2.5 5.876 2.5 9\" /><path d=\"M18 14v7m-3 -3l3 3l3 -3\" /></svg>";

/***/ }),

/***/ "./style/icons/info.svg?77f4":
/*!******************************!*\
  !*** ./style/icons/info.svg ***!
  \******************************/
/***/ ((module) => {

module.exports = "<svg viewBox=\"0 0 512 512\" xmlns=\"http://www.w3.org/2000/svg\">\n    <polyline points=\"196 220 260 220 260 392\" \n        style=\"fill:none;stroke:#fff;stroke-linecap:round;stroke-linejoin:round;stroke-width:40px\"/>\n    <line x1=\"187\" y1=\"396\" x2=\"325\" y2=\"396\" \n        style=\"fill:none;stroke:#fff;stroke-linecap:round;stroke-miterlimit:10;stroke-width:40px\"/>\n    <path d=\"M256,160a32,32,0,1,1,32-32A32,32,0,0,1,256,160Z\" style=\"fill:#fff\"/>\n</svg>";

/***/ }),

/***/ "./style/icons/lock.svg":
/*!******************************!*\
  !*** ./style/icons/lock.svg ***!
  \******************************/
/***/ ((module) => {

module.exports = "\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 ***!
  \***********************************/
/***/ ((module) => {

module.exports = "<!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 ***!
  \******************************/
/***/ ((module) => {

module.exports = "<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 ***!
  \************************************/
/***/ ((module) => {

module.exports = "<!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 ***!
  \********************************/
/***/ ((module) => {

module.exports = "<?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/set-variable-component.svg":
/*!************************************************!*\
  !*** ./style/icons/set-variable-component.svg ***!
  \************************************************/
/***/ ((module) => {

module.exports = "<svg  xmlns=\"http://www.w3.org/2000/svg\"  width=\"24\"  height=\"24\"  viewBox=\"0 0 24 24\"  fill=\"none\"  stroke=\"currentColor\"  stroke-width=\"2\"  stroke-linecap=\"round\"  stroke-linejoin=\"round\"  className=\"icon icon-tabler icons-tabler-outline icon-tabler-world-upload\"><path stroke=\"none\" d=\"M0 0h24v24H0z\" fill=\"none\"/><path d=\"M21 12a9 9 0 1 0 -9 9\" /><path d=\"M3.6 9h16.8\" /><path d=\"M3.6 15h8.4\" /><path d=\"M11.578 3a17 17 0 0 0 0 18\" /><path d=\"M12.5 3c1.719 2.755 2.5 5.876 2.5 9\" /><path d=\"M18 21v-7m3 3l-3 -3l-3 3\" /></svg>";

/***/ }),

/***/ "./style/icons/start-finish-component.svg":
/*!************************************************!*\
  !*** ./style/icons/start-finish-component.svg ***!
  \************************************************/
/***/ ((module) => {

module.exports = "<svg  xmlns=\"http://www.w3.org/2000/svg\"  width=\"24\"  height=\"24\"  viewBox=\"0 0 24 24\"  fill=\"currentColor\"  className=\"icon icon-tabler icons-tabler-filled icon-tabler-direction-sign\"><path stroke=\"none\" d=\"M0 0h24v24H0z\" fill=\"none\"/><path d=\"M10.52 2.614a2.095 2.095 0 0 1 2.835 -.117l.126 .117l7.905 7.905c.777 .777 .816 2.013 .117 2.836l-.117 .126l-7.905 7.905a2.094 2.094 0 0 1 -2.836 .117l-.126 -.117l-7.907 -7.906a2.096 2.096 0 0 1 -.115 -2.835l.117 -.126l7.905 -7.905zm5.969 9.535l.01 -.116l-.003 -.12l-.016 -.114l-.03 -.11l-.044 -.112l-.052 -.098l-.076 -.105l-.07 -.081l-3.5 -3.5l-.095 -.083a1 1 0 0 0 -1.226 0l-.094 .083l-.083 .094a1 1 0 0 0 0 1.226l.083 .094l1.792 1.793h-5.085l-.117 .007a1 1 0 0 0 0 1.986l.117 .007h5.085l-1.792 1.793l-.083 .094a1 1 0 0 0 1.403 1.403l.094 -.083l3.5 -3.5l.097 -.112l.05 -.074l.037 -.067l.05 -.112l.023 -.076l.025 -.117z\" /></svg>";

/***/ }),

/***/ "./style/icons/variable-component.svg":
/*!********************************************!*\
  !*** ./style/icons/variable-component.svg ***!
  \********************************************/
/***/ ((module) => {

module.exports = "<svg  xmlns=\"http://www.w3.org/2000/svg\"  width=\"24\"  height=\"24\"  viewBox=\"0 0 24 24\"  fill=\"none\"  stroke=\"currentColor\"  stroke-width=\"2\"  stroke-linecap=\"round\"  stroke-linejoin=\"round\"  className=\"icon icon-tabler icons-tabler-outline icon-tabler-variable\"><path stroke=\"none\" d=\"M0 0h24v24H0z\" fill=\"none\"/><path d=\"M5 4c-2.5 5 -2.5 10 0 16m14 -16c2.5 5 2.5 10 0 16m-10 -11h1c1 0 1 1 2.016 3.527c.984 2.473 .984 3.473 1.984 3.473h1\" /><path d=\"M8 16c1.5 0 3 -2 4 -3.5s2.5 -3.5 4 -3.5\" /></svg>";

/***/ }),

/***/ "./style/icons/workflow-component.svg":
/*!********************************************!*\
  !*** ./style/icons/workflow-component.svg ***!
  \********************************************/
/***/ ((module) => {

module.exports = "<svg  xmlns=\"http://www.w3.org/2000/svg\"  width=\"24\"  height=\"24\"  viewBox=\"0 0 24 24\"  fill=\"none\"  stroke=\"currentColor\"  stroke-width=\"2\"  stroke-linecap=\"round\"  stroke-linejoin=\"round\"  className=\"icon icon-tabler icons-tabler-outline icon-tabler-chart-dots-3\"><path stroke=\"none\" d=\"M0 0h24v24H0z\" fill=\"none\"/><path d=\"M5 7m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0\" /><path d=\"M16 15m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0\" /><path d=\"M18 6m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0\" /><path d=\"M6 18m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0\" /><path d=\"M9 17l5 -1.5\" /><path d=\"M6.5 8.5l7.81 5.37\" /><path d=\"M7 7l8 -1\" /></svg>";

/***/ }),

/***/ "./style/icons/xpress-logo.svg":
/*!*************************************!*\
  !*** ./style/icons/xpress-logo.svg ***!
  \*************************************/
/***/ ((module) => {

module.exports = "<?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";

/***/ })

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