All files / packages/tools/src/stateManagement/annotation FrameOfReferenceSpecificAnnotationManager.ts

69.53% Statements 89/128
66.66% Branches 36/54
63.15% Functions 12/19
69.53% Lines 89/128

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 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 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414                                                                              1x     1x 1x     1x                             1x 523x       523x 523x   523x           523x                   1x                                                               1x 1x                         1x       423x   423x 90x     333x 332x         1x                   1x 432x   432x 422x   422x 422x   422x 448x 414x                                 1x                                                   1x 107x 107x   107x   107x   107x   107x 78x   78x     107x   107x 79x   79x     107x 107x 107x                 1x 80x   80x 80x   80x 80x   80x 86x     80x 80x   80x 69x         80x 69x                       1x                                           1x       8x   8x 1x   1x         1x   1x 7x 1x   1x     6x                             1x         112x   112x     1x   1x 1x   1x     1x 111x     1x     110x             1x 6x   6x                   1x                                 1x           1x        
import cloneDeep from 'lodash.clonedeep';
import {
  Annotation,
  Annotations,
  AnnotationState,
  GroupSpecificAnnotations,
} from '../../types/AnnotationTypes';
 
import { AnnotationGroupSelector, IAnnotationManager } from '../../types';
 
import {
  Enums,
  eventTarget,
  getEnabledElement,
  Types,
  utilities,
} from '@cornerstonejs/core';
 
import { checkAndDefineIsLockedProperty } from './annotationLocking';
import { checkAndDefineIsVisibleProperty } from './annotationVisibility';
 
/**
 * This is the default annotation manager. It stores annotations by default
 * based on the FrameOfReferenceUID. However, it is possible to override the
 * getAnnotationStateKey function to store annotations based on any other
 * property of the element. When you write your custom annotation manager, you
 * can use the setAnnotationManager function to set your custom annotation.
 *
 * Note that this class is a singleton and should not be instantiated directly.
 * To get the stored annotations information you can use ToolState helpers.
 */
class FrameOfReferenceSpecificAnnotationManager implements IAnnotationManager {
  private annotations: AnnotationState;
  public readonly uid: string;
 
  /**
   * @param uid - The uid of the state manager. If omitted it is autogenerated.
   */
  constructor(uid?: string) {
    Iif (!uid) {
      uid = utilities.uuidv4();
    }
    this.annotations = {};
    this.uid = uid;
 
    // Listen to the IMAGE_VOLUME_MODIFIED event to invalidate data.
    eventTarget.addEventListener(
      Enums.Events.IMAGE_VOLUME_MODIFIED,
      this._imageVolumeModifiedHandler
    );
  }
 
  /**
   * Default annotation manager works with FrameOfReferenceUID as the key. The
   * manager adds them under the FrameOfReferenceUID for the element being
   * annotated.
   *
   * @param annotationGroupSelector - element or a string that is provided
   * to the annotation manager to get the key.
   * @returns - The annotation state key for the element.
   */
  getGroupKey = (annotationGroupSelector: AnnotationGroupSelector): string => {
    Iif (typeof annotationGroupSelector === 'string') {
      return annotationGroupSelector;
    }
 
    const element = annotationGroupSelector;
    const enabledElement = getEnabledElement(element);
 
    Iif (!enabledElement) {
      throw new Error(
        'Element not enabled, you must have an enabled element if you are not providing a FrameOfReferenceUID'
      );
    }
 
    return enabledElement.FrameOfReferenceUID;
  };
 
  /**
   * When a volume is modified we invalidate all of the `annotations` on the
   * volume's `FrameOfReferenceUID`. This is mainly to update statistics calculations
   * when an annotation is drawn whilst data is still loading.
   *
   * @param evt - The IMAGE_VOLUME_MODIFIED rendering event.
   */
  _imageVolumeModifiedHandler = (
    evt: Types.EventTypes.ImageVolumeModifiedEvent
  ) => {
    const eventDetail = evt.detail;
    const { FrameOfReferenceUID } = eventDetail;
 
    const annotations = this.annotations;
    const frameOfReferenceSpecificAnnotations =
      annotations[FrameOfReferenceUID];
 
    if (!frameOfReferenceSpecificAnnotations) {
      return;
    }
 
    Object.keys(frameOfReferenceSpecificAnnotations).forEach((toolName) => {
      const toolSpecificAnnotations =
        frameOfReferenceSpecificAnnotations[toolName];
 
      toolSpecificAnnotations.forEach((annotation) => {
        const invalidated = annotation.invalidated;
 
        if (invalidated !== undefined) {
          annotation.invalidated = true;
        }
      });
    });
  };
 
  /**
   * Returns all the available frameOfReferences inside the state manager
   * @returns - All the added frames of references inside the manager
   */
  getFramesOfReference = (): Array<string> => {
    return Object.keys(this.annotations);
  };
 
