all files / Github/diagram-js/lib/features/connection-preview/ ConnectionPreview.js

97.56% Statements 80/82
83.33% Branches 45/54
100% Functions 12/12
97.56% Lines 80/82
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295                                                                      68× 68× 68×     68× 68×                                                       13×   13× 13× 13× 13× 13× 13× 13× 13× 13× 13×     13×   13×     13×   13×       13×     13×                                                                                                                                                                                                                                               12×   12×   12×     12×                                
import {
  append as svgAppend,
  attr as svgAttr,
  classes as svgClasses,
  create as svgCreate,
  remove as svgRemove,
  clear as svgClear
} from 'tiny-svg';
 
import {
  isObject
} from 'min-dash';
 
import {
  getElementLineIntersection,
  getMid
} from '../../layout/LayoutUtil';
 
 
var MARKER_CONNECTION_PREVIEW = 'djs-connection-preview';
 
/**
 * Draws connection preview. Optionally, this can use layouter and connection docking to draw
 * better looking previews.
 *
 * @param {didi.Injector} injector
 * @param {Canvas} canvas
 * @param {GraphicsFactory} graphicsFactory
 * @param {ElementFactory} elementFactory
 */
export default function ConnectionPreview(
    injector,
    canvas,
    graphicsFactory,
    elementFactory
) {
  this._canvas = canvas;
  this._graphicsFactory = graphicsFactory;
  this._elementFactory = elementFactory;
 
  // optional components
  this._connectionDocking = injector.get('connectionDocking', false);
  this._layouter = injector.get('layouter', false);
}
 
ConnectionPreview.$inject = [
  'injector',
  'canvas',
  'graphicsFactory',
  'elementFactory'
];
 
/**
 * Draw connection preview.
 *
 * Provide at least one of <source, connectionStart> and <target, connectionEnd> to create a preview.
 * In the clean up stage, call `connectionPreview#cleanUp` with the context to remove preview.
 *
 * @param {Object} context
 * @param {Object|boolean} canConnect
 * @param {Object} hints
 * @param {djs.model.shape} [hints.source] source element
 * @param {djs.model.shape} [hints.target] target element
 * @param {Point} [hints.connectionStart] connection preview start
 * @param {Point} [hints.connectionEnd] connection preview end
 * @param {Array<Point>} [hints.waypoints] provided waypoints for preview
 * @param {boolean} [hints.noLayout] true if preview should not be laid out
 * @param {boolean} [hints.noCropping] true if preview should not be cropped
 * @param {boolean} [hints.noNoop] true if simple connection should not be drawn
 */
ConnectionPreview.prototype.drawPreview = function(context, canConnect, hints) {
 
  hints = hints || {};
 
  var connectionPreviewGfx = context.connectionPreviewGfx,
      getConnection = context.getConnection,
      source = hints.source,
      target = hints.target,
      waypoints = hints.waypoints,
      connectionStart = hints.connectionStart,
      connectionEnd = hints.connectionEnd,
      noLayout = hints.noLayout,
      noCropping = hints.noCropping,
      noNoop = hints.noNoop,
      connection;
 
  var self = this;
 
  if (!connectionPreviewGfx) {
    connectionPreviewGfx = context.connectionPreviewGfx = this.createConnectionPreviewGfx();
  }
 
  svgClear(connectionPreviewGfx);
 
  if (!getConnection) {
    getConnection = context.getConnection = cacheReturnValues(function(canConnect, source, target) {
      return self.getConnection(canConnect, source, target);
    });
  }
 
  if (canConnect) {
    connection = getConnection(canConnect, source, target);
  }
 
  if (!connection) {
    !noNoop && this.drawNoopPreview(connectionPreviewGfx, hints);
    return;
  }
 
  connection.waypoints = waypoints || [];
 
  // optional layout
  if (this._layouter && !noLayout) {
    connection.waypoints = this._layouter.layoutConnection(connection, {
      source: source,
      target: target,
      connectionStart: connectionStart,
      connectionEnd: connectionEnd
    });
  }
 
  // fallback if no waypoints were provided nor created with layouter
  Iif (!connection.waypoints || !connection.waypoints.length) {
    connection.waypoints = [
      source ? getMid(source) : connectionStart,
      target ? getMid(target) : connectionEnd
    ];
  }
 
  // optional cropping
  if (this._connectionDocking && (source || target) && !noCropping) {
    connection.waypoints = this._connectionDocking.getCroppedWaypoints(connection, source, target);
  }
 
  this._graphicsFactory.drawConnection(connectionPreviewGfx, connection);
};
 
