workflow.js 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081
  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. if (self[key]) { //ugly? // allow custom sub bindings in foreach
  305. self[key].subscribe(function(value) {
  306. self.is_dirty(true);
  307. self.model[key] = ko.mapping.toJS(value);
  308. });
  309. }
  310. });
  311. self.model = options.model;
  312. self.registry = options.registry;
  313. self.options = options;
  314. self.el = (options.el) ? $(options.el) : $('#workflow');
  315. self.nodes = ko.observableArray([]);
  316. self.kill = null;
  317. self.is_dirty = ko.observable( false );
  318. self.loading = ko.observable( false );
  319. self.read_only = ko.observable( options.read_only || false );
  320. self.new_node = ko.observable();
  321. self.url = ko.computed(function() {
  322. return '/oozie/workflows/' + self.id()
  323. });
  324. // Events
  325. self.el.on('workflow:rebuild', function() {
  326. self.rebuild();
  327. });
  328. self.el.on('workflow:events:load', function() {
  329. self.dragAndDropEvents( options );
  330. });
  331. self.el.on('workflow:droppables:load', function() {
  332. self.droppables();
  333. });
  334. self.el.on('workflow:draggables:load', function() {
  335. self.draggables();
  336. });
  337. self.dragAndDropEvents( options );
  338. self.el.trigger('workflow:events:loaded');
  339. module.prototype.initialize.apply(self, arguments);
  340. self.sla = self.model['sla']; // Need to persists here for some reason
  341. return self;
  342. };
  343. $.extend(module.prototype, {
  344. // Normal stuff
  345. initialize: function(options) {
  346. var self = this;
  347. $.extend(self.options, options);
  348. if ('model' in options) {
  349. self.model = options.model;
  350. // Initialize nodes
  351. if (self.model.nodes) {
  352. self.registry.clear();
  353. $.each(self.model.nodes, function(index, node) {
  354. var NodeModel = NodeModelChooser(node.node_type);
  355. var model = new NodeModel(node);
  356. var temp = null;
  357. switch(node.node_type) {
  358. case 'start':
  359. temp = new StartNode(self, model, self.registry);
  360. break;
  361. case 'fork':
  362. temp = new ForkNode(self, model, self.registry);
  363. break;
  364. case 'decision':
  365. temp = new DecisionNode(self, model, self.registry);
  366. break;
  367. case 'kill':
  368. temp = self.kill = new Node(self, model, self.registry);
  369. break;
  370. default:
  371. temp = new Node(self, model, self.registry);
  372. break;
  373. }
  374. self.registry.add(temp.id(), temp);
  375. });
  376. }
  377. // Update data
  378. $.each(self.model, function (key, value) {
  379. if (key in self) {
  380. switch(key) {
  381. case 'job_properties':
  382. case 'parameters':
  383. // These may be serialized JSON data since that is how they are stored
  384. self[key].removeAll();
  385. var arr;
  386. try {
  387. arr = $.parseJSON(value);
  388. }
  389. catch (error){
  390. arr = value;
  391. }
  392. $.each(arr, function(index, obj) {
  393. var mapping = ko.mapping.fromJS(obj);
  394. mapping.name.subscribe(function(value) {
  395. self[key].valueHasMutated();
  396. });
  397. mapping.value.subscribe(function(value) {
  398. self[key].valueHasMutated();
  399. });
  400. self[key].push(mapping);
  401. });
  402. break;
  403. case 'nodes':
  404. break;
  405. default:
  406. self[key](value);
  407. break;
  408. }
  409. }
  410. });
  411. self.is_dirty( false );
  412. }
  413. if (!self.kill) {
  414. var kill_json = {
  415. "description": "",
  416. "workflow": self.id(),
  417. "child_links": [],
  418. "node_type": "kill",
  419. "message": "Action failed, error message[${wf:errorMessage(wf:lastErrorNode())}]",
  420. "name": "kill",
  421. "id": IdGeneratorTable['kill'].nextId()
  422. };
  423. var NodeModel = NodeModelChooser(kill_json.node_type);
  424. var model = new NodeModel(kill_json);
  425. self.kill = new Node(self, model, self.registry);
  426. self.registry.add(self.kill.id(), self.kill);
  427. }
  428. if ('read_only' in options) {
  429. self.read_only(options['read_only']);
  430. }
  431. if (self.errors) {
  432. ko.mapping.fromJS(format_errors_mapping(self.model), self.errors);
  433. } else {
  434. self.errors = ko.mapping.fromJS(format_errors_mapping(self.model));
  435. }
  436. },
  437. toString: function() {
  438. return '';
  439. var s = '[';
  440. $.each(self.registry.nodes, function(key, node) {
  441. s += node.model.toString() + ",\n";
  442. });
  443. return s + ']';
  444. },
  445. // Data manipulation
  446. toJSON: function() {
  447. var self = this;
  448. data = $.extend(true, {}, self.model);
  449. var nodes = [];
  450. $.each(self.registry.nodes, function(key, node) {
  451. // Create object with members from the actual model to address JSON.stringify bug
  452. // JSON.stringify does not pick up members specified in prototype prior to object creation.
  453. var model = {};
  454. for (var key in node.model) {
  455. model[key] = node.model[key];
  456. }
  457. nodes.push(model);
  458. });
  459. data['nodes'] = nodes;
  460. data['sla'] = self.sla;
  461. return JSON.stringify(data);
  462. },
  463. save: function( options ) {
  464. var self = this;
  465. var request = $.extend({
  466. url: self.url() + '/save',
  467. type: 'POST',
  468. data: { workflow: self.toJSON() },
  469. success: $.noop,
  470. error: $.noop
  471. }, options || {});
  472. $.ajax(request);
  473. },
  474. load: function( options ) {
  475. var self = this;
  476. var request = $.extend({
  477. url: self.url(),
  478. dataType: 'json',
  479. type: 'GET',
  480. success: $.noop,
  481. error: $.noop
  482. }, options || {});
  483. $.ajax(request);
  484. },
  485. reload: function(model) {
  486. var self = this;
  487. // Clear all children
  488. $.each(self.registry.nodes, function(index, node) {
  489. node.children.removeAll();
  490. });
  491. self.nodes.removeAll();
  492. self.initialize({model: model});
  493. self.rebuild();
  494. self.el.trigger('workflow:loaded');
  495. },
  496. addParameter: function(data, event) {
  497. var self = this;
  498. var prop = { name: ko.observable(""), value: ko.observable("") };
  499. // force bubble up to containing observable array.
  500. prop.name.subscribe(function(){
  501. self.parameters.valueHasMutated();
  502. });
  503. prop.value.subscribe(function(){
  504. self.parameters.valueHasMutated();
  505. });
  506. self.parameters.push(prop);
  507. },
  508. removeParameter: function(data, event) {
  509. var self = this;
  510. self.parameters.remove(data);
  511. },
  512. addJobProperty: function(data, event) {
  513. var self = this;
  514. var prop = { name: ko.observable(""), value: ko.observable("") };
  515. // force bubble up to containing observable array.
  516. prop.name.subscribe(function(){
  517. self.parameters.valueHasMutated();
  518. });
  519. prop.value.subscribe(function(){
  520. self.parameters.valueHasMutated();
  521. });
  522. self.job_properties.push(prop);
  523. },
  524. removeJobProperty: function(data, event) {
  525. var self = this;
  526. self.job_properties.remove(data);
  527. },
  528. // Workflow UI
  529. // Function to build nodes... recursively.
  530. build: function() {
  531. var self = this;
  532. var maximum = 100;
  533. var count = 0;
  534. var methodChooser = function(node, collection, skip_parents_check) {
  535. if (count++ >= maximum) {
  536. console.error('Hit maximum number of node recursion: ' + maximum);
  537. return null;
  538. }
  539. if (!node) {
  540. return node;
  541. }
  542. var parents = node.findParents();
  543. // Found end of decision node or found join!
  544. if (parents.length > 1 && !skip_parents_check) {
  545. return node;
  546. }
  547. switch(node.node_type()) {
  548. case 'start':
  549. case 'end':
  550. case 'kill':
  551. case 'fork':
  552. case 'join':
  553. case 'decision':
  554. case 'decisionend':
  555. return control(node, collection);
  556. default:
  557. return normal(node, collection);
  558. }
  559. };
  560. var normal = function(node, collection) {
  561. collection.push(node);
  562. var retNode = null;
  563. $.each(node.links(), function(index, link) {
  564. var next_node = self.registry.get(link.child());
  565. retNode = methodChooser(next_node, collection, false, true);
  566. });
  567. return retNode;
  568. };
  569. var control = function(node, collection, skip_parents_check) {
  570. switch(node.node_type()) {
  571. case 'start':
  572. case 'end':
  573. case 'kill':
  574. case 'join':
  575. case 'decisionend':
  576. return normal(node, collection, false, true);
  577. case 'fork':
  578. collection.push(node);
  579. // Wait for join.
  580. // Iterate through all children and add them to child collection.
  581. var join = null;
  582. $.each(node.links(), function(index, link) {
  583. var next_node = self.registry.get(link.child());
  584. var collection = ko.observableArray([]);
  585. node.children.push(collection);
  586. join = methodChooser(next_node, collection, false, true);
  587. });
  588. // Add join to collection, then find its single child.
  589. return methodChooser(join, collection, true, true);
  590. case 'decision':
  591. collection.push(node);
  592. // Waits for end, then runs through children of end node
  593. var end = null;
  594. $.each(node.links(), function(index, link) {
  595. var next_node = self.registry.get(link.child());
  596. var collection = ko.observableArray([]);
  597. node.children.push(collection);
  598. end = methodChooser(next_node, collection, true, true);
  599. });
  600. // Add end
  601. return methodChooser(node.end(), collection, true, true);
  602. default:
  603. // Should never get here.
  604. return node;
  605. }
  606. };
  607. methodChooser(self.registry.get(self.start()), self.nodes, false, true);
  608. $(".tooltip").remove();
  609. $("[relz=tooltip]").tooltip({placement: "left", delay: 0});
  610. $("[relz=tooltip]").hover(function () {
  611. $(".tooltip").css("left", parseInt($(".tooltip").css("left")) - 10 + "px");
  612. }, function () {
  613. $(".tooltip").remove();
  614. });
  615. },
  616. rebuild: function() {
  617. var self = this;
  618. // Clear all children
  619. $.each(self.registry.nodes, function(index, node) {
  620. node.children.removeAll();
  621. });
  622. self.nodes.removeAll();
  623. // Rebuild
  624. self.build();
  625. self.draggables();
  626. self.droppables();
  627. self.el.trigger('workflow:rebuilt');
  628. },
  629. draggables: function() {
  630. var self = this;
  631. self.el.find('.node-action').each(function(index, el) {
  632. if (!$(el).hasClass('ui-draggable')) {
  633. $(el).find('.row-fluid').eq(0).css('cursor', 'move');
  634. $(el).draggable({
  635. containment: [ self.el.offset().left - 10, self.el.offset().top - 10,
  636. self.el.offset().left + self.el.outerWidth(), self.el.offset().top + self.el.outerHeight() ],
  637. refreshPositions: true,
  638. revert: true,
  639. zIndex: 1000,
  640. opacity: 0.45,
  641. revertDuration: 0,
  642. cancel: '.node-action-bar'
  643. });
  644. }
  645. });
  646. },
  647. droppables: function() {
  648. var self = this;
  649. self.el.find('.node-link').each(function(index, el) {
  650. $(el).droppable({
  651. 'hoverClass': 'node-link-hover',
  652. 'greedy': true,
  653. 'accept': '.node-action',
  654. 'tolerance': 'pointer'
  655. });
  656. });
  657. self.el.find('.node-decision-end').each(function(index, el) {
  658. $(el).droppable({
  659. 'hoverClass': 'node-link-hover',
  660. 'greedy': true,
  661. 'accept': '.node-action',
  662. 'tolerance': 'pointer'
  663. });
  664. });
  665. self.el.find('.node-fork .action').each(function(index, el) {
  666. $(el).droppable({
  667. 'hoverClass': 'node-fork-hover',
  668. 'greedy': true,
  669. 'accept': '.node-action',
  670. 'tolerance': 'pointer'
  671. });
  672. });
  673. self.el.find('.node-decision .action').each(function(index, el) {
  674. $(el).droppable({
  675. 'hoverClass': 'node-fork-hover',
  676. 'greedy': true,
  677. 'accept': '.node-action',
  678. 'tolerance': 'pointer'
  679. });
  680. });
  681. self.el.find('.node-action .action').each(function(index, el) {
  682. $(el).droppable({
  683. 'hoverClass': 'node-action-hover',
  684. 'greedy': true,
  685. 'accept': '.node-action',
  686. 'tolerance': 'pointer'
  687. });
  688. });
  689. },
  690. dragAndDropEvents: function( options ) {
  691. var self = this;
  692. var read_only_error_handler = options.read_only_error_handler;
  693. // Build event delegations.
  694. // Drop on node link
  695. self.el.on('drop', '.node-link', function(e, ui) {
  696. if (self.read_only()) {
  697. read_only_error_handler();
  698. return false;
  699. }
  700. // draggable should be a node.
  701. // droppable should be a link.
  702. var draggable = ko.contextFor(ui.draggable[0]).$data;
  703. var droppable = ko.contextFor(this).$data;
  704. // If newParent is fork, prepend to child instead.
  705. // This will make it so that we can drop and drop to the top of a node list within a fork.
  706. var newParent = self.registry.get(droppable.parent());
  707. if (newParent.id() != draggable.id() && !newParent.isChild(draggable)) {
  708. switch(newParent.node_type()) {
  709. case 'fork':
  710. case 'decision':
  711. // Children that are forks or decisions may be removed when we detach.
  712. // Remember children in this case to find correct node.
  713. var child = self.registry.get(droppable.child());
  714. var children_of_child = [];
  715. if (child.node_type() == 'fork' || child.node_type() == 'decision') {
  716. children_of_child = child.findChildren();
  717. }
  718. draggable.detach();
  719. // Make sure fork and decision still exist
  720. // Otherwise find child that replaced it
  721. var child_to_replace = child;
  722. if (child.node_type() == 'fork' || child.node_type() == 'decision') {
  723. if (!self.registry.get(child.id())) {
  724. // Guaranteed one because the fork is being removed right now.
  725. child_to_replace = $.grep(children_of_child, function(child_of_child, index) {
  726. return child_of_child.findParents().length > 0;
  727. })[0];
  728. }
  729. }
  730. newParent.replaceChild(child_to_replace, draggable);
  731. draggable.addChild(child_to_replace);
  732. break;
  733. case 'join':
  734. case 'decisionend':
  735. // Join and decisionend may disappear when we detach...
  736. // Remember its children and append to child.
  737. var parents = newParent.findParents();
  738. draggable.detach();
  739. if (newParent.findParents().length < 2) {
  740. $.each(parents, function(index, parent) {
  741. parent.append(draggable);
  742. });
  743. } else {
  744. newParent.append(draggable);
  745. }
  746. break;
  747. default:
  748. draggable.detach();
  749. newParent.append(draggable);
  750. break;
  751. }
  752. workflow.is_dirty( true );
  753. self.rebuild();
  754. }
  755. // Prevent bubbling events
  756. return false;
  757. });
  758. // Drop on fork
  759. self.el.on('drop', '.node-fork', function(e, ui) {
  760. if (self.read_only()) {
  761. read_only_error_handler();
  762. return false;
  763. }
  764. // draggable should be a node.
  765. // droppable should be a fork.
  766. var draggable = ko.contextFor(ui.draggable[0]).$data;
  767. var droppable = ko.contextFor(this).$data;
  768. if (!droppable.isChild(draggable) && droppable.id() != draggable.id()) {
  769. draggable.detach();
  770. droppable.append(draggable);
  771. self.rebuild();
  772. }
  773. // Prevent bubbling events
  774. return false;
  775. });
  776. // Drop on decision
  777. self.el.on('drop', '.node-decision', function(e, ui) {
  778. if (self.read_only()) {
  779. read_only_error_handler();
  780. return false;
  781. }
  782. // draggable should be a node.
  783. // droppable should be a fork.
  784. var draggable = ko.contextFor(ui.draggable[0]).$data;
  785. var droppable = ko.contextFor(this).$data;
  786. if (!droppable.isChild(draggable) && droppable.id() != draggable.id()) {
  787. draggable.detach();
  788. droppable.append(draggable);
  789. self.rebuild();
  790. }
  791. // Prevent bubbling events
  792. return false;
  793. });
  794. // Drop on action
  795. self.el.on('drop', '.node-action', function(e, ui) {
  796. if (self.read_only()) {
  797. read_only_error_handler();
  798. return false;
  799. }
  800. // draggable should be a node.
  801. // droppable should be a node.
  802. var draggable = ko.contextFor(ui.draggable[0]).$data;
  803. var droppable = ko.contextFor(this).$data;
  804. // Create a fork and join programatically.
  805. var newParents = droppable.findParents();
  806. // skip forking beneathe a decision node
  807. if (droppable.id() != draggable.id() && newParents.length == 1 && draggable.findParents().length <= 1) {
  808. var ForkModel = NodeModelChooser('fork');
  809. var JoinModel = NodeModelChooser('join');
  810. var fork = new ForkModel({
  811. id: IdGeneratorTable['fork'].nextId(),
  812. description: "",
  813. workflow: self.id,
  814. node_type: "fork",
  815. child_links: []
  816. });
  817. var forkNode = new ForkNode(self, fork, self.registry);
  818. var join = new JoinModel({
  819. id: IdGeneratorTable['join'].nextId(),
  820. description: "",
  821. workflow: self.id,
  822. node_type: "join",
  823. child_links: []
  824. });
  825. var joinNode = new Node(self, join, self.registry);
  826. self.registry.add(forkNode.id(), forkNode);
  827. self.registry.add(joinNode.id(), joinNode);
  828. forkNode.addChild(joinNode);
  829. // Handles fork creation.
  830. $.each(newParents, function(index, parent) {
  831. parent.replaceChild(droppable, forkNode);
  832. });
  833. draggable.detach();
  834. forkNode.append(draggable);
  835. forkNode.append(droppable);
  836. self.rebuild();
  837. }
  838. // Prevent bubbling events.
  839. return false;
  840. });
  841. }
  842. });
  843. return module;
  844. };
  845. var Workflow = WorkflowModule($, nodeModelChooser, Node, ForkNode, DecisionNode, IdGeneratorTable);
  846. // Manage Kill Module
  847. function ManageKillModule($, workflow, NodeModelChooser, Node, NodeModel) {
  848. var email_action = null;
  849. var parents = workflow.kill.findParents();
  850. var email_enabled = ko.observable();
  851. if (parents.length > 0) {
  852. email_action = parents[0];
  853. email_enabled(true);
  854. } else {
  855. var email_json = {
  856. "description": "",
  857. "workflow": workflow.id(),
  858. "child_links": [],
  859. "node_type": "email",
  860. "message": "Action failed, error message[${wf:errorMessage(wf:lastErrorNode())}]",
  861. "name": 'killemail',
  862. "id": IdGeneratorTable['email'].nextId()
  863. };
  864. var NodeModel = NodeModelChooser(email_json.node_type);
  865. var model = new NodeModel(email_json);
  866. email_action = new Node(workflow, model, workflow.registry);
  867. email_enabled(false);
  868. }
  869. var replace_email = function(email_action) {
  870. email_action.removeAllChildren();
  871. email_action.removeErrorChildren();
  872. $.each(workflow.registry.nodes, function(index, node) {
  873. if (node.getErrorChild() && node.id() != email_action.id()) {
  874. node.putErrorChild(workflow.kill);
  875. }
  876. });
  877. };
  878. var replace_kill = function(email_action) {
  879. if (email_action.findChildren().length == 0) {
  880. email_action.addChild(workflow.kill, 'ok');
  881. }
  882. if (!email_action.getErrorChild()) {
  883. email_action.putErrorChild(workflow.kill);
  884. }
  885. $.each(workflow.registry.nodes, function(index, node) {
  886. if (node.getErrorChild() && node.id() != email_action.id()) {
  887. node.putErrorChild(email_action);
  888. }
  889. });
  890. };
  891. // Add/Remove kill email action node from registry so that it is not sent to server.
  892. email_action.to.subscribe(function(value) {
  893. if (value && !email_enabled()) {
  894. workflow.registry.add(email_action.id(), email_action);
  895. replace_kill(email_action);
  896. email_enabled(true);
  897. } else if (!value && email_enabled()) {
  898. replace_email(email_action);
  899. email_enabled(false);
  900. workflow.registry.remove(email_action.id());
  901. email_action.id(IdGeneratorTable['email'].nextId());
  902. }
  903. return value;
  904. });
  905. // View model
  906. return {
  907. 'enabled': email_enabled,
  908. 'isValid': function() {
  909. return email_action.validate();
  910. },
  911. 'context': ko.observable({
  912. 'node': ko.observable(email_action),
  913. 'read_only': ko.observable(workflow.read_only())
  914. })
  915. };
  916. };