  /**
   * Returns the annotations associated with the specified frameOfReference and tool, or
   * all annotations for the group if the tool name is not provided.
   *
   * @param groupKey - The annotation group key to retrieve annotations for (in default manager it is FrameOfReferenceUID).
   * @param toolName - Optional. The name of the tool to retrieve annotations for.
   * @returns The annotations associated with the specified group (default FrameOfReferenceUID) and tool,
   * or all annotations for the group (FrameOfReferenceUID) if the tool name is not provided.
   * WARNING: The list returned here is internal tool data, not a copy, so do NOT modify it.
   */
  getAnnotations = (
    groupKey: string,
    toolName?: string
  ): GroupSpecificAnnotations | Annotations => {
    const annotations = this.annotations;
 
    if (!annotations[groupKey]) {
      return [];
    }
 
    if (toolName) {
      return annotations[groupKey][toolName]
        ? annotations[groupKey][toolName]
        : [];
    }
 
    return annotations[groupKey];
  };
 
  /**
   * Given the unique identified for the some `annotation`, returns the `annotation`
   * from the `annotations`. Each `annotation` has a unique identifier.
   *
   * @param annotationUID - The unique identifier of the `annotation`.
   * @returns The retrieved `annotation`.
   */
  getAnnotation = (annotationUID: string): Annotation | undefined => {
    const annotations = this.annotations;
 
    for (const frameOfReferenceUID in annotations) {
      const frameOfReferenceAnnotations = annotations[frameOfReferenceUID];
 
      for (const toolName in frameOfReferenceAnnotations) {
        const toolSpecificAnnotations = frameOfReferenceAnnotations[toolName];
 
        for (const annotation of toolSpecificAnnotations) {
          if (annotationUID === annotation.annotationUID) {
            return annotation;
          }
        }
      }
    }
  };
 
  /**
   * A function that returns the number of annotations for a given tool in the
   * specific group (default FrameOfReferenceUID) IF no groupKey (FrameOfReferenceUID) is provided,
   * it will return the number of annotations for the tool in all groups (FrameOfReferenceUIDs)
   *
   * @param groupKey - The annotation group key to retrieve annotations for (in default manager it is FrameOfReferenceUID).
   * @param toolName - The name of the tool to retrieve data for.
   *
   * @returns The number of annotations for a given tool in the state
   */
  getNumberOfAnnotations = (groupKey: string, toolName?: string): number => {
    const annotations = this.getAnnotations(groupKey, toolName);
 
    if (!annotations.length) {
      return 0;
    }
 
    if (toolName) {
      return (annotations as Annotations).length;
    }
 
    let total = 0;
 
    for (const toolName in annotations) {
      total += annotations[toolName].length;
    }
 
    return total;
  };
 
  /**
   * Adds an instance of `Annotation` to the `annotations`.
   *
   * @param annotation - The annotation to add.
   * @param groupKey - The annotation group key to add the annotation to (in default manager it is FrameOfReferenceUID).
   */
  addAnnotation = (annotation: Annotation, groupKey?: string): void => {
    const { metadata } = annotation;
    const { FrameOfReferenceUID, toolName } = metadata;
 
    groupKey = groupKey || FrameOfReferenceUID;
 
    const annotations = this.annotations;
 
    let frameOfReferenceSpecificAnnotations = annotations[groupKey];
 
    if (!frameOfReferenceSpecificAnnotations) {
      annotations[groupKey] = {};
 
      frameOfReferenceSpecificAnnotations = annotations[groupKey];
    }
 
    let toolSpecificAnnotations = frameOfReferenceSpecificAnnotations[toolName];
 
    if (!toolSpecificAnnotations) {
      frameOfReferenceSpecificAnnotations[toolName] = [];
 
      toolSpecificAnnotations = frameOfReferenceSpecificAnnotations[toolName];
    }
 
    toolSpecificAnnotations.push(annotation);
    checkAndDefineIsLockedProperty(annotation);
    checkAndDefineIsVisibleProperty(annotation);
  };
 
  /**
   * Given the unique identified for the some `annotation`, removes the `annotation`
   * from the `annotations`.
   *
   * @param annotationUID - The unique identifier of the `annotation` to remove.
   */
  removeAnnotation = (annotationUID: string): void => {
    const { annotations } = this;
 
    for (const groupKey in annotations) {
      const groupAnnotations = annotations[groupKey];
 
      for (const toolName in groupAnnotations) {
        const toolAnnotations = groupAnnotations[toolName];
 
        const index = toolAnnotations.findIndex(
          (annotation) => annotation.annotationUID === annotationUID
        );
 
        Eif (index !== -1) {
          toolAnnotations.splice(index, 1);
 
          if (toolAnnotations.length === 0) {
            delete groupAnnotations[toolName];
          }
        }
      }
 
      if (Object.keys(groupAnnotations).length === 0) {
        delete annotations[groupKey];
      }
    }
  };
 
