workflow.js 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069
  1. // Licensed to Cloudera, Inc. under one
  2. // or more contributor license agreements. See the NOTICE file
  3. // distributed with this work for additional information
  4. // regarding copyright ownership. Cloudera, Inc. licenses this file
  5. // to you under the Apache License, Version 2.0 (the
  6. // "License"); you may not use this file except in compliance
  7. // with the License. You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing, software
  12. // distributed under the License is distributed on an "AS IS" BASIS,
  13. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. // See the License for the specific language governing permissions and
  15. // limitations under the License.
  16. var Registry = RegistryModule($);
  17. var Modal = ModalModule($, ko);
  18. var Node = NodeModule($, IdGeneratorTable, NodeFields);
  19. var StartNode = NodeModule($, IdGeneratorTable, NodeFields);
  20. $.extend(StartNode.prototype, Node.prototype, {
  21. /**
  22. * Same as addChild for nodes, except if we reach the end,
  23. * we add the end node to our child_links in the form of a
  24. * 'related' link and 'start' link.
  25. * We should always have a start link in an empty workflow!
  26. */
  27. replaceChild: function(child, replacement) {
  28. var self = this;
  29. var index = -1;
  30. $.each(self.non_error_links(), function(i, link) {
  31. if (link.child() == child.id()) {
  32. index = i;
  33. }
  34. });
  35. if (index > -1) {
  36. self.child_links.splice(index, 1);
  37. var links = self.child_links.splice(index);
  38. var link = {
  39. parent: ko.observable(self.id()),
  40. child: ko.observable(replacement.id()),
  41. name: ko.observable('to'),
  42. comment: ko.observable('')
  43. };
  44. self.child_links.push(link);
  45. $.each(links, function(index, link) {
  46. self.child_links.push(link);
  47. });
  48. }
  49. return index != -1;
  50. }
  51. });
  52. var ForkNode = NodeModule($, IdGeneratorTable, NodeFields);
  53. $.extend(ForkNode.prototype, Node.prototype, {
  54. // Join nodes are connected through 'related' links
  55. join: function() {
  56. var self = this;
  57. var join = null;
  58. $.each(self.child_links(), function(index, link) {
  59. if (link.name() == 'related') {
  60. join = self.registry.get(link.child());
  61. }
  62. });
  63. return join;
  64. },
  65. /**
  66. * Append a node to the current fork
  67. * Also adds join node to node.
  68. * When adding the join node, append will remove all the children from the join!
  69. * We need to make sure the join remembers its children since append will replace them.
  70. * NOTE: Cannot append a fork or decision! Use addChild or replaceChild instead!
  71. */
  72. append: function(node) {
  73. var self = this;
  74. if (node.node_type() != 'decision' && node.node_type() != 'fork') {
  75. var join = self.join();
  76. if (join.id() != node.id()) {
  77. var children = join.findChildren();
  78. self.addChild(node);
  79. node.append(join);
  80. // remember children
  81. $.each(children, function(index, child) {
  82. join.addChild(child);
  83. });
  84. }
  85. }
  86. },
  87. /**
  88. * Replace child node with another node
  89. * 1. Remove child if the replacement is related join
  90. * 2. Apply Node.replaceChild for all other causes
  91. * NOTE: can assume the only join this fork will ever see is the related join!
  92. * This is because the related will always be the closest join for children.
  93. * Also, the operations allowed that would make this all possible: detach, append;
  94. * are inherently going to remove any other joins if they exist.
  95. * This is also easier given nodes are contained within Forks!
  96. */
  97. replaceChild: function(child, replacement) {
  98. var self = this;
  99. var ret = true;
  100. if (self.join().id() == replacement.id()) {
  101. ret = self.removeChild(child);
  102. } else {
  103. ret = Node.prototype.replaceChild.apply(self, arguments);
  104. }
  105. var links = self.links().filter(function(element, index, arr) {
  106. return self.registry.get(element.child()).node_type() != 'join';
  107. });
  108. if (links.length < 2) {
  109. self.detach();
  110. self.join().detach();
  111. self.erase();
  112. self.join().erase();
  113. }
  114. return ret;
  115. },
  116. /**
  117. * Converts fork node into decision node in the following way:
  118. * 1. Copies contents of current fork node into a new decision node
  119. * 2. Detach fork node
  120. * 3. Erase fork node
  121. * 4. Append decision node to parent
  122. */
  123. convertToDecision: function() {
  124. var self = this;
  125. var join = self.join();
  126. var end = null;
  127. var child = join.findChildren()[0];
  128. // Replace join with decision end
  129. var decision_end_model = new NodeModel({
  130. id: IdGeneratorTable['decisionend'].nextId(),
  131. node_type: 'decisionend',
  132. workflow: self.workflow(),
  133. child_links: join.model.child_links
  134. });
  135. var decision_end_node = new Node(self._workflow, decision_end_model, self.registry);
  136. $.each(decision_end_model.child_links, function(index, link) {
  137. link.parent = decision_end_model.id;
  138. });
  139. var parents = join.findParents();
  140. $.each(parents, function(index, parent) {
  141. parent.replaceChild(join, decision_end_node);
  142. });
  143. // Replace fork with decision node
  144. var decision_model = new DecisionModel({
  145. id: IdGeneratorTable['decision'].nextId(),
  146. name: self.name(),
  147. description: self.description(),
  148. node_type: 'decision',
  149. workflow: self.workflow(),
  150. child_links: self.model.child_links
  151. });
  152. var default_link = {
  153. parent: decision_model.id,
  154. child: self._workflow.end(),
  155. name: 'default',
  156. comment: ''
  157. };
  158. decision_model.child_links.push(default_link);
  159. $.each(decision_model.child_links, function(index, link) {
  160. link.parent = decision_model.id;
  161. });
  162. var parents = self.findParents();
  163. var decision_node = new DecisionNode(self._workflow, decision_model, self.registry);
  164. decision_node.removeChild(join);
  165. decision_node.addChild(decision_end_node);
  166. $.each(parents, function(index, parent) {
  167. parent.replaceChild(self, decision_node);
  168. });
  169. // Get rid of fork and join in registry
  170. join.erase();
  171. self.erase();
  172. // Add decision and decision end to registry
  173. self.registry.add(decision_node.id(), decision_node);
  174. self.registry.add(decision_end_node.id(), decision_end_node);
  175. }
  176. });
  177. var DecisionNode = NodeModule($, IdGeneratorTable, NodeFields);
  178. $.extend(DecisionNode.prototype, ForkNode.prototype, {
  179. initialize: function(workflow, model, registry) {
  180. var self = this;
  181. var registry = registry;
  182. var end = null;
  183. },
  184. end: function() {
  185. var self = this;
  186. var end = null;
  187. $.each(self.child_links(), function(index, link) {
  188. if (link.name() == 'related') {
  189. end = self.registry.get(link.child());
  190. }
  191. });
  192. return end;
  193. },
  194. /**
  195. * Append a node to the current decision
  196. * Also appends end node to node.
  197. * NOTE: Cannot append a decision or fork! Use addChild or replaceChild instead!
  198. */
  199. append: function(node) {
  200. var self = this;
  201. if (node.node_type() != 'decision' && node.node_type() != 'fork') {
  202. var end = self.end();
  203. if (end.id() != node.id()) {
  204. var children = end.findChildren();
  205. self.addChild(node);
  206. node.append(end);
  207. // remember children
  208. $.each(children, function(index, child) {
  209. end.addChild(child);
  210. });
  211. }
  212. }
  213. },
  214. /**
  215. * Replace child node with another node
  216. * 1. Remove child if the replacement is end
  217. * 2. Apply Node.replaceChild for all other causes
  218. */
  219. replaceChild: function(child, replacement) {
  220. var self = this;
  221. var ret = true;
  222. var end = self.end();
  223. if (end && end.id() == replacement.id()) {
  224. ret = self.removeChild(child);
  225. } else {
  226. ret = Node.prototype.replaceChild.apply(self, arguments);
  227. }
  228. if (self.links().length < 2) {
  229. self.detach();
  230. end.detach();
  231. self.erase();
  232. end.erase();
  233. }
  234. return ret;
  235. }
  236. });
  237. /**
  238. * Workflow module
  239. */
  240. var WorkflowModule = function($, NodeModelChooser, Node, ForkNode, DecisionNode, IdGeneratorTable) {
  241. var module = function(options) {
  242. var self = this;
  243. // @see http://knockoutjs.com/documentation/plugins-mapping.html
  244. var mapping = ko.mapping.fromJS(options.model, {
  245. ignore: ['initialize', 'toString', 'copy', 'nodes'],
  246. job_properties: {
  247. create: function(options) {
  248. var parent = options.parent;
  249. var subscribe = function(mapping) {
  250. mapping.name.subscribe(function(value) {
  251. parent.job_properties.valueHasMutated();
  252. });
  253. mapping.value.subscribe(function(value) {
  254. parent.job_properties.valueHasMutated();
  255. });
  256. };
  257. return map_params(options, subscribe);
  258. },
  259. update: function(options) {
  260. var parent = options.parent;
  261. var subscribe = function(mapping) {
  262. mapping.name.subscribe(function(value) {
  263. parent.job_properties.valueHasMutated();
  264. });
  265. mapping.value.subscribe(function(value) {
  266. parent.job_properties.valueHasMutated();
  267. });
  268. };
  269. return map_params(options, subscribe);
  270. }
  271. },
  272. parameters: {
  273. // Will receive individual objects to subscribe.
  274. // Containing array is mapped automagically
  275. create: function(options) {
  276. var parent = options.parent;
  277. var subscribe = function(mapping) {
  278. mapping.name.subscribe(function(value) {
  279. parent.parameters.valueHasMutated();
  280. });
  281. mapping.value.subscribe(function(value) {
  282. parent.parameters.valueHasMutated();
  283. });
  284. };
  285. return map_params(options, subscribe);
  286. },
  287. update: function(options) {
  288. var parent = options.parent;
  289. var subscribe = function(mapping) {
  290. mapping.name.subscribe(function(value) {
  291. parent.parameters.valueHasMutated();
  292. });
  293. mapping.value.subscribe(function(value) {
  294. parent.parameters.valueHasMutated();
  295. });
  296. };
  297. return map_params(options, subscribe);
  298. }
  299. }
  300. });
  301. $.extend(self, mapping);
  302. $.each(mapping['__ko_mapping__'].mappedProperties, function(key, value) {
  303. var key = key;
  304. self[key].subscribe(function(value) {
  305. self.is_dirty( true );
  306. self.model[key] = ko.mapping.toJS(value);
  307. });
  308. });
  309. self.model = options.model;
  310. self.registry = options.registry;
  311. self.options = options;
  312. self.el = (options.el) ? $(options.el) : $('#workflow');
  313. self.nodes = ko.observableArray([]);
  314. self.kill = null;
  315. self.is_dirty = ko.observable( false );
  316. self.loading = ko.observable( false );
  317. self.read_only = ko.observable( options.read_only || false );
  318. self.new_node = ko.observable();
  319. self.url = ko.computed(function() {
  320. return '/oozie/workflows/' + self.id()
  321. });
  322. // Events
  323. self.el.on('workflow:rebuild', function() {
  324. self.rebuild();
  325. });
  326. self.el.on('workflow:events:load', function() {
  327. self.dragAndDropEvents( options );
  328. });
  329. self.el.on('workflow:droppables:load', function() {
  330. self.droppables();
  331. });
  332. self.el.on('workflow:draggables:load', function() {
  333. self.draggables();
  334. });
  335. self.dragAndDropEvents( options );
  336. self.el.trigger('workflow:events:loaded');
  337. module.prototype.initialize.apply(self, arguments);
  338. return self;
  339. };
  340. $.extend(module.prototype, {
  341. // Normal stuff
  342. initialize: function(options) {
  343. var self = this;
  344. $.extend(self.options, options);
  345. if ('model' in options) {
  346. self.model = options.model;
  347. // Initialize nodes
  348. if (self.model.nodes) {
  349. self.registry.clear();
  350. $.each(self.model.nodes, function(index, node) {
  351. var NodeModel = NodeModelChooser(node.node_type);
  352. var model = new NodeModel(node);
  353. var temp = null;
  354. switch(node.node_type) {
  355. case 'start':
  356. temp = new StartNode(self, model, self.registry);
  357. break;
  358. case 'fork':
  359. temp = new ForkNode(self, model, self.registry);
  360. break;
  361. case 'decision':
  362. temp = new DecisionNode(self, model, self.registry);
  363. break;
  364. case 'kill':
  365. temp = self.kill = new Node(self, model, self.registry);
  366. break;
  367. default:
  368. temp = new Node(self, model, self.registry);
  369. break;
  370. }
  371. self.registry.add(temp.id(), temp);
  372. });
  373. }
  374. // Update data
  375. $.each(self.model, function (key, value) {
  376. if (key in self) {
  377. switch(key) {
  378. case 'job_properties':
  379. case 'parameters':
  380. // These may be serialized JSON data since that is how they are stored
  381. self[key].removeAll();
  382. var arr;
  383. try {
  384. arr = $.parseJSON(value);
  385. }
  386. catch (error){
  387. arr = value;
  388. }
  389. $.each(arr, function(index, obj) {
  390. var mapping = ko.mapping.fromJS(obj);
  391. mapping.name.subscribe(function(value) {
  392. self[key].valueHasMutated();
  393. });
  394. mapping.value.subscribe(function(value) {
  395. self[key].valueHasMutated();
  396. });
  397. self[key].push(mapping);
  398. });
  399. break;
  400. case 'nodes':
  401. break;
  402. default:
  403. self[key](value);
  404. break;
  405. }
  406. }
  407. });
  408. self.is_dirty( false );
  409. }
  410. if (!self.kill) {
  411. var kill_json = {
  412. "description": "",
  413. "workflow": self.id(),
  414. "child_links": [],
  415. "node_type": "kill",
  416. "message": "Action failed, error message[${wf:errorMessage(wf:lastErrorNode())}]",
  417. "name": "kill",
  418. "id": IdGeneratorTable['kill'].nextId()
  419. };
  420. var NodeModel = NodeModelChooser(kill_json.node_type);
  421. var model = new NodeModel(kill_json);
  422. self.kill = new Node(self, model, self.registry);
  423. self.registry.add(self.kill.id(), self.kill);
  424. }
  425. if ('read_only' in options) {
  426. self.read_only(options['read_only']);
  427. }
  428. },
  429. toString: function() {
  430. return '';
  431. var s = '[';
  432. $.each(self.registry.nodes, function(key, node) {
  433. s += node.model.toString() + ",\n";
  434. });
  435. return s + ']';
  436. },
  437. // Data manipulation
  438. toJSON: function() {
  439. var self = this;
  440. data = $.extend(true, {}, self.model);
  441. var nodes = [];
  442. $.each(self.registry.nodes, function(key, node) {
  443. // Create object with members from the actual model to address JSON.stringify bug
  444. // JSON.stringify does not pick up members specified in prototype prior to object creation.
  445. var model = {};
  446. for (var key in node.model) {
  447. model[key] = node.model[key];
  448. }
  449. nodes.push(model);
  450. });
  451. data['nodes'] = nodes;
  452. return JSON.stringify(data);
  453. },
  454. save: function( options ) {
  455. var self = this;
  456. var request = $.extend({
  457. url: self.url() + '/save',
  458. type: 'POST',
  459. data: { workflow: self.toJSON() },
  460. success: $.noop,
  461. error: $.noop
  462. }, options || {});
  463. $.ajax(request);
  464. },
  465. load: function( options ) {
  466. var self = this;
  467. var request = $.extend({
  468. url: self.url(),
  469. dataType: 'json',
  470. type: 'GET',
  471. success: $.noop,
  472. error: $.noop
  473. }, options || {});
  474. $.ajax(request);
  475. },
  476. reload: function(model) {
  477. var self = this;
  478. // Clear all children
  479. $.each(self.registry.nodes, function(index, node) {
  480. node.children.removeAll();
  481. });
  482. self.nodes.removeAll();
  483. self.initialize({model: model});
  484. self.rebuild();
  485. self.el.trigger('workflow:loaded');
  486. },
  487. addParameter: function(data, event) {
  488. var self = this;
  489. var prop = { name: ko.observable(""), value: ko.observable("") };
  490. // force bubble up to containing observable array.
  491. prop.name.subscribe(function(){
  492. self.parameters.valueHasMutated();
  493. });
  494. prop.value.subscribe(function(){
  495. self.parameters.valueHasMutated();
  496. });
  497. self.parameters.push(prop);
  498. },
  499. removeParameter: function(data, event) {
  500. var self = this;
  501. self.parameters.remove(data);
  502. },
  503. addJobProperty: function(data, event) {
  504. var self = this;
  505. var prop = { name: ko.observable(""), value: ko.observable("") };
  506. // force bubble up to containing observable array.
  507. prop.name.subscribe(function(){
  508. self.parameters.valueHasMutated();
  509. });
  510. prop.value.subscribe(function(){
  511. self.parameters.valueHasMutated();
  512. });
  513. self.job_properties.push(prop);
  514. },
  515. removeJobProperty: function(data, event) {
  516. var self = this;
  517. self.job_properties.remove(data);
  518. },
  519. // Workflow UI
  520. // Function to build nodes... recursively.
  521. build: function() {
  522. var self = this;
  523. var maximum = 100;
  524. var count = 0;
  525. var methodChooser = function(node, collection, skip_parents_check) {
  526. if (count++ >= maximum) {
  527. console.error('Hit maximum number of node recursion: ' + maximum);
  528. return null;
  529. }
  530. if (!node) {
  531. return node;
  532. }
  533. var parents = node.findParents();
  534. // Found end of decision node or found join!
  535. if (parents.length > 1 && !skip_parents_check) {
  536. return node;
  537. }
  538. switch(node.node_type()) {
  539. case 'start':
  540. case 'end':
  541. case 'kill':
  542. case 'fork':
  543. case 'join':
  544. case 'decision':
  545. case 'decisionend':
  546. return control(node, collection);
  547. default:
  548. return normal(node, collection);
  549. }
  550. };
  551. var normal = function(node, collection) {
  552. collection.push(node);
  553. var retNode = null;
  554. $.each(node.links(), function(index, link) {
  555. var next_node = self.registry.get(link.child());
  556. retNode = methodChooser(next_node, collection, false, true);
  557. });
  558. return retNode;
  559. };
  560. var control = function(node, collection, skip_parents_check) {
  561. switch(node.node_type()) {
  562. case 'start':
  563. case 'end':
  564. case 'kill':
  565. case 'join':
  566. case 'decisionend':
  567. return normal(node, collection, false, true);
  568. case 'fork':
  569. collection.push(node);
  570. // Wait for join.
  571. // Iterate through all children and add them to child collection.
  572. var join = null;
  573. $.each(node.links(), function(index, link) {
  574. var next_node = self.registry.get(link.child());
  575. var collection = ko.observableArray([]);
  576. node.children.push(collection);
  577. join = methodChooser(next_node, collection, false, true);
  578. });
  579. // Add join to collection, then find its single child.
  580. return methodChooser(join, collection, true, true);
  581. case 'decision':
  582. collection.push(node);
  583. // Waits for end, then runs through children of end node
  584. var end = null;
  585. $.each(node.links(), function(index, link) {
  586. var next_node = self.registry.get(link.child());
  587. var collection = ko.observableArray([]);
  588. node.children.push(collection);
  589. end = methodChooser(next_node, collection, true, true);
  590. });
  591. // Add end
  592. return methodChooser(node.end(), collection, true, true);
  593. default:
  594. // Should never get here.
  595. return node;
  596. }
  597. };
  598. methodChooser(self.registry.get(self.start()), self.nodes, false, true);
  599. $(".tooltip").remove();
  600. $("[relz=tooltip]").tooltip({placement: "left", delay: 0});
  601. $("[relz=tooltip]").hover(function () {
  602. $(".tooltip").css("left", parseInt($(".tooltip").css("left")) - 10 + "px");
  603. }, function () {
  604. $(".tooltip").remove();
  605. });
  606. },
  607. rebuild: function() {
  608. var self = this;
  609. // Clear all children
  610. $.each(self.registry.nodes, function(index, node) {
  611. node.children.removeAll();
  612. });
  613. self.nodes.removeAll();
  614. // Rebuild
  615. self.build();
  616. self.draggables();
  617. self.droppables();
  618. self.el.trigger('workflow:rebuilt');
  619. },
  620. draggables: function() {
  621. var self = this;
  622. self.el.find('.node-action').each(function(index, el) {
  623. if (!$(el).hasClass('ui-draggable')) {
  624. $(el).find('.row-fluid').eq(0).css('cursor', 'move');
  625. $(el).draggable({
  626. containment: [ self.el.offset().left - 10, self.el.offset().top - 10,
  627. self.el.offset().left + self.el.outerWidth(), self.el.offset().top + self.el.outerHeight() ],
  628. refreshPositions: true,
  629. revert: true,
  630. zIndex: 1000,
  631. opacity: 0.45,
  632. revertDuration: 0,
  633. cancel: '.node-action-bar'
  634. });
  635. }
  636. });
  637. },
  638. droppables: function() {
  639. var self = this;
  640. self.el.find('.node-link').each(function(index, el) {
  641. $(el).droppable({
  642. 'hoverClass': 'node-link-hover',
  643. 'greedy': true,
  644. 'accept': '.node-action',
  645. 'tolerance': 'pointer'
  646. });
  647. });
  648. self.el.find('.node-decision-end').each(function(index, el) {
  649. $(el).droppable({
  650. 'hoverClass': 'node-link-hover',
  651. 'greedy': true,
  652. 'accept': '.node-action',
  653. 'tolerance': 'pointer'
  654. });
  655. });
  656. self.el.find('.node-fork .action').each(function(index, el) {
  657. $(el).droppable({
  658. 'hoverClass': 'node-fork-hover',
  659. 'greedy': true,
  660. 'accept': '.node-action',
  661. 'tolerance': 'pointer'
  662. });
  663. });
  664. self.el.find('.node-decision .action').each(function(index, el) {
  665. $(el).droppable({
  666. 'hoverClass': 'node-fork-hover',
  667. 'greedy': true,
  668. 'accept': '.node-action',
  669. 'tolerance': 'pointer'
  670. });
  671. });
  672. self.el.find('.node-action .action').each(function(index, el) {
  673. $(el).droppable({
  674. 'hoverClass': 'node-action-hover',
  675. 'greedy': true,
  676. 'accept': '.node-action',
  677. 'tolerance': 'pointer'
  678. });
  679. });
  680. },
  681. dragAndDropEvents: function( options ) {
  682. var self = this;
  683. var read_only_error_handler = options.read_only_error_handler;
  684. // Build event delegations.
  685. // Drop on node link
  686. self.el.on('drop', '.node-link', function(e, ui) {
  687. if (self.read_only()) {
  688. read_only_error_handler();
  689. return false;
  690. }
  691. // draggable should be a node.
  692. // droppable should be a link.
  693. var draggable = ko.contextFor(ui.draggable[0]).$data;
  694. var droppable = ko.contextFor(this).$data;
  695. // If newParent is fork, prepend to child instead.
  696. // This will make it so that we can drop and drop to the top of a node list within a fork.
  697. var newParent = self.registry.get(droppable.parent());
  698. if (newParent.id() != draggable.id() && !newParent.isChild(draggable)) {
  699. switch(newParent.node_type()) {
  700. case 'fork':
  701. case 'decision':
  702. // Children that are forks or decisions may be removed when we detach.
  703. // Remember children in this case to find correct node.
  704. var child = self.registry.get(droppable.child());
  705. var children_of_child = [];
  706. if (child.node_type() == 'fork' || child.node_type() == 'decision') {
  707. children_of_child = child.findChildren();
  708. }
  709. draggable.detach();
  710. // Make sure fork and decision still exist
  711. // Otherwise find child that replaced it
  712. var child_to_replace = child;
  713. if (child.node_type() == 'fork' || child.node_type() == 'decision') {
  714. if (!self.registry.get(child.id())) {
  715. // Guaranteed one because the fork is being removed right now.
  716. child_to_replace = $.grep(children_of_child, function(child_of_child, index) {
  717. return child_of_child.findParents().length > 0;
  718. })[0];
  719. }
  720. }
  721. newParent.replaceChild(child_to_replace, draggable);
  722. draggable.addChild(child_to_replace);
  723. break;
  724. case 'join':
  725. case 'decisionend':
  726. // Join and decisionend may disappear when we detach...
  727. // Remember its children and append to child.
  728. var parents = newParent.findParents();
  729. draggable.detach();
  730. if (newParent.findParents().length < 2) {
  731. $.each(parents, function(index, parent) {
  732. parent.append(draggable);
  733. });
  734. } else {
  735. newParent.append(draggable);
  736. }
  737. break;
  738. default:
  739. draggable.detach();
  740. newParent.append(draggable);
  741. break;
  742. }
  743. workflow.is_dirty( true );
  744. self.rebuild();
  745. }
  746. // Prevent bubbling events
  747. return false;
  748. });
  749. // Drop on fork
  750. self.el.on('drop', '.node-fork', function(e, ui) {
  751. if (self.read_only()) {
  752. read_only_error_handler();
  753. return false;
  754. }
  755. // draggable should be a node.
  756. // droppable should be a fork.
  757. var draggable = ko.contextFor(ui.draggable[0]).$data;
  758. var droppable = ko.contextFor(this).$data;
  759. if (!droppable.isChild(draggable) && droppable.id() != draggable.id()) {
  760. draggable.detach();
  761. droppable.append(draggable);
  762. self.rebuild();
  763. }
  764. // Prevent bubbling events
  765. return false;
  766. });
  767. // Drop on decision
  768. self.el.on('drop', '.node-decision', function(e, ui) {
  769. if (self.read_only()) {
  770. read_only_error_handler();
  771. return false;
  772. }
  773. // draggable should be a node.
  774. // droppable should be a fork.
  775. var draggable = ko.contextFor(ui.draggable[0]).$data;
  776. var droppable = ko.contextFor(this).$data;
  777. if (!droppable.isChild(draggable) && droppable.id() != draggable.id()) {
  778. draggable.detach();
  779. droppable.append(draggable);
  780. self.rebuild();
  781. }
  782. // Prevent bubbling events
  783. return false;
  784. });
  785. // Drop on action
  786. self.el.on('drop', '.node-action', function(e, ui) {
  787. if (self.read_only()) {
  788. read_only_error_handler();
  789. return false;
  790. }
  791. // draggable should be a node.
  792. // droppable should be a node.
  793. var draggable = ko.contextFor(ui.draggable[0]).$data;
  794. var droppable = ko.contextFor(this).$data;
  795. // Create a fork and join programatically.
  796. var newParents = droppable.findParents();
  797. // skip forking beneathe a decision node
  798. if (droppable.id() != draggable.id() && newParents.length == 1 && draggable.findParents().length <= 1) {
  799. var ForkModel = NodeModelChooser('fork');
  800. var JoinModel = NodeModelChooser('join');
  801. var fork = new ForkModel({
  802. id: IdGeneratorTable['fork'].nextId(),
  803. description: "",
  804. workflow: self.id,
  805. node_type: "fork",
  806. child_links: []
  807. });
  808. var forkNode = new ForkNode(self, fork, self.registry);
  809. var join = new JoinModel({
  810. id: IdGeneratorTable['join'].nextId(),
  811. description: "",
  812. workflow: self.id,
  813. node_type: "join",
  814. child_links: []
  815. });
  816. var joinNode = new Node(self, join, self.registry);
  817. self.registry.add(forkNode.id(), forkNode);
  818. self.registry.add(joinNode.id(), joinNode);
  819. forkNode.addChild(joinNode);
  820. // Handles fork creation.
  821. $.each(newParents, function(index, parent) {
  822. parent.replaceChild(droppable, forkNode);
  823. });
  824. draggable.detach();
  825. forkNode.append(draggable);
  826. forkNode.append(droppable);
  827. self.rebuild();
  828. }
  829. // Prevent bubbling events.
  830. return false;
  831. });
  832. }
  833. });
  834. return module;
  835. };
  836. var Workflow = WorkflowModule($, nodeModelChooser, Node, ForkNode, DecisionNode, IdGeneratorTable);
  837. // Manage Kill Module
  838. function ManageKillModule($, workflow, NodeModelChooser, Node, NodeModel) {
  839. var email_action = null;
  840. var parents = workflow.kill.findParents();
  841. var email_enabled = ko.observable();
  842. if (parents.length > 0) {
  843. email_action = parents[0];
  844. email_enabled(true);
  845. } else {
  846. var email_json = {
  847. "description": "",
  848. "workflow": workflow.id(),
  849. "child_links": [],
  850. "node_type": "email",
  851. "message": "Action failed, error message[${wf:errorMessage(wf:lastErrorNode())}]",
  852. "name": 'killemail',
  853. "id": IdGeneratorTable['email'].nextId()
  854. };
  855. var NodeModel = NodeModelChooser(email_json.node_type);
  856. var model = new NodeModel(email_json);
  857. email_action = new Node(workflow, model, workflow.registry);
  858. email_enabled(false);
  859. }
  860. var replace_email = function(email_action) {
  861. email_action.removeAllChildren();
  862. email_action.removeErrorChildren();
  863. $.each(workflow.registry.nodes, function(index, node) {
  864. if (node.getErrorChild() && node.id() != email_action.id()) {
  865. node.putErrorChild(workflow.kill);
  866. }
  867. });
  868. };
  869. var replace_kill = function(email_action) {
  870. if (email_action.findChildren().length == 0) {
  871. email_action.addChild(workflow.kill, 'ok');
  872. }
  873. if (!email_action.getErrorChild()) {
  874. email_action.putErrorChild(workflow.kill);
  875. }
  876. $.each(workflow.registry.nodes, function(index, node) {
  877. if (node.getErrorChild() && node.id() != email_action.id()) {
  878. node.putErrorChild(email_action);
  879. }
  880. });
  881. };
  882. // Add/Remove kill email action node from registry so that it is not sent to server.
  883. email_action.to.subscribe(function(value) {
  884. if (value && !email_enabled()) {
  885. workflow.registry.add(email_action.id(), email_action);
  886. replace_kill(email_action);
  887. email_enabled(true);
  888. } else if (!value && email_enabled()) {
  889. replace_email(email_action);
  890. email_enabled(false);
  891. workflow.registry.remove(email_action.id());
  892. email_action.id(IdGeneratorTable['email'].nextId());
  893. }
  894. return value;
  895. });
  896. // View model
  897. return {
  898. 'enabled': email_enabled,
  899. 'isValid': function() {
  900. return email_action.validate();
  901. },
  902. 'context': ko.observable({
  903. 'node': ko.observable(email_action),
  904. 'read_only': ko.observable(workflow.read_only())
  905. })
  906. };
  907. };