workflow.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152
  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. updateData(self[key], data);
  471. break;
  472. default:
  473. self[key](value);
  474. break;
  475. }
  476. }
  477. });
  478. self.is_dirty( false );
  479. }
  480. if (!self.kill) {
  481. var kill_json = {
  482. "description": "",
  483. "workflow": self.id(),
  484. "child_links": [],
  485. "node_type": "kill",
  486. "message": "Action failed, error message[${wf:errorMessage(wf:lastErrorNode())}]",
  487. "name": "kill",
  488. "id": IdGeneratorTable['kill'].nextId()
  489. };
  490. var NodeModel = NodeModelChooser(kill_json.node_type);
  491. var model = new NodeModel(kill_json);
  492. self.kill = new Node(self, model, self.registry);
  493. self.registry.add(self.kill.id(), self.kill);
  494. }
  495. if ('read_only' in options) {
  496. self.read_only(options['read_only']);
  497. }
  498. if (self.errors) {
  499. ko.mapping.fromJS(format_errors_mapping(self.model), self.errors);
  500. } else {
  501. self.errors = ko.mapping.fromJS(format_errors_mapping(self.model));
  502. }
  503. },
  504. toString: function() {
  505. return '';
  506. var s = '[';
  507. $.each(self.registry.nodes, function(key, node) {
  508. s += node.model.toString() + ",\n";
  509. });
  510. return s + ']';
  511. },
  512. // Data manipulation
  513. toJSON: function() {
  514. var self = this;
  515. data = $.extend(true, {}, self.model);
  516. var nodes = [];
  517. $.each(self.registry.nodes, function(key, node) {
  518. // Create object with members from the actual model to address JSON.stringify bug
  519. // JSON.stringify does not pick up members specified in prototype prior to object creation.
  520. var model = {};
  521. for (var key in node.model) {
  522. model[key] = node.model[key];
  523. }
  524. nodes.push(model);
  525. });
  526. data['nodes'] = nodes;
  527. //data['sla'] = self.sla;
  528. return JSON.stringify(data);
  529. },
  530. save: function( options ) {
  531. var self = this;
  532. var request = $.extend({
  533. url: self.url() + '/save',
  534. type: 'POST',
  535. data: { workflow: self.toJSON() },
  536. success: $.noop,
  537. error: $.noop
  538. }, options || {});
  539. $.ajax(request);
  540. },
  541. load: function( options ) {
  542. var self = this;
  543. var request = $.extend({
  544. url: self.url(),
  545. dataType: 'json',
  546. type: 'GET',
  547. success: $.noop,
  548. error: $.noop
  549. }, options || {});
  550. $.ajax(request);
  551. },
  552. reload: function(model) {
  553. var self = this;
  554. // Clear all children
  555. $.each(self.registry.nodes, function(index, node) {
  556. node.children.removeAll();
  557. });
  558. self.nodes.removeAll();
  559. self.initialize({model: model});
  560. self.rebuild();
  561. self.el.trigger('workflow:loaded');
  562. },
  563. addParameter: function(data, event) {
  564. var self = this;
  565. var prop = { name: ko.observable(""), value: ko.observable("") };
  566. // force bubble up to containing observable array.
  567. prop.name.subscribe(function(){
  568. self.parameters.valueHasMutated();
  569. });
  570. prop.value.subscribe(function(){
  571. self.parameters.valueHasMutated();
  572. });
  573. self.parameters.push(prop);
  574. },
  575. removeParameter: function(data, event) {
  576. var self = this;
  577. self.parameters.remove(data);
  578. },
  579. addJobProperty: function(data, event) {
  580. var self = this;
  581. var prop = { name: ko.observable(""), value: ko.observable("") };
  582. // force bubble up to containing observable array.
  583. prop.name.subscribe(function(){
  584. self.job_properties.valueHasMutated();
  585. });
  586. prop.value.subscribe(function(){
  587. self.job_properties.valueHasMutated();
  588. });
  589. self.job_properties.push(prop);
  590. },
  591. removeJobProperty: function(data, event) {
  592. var self = this;
  593. self.job_properties.remove(data);
  594. },
  595. // Workflow UI
  596. // Function to build nodes... recursively.
  597. build: function() {
  598. var self = this;
  599. var maximum = 100;
  600. var count = 0;
  601. var methodChooser = function(node, collection, skip_parents_check) {
  602. if (count++ >= maximum) {
  603. console.error('Hit maximum number of node recursion: ' + maximum);
  604. return null;
  605. }
  606. if (!node) {
  607. return node;
  608. }
  609. var parents = node.findParents();
  610. // Found end of decision node or found join!
  611. if (parents.length > 1 && !skip_parents_check) {
  612. return node;
  613. }
  614. switch(node.node_type()) {
  615. case 'start':
  616. case 'end':
  617. case 'kill':
  618. case 'fork':
  619. case 'join':
  620. case 'decision':
  621. case 'decisionend':
  622. return control(node, collection);
  623. default:
  624. return normal(node, collection);
  625. }
  626. };
  627. var normal = function(node, collection) {
  628. collection.push(node);
  629. var retNode = null;
  630. $.each(node.links(), function(index, link) {
  631. var next_node = self.registry.get(link.child());
  632. retNode = methodChooser(next_node, collection, false, true);
  633. });
  634. return retNode;
  635. };
  636. var control = function(node, collection, skip_parents_check) {
  637. switch(node.node_type()) {
  638. case 'start':
  639. case 'end':
  640. case 'kill':
  641. case 'join':
  642. case 'decisionend':
  643. return normal(node, collection, false, true);
  644. case 'fork':
  645. collection.push(node);
  646. // Wait for join.
  647. // Iterate through all children and add them to child collection.
  648. var join = null;
  649. $.each(node.links(), function(index, link) {
  650. var next_node = self.registry.get(link.child());
  651. var collection = ko.observableArray([]);
  652. node.children.push(collection);
  653. join = methodChooser(next_node, collection, false, true);
  654. });
  655. // Add join to collection, then find its single child.
  656. return methodChooser(join, collection, true, true);
  657. case 'decision':
  658. collection.push(node);
  659. // Waits for end, then runs through children of end node
  660. var end = null;
  661. $.each(node.links(), function(index, link) {
  662. var next_node = self.registry.get(link.child());
  663. var collection = ko.observableArray([]);
  664. node.children.push(collection);
  665. end = methodChooser(next_node, collection, true, true);
  666. });
  667. // Add end
  668. return methodChooser(node.end(), collection, true, true);
  669. default:
  670. // Should never get here.
  671. return node;
  672. }
  673. };
  674. methodChooser(self.registry.get(self.start()), self.nodes, false, true);
  675. $(".tooltip").remove();
  676. $("[relz=tooltip]").tooltip({placement: "left", delay: 0});
  677. $("[relz=tooltip]").hover(function () {
  678. $(".tooltip").css("left", parseInt($(".tooltip").css("left")) - 10 + "px");
  679. }, function () {
  680. $(".tooltip").remove();
  681. });
  682. },
  683. rebuild: function() {
  684. var self = this;
  685. // Clear all children
  686. $.each(self.registry.nodes, function(index, node) {
  687. node.children.removeAll();
  688. });
  689. self.nodes.removeAll();
  690. // Rebuild
  691. self.build();
  692. self.draggables();
  693. self.droppables();
  694. self.el.trigger('workflow:rebuilt');
  695. },
  696. draggables: function() {
  697. var self = this;
  698. self.el.find('.node-action').each(function(index, el) {
  699. if (!$(el).hasClass('ui-draggable')) {
  700. $(el).find('.row-fluid').eq(0).css('cursor', 'move');
  701. $(el).draggable({
  702. containment: [ self.el.offset().left - 10, self.el.offset().top - 10,
  703. self.el.offset().left + self.el.outerWidth(), self.el.offset().top + self.el.outerHeight() ],
  704. refreshPositions: true,
  705. revert: true,
  706. zIndex: 1000,
  707. opacity: 0.45,
  708. revertDuration: 0,
  709. cancel: '.node-action-bar'
  710. });
  711. }
  712. });
  713. },
  714. droppables: function() {
  715. var self = this;
  716. self.el.find('.node-link').each(function(index, el) {
  717. $(el).droppable({
  718. 'hoverClass': 'node-link-hover',
  719. 'greedy': true,
  720. 'accept': '.node-action',
  721. 'tolerance': 'pointer'
  722. });
  723. });
  724. self.el.find('.node-decision-end').each(function(index, el) {
  725. $(el).droppable({
  726. 'hoverClass': 'node-link-hover',
  727. 'greedy': true,
  728. 'accept': '.node-action',
  729. 'tolerance': 'pointer'
  730. });
  731. });
  732. self.el.find('.node-fork .action').each(function(index, el) {
  733. $(el).droppable({
  734. 'hoverClass': 'node-fork-hover',
  735. 'greedy': true,
  736. 'accept': '.node-action',
  737. 'tolerance': 'pointer'
  738. });
  739. });
  740. self.el.find('.node-decision .action').each(function(index, el) {
  741. $(el).droppable({
  742. 'hoverClass': 'node-fork-hover',
  743. 'greedy': true,
  744. 'accept': '.node-action',
  745. 'tolerance': 'pointer'
  746. });
  747. });
  748. self.el.find('.node-action .action').each(function(index, el) {
  749. $(el).droppable({
  750. 'hoverClass': 'node-action-hover',
  751. 'greedy': true,
  752. 'accept': '.node-action',
  753. 'tolerance': 'pointer'
  754. });
  755. });
  756. },
  757. dragAndDropEvents: function( options ) {
  758. var self = this;
  759. var read_only_error_handler = options.read_only_error_handler;
  760. // Build event delegations.
  761. // Drop on node link
  762. self.el.on('drop', '.node-link', function(e, ui) {
  763. if (self.read_only()) {
  764. read_only_error_handler();
  765. return false;
  766. }
  767. // draggable should be a node.
  768. // droppable should be a link.
  769. var draggable = ko.contextFor(ui.draggable[0]).$data;
  770. var droppable = ko.contextFor(this).$data;
  771. // If newParent is fork, prepend to child instead.
  772. // This will make it so that we can drop and drop to the top of a node list within a fork.
  773. var newParent = self.registry.get(droppable.parent());
  774. if (newParent.id() != draggable.id() && !newParent.isChild(draggable)) {
  775. switch(newParent.node_type()) {
  776. case 'fork':
  777. case 'decision':
  778. // Children that are forks or decisions may be removed when we detach.
  779. // Remember children in this case to find correct node.
  780. var child = self.registry.get(droppable.child());
  781. var children_of_child = [];
  782. if (child.node_type() == 'fork' || child.node_type() == 'decision') {
  783. children_of_child = child.findChildren();
  784. }
  785. draggable.detach();
  786. // Make sure fork and decision still exist
  787. // Otherwise find child that replaced it
  788. var child_to_replace = child;
  789. if (child.node_type() == 'fork' || child.node_type() == 'decision') {
  790. if (!self.registry.get(child.id())) {
  791. // Guaranteed one because the fork is being removed right now.
  792. child_to_replace = $.grep(children_of_child, function(child_of_child, index) {
  793. return child_of_child.findParents().length > 0;
  794. })[0];
  795. }
  796. }
  797. newParent.replaceChild(child_to_replace, draggable);
  798. draggable.addChild(child_to_replace);
  799. break;
  800. case 'join':
  801. case 'decisionend':
  802. // Join and decisionend may disappear when we detach...
  803. // Remember its children and append to child.
  804. var parents = newParent.findParents();
  805. draggable.detach();
  806. if (newParent.findParents().length < 2) {
  807. $.each(parents, function(index, parent) {
  808. parent.append(draggable);
  809. });
  810. } else {
  811. newParent.append(draggable);
  812. }
  813. break;
  814. default:
  815. draggable.detach();
  816. newParent.append(draggable);
  817. break;
  818. }
  819. workflow.is_dirty( true );
  820. self.rebuild();
  821. }
  822. // Prevent bubbling events
  823. return false;
  824. });
  825. // Drop on fork
  826. self.el.on('drop', '.node-fork', function(e, ui) {
  827. if (self.read_only()) {
  828. read_only_error_handler();
  829. return false;
  830. }
  831. // draggable should be a node.
  832. // droppable should be a fork.
  833. var draggable = ko.contextFor(ui.draggable[0]).$data;
  834. var droppable = ko.contextFor(this).$data;
  835. if (!droppable.isChild(draggable) && droppable.id() != draggable.id()) {
  836. draggable.detach();
  837. droppable.append(draggable);
  838. self.rebuild();
  839. }
  840. // Prevent bubbling events
  841. return false;
  842. });
  843. // Drop on decision
  844. self.el.on('drop', '.node-decision', function(e, ui) {
  845. if (self.read_only()) {
  846. read_only_error_handler();
  847. return false;
  848. }
  849. // draggable should be a node.
  850. // droppable should be a fork.
  851. var draggable = ko.contextFor(ui.draggable[0]).$data;
  852. var droppable = ko.contextFor(this).$data;
  853. if (!droppable.isChild(draggable) && droppable.id() != draggable.id()) {
  854. draggable.detach();
  855. droppable.append(draggable);
  856. self.rebuild();
  857. }
  858. // Prevent bubbling events
  859. return false;
  860. });
  861. // Drop on action
  862. self.el.on('drop', '.node-action', function(e, ui) {
  863. if (self.read_only()) {
  864. read_only_error_handler();
  865. return false;
  866. }
  867. // draggable should be a node.
  868. // droppable should be a node.
  869. var draggable = ko.contextFor(ui.draggable[0]).$data;
  870. var droppable = ko.contextFor(this).$data;
  871. // Create a fork and join programatically.
  872. var newParents = droppable.findParents();
  873. // skip forking beneathe a decision node
  874. if (droppable.id() != draggable.id() && newParents.length == 1 && draggable.findParents().length <= 1) {
  875. var ForkModel = NodeModelChooser('fork');
  876. var JoinModel = NodeModelChooser('join');
  877. var fork = new ForkModel({
  878. id: IdGeneratorTable['fork'].nextId(),
  879. description: "",
  880. workflow: self.id,
  881. node_type: "fork",
  882. child_links: []
  883. });
  884. var forkNode = new ForkNode(self, fork, self.registry);
  885. var join = new JoinModel({
  886. id: IdGeneratorTable['join'].nextId(),
  887. description: "",
  888. workflow: self.id,
  889. node_type: "join",
  890. child_links: []
  891. });
  892. var joinNode = new Node(self, join, self.registry);
  893. self.registry.add(forkNode.id(), forkNode);
  894. self.registry.add(joinNode.id(), joinNode);
  895. forkNode.addChild(joinNode);
  896. // Handles fork creation.
  897. $.each(newParents, function(index, parent) {
  898. parent.replaceChild(droppable, forkNode);
  899. });
  900. draggable.detach();
  901. forkNode.append(draggable);
  902. forkNode.append(droppable);
  903. self.rebuild();
  904. }
  905. // Prevent bubbling events.
  906. return false;
  907. });
  908. }
  909. });
  910. return module;
  911. };
  912. var Workflow = WorkflowModule($, nodeModelChooser, Node, ForkNode, DecisionNode, IdGeneratorTable);
  913. // Manage Kill Module
  914. function ManageKillModule($, workflow, NodeModelChooser, Node, NodeModel) {
  915. var email_action = null;
  916. var parents = workflow.kill.findParents();
  917. var email_enabled = ko.observable();
  918. if (parents.length > 0) {
  919. email_action = parents[0];
  920. email_enabled(true);
  921. } else {
  922. var email_json = {
  923. "description": "",
  924. "workflow": workflow.id(),
  925. "child_links": [],
  926. "node_type": "email",
  927. "message": "Action failed, error message[${wf:errorMessage(wf:lastErrorNode())}]",
  928. "name": 'killemail',
  929. "id": IdGeneratorTable['email'].nextId()
  930. };
  931. var NodeModel = NodeModelChooser(email_json.node_type);
  932. var model = new NodeModel(email_json);
  933. email_action = new Node(workflow, model, workflow.registry);
  934. email_enabled(false);
  935. }
  936. var replace_email = function(email_action) {
  937. email_action.removeAllChildren();
  938. email_action.removeErrorChildren();
  939. $.each(workflow.registry.nodes, function(index, node) {
  940. if (node.getErrorChild() && node.id() != email_action.id()) {
  941. node.putErrorChild(workflow.kill);
  942. }
  943. });
  944. };
  945. var replace_kill = function(email_action) {
  946. if (email_action.findChildren().length == 0) {
  947. email_action.addChild(workflow.kill, 'ok');
  948. }
  949. if (!email_action.getErrorChild()) {
  950. email_action.putErrorChild(workflow.kill);
  951. }
  952. $.each(workflow.registry.nodes, function(index, node) {
  953. if (node.getErrorChild() && node.id() != email_action.id()) {
  954. node.putErrorChild(email_action);
  955. }
  956. });
  957. };
  958. // Add/Remove kill email action node from registry so that it is not sent to server.
  959. email_action.to.subscribe(function(value) {
  960. if (value && !email_enabled()) {
  961. workflow.registry.add(email_action.id(), email_action);
  962. replace_kill(email_action);
  963. email_enabled(true);
  964. } else if (!value && email_enabled()) {
  965. replace_email(email_action);
  966. email_enabled(false);
  967. workflow.registry.remove(email_action.id());
  968. email_action.id(IdGeneratorTable['email'].nextId());
  969. }
  970. return value;
  971. });
  972. // View model
  973. return {
  974. 'enabled': email_enabled,
  975. 'isValid': function() {
  976. return email_action.validate();
  977. },
  978. 'context': ko.observable({
  979. 'node': ko.observable(email_action),
  980. 'read_only': ko.observable(workflow.read_only())
  981. })
  982. };
  983. };