workflow.js 34 KB

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