All files / packages/tools/src/store/SynchronizerManager Synchronizer.ts

79.67% Statements 98/123
69.81% Branches 37/53
77.14% Functions 27/35
78.81% Lines 93/118

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                                                3x                   3x 3x 3x 3x 3x 3x 3x 3x     3x               16x                                                                 4x 4x               5x       5x     5x   5x             5x   5x   5x 1x 1x       5x   5x                 5x       5x 5x                                       2x 2x                                 2x   2x       2x   2x     2x   2x 2x   1x     2x                   2x   2x       2x 2x             1x                   1x             15x       15x 15x 15x 15x 28x   28x   28x 13x   15x                   15x             15x         15x         3x 26x 11x               15x       15x   15x       15x       21x       15x                   16x       14x       14x 14x       14x 18x   18x       18x   18x       18x   18x       18x                 14x   14x   14x 24x 24x     12x       18x       14x             4x   4x                 12x   6x           2x 2x       2x        
import {
  getRenderingEngine,
  getEnabledElement,
  Enums,
  Types,
} from '@cornerstonejs/core';
 
import { ISynchronizerEventHandler } from '../../types';
 
/**
 * Synchronizer is a class that listens to a specific event on a specific source
 * targets and fires a specific event on a specific target elements. Use cases
 * include: synchronizing a camera between two viewports, synchronizing a
 * windowLevel between various viewports.
 */
class Synchronizer {
  //
  private _enabled: boolean;
  private _eventName: string;
  private _auxiliaryEventNames: string[];
  private _eventHandler: ISynchronizerEventHandler;
  private _ignoreFiredEvents: boolean;
  private _sourceViewports: Array<Types.IViewportId>;
  private _targetViewports: Array<Types.IViewportId>;
  private _viewportOptions: Record<string, Record<string, unknown>> = {};
  private _options: any;
  public id: string;
 
  constructor(
    synchronizerId: string,
    eventName: string,
    eventHandler: ISynchronizerEventHandler,
    options?: any
  ) {
    this._enabled = true;
    this._eventName = eventName;
    this._eventHandler = eventHandler;
    this._ignoreFiredEvents = false;
    this._sourceViewports = [];
    this._targetViewports = [];
    this._options = options || {};
    this._auxiliaryEventNames = this._options.auxiliaryEventNames || [];
 
    //
    this.id = synchronizerId;
  }
 
  /**
   * "Returns true if the synchronizer is disabled."
   * @returns A boolean value.
   */
  public isDisabled(): boolean {
    return !this._enabled || !this._hasSourceElements();
  }
 
  /**
   * Sets the options for the viewport id.  This can be used to
   * provide configuration on a viewport basis for things like offsets
   * to the general synchronization, or turn on/off synchronization of certain
   * attributes.
   */
  public setOptions(
    viewportId: string,
    options: Record<string, unknown> = {}
  ): void {
    this._viewportOptions[viewportId] = options;
  }
 
  /**
   * Sets a synchronizer enabled
   */
  public setEnabled(enabled: boolean) {
    this._enabled = enabled;
  }
 
  /** Gets the options for the given viewport id */
  public getOptions(viewportId: string): Record<string, unknown> | undefined {
    return this._viewportOptions[viewportId];
  }
 
  /**
   * Add a viewport to the list of targets and sources both.
   * @param viewportInfo - The viewportId and its renderingEngineId to add to the list of targets and sources.
   */
  public add(viewportInfo: Types.IViewportId): void {
    this.addTarget(viewportInfo);
    this.addSource(viewportInfo);
  }
 
  /**
   * Add a viewport to the list of sources (source ONLY)
   * @param viewportInfo - The viewportId and its renderingEngineId to add to the list of targets and sources.
   */
  public addSource(viewportInfo: Types.IViewportId): void {
    Iif (_containsViewport(this._sourceViewports, viewportInfo)) {
      return;
    }
 
    const { renderingEngineId, viewportId } = viewportInfo;
 
    const viewport =
      getRenderingEngine(renderingEngineId).getViewport(viewportId);
 
    Iif (!viewport) {
      console.warn(
        `Synchronizer.addSource: No viewport for ${renderingEngineId} ${viewportId}`
      );
      return;
    }
 
    const element = viewport.element;
 
    element.addEventListener(this._eventName, this._onEvent.bind(this));
 
    if (this._auxiliaryEventNames.length) {
      this._auxiliaryEventNames.forEach((eventName) => {
        element.addEventListener(eventName, this._onEvent.bind(this));
      });
    }
 
    this._updateDisableHandlers();
 
    this._sourceViewports.push(viewportInfo);
  }
 
