workflow.js 31 KB

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