Got to start somewhere

This commit is contained in:
Nicholas O'Leary
2013-09-05 15:02:48 +01:00
commit 32796dd74c
155 changed files with 21836 additions and 0 deletions

70
public/red/history.js Normal file
View File

@@ -0,0 +1,70 @@
/**
* Copyright 2013 IBM Corp.
*
* 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.history = function() {
var undo_history = [];
return {
//TODO: this function is a placeholder until there is a 'save' event that can be listened to
markAllDirty: function() {
for (var i in undo_history) {
undo_history[i].dirty = true;
}
},
push: function(ev) {
undo_history.push(ev);
},
pop: function() {
var ev = undo_history.pop();
if (ev) {
if (ev.t == 'add') {
for (var i in ev.nodes) {
RED.nodes.remove(ev.nodes[i]);
}
for (var i in ev.links) {
RED.nodes.removeLink(ev.links[i]);
}
} else if (ev.t == "delete") {
for (var i in ev.nodes) {
RED.nodes.add(ev.nodes[i]);
}
for (var i in ev.links) {
RED.nodes.addLink(ev.links[i]);
}
} else if (ev.t == "move") {
for (var i in ev.nodes) {
var n = ev.nodes[i];
n.n.x = n.ox;
n.n.y = n.oy;
n.n.dirty = true;
}
} else if (ev.t == "edit") {
for (var i in ev.changes) {
ev.node[i] = ev.changes[i];
}
RED.editor.updateNodeProperties(ev.node);
for (var i in ev.links) {
RED.nodes.addLink(ev.links[i]);
}
RED.editor.validateNode(ev.node);
ev.node.dirty = true;
}
RED.view.dirty(ev.dirty);
RED.view.redraw();
}
}
}
}();

120
public/red/main.js Normal file
View File

@@ -0,0 +1,120 @@
/**
* Copyright 2013 IBM Corp.
*
* 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.
**/
var RED = function() {
$('#btn-keyboard-shortcuts').click(function(){showHelp();});
function save(force) {
if (RED.view.dirty()) {
if (!force) {
var invalid = false;
RED.nodes.eachNode(function(node) {
invalid = invalid || !node.valid;
});
if (invalid) {
$( "#node-dialog-confirm-deploy" ).dialog( "open" );
return;
}
}
var nns = RED.nodes.createCompleteNodeSet();
d3.xhr("flows").post(JSON.stringify(nns),function(err,resp) {
if (resp && resp.status == 204) {
RED.notify("Successfully deployed","success");
RED.view.dirty(false);
// Once deployed, cannot undo back to a clean state
RED.history.markAllDirty();
} else {
if (resp) {
RED.notify("<strong>Error</strong>: "+resp,"error");
} else {
RED.notify("<strong>Error</strong>: no response from server","error");
}
console.log(err,resp);
}
});
}
}
$('#btn-deploy').click(function() { save(); });
$( "#node-dialog-confirm-deploy" ).dialog({
title: "Confirm deploy",
modal: true,
autoOpen: false,
width: 530,
height: 230,
buttons: [
{
text: "Confirm deploy",
click: function() {
save(true);
$( this ).dialog( "close" );
}
},
{
text: "Cancel",
click: function() {
$( this ).dialog( "close" );
}
}
]
});
function loadNodes() {
$.get('nodes', function(data) {
$("body").append(data);
loadFlows();
});
}
function loadFlows() {
d3.json("flows",function(nodes) {
RED.nodes.import(nodes);
RED.view.dirty(false);
RED.view.redraw();
});
}
function showHelp() {
var dialog = $('#node-help');
//$("#node-help").draggable({
// handle: ".modal-header"
//});
dialog.on('show',function() {
RED.keyboard.disable();
});
dialog.on('hidden',function() {
RED.keyboard.enable();
});
dialog.modal();
}
$(function() {
RED.keyboard.add(/* ? */ 191,{shift:true},function(){showHelp();d3.event.preventDefault();});
loadNodes();
});
return {
};
}();

312
public/red/nodes.js Normal file
View File

@@ -0,0 +1,312 @@
/**
* Copyright 2013 IBM Corp.
*
* 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.nodes = function() {
var node_defs = {};
var nodes = [];
var configNodes = {};
var links = [];
function registerType(nt,def) {
node_defs[nt] = def;
// TODO: too tightly coupled into palette UI
RED.palette.add(nt,def);
}
function getType(type) {
return node_defs[type];
}
function addNode(n) {
if (n._def.category == "config") {
configNodes[n.id] = n;
} else {
n.dirty = true;
nodes.push(n);
}
}
function addLink(l) {
links.push(l);
}
function addConfig(c) {
configNodes[c.id] = c;
}
function getNode(id) {
if (id in configNodes) {
return configNodes[id];
} else {
for (var n in nodes) {
if (nodes[n].id == id) {
return nodes[n];
}
}
}
return null;
}
function removeNode(id) {
var removedLinks = [];
if (id in configNodes) {
delete configNodes[id];
} else {
var node = getNode(id);
if (node) {
nodes.splice(nodes.indexOf(node),1);
removedLinks = links.filter(function(l) { return (l.source === node) || (l.target === node); });
removedLinks.map(function(l) {links.splice(links.indexOf(l), 1); });
}
}
return removedLinks;
}
function removeLink(l) {
var index = links.indexOf(l);
if (index != -1) {
links.splice(index,1);
}
}
function refreshValidation() {
for (var n in nodes) {
RED.editor.validateNode(nodes[n]);
}
}
function getAllFlowNodes(node) {
var visited = {};
visited[node.id] = true;
var nns = [node];
var stack = [node];
while(stack.length != 0) {
var n = stack.shift();
var childLinks = links.filter(function(d) { return (d.source === n) || (d.target === n);});
for (var i in childLinks) {
var child = (childLinks[i].source === n)?childLinks[i].target:childLinks[i].source;
if (!visited[child.id]) {
visited[child.id] = true;
nns.push(child);
stack.push(child);
}
}
}
return nns;
}
/**
* Converts a node to an exportable JSON Object
**/
function convertNode(n) {
var node = {};
node.id = n.id;
node.type = n.type;
for (var d in n._def.defaults) {
node[d] = n[d];
}
if (n._def.category != "config") {
node.x = n.x;
node.y = n.y;
node.wires = [];
for(var i=0;i<n.outputs;i++) {
node.wires.push([]);
}
var wires = links.filter(function(d){return d.source === n;});
for (var i in wires) {
var w = wires[i];
node.wires[w.sourcePort].push(w.target.id);
}
}
return node;
}
/**
* Converts the current node selection to an exportable JSON Object
**/
function createExportableNodeSet(set) {
var nns = [];
var exportedConfigNodes = {};
for (var n in set) {
var node = set[n].n;
var convertedNode = RED.nodes.convertNode(node);
for (var d in node._def.defaults) {
if (node._def.defaults[d].type && node[d] in configNodes) {
var confNode = configNodes[node[d]];
var exportable = getType(node._def.defaults[d].type).exportable;
if ((exportable == null || exportable)) {
if (!(node[d] in exportedConfigNodes)) {
exportedConfigNodes[node[d]] = true;
nns.unshift(RED.nodes.convertNode(confNode));
}
} else {
convertedNode[d] = "";
}
}
}
nns.push(convertedNode);
}
return nns;
}
//TODO: rename this (createCompleteNodeSet)
function createCompleteNodeSet() {
var nns = [];
for (var i in configNodes) {
nns.push(convertNode(configNodes[i]));
}
for (var i in nodes) {
var node = nodes[i];
nns.push(convertNode(node));
}
return nns;
}
function importNodes(newNodesObj,createNewIds) {
try {
var newNodes;
if (typeof newNodesObj === "string") {
if (newNodesObj == "") {
return;
}
newNodes = JSON.parse(newNodesObj);
} else {
newNodes = newNodesObj;
}
if (!$.isArray(newNodes)) {
newNodes = [newNodes];
}
for (var i in newNodes) {
var n = newNodes[i];
if (!getType(n.type)) {
// TODO: get this UI thing out of here! (see below as well)
RED.notify("<strong>Failed to import nodes</strong>: unrecognised type '"+n.type+"'","error");
return null;
}
}
var node_map = {};
var new_nodes = [];
var new_links = [];
for (var i in newNodes) {
var n = newNodes[i];
var def = getType(n.type);
if (def && def.category == "config") {
if (!RED.nodes.node(n.id)) {
var configNode = {id:n.id,type:n.type,users:[]};
for (var d in def.defaults) {
configNode[d] = n[d];
}
configNode.label = def.label;
configNode._def = def;
RED.nodes.add(configNode);
}
} else {
var node = {x:n.x,y:n.y,type:0,wires:n.wires};
if (createNewIds) {
node.id = (1+Math.random()*4294967295).toString(16);
} else {
node.id = n.id;
}
node.type = n.type;
node._def = def;
if (!node._def) {
node._def = {
color:"#fee",
defaults: {},
label: "unknown: "+n.type,
labelStyle: "node_label_italic",
outputs: n.outputs||n.wires.length
}
}
node.outputs = n.outputs||node._def.outputs;
for (var d in node._def.defaults) {
node[d] = n[d];
if (node._def.defaults[d].type) {
var configNode = RED.nodes.node(n[d]);
if (configNode) {
configNode.users.push(node);
}
}
}
addNode(node);
RED.editor.validateNode(node);
node_map[n.id] = node;
new_nodes.push(node);
}
}
for (var i in new_nodes) {
var n = new_nodes[i];
for (var w1 in n.wires) {
var wires = (n.wires[w1] instanceof Array)?n.wires[w1]:[n.wires[w1]];
for (var w2 in wires) {
if (wires[w2] in node_map) {
var link = {source:n,sourcePort:w1,target:node_map[wires[w2]]};
addLink(link);
new_links.push(link);
}
}
}
delete n.wires;
}
return [new_nodes,new_links];
} catch(error) {
//TODO: get this UI thing out of here! (see above as well)
RED.notify("<strong>Error</strong>: "+error,"error");
return null;
}
}
return {
registerType: registerType,
getType: getType,
convertNode: convertNode,
add: addNode,
addLink: addLink,
remove: removeNode,
removeLink: removeLink,
eachNode: function(cb) {
for (var n in nodes) {
cb(nodes[n]);
}
},
eachLink: function(cb) {
for (var l in links) {
cb(links[l]);
}
},
eachConfig: function(cb) {
for (var id in configNodes) {
cb(configNodes[id]);
}
},
node: getNode,
import: importNodes,
refreshValidation: refreshValidation,
getAllFlowNodes: getAllFlowNodes,
createExportableNodeSet: createExportableNodeSet,
createCompleteNodeSet: createCompleteNodeSet,
nodes: nodes, // TODO: exposed for d3 vis
links: links // TODO: exposed for d3 vis
};
}();