  /**
   * Add a viewport to the list of viewports that will get the eventHandler
   * executed when the event is fired on the source viewport.
   * @param viewportInfo - The viewportId and its renderingEngineId to add to the list of targets and sources.
   */
  public addTarget(viewportInfo: Types.IViewportId): void {
    Iif (_containsViewport(this._targetViewports, viewportInfo)) {
      return;
    }
 
    this._targetViewports.push(viewportInfo);
    this._updateDisableHandlers();
  }
 
  /**
   * Get the list of source viewports (as {viewportId, renderingEngineId} objects)
   * @returns An array of {viewportId, renderingEngineId} objects.
   */
  public getSourceViewports(): Array<Types.IViewportId> {
    return this._sourceViewports;
  }
 
  /**
   * Get the list of target viewports (as {viewportId, renderingEngineId} objects)
   * @returns An array of {viewportId, renderingEngineId} objects.
   */
  public getTargetViewports(): Array<Types.IViewportId> {
    return this._targetViewports;
  }
 
  public destroy(): void {
    this._sourceViewports.forEach((s) => this.removeSource(s));
    this._targetViewports.forEach((t) => this.removeTarget(t));
  }
 
  /**
   * Remove the viewport from the list of targets and sources
   * @param viewportInfo - The viewport info including viewportId and renderingEngineId.
   */
  public remove(viewportInfo: Types.IViewportId): void {
    this.removeTarget(viewportInfo);
    this.removeSource(viewportInfo);
  }
 
  /**
   * Remove the viewport from the list of source viewports
   * @param viewportInfo - The viewport info including viewportId and renderingEngineId.
   */
  public removeSource(viewportInfo: Types.IViewportId): void {
    const index = _getViewportIndex(this._sourceViewports, viewportInfo);
 
    Iif (index === -1) {
      return;
    }
 
    const element = _getViewportElement(viewportInfo);
 
    this._sourceViewports.splice(index, 1);
 
    //@ts-ignore
    element.removeEventListener(this._eventName, this._eventHandler);
 
    Eif (this._auxiliaryEventNames) {
      this._auxiliaryEventNames.forEach((eventName) => {
        //@ts-ignore
        element.removeEventListener(eventName, this._eventHandler);
      });
    }
    this._updateDisableHandlers();
  }
 
  /**
   * Remove the viewport from the list of viewports that are currently targeted by
   * this handler
   * @param viewportInfo - The viewport info including viewportId and renderingEngineId.
   *
   */
  public removeTarget(viewportInfo: Types.IViewportId): void {
    const index = _getViewportIndex(this._targetViewports, viewportInfo);
 
    Iif (index === -1) {
      return;
    }
 
    this._targetViewports.splice(index, 1);
    this._updateDisableHandlers();
  }
 
  public hasSourceViewport(
    renderingEngineId: string,
    viewportId: string
  ): boolean {
    return _containsViewport(this._sourceViewports, {
      renderingEngineId,
      viewportId,
    });
  }
 
  public hasTargetViewport(
    renderingEngineId: string,
    viewportId: string
  ): boolean {
    return _containsViewport(this._targetViewports, {
      renderingEngineId,
      viewportId,
    });
  }
 
