All files / packages/tools/src/utilities triggerAnnotationRender.ts

95.38% Statements 62/65
86.36% Branches 19/22
100% Functions 16/16
95.16% Lines 59/62

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 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238                  1x                                         8x 1x                     96x               4x     4x           4x                   495x               131x               131x   131x   131x 578x 578x 176x     176x       176x 131x 131x 131x           4x 4x   4x 18x     4x     495x 495x     495x   495x 495x         495x                 495x 127x         127x         176x   176x 36x 36x     140x     140x         140x           140x 140x                     140x 140x 140x 172x 125x       125x                   140x   140x 82x                 4x   4x 4x 4x   4x       1x               495x            
import {
  getEnabledElement,
  triggerEvent,
  getRenderingEngine,
} from '@cornerstonejs/core';
import { Events, ToolModes } from '../enums';
import { draw as drawSvg } from '../drawingSvg';
import getToolsWithModesForElement from './getToolsWithModesForElement';
import { AnnotationRenderedEventDetail } from '../types/EventTypes';
const { Active, Passive, Enabled } = ToolModes;
 
/**
 * AnnotationRenderingEngine is a class that is responsible for rendering
 * annotations defined in the renderAnnotation method of annotation tools on the page.
 * It mimics the RenderingEngine in the Cornerstone Core. Here it uses requestAnimationFrame
 * is used to render annotations by calling renderAnnotations() on each enabled tool. Note: This
 * is a Singleton class and should not be instantiated directly. To trigger
 * an annotation render for an HTML element containing a viewport you can use
 *
 * ```
 * triggerAnnotationRender(element)
 * ```
 */
class AnnotationRenderingEngine {
  public hasBeenDestroyed: boolean;
  private _needsRender: Set<HTMLDivElement> = new Set();
  private _animationFrameSet = false;
  private _animationFrameHandle: number | null = null;
  private _viewportElements: Map<string, HTMLDivElement>;
 
  constructor() {
    this._viewportElements = new Map();
  }
 
  /**
   * Add the viewport's HTMLDivElement to the viewports for rendering. This method
   * just informs the annotationRenderingEngine about the viewport and
   * does not initiate a render.
   * @param viewportId - Viewport Unique identifier
   * @param element - HTMLDivElement
   */
  public addViewportElement(viewportId: string, element: HTMLDivElement) {
    this._viewportElements.set(viewportId, element);
  }
 
  /**
   * Remove the viewport's HTMLDivElement from subsequent annotation renders
   * @param viewportId - Viewport Unique identifier
   */
  public removeViewportElement(viewportId: string, element: HTMLDivElement) {
    this._viewportElements.delete(viewportId);
 
    // delete element from needsRender if element exist
    this._needsRender.delete(element);
 
    // I don' think there is any disadvantage to canceling the animation frame
    // and resetting the flags on viewport's element removal, since the removeVIewportElement
    // might be as a result of reEnabling the element (in re-enable we disable first), hence the need to render the
    // new one while removing the old one
    this._reset();
  }
 
  /**
   * It tells the AnnotationRenderingEngine to render the viewport element the next
   * time it renders.
   *
   * @param element - The element to render.
   */
  public renderViewport(element: HTMLDivElement): void {
    this._setViewportsToBeRenderedNextFrame([element]);
  }
 
  /**
   * _throwIfDestroyed Throws an error if trying to interact with the `RenderingEngine`
   * instance after its `destroy` method has been called.
   */
  private _throwIfDestroyed() {
    Iif (this.hasBeenDestroyed) {
      throw new Error(
        'this.destroy() has been manually called to free up memory, can not longer use this instance. Instead make a new one.'
      );
    }
  }
 
