workflow.js 28 KB

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