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

78.37% Statements 58/74
42.85% Branches 6/14
100% Functions 5/5
78.87% Lines 56/71

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 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                                            73x                           73x                 73x                     73x     73x 73x 73x 73x       73x   8x 8x   8x 18x 18x   18x       8x                       8x           8x         8x 8x   8x   8x   65x   65x     65x 65x 150x 150x   150x     65x 65x 65x           73x                       65x 65x 65x   65x 65x 65x     65x 65x 65x 65x 65x 65x   65x       150x 150x           150x 150x 150x   150x       73x       73x 73x       73x                                                      
import type { Types } from '@cornerstonejs/core';
import { SVGDrawingHelper } from '../types';
 
import _getHash from './_getHash';
import setAttributesIfNecessary from './setAttributesIfNecessary';
 
/**
 * Draws a textBox.
 *
 * @param textLines - The text to display.
 * @param position - The x/y position of the textbox
 * @param options - Options for the textBox.
 * @returns Bounding box; can be used for isPointNearTool
 */
function drawTextBox(
  svgDrawingHelper: SVGDrawingHelper,
  annotationUID: string,
  textUID: string,
  textLines: Array<string>,
  position: Types.Point2,
  options = {}
): SVGRect {
  const mergedOptions = Object.assign(
    {
      fontFamily: 'Helvetica, Arial, sans-serif',
      fontSize: '14px',
      color: 'rgb(255, 255, 0)',
      background: '',
      padding: 25,
      centerX: false,
      centerY: true,
    },
    options
  );
 
  // Draw each of the text lines on top of the background box
  const textGroupBoundingBox = _drawTextGroup(
    svgDrawingHelper,
    annotationUID,
    textUID,
    textLines,
    position,
    mergedOptions
  );
 
  return textGroupBoundingBox;
}
 
function _drawTextGroup(
  svgDrawingHelper: SVGDrawingHelper,
  annotationUID: string,
  textUID: string,
  textLines: Array<string> = [''],
  position: Types.Point2,
  options: any
): SVGRect {
  const { padding, color, fontFamily, fontSize, background } = options;
 
  let textGroupBoundingBox;
  const [x, y] = [position[0] + padding, position[1] + padding];
  const svgns = 'http://www.w3.org/2000/svg';
  const svgNodeHash = _getHash(annotationUID, 'text', textUID);
  const existingTextGroup = svgDrawingHelper.getSvgNode(svgNodeHash);
 
  // Todo: right now textBox gets a re-render even if the textBox has not changed
  // and evenIf the attributes are not set again since they are the same.
  if (existingTextGroup) {
    // TODO: Iterate each node and update color? font-size?
    const textElement = existingTextGroup.querySelector('text');
    const textSpans = Array.from(textElement.children) as Array<SVGElement>;
 
    for (let i = 0; i < textSpans.length; i++) {
      const textSpanElement = textSpans[i];
      const text = textLines[i] || '';
 
      textSpanElement.textContent = text;
    }
 
    // if the textLines have changed size, we need to create textSpans for them
    Iif (textLines.length > textSpans.length) {
      for (let i = 0; i < textLines.length - textSpans.length; i++) {
        const textLine = textLines[i + textSpans.length];
        const textSpan = _createTextSpan(textLine);
 
        textElement.appendChild(textSpan);
      }
 
      existingTextGroup.appendChild(textElement);
      svgDrawingHelper.appendNode(existingTextGroup, svgNodeHash);
    }
 
    const textAttributes = {
      fill: color,
      'font-size': fontSize,
      'font-family': fontFamily,
    };
 
    const textGroupAttributes = {
      transform: `translate(${x} ${y})`,
    };
 
    // Todo: for some reason this does not work to not re-render the textBox
    setAttributesIfNecessary(textAttributes, textElement);
    setAttributesIfNecessary(textGroupAttributes, existingTextGroup);
 
    textGroupBoundingBox = _drawTextBackground(existingTextGroup, background);
 
    svgDrawingHelper.setNodeTouched(svgNodeHash);
  } else {
    const textGroup = document.createElementNS(svgns, 'g');
 
    textGroup.setAttribute('transform', `translate(${x} ${y})`);
 
    //
    const textElement = _createTextElement(svgDrawingHelper, options);
    for (let i = 0; i < textLines.length; i++) {
      const textLine = textLines[i];
      const textSpan = _createTextSpan(textLine);
 
      textElement.appendChild(textSpan);
    }
 
    textGroup.appendChild(textElement);
    svgDrawingHelper.appendNode(textGroup, svgNodeHash);
    textGroupBoundingBox = _drawTextBackground(textGroup, background);
  }
 
  // We translate the group using `position`
  // which means we also need to pluck those values when returning
  // the bounding box
  return Object.assign({}, textGroupBoundingBox, {
    x,
    y,
    height: textGroupBoundingBox.height + padding,
    width: textGroupBoundingBox.width + padding,
  });
}
 
function _createTextElement(
  svgDrawingHelper: SVGDrawingHelper,
  options: any
): SVGElement {
  const { color, fontFamily, fontSize } = options;
  const svgns = 'http://www.w3.org/2000/svg';
  const textElement = document.createElementNS(svgns, 'text');
  const noSelectStyle =
    'user-select: none; pointer-events: none; -webkit-tap-highlight-color:  rgba(255, 255, 255, 0);';
  const dropShadowStyle = `filter:url(#shadow-${svgDrawingHelper.svgLayerElement.id});`;
  const combinedStyle = `${noSelectStyle}${dropShadowStyle}`;
 
  // font-size="100"
  textElement.setAttribute('x', '0');
  textElement.setAttribute('y', '0');
  textElement.setAttribute('fill', color);
  textElement.setAttribute('font-family', fontFamily);
  textElement.setAttribute('font-size', fontSize);
  textElement.setAttribute('style', combinedStyle);
 
  return textElement;
}
 
function _createTextSpan(text): SVGElement {
  const svgns = 'http://www.w3.org/2000/svg';
  const textSpanElement = document.createElementNS(svgns, 'tspan');
 
  // TODO: centerX
  // (parent width / 2) - my width
  // TODO: centerY
 
  textSpanElement.setAttribute('x', '0');
  textSpanElement.setAttribute('dy', '1.2em');
  textSpanElement.textContent = text;
 
  return textSpanElement;
}
 
function _drawTextBackground(group: SVGGElement, color: string) {
  let element = group.querySelector('rect.background');
 
  // If we have no background color, remove any element that exists and return
  // the bounding box of the text
  Eif (!color) {
    Iif (element) {
      group.removeChild(element);
    }
 
    return group.getBBox();
  }
 
  // Otherwise, check if we have a <rect> element. If not, create one
  if (!element) {
    element = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
    element.setAttribute('class', 'background');
    group.insertBefore(element, group.firstChild);
  }
 
  // Get the text groups's bounding box and use it to draw the background rectangle
  const bBox = group.getBBox();
 
  const attributes = {
    x: `${bBox.x}`,
    y: `${bBox.y}`,
    width: `${bBox.width}`,
    height: `${bBox.height}`,
    fill: color,
  };
 
  setAttributesIfNecessary(attributes, element);
 
  return bBox;
}
 
export default drawTextBox;