/**
 * Draw simple connection between source and target or provided points.
 *
 * @param {SVGElement} connectionPreviewGfx container for the connection
 * @param {Object} hints
 * @param {djs.model.shape} [hints.source] source element
 * @param {djs.model.shape} [hints.target] target element
 * @param {Point} [hints.connectionStart] required if source is not provided
 * @param {Point} [hints.connectionEnd] required if target is not provided
 */
ConnectionPreview.prototype.drawNoopPreview = function(connectionPreviewGfx, hints) {
  var source = hints.source,
      target = hints.target,
      start = hints.connectionStart || getMid(source),
      end = hints.connectionEnd || getMid(target);
 
  var waypoints = this.cropWaypoints(start, end, source, target);
 
  var connection = this.createNoopConnection(waypoints[0], waypoints[1]);
 
  svgAppend(connectionPreviewGfx, connection);
};
 
/**
 * Return cropped waypoints.
 *
 * @param {Point} start
 * @param {Point} end
 * @param {djs.model.shape} source
 * @param {djs.model.shape} target
 *
 * @returns {Array}
 */
ConnectionPreview.prototype.cropWaypoints = function(start, end, source, target) {
  var graphicsFactory = this._graphicsFactory,
      sourcePath = source && graphicsFactory.getShapePath(source),
      targetPath = target && graphicsFactory.getShapePath(target),
      connectionPath = graphicsFactory.getConnectionPath({ waypoints: [ start, end ] });
 
  start = (source && getElementLineIntersection(sourcePath, connectionPath, true)) || start;
  end = (target && getElementLineIntersection(targetPath, connectionPath, false)) || end;
 
  return [ start, end ];
};
 
/**
 * Remove connection preview container if it exists.
 *
 * @param {Object} [context]
 * @param {SVGElement} [context.connectionPreviewGfx] preview container
 */
ConnectionPreview.prototype.cleanUp = function(context) {
  Eif (context && context.connectionPreviewGfx) {
    svgRemove(context.connectionPreviewGfx);
  }
};
 
/**
 * Get connection that connects source and target.
 *
 * @param {Object|boolean} canConnect
 *
 * @returns {djs.model.connection}
 */
ConnectionPreview.prototype.getConnection = function(canConnect) {
  var attrs = ensureConnectionAttrs(canConnect);
 
  return this._elementFactory.createConnection(attrs);
};
 
 
/**
 * Add and return preview graphics.
 *
 * @returns {SVGElement}
 */
ConnectionPreview.prototype.createConnectionPreviewGfx = function() {
  var gfx = svgCreate('g');
 
  svgAttr(gfx, {
    pointerEvents: 'none'
  });
 
  svgClasses(gfx).add(MARKER_CONNECTION_PREVIEW);
 
  svgAppend(this._canvas.getDefaultLayer(), gfx);
 
  return gfx;
};
 
/**
 * Create and return simple connection.
 *
 * @param {Point} start
 * @param {Point} end
 *
 * @returns {SVGElement}
 */
ConnectionPreview.prototype.createNoopConnection = function(start, end) {
  var connection = svgCreate('polyline');
 
  svgAttr(connection, {
    'stroke': '#333',
    'strokeDasharray': [ 1 ],
    'strokeWidth': 2,
    'pointer-events': 'none'
  });
 
  svgAttr(connection, { 'points': [ start.x, start.y, end.x, end.y ] });
 
  return connection;
};
 
// helpers //////////
 
/**
 * Returns function that returns cached return values referenced by stringified first argument.
 *
 * @param {Function} fn
 *
 * @return {Function}
 */
function cacheReturnValues(fn) {
  var returnValues = {};
 
  /**
   * Return cached return value referenced by stringified first argument.
   *
   * @returns {*}
   */
  return function(firstArgument) {
    var key = JSON.stringify(firstArgument);
 
    var returnValue = returnValues[key];
 
    if (!returnValue) {
      returnValue = returnValues[key] = fn.apply(null, arguments);
    }
 
    return returnValue;
  };
}
 
/**
 * Ensure connection attributes is object.
 *
 * @param {Object|boolean} canConnect
 *
 * @returns {Object}
 */
function ensureConnectionAttrs(canConnect) {
  Eif (isObject(canConnect)) {
    return canConnect;
  } else {
    return {};
  }
}