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

85.96% Statements 49/57
86.36% Branches 19/22
92.85% Functions 13/14
85.18% Lines 46/54

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                  1x                                         8x 1x                     96x               4x     4x                       495x               102x               102x   102x   102x 454x 454x 129x     129x       129x 102x 102x 102x           495x   495x 495x       495x                 495x 102x         102x         129x   129x 16x 16x     113x     113x         113x           113x 113x                     113x 113x 113x 145x 100x       100x                   113x   113x 68x                                 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) {
    this._viewportElements.delete(viewportId);
 
    // Reset the request animation frame if no enabled elements
    Iif (this._viewportElements.size === 0) {
      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 _setViewportsToBeRenderedNextFrame(elements: HTMLDivElement[]) {
    // Add the viewports to the set of flagged viewports
    elements.forEach((element) => {
      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;
  }
}
 
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;