424
public/red/ui/editor.js Normal file
View File

@@ -0,0 +1,424 @@
/**
* Copyright 2013 IBM Corp.
*
* 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.editor = function() {
var editing_node = null;
// TODO: should IMPORT/EXPORT get their own dialogs?
function showEditDialog(node) {
editing_node = node;
RED.view.state(RED.state.EDITING);
$("#dialog-form").html($("script[data-template-name='"+node.type+"']").html());
if (node._def.defaults) {
for (var d in node._def.defaults) {
var def = node._def.defaults[d];
var input = $("#node-input-"+d);
var node_def = RED.nodes.getType(def.type);
if (node_def && node_def.category == "config") {
input.replaceWith('<select style="width: 60%;" id="node-input-'+d+'"></select>');
updateConfigNodeSelect(d,def.type,node[d]);
var select = $("#node-input-"+d);
select.after(' <a id="node-input-lookup-'+d+'" class="btn"><i class="icon icon-pencil"></i></a>');
var name = d;
var type = def.type;
$('#node-input-lookup-'+d).click(function(e) {
showEditConfigNodeDialog(name,type,select.find(":selected").val());
e.preventDefault();
});
var label = "";
var configNode = RED.nodes.node(node[d]);
if (configNode && node_def.label) {
if (typeof node_def.label == "function") {
label = node_def.label.call(configNode);
} else {
label = node_def.label;
}
}
input.val(label);
} else {
if (input.attr('type') === "checkbox") {
input.prop('checked',node[d]);
} else {
input.val(node[d]||"");
}
}
$("#node-input-"+d).change(function() {
var n = node;
var property = d;
return function() {
if (!validateNodeProperty(node, property,this.value)) {
$(this).addClass("input-error");
} else {
$(this).removeClass("input-error");
}
};
}());
$("#node-input-"+d).change();
}
}
if (node._def.oneditprepare) {
node._def.oneditprepare.call(node);
}
$( "#dialog" ).dialog("option","title","Edit "+node.type+" node").dialog( "open" );
}
function validateNode(node) {
var oldValue = node.valid;
node.valid = true;
for (var d in node._def.defaults) {
if (!validateNodeProperty(node,d,node[d])) {
node.valid = false;
}
}
if (node.valid != oldValue) {
node.dirty = true;
}
}
function validateNodeProperty(node,property,value) {
var valid = true;
if ("required" in node._def.defaults[property] && node._def.defaults[property].required) {
valid = value !== "";
}
if (valid && "validate" in node._def.defaults[property]) {
valid = node._def.defaults[property].validate(value);
}
if (valid && node._def.defaults[property].type && RED.nodes.getType(node._def.defaults[property].type)) {
valid = (value != "_ADD_");
}
return valid;
}
function updateNodeProperties(node) {
node.resize = true;
node.dirty = true;
var removedLinks = [];
if (node.outputs < node.ports.length) {
while (node.outputs < node.ports.length) {
node.ports.pop();
}
var removedLinks = [];
RED.nodes.eachLink(function(l) {
if (l.source === node && l.sourcePort >= node.outputs) {
removedLinks.push(l);
}
});
for (var l in removedLinks) {
RED.nodes.removeLink(removedLinks[l]);
}
} else if (node.outputs > node.ports.length) {
while (node.outputs > node.ports.length) {
node.ports.push(node.ports.length);
}
}
return removedLinks;
}
$( "#dialog" ).dialog({
modal: true,
autoOpen: false,
width: 500,
buttons: [
{
text: "Ok",
click: function() {
if (editing_node) {
var changes = {};
var changed = false;
var wasDirty = RED.view.dirty();
if (editing_node._def.oneditsave) {
editing_node._def.oneditsave.call(editing_node);
}
if (editing_node._def.defaults) {
for (var d in editing_node._def.defaults) {
var input = $("#node-input-"+d);
var newValue;
if (input.attr('type') === "checkbox") {
newValue = input.prop('checked');
} else {
newValue = input.val();
}
if (newValue != null) {
if (editing_node[d] != newValue) {
if (editing_node._def.defaults[d].type) {
if (newValue == "_ADD_") {
newValue = "";
}
// Change to a related config node
var configNode = RED.nodes.node(editing_node[d]);
if (configNode) {
var users = configNode.users;
users.splice(users.indexOf(editing_node),1);
}
var configNode = RED.nodes.node(newValue);
if (configNode) {
configNode.users.push(editing_node);
}
}
changes[d] = editing_node[d];
editing_node[d] = newValue;
changed = true;
RED.view.dirty(true);
}
}
}
}
var removedLinks = updateNodeProperties(editing_node);
if (changed) {
RED.history.push({t:'edit',node:editing_node,changes:changes,links:removedLinks,dirty:wasDirty});
}
editing_node.dirty = true;
validateNode(editing_node);
RED.view.redraw();
} else if (RED.view.state() == RED.state.EXPORT) {
if (/library/.test($( "#dialog" ).dialog("option","title"))) {
//TODO: move this to RED.library
var flowName = $("#node-input-filename").val();
if (!/^\s*$/.test(flowName)) {
$.post('library/flows/'+flowName,$("#node-input-filename").attr('nodes'),function() {
RED.library.loadFlowLibrary();
RED.notify("Saved nodes","success");
});
}
};
} else if (RED.view.state() == RED.state.IMPORT) {
RED.view.importNodes($("#node-input-import").val());
}
$( this ).dialog( "close" );
}
},
{
text: "Cancel",
click: function() {
$( this ).dialog( "close" );
}
}
],
resize: function(e,ui) {
if (editing_node) {
$(this).dialog('option',"sizeCache-"+editing_node.type,ui.size);
}
},
open: function(e) {
RED.keyboard.disable();
if (editing_node) {
var size = $(this).dialog('option','sizeCache-'+editing_node.type);
if (size) {
$(this).dialog('option','width',size.width);
$(this).dialog('option','height',size.height);
}
}
},
close: function(e) {
RED.keyboard.enable();
if (RED.view.state() != RED.state.IMPORT_DRAGGING) {
RED.view.state(0);
}
$( this ).dialog('option','height','auto');
$( this ).dialog('option','width','500');
editing_node = null;
}
});
function showEditConfigNodeDialog(name,type,id) {
$("#dialog-config-form").html($("script[data-template-name='"+type+"']").html());
var node_def = RED.nodes.getType(type);
var configNode = RED.nodes.node(id);
for (var d in node_def.defaults) {
var input = $("#node-config-input-"+d);
if (id == "_ADD_") {
input.val(node_def.defaults[d].value);
} else {
input.val(configNode[d]);
}
}
var buttons = $( "#node-config-dialog" ).dialog("option","buttons");
if (id == "_ADD_") {
if (buttons.length == 3) {
buttons = buttons.splice(1);
}
buttons[0].text = "Add";
$("#node-config-dialog-user-count").html("").hide();
} else {
if (buttons.length == 2) {
buttons.unshift({
class: 'leftButton',
text: "Delete",
click: function() {
var configProperty = $(this).dialog('option','node-property');
var configId = $(this).dialog('option','node-id');
var configType = $(this).dialog('option','node-type');
var configNode = RED.nodes.node(configId);
var configTypeDef = RED.nodes.getType(configType);
if (configTypeDef.ondelete) {
configTypeDef.ondelete.call(RED.nodes.node(configId));
}
RED.nodes.remove(configId);
for (var i in configNode.users) {
var user = configNode.users[i];
for (var d in user._def.defaults) {
if (user[d] == configId) {
user[d] = "";
}
}
validateNode(user);
}
updateConfigNodeSelect(configProperty,configType,"");
RED.view.dirty(true);
$( this ).dialog( "close" );
RED.view.redraw();
}
});
}
buttons[1].text = "Update";
$("#node-config-dialog-user-count").html(configNode.users.length+" node"+(configNode.users.length==1?" uses":"s use")+" this config").show();
}
$( "#node-config-dialog" ).dialog("option","buttons",buttons);
var adding = (id == "_ADD_");
if (adding) {
id = (1+Math.random()*4294967295).toString(16);
}
if (node_def.oneditprepare) {
var cn = RED.nodes.node(id);
if (cn) {
node_def.oneditprepare.call(cn);
} else {
node_def.oneditprepare.call({id:id});
}
}
$( "#node-config-dialog" )
.dialog("option","node-adding",adding)
.dialog("option","node-property",name)
.dialog("option","node-id",id)
.dialog("option","node-type",type)
.dialog("option","title",(adding?"Add new ":"Edit ")+type+" config node")
.dialog( "open" );
}
function updateConfigNodeSelect(name,type,value) {
var select = $("#node-input-"+name);
var node_def = RED.nodes.getType(type);
select.children().remove();
RED.nodes.eachConfig(function(config) {
if (config.type == type) {
var label = "";
if (typeof node_def.label == "function") {
label = node_def.label.call(config);
} else {
label = node_def.label;
}
select.append('<option value="'+config.id+'"'+(value==config.id?" selected":"")+'>'+label+'</option>');
}
});
select.append('<option value="_ADD_"'+(value==""?" selected":"")+'>Add new '+type+'...</option>');
select.change();
}
$( "#node-config-dialog" ).dialog({
modal: true,
autoOpen: false,
width: 500,
buttons: [
{
text: "Ok",
click: function() {
var configProperty = $(this).dialog('option','node-property');
var configId = $(this).dialog('option','node-id');
var configType = $(this).dialog('option','node-type');
var configAdding = $(this).dialog('option','node-adding');
var configTypeDef = RED.nodes.getType(configType);
if (configAdding) {
var nn = {type:configType,id:configId,users:[]};
for (var d in configTypeDef.defaults) {
var input = $("#node-config-input-"+d);
nn[d] = input.val();
}
nn.label = configTypeDef.label;
nn._def = configTypeDef;
//console.log(nn.id,nn.label());
RED.nodes.add(nn);
updateConfigNodeSelect(configProperty,configType,nn.id);
} else {
for (var d in configTypeDef.defaults) {
var input = $("#node-config-input-"+d);
var configNode = RED.nodes.node(configId);
configNode[d] = input.val();
}
updateConfigNodeSelect(configProperty,configType,configId);
}
if (configTypeDef.oneditsave) {
configTypeDef.oneditsave.call(RED.nodes.node(configId));
}
RED.view.dirty(true);
$( this ).dialog( "close" );
}
},
{
text: "Cancel",
click: function() {
var configType = $(this).dialog('option','node-type');
var configId = $(this).dialog('option','node-id');
var configAdding = $(this).dialog('option','node-adding');
var configTypeDef = RED.nodes.getType(configType);
if (configTypeDef.oneditcancel) {
// TODO: what to pass as this to call
if (configTypeDef.oneditcancel) {
var cn = RED.nodes.node(configId);
if (cn) {
configTypeDef.oneditcancel.call(cn,false);
} else {
configTypeDef.oneditcancel.call({id:configId},true);
}
}
}
$( this ).dialog( "close" );
}
}
],
resize: function(e,ui) {
},
open: function(e) {
},
close: function(e) {
}
});
return {
edit: showEditDialog,
validateNode: validateNode,
updateNodeProperties: updateNodeProperties // TODO: only exposed for edit-undo
}
}();

53
public/red/ui/keyboard.js Normal file
View File

@@ -0,0 +1,53 @@
/**
* Copyright 2013 IBM Corp.
*
* 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.keyboard = function() {
var active = true;
var handlers = {};
d3.select(window).on("keydown",function() {
if (!active) { return; }
var handler = handlers[d3.event.keyCode];
if (handler) {
if (!handler.modifiers ||
((!handler.modifiers.shift || d3.event.shiftKey)&&
(!handler.modifiers.ctrl || d3.event.ctrlKey))) {
handler.callback();
}
}
});
function addHandler(key,modifiers,callback) {
var mod = modifiers;
var cb = callback;
if (typeof modifiers == "function") {
mod = {};
cb = modifiers;
}
handlers[key] = {modifiers:mod, callback:cb};
}
function removeHandler(key) {
delete handlers[key];
}
return {
add: addHandler,
remove: removeHandler,
disable: function(){ active = false;},
enable: function(){ active = true; }
}
}();

359
public/red/ui/library.js Normal file
View File

@@ -0,0 +1,359 @@
/**
* Copyright 2013 IBM Corp.
*
* 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.library = function() {
function loadFlowLibrary() {
d3.json("library/flows",function(data) {
//console.log(data);
var buildMenu = function(data,root) {
var ul = document.createElement("ul");
ul.className = "dropdown-menu";
if (data.d) {
for (var i in data.d) {
var li = document.createElement("li");
li.className = "dropdown-submenu pull-left";
var a = document.createElement("a");
a.href="#";
a.innerHTML = i;
li.appendChild(a);
li.appendChild(buildMenu(data.d[i],root+(root!=""?"/":"")+i));
ul.appendChild(li);
}
}
if (data.f) {
for (var i in data.f) {
var li = document.createElement("li");
var a = document.createElement("a");
a.href="#";
a.innerHTML = data.f[i];
a.flowName = root+(root!=""?"/":"")+data.f[i];
a.onclick = function() {
$.get('library/flows/'+this.flowName, function(data) {
RED.view.importNodes(data);
});
};
li.appendChild(a);
ul.appendChild(li);
}
}
return ul;
};
var menu = buildMenu(data,"");
$("#flow-menu-parent>ul").replaceWith(menu);
});
}
loadFlowLibrary();
function createUI(options) {
var libraryData = {};
var selectedLibraryItem = null;
var libraryEditor = null;
function buildFileListItem(item) {
var li = document.createElement("li");
li.onmouseover = function(e) { $(this).addClass("list-hover"); };
li.onmouseout = function(e) { $(this).removeClass("list-hover"); };
return li;
}
function buildFileList(root,data) {
var ul = document.createElement("ul");
for (var i in data) {
var v = data[i];
if (typeof v === "string") {
// directory
var li = buildFileListItem(v);
li.onclick = function () {
var dirName = v;
return function(e) {
var bcli = $('<li class="active"><a href="#">'+dirName+'</a> <span class="divider">/</span></li>');
$("a",bcli).click(function(e) {
$(this).parent().nextAll().remove();
$.getJSON("library/"+options.url+root+dirName,function(data) {
$("#node-select-library").children().first().replaceWith(buildFileList(root+dirName+"/",data));
});
e.stopPropagation();
});
var bc = $("#node-dialog-library-breadcrumbs");
$(".active",bc).removeClass("active");
bc.append(bcli);
$.getJSON("library/"+options.url+root+dirName,function(data) {
$("#node-select-library").children().first().replaceWith(buildFileList(root+dirName+"/",data));
});
}
}();
li.innerHTML = '<i class="icon-folder-close"></i> '+v+"</i>";
ul.appendChild(li);
} else {
// file
var li = buildFileListItem(v);
li.innerHTML = v.name;
li.onclick = function() {
var item = v;
return function(e) {
$(".list-selected",ul).removeClass("list-selected");
$(this).addClass("list-selected");
$.get("library/"+options.url+root+item.fn, function(data) {
selectedLibraryItem = item;
libraryEditor.setText(data);
});
}
}();
ul.appendChild(li);
}
}
return ul;
}
$('#node-input-name').addClass('input-append-left').css("width","65%").after(
'<div class="btn-group" style="margin-left: -5px;">'+
'<button id="node-input-'+options.type+'-lookup" class="btn input-append-right" data-toggle="dropdown"><i class="icon-book"></i> <span class="caret"></span></button>'+
'<ul class="dropdown-menu pull-right" role="menu">'+
'<li><a id="node-input-'+options.type+'-menu-open-library" tabindex="-1" href="#">Open Library...</a></li>'+
'<li><a id="node-input-'+options.type+'-menu-save-library" tabindex="-1" href="#">Save to Library...</a></li>'+
'</ul></div>'
);
$('#node-input-'+options.type+'-menu-open-library').click(function(e) {
$("#node-select-library").children().remove();
var bc = $("#node-dialog-library-breadcrumbs");
bc.children().first().nextAll().remove();
libraryEditor.setText('');
$.getJSON("library/"+options.url,function(data) {
$("#node-select-library").append(buildFileList("/",data));
$("#node-dialog-library-breadcrumbs a").click(function(e) {
$(this).parent().nextAll().remove();
$("#node-select-library").children().first().replaceWith(buildFileList("/",data));
e.stopPropagation();
});
$( "#node-dialog-library-lookup" ).dialog( "open" );
});
e.preventDefault();
});
$('#node-input-'+options.type+'-menu-save-library').click(function(e) {
//var found = false;
var name = $("#node-input-name").val().replace(/(^\s*)|(\s*$)/g,"");
//var buildPathList = function(data,root) {
// var paths = [];
// if (data.d) {
// for (var i in data.d) {
// var dn = root+(root==""?"":"/")+i;
// var d = {
// label:dn,
// files:[]
// };
// for (var f in data.d[i].f) {
// d.files.push(data.d[i].f[f].fn.split("/").slice(-1)[0]);
// }
// paths.push(d);
// paths = paths.concat(buildPathList(data.d[i],root+(root==""?"":"/")+i));
// }
// }
// return paths;
//};
$("#node-dialog-library-save-folder").attr("value","");
var filename = name.replace(/[^\w-]/g,"-");
if (filename == "") {
filename = "unnamed-"+options.type;
}
$("#node-dialog-library-save-filename").attr("value",filename+".js");
//var paths = buildPathList(libraryData,"");
//$("#node-dialog-library-save-folder").autocomplete({
// minLength: 0,
// source: paths,
// select: function( event, ui ) {
// $("#node-dialog-library-save-filename").autocomplete({
// minLength: 0,
// source: ui.item.files
// });
// }
//});
$( "#node-dialog-library-save" ).dialog( "open" );
e.preventDefault();
});
require(["orion/editor/edit"], function(edit) {
libraryEditor = edit({
parent:document.getElementById('node-select-library-text'),
lang:"js",
readonly: true
});
});
$( "#node-dialog-library-lookup" ).dialog({
title: options.type+" library",
modal: true,
autoOpen: false,
width: 800,
height: 450,
buttons: [
{
text: "Ok",
click: function() {
if (selectedLibraryItem) {
for (var i in options.fields) {
var field = options.fields[i];
$("#node-input-"+field).val(selectedLibraryItem[field]);
};
options.editor.setText(libraryEditor.getText());
}
$( this ).dialog( "close" );
}
},
{
text: "Cancel",
click: function() {
$( this ).dialog( "close" );
}
}
],
open: function(e) {
var form = $("form",this);
form.height(form.parent().height()-30);
$(".form-row:last-child",form).height(form.height()-60);
},
resize: function(e) {
var form = $("form",this);
form.height(form.parent().height()-30);
$(".form-row:last-child",form).height(form.height()-60);
}
});
function saveToLibrary(overwrite) {
var name = $("#node-input-name").val().replace(/(^\s*)|(\s*$)/g,"");
if (name == "") {
name = "Unnamed "+options.type;
}
var filename = $("#node-dialog-library-save-filename").val().replace(/(^\s*)|(\s*$)/g,"");
var pathname = $("#node-dialog-library-save-folder").val().replace(/(^\s*)|(\s*$)/g,"");
if (filename == "" || !/.+\.js$/.test(filename)) {
RED.notify("Invalid filename","warning");
return;
}
var fullpath = pathname+(pathname==""?"":"/")+filename;
if (!overwrite) {
//var pathnameParts = pathname.split("/");
//var exists = false;
//var ds = libraryData;
//for (var pnp in pathnameParts) {
// if (ds.d && pathnameParts[pnp] in ds.d) {
// ds = ds.d[pathnameParts[pnp]];
// } else {
// ds = null;
// break;
// }
//}
//if (ds && ds.f) {
// for (var f in ds.f) {
// if (ds.f[f].fn == fullpath) {
// exists = true;
// break;
// }
// }
//}
//if (exists) {
// $("#node-dialog-library-save-type").html(options.type);
// $("#node-dialog-library-save-name").html(fullpath);
// $("#node-dialog-library-save-confirm").dialog( "open" );
// return;
//}
}
var queryArgs = [];
for (var i in options.fields) {
var field = options.fields[i];
if (field == "name") {
queryArgs.push("name="+encodeURIComponent(name));
} else {
queryArgs.push(encodeURIComponent(field)+"="+encodeURIComponent($("#node-input-"+field).val()));
}
}
var queryString = queryArgs.join("&");
var text = options.editor.getText();
$.post("library/"+options.url+'/'+fullpath+"?"+queryString,text,function() {
RED.notify("Saved "+options.type,"success");
});
}
$( "#node-dialog-library-save-confirm" ).dialog({
title: "Save to library",
modal: true,
autoOpen: false,
width: 530,
height: 230,
buttons: [
{
text: "Ok",
click: function() {
saveToLibrary(true);
$( this ).dialog( "close" );
}
},
{
text: "Cancel",
click: function() {
$( this ).dialog( "close" );
}
}
]
});
$( "#node-dialog-library-save" ).dialog({
title: "Save to library",
modal: true,
autoOpen: false,
width: 530,
height: 230,
buttons: [
{
text: "Ok",
click: function() {
saveToLibrary(false);
$( this ).dialog( "close" );
}
},
{
text: "Cancel",
click: function() {
$( this ).dialog( "close" );
}
}
]
});
}
return {
create: createUI,
loadFlowLibrary: loadFlowLibrary
}
}();

View File

@@ -0,0 +1,48 @@
/**
* Copyright 2013 IBM Corp.
*
* 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.notify = function() {
var currentNotifications = [];
var c = 0;
return function(msg,type) {
while (currentNotifications.length > 4) {
var n = currentNotifications[0];
window.clearTimeout(n.id);
n.slideup();
}
var n = document.createElement("div");
n.className = "alert";
if (type) {
n.className = "alert alert-"+type;
}
n.style.display = "none";
n.innerHTML = msg;
$("#notifications").append(n);
$(n).slideDown(300);
var slideup = function() {
var nn = n;
return function() {
currentNotifications.shift();
$(nn).slideUp(300, function() {
nn.parentNode.removeChild(nn);
});
};
}();
var id = window.setTimeout(slideup,3000);
currentNotifications.push({id:id,slideup:slideup,c:c});
c+=1;
}
}();

86
public/red/ui/palette.js Normal file
View File

@@ -0,0 +1,86 @@
/**
* Copyright 2013 IBM Corp.
*
* 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.palette = function() {
function addNodeType(nt,def) {
if (def.category != 'config') {
var d = document.createElement("div");
d.id = "pn_"+nt;
d.type = nt;
var label = /^(.*?)( in| out)?$/.exec(nt)[1];
d.innerHTML = '<div class="palette_label">'+label+"</div>";
d.className="palette_node";
if (def.icon) {
d.style.backgroundImage = "url(icons/"+def.icon+")";
if (def.align == "right") {
d.style.backgroundPosition = "95% 50%";
} else if (def.inputs > 0) {
d.style.backgroundPosition = "10% 50%";
}
}
d.style.backgroundColor = def.color;
if (def.outputs > 0) {
var port = document.createElement("div");
port.className = "palette_port palette_port_output";
d.appendChild(port);
}
if (def.inputs > 0) {
var port = document.createElement("div");
port.className = "palette_port";
d.appendChild(port);
}
// TODO: add categories dynamically?
$("#palette-"+def.category).append(d);
d.onmousedown = function(e) { e.preventDefault(); }
$(d).popover({
title:d.type,
placement:"right",
trigger: "hover",
delay: { show: 750, hide: 50 },
html: true,
title: nt,
container:'body',
content: $(($("script[data-help-name|='"+nt+"']").html()||"<p>no information available</p>").trim())[0]
});
$(d).draggable({
helper: 'clone',
appendTo: 'body',
revert: true,
revertDuration: 50
});
}
}
$(".palette-header").click(
function(e) {
$(this).next().slideToggle();
$(this).children("i").toggleClass("expanded");
});
return {
add:addNodeType
};
}();

93
public/red/ui/sidebar.js Normal file
View File

@@ -0,0 +1,93 @@
/**
* Copyright 2013 IBM Corp.
*
* 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.sidebar = function() {
$('#sidebar').tabs();
$('#btn-sidebar').click(function() {toggleSidebar();});
RED.keyboard.add(/* SPACE */ 32,{ctrl:true},function(){toggleSidebar();d3.event.preventDefault();});
var sidebarSeparator = {};
$("#sidebar-separator").draggable({
axis: "x",
start:function(event,ui) {
var winWidth = $(window).width();
sidebarSeparator.start = ui.position.left;
sidebarSeparator.width = $("#sidebar").width();
sidebarSeparator.chartWidth = $("#chart").width();
sidebarSeparator.chartRight = winWidth-$("#chart").width()-$("#chart").offset().left-2;
sidebarSeparator.closing = false;
},
drag: function(event,ui) {
var d = ui.position.left-sidebarSeparator.start;
var newSidebarWidth = sidebarSeparator.width-d;
if (newSidebarWidth > 180 && sidebarSeparator.chartWidth+d > 200) {
var newChartRight = sidebarSeparator.chartRight-d;
$("#chart").css("right",newChartRight);
$("#chart-zoom-controls").css("right",newChartRight+20);
$("#sidebar").width(newSidebarWidth);
}
if (newSidebarWidth < 150 && !sidebarSeparator.closing) {
$("#sidebar").addClass("closing");
sidebarSeparator.closing = true;
}
if (newSidebarWidth >= 150 && sidebarSeparator.closing) {
sidebarSeparator.closing = false;
$("#sidebar").removeClass("closing");
}
},
stop:function(event,ui) {
$("#sidebar-separator").css("left","auto");
$("#sidebar-separator").css("right",($("#sidebar").width()+15)+"px");
if (sidebarSeparator.closing) {
$("#sidebar").removeClass("closing");
toggleSidebar();
}
}
});
function toggleSidebar() {
if ($('#sidebar').tabs( "option", "active" ) === false) {
$('#sidebar').tabs( "option", "active",0);
}
var btnSidebar = $("#btn-sidebar");
btnSidebar.toggleClass("active");
if (!btnSidebar.hasClass("active")) {
$("#main-container").addClass("sidebar-closed");
} else {
$("#main-container").removeClass("sidebar-closed");
}
}
function addTab(title,content) {
var tab = document.createElement("li");
tab.innerHTML = '<a href="#tab-'+title+'">'+title+'</a>';
$("#sidebar-tabs").append(tab);
$("#sidebar-content").append(content);
$('#sidebar').tabs("refresh");
}
return {
addTab: addTab
}
}();

