GridSnappingAutoPlaceBehavior.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import { getNewShapePosition } from '../../auto-place/BpmnAutoPlaceUtil';
  2. import { getMid } from 'diagram-js/lib/layout/LayoutUtil';
  3. import { is } from '../../../util/ModelUtil';
  4. /**
  5. * @typedef {import('diagram-js/lib/core/EventBus').default} EventBus
  6. * @typedef {import('diagram-js/lib/features/grid-snapping/GridSnapping').default} GridSnapping
  7. *
  8. * @typedef {import('diagram-js/lib/util/Types').Axis} Axis
  9. */
  10. var HIGH_PRIORITY = 2000;
  11. /**
  12. * @param {EventBus} eventBus
  13. * @param {GridSnapping} gridSnapping
  14. */
  15. export default function GridSnappingAutoPlaceBehavior(eventBus, gridSnapping) {
  16. eventBus.on('autoPlace', HIGH_PRIORITY, function(context) {
  17. var source = context.source,
  18. sourceMid = getMid(source),
  19. shape = context.shape;
  20. var position = getNewShapePosition(source, shape);
  21. [ 'x', 'y' ].forEach(function(axis) {
  22. var options = {};
  23. // do not snap if x/y equal
  24. if (position[ axis ] === sourceMid[ axis ]) {
  25. return;
  26. }
  27. if (position[ axis ] > sourceMid[ axis ]) {
  28. options.min = position[ axis ];
  29. } else {
  30. options.max = position[ axis ];
  31. }
  32. if (is(shape, 'bpmn:TextAnnotation')) {
  33. if (isHorizontal(axis)) {
  34. options.offset = -shape.width / 2;
  35. } else {
  36. options.offset = -shape.height / 2;
  37. }
  38. }
  39. position[ axis ] = gridSnapping.snapValue(position[ axis ], options);
  40. });
  41. // must be returned to be considered by auto place
  42. return position;
  43. });
  44. }
  45. GridSnappingAutoPlaceBehavior.$inject = [
  46. 'eventBus',
  47. 'gridSnapping'
  48. ];
  49. // helpers //////////
  50. /**
  51. * @param {Axis} axis
  52. *
  53. * @return {boolean}
  54. */
  55. function isHorizontal(axis) {
  56. return axis === 'x';
  57. }