ToolManager.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. import {
  2. forEach
  3. } from 'min-dash';
  4. import {
  5. closest as domClosest
  6. } from 'min-dom';
  7. var LOW_PRIORITY = 250;
  8. /**
  9. * The tool manager acts as middle-man between the available tool's and the Palette,
  10. * it takes care of making sure that the correct active state is set.
  11. *
  12. * @param {Object} eventBus
  13. * @param {Object} dragging
  14. */
  15. export default function ToolManager(eventBus, dragging) {
  16. this._eventBus = eventBus;
  17. this._dragging = dragging;
  18. this._tools = [];
  19. this._active = null;
  20. }
  21. ToolManager.$inject = [ 'eventBus', 'dragging' ];
  22. ToolManager.prototype.registerTool = function(name, events) {
  23. var tools = this._tools;
  24. if (!events) {
  25. throw new Error('A tool has to be registered with it\'s "events"');
  26. }
  27. tools.push(name);
  28. this.bindEvents(name, events);
  29. };
  30. ToolManager.prototype.isActive = function(tool) {
  31. return tool && this._active === tool;
  32. };
  33. ToolManager.prototype.length = function(tool) {
  34. return this._tools.length;
  35. };
  36. ToolManager.prototype.setActive = function(tool) {
  37. var eventBus = this._eventBus;
  38. if (this._active !== tool) {
  39. this._active = tool;
  40. eventBus.fire('tool-manager.update', { tool: tool });
  41. }
  42. };
  43. ToolManager.prototype.bindEvents = function(name, events) {
  44. var eventBus = this._eventBus,
  45. dragging = this._dragging;
  46. var eventsToRegister = [];
  47. eventBus.on(events.tool + '.init', function(event) {
  48. var context = event.context;
  49. // Active tools that want to reactivate themselves must do this explicitly
  50. if (!context.reactivate && this.isActive(name)) {
  51. this.setActive(null);
  52. dragging.cancel();
  53. return;
  54. }
  55. this.setActive(name);
  56. }, this);
  57. // Todo[ricardo]: add test cases
  58. forEach(events, function(event) {
  59. eventsToRegister.push(event + '.ended');
  60. eventsToRegister.push(event + '.canceled');
  61. });
  62. eventBus.on(eventsToRegister, LOW_PRIORITY, function(event) {
  63. var originalEvent = event.originalEvent;
  64. // We defer the de-activation of the tool to the .activate phase,
  65. // so we're able to check if we want to toggle off the current
  66. // active tool or switch to a new one
  67. if (!this._active) {
  68. return;
  69. }
  70. if (originalEvent && domClosest(originalEvent.target, '.group[data-group="tools"]')) {
  71. return;
  72. }
  73. this.setActive(null);
  74. }, this);
  75. };