25
public/red/ui/state.js Normal file
View File

@@ -0,0 +1,25 @@
/**
* Copyright 2013 IBM Corp.
*
* 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.state = {
MOVING: 1,
JOINING: 2,
MOVING_ACTIVE: 3,
ADDING: 4,
EDITING: 5,
EXPORT: 6,
IMPORT: 7,
IMPORT_DRAGGING: 8
}

944
public/red/ui/view.js Normal file
View File

@@ -0,0 +1,944 @@
/**
* Copyright 2013 IBM Corp.
*
* 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.view = function() {
var space_width = 5000,
space_height = 5000,
lineCurveScale = 0.75,
scaleFactor = 1,
node_width = 100,
node_height = 30;
var selected_link = null,
mousedown_link = null,
mousedown_node = null,
mousedown_port_type = null,
mousedown_port_index = 0,
mouseup_node = null,
mouse_offset = [0,0],
mouse_position = null,
mouse_mode = 0,
moving_set = [],
dirty = false,
lasso = null,
active_group = null;
pressTimer = null;
var clipboard = "";
var outer = d3.select("#chart")
.append("svg:svg")
.attr("width", space_width)
.attr("height", space_height)
.attr("pointer-events", "all")
.style("cursor","crosshair");
var vis = outer
.append('svg:g')
.on("dblclick.zoom", null)
.append('svg:g')
.on("mousemove", canvasMouseMove)
.on("mousedown", canvasMouseDown)
.on("mouseup", canvasMouseUp)
.on("touchstart",canvasMouseDown)
.on("touchend",canvasMouseUp)
.on("touchmove",canvasMouseMove);
var outer_background = vis.append('svg:rect')
.attr('width', space_width)
.attr('height', space_height)
.attr('fill','#fff');
var drag_line = vis.append("svg:path").attr("class", "drag_line");
//d3.select(window).on("keydown", keydown);
function canvasMouseDown() {
// if (d3.event.shiftKey) {
// var point = d3.mouse(this),
// node = {x: point[0], y: point[1], w:node_width, h:node_height, type:Math.floor(Math.random()*3)},
// n = nodes.push(node);
// redraw();
// } else
//
if (typeof d3.touches(this)[0] == "object") {
pressTimer = setTimeout(function() { RED.history.pop(); }, 1500);
}
if (!mousedown_node && !mousedown_link) {
selected_link = null;
updateSelection();
//vis.call(d3.behavior.zoom().on("zoom"), rescale);
}
if (mouse_mode == 0) {
if (lasso) {
lasso.remove();
lasso = null;
}
var point = d3.touches(this)[0]||d3.mouse(this);
if (d3.touches(this).length === 0) {
lasso = vis.append('rect')
.attr("ox",point[0])
.attr("oy",point[1])
.attr("rx",2)
.attr("ry",2)
.attr("x",point[0])
.attr("y",point[1])
.attr("width",0)
.attr("height",0)
.attr("class","lasso");
d3.event.preventDefault();
}
}
}
function canvasMouseMove() {
clearTimeout(pressTimer);
mouse_position = d3.touches(this)[0]||d3.mouse(this);
// TODO: auto scroll the container
//var point = d3.mouse(this);
//if (point[0]-container.scrollLeft < 30 && container.scrollLeft > 0) { container.scrollLeft -= 15; }
//console.log(d3.mouse(this),container.offsetWidth,container.offsetHeight,container.scrollLeft,container.scrollTop);
if (lasso) {
var ox = parseInt(lasso.attr("ox"));
var oy = parseInt(lasso.attr("oy"));
var x = parseInt(lasso.attr("x"));
var y = parseInt(lasso.attr("y"));
if (mouse_position[0] < ox) {
x = mouse_position[0];
w = ox-x;
} else {
w = mouse_position[0]-x;
}
if (mouse_position[1] < oy) {
y = mouse_position[1];
h = oy-y;
} else {
h = mouse_position[1]-y;
}
lasso
.attr("x",x)
.attr("y",y)
.attr("width",w)
.attr("height",h)
;
return;
}
if (mouse_mode != RED.state.IMPORT_DRAGGING && !mousedown_node && selected_link == null) return;
if (mouse_mode == RED.state.JOINING) {
// update drag line
drag_line.attr("class", "drag_line");
var mousePos = mouse_position;
var numOutputs = (mousedown_port_type == 0)?(mousedown_node.outputs || 1):1;
var sourcePort = mousedown_port_index;
var y = -((numOutputs-1)/2)*13 +13*sourcePort;
var sc = (mousedown_port_type == 0)?1:-1;
var dy = mousePos[1]-(mousedown_node.y+y);
var dx = mousePos[0]-(mousedown_node.x+sc*mousedown_node.w/2);
var delta = Math.sqrt(dy*dy+dx*dx);
var scale = lineCurveScale;
if (delta < node_width) {
scale = 0.75-0.75*((node_width-delta)/node_width);
}
drag_line.attr("d",
"M "+(mousedown_node.x+sc*mousedown_node.w/2)+" "+(mousedown_node.y+y)+
" C "+(mousedown_node.x+sc*(mousedown_node.w/2+node_width*scale))+" "+(mousedown_node.y+y)+" "+
(mousePos[0]-sc*(scale)*node_width)+" "+mousePos[1]+" "+
mousePos[0]+" "+mousePos[1]
);
} else if (mouse_mode == RED.state.MOVING) {
var m = mouse_position;
var d = (mouse_offset[0]-m[0])*(mouse_offset[0]-m[0]) + (mouse_offset[1]-m[1])*(mouse_offset[1]-m[1]);
if (d > 2) {
mouse_mode = RED.state.MOVING_ACTIVE;
clearTimeout(pressTimer);
}
} else if (mouse_mode == RED.state.MOVING_ACTIVE || mouse_mode == RED.state.IMPORT_DRAGGING) {
var mousePos = mouse_position;
if (d3.event.shiftKey && moving_set.length > 1) {
mousePos[0] = 20*Math.floor(mousePos[0]/20);
mousePos[1] = 20*Math.floor(mousePos[1]/20);
}
for (var n in moving_set) {
var node = moving_set[n];
node.n.x = mousePos[0]+node.dx;
node.n.y = mousePos[1]+node.dy;
if (d3.event.shiftKey && moving_set.length == 1) {
node.n.x = 20*Math.floor(node.n.x/20);
node.n.y = 20*Math.floor(node.n.y/20);
}
node.n.dirty = true;
}
}
redraw();
}
function canvasMouseUp() {
clearTimeout(pressTimer);
if (mousedown_node && mouse_mode == RED.state.JOINING) {
drag_line.attr("class", "drag_line_hidden");
}
if (lasso) {
var x = parseInt(lasso.attr("x"));
var y = parseInt(lasso.attr("y"));
var x2 = x+parseInt(lasso.attr("width"));
var y2 = y+parseInt(lasso.attr("height"));
if (!d3.event.ctrlKey) {
clearSelection();
}
RED.nodes.eachNode(function(n) {
if (!n.selected) {
n.selected = (n.x > x && n.x < x2 && n.y > y && n.y < y2);
if (n.selected) {
n.dirty = true;
moving_set.push({n:n});
}
}
});
updateSelection();
lasso.remove();
lasso = null;
}
if (mouse_mode == RED.state.MOVING_ACTIVE) {
if (moving_set.length > 0) {
var ns = [];
for (var i in moving_set) {
ns.push({n:moving_set[i].n,ox:moving_set[i].ox,oy:moving_set[i].oy});
}
RED.history.push({t:'move',nodes:ns,dirty:dirty});
}
}
if (mouse_mode == RED.state.IMPORT_DRAGGING) {
RED.keyboard.remove(/* ESCAPE */ 27);
var mousePos = d3.touches(this)[0]||d3.mouse(this);
if (d3.event.shiftKey && moving_set.length > 1) {
mousePos[0] = 20*Math.floor(mousePos[0]/20);
mousePos[1] = 20*Math.floor(mousePos[1]/20);
}
for (var n in moving_set) {
var node = moving_set[n];
node.n.x = mousePos[0]+node.dx;
node.n.y = mousePos[1]+node.dy;
if (d3.event.shiftKey && moving_set.length == 1) {
node.n.x = 20*Math.floor(node.n.x/20);
node.n.y = 20*Math.floor(node.n.y/20);
}
node.n.dirty = true;
}
}
redraw();
// clear mouse event vars
resetMouseVars();
}
$('#btn-zoom-out').click(function() {zoomOut();});
$('#btn-zoom-zero').click(function() {zoomZero();});
$('#btn-zoom-in').click(function() {zoomIn();});
$("#chart").on('DOMMouseScroll mousewheel', function (evt) {
if ( evt.altKey ) {
evt.preventDefault();
evt.stopPropagation();
var move = evt.originalEvent.detail || evt.originalEvent.wheelDelta;
if (move <= 0) { zoomIn(); }
else { zoomOut(); }
}
});
$("#chart").droppable({
accept:".palette_node",
drop: function( event, ui ) {
d3.event = event;
var selected_tool = ui.draggable[0].type;
var mousePos = d3.touches(this)[0]||d3.mouse(this);
mousePos[1] += this.scrollTop;
mousePos[0] += this.scrollLeft;
mousePos[1] /= scaleFactor;
mousePos[0] /= scaleFactor;
var nn = { id:(1+Math.random()*4294967295).toString(16),x: mousePos[0],y:mousePos[1],w:node_width};
nn.type = selected_tool;
nn._def = RED.nodes.getType(nn.type);
nn.outputs = nn._def.outputs;
nn.h = Math.max(node_height,(nn.outputs||0) * 15);
for (var d in nn._def.defaults) {
nn[d] = nn._def.defaults[d].value;
}
RED.history.push({t:'add',nodes:[nn.id],dirty:dirty});
RED.nodes.add(nn);
RED.editor.validateNode(nn);
setDirty(true);
redraw();
if (nn._def.autoedit) {
RED.editor.edit(nn);
}
}
});
function zoomIn() {
if (scaleFactor < 2) {
scaleFactor += 0.1;
redraw();
}
}
function zoomOut() {
if (scaleFactor > 0.3) {
scaleFactor -= 0.1;
redraw();
}
}
function zoomZero() {
scaleFactor = 1;
redraw();
}
function selectAll() {
RED.nodes.eachNode(function(n) {
if (!n.selected) {
n.selected = true;
n.dirty = true;
moving_set.push({n:n});
}
});
selected_link = null;
updateSelection();
redraw();
}
function clearSelection() {
for (var i in moving_set) {
var n = moving_set[i];
n.n.dirty = true;
n.n.selected = false;
}
moving_set = [];
selected_link = null;
}
function updateSelection() {
if (moving_set.length == 0) {
$("#li-menu-export").addClass("disabled");
$("#li-menu-export-clipboard").addClass("disabled");
$("#li-menu-export-library").addClass("disabled");
} else {
$("#li-menu-export").removeClass("disabled");
$("#li-menu-export-clipboard").removeClass("disabled");
$("#li-menu-export-library").removeClass("disabled");
}
if (moving_set.length == 0 && selected_link == null) {
RED.keyboard.remove(/* backspace */ 8);
RED.keyboard.remove(/* delete */ 46);
RED.keyboard.remove(/* c */ 67);
} else {
RED.keyboard.add(/* backspace */ 8,function(){deleteSelection();d3.event.preventDefault();});
RED.keyboard.add(/* delete */ 46,function(){deleteSelection();d3.event.preventDefault();});
RED.keyboard.add(/* c */ 67,{ctrl:true},function(){copySelection();d3.event.preventDefault();});
}
if (moving_set.length == 1) {
buildInfo(moving_set[0].n);
} else {
$("#tab-info").html("");
}
}
function deleteSelection() {
var removedNodes = [];
var removedLinks = [];
var startDirty = dirty;
if (moving_set.length > 0) {
for (var i in moving_set) {
var node = moving_set[i].n;
node.selected = false;
if (node.x < 0) {node.x = 25};
var rmlinks = RED.nodes.remove(node.id);
removedNodes.push(node);
removedLinks = removedLinks.concat(rmlinks);
}
moving_set = [];
setDirty(true);
}
if (selected_link) {
RED.nodes.removeLink(selected_link);
removedLinks.push(selected_link);
setDirty(true);
}
RED.history.push({t:'delete',nodes:removedNodes,links:removedLinks,dirty:startDirty});
selected_link = null;
updateSelection();
redraw();
}
function copySelection() {
if (moving_set.length > 0) {
var nns = [];
for (var n in moving_set) {
var node = moving_set[n].n;
nns.push(RED.nodes.convertNode(node));
}
clipboard = JSON.stringify(nns);
RED.notify(moving_set.length+" node"+(moving_set.length>1?"s":"")+" copied");
}
}
function buildInfo(node) {
var table = '<table class="node-info"><tbody>';
table += "<tr><td>Type</td><td>&nbsp;"+node.type+"</td></tr>";
table += "<tr><td>ID</td><td>&nbsp;"+node.id+"</td></tr>";
table += '<tr class="blank"><td colspan="2">&nbsp;Properties</td></tr>';
for (var n in node._def.defaults) {
if ((n != "func")&&(n != "template")) {
var safe = (node[n]||"").toString().replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");
table += "<tr><td>&nbsp;"+n+"</td><td>"+safe+"</td></tr>";
}
if ((n == "func")||(n == "template")) {
table += "<tr><td>&nbsp;"+n+"</td><td>(...)</td></tr>";
}
}
table += "</tbody></table><br/>";
table += '<div class="node-help">'+($("script[data-help-name|='"+node.type+"']").html()||"")+"</div>";
$("#tab-info").html(table);
}
function calculateTextWidth(str) {
var sp = document.createElement("span");
sp.className = "node_label";
sp.style.position = "absolute";
sp.style.top = "-1000px";
sp.innerHTML = (str||"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");
document.body.appendChild(sp);
var w = sp.offsetWidth;
document.body.removeChild(sp);
return 35+w;
}
function resetMouseVars() {
mousedown_node = null;
mouseup_node = null;
mousedown_link = null;
mouse_mode = 0;
mousedown_port_type = 0;
}
function portMouseDown(d,portType,portIndex) {
// disable zoom
vis.call(d3.behavior.zoom().on("zoom"), null);
mousedown_node = d;
selected_link = null;
mouse_mode = RED.state.JOINING;
mousedown_port_type = portType;
mousedown_port_index = portIndex || 0;
document.body.style.cursor = "crosshair";
};
function portMouseUp(d,portType,portIndex) {
document.body.style.cursor = "";
if (mouse_mode == RED.state.JOINING && mousedown_node) {
mouseup_node = d;
if (portType == mousedown_port_type || mouseup_node === mousedown_node) {
drag_line.attr("class", "drag_line_hidden");
resetMouseVars(); return;
}
var src,dst,src_port;
if (mousedown_port_type == 0) {
src = mousedown_node;
src_port = mousedown_port_index;
dst = mouseup_node;
} else if (mousedown_port_type == 1) {
src = mouseup_node;
dst = mousedown_node;
src_port = portIndex;
}
var existingLink = false;
RED.nodes.eachLink(function(d) {
existingLink = existingLink || (d.source === src && d.target === dst && d.sourcePort == src_port);
});
if (!existingLink) {
var link = {source: src, sourcePort:src_port, target: dst};
RED.nodes.addLink(link);
RED.history.push({t:'add',links:[link],dirty:dirty});
setDirty(true);
}
selected_link = null;
redraw();
}
}
function nodeMouseUp(d) {
portMouseUp(d, d._def.inputs > 0 ? 1 : 0, 0);
}
function nodeMouseDown(d) {
if (typeof d3.touches(this)[0] == "object") {
pressTimer = setTimeout(function() { RED.editor.edit(d); }, 1500);
}
if (mouse_mode == RED.state.IMPORT_DRAGGING) {
RED.keyboard.remove(/* ESCAPE */ 27);
updateSelection();
setDirty(true);
redraw();
resetMouseVars();
d3.event.stopPropagation();
return;
}
mousedown_node = d;
if (d.selected && d3.event.ctrlKey) {
d.selected = false;
for (var i=0;i<moving_set.length;i+=1) {
if (moving_set[i].n === d) {
moving_set.splice(i,1);
break;
}
}
} else {
if (d3.event.shiftKey) {
clearSelection();
var cnodes = RED.nodes.getAllFlowNodes(mousedown_node);
for (var i in cnodes) {
cnodes[i].selected = true;
cnodes[i].dirty = true;
moving_set.push({n:cnodes[i]});
}
} else if (!d.selected) {
if (!d3.event.ctrlKey) {
clearSelection();
}
mousedown_node.selected = true;
moving_set.push({n:mousedown_node});
}
selected_link = null;
if (d3.event.button != 2) {
mouse_mode = RED.state.MOVING;
var mouse = d3.touches(this)[0]||d3.mouse(this);
mouse[0] += d.x-d.w/2;
mouse[1] += d.y-d.h/2;
for (var i in moving_set) {
moving_set[i].ox = moving_set[i].n.x;
moving_set[i].oy = moving_set[i].n.y;
moving_set[i].dx = moving_set[i].n.x-mouse[0];
moving_set[i].dy = moving_set[i].n.y-mouse[1];
}
mouse_offset = d3.mouse(document.body);
if (isNaN(mouse_offset[0])) {
mouse_offset = d3.touches(document.body)[0];
}
}
}
d.dirty = true;
updateSelection();
redraw();
d3.event.stopPropagation();
}
function redraw() {
vis.attr("transform","scale("+scaleFactor+")");
outer.attr("width", space_width*scaleFactor).attr("height", space_height*scaleFactor);
outer_background.attr('fill', function() {
return active_group == null?'#fff':'#eee';
});
if (mouse_mode != RED.state.JOINING) {
// Don't bother redrawing nodes if we're drawing links
var node = vis.selectAll(".nodegroup").data(RED.nodes.nodes,function(d){return d.id});
node.exit().remove();
var nodeEnter = node.enter().insert("svg:g").attr("class", "node nodegroup");
nodeEnter.each(function(d,i) {
var node = d3.select(this);
var l = d._def.label;
l = (typeof l === "function" ? l.call(d) : l)||"";
d.w = Math.max(node_width,calculateTextWidth(l)+(d._def.inputs>0?7:0) );
d.h = Math.max(node_height,(d.outputs||0) * 15);
if (d._def.badge) {
var badge = node.append("svg:g").attr("class","node_badge_group");
var badgeRect = badge.append("rect").attr("class","node_badge").attr("rx",5).attr("ry",5).attr("width",40).attr("height",15);
badge.append("svg:text").attr("class","node_badge_label").attr("x",35).attr("y",11).attr('text-anchor','end').text(d._def.badge());
if (d._def.onbadgeclick) {
badgeRect.attr("cursor","pointer")
.on("click",function(d) { d._def.onbadgeclick.call(d);d3.event.preventDefault();});
}
}
if (d._def.button) {
node.append('rect')
.attr("class",function(d) { return (d._def.align == "right") ? "node_right_button_group" : "node_left_button_group"; })
.attr("x",function(d) { return (d._def.align == "right") ? 94 : -25; })
.attr("y",2)
.attr("rx",8)
.attr("ry",8)
.attr("width",32)
.attr("height",node_height-4)
.attr("fill","#eee");//function(d) { return d._def.color;})
node.append('rect')
.attr("class",function(d) { return (d._def.align == "right") ? "node_right_button" : "node_left_button"; })
.attr("x",function(d) { return (d._def.align == "right") ? 104 : -20; })
.attr("y",6)
.attr("rx",5)
.attr("ry",5)
.attr("width",16)
.attr("height",node_height-12)
.attr("fill",function(d) { return d._def.color;})
.attr("cursor","pointer")
.on("mousedown",function(d) {if (!lasso) { d3.select(this).attr("fill-opacity",0.2);d3.event.preventDefault(); d3.event.stopPropagation();}})
.on("mouseup",function(d) {if (!lasso) { d3.select(this).attr("fill-opacity",0.4);d3.event.preventDefault();d3.event.stopPropagation();}})
.on("mouseover",function(d) {if (!lasso) { d3.select(this).attr("fill-opacity",0.4);}})
.on("mouseout",function(d) {if (!lasso) { d3.select(this).attr("fill-opacity",1);}})
.on("click",function(d) { d._def.button.onclick.call(d); d3.event.preventDefault(); })
.on("touchstart",function(d) { d._def.button.onclick.call(d); d3.event.preventDefault(); })
}
var mainRect = node.append("rect")
.attr("class", "node")
.attr("rx", 6)
.attr("ry", 6)
.attr("fill",function(d) { return d._def.color;})
.on("mousedown",nodeMouseDown)
.on("touchstart",nodeMouseDown)
.on("dblclick",function(d) {RED.editor.edit(d);})
.on("mouseover",function(d) {
if (mouse_mode == 0) {
var node = d3.select(this);
node.classed("node_hovered",true);
}
})
.on("mouseout",function(d) {
var node = d3.select(this);
node.classed("node_hovered",false);
});
//node.append("rect").attr("class", "node-gradient-top").attr("rx", 6).attr("ry", 6).attr("height",30).attr("stroke","none").attr("fill","url(#gradient-top)").style("pointer-events","none");
//node.append("rect").attr("class", "node-gradient-bottom").attr("rx", 6).attr("ry", 6).attr("height",30).attr("stroke","none").attr("fill","url(#gradient-bottom)").style("pointer-events","none");
mainRect.on("mouseup",nodeMouseUp);
mainRect.on("touchend",function(){ clearTimeout(pressTimer); nodeMouseUp; });
//mainRect.on("touchend",nodeMouseUp);
if (d._def.icon) {
var icon = node.append("image").attr("xlink:href","icons/"+d._def.icon).attr("class","node_icon").attr("x",0).attr("y",0).attr("width","15").attr("height",function(d){return Math.min(50,d.h);});
if (d._def.align) {
icon.attr('class','node_icon node_icon_'+d._def.align);
}
if (d._def.inputs > 0) {
icon.attr("x",8);
}
icon.style("pointer-events","none");
}
var text = node.append('svg:text').attr('class','node_label').attr('x', 23).attr('dy', '.35em').attr('text-anchor','start');
if (d._def.align) {
text.attr('class','node_label node_label_'+d._def.align);
text.attr('text-anchor','end');
}
if (d._def.inputs > 0) {
text.attr("x",30);
node.append("rect").attr("class","port port_input").attr("rx",3).attr("ry",3).attr("x",-5).attr("width",10).attr("height",10)
.on("mousedown",function(d){portMouseDown(d,1,0);})
.on("touchstart",function(d){portMouseDown(d,1,0);})
.on("mouseup",function(d){portMouseUp(d,1,0);} )
.on("touchend",function(d){portMouseUp(d,1,0);} )
.on("mouseover",function(d) { var port = d3.select(this); port.classed("port_hovered",(mouse_mode!=RED.state.JOINING || mousedown_port_type != 1 ));})
.on("mouseout",function(d) { var port = d3.select(this); port.classed("port_hovered",false);})
}
//node.append("path").attr("class","node_error").attr("d","M 3,-3 l 10,0 l -5,-8 z");
node.append("image").attr("class","node_error hidden").attr("xlink:href","icons/node-error.png").attr("x",0).attr("y",-6).attr("width",10).attr("height",9);
});
node.each(function(d,i) {
if (d.dirty) {
if (d.x < -50) deleteSelection(); // Delete nodes if dragged back to palette
if (d.resize) {
var l = d._def.label;
l = (typeof l === "function" ? l.call(d) : l)||"";
d.w = Math.max(node_width,calculateTextWidth(l)+(d._def.inputs>0?7:0) );
d.h = Math.max(node_height,(d.outputs||0) * 15);
}
var thisNode = d3.select(this);
thisNode.attr("transform", function(d) { return "translate(" + (d.x-d.w/2) + "," + (d.y-d.h/2) + ")"; });
thisNode.selectAll(".node")
.attr("width",function(d){return d.w})
.attr("height",function(d){return d.h})
.classed("node_selected",function(d) { return d.selected; })
.classed("node_highlighted",function(d) { return d.highlighted; })
;
//thisNode.selectAll(".node-gradient-top").attr("width",function(d){return d.w});
//thisNode.selectAll(".node-gradient-bottom").attr("width",function(d){return d.w}).attr("y",function(d){return d.h-30});
thisNode.selectAll(".node_label_right").attr('x', function(d){return d.w-23-(d.outputs>0?5:0);});
thisNode.selectAll(".node_icon_right").attr("x",function(d){return d.w-16-(d.outputs>0?5:0);});
var numOutputs = d.outputs;
var y = (d.h/2)-((numOutputs-1)/2)*13;
d.ports = d.ports || d3.range(numOutputs);
d._ports = thisNode.selectAll(".port_output").data(d.ports);
d._ports.enter().append("rect").attr("class","port port_output").attr("rx",3).attr("ry",3).attr("width",10).attr("height",10)
.on("mousedown",function(){var node = d; return function(d,i){portMouseDown(node,0,i);}}() )
.on("touchstart",function(){var node = d; return function(d,i){portMouseDown(node,0,i);}}() )
.on("mouseup",function(){var node = d; return function(d,i){portMouseUp(node,0,i);}}() )
.on("touchend",function(){var node = d; return function(d,i){portMouseUp(node,0,i);}}() )
.on("mouseover",function(d,i) { var port = d3.select(this); port.classed("port_hovered",(mouse_mode!=RED.state.JOINING || mousedown_port_type != 0 ));})
.on("mouseout",function(d,i) { var port = d3.select(this); port.classed("port_hovered",false);});
d._ports.exit().remove();
if (d._ports) {
var numOutputs = d.outputs || 1;
var y = (d.h/2)-((numOutputs-1)/2)*13;
var x = d.w - 5;
d._ports.each(function(d,i) {
var port = d3.select(this);
port.attr("y",(y+13*i)-5).attr("x",x);
});
}
thisNode.selectAll('text.node_label').text(function(d,i){
if (d._def.label) {
if (typeof d._def.label == "function") {
return d._def.label.call(d);
} else {
return d._def.label;
}
}
return "";
})
.attr('y', function(d){return (d.h/2)-1;})
.attr('class',function(d){
return 'node_label'+
(d._def.align?' node_label_'+d._def.align:'')+
(d._def.label?' '+(typeof d._def.labelStyle == "function" ? d._def.labelStyle.call(d):d._def.labelStyle):'') ;
});
thisNode.selectAll(".node_tools").attr("x",function(d){return d.w-35;}).attr("y",function(d){return d.h-20;});
thisNode.selectAll(".node_error")
.attr("x",function(d){return d.w-5})
.classed("hidden",function(d) { return d.valid; });
thisNode.selectAll(".port_input").each(function(d,i) {
var port = d3.select(this);
port.attr("y",function(d){return (d.h/2)-5;})
});
thisNode.selectAll(".node_icon").attr("height",function(d){return Math.min(50,d.h);});
thisNode.selectAll('.node_right_button_group').attr("transform",function(d){return "translate("+(d.w-100)+","+0+")";});
thisNode.selectAll('.node_right_button').attr("transform",function(d){return "translate("+(d.w-100)+","+0+")";}).attr("fill",function(d) {
return typeof d._def.button.color === "function" ? d._def.button.color.call(d):(d._def.button.color != null ? d._def.button.color : d._def.color)
});
thisNode.selectAll('.node_badge_group').attr("transform",function(d){return "translate("+(d.w-40)+","+(d.h+3)+")";});
thisNode.selectAll('text.node_badge_label').text(function(d,i) {
if (d._def.badge) {
if (typeof d._def.badge == "function") {
return d._def.badge.call(d);
} else {
return d._def.badge;
}
}
return "";
});
d.dirty = false;
}
});
}
var link = vis.selectAll(".link").data(RED.nodes.links);
link.enter().insert("svg:path",".node").attr("class","link")
.on("mousedown",function(d) {
mousedown_link = d;
clearSelection();
selected_link = mousedown_link;
updateSelection();
redraw();
d3.event.stopPropagation();
})
.on("touchstart",function(d) {
mousedown_link = d;
clearSelection();
selected_link = mousedown_link;
updateSelection();
redraw();
d3.event.stopPropagation();
pressTimer = setTimeout(function() { deleteSelection(); }, 1500);
})
.on("touchend",function() { clearTimeout(pressTimer); });
link.exit().remove();
link.attr("d",function(d){
var numOutputs = d.source.outputs || 1;
var sourcePort = d.sourcePort || 0;
var y = -((numOutputs-1)/2)*13 +13*sourcePort;
var dy = d.target.y-(d.source.y+y);
var dx = (d.target.x-d.target.w/2)-(d.source.x+d.source.w/2);
var delta = Math.sqrt(dy*dy+dx*dx);
var scale = lineCurveScale;
if (delta < node_width) {
scale = 0.75-0.75*((node_width-delta)/node_width);
}
d.x1 = d.source.x+d.source.w/2;
d.y1 = d.source.y+y;
d.x2 = d.target.x-d.target.w/2;
d.y2 = d.target.y;
return "M "+(d.source.x+d.source.w/2)+" "+(d.source.y+y)+
" C "+(d.source.x+d.source.w/2+scale*node_width)+" "+(d.source.y+y)+" "+
(d.target.x-d.target.w/2-scale*node_width)+" "+d.target.y+" "+
(d.target.x-d.target.w/2)+" "+d.target.y;
})
link.classed("link_selected", function(d) { return d === selected_link || d.selected; });
if (d3.event) {
d3.event.preventDefault();
}
}
RED.keyboard.add(/* z */ 90,{ctrl:true},function(){RED.history.pop();});
RED.keyboard.add(/* a */ 65,{ctrl:true},function(){selectAll();d3.event.preventDefault();});
RED.keyboard.add(/* = */ 187,{ctrl:true},function(){zoomIn();d3.event.preventDefault();});
RED.keyboard.add(/* - */ 189,{ctrl:true},function(){zoomOut();d3.event.preventDefault();});
RED.keyboard.add(/* 0 */ 48,{ctrl:true},function(){zoomZero();d3.event.preventDefault();});
RED.keyboard.add(/* v */ 86,{ctrl:true},function(){importNodes(clipboard);d3.event.preventDefault();});
RED.keyboard.add(/* e */ 69,{ctrl:true},function(){showExportNodesDialog();d3.event.preventDefault();});
RED.keyboard.add(/* i */ 73,{ctrl:true},function(){showImportNodesDialog();d3.event.preventDefault();});
// TODO: 'dirty' should be a property of RED.nodes - with an event callback for ui hooks
function setDirty(d) {
dirty = d;
if (dirty) {
$("#btn-deploy").removeClass("disabled").addClass("btn-danger");
} else {
$("#btn-deploy").addClass("disabled").removeClass("btn-danger");;
}
}
/**
* Imports a new collection of nodes from a JSON String.
* - all get new IDs assigned
* - all 'selected'
* - attached to mouse for placing - 'IMPORT_DRAGGING'
*/
function importNodes(newNodesStr) {
try {
var result = RED.nodes.import(newNodesStr,true);
if (result) {
var new_nodes = result[0];
var new_links = result[1];
var new_ms = new_nodes.map(function(n) { return {n:n};});
var new_node_ids = new_nodes.map(function(n){ return n.id; });
// TODO: pick a more sensible root node
var root_node = new_ms[0].n;
var dx = root_node.x;
var dy = root_node.y;
for (var i in new_ms) {
new_ms[i].n.selected = true;
new_ms[i].n.x -= dx - mouse_position[0];
new_ms[i].n.y -= dy - mouse_position[1];
new_ms[i].dx = new_ms[i].n.x - mouse_position[0];
new_ms[i].dy = new_ms[i].n.y - mouse_position[1];
}
mouse_mode = RED.state.IMPORT_DRAGGING;
RED.keyboard.add(/* ESCAPE */ 27,function(){
RED.keyboard.remove(/* ESCAPE */ 27);
clearSelection();
RED.history.pop();
mouse_mode = 0;
});
RED.history.push({t:'add',nodes:new_node_ids,links:new_links,dirty:RED.view.dirty()});
clearSelection();
moving_set = new_ms;
redraw();
}
} catch(error) {
console.log(error);
RED.notify("<strong>Error</strong>: "+error,"error");
}
}
$('#btn-import').click(function() {showImportNodesDialog();});
$('#btn-export-clipboard').click(function() {showExportNodesDialog();});
$('#btn-export-library').click(function() {showExportNodesLibraryDialog();});
function showExportNodesDialog() {
mouse_mode = RED.state.EXPORT;
var nns = RED.nodes.createExportableNodeSet(moving_set);
$("#dialog-form").html($("script[data-template-name='export-clipboard-dialog']").html());
$("#node-input-export").val(JSON.stringify(nns));
$("#node-input-export").focus(function() {
var textarea = $(this);
textarea.select();
textarea.mouseup(function() {
textarea.unbind("mouseup");
return false;
});
});
$( "#dialog" ).dialog("option","title","Export nodes to clipboard").dialog( "open" );
$("#node-input-export").focus();
}
function showExportNodesLibraryDialog() {
mouse_mode = RED.state.EXPORT;
var nns = RED.nodes.createExportableNodeSet(moving_set);
$("#dialog-form").html($("script[data-template-name='export-library-dialog']").html());
$("#node-input-filename").attr('nodes',JSON.stringify(nns));
$( "#dialog" ).dialog("option","title","Export nodes to library").dialog( "open" );
}
function showImportNodesDialog() {
mouse_mode = RED.state.IMPORT;
$("#dialog-form").html($("script[data-template-name='import-dialog']").html());
$("#node-input-import").val("");
$( "#dialog" ).dialog("option","title","Import nodes").dialog( "open" );
}
return {
state:function(state) {
if (state == null) {
return mouse_mode
} else {
mouse_mode = state;
}
},
redraw:redraw,
dirty: function(d) {
if (d == null) {
return dirty;
} else {
setDirty(d);
}
},
importNodes: importNodes
};
}();

19
public/red/validators.js Normal file
View File

@@ -0,0 +1,19 @@
/**
* Copyright 2013 IBM Corp.
*
* 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.validators = {
number: function(){return function(v) { return v!=='' && !isNaN(v);}},
regex: function(re){return function(v) { return re.test(v);}}
};