Selection.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import {
  2. isArray,
  3. forEach
  4. } from 'min-dash';
  5. /**
  6. * A service that offers the current selection in a diagram.
  7. * Offers the api to control the selection, too.
  8. *
  9. * @class
  10. *
  11. * @param {EventBus} eventBus the event bus
  12. */
  13. export default function Selection(eventBus) {
  14. this._eventBus = eventBus;
  15. this._selectedElements = [];
  16. var self = this;
  17. eventBus.on([ 'shape.remove', 'connection.remove' ], function(e) {
  18. var element = e.element;
  19. self.deselect(element);
  20. });
  21. eventBus.on([ 'diagram.clear' ], function(e) {
  22. self.select(null);
  23. });
  24. }
  25. Selection.$inject = [ 'eventBus' ];
  26. Selection.prototype.deselect = function(element) {
  27. var selectedElements = this._selectedElements;
  28. var idx = selectedElements.indexOf(element);
  29. if (idx !== -1) {
  30. var oldSelection = selectedElements.slice();
  31. selectedElements.splice(idx, 1);
  32. this._eventBus.fire('selection.changed', { oldSelection: oldSelection, newSelection: selectedElements });
  33. }
  34. };
  35. Selection.prototype.get = function() {
  36. return this._selectedElements;
  37. };
  38. Selection.prototype.isSelected = function(element) {
  39. return this._selectedElements.indexOf(element) !== -1;
  40. };
  41. /**
  42. * This method selects one or more elements on the diagram.
  43. *
  44. * By passing an additional add parameter you can decide whether or not the element(s)
  45. * should be added to the already existing selection or not.
  46. *
  47. * @method Selection#select
  48. *
  49. * @param {Object|Object[]} elements element or array of elements to be selected
  50. * @param {boolean} [add] whether the element(s) should be appended to the current selection, defaults to false
  51. */
  52. Selection.prototype.select = function(elements, add) {
  53. var selectedElements = this._selectedElements,
  54. oldSelection = selectedElements.slice();
  55. if (!isArray(elements)) {
  56. elements = elements ? [ elements ] : [];
  57. }
  58. // selection may be cleared by passing an empty array or null
  59. // to the method
  60. if (add) {
  61. forEach(elements, function(element) {
  62. if (selectedElements.indexOf(element) !== -1) {
  63. // already selected
  64. return;
  65. } else {
  66. selectedElements.push(element);
  67. }
  68. });
  69. } else {
  70. this._selectedElements = selectedElements = elements.slice();
  71. }
  72. this._eventBus.fire('selection.changed', { oldSelection: oldSelection, newSelection: selectedElements });
  73. };