  private fireEvent(sourceViewport: Types.IViewportId, sourceEvent: any): void {
    Iif (this.isDisabled() || this._ignoreFiredEvents) {
      return;
    }
 
    this._ignoreFiredEvents = true;
    const promises = [];
    try {
      for (let i = 0; i < this._targetViewports.length; i++) {
        const targetViewport = this._targetViewports[i];
        const targetIsSource =
          sourceViewport.viewportId === targetViewport.viewportId;
 
        if (targetIsSource) {
          continue;
        }
        const result = this._eventHandler(
          this,
          sourceViewport,
          targetViewport,
          sourceEvent,
          this._options
        );
 
        // if the result is a promise, then add it to the list of promises
        // to wait for before setting _ignoreFiredEvents to false
        Iif (result instanceof Promise) {
          promises.push(result);
        }
      }
    } catch (ex) {
      console.warn(`Synchronizer, for: ${this._eventName}`, ex);
    } finally {
      Iif (promises.length) {
        Promise.allSettled(promises).then(() => {
          this._ignoreFiredEvents = false;
        });
      } else {
        this._ignoreFiredEvents = false;
      }
    }
  }
 
  private _onEvent = (evt: any): void => {
    if (this._ignoreFiredEvents === true) {
      return;
    }
 
    // If no target viewports, then return immediately, this is useful
    // when switching between layouts, when previous layout has disabled
    // its viewports, and the new layout has not yet enabled them.
    // Right now we don't "delete" the synchronizer if all source and targets
    // are removed, but we may want to do that in the future.
    Iif (!this._targetViewports.length) {
      return;
    }
 
    const enabledElement = getEnabledElement(evt.currentTarget);
 
    Iif (!enabledElement) {
      return;
    }
 
    const { renderingEngineId, viewportId } = enabledElement;
 
    // If the viewport has been removed from the synchronizer before the event is
    // fired, then return immediately.
    Iif (!this._sourceViewports.find((s) => s.viewportId === viewportId)) {
      return;
    }
 
    this.fireEvent(
      {
        renderingEngineId,
        viewportId,
      },
      evt
    );
  };
 
  private _hasSourceElements(): boolean {
    return this._sourceViewports.length !== 0;
  }
 
  private _updateDisableHandlers(): void {
    const viewports = _getUniqueViewports(
      this._sourceViewports,
      this._targetViewports
    );
    const _remove = this.remove;
    const disableHandler = (elementDisabledEvent) => {
      _remove(elementDisabledEvent.detail.element);
    };
 
    viewports.forEach(function (vUid) {
      const renderingEngine = getRenderingEngine(vUid.renderingEngineId);
 
      Iif (!renderingEngine) {
        return;
      }
 
      const viewport = renderingEngine.getViewport(vUid.viewportId);
 
      Iif (!viewport) {
        return;
      }
 
      const { element } = viewport;
 
      element.removeEventListener(
        Enums.Events.ELEMENT_DISABLED,
        disableHandler
      );
      element.addEventListener(Enums.Events.ELEMENT_DISABLED, disableHandler);
    });
  }
}
 
function _getUniqueViewports(
  vp1: Array<Types.IViewportId>,
  vp2: Array<Types.IViewportId>
): Array<Types.IViewportId> {
  const unique = [];
 
  const vps = vp1.concat(vp2);
 
  for (let i = 0; i < vps.length; i++) {
    const vp = vps[i];
    if (
      !unique.some(
        (u) =>
          vp.renderingEngineId === u.renderingEngineId &&
          vp.viewportId === u.viewportId
      )
    ) {
      unique.push(vp);
    }
  }
 
  return unique;
}
 
function _getViewportIndex(
  arr: Array<Types.IViewportId>,
  vp: Types.IViewportId
): number {
  return arr.findIndex(
    (ar) =>
      vp.renderingEngineId === ar.renderingEngineId &&
      vp.viewportId === ar.viewportId
  );
}
 
function _containsViewport(
  arr: Array<Types.IViewportId>,
  vp: Types.IViewportId
) {
  return arr.some(
    (ar) =>
      ar.renderingEngineId === vp.renderingEngineId &&
      ar.viewportId === vp.viewportId
  );
}
 
function _getViewportElement(vp: Types.IViewportId): HTMLDivElement {
  const renderingEngine = getRenderingEngine(vp.renderingEngineId);
  Iif (!renderingEngine) {
    throw new Error(`No RenderingEngine for Id: ${vp.renderingEngineId}`);
  }
 
  return renderingEngine.getViewport(vp.viewportId).element;
}
 
export default Synchronizer;