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

88.4% Statements 61/69
66.66% Branches 14/21
92.3% Functions 12/13
89.39% Lines 59/66

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                204x     7572x     7572x       101734x 101734x   101734x 253827x 253827x 253827x   253827x 203709x     50118x   50118x       50118x   50118x               101734x       7572x 51616x           51616x 51616x 51616x     51616x     7572x   7572x 51616x             7572x                                                                       5556x   5556x     5556x         5556x 594x 7966x   7966x 230x     7736x   7736x       7736x               7736x   7736x 439x       439x     7297x         7297x 7297x 7572x 7572x       7297x   7572x 7572x 7572x             7297x             594x   594x   594x                                                             594x                 594x 1908x 318x                           5556x    
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, fallbackLabel } = 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,
    fallbackLabel,
    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);
 
      // Deduplicate representations by segmentationId to prevent showing
      // the same segmentation multiple times in the panel when it has
      // multiple representation types (e.g., labelmap and surface)
      const uniqueSegmentationMap = new Map();
      representations.forEach(representation => {
        if (!uniqueSegmentationMap.has(representation.segmentationId)) {
          uniqueSegmentationMap.set(representation.segmentationId, representation);
        }
      });
 
      const newSegmentationsWithRepresentations = Array.from(uniqueSegmentationMap.values()).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
      ),
      // What this hook reads is `getSegmentationRepresentations(viewportId)`, so a
      // representation leaving the viewport changes its answer and has to re-run it.
      // Without this, "Remove from Viewport" cleared the overlay from the image but
      // left the segmentation listed in the panel: the data was already correct, the
      // panel simply never asked again. Nothing else covers it — a hydrated
      // segmentation is not a display set in the viewport, so removing it moves no
      // grid state and fires no grid event either.
      segmentationService.subscribe(
        segmentationService.EVENTS.SEGMENTATION_REPRESENTATION_REMOVED,
        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;
}