/** * Copyright JS Foundation and other contributors, http://js.foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ RED.subflow = (function() { var currentLocale = "en-US"; var _subflowEditTemplate = ''; var _subflowTemplateEditTemplate = ''; var _subflowModulePaneTemplate = '
'+ '
'+ ''+ ''+ '
'+ '
'+ ''+ ''+ '
'+ '
'+ ''+ ''+ '
'+ '
'+ ''+ ''+ '
'+ '
'+ ''+ ''+ '
'+ '
'+ ''+ ''+ '
'+ '
'+ ''+ ''+ '
'+ '
'; function findAvailableSubflowIOPosition(subflow,isInput) { var pos = {x:50,y:30}; if (!isInput) { pos.x += 110; } var ports = [].concat(subflow.out).concat(subflow.in); if (subflow.status) { ports.push(subflow.status); } ports.sort(function(A,B) { return A.x-B.x; }); for (var i=0; i output.i) { subflowMovedLinks.push(l); } } }); subflowRemovedLinks.forEach(function(l) { RED.nodes.removeLink(l)}); subflowMovedLinks.forEach(function(l) { l.sourcePort--; }); removedLinks = removedLinks.concat(subflowRemovedLinks); for (var j=output.i;j ').appendTo(toolbar); // Inputs $(' '+ '
'+ '0'+ '1'+ '
').appendTo(toolbar); // Outputs $('
'+ ''+ '
3
'+ ''+ '
').appendTo(toolbar); // Status $('').appendTo(toolbar); // $(' ').appendTo(toolbar); // $(' ').appendTo(toolbar); // Delete $(' ').appendTo(toolbar); toolbar.i18n(); $("#red-ui-subflow-output-remove").on("click", function(event) { event.preventDefault(); var wasDirty = RED.nodes.dirty(); var wasChanged = activeSubflow.changed; var result = removeSubflowOutput(); if (result) { var inst = refresh(true); RED.history.push({ t:'delete', links:result.links, subflowOutputs: result.subflowOutputs, changed: wasChanged, dirty:wasDirty, subflow: { instances: inst.instances } }); RED.view.select(); RED.nodes.dirty(true); RED.view.redraw(true); } }); $("#red-ui-subflow-output-add").on("click", function(event) { event.preventDefault(); addSubflowOutput(); }); $("#red-ui-subflow-input-add").on("click", function(event) { event.preventDefault(); addSubflowInput(); }); $("#red-ui-subflow-input-remove").on("click", function(event) { event.preventDefault(); var wasDirty = RED.nodes.dirty(); var wasChanged = activeSubflow.changed; activeSubflow.changed = true; var result = removeSubflowInput(); if (result) { var inst = refresh(true); RED.history.push({ t:'delete', links:result.links, changed: wasChanged, subflowInputs: result.subflowInputs, dirty:wasDirty, subflow: { instances: inst.instances } }); RED.view.select(); RED.nodes.dirty(true); RED.view.redraw(true); } }); $("#red-ui-subflow-status").on("change", function(evt) { if (this.checked) { addSubflowStatus(); } else { var currentStatus = activeSubflow.status; var wasChanged = activeSubflow.changed; var result = removeSubflowStatus(); if (result) { activeSubflow.changed = true; var wasDirty = RED.nodes.dirty(); RED.history.push({ t:'delete', links:result.links, changed: wasChanged, dirty:wasDirty, subflow: { id: activeSubflow.id, status: currentStatus } }); RED.view.select(); RED.nodes.dirty(true); RED.view.redraw(); } } }) $("#red-ui-subflow-edit").on("click", function(event) { RED.editor.editSubflow(RED.nodes.subflow(RED.workspaces.active())); event.preventDefault(); }); $("#red-ui-subflow-delete").on("click", function(event) { event.preventDefault(); var subflow = RED.nodes.subflow(RED.workspaces.active()); if (subflow.instances.length > 0) { var msg = $('
') $('

').text(RED._("subflow.subflowInstances",{count: subflow.instances.length})).appendTo(msg); $('

').text(RED._("subflow.confirmDelete")).appendTo(msg); var confirmDeleteNotification = RED.notify(msg, { modal: true, fixed: true, buttons: [ { text: RED._('common.label.cancel'), click: function() { confirmDeleteNotification.close(); } }, { text: RED._('workspace.confirmDelete'), class: "primary", click: function() { confirmDeleteNotification.close(); completeDelete(); } } ] }); return; } else { completeDelete(); } function completeDelete() { var startDirty = RED.nodes.dirty(); var historyEvent = removeSubflow(RED.workspaces.active()); historyEvent.t = 'delete'; historyEvent.dirty = startDirty; RED.history.push(historyEvent); } }); refreshToolbar(activeSubflow); $("#red-ui-workspace-chart").css({"margin-top": "40px"}); $("#red-ui-workspace-toolbar").show(); } function hideWorkspaceToolbar() { $("#red-ui-workspace-toolbar").hide().empty(); $("#red-ui-workspace-chart").css({"margin-top": "0"}); } function removeSubflow(id, keepInstanceNodes) { // TODO: A lot of this logic is common with RED.nodes.removeWorkspace var removedNodes = []; var removedLinks = []; var removedGroups = []; var activeSubflow = RED.nodes.subflow(id); RED.nodes.eachNode(function(n) { if (!keepInstanceNodes && n.type == "subflow:"+id) { removedNodes.push(n); } if (n.z == id) { removedNodes.push(n); } }); RED.nodes.eachConfig(function(n) { if (n.z == id) { removedNodes.push(n); } }); RED.nodes.groups(id).forEach(function(n) { removedGroups.push(n); }) var removedConfigNodes = []; for (var i=0;i=0; i--) { RED.nodes.removeGroup(removedGroups[i]); } RED.nodes.removeSubflow(activeSubflow); RED.workspaces.remove(activeSubflow); RED.nodes.dirty(true); RED.view.redraw(); return { nodes:removedNodes, links:removedLinks, groups: removedGroups, subflows: [activeSubflow] } } function init() { RED.events.on("workspace:change",function(event) { var activeSubflow = RED.nodes.subflow(event.workspace); if (activeSubflow) { showWorkspaceToolbar(activeSubflow); } else { hideWorkspaceToolbar(); } }); RED.events.on("view:selection-changed",function(selection) { if (!selection.nodes) { RED.menu.setDisabled("menu-item-subflow-convert",true); } else { RED.menu.setDisabled("menu-item-subflow-convert",false); } }); RED.actions.add("core:create-subflow",createSubflow); RED.actions.add("core:convert-to-subflow",convertToSubflow); $(_subflowEditTemplate).appendTo("#red-ui-editor-node-configs"); $(_subflowTemplateEditTemplate).appendTo("#red-ui-editor-node-configs"); } function createSubflow() { var lastIndex = 0; RED.nodes.eachSubflow(function(sf) { var m = (new RegExp("^Subflow (\\d+)$")).exec(sf.name); if (m) { lastIndex = Math.max(lastIndex,m[1]); } }); var name = "Subflow "+(lastIndex+1); var subflowId = RED.nodes.id(); var subflow = { type:"subflow", id:subflowId, name:name, info:"", in: [], out: [] }; RED.nodes.addSubflow(subflow); RED.history.push({ t:'createSubflow', subflow: { subflow:subflow }, dirty:RED.nodes.dirty() }); RED.workspaces.show(subflowId); RED.nodes.dirty(true); } function snapToGrid(x) { if (RED.settings.get("editor").view['view-snap-grid']) { x = Math.round(x / RED.view.gridSize()) * RED.view.gridSize(); } return x; } function convertToSubflow() { var selection = RED.view.selection(); if (!selection.nodes) { RED.notify(RED._("subflow.errors.noNodesSelected"),"error"); return; } var i,n; var nodeList = new Set(); var tmplist = selection.nodes.slice(); var includedGroups = new Set(); while(tmplist.length > 0) { n = tmplist.shift(); if (n.type === "group") { includedGroups.add(n.id); tmplist = tmplist.concat(n.nodes); } nodeList.add(n); } nodeList = Array.from(nodeList); var containingGroup = nodeList[0].g; var nodesMovedFromGroup = []; for (i=0; i 1) { RED.notify(RED._("subflow.errors.multipleInputsToSelection"),"error"); return; } var lastIndex = 0; RED.nodes.eachSubflow(function(sf) { var m = (new RegExp("^Subflow (\\d+)$")).exec(sf.name); if (m) { lastIndex = Math.max(lastIndex,m[1]); } }); var name = "Subflow "+(lastIndex+1); var subflowId = RED.nodes.id(); var subflow = { type:"subflow", id:subflowId, name:name, info:"", in: Object.keys(candidateInputNodes).map(function(v,i) { var index = i; return { type:"subflow", direction:"in", x:snapToGrid(candidateInputNodes[v].x-(candidateInputNodes[v].w/2)-80 - offsetX), y:snapToGrid(candidateInputNodes[v].y - offsetY), z:subflowId, i:index, id:RED.nodes.id(), wires:[{id:candidateInputNodes[v].id}] }}), out: candidateOutputs.map(function(v,i) { var index = i; return { type:"subflow", direction:"out", x:snapToGrid(v.source.x+(v.source.w/2)+80 - offsetX), y:snapToGrid(v.source.y - offsetY), z:subflowId, i:index, id:RED.nodes.id(), wires:[{id:v.source.id,port:v.sourcePort}] }}) }; RED.nodes.addSubflow(subflow); var subflowInstance = { id:RED.nodes.id(), type:"subflow:"+subflow.id, x: center[0], y: center[1], z: RED.workspaces.active(), inputs: subflow.in.length, outputs: subflow.out.length, h: Math.max(30/*node_height*/,(subflow.out.length||0) * 15), changed:true } subflowInstance._def = RED.nodes.getType(subflowInstance.type); RED.editor.validateNode(subflowInstance); RED.nodes.add(subflowInstance); if (containingGroup) { RED.group.addToGroup(containingGroup, subflowInstance); nodeList.forEach(function(nl) { if (nl.g === containingGroup.id) { delete nl.g; var index = containingGroup.nodes.indexOf(nl); containingGroup.nodes.splice(index,1); nodesMovedFromGroup.push(nl); } }) containingGroup.dirty = true; } candidateInputs.forEach(function(l) { var link = {source:l.source, sourcePort:l.sourcePort, target: subflowInstance}; new_links.push(link); RED.nodes.addLink(link); }); candidateOutputs.forEach(function(output,i) { output.targets.forEach(function(target) { var link = {source:subflowInstance, sourcePort:i, target: target}; new_links.push(link); RED.nodes.addLink(link); }); }); subflow.in.forEach(function(input) { input.wires.forEach(function(wire) { var link = {source: input, sourcePort: 0, target: RED.nodes.node(wire.id) } new_links.push(link); RED.nodes.addLink(link); }); }); subflow.out.forEach(function(output,i) { output.wires.forEach(function(wire) { var link = {source: RED.nodes.node(wire.id), sourcePort: wire.port , target: output } new_links.push(link); RED.nodes.addLink(link); }); }); for (i=0;i -1) { otherNode.links.splice(i,1); } } } return isLocalLink; }); } n.x -= offsetX; n.y -= offsetY; RED.nodes.moveNodeToTab(n, subflow.id); } var historyEvent = { t:'createSubflow', nodes:[subflowInstance.id], links:new_links, subflow: { subflow: subflow, offsetX: offsetX, offsetY: offsetY }, activeWorkspace: RED.workspaces.active(), removedLinks: removedLinks, dirty:RED.nodes.dirty() } if (containingGroup) { historyEvent = { t:'multi', events: [ historyEvent ] } historyEvent.events.push({ t:'addToGroup', group: containingGroup, nodes: [subflowInstance] }) historyEvent.events.push({ t:'removeFromGroup', group: containingGroup, nodes: nodesMovedFromGroup, reparent: false }) } RED.history.push(historyEvent); RED.editor.validateNode(subflow); RED.nodes.dirty(true); RED.view.updateActive(); RED.view.select(null); } /** * Create interface for controlling env var UI definition */ function buildEnvControl(envList,node) { var tabs = RED.tabs.create({ id: "subflow-env-tabs", onchange: function(tab) { if (tab.id === "subflow-env-tab-preview") { var inputContainer = $("#subflow-input-ui"); var list = envList.editableList("items"); var exportedEnv = exportEnvList(list, true); buildEnvUI(inputContainer, exportedEnv,node); } $("#subflow-env-tabs-content").children().hide(); $("#" + tab.id).show(); } }); tabs.addTab({ id: "subflow-env-tab-edit", label: RED._("editor-tab.envProperties") }); tabs.addTab({ id: "subflow-env-tab-preview", label: RED._("editor-tab.preview") }); var localesList = RED.settings.theme("languages") .map(function(lc) { var name = RED._("languages."+lc); return {text: (name ? name : lc), val: lc}; }) .sort(function(a, b) { return a.text.localeCompare(b.text) }); RED.popover.tooltip($(".node-input-env-locales-row i"),RED._("editor.locale")) var locales = $("#subflow-input-env-locale") localesList.forEach(function(item) { var opt = { value: item.val }; if (item.val === "en-US") { // make en-US default selected opt.selected = ""; } $("

'):undefined, addItem: function(container, i, opt) { // If this is an instance node, these are properties unique to // this instance - ie opt.parent will not be defined. if (isTemplateNode) { container.addClass("red-ui-editor-subflow-env-editable") } var envRow = $('
').appendTo(container); var nameField = null; var valueField = null; nameField = $('', { class: "node-input-env-name", type: "text", placeholder: RED._("common.label.name") }).attr("autocomplete","disable").appendTo(envRow).val(opt.name); valueField = $('',{ style: "width:100%", class: "node-input-env-value", type: "text", }).attr("autocomplete","disable").appendTo(envRow) valueField.typedInput({default:'str',types:isTemplateNode?DEFAULT_ENV_TYPE_LIST:DEFAULT_ENV_TYPE_LIST_INC_CRED}); valueField.typedInput('type', opt.type); if (opt.type === "cred") { if (opt.value) { valueField.typedInput('value', opt.value); } else if (node.credentials && node.credentials[opt.name]) { valueField.typedInput('value', node.credentials[opt.name]); } else if (node.credentials && node.credentials['has_'+opt.name]) { valueField.typedInput('value', "__PWRD__"); } else { valueField.typedInput('value', ""); } } else { valueField.typedInput('value', opt.value); } opt.nameField = nameField; opt.valueField = valueField; var actionButton = $('',{href:"#",class:"red-ui-editableList-item-remove red-ui-button red-ui-button-small"}).appendTo(envRow); $('',{class:"fa "+(opt.parent?"fa-reply":"fa-remove")}).appendTo(actionButton); var removeTip = RED.popover.tooltip(actionButton,RED._("subflow.env.remove")); actionButton.on("click", function(evt) { evt.preventDefault(); removeTip.close(); container.parent().addClass("red-ui-editableList-item-deleting") container.fadeOut(300, function() { envContainer.editableList('removeItem',opt); }); }); if (isTemplateNode) { // Add the UI customisation row // if `opt.ui` does not exist, then apply defaults. If these // defaults do not change then they will get stripped off // before saving. if (opt.type === 'cred') { opt.ui = opt.ui || { icon: "", type: "cred" } opt.ui.type = "cred"; } else { opt.ui = opt.ui || { icon: "", type: "input", opts: {types:DEFAULT_ENV_TYPE_LIST} } } opt.ui.label = opt.ui.label || {}; opt.ui.type = opt.ui.type || "input"; var uiRow = $('
').appendTo(container).hide(); // save current info for reverting on cancel // var copy = $.extend(true, {}, ui); $('').prependTo(envRow).on("click", function (evt) { evt.preventDefault(); if ($(this).hasClass('expanded')) { uiRow.slideUp(); $(this).removeClass('expanded'); } else { uiRow.slideDown(); $(this).addClass('expanded'); } }); buildEnvEditRow(uiRow, opt.ui, nameField, valueField); nameField.trigger('change'); } }, sortable: ".red-ui-editableList-item-handle", removable: false }); var parentEnv = {}; var envList = []; if (/^subflow:/.test(node.type)) { var subflowDef = RED.nodes.subflow(node.type.substring(8)); if (subflowDef.env) { subflowDef.env.forEach(function(env) { var item = { name:env.name, parent: { type: env.type, value: env.value, ui: env.ui } } envList.push(item); parentEnv[env.name] = item; }) } } if (node.env) { for (var i = 0; i < node.env.length; i++) { var env = node.env[i]; if (parentEnv.hasOwnProperty(env.name)) { parentEnv[env.name].type = env.type; parentEnv[env.name].value = env.value; } else { envList.push({ name: env.name, type: env.type, value: env.value, ui: env.ui }); } } } envList.forEach(function(env) { if (env.parent && env.parent.ui && env.parent.ui.type === 'hide') { return; } if (!isTemplateNode && env.parent) { return; } envContainer.editableList('addItem', JSON.parse(JSON.stringify(env))); }); } /** * Create UI edit interface for environment variable * @param container - container * @param env - env var definition * @param nameField - name field of env var * @param valueField - value field of env var */ function buildEnvEditRow(container, ui, nameField, valueField) { container.addClass("red-ui-editor-subflow-env-ui-row") var topRow = $('
').appendTo(container); $('
').appendTo(topRow); $('
').text(RED._("editor.icon")).appendTo(topRow); $('
').text(RED._("editor.label")).appendTo(topRow); $('
').text(RED._("editor.inputType")).appendTo(topRow); var row = $('
').appendTo(container); $('
').appendTo(row); var typeOptions = { 'input': {types:DEFAULT_ENV_TYPE_LIST}, 'select': {opts:[]}, 'spinner': {}, 'cred': {} }; if (ui.opts) { typeOptions[ui.type] = ui.opts; } else { // Pick up the default values if not otherwise provided ui.opts = typeOptions[ui.type]; } var iconCell = $('
').appendTo(row); var iconButton = $('').appendTo(iconCell); iconButton.on("click", function(evt) { evt.preventDefault(); var icon = ui.icon || ""; var iconPath = (icon ? RED.utils.separateIconPath(icon) : {}); RED.editor.showIconPicker(iconButton, null, iconPath, true, function (newIcon) { iconButton.empty(); var path = newIcon || ""; var newPath = RED.utils.separateIconPath(path); if (newPath) { $('').addClass(newPath.file).appendTo(iconButton); } ui.icon = path; }); }) if (ui.icon) { var newPath = RED.utils.separateIconPath(ui.icon); $('').appendTo(iconButton); } var labelCell = $('
').appendTo(row); var label = ui.label && ui.label[currentLocale] || ""; var labelInput = $('').val(label).appendTo(labelCell); ui.labelField = labelInput; labelInput.on('change', function(evt) { ui.label = ui.label || {}; var val = $(this).val().trim(); if (val === "") { delete ui.label[currentLocale]; } else { ui.label[currentLocale] = val; } }) var labelIcon = $('').appendTo(labelCell); RED.popover.tooltip(labelIcon,function() { var langs = Object.keys(ui.label); var content = $("
"); if (langs.indexOf(currentLocale) === -1) { langs.push(currentLocale); langs.sort(); } langs.forEach(function(l) { var row = $('
').appendTo(content); $('').css({display:"inline-block",width:"120px"}).text(RED._("languages."+l)+(l===currentLocale?"*":"")).appendTo(row); $('').text(ui.label[l]||"").appendTo(row); }); return content; }) nameField.on('change',function(evt) { labelInput.attr("placeholder",$(this).val()) }); var inputCell = $('
').appendTo(row); var inputCellInput = $('').css("width","100%").appendTo(inputCell); if (ui.type === "input") { inputCellInput.val(ui.opts.types.join(",")); } var checkbox; var selectBox; inputCellInput.typedInput({ types: [ { value:"input", label:RED._("editor.inputs.input"), icon:"fa fa-i-cursor",showLabel:false,multiple:true,options:[ {value:"str",label:RED._("editor.types.str"),icon:"red/images/typedInput/az.svg"}, {value:"num",label:RED._("editor.types.num"),icon:"red/images/typedInput/09.svg"}, {value:"bool",label:RED._("editor.types.bool"),icon:"red/images/typedInput/bool.svg"}, {value:"json",label:RED._("editor.types.json"),icon:"red/images/typedInput/json.svg"}, {value: "bin",label: RED._("editor.types.bin"),icon: "red/images/typedInput/bin.svg"}, {value: "env",label: RED._("editor.types.env"),icon: "red/images/typedInput/env.svg"}, {value: "cred",label: RED._("editor.types.cred"),icon: "fa fa-lock"} ], default: DEFAULT_ENV_TYPE_LIST, valueLabel: function(container,value) { container.css("padding",0); var innerContainer = $('
').appendTo(container); var input = $('
').appendTo(innerContainer); $('').appendTo(input); if (value.length) { value.forEach(function(v) { if (!/^fa /.test(v.icon)) { $('',{src:v.icon,style:"max-width:14px; padding: 0 3px; margin-top:-4px; margin-left: 1px"}).appendTo(input); } else { var s = $('',{style:"max-width:14px; padding: 0 3px; margin-top:-4px; margin-left: 1px"}).appendTo(input); $("",{class: v.icon}).appendTo(s); } }) } else { $('').text(RED._("editor.selectType")).appendTo(input); } } }, { value: "cred", label: RED._("typedInput.type.cred"), icon:"fa fa-lock", showLabel: false, valueLabel: function(container,value) { container.css("padding",0); var innerContainer = $('
').css({ "border-top-right-radius": "4px", "border-bottom-right-radius": "4px" }).appendTo(container); $('
').html("••••••••").appendTo(innerContainer); } }, { value:"select", label:RED._("editor.inputs.select"), icon:"fa fa-tasks",showLabel:false, valueLabel: function(container,value) { container.css("padding","0"); selectBox = $('').appendTo(container); if (ui.opts && Array.isArray(ui.opts.opts)) { ui.opts.opts.forEach(function(o) { var label = lookupLabel(o.l, o.l["en-US"]||o.v, currentLocale); // $('