UpdateAttachmentHandler.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import {
  2. add as collectionAdd,
  3. remove as collectionRemove
  4. } from '../../../util/Collections';
  5. /**
  6. * A handler that implements reversible attaching/detaching of shapes.
  7. */
  8. export default function UpdateAttachmentHandler(modeling) {
  9. this._modeling = modeling;
  10. }
  11. UpdateAttachmentHandler.$inject = [ 'modeling' ];
  12. UpdateAttachmentHandler.prototype.execute = function(context) {
  13. var shape = context.shape,
  14. newHost = context.newHost,
  15. oldHost = shape.host;
  16. // (0) detach from old host
  17. context.oldHost = oldHost;
  18. context.attacherIdx = removeAttacher(oldHost, shape);
  19. // (1) attach to new host
  20. addAttacher(newHost, shape);
  21. // (2) update host
  22. shape.host = newHost;
  23. return shape;
  24. };
  25. UpdateAttachmentHandler.prototype.revert = function(context) {
  26. var shape = context.shape,
  27. newHost = context.newHost,
  28. oldHost = context.oldHost,
  29. attacherIdx = context.attacherIdx;
  30. // (2) update host
  31. shape.host = oldHost;
  32. // (1) attach to new host
  33. removeAttacher(newHost, shape);
  34. // (0) detach from old host
  35. addAttacher(oldHost, shape, attacherIdx);
  36. return shape;
  37. };
  38. function removeAttacher(host, attacher) {
  39. // remove attacher from host
  40. return collectionRemove(host && host.attachers, attacher);
  41. }
  42. function addAttacher(host, attacher, idx) {
  43. if (!host) {
  44. return;
  45. }
  46. var attachers = host.attachers;
  47. if (!attachers) {
  48. host.attachers = attachers = [];
  49. }
  50. collectionAdd(attachers, attacher, idx);
  51. }