All files / extensions/cornerstone/src/hooks useViewportSegmentations.ts

87.69% Statements 57/65
65% Branches 13/20
91.66% Functions 11/12
88.7% Lines 55/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                34x     175x     175x       11654x 11654x   11654x 48597x 48597x 48597x   48597x 42770x     5827x   5827x       5827x   5827x               11654x       175x 5827x           5827x 5827x 5827x     5827x     175x   175x 5827x             175x                                                                     202x   202x     202x         202x 36x 241x   241x 2x     239x   239x       239x               239x   239x 33x       33x     206x   206x 175x 175x 175x           206x             36x   36x   36x                                       36x                 36x 65x 13x                           202x    
import { useState, useEffect } from 'react';
import debounce from 'lodash.debounce';
import { roundNumber } from '@ohif/core/src/utils';
import {
  SegmentationData,
  SegmentationRepresentation,
} from '../services/SegmentationService/SegmentationService';
import { useSystem } from '@ohif/core';
const excludedModalities = ['SM', 'OT', 'DOC', 'ECG'];
 
function mapSegmentationToDisplay(segmentation, customizationService) {
  const { label, segments } = segmentation;
 
  // Get the readable text mapping once
  const readableTextMap = customizationService.getCustomization('panelSegmentation.readableText');
 
  // Helper function to recursively map cachedStats to readable display text
  function mapStatsToDisplay(stats, indent = 0) {
    const primary = [];
    const indentation = '  '.repeat(indent);
 
    for (const key in stats) {
      if (Object.prototype.hasOwnProperty.call(stats, key)) {
        const value = stats[key];
        const readableText = readableTextMap?.[key];
 
        if (!readableText) {
          continue;
        }
 
        if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
          // Add empty row before category (except for the first category)
          Iif (primary.length > 0) {
            primary.push('');
          }
          // Add category title
          primary.push(`${indentation}${readableText}`);
          // Recursively handle nested objects
          primary.push(...mapStatsToDisplay(value, indent + 1));
        } else E{
          // For non-nested values, don't add empty rows
          primary.push(`${indentation}${readableText}: ${roundNumber(value, 2)}`);
        }
      }
    }
 
    return primary;
  }
 
  // Get customization for display text mapping
  const displayTextMapper = segment => {
    const defaultDisplay = {
      primary: [],
      secondary: [],
    };
 
    // If the segment has cachedStats, map it to readable text
    if (segment.cachedStats) {
      const primary = mapStatsToDisplay(segment.cachedStats);
      defaultDisplay.primary = primary;
    }
 
    return defaultDisplay;
  };
 
  const updatedSegments = {};
 
  Object.entries(segments).forEach(([segmentIndex, segment]) => {
    updatedSegments[segmentIndex] = {
      ...segment,
      displayText: displayTextMapper(segment),
    };
  });
 
  // Map the segments and apply the display text mapper
  return {
    ...segmentation,
    label,
    segments: updatedSegments,
  };
}
 
/**
 * Represents the combination of segmentation data and its representation in a viewport.
 */
type ViewportSegmentationRepresentation = {
  segmentationsWithRepresentations: {
    representation: SegmentationRepresentation;
    segmentation: SegmentationData;
  }[];
  disabled: boolean;
};
 
/**
 * Custom hook that provides segmentation data and their representations for the active viewport.
 * @param options - The options object.
 * @param options.servicesManager - The services manager object.
 * @param options.subscribeToDataModified - Whether to subscribe to segmentation data modifications.
 * @param options.debounceTime - Debounce time in milliseconds for updates.
 * @returns An array of segmentation data and their representations for the active viewport.
 */
export function useViewportSegmentations({
  viewportId,
  subscribeToDataModified = false,
  debounceTime = 0,
}: {
  viewportId: string;
  subscribeToDataModified?: boolean;
  debounceTime?: number;
}): ViewportSegmentationRepresentation {
  const { servicesManager } = useSystem();
  const { segmentationService, viewportGridService, customizationService, displaySetService } =
    servicesManager.services;
 
  const [segmentationsWithRepresentations, setSegmentationsWithRepresentations] =
    useState<ViewportSegmentationRepresentation>({
      segmentationsWithRepresentations: [],
      disabled: false,
    });
 
  useEffect(() => {
    const update = () => {
      const displaySetUIDs = viewportGridService.getDisplaySetsUIDsForViewport(viewportId);
 
      if (!displaySetUIDs?.length) {
        return;
      }
 
      const displaySet = displaySetService.getDisplaySetByUID(displaySetUIDs[0]);
 
      Iif (!displaySet) {
        return;
      }
 
      Iif (excludedModalities.includes(displaySet.Modality)) {
        setSegmentationsWithRepresentations(prev => ({
          segmentationsWithRepresentations: [],
          disabled: true,
        }));
        return;
      }
 
      const segmentations = segmentationService.getSegmentations();
 
      if (!segmentations?.length) {
        setSegmentationsWithRepresentations(prev => ({
          segmentationsWithRepresentations: [],
          disabled: false,
        }));
        return;
      }
 
      const representations = segmentationService.getSegmentationRepresentations(viewportId);
 
      const newSegmentationsWithRepresentations = representations.map(representation => {
        const segmentation = segmentationService.getSegmentation(representation.segmentationId);
        const mappedSegmentation = mapSegmentationToDisplay(segmentation, customizationService);
        return {
          representation,
          segmentation: mappedSegmentation,
        };
      });
 
      setSegmentationsWithRepresentations({
        segmentationsWithRepresentations: newSegmentationsWithRepresentations,
        disabled: false,
      });
    };
 
    const debouncedUpdate =
      debounceTime > 0 ? debounce(update, debounceTime, { leading: true, trailing: true }) : update;
 
    update();
 
    const subscriptions = [
      segmentationService.subscribe(
        segmentationService.EVENTS.SEGMENTATION_MODIFIED,
        debouncedUpdate
      ),
      segmentationService.subscribe(
        segmentationService.EVENTS.SEGMENTATION_REMOVED,
        debouncedUpdate
      ),
      segmentationService.subscribe(
        segmentationService.EVENTS.SEGMENTATION_REPRESENTATION_MODIFIED,
        debouncedUpdate
      ),
      viewportGridService.subscribe(
        viewportGridService.EVENTS.ACTIVE_VIEWPORT_ID_CHANGED,
        debouncedUpdate
      ),
      viewportGridService.subscribe(viewportGridService.EVENTS.GRID_STATE_CHANGED, debouncedUpdate),
    ];
 
    Iif (subscribeToDataModified) {
      subscriptions.push(
        segmentationService.subscribe(
          segmentationService.EVENTS.SEGMENTATION_DATA_MODIFIED,
          debouncedUpdate
        )
      );
    }
 
    return () => {
      subscriptions.forEach(subscription => subscription.unsubscribe());
      Iif (debounceTime > 0) {
        debouncedUpdate.cancel();
      }
    };
  }, [
    segmentationService,
    viewportGridService,
    customizationService,
    displaySetService,
    debounceTime,
    subscribeToDataModified,
    viewportId,
  ]);
 
  return segmentationsWithRepresentations;
}