CustomAutoPlace.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import AutoPlace from 'diagram-js/lib/features/auto-place/AutoPlace';
  2. export default function CustomAutoPlace(eventBus, modeling) {
  3. AutoPlace.call(this, eventBus, modeling, 3000);
  4. eventBus.on('autoPlace', 3000, function(context) {
  5. const shape = context.shape;
  6. const source = context.source;
  7. return getNewCustomShapePosition(source, shape);
  8. });
  9. this.append = function(source, shape, hints) {
  10. eventBus.fire('autoPlace.start', {
  11. source: source,
  12. shape: shape
  13. });
  14. // allow others to provide the position
  15. var position = eventBus.fire('autoPlace', {
  16. source: source,
  17. shape: shape
  18. });
  19. console.log('hints', hints, 'position', position);
  20. var newShape = modeling.appendShape(source, shape, position, source.parent, hints);
  21. eventBus.fire('autoPlace.end', {
  22. source: source,
  23. shape: newShape
  24. });
  25. return newShape;
  26. };
  27. }
  28. export function asTRBL(bounds) {
  29. return {
  30. top: bounds.y,
  31. right: bounds.x + (bounds.width || 0),
  32. bottom: bounds.y + (bounds.height || 0),
  33. left: bounds.x
  34. };
  35. }
  36. export function roundPoint(point) {
  37. return {
  38. x: Math.round(point.x),
  39. y: Math.round(point.y)
  40. };
  41. }
  42. export function getMid(bounds) {
  43. return roundPoint({
  44. x: bounds.x + (bounds.width || 0) / 2,
  45. y: bounds.y + (bounds.height || 0) / 2
  46. });
  47. }
  48. export function getNewCustomShapePosition(source, element, hints) {
  49. if (!hints) {
  50. hints = {};
  51. }
  52. var distance = hints.defaultDistance || 50;
  53. var sourceMid = getMid(source);
  54. var sourceTrbl = asTRBL(source);
  55. // simply put element right next to source
  56. return {
  57. x: sourceMid.x,
  58. y: sourceTrbl.bottom + distance + element.height / 2
  59. };
  60. }
  61. const F = function() {}; // 核心,利用空对象作为中介;
  62. F.prototype = AutoPlace.prototype; // 核心,将父类的原型赋值给空对象F;
  63. CustomAutoPlace.prototype = new F(); // 核心,将 F的实例赋值给子类;
  64. CustomAutoPlace.prototype.constructor = AutoPlace; // 修复子类CustomRenderer的构造器指向,防止原型链的混乱;