  private _renderFlaggedViewports = () => {
    this._throwIfDestroyed();
 
    const elements = Array.from(this._viewportElements.values());
 
    for (let i = 0; i < elements.length; i++) {
      const element = elements[i];
      if (this._needsRender.has(element)) {
        this._triggerRender(element);
 
        // This viewport has been rendered, we can remove it from the set
        this._needsRender.delete(element);
 
        // If there is nothing left that is flagged for rendering, stop here
        // and allow RAF to be called again
        if (this._needsRender.size === 0) {
          this._animationFrameSet = false;
          this._animationFrameHandle = null;
          return;
        }
      }
    }
  };
 
  private _setAllViewportsToBeRenderedNextFrame() {
    const elements = [...this._viewportElements.values()];
 
    elements.forEach((element) => {
      this._needsRender.add(element);
    });
 
    this._renderFlaggedViewports();
  }
 
  private _setViewportsToBeRenderedNextFrame(elements: HTMLDivElement[]) {
    const elementsEnabled = [...this._viewportElements.values()];
 
    // Add the viewports to the set of flagged viewports
    elements.forEach((element) => {
      // only enabledElement need to render
      Eif (elementsEnabled.indexOf(element) !== -1) {
        this._needsRender.add(element);
      }
    });
 
    // Render any flagged viewports
    this._render();
  }
 
  /**
   * _render Sets up animation frame if necessary
   */
  private _render() {
    // If we have viewports that need rendering and we have not already
    // set the RAF callback to run on the next frame.
    if (this._needsRender.size > 0 && this._animationFrameSet === false) {
      this._animationFrameHandle = window.requestAnimationFrame(
        this._renderFlaggedViewports
      );
 
      // Set the flag that we have already set up the next RAF call.
      this._animationFrameSet = true;
    }
  }
 
  _triggerRender(element) {
    const enabledElement = getEnabledElement(element);
 
    if (!enabledElement) {
      console.warn('Element has been disabled');
      return;
    }
 
    const renderingEngine = getRenderingEngine(
      enabledElement.renderingEngineId
    );
    Iif (!renderingEngine) {
      console.warn('rendering Engine has been destroyed');
      return;
    }
 
    const enabledTools = getToolsWithModesForElement(element, [
      Active,
      Passive,
      Enabled,
    ]);
 
    const { renderingEngineId, viewportId } = enabledElement;
    const eventDetail: AnnotationRenderedEventDetail = {
      element,
      renderingEngineId,
      viewportId,
    };
 
    // const enabledToolsWithAnnotations = enabledTools.filter((tool) => {
    //   const annotations = getAnnotations(element, tool.getToolName());
    //   return annotations && annotations.length;
    // });
 
    drawSvg(element, (svgDrawingHelper) => {
      let anyRendered = false;
      const handleDrawSvg = (tool) => {
        if (tool.renderAnnotation) {
          const rendered = tool.renderAnnotation(
            enabledElement,
            svgDrawingHelper
          );
          anyRendered = anyRendered || rendered;
        }
      };
 
      /**
       * We should be able to filter tools that don't have annotations, but
       * currently some of tools have renderAnnotation method BUT
       * don't keep annotation in the state, so if we do so, the tool will not be
       * rendered.
       */
      enabledTools.forEach(handleDrawSvg);
 
      if (anyRendered) {
        triggerEvent(element, Events.ANNOTATION_RENDERED, { ...eventDetail });
      }
    });
  }
 
  /**
   * _reset Resets the `RenderingEngine`
   */
  private _reset() {
    window.cancelAnimationFrame(this._animationFrameHandle);
 
    this._needsRender.clear();
    this._animationFrameSet = false;
    this._animationFrameHandle = null;
 
    this._setAllViewportsToBeRenderedNextFrame();
  }
}
 
const annotationRenderingEngine = new AnnotationRenderingEngine();
 
/**
 * It triggers the rendering of the annotations for the given HTML element using
 * the `AnnotationRenderingEngine`
 * @param element - The element to render the annotation on.
 */
function triggerAnnotationRender(element: HTMLDivElement): void {
  annotationRenderingEngine.renderViewport(element);
}
 
export { annotationRenderingEngine, triggerAnnotationRender };
 
export default triggerAnnotationRender;