OrderingProvider.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import inherits from 'inherits';
  2. import CommandInterceptor from '../../command/CommandInterceptor';
  3. /**
  4. * An abstract provider that allows modelers to implement a custom
  5. * ordering of diagram elements on the canvas.
  6. *
  7. * It makes sure that the order is always preserved during element
  8. * creation and move operations.
  9. *
  10. * In order to use this behavior, inherit from it and override
  11. * the method {@link OrderingProvider#getOrdering}.
  12. *
  13. * @example
  14. *
  15. * ```javascript
  16. * function CustomOrderingProvider(eventBus) {
  17. * OrderingProvider.call(this, eventBus);
  18. *
  19. * this.getOrdering = function(element, newParent) {
  20. * // always insert elements at the front
  21. * // when moving
  22. * return {
  23. * index: 0,
  24. * parent: newParent
  25. * };
  26. * };
  27. * }
  28. * ```
  29. *
  30. * @param {EventBus} eventBus
  31. */
  32. export default function OrderingProvider(eventBus) {
  33. CommandInterceptor.call(this, eventBus);
  34. var self = this;
  35. this.preExecute([ 'shape.create', 'connection.create' ], function(event) {
  36. var context = event.context,
  37. element = context.shape || context.connection,
  38. parent = context.parent;
  39. var ordering = self.getOrdering(element, parent);
  40. if (ordering) {
  41. if (ordering.parent !== undefined) {
  42. context.parent = ordering.parent;
  43. }
  44. context.parentIndex = ordering.index;
  45. }
  46. });
  47. this.preExecute([ 'shape.move', 'connection.move' ], function(event) {
  48. var context = event.context,
  49. element = context.shape || context.connection,
  50. parent = context.newParent || element.parent;
  51. var ordering = self.getOrdering(element, parent);
  52. if (ordering) {
  53. if (ordering.parent !== undefined) {
  54. context.newParent = ordering.parent;
  55. }
  56. context.newParentIndex = ordering.index;
  57. }
  58. });
  59. }
  60. /**
  61. * Return a custom ordering of the element, both in terms
  62. * of parent element and index in the new parent.
  63. *
  64. * Implementors of this method must return an object with
  65. * `parent` _and_ `index` in it.
  66. *
  67. * @param {djs.model.Base} element
  68. * @param {djs.model.Shape} newParent
  69. *
  70. * @return {Object} ordering descriptor
  71. */
  72. OrderingProvider.prototype.getOrdering = function(element, newParent) {
  73. return null;
  74. };
  75. inherits(OrderingProvider, CommandInterceptor);