CreateLabelHandler.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import inherits from 'inherits-browser';
  2. import CreateShapeHandler from './CreateShapeHandler';
  3. /**
  4. * A handler that attaches a label to a given target shape.
  5. *
  6. * @param {Canvas} canvas
  7. */
  8. export default function CreateLabelHandler(canvas) {
  9. CreateShapeHandler.call(this, canvas);
  10. }
  11. inherits(CreateLabelHandler, CreateShapeHandler);
  12. CreateLabelHandler.$inject = [ 'canvas' ];
  13. // api //////////////////////
  14. var originalExecute = CreateShapeHandler.prototype.execute;
  15. /**
  16. * Appends a label to a target shape.
  17. *
  18. * @method CreateLabelHandler#execute
  19. *
  20. * @param {Object} context
  21. * @param {ElementDescriptor} context.target the element the label is attached to
  22. * @param {ElementDescriptor} context.parent the parent object
  23. * @param {Point} context.position position of the new element
  24. */
  25. CreateLabelHandler.prototype.execute = function(context) {
  26. var label = context.shape;
  27. ensureValidDimensions(label);
  28. label.labelTarget = context.labelTarget;
  29. return originalExecute.call(this, context);
  30. };
  31. var originalRevert = CreateShapeHandler.prototype.revert;
  32. /**
  33. * Undo append by removing the shape
  34. */
  35. CreateLabelHandler.prototype.revert = function(context) {
  36. context.shape.labelTarget = null;
  37. return originalRevert.call(this, context);
  38. };
  39. // helpers //////////////////////
  40. function ensureValidDimensions(label) {
  41. // make sure a label has valid { width, height } dimensions
  42. [ 'width', 'height' ].forEach(function(prop) {
  43. if (typeof label[prop] === 'undefined') {
  44. label[prop] = 0;
  45. }
  46. });
  47. }