  /**
   * Removes all annotations associated with the specified group (FrameOfReferenceUID) and tool, or
   * all annotations for the group (FrameOfReferenceUID) if the tool name is not provided.
   *
   * @param groupKey - The group key to remove annotations for (in default manager it is FrameOfReferenceUID).
   * @param toolName - Optional. The name of the tool to remove annotations for.
   */
  removeAnnotations = (groupKey: string, toolName?: string): void => {
    const annotations = this.annotations;
    if (annotations[groupKey]) {
      if (toolName) {
        delete annotations[groupKey][toolName];
      } else {
        delete annotations[groupKey];
      }
    }
  };
 
  /**
   * Returns a section of the annotations. Useful for serialization.
   * If both groupKey (default manager is FrameOfReferenceUID) and toolName are provided, returns the corresponding Annotations instance
   * for that groupKey (FrameOfReferenceUID) and toolName.
   * If only groupKey is provided, returns the corresponding FrameOfReferenceSpecificAnnotations instance
   * for that groupKey.
   * If neither groupKey nor toolName is provided, returns the entire AnnotationState object.
   * @param groupKey - Optional. The group key (e.g. FrameOfReferenceUID) to retrieve annotations for.
   * @param toolName - Optional. The name of the tool to retrieve annotations for.
   * @returns A section of the annotations.
   */
  saveAnnotations = (
    groupKey?: string,
    toolName?: string
  ): AnnotationState | GroupSpecificAnnotations | Annotations => {
    const annotations = this.annotations;
 
    if (groupKey && toolName) {
      const frameOfReferenceSpecificAnnotations = annotations[groupKey];
 
      Iif (!frameOfReferenceSpecificAnnotations) {
        return;
      }
 
      const toolSpecificAnnotations =
        frameOfReferenceSpecificAnnotations[toolName];
 
      return cloneDeep(toolSpecificAnnotations);
    } else if (groupKey) {
      const frameOfReferenceSpecificAnnotations = annotations[groupKey];
 
      return cloneDeep(frameOfReferenceSpecificAnnotations);
    }
 
    return cloneDeep(annotations);
  };
 
  /**
   * Restores a section of the `annotations`. Useful for loading in serialized data.
   *
   * - If no arguments are given, the entire `AnnotationState` instance is restored.
   * - If the `FrameOfReferenceUID` is given, the corresponding
   * `FrameOfReferenceSpecificAnnotations` instance is restored.
   * - If both the `FrameOfReferenceUID` and the `toolName` are are given, the
   * corresponding `Annotations` instance is restored.
   *
   * @param groupKey - A filter string for restoring only the `annotations` of a specific frame of reference.
   * @param toolName - A filter string for restoring `annotation` for a specific tool on a specific frame of reference.
   */
  restoreAnnotations = (
    state: AnnotationState | GroupSpecificAnnotations | Annotations,
    groupKey?: string,
    toolName?: string
  ): void => {
    const annotations = this.annotations;
 
    if (groupKey && toolName) {
      // Set Annotations for FrameOfReferenceUID and toolName.
 
      let frameOfReferenceSpecificAnnotations = annotations[groupKey];
 
      Eif (!frameOfReferenceSpecificAnnotations) {
        annotations[groupKey] = {};
 
        frameOfReferenceSpecificAnnotations = annotations[groupKey];
      }
 
      frameOfReferenceSpecificAnnotations[toolName] = <Annotations>state;
    } else if (groupKey) {
      // Set FrameOfReferenceSpecificAnnotations for FrameOfReferenceUID.
 
      annotations[groupKey] = <GroupSpecificAnnotations>state;
    } else {
      // Set entire annotations
      this.annotations = <AnnotationState>cloneDeep(state);
    }
  };
 
  /**
   * return all annotations as a single array
   */
  getAllAnnotations = (): Annotations => {
    return Object.values(this.annotations)
      .map((frameOfReferenceSpecificAnnotations) =>
        Object.values(frameOfReferenceSpecificAnnotations)
      )
      .flat(2);
  };
 
  /**
   * A function that returns the number of all annotations in the annotation state
   *
   * @returns The number of all annotations in the state
   */
  getNumberOfAllAnnotations = (): number => {
    let count = 0;
    const annotations = this.annotations;
    for (const groupKey in annotations) {
      const frameOfReferenceSpecificAnnotations = annotations[groupKey];
      for (const toolName in frameOfReferenceSpecificAnnotations) {
        const toolSpecificAnnotations =
          frameOfReferenceSpecificAnnotations[toolName];
        count += toolSpecificAnnotations.length;
      }
    }
    return count;
  };
 
  /**
   * Removes all annotations in the annotation state.
   */
  removeAllAnnotations = (): void => {
    this.annotations = {};
  };
}
 
const defaultFrameOfReferenceSpecificAnnotationManager =
  new FrameOfReferenceSpecificAnnotationManager('DEFAULT');
 
export { defaultFrameOfReferenceSpecificAnnotationManager };
export default FrameOfReferenceSpecificAnnotationManager;