workflow.js 34 KB

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