CreateShapeHandler.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import { assign } from 'min-dash';
  2. var round = Math.round;
  3. /**
  4. * A handler that implements reversible addition of shapes.
  5. *
  6. * @param {canvas} Canvas
  7. */
  8. export default function CreateShapeHandler(canvas) {
  9. this._canvas = canvas;
  10. }
  11. CreateShapeHandler.$inject = [ 'canvas' ];
  12. // api //////////////////////
  13. /**
  14. * Appends a shape to a target shape
  15. *
  16. * @param {Object} context
  17. * @param {djs.model.Base} context.parent the parent object
  18. * @param {Point} context.position position of the new element
  19. */
  20. CreateShapeHandler.prototype.execute = function(context) {
  21. var shape = context.shape,
  22. positionOrBounds = context.position,
  23. parent = context.parent,
  24. parentIndex = context.parentIndex;
  25. if (!parent) {
  26. throw new Error('parent required');
  27. }
  28. if (!positionOrBounds) {
  29. throw new Error('position required');
  30. }
  31. // (1) add at event center position _or_ at given bounds
  32. if (positionOrBounds.width !== undefined) {
  33. assign(shape, positionOrBounds);
  34. } else {
  35. assign(shape, {
  36. x: positionOrBounds.x - round(shape.width / 2),
  37. y: positionOrBounds.y - round(shape.height / 2)
  38. });
  39. }
  40. // (2) add to canvas
  41. this._canvas.addShape(shape, parent, parentIndex);
  42. return shape;
  43. };
  44. /**
  45. * Undo append by removing the shape
  46. */
  47. CreateShapeHandler.prototype.revert = function(context) {
  48. var shape = context.shape;
  49. // (3) remove form canvas
  50. this._canvas.removeShape(shape);
  51. return shape;
  52. };