All files / packages/tools/src/drawingSvg drawPolyline.ts

0% Statements 0/26
0% Branches 0/8
0% Functions 0/1
0% Lines 0/21

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                                                                                                                                 
import type { Types } from '@cornerstonejs/core';
import _getHash from './_getHash';
import _setNewAttributesIfValid from './_setNewAttributesIfValid';
import _setAttributesIfNecessary from './_setAttributesIfNecessary';
import { SVGDrawingHelper } from '../types';
 
/**
 * Draws an SVG polyline with the given points.
 *
 * The `connectLastToFirst` option, if true, draws a closed polyline, with the
 * last point connected to the first.
 */
export default function drawPolyline(
  svgDrawingHelper: SVGDrawingHelper,
  annotationUID: string,
  polylineUID: string,
  points: Types.Point2[],
  options: {
    color?: string;
    width?: number;
    lineWidth?: number;
    lineDash?: string;
    connectLastToFirst?: boolean;
  }
): void {
  if (points.length < 2) {
    return;
  }
 
  const { color, width, lineWidth, lineDash } = Object.assign(
    {
      color: 'dodgerblue',
      width: '2',
      lineWidth: undefined,
      lineDash: undefined,
      connectLastToFirst: false,
    },
    options
  );
 
  // for supporting both lineWidth and width options
  const strokeWidth = lineWidth || width;
 
  const svgns = 'http://www.w3.org/2000/svg';
  const svgNodeHash = _getHash(annotationUID, 'polyline', polylineUID);
  const existingPolyLine = svgDrawingHelper.getSvgNode(svgNodeHash);
 
  let pointsAttribute = '';
 
  for (const point of points) {
    pointsAttribute += `${point[0]}, ${point[1]} `;
  }
 
  if (options.connectLastToFirst) {
    const firstPoint = points[0];
 
    pointsAttribute += `${firstPoint[0]}, ${firstPoint[1]}`;
  }
 
  const attributes = {
    points: pointsAttribute,
    stroke: color,
    fill: 'none',
    'stroke-width': strokeWidth,
    'stroke-dasharray': lineDash,
  };
 
  if (existingPolyLine) {
    // This is run to avoid re-rendering annotations that actually haven't changed
    _setAttributesIfNecessary(attributes, existingPolyLine);
 
    svgDrawingHelper.setNodeTouched(svgNodeHash);
  } else {
    const newPolyLine = document.createElementNS(svgns, 'polyline');
 
    _setNewAttributesIfValid(attributes, newPolyLine);
 
    svgDrawingHelper.appendNode(newPolyLine, svgNodeHash);
  }
}