workflow.js 34 KB

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