@ohif/extension-cornerstone 3.14.0-beta.12 → 3.14.0-beta.120

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (332) hide show
  1. package/dist/915.ohif-extension-cornerstone.umd.js +1 -1
  2. package/dist/ohif-extension-cornerstone.umd.js +1 -5
  3. package/package.json +33 -25
  4. package/src/Viewport/OHIFCornerstoneViewport.css +46 -0
  5. package/src/Viewport/OHIFCornerstoneViewport.tsx +498 -0
  6. package/src/Viewport/Overlays/CornerstoneOverlays.tsx +103 -0
  7. package/src/Viewport/Overlays/CustomizableViewportOverlay.css +25 -0
  8. package/src/Viewport/Overlays/CustomizableViewportOverlay.tsx +469 -0
  9. package/src/Viewport/Overlays/ViewportImageScrollbar.tsx +106 -0
  10. package/src/Viewport/Overlays/ViewportImageSliceLoadingIndicator.tsx +87 -0
  11. package/src/Viewport/Overlays/ViewportOrientationMarkers.css +41 -0
  12. package/src/Viewport/Overlays/ViewportOrientationMarkers.tsx +136 -0
  13. package/src/Viewport/Overlays/ViewportSliceProgressScrollbar/ViewportSliceProgressScrollbar.tsx +195 -0
  14. package/src/Viewport/Overlays/ViewportSliceProgressScrollbar/helpers.ts +46 -0
  15. package/src/Viewport/Overlays/ViewportSliceProgressScrollbar/hooks.ts +383 -0
  16. package/src/Viewport/Overlays/ViewportSliceProgressScrollbar/index.ts +1 -0
  17. package/src/Viewport/Overlays/ViewportSliceProgressScrollbar/types.ts +17 -0
  18. package/src/Viewport/Overlays/utils.ts +66 -0
  19. package/src/commandsModule.ts +2970 -0
  20. package/src/components/AccordionGroup/AccordionGroup.tsx +195 -0
  21. package/src/components/AccordionGroup/index.ts +4 -0
  22. package/src/components/ActiveViewportWindowLevel/ActiveViewportWindowLevel.tsx +23 -0
  23. package/src/components/ActiveViewportWindowLevel/index.js +1 -0
  24. package/src/components/AdvancedRenderingControls/AdvancedRenderingControls.tsx +149 -0
  25. package/src/components/AdvancedRenderingControls/index.ts +1 -0
  26. package/src/components/CinePlayer/CinePlayer.tsx +247 -0
  27. package/src/components/CinePlayer/index.ts +3 -0
  28. package/src/components/DicomUpload/DicomUpload.tsx +111 -0
  29. package/src/components/DicomUpload/DicomUploadProgress.tsx +396 -0
  30. package/src/components/DicomUpload/DicomUploadProgressItem.tsx +119 -0
  31. package/src/components/ExportSegmentationSubMenuItem.tsx +75 -0
  32. package/src/components/FidelityIndicator/FidelityIndicator.tsx +152 -0
  33. package/src/components/FidelityIndicator/index.ts +1 -0
  34. package/src/components/MeasurementItems.tsx +70 -0
  35. package/src/components/MeasurementTableNested.tsx +30 -0
  36. package/src/components/MeasurementsMenu.tsx +84 -0
  37. package/src/components/MeasurementsOrAdditionalFindings.tsx +82 -0
  38. package/src/components/ModalityLoadBadge/ModalityLoadBadge.tsx +171 -0
  39. package/src/components/ModalityLoadBadge/index.ts +1 -0
  40. package/src/components/NavigationComponent/NavigationComponent.tsx +138 -0
  41. package/src/components/NavigationComponent/index.ts +3 -0
  42. package/src/components/OHIFViewportActionCorners.tsx +109 -0
  43. package/src/components/OpacityMenu/OpacityMenu.tsx +54 -0
  44. package/src/components/OpacityMenu/OpacityMenuWrapper.tsx +85 -0
  45. package/src/components/OpacityMenu/index.ts +2 -0
  46. package/src/components/PanelAccordionTrigger.tsx +48 -0
  47. package/src/components/SegmentationToolConfig.tsx +71 -0
  48. package/src/components/SegmentationUtilityButton.tsx +61 -0
  49. package/src/components/SelectItemWithModality.tsx +29 -0
  50. package/src/components/SeriesMeasurements.tsx +90 -0
  51. package/src/components/SeriesSummaryFromDisplaySet.tsx +21 -0
  52. package/src/components/StudyMeasurements.tsx +88 -0
  53. package/src/components/StudyMeasurementsActions.tsx +75 -0
  54. package/src/components/StudySummaryFromMetadata.test.ts +47 -0
  55. package/src/components/StudySummaryFromMetadata.tsx +31 -0
  56. package/src/components/StudySummaryWithActions.tsx +14 -0
  57. package/src/components/ThresholdMenu/ThresholdMenu.tsx +104 -0
  58. package/src/components/ThresholdMenu/ThresholdMenuWrapper.tsx +85 -0
  59. package/src/components/ThresholdMenu/index.ts +2 -0
  60. package/src/components/TrackingStatus/TrackingStatus.tsx +32 -0
  61. package/src/components/TrackingStatus/index.ts +1 -0
  62. package/src/components/VOIManualControlMenu/VOIManualControlMenu.tsx +190 -0
  63. package/src/components/VOIManualControlMenu/VOIManualControlMenuWrapper.tsx +85 -0
  64. package/src/components/VOIManualControlMenu/index.ts +2 -0
  65. package/src/components/ViewportColorbar/ViewportColorbar.tsx +150 -0
  66. package/src/components/ViewportColorbar/ViewportColorbarsContainer.tsx +125 -0
  67. package/src/components/ViewportColorbar/index.ts +5 -0
  68. package/src/components/ViewportDataOverlaySettingMenu/ViewportDataOverlayMenu.tsx +538 -0
  69. package/src/components/ViewportDataOverlaySettingMenu/ViewportDataOverlayMenuWrapper.tsx +91 -0
  70. package/src/components/ViewportDataOverlaySettingMenu/utils.ts +118 -0
  71. package/src/components/ViewportOrientationMenu/ViewportOrientationMenu.tsx +249 -0
  72. package/src/components/ViewportOrientationMenu/ViewportOrientationMenuWrapper.tsx +29 -0
  73. package/src/components/ViewportWindowLevel/ViewportWindowLevel.tsx +261 -0
  74. package/src/components/ViewportWindowLevel/getViewportVolumeHistogram.ts +72 -0
  75. package/src/components/ViewportWindowLevel/histogramWorker.js +97 -0
  76. package/src/components/ViewportWindowLevel/index.js +1 -0
  77. package/src/components/ViewportWindowLevel/utils.ts +176 -0
  78. package/src/components/WindowLevelActionMenu/Colorbar.tsx +30 -0
  79. package/src/components/WindowLevelActionMenu/Colormap.tsx +121 -0
  80. package/src/components/WindowLevelActionMenu/VolumeLighting.tsx +82 -0
  81. package/src/components/WindowLevelActionMenu/VolumeRenderingOptions.tsx +38 -0
  82. package/src/components/WindowLevelActionMenu/VolumeRenderingPresets.tsx +36 -0
  83. package/src/components/WindowLevelActionMenu/VolumeRenderingPresetsContent.tsx +78 -0
  84. package/src/components/WindowLevelActionMenu/VolumeRenderingQuality.tsx +64 -0
  85. package/src/components/WindowLevelActionMenu/VolumeShade.tsx +47 -0
  86. package/src/components/WindowLevelActionMenu/VolumeShift.tsx +92 -0
  87. package/src/components/WindowLevelActionMenu/WindowLevel.tsx +157 -0
  88. package/src/components/WindowLevelActionMenu/WindowLevelActionMenu.tsx +102 -0
  89. package/src/components/WindowLevelActionMenu/WindowLevelActionMenuWrapper.tsx +131 -0
  90. package/src/components/WindowLevelActionMenu/defaultWindowLevelPresets.ts +23 -0
  91. package/src/components/WindowLevelActionMenu/index.ts +11 -0
  92. package/src/components/WindowLevelActionMenu/windowLevelPresetHotkeys.test.ts +19 -0
  93. package/src/components/index.ts +13 -0
  94. package/src/constants/index.ts +13 -0
  95. package/src/customizations/CustomDropdownMenuContent.tsx +106 -0
  96. package/src/customizations/CustomSegmentStatisticsHeader.tsx +140 -0
  97. package/src/customizations/captureViewportModalCustomization.tsx +175 -0
  98. package/src/customizations/colorbarCustomization.ts +93 -0
  99. package/src/customizations/gpuSettingsPresetCustomization.ts +8 -0
  100. package/src/customizations/layoutSelectorCustomization.ts +104 -0
  101. package/src/customizations/measurementsCustomization.ts +124 -0
  102. package/src/customizations/miscCustomization.ts +22 -0
  103. package/src/customizations/modalityColorMapCustomization.ts +23 -0
  104. package/src/customizations/segmentationHydrationCustomization.ts +16 -0
  105. package/src/customizations/segmentationPanelCustomization.tsx +119 -0
  106. package/src/customizations/segmentationToolbarCustomization.ts +964 -0
  107. package/src/customizations/toolGroupToolsCustomization.ts +204 -0
  108. package/src/customizations/toolbarButtonsCustomization.ts +805 -0
  109. package/src/customizations/viewportClickCommandsCustomization.ts +15 -0
  110. package/src/customizations/viewportDownloadWarningCustomization.tsx +6 -0
  111. package/src/customizations/viewportOverlayCustomization.tsx +46 -0
  112. package/src/customizations/viewportScrollbarCustomization.tsx +27 -0
  113. package/src/customizations/viewportToolsCustomization.ts +33 -0
  114. package/src/customizations/volumeRenderingCustomization.ts +14 -0
  115. package/src/customizations/windowLevelPresetsCustomization.ts +5 -0
  116. package/src/enums.ts +9 -0
  117. package/src/getCustomizationModule.tsx +54 -0
  118. package/src/getHangingProtocolModule.ts +47 -0
  119. package/src/getPanelModule.tsx +128 -0
  120. package/src/getSopClassHandlerModule.js +284 -0
  121. package/src/getToolbarModule.tsx +622 -0
  122. package/src/hooks/index.ts +9 -0
  123. package/src/hooks/useActiveViewportSegmentationRepresentations.ts +14 -0
  124. package/src/hooks/useMeasurementTracking.ts +132 -0
  125. package/src/hooks/useMeasurements.ts +104 -0
  126. package/src/hooks/useSegmentations.ts +147 -0
  127. package/src/hooks/useViewportDisplaySets.ts +284 -0
  128. package/src/hooks/useViewportFidelity.ts +243 -0
  129. package/src/hooks/useViewportHover.ts +77 -0
  130. package/src/hooks/useViewportRendering.tsx +868 -0
  131. package/src/hooks/useViewportSegmentations.ts +245 -0
  132. package/src/hps/fourUp.ts +117 -0
  133. package/src/hps/frameView.ts +1581 -0
  134. package/src/hps/main3D.ts +142 -0
  135. package/src/hps/mpr.ts +197 -0
  136. package/src/hps/mprAnd3DVolumeViewport.ts +124 -0
  137. package/src/hps/only3D.ts +70 -0
  138. package/src/hps/primary3D.ts +142 -0
  139. package/src/hps/primaryAxial.ts +114 -0
  140. package/src/id.js +5 -0
  141. package/src/index.tsx +350 -0
  142. package/src/init.tsx +450 -0
  143. package/src/initCineService.ts +75 -0
  144. package/src/initContextMenu.ts +94 -0
  145. package/src/initCornerstoneTools.js +188 -0
  146. package/src/initDoubleClick.ts +82 -0
  147. package/src/initMeasurementService.ts +576 -0
  148. package/src/initStudyPrefetcherService.ts +33 -0
  149. package/src/initWADOImageLoader.js +56 -0
  150. package/src/panels/PanelMeasurement.tsx +84 -0
  151. package/src/panels/PanelSegmentation.tsx +338 -0
  152. package/src/services/ColorbarService/ColorbarService.ts +242 -0
  153. package/src/services/ColorbarService/index.ts +2 -0
  154. package/src/services/CornerstoneCacheService/CornerstoneCacheService.ts +326 -0
  155. package/src/services/CornerstoneCacheService/index.js +3 -0
  156. package/src/services/SegmentationService/RTSTRUCT/mapROIContoursToRTStructData.ts +36 -0
  157. package/src/services/SegmentationService/SegmentationService.test.ts +3727 -0
  158. package/src/services/SegmentationService/SegmentationService.ts +2390 -0
  159. package/src/services/SegmentationService/backends/ISegmentationBackend.ts +102 -0
  160. package/src/services/SegmentationService/backends/ISegmentationServiceInternals.ts +44 -0
  161. package/src/services/SegmentationService/backends/LegacySegmentationBackend.ts +139 -0
  162. package/src/services/SegmentationService/backends/NextSegmentationBackend.ts +159 -0
  163. package/src/services/SegmentationService/backends/index.ts +4 -0
  164. package/src/services/SegmentationService/index.ts +3 -0
  165. package/src/services/SyncGroupService/SyncGroupService.ts +264 -0
  166. package/src/services/SyncGroupService/createHydrateSegmentationSynchronizer.ts +118 -0
  167. package/src/services/SyncGroupService/index.js +3 -0
  168. package/src/services/ToolGroupService/ToolGroupService.test.ts +83 -0
  169. package/src/services/ToolGroupService/ToolGroupService.ts +541 -0
  170. package/src/services/ToolGroupService/index.js +3 -0
  171. package/src/services/ViewedDataService/ViewedDataService.ts +58 -0
  172. package/src/services/ViewedDataService/index.ts +3 -0
  173. package/src/services/ViewportService/CornerstoneViewportService.ts +1814 -0
  174. package/src/services/ViewportService/IViewportService.ts +64 -0
  175. package/src/services/ViewportService/Viewport.ts +372 -0
  176. package/src/services/ViewportService/adapter/IViewportAdapter.contract.test.ts +467 -0
  177. package/src/services/ViewportService/adapter/IViewportAdapter.ts +179 -0
  178. package/src/services/ViewportService/adapter/LegacyViewportAdapter.ts +240 -0
  179. package/src/services/ViewportService/adapter/NextViewportAdapter.ts +241 -0
  180. package/src/services/ViewportService/adapter/getViewportAdapter.ts +62 -0
  181. package/src/services/ViewportService/adapter/index.ts +16 -0
  182. package/src/services/ViewportService/backends/IViewportBackend.ts +195 -0
  183. package/src/services/ViewportService/backends/IViewportOperations.ts +98 -0
  184. package/src/services/ViewportService/backends/IViewportServiceInternals.ts +47 -0
  185. package/src/services/ViewportService/backends/LegacyViewportBackend.ts +264 -0
  186. package/src/services/ViewportService/backends/LegacyViewportOperations.ts +272 -0
  187. package/src/services/ViewportService/backends/NextViewportBackend.ts +673 -0
  188. package/src/services/ViewportService/backends/NextViewportOperations.ts +169 -0
  189. package/src/services/ViewportService/backends/README.md +62 -0
  190. package/src/services/ViewportService/backends/dataIdRegistry.ts +121 -0
  191. package/src/services/ViewportService/backends/viewportOperations.ts +71 -0
  192. package/src/services/ViewportService/constants.ts +3 -0
  193. package/src/state.ts +34 -0
  194. package/src/stores/index.ts +5 -0
  195. package/src/stores/presentationUtils.ts +42 -0
  196. package/src/stores/useLutPresentationStore.ts +166 -0
  197. package/src/stores/usePositionPresentationStore.ts +172 -0
  198. package/src/stores/useSegmentationPresentationStore.test.ts +146 -0
  199. package/src/stores/useSegmentationPresentationStore.ts +417 -0
  200. package/src/stores/useSelectedSegmentationsForViewportStore.ts +85 -0
  201. package/src/stores/useSynchronizersStore.ts +84 -0
  202. package/src/synchronizers/frameViewSynchronizer.ts +52 -0
  203. package/src/tools/CalibrationLineTool.ts +97 -0
  204. package/src/tools/ImageOverlayViewerTool.tsx +279 -0
  205. package/src/tools/OverlayPlaneModuleProvider.ts +40 -0
  206. package/src/tools/WindowLevelTool.test.ts +55 -0
  207. package/src/tools/WindowLevelTool.ts +22 -0
  208. package/src/types/AppTypes.ts +70 -0
  209. package/src/types/Colorbar.ts +114 -0
  210. package/src/types/Colormap.ts +16 -0
  211. package/src/types/CornerstoneCacheService.ts +40 -0
  212. package/src/types/CornerstoneServices.ts +18 -0
  213. package/src/types/Presentation.ts +83 -0
  214. package/src/types/SelectedSegmentationByTypeMap.ts +3 -0
  215. package/src/types/ViewportPresets.ts +53 -0
  216. package/src/types/VolumeLighting.ts +7 -0
  217. package/src/types/VolumeRenderingConfig.ts +8 -0
  218. package/src/types/WindowLevel.ts +5 -0
  219. package/src/types/index.ts +10 -0
  220. package/src/utils/ActiveViewportBehavior.tsx +80 -0
  221. package/src/utils/CornerstoneViewportDownloadForm.tsx +319 -0
  222. package/src/utils/DicomFileUploader.ts +204 -0
  223. package/src/utils/JumpPresets.ts +14 -0
  224. package/src/utils/autoHydrateViewportTypes.ts +69 -0
  225. package/src/utils/colormaps.js +1597 -0
  226. package/src/utils/createSegmentationForViewport.test.ts +93 -0
  227. package/src/utils/createSegmentationForViewport.ts +123 -0
  228. package/src/utils/dicomLoaderService.js +225 -0
  229. package/src/utils/ecgMetadata.test.ts +137 -0
  230. package/src/utils/ecgMetadata.ts +109 -0
  231. package/src/utils/findNearbyToolData.test.ts +125 -0
  232. package/src/utils/findNearbyToolData.ts +21 -0
  233. package/src/utils/findWindowLevelPreset.test.ts +55 -0
  234. package/src/utils/findWindowLevelPreset.ts +46 -0
  235. package/src/utils/generateSegmentationCSVReport.test.ts +324 -0
  236. package/src/utils/generateSegmentationCSVReport.ts +131 -0
  237. package/src/utils/getActiveViewportEnabledElement.test.ts +70 -0
  238. package/src/utils/getActiveViewportEnabledElement.ts +8 -0
  239. package/src/utils/getCenterExtent.test.ts +313 -0
  240. package/src/utils/getCenterExtent.ts +46 -0
  241. package/src/utils/getCornerstoneBlendMode.test.ts +59 -0
  242. package/src/utils/getCornerstoneBlendMode.ts +25 -0
  243. package/src/utils/getCornerstoneOrientation.test.ts +78 -0
  244. package/src/utils/getCornerstoneOrientation.ts +31 -0
  245. package/src/utils/getCornerstoneViewportType.test.ts +169 -0
  246. package/src/utils/getCornerstoneViewportType.ts +88 -0
  247. package/src/utils/getInterleavedFrames.test.ts +85 -0
  248. package/src/utils/getInterleavedFrames.ts +73 -0
  249. package/src/utils/getLegacyViewportType.ts +64 -0
  250. package/src/utils/getNthFrames.test.ts +145 -0
  251. package/src/utils/getNthFrames.ts +31 -0
  252. package/src/utils/getViewportEnabledElement.test.ts +83 -0
  253. package/src/utils/getViewportEnabledElement.ts +8 -0
  254. package/src/utils/getViewportOrientationFromImageOrientationPatient.test.ts +50 -0
  255. package/src/utils/getViewportOrientationFromImageOrientationPatient.ts +56 -0
  256. package/src/utils/hydrationUtils.test.ts +572 -0
  257. package/src/utils/hydrationUtils.ts +197 -0
  258. package/src/utils/imageSliceSync/calculateViewportRegistrations.ts +28 -0
  259. package/src/utils/imageSliceSync/toggleImageSliceSync.ts +101 -0
  260. package/src/utils/index.ts +29 -0
  261. package/src/utils/initGpuSettingsPreset.ts +51 -0
  262. package/src/utils/initViewTiming.test.ts +342 -0
  263. package/src/utils/initViewTiming.ts +52 -0
  264. package/src/utils/initWebWorkerProgressHandler.test.ts +381 -0
  265. package/src/utils/initWebWorkerProgressHandler.ts +110 -0
  266. package/src/utils/interleave.test.ts +304 -0
  267. package/src/utils/interleave.ts +32 -0
  268. package/src/utils/interleaveCenterLoader.test.ts +547 -0
  269. package/src/utils/interleaveCenterLoader.ts +143 -0
  270. package/src/utils/interleaveTopToBottom.test.ts +487 -0
  271. package/src/utils/interleaveTopToBottom.ts +132 -0
  272. package/src/utils/isAnyDisplaySetCommon.ts +18 -0
  273. package/src/utils/isDisplaySetOverlayable.ts +106 -0
  274. package/src/utils/isMeasurementWithinViewport.test.ts +340 -0
  275. package/src/utils/isMeasurementWithinViewport.ts +33 -0
  276. package/src/utils/isReferenceViewable.test.ts +581 -0
  277. package/src/utils/isReferenceViewable.ts +95 -0
  278. package/src/utils/loadDisplaySetData.ts +49 -0
  279. package/src/utils/measurementServiceMappings/Angle.ts +200 -0
  280. package/src/utils/measurementServiceMappings/ArrowAnnotate.ts +176 -0
  281. package/src/utils/measurementServiceMappings/Bidirectional.ts +193 -0
  282. package/src/utils/measurementServiceMappings/CircleROI.ts +227 -0
  283. package/src/utils/measurementServiceMappings/CobbAngle.ts +206 -0
  284. package/src/utils/measurementServiceMappings/EllipticalROI.ts +221 -0
  285. package/src/utils/measurementServiceMappings/Length.ts +206 -0
  286. package/src/utils/measurementServiceMappings/LivewireContour.ts +175 -0
  287. package/src/utils/measurementServiceMappings/PlanarFreehandROI.ts +228 -0
  288. package/src/utils/measurementServiceMappings/Probe.ts +192 -0
  289. package/src/utils/measurementServiceMappings/RectangleROI.ts +225 -0
  290. package/src/utils/measurementServiceMappings/SegmentBidirectional.ts +184 -0
  291. package/src/utils/measurementServiceMappings/SplineROI.ts +227 -0
  292. package/src/utils/measurementServiceMappings/UltrasoundDirectional.ts +214 -0
  293. package/src/utils/measurementServiceMappings/UltrasoundPleuraBLine.ts +179 -0
  294. package/src/utils/measurementServiceMappings/constants/supportedTools.js +21 -0
  295. package/src/utils/measurementServiceMappings/index.ts +3 -0
  296. package/src/utils/measurementServiceMappings/measurementServiceMappingsFactory.ts +324 -0
  297. package/src/utils/measurementServiceMappings/utils/getDisplayUnit.js +3 -0
  298. package/src/utils/measurementServiceMappings/utils/getHandlesFromPoints.js +14 -0
  299. package/src/utils/measurementServiceMappings/utils/getIsLocked.ts +5 -0
  300. package/src/utils/measurementServiceMappings/utils/getIsVisible.ts +6 -0
  301. package/src/utils/measurementServiceMappings/utils/getSOPInstanceAttributes.js +66 -0
  302. package/src/utils/measurementServiceMappings/utils/getValueDisplayString.js +12 -0
  303. package/src/utils/measurementServiceMappings/utils/index.ts +17 -0
  304. package/src/utils/measurementServiceMappings/utils/selection.ts +33 -0
  305. package/src/utils/mpr/getProtocolViewportStructureFromGridViewports.ts +74 -0
  306. package/src/utils/nextViewportPolicies.ts +41 -0
  307. package/src/utils/nextViewports.ts +157 -0
  308. package/src/utils/nthLoader.test.ts +317 -0
  309. package/src/utils/nthLoader.ts +78 -0
  310. package/src/utils/presentations/getViewportPresentations.test.ts +280 -0
  311. package/src/utils/presentations/getViewportPresentations.ts +151 -0
  312. package/src/utils/promptHydrationDialog.test.ts +490 -0
  313. package/src/utils/promptHydrationDialog.ts +197 -0
  314. package/src/utils/promptTimePointScope.tsx +82 -0
  315. package/src/utils/removeViewportSegmentationRepresentations.test.ts +129 -0
  316. package/src/utils/removeViewportSegmentationRepresentations.ts +17 -0
  317. package/src/utils/segmentUtils.test.ts +515 -0
  318. package/src/utils/segmentUtils.ts +46 -0
  319. package/src/utils/segmentationExportUtils.test.ts +100 -0
  320. package/src/utils/segmentationExportUtils.ts +171 -0
  321. package/src/utils/segmentationHandlers.test.ts +614 -0
  322. package/src/utils/segmentationHandlers.ts +164 -0
  323. package/src/utils/setUpAnnotationEventHandlers.ts +26 -0
  324. package/src/utils/setUpSegmentationEventHandlers.test.ts +372 -0
  325. package/src/utils/setUpSegmentationEventHandlers.ts +122 -0
  326. package/src/utils/toggleVOISliceSync.test.ts +606 -0
  327. package/src/utils/toggleVOISliceSync.ts +103 -0
  328. package/src/utils/transitions.test.ts +351 -0
  329. package/src/utils/transitions.ts +300 -0
  330. package/src/utils/updateSegmentationStats.test.ts +942 -0
  331. package/src/utils/updateSegmentationStats.ts +192 -0
  332. package/src/utils/viewportDataShape.ts +85 -0
@@ -0,0 +1,3727 @@
1
+ import {
2
+ cache,
3
+ Enums as csEnums,
4
+ eventTarget,
5
+ geometryLoader,
6
+ getEnabledElementByViewportId,
7
+ imageLoader,
8
+ Types as csTypes,
9
+ metaData,
10
+ } from '@cornerstonejs/core';
11
+ import { ViewportType } from '@cornerstonejs/core/enums';
12
+
13
+ import {
14
+ Enums as csToolsEnums,
15
+ segmentation as cstSegmentation,
16
+ Types as cstTypes,
17
+ } from '@cornerstonejs/tools';
18
+
19
+ import { EasingFunctionEnum, EasingFunctionMap } from '../../utils/transitions';
20
+ import * as MapROIContoursToRTStructData from './RTSTRUCT/mapROIContoursToRTStructData';
21
+ import SegmentationServiceClass, { SegmentationRepresentation } from './SegmentationService';
22
+ import { setNextViewportsEnabled } from '../../utils/nextViewports';
23
+
24
+ jest.mock('@cornerstonejs/core', () => ({
25
+ ...jest.requireActual('@cornerstonejs/core'),
26
+ getEnabledElementByViewportId: jest.fn(),
27
+ eventTarget: {
28
+ addEventListener: jest.fn(),
29
+ removeEventListener: jest.fn(),
30
+ },
31
+ }));
32
+
33
+ jest.mock('@cornerstonejs/tools', () => ({
34
+ ...jest.requireActual('@cornerstonejs/tools'),
35
+ segmentation: {
36
+ ...jest.requireActual('@cornerstonejs/tools').segmentation,
37
+ activeSegmentation: {
38
+ getActiveSegmentation: jest.fn(),
39
+ setActiveSegmentation: jest.fn(),
40
+ },
41
+ addSegmentations: jest.fn(),
42
+ config: {
43
+ color: {
44
+ getSegmentIndexColor: jest.fn(),
45
+ setSegmentIndexColor: jest.fn(),
46
+ },
47
+ visibility: {
48
+ getHiddenSegmentIndices: jest.fn(),
49
+ getSegmentIndexVisibility: jest.fn(),
50
+ setSegmentIndexVisibility: jest.fn(),
51
+ setSegmentationRepresentationVisibility: jest.fn(),
52
+ },
53
+ style: {
54
+ hasCustomStyle: jest.fn(),
55
+ getRenderInactiveSegmentations: jest.fn(),
56
+ getStyle: jest.fn(),
57
+ resetToGlobalStyle: jest.fn(),
58
+ setRenderInactiveSegmentations: jest.fn(),
59
+ setStyle: jest.fn(),
60
+ },
61
+ },
62
+ getLabelmapImageIds: jest.fn(),
63
+ helpers: { convertStackToVolumeLabelmap: jest.fn() },
64
+ removeSegment: jest.fn(),
65
+ removeSegmentationRepresentations: jest.fn(),
66
+ segmentIndex: {
67
+ setActiveSegmentIndex: jest.fn(),
68
+ },
69
+ segmentLocking: {
70
+ isSegmentIndexLocked: jest.fn(),
71
+ setSegmentIndexLocked: jest.fn(),
72
+ },
73
+ state: {
74
+ addColorLUT: jest.fn(),
75
+ getSegmentation: jest.fn(),
76
+ getSegmentations: jest.fn(),
77
+ getSegmentationRepresentationsBySegmentationId: jest.fn(),
78
+ getSegmentationRepresentations: jest.fn(),
79
+ getViewportIdsWithSegmentation: jest.fn(),
80
+ removeAllSegmentations: jest.fn(),
81
+ removeSegmentation: jest.fn(),
82
+ updateLabelmapSegmentationImageReferences: jest.fn(),
83
+ },
84
+ triggerSegmentationEvents: { triggerSegmentationRepresentationModified: jest.fn() },
85
+ },
86
+ }));
87
+
88
+ const serviceManagerMock = {
89
+ services: {
90
+ cornerstoneViewportService: {
91
+ getCornerstoneViewport: jest.fn(),
92
+ },
93
+ displaySetService: {
94
+ getDisplaySetByUID: jest.fn(),
95
+ },
96
+ viewportGridService: {
97
+ EVENTS: {
98
+ GRID_STATE_CHANGED: 'event::gridStateChanged',
99
+ },
100
+ getState: jest.fn(),
101
+ setDisplaySetsForViewport: jest.fn(),
102
+ subscribe: jest.fn(),
103
+ },
104
+ },
105
+ };
106
+
107
+ describe('SegmentationService', () => {
108
+ let service: SegmentationServiceClass;
109
+ const viewportId = 'viewportId';
110
+ const mockCornerstoneRepresentations = [
111
+ {
112
+ segmentationId: 'd7682642-c41d-abe5-3c78-716191336ab1',
113
+ type: 'Labelmap',
114
+ active: true,
115
+ visible: true,
116
+ colorLUTIndex: 0,
117
+ segments: {
118
+ '1': { visible: true },
119
+ },
120
+ config: {
121
+ cfun: { nodes: [] },
122
+ ofun: { nodes: [] },
123
+ colorLUTIndex: 0,
124
+ colorLUTOrIndex: 0,
125
+ },
126
+ },
127
+ {
128
+ segmentationId: 'd7682642-c41d-abe5-3c78-716191336ab2',
129
+ type: 'Labelmap',
130
+ active: true,
131
+ visible: true,
132
+ colorLUTIndex: 0,
133
+ segments: {
134
+ '1': { visible: true },
135
+ },
136
+ config: {
137
+ cfun: { nodes: [] },
138
+ ofun: { nodes: [] },
139
+ colorLUTIndex: 0,
140
+ colorLUTOrIndex: 0,
141
+ },
142
+ },
143
+ ];
144
+ const mockCornerstoneSegmentation = {
145
+ segmentationId: '1d6ce0c8-aeae-6890-1cc6-b39560866811',
146
+ label: 'Segmentation',
147
+ cachedStats: {},
148
+ segments: {
149
+ '1': {
150
+ active: true,
151
+ cachedStats: {},
152
+ label: 'Segment 1',
153
+ locked: false,
154
+ segmentIndex: 1,
155
+ },
156
+ },
157
+ representationData: { Labelmap: {} },
158
+ };
159
+ const mockVolumeCornerstoneSegmentation = {
160
+ ...mockCornerstoneSegmentation,
161
+ representationData: { Labelmap: { volumeId: 'volumeId' } },
162
+ };
163
+ const mockCornerstoneStackViewport = {
164
+ element: {
165
+ addEventListener: jest.fn(),
166
+ removeEventListener: jest.fn(),
167
+ },
168
+ id: viewportId,
169
+ type: ViewportType.STACK,
170
+ getFrameOfReferenceUID: jest.fn(),
171
+ getViewPresentation: jest.fn(),
172
+ getViewReference: jest.fn(),
173
+ };
174
+ const mockCornerstoneVolumeViewport = {
175
+ id: viewportId,
176
+ type: ViewportType.VOLUME_3D,
177
+ getFrameOfReferenceUID: jest.fn(),
178
+ setViewPresentation: jest.fn(),
179
+ setViewReference: jest.fn(),
180
+ render: jest.fn(),
181
+ };
182
+ const representations = [
183
+ {
184
+ ...mockCornerstoneRepresentations[0],
185
+ viewportId: 'viewportId',
186
+ id: 'test-id',
187
+ label: 'Test Segmentation',
188
+ styles: {},
189
+ segments: {
190
+ 1: {
191
+ color: [255, 0, 0, 1],
192
+ opacity: 1,
193
+ segmentIndex: 1,
194
+ visible: true,
195
+ },
196
+ },
197
+ },
198
+ ] as SegmentationRepresentation[];
199
+
200
+ beforeEach(() => {
201
+ service = new SegmentationServiceClass({ servicesManager: serviceManagerMock });
202
+
203
+ jest.clearAllMocks();
204
+ });
205
+
206
+ it('should instantiate the service properly', () => {
207
+ expect(service).toBeDefined();
208
+ expect(service.servicesManager).toBe(serviceManagerMock);
209
+ expect(service.EVENTS).toBeDefined();
210
+ });
211
+
212
+ it('should instantiate service through registration', () => {
213
+ // @ts-expect-error - mock only has a subset of the properties
214
+ const service = SegmentationServiceClass.REGISTRATION.create({
215
+ servicesManager: serviceManagerMock,
216
+ });
217
+
218
+ expect(service).toBeDefined();
219
+ });
220
+
221
+ describe('onModeEnter', () => {
222
+ it('should add event listeners', () => {
223
+ service.onModeEnter();
224
+
225
+ expect(eventTarget.addEventListener).toHaveBeenCalledTimes(8);
226
+
227
+ expect(eventTarget.addEventListener).toHaveBeenCalledWith(
228
+ csToolsEnums.Events.SEGMENTATION_MODIFIED,
229
+ expect.any(Function)
230
+ );
231
+ expect(eventTarget.addEventListener).toHaveBeenCalledWith(
232
+ csToolsEnums.Events.SEGMENTATION_REMOVED,
233
+ expect.any(Function)
234
+ );
235
+ expect(eventTarget.addEventListener).toHaveBeenCalledWith(
236
+ csToolsEnums.Events.SEGMENTATION_DATA_MODIFIED,
237
+ expect.any(Function)
238
+ );
239
+ expect(eventTarget.addEventListener).toHaveBeenCalledWith(
240
+ csToolsEnums.Events.SEGMENTATION_REPRESENTATION_MODIFIED,
241
+ expect.any(Function)
242
+ );
243
+ expect(eventTarget.addEventListener).toHaveBeenCalledWith(
244
+ csToolsEnums.Events.SEGMENTATION_REPRESENTATION_ADDED,
245
+ expect.any(Function)
246
+ );
247
+ expect(eventTarget.addEventListener).toHaveBeenCalledWith(
248
+ csToolsEnums.Events.SEGMENTATION_REPRESENTATION_REMOVED,
249
+ expect.any(Function)
250
+ );
251
+ expect(eventTarget.addEventListener).toHaveBeenCalledWith(
252
+ csToolsEnums.Events.SEGMENTATION_ADDED,
253
+ expect.any(Function)
254
+ );
255
+ expect(eventTarget.addEventListener).toHaveBeenCalledWith(
256
+ csToolsEnums.Events.ANNOTATION_CUT_MERGE_PROCESS_COMPLETED,
257
+ expect.any(Function)
258
+ );
259
+ });
260
+ });
261
+
262
+ describe('onModeExit', () => {
263
+ it('should remove event listeners', () => {
264
+ jest.spyOn(service, 'reset');
265
+
266
+ service.onModeExit();
267
+
268
+ expect(eventTarget.removeEventListener).toHaveBeenCalledTimes(7);
269
+
270
+ expect(eventTarget.removeEventListener).toHaveBeenCalledWith(
271
+ csToolsEnums.Events.SEGMENTATION_MODIFIED,
272
+ expect.any(Function)
273
+ );
274
+ expect(eventTarget.removeEventListener).toHaveBeenCalledWith(
275
+ csToolsEnums.Events.SEGMENTATION_REMOVED,
276
+ expect.any(Function)
277
+ );
278
+ expect(eventTarget.removeEventListener).toHaveBeenCalledWith(
279
+ csToolsEnums.Events.SEGMENTATION_DATA_MODIFIED,
280
+ expect.any(Function)
281
+ );
282
+ expect(eventTarget.removeEventListener).toHaveBeenCalledWith(
283
+ csToolsEnums.Events.SEGMENTATION_REPRESENTATION_MODIFIED,
284
+ expect.any(Function)
285
+ );
286
+ expect(eventTarget.removeEventListener).toHaveBeenCalledWith(
287
+ csToolsEnums.Events.SEGMENTATION_REPRESENTATION_ADDED,
288
+ expect.any(Function)
289
+ );
290
+ expect(eventTarget.removeEventListener).toHaveBeenCalledWith(
291
+ csToolsEnums.Events.SEGMENTATION_REPRESENTATION_REMOVED,
292
+ expect.any(Function)
293
+ );
294
+ expect(eventTarget.removeEventListener).toHaveBeenCalledWith(
295
+ csToolsEnums.Events.SEGMENTATION_ADDED,
296
+ expect.any(Function)
297
+ );
298
+
299
+ expect(service.reset).toHaveBeenCalled();
300
+ });
301
+ });
302
+
303
+ describe('getSegmentation', () => {
304
+ it('should call cornerstone to get specific segmentation', () => {
305
+ service.getSegmentation('segmentationId');
306
+
307
+ expect(cstSegmentation.state.getSegmentation).toHaveBeenCalledWith('segmentationId');
308
+ });
309
+ });
310
+
311
+ describe('getSegmentations', () => {
312
+ it('should call cornerstone to get all segmentations', () => {
313
+ service.getSegmentations();
314
+
315
+ expect(cstSegmentation.state.getSegmentations).toHaveBeenCalled();
316
+ });
317
+ });
318
+
319
+ describe('getPresentation', () => {
320
+ it('should properly retrieve the segmentation presentations', () => {
321
+ jest
322
+ .spyOn(cstSegmentation.state, 'getSegmentationRepresentations')
323
+ .mockReturnValueOnce(
324
+ mockCornerstoneRepresentations as cstTypes.SegmentationRepresentation[]
325
+ );
326
+ jest
327
+ .spyOn(cstSegmentation.state, 'getSegmentation')
328
+ .mockReturnValue(mockCornerstoneSegmentation as cstTypes.Segmentation);
329
+ jest
330
+ .spyOn(cstSegmentation.config.color, 'getSegmentIndexColor')
331
+ .mockReturnValue([0, 0, 0, 1]);
332
+ jest
333
+ .spyOn(cstSegmentation.config.visibility, 'getSegmentIndexVisibility')
334
+ .mockReturnValue(true);
335
+ jest.spyOn(cstSegmentation.config.style, 'getStyle').mockReturnValue({});
336
+
337
+ const returnedPresentations = service.getPresentation(viewportId);
338
+
339
+ // config is empty due to _toOHIFSegmentationRepresentation returning empty config
340
+ expect(returnedPresentations).toEqual([
341
+ {
342
+ config: {},
343
+ hydrated: true,
344
+ segmentationId: 'd7682642-c41d-abe5-3c78-716191336ab1',
345
+ type: 'Labelmap',
346
+ },
347
+ {
348
+ config: {},
349
+ hydrated: true,
350
+ segmentationId: 'd7682642-c41d-abe5-3c78-716191336ab2',
351
+ type: 'Labelmap',
352
+ },
353
+ ]);
354
+ });
355
+
356
+ it('should ignore when representation is undefined', () => {
357
+ jest.spyOn(service, 'getSegmentationRepresentations').mockReturnValueOnce([undefined]);
358
+
359
+ const returnedPresentations = service.getPresentation(viewportId);
360
+
361
+ expect(returnedPresentations).toEqual([]);
362
+ });
363
+ });
364
+
365
+ describe('getRepresentationsForSegmentation', () => {
366
+ it('should call cornerstone to get representations for a segmentation', () => {
367
+ service.getRepresentationsForSegmentation('segmentationId');
368
+
369
+ expect(
370
+ cstSegmentation.state.getSegmentationRepresentationsBySegmentationId
371
+ ).toHaveBeenCalledWith('segmentationId');
372
+ });
373
+ });
374
+
375
+ describe('getSegmentationRepresentations', () => {
376
+ it('should properly map cornerstone representations to OHIF representations', () => {
377
+ jest
378
+ .spyOn(cstSegmentation.state, 'getSegmentationRepresentations')
379
+ .mockReturnValueOnce(
380
+ mockCornerstoneRepresentations as cstTypes.SegmentationRepresentation[]
381
+ );
382
+ jest
383
+ .spyOn(cstSegmentation.state, 'getSegmentation')
384
+ .mockReturnValue(mockCornerstoneSegmentation as cstTypes.Segmentation);
385
+ jest
386
+ .spyOn(cstSegmentation.config.color, 'getSegmentIndexColor')
387
+ .mockReturnValue([0, 0, 0, 1]);
388
+ jest
389
+ .spyOn(cstSegmentation.config.visibility, 'getSegmentIndexVisibility')
390
+ .mockReturnValue(true);
391
+ jest.spyOn(cstSegmentation.config.style, 'getStyle').mockReturnValue({});
392
+
393
+ const returnedPresentations = service.getSegmentationRepresentations(viewportId);
394
+
395
+ expect(returnedPresentations).toEqual([
396
+ {
397
+ active: true,
398
+ colorLUTIndex: 0,
399
+ config: {},
400
+ id: 'd7682642-c41d-abe5-3c78-716191336ab1-Labelmap-viewportId',
401
+ label: 'Segmentation',
402
+ segmentationId: 'd7682642-c41d-abe5-3c78-716191336ab1',
403
+ segments: {
404
+ '1': {
405
+ color: [0, 0, 0, 1],
406
+ opacity: 1,
407
+ segmentIndex: 1,
408
+ visible: true,
409
+ },
410
+ },
411
+ styles: {},
412
+ type: 'Labelmap',
413
+ viewportId: 'viewportId',
414
+ visible: true,
415
+ },
416
+ {
417
+ active: true,
418
+ colorLUTIndex: 0,
419
+ config: {},
420
+ id: 'd7682642-c41d-abe5-3c78-716191336ab2-Labelmap-viewportId',
421
+ label: 'Segmentation',
422
+ segmentationId: 'd7682642-c41d-abe5-3c78-716191336ab2',
423
+ segments: {
424
+ '1': {
425
+ color: [0, 0, 0, 1],
426
+ opacity: 1,
427
+ segmentIndex: 1,
428
+ visible: true,
429
+ },
430
+ },
431
+ styles: {},
432
+ type: 'Labelmap',
433
+ viewportId: 'viewportId',
434
+ visible: true,
435
+ },
436
+ ]);
437
+
438
+ expect(cstSegmentation.state.getSegmentationRepresentations).toHaveBeenCalledTimes(1);
439
+ expect(cstSegmentation.state.getSegmentationRepresentations).toHaveBeenCalledWith(
440
+ viewportId,
441
+ {}
442
+ );
443
+
444
+ expect(cstSegmentation.state.getSegmentation).toHaveBeenCalledTimes(2);
445
+ expect(cstSegmentation.state.getSegmentation).toHaveBeenCalledWith(
446
+ mockCornerstoneRepresentations[0].segmentationId
447
+ );
448
+ expect(cstSegmentation.state.getSegmentation).toHaveBeenCalledWith(
449
+ mockCornerstoneRepresentations[1].segmentationId
450
+ );
451
+
452
+ expect(cstSegmentation.config.color.getSegmentIndexColor).toHaveBeenCalledTimes(2);
453
+ expect(cstSegmentation.config.color.getSegmentIndexColor).toHaveBeenCalledWith(
454
+ viewportId,
455
+ mockCornerstoneRepresentations[0].segmentationId,
456
+ mockCornerstoneSegmentation.segments['1'].segmentIndex
457
+ );
458
+ expect(cstSegmentation.config.color.getSegmentIndexColor).toHaveBeenCalledWith(
459
+ viewportId,
460
+ mockCornerstoneRepresentations[1].segmentationId,
461
+ mockCornerstoneSegmentation.segments['1'].segmentIndex
462
+ );
463
+
464
+ expect(cstSegmentation.config.visibility.getSegmentIndexVisibility).toHaveBeenCalledTimes(2);
465
+ expect(cstSegmentation.config.visibility.getSegmentIndexVisibility).toHaveBeenCalledWith(
466
+ viewportId,
467
+ {
468
+ segmentationId: mockCornerstoneRepresentations[0].segmentationId,
469
+ type: mockCornerstoneRepresentations[0].type,
470
+ },
471
+ mockCornerstoneSegmentation.segments['1'].segmentIndex
472
+ );
473
+ expect(cstSegmentation.config.visibility.getSegmentIndexVisibility).toHaveBeenCalledWith(
474
+ viewportId,
475
+ {
476
+ segmentationId: mockCornerstoneRepresentations[1].segmentationId,
477
+ type: mockCornerstoneRepresentations[1].type,
478
+ },
479
+ mockCornerstoneSegmentation.segments['1'].segmentIndex
480
+ );
481
+
482
+ expect(cstSegmentation.config.style.getStyle).toHaveBeenCalledTimes(2);
483
+ expect(cstSegmentation.config.style.getStyle).toHaveBeenCalledWith({
484
+ viewportId,
485
+ segmentationId: mockCornerstoneRepresentations[0].segmentationId,
486
+ type: 'Labelmap',
487
+ });
488
+ expect(cstSegmentation.config.style.getStyle).toHaveBeenCalledWith({
489
+ viewportId,
490
+ segmentationId: mockCornerstoneRepresentations[1].segmentationId,
491
+ type: 'Labelmap',
492
+ });
493
+ });
494
+
495
+ it('should throw an error if the segmentation is not found', () => {
496
+ jest
497
+ .spyOn(cstSegmentation.state, 'getSegmentationRepresentations')
498
+ .mockReturnValueOnce(
499
+ mockCornerstoneRepresentations as cstTypes.SegmentationRepresentation[]
500
+ );
501
+ jest
502
+ .spyOn(cstSegmentation.state, 'getSegmentation')
503
+ .mockReturnValue(null as cstTypes.Segmentation);
504
+
505
+ expect(() => service.getSegmentationRepresentations(viewportId)).toThrow(
506
+ `Segmentation with ID ${mockCornerstoneRepresentations[0].segmentationId} not found.`
507
+ );
508
+ });
509
+
510
+ it('should forward the specifier to the cornerstone getSegmentationRepresentations', () => {
511
+ jest
512
+ .spyOn(cstSegmentation.state, 'getSegmentationRepresentations')
513
+ .mockReturnValueOnce(
514
+ mockCornerstoneRepresentations as cstTypes.SegmentationRepresentation[]
515
+ );
516
+ jest
517
+ .spyOn(cstSegmentation.state, 'getSegmentation')
518
+ .mockReturnValue(mockCornerstoneSegmentation as cstTypes.Segmentation);
519
+ jest
520
+ .spyOn(cstSegmentation.config.color, 'getSegmentIndexColor')
521
+ .mockReturnValue([0, 0, 0, 1]);
522
+ jest
523
+ .spyOn(cstSegmentation.config.visibility, 'getSegmentIndexVisibility')
524
+ .mockReturnValue(true);
525
+ jest.spyOn(cstSegmentation.config.style, 'getStyle').mockReturnValue({});
526
+
527
+ service.getSegmentationRepresentations(viewportId, {
528
+ segmentationId: mockCornerstoneRepresentations[0].segmentationId,
529
+ type: mockCornerstoneRepresentations[0].type as csToolsEnums.SegmentationRepresentations,
530
+ });
531
+
532
+ expect(cstSegmentation.state.getSegmentationRepresentations).toHaveBeenCalledTimes(1);
533
+ expect(cstSegmentation.state.getSegmentationRepresentations).toHaveBeenCalledWith(
534
+ viewportId,
535
+ {
536
+ segmentationId: mockCornerstoneRepresentations[0].segmentationId,
537
+ type: mockCornerstoneRepresentations[0].type,
538
+ }
539
+ );
540
+ });
541
+ });
542
+
543
+ describe('destroy', () => {
544
+ it('should remove event listeners and reset the service', () => {
545
+ jest.spyOn(service, 'reset');
546
+
547
+ service.destroy();
548
+
549
+ expect(eventTarget.removeEventListener).toHaveBeenCalledTimes(7);
550
+
551
+ expect(eventTarget.removeEventListener).toHaveBeenCalledWith(
552
+ csToolsEnums.Events.SEGMENTATION_MODIFIED,
553
+ expect.any(Function)
554
+ );
555
+ expect(eventTarget.removeEventListener).toHaveBeenCalledWith(
556
+ csToolsEnums.Events.SEGMENTATION_REMOVED,
557
+ expect.any(Function)
558
+ );
559
+ expect(eventTarget.removeEventListener).toHaveBeenCalledWith(
560
+ csToolsEnums.Events.SEGMENTATION_DATA_MODIFIED,
561
+ expect.any(Function)
562
+ );
563
+ expect(eventTarget.removeEventListener).toHaveBeenCalledWith(
564
+ csToolsEnums.Events.SEGMENTATION_REPRESENTATION_MODIFIED,
565
+ expect.any(Function)
566
+ );
567
+ expect(eventTarget.removeEventListener).toHaveBeenCalledWith(
568
+ csToolsEnums.Events.SEGMENTATION_REPRESENTATION_ADDED,
569
+ expect.any(Function)
570
+ );
571
+ expect(eventTarget.removeEventListener).toHaveBeenCalledWith(
572
+ csToolsEnums.Events.SEGMENTATION_REPRESENTATION_REMOVED,
573
+ expect.any(Function)
574
+ );
575
+ expect(eventTarget.removeEventListener).toHaveBeenCalledWith(
576
+ csToolsEnums.Events.SEGMENTATION_ADDED,
577
+ expect.any(Function)
578
+ );
579
+
580
+ expect(service.reset).toHaveBeenCalled();
581
+ });
582
+ });
583
+
584
+ describe('addSegmentationRepresentation', () => {
585
+ describe('stack viewport', () => {
586
+ it('should add a non volume segmentation representation to stack viewport through Cornerstone updateLabelmapSegmentationImageReferences', async () => {
587
+ jest
588
+ .spyOn(cstSegmentation.state, 'getSegmentation')
589
+ .mockReturnValue(mockCornerstoneSegmentation as cstTypes.Segmentation);
590
+ jest
591
+ .spyOn(serviceManagerMock.services.cornerstoneViewportService, 'getCornerstoneViewport')
592
+ // only needed interfaces for the addSegmentationRepresentation call
593
+ .mockReturnValue(mockCornerstoneStackViewport as unknown as csTypes.IStackViewport);
594
+ jest
595
+ .spyOn(cstSegmentation.state, 'updateLabelmapSegmentationImageReferences')
596
+ .mockReturnValue('labelmapImageId');
597
+ jest
598
+ .spyOn(cstSegmentation, 'addSegmentationRepresentations')
599
+ .mockReturnValueOnce(undefined);
600
+
601
+ const callback = jest.fn();
602
+ service.subscribe(service.EVENTS.SEGMENTATION_REPRESENTATION_MODIFIED, callback);
603
+
604
+ await service.addSegmentationRepresentation(viewportId, {
605
+ segmentationId: mockCornerstoneSegmentation.segmentationId,
606
+ type: csToolsEnums.SegmentationRepresentations.Labelmap,
607
+ });
608
+
609
+ expect(
610
+ cstSegmentation.state.updateLabelmapSegmentationImageReferences
611
+ ).toHaveBeenCalledTimes(1);
612
+ expect(
613
+ cstSegmentation.state.updateLabelmapSegmentationImageReferences
614
+ ).toHaveBeenCalledWith(viewportId, mockCornerstoneSegmentation.segmentationId);
615
+
616
+ // this will be called directly because there's no OHIF conversion needed
617
+ expect(cstSegmentation.addSegmentationRepresentations).toHaveBeenCalledTimes(1);
618
+ expect(cstSegmentation.addSegmentationRepresentations).toHaveBeenCalledWith(viewportId, [
619
+ {
620
+ type: csToolsEnums.SegmentationRepresentations.Labelmap,
621
+ segmentationId: mockCornerstoneSegmentation.segmentationId,
622
+ config: { colorLUTOrIndex: undefined }, // expected since _segmentationIdToColorLUTIndexMap wasn't previous set
623
+ },
624
+ ]);
625
+
626
+ expect(callback).toHaveBeenCalledTimes(1);
627
+ expect(callback).toHaveBeenCalledWith({
628
+ segmentationId: mockCornerstoneSegmentation.segmentationId,
629
+ });
630
+ });
631
+
632
+ it('should add a non volume segmentation representation to stack viewport through SegmentationService conversion attempt', async () => {
633
+ const frameOfReferenceUID = 'frameOfReferenceUID';
634
+ const imageId = 'imageId';
635
+ const viewportGridServiceUnsubscribe = jest.fn();
636
+
637
+ const prevViewPresentation = {};
638
+ const prevViewReference = {};
639
+
640
+ mockCornerstoneStackViewport.getFrameOfReferenceUID.mockReturnValueOnce(
641
+ frameOfReferenceUID
642
+ );
643
+ mockCornerstoneStackViewport.getViewPresentation.mockReturnValueOnce(prevViewPresentation);
644
+ mockCornerstoneStackViewport.getViewReference.mockReturnValueOnce(prevViewReference);
645
+
646
+ jest
647
+ .spyOn(cstSegmentation.state, 'getSegmentation')
648
+ .mockReturnValue(mockCornerstoneSegmentation as cstTypes.Segmentation);
649
+ jest
650
+ .spyOn(serviceManagerMock.services.cornerstoneViewportService, 'getCornerstoneViewport')
651
+ // only needed interfaces for the addSegmentationRepresentation call
652
+ .mockReturnValue(mockCornerstoneStackViewport as unknown as csTypes.IStackViewport);
653
+ jest
654
+ .spyOn(cstSegmentation.state, 'updateLabelmapSegmentationImageReferences')
655
+ .mockReturnValue(undefined);
656
+ jest.spyOn(cstSegmentation, 'getLabelmapImageIds').mockReturnValue([imageId]);
657
+ jest
658
+ .spyOn(cstSegmentation, 'addSegmentationRepresentations')
659
+ .mockReturnValueOnce(undefined);
660
+ jest
661
+ .spyOn(cache, 'getImage')
662
+ .mockReturnValueOnce({ FrameOfReferenceUID: frameOfReferenceUID } as csTypes.IImage);
663
+ jest.spyOn(serviceManagerMock.services.viewportGridService, 'getState').mockReturnValue({
664
+ viewports: new Map([
665
+ [
666
+ viewportId,
667
+ { displaySetInstanceUIDs: ['displaySetInstanceUID'], viewportOptions: {} },
668
+ ],
669
+ ]),
670
+ });
671
+ jest
672
+ .spyOn(cstSegmentation, 'addSegmentationRepresentations')
673
+ .mockReturnValueOnce(undefined);
674
+ jest.spyOn(serviceManagerMock.services.viewportGridService, 'subscribe').mockReturnValue({
675
+ unsubscribe: viewportGridServiceUnsubscribe,
676
+ });
677
+
678
+ // awaiting here will wait for publishing of viewportGridService.EVENTS.GRID_STATE_CHANGED (deadlock avoidance)
679
+ const serviceAddSegmentationRepresentationPromise = service.addSegmentationRepresentation(
680
+ viewportId,
681
+ {
682
+ segmentationId: mockCornerstoneSegmentation.segmentationId,
683
+ type: csToolsEnums.SegmentationRepresentations.Labelmap,
684
+ }
685
+ );
686
+
687
+ let _addSegmentationRepresentationCallback;
688
+ const waitForSubscription = async () => {
689
+ let remainingAttempts = 100;
690
+
691
+ while (_addSegmentationRepresentationCallback === undefined && remainingAttempts > 0) {
692
+ _addSegmentationRepresentationCallback = jest.mocked(
693
+ serviceManagerMock.services.viewportGridService.subscribe
694
+ ).mock.calls[0]?.[1];
695
+
696
+ await new Promise(resolve => resolve(void 0));
697
+ remainingAttempts--;
698
+ }
699
+ };
700
+
701
+ await waitForSubscription();
702
+
703
+ // trigger callback being awaited
704
+ _addSegmentationRepresentationCallback();
705
+ await serviceAddSegmentationRepresentationPromise;
706
+
707
+ expect(cstSegmentation.getLabelmapImageIds).toHaveBeenCalledTimes(1);
708
+ expect(cstSegmentation.getLabelmapImageIds).toHaveBeenCalledWith(
709
+ mockCornerstoneSegmentation.segmentationId
710
+ );
711
+
712
+ expect(mockCornerstoneStackViewport.getFrameOfReferenceUID).toHaveBeenCalledTimes(1);
713
+ expect(mockCornerstoneStackViewport.getFrameOfReferenceUID).toHaveBeenCalledWith();
714
+
715
+ expect(cache.getImage).toHaveBeenCalledTimes(1);
716
+ expect(cache.getImage).toHaveBeenCalledWith(imageId);
717
+
718
+ expect(serviceManagerMock.services.viewportGridService.getState).toHaveBeenCalledTimes(1);
719
+ expect(serviceManagerMock.services.viewportGridService.getState).toHaveBeenCalledWith();
720
+
721
+ expect(mockCornerstoneStackViewport.getViewPresentation).toHaveBeenCalledTimes(1);
722
+ expect(mockCornerstoneStackViewport.getViewPresentation).toHaveBeenCalledWith();
723
+
724
+ expect(mockCornerstoneStackViewport.getViewReference).toHaveBeenCalledTimes(1);
725
+ expect(mockCornerstoneStackViewport.getViewReference).toHaveBeenCalledWith();
726
+
727
+ expect(
728
+ serviceManagerMock.services.cornerstoneViewportService.getCornerstoneViewport
729
+ ).toHaveBeenCalledTimes(2);
730
+ expect(
731
+ serviceManagerMock.services.cornerstoneViewportService.getCornerstoneViewport
732
+ ).toHaveBeenCalledWith(viewportId);
733
+
734
+ expect(mockCornerstoneStackViewport.element.addEventListener).toHaveBeenCalledTimes(1);
735
+ expect(mockCornerstoneStackViewport.element.addEventListener).toHaveBeenCalledWith(
736
+ csEnums.Events.VOLUME_VIEWPORT_NEW_VOLUME,
737
+ expect.any(Function)
738
+ );
739
+
740
+ const volumeViewportNewVolumeHandlerCallback = jest.mocked(
741
+ mockCornerstoneStackViewport.element.addEventListener
742
+ ).mock.calls[0][1];
743
+
744
+ expect(
745
+ serviceManagerMock.services.viewportGridService.setDisplaySetsForViewport
746
+ ).toHaveBeenCalledTimes(1);
747
+ expect(
748
+ serviceManagerMock.services.viewportGridService.setDisplaySetsForViewport
749
+ ).toHaveBeenCalledWith({
750
+ viewportId,
751
+ displaySetInstanceUIDs: ['displaySetInstanceUID'],
752
+ viewportOptions: { viewportType: ViewportType.ORTHOGRAPHIC },
753
+ });
754
+
755
+ expect(
756
+ cstSegmentation.triggerSegmentationEvents.triggerSegmentationRepresentationModified
757
+ ).toHaveBeenCalledTimes(1);
758
+ expect(
759
+ cstSegmentation.triggerSegmentationEvents.triggerSegmentationRepresentationModified
760
+ ).toHaveBeenCalledWith(
761
+ viewportId,
762
+ mockCornerstoneSegmentation.segmentationId,
763
+ csToolsEnums.SegmentationRepresentations.Labelmap
764
+ );
765
+
766
+ jest
767
+ .spyOn(serviceManagerMock.services.cornerstoneViewportService, 'getCornerstoneViewport')
768
+ // only needed interfaces for the addSegmentationRepresentation call
769
+ .mockReturnValue(mockCornerstoneVolumeViewport as unknown as csTypes.IVolumeViewport);
770
+
771
+ volumeViewportNewVolumeHandlerCallback();
772
+
773
+ expect(
774
+ serviceManagerMock.services.cornerstoneViewportService.getCornerstoneViewport
775
+ ).toHaveBeenCalledTimes(3);
776
+ expect(
777
+ serviceManagerMock.services.cornerstoneViewportService.getCornerstoneViewport
778
+ ).toHaveBeenCalledWith(viewportId);
779
+
780
+ expect(mockCornerstoneVolumeViewport.setViewPresentation).toHaveBeenCalledTimes(1);
781
+ expect(mockCornerstoneVolumeViewport.setViewPresentation).toHaveBeenCalledWith(
782
+ prevViewPresentation
783
+ );
784
+
785
+ expect(mockCornerstoneVolumeViewport.setViewReference).toHaveBeenCalledTimes(1);
786
+ expect(mockCornerstoneVolumeViewport.setViewReference).toHaveBeenCalledWith(
787
+ prevViewReference
788
+ );
789
+
790
+ expect(mockCornerstoneVolumeViewport.render).toHaveBeenCalledTimes(1);
791
+ expect(mockCornerstoneVolumeViewport.render).toHaveBeenCalledWith();
792
+
793
+ expect(mockCornerstoneStackViewport.element.removeEventListener).toHaveBeenCalledTimes(1);
794
+ expect(mockCornerstoneStackViewport.element.removeEventListener).toHaveBeenCalledWith(
795
+ csEnums.Events.VOLUME_VIEWPORT_NEW_VOLUME,
796
+ expect.any(Function)
797
+ );
798
+
799
+ expect(serviceManagerMock.services.viewportGridService.subscribe).toHaveBeenCalledTimes(1);
800
+ expect(serviceManagerMock.services.viewportGridService.subscribe).toHaveBeenCalledWith(
801
+ serviceManagerMock.services.viewportGridService.EVENTS.GRID_STATE_CHANGED,
802
+ expect.any(Function)
803
+ );
804
+
805
+ expect(cstSegmentation.addSegmentationRepresentations).toHaveBeenCalledTimes(1);
806
+ expect(cstSegmentation.addSegmentationRepresentations).toHaveBeenCalledWith(viewportId, [
807
+ {
808
+ type: csToolsEnums.SegmentationRepresentations.Labelmap,
809
+ segmentationId: mockCornerstoneSegmentation.segmentationId,
810
+ config: { colorLUTOrIndex: undefined },
811
+ },
812
+ ]);
813
+
814
+ expect(viewportGridServiceUnsubscribe).toHaveBeenCalledTimes(1);
815
+ expect(viewportGridServiceUnsubscribe).toHaveBeenCalledWith();
816
+ });
817
+
818
+ it('should add a volume segmentation representation to stack viewport through SegmentationService conversion', async () => {
819
+ mockCornerstoneStackViewport.getViewPresentation.mockReturnValueOnce({});
820
+ mockCornerstoneStackViewport.getViewReference.mockReturnValueOnce({});
821
+
822
+ jest
823
+ .spyOn(cstSegmentation.state, 'getSegmentation')
824
+ .mockReturnValue(mockVolumeCornerstoneSegmentation as cstTypes.Segmentation);
825
+ jest
826
+ .spyOn(serviceManagerMock.services.cornerstoneViewportService, 'getCornerstoneViewport')
827
+ // only needed interfaces for the addSegmentationRepresentation call
828
+ .mockReturnValue(mockCornerstoneStackViewport as unknown as csTypes.IStackViewport);
829
+ jest.spyOn(serviceManagerMock.services.viewportGridService, 'getState').mockReturnValue({
830
+ viewports: new Map([
831
+ [
832
+ viewportId,
833
+ { displaySetInstanceUIDs: ['displaySetInstanceUID'], viewportOptions: {} },
834
+ ],
835
+ ]),
836
+ });
837
+
838
+ // awaiting here will wait for publishing of viewportGridService.EVENTS.GRID_STATE_CHANGED (deadlock avoidance)
839
+ const serviceAddSegmentationRepresentationPromise = service.addSegmentationRepresentation(
840
+ viewportId,
841
+ {
842
+ segmentationId: mockCornerstoneSegmentation.segmentationId,
843
+ type: csToolsEnums.SegmentationRepresentations.Labelmap,
844
+ }
845
+ );
846
+
847
+ let _addSegmentationRepresentationCallback;
848
+ const waitForSubscription = async () => {
849
+ let remainingAttempts = 100;
850
+
851
+ while (_addSegmentationRepresentationCallback === undefined && remainingAttempts > 0) {
852
+ _addSegmentationRepresentationCallback = jest.mocked(
853
+ serviceManagerMock.services.viewportGridService.subscribe
854
+ ).mock.calls[0]?.[1];
855
+
856
+ await new Promise(resolve => resolve(void 0));
857
+ remainingAttempts--;
858
+ }
859
+ };
860
+
861
+ await waitForSubscription();
862
+
863
+ // trigger callback being awaited
864
+ _addSegmentationRepresentationCallback();
865
+ await serviceAddSegmentationRepresentationPromise;
866
+
867
+ // guarantee the early exit at handleStackViewportCase (isVolumeSegmentation)
868
+ expect(
869
+ cstSegmentation.state.updateLabelmapSegmentationImageReferences
870
+ ).not.toHaveBeenCalled();
871
+
872
+ expect(
873
+ serviceManagerMock.services.viewportGridService.setDisplaySetsForViewport
874
+ ).toHaveBeenCalledTimes(1);
875
+ expect(
876
+ serviceManagerMock.services.viewportGridService.setDisplaySetsForViewport
877
+ ).toHaveBeenCalledWith({
878
+ viewportId,
879
+ displaySetInstanceUIDs: ['displaySetInstanceUID'],
880
+ viewportOptions: { viewportType: ViewportType.ORTHOGRAPHIC },
881
+ });
882
+
883
+ const volumeViewportNewVolumeHandlerCallback = jest.mocked(
884
+ mockCornerstoneStackViewport.element.addEventListener
885
+ ).mock.calls[0][1];
886
+
887
+ jest
888
+ .spyOn(serviceManagerMock.services.cornerstoneViewportService, 'getCornerstoneViewport')
889
+ // only needed interfaces for the addSegmentationRepresentation call
890
+ .mockReturnValue(mockCornerstoneVolumeViewport as unknown as csTypes.IVolumeViewport);
891
+
892
+ volumeViewportNewVolumeHandlerCallback();
893
+
894
+ expect(
895
+ serviceManagerMock.services.cornerstoneViewportService.getCornerstoneViewport
896
+ ).toHaveBeenCalledTimes(3);
897
+ expect(
898
+ serviceManagerMock.services.cornerstoneViewportService.getCornerstoneViewport
899
+ ).toHaveBeenCalledWith(viewportId);
900
+
901
+ expect(mockCornerstoneStackViewport.element.removeEventListener).toHaveBeenCalledTimes(1);
902
+ expect(mockCornerstoneStackViewport.element.removeEventListener).toHaveBeenCalledWith(
903
+ csEnums.Events.VOLUME_VIEWPORT_NEW_VOLUME,
904
+ expect.any(Function)
905
+ );
906
+
907
+ expect(cstSegmentation.addSegmentationRepresentations).toHaveBeenCalledTimes(1);
908
+ expect(cstSegmentation.addSegmentationRepresentations).toHaveBeenCalledWith(viewportId, [
909
+ {
910
+ type: csToolsEnums.SegmentationRepresentations.Labelmap,
911
+ segmentationId: mockCornerstoneSegmentation.segmentationId,
912
+ config: { colorLUTOrIndex: undefined },
913
+ },
914
+ ]);
915
+ });
916
+ });
917
+
918
+ describe('next (generic) viewport', () => {
919
+ // A native GenericViewport (raw PlanarViewport) exposes setDisplaySets /
920
+ // setDisplaySetPresentation / setViewState, so csUtils.isGenericViewport is
921
+ // true and addSegmentationRepresentation routes to NextSegmentationBackend.
922
+ // It deliberately has NO getViewPresentation: the native path must never reach
923
+ // convertStackToVolumeViewport (the source of the observed
924
+ // "getViewPresentation is not a function" / silent ORTHOGRAPHIC flip).
925
+ const makeNextViewport = () => ({
926
+ element: { addEventListener: jest.fn(), removeEventListener: jest.fn() },
927
+ id: viewportId,
928
+ type: ViewportType.PLANAR_NEXT,
929
+ setDisplaySets: jest.fn(),
930
+ setDisplaySetPresentation: jest.fn(),
931
+ setViewState: jest.fn(),
932
+ });
933
+
934
+ it('renders the labelmap in place and never promotes the viewport (resolver maps in place)', async () => {
935
+ jest
936
+ .spyOn(cstSegmentation.state, 'getSegmentation')
937
+ .mockReturnValue(mockCornerstoneSegmentation as cstTypes.Segmentation);
938
+ jest
939
+ .spyOn(serviceManagerMock.services.cornerstoneViewportService, 'getCornerstoneViewport')
940
+ .mockReturnValue(makeNextViewport() as unknown as csTypes.IStackViewport);
941
+ jest
942
+ .spyOn(cstSegmentation.state, 'updateLabelmapSegmentationImageReferences')
943
+ .mockReturnValue('labelmapImageId');
944
+ jest
945
+ .spyOn(cstSegmentation, 'addSegmentationRepresentations')
946
+ .mockReturnValueOnce(undefined);
947
+ const convertSpy = jest.spyOn(service, 'convertStackToVolumeViewport');
948
+
949
+ const callback = jest.fn();
950
+ service.subscribe(service.EVENTS.SEGMENTATION_REPRESENTATION_MODIFIED, callback);
951
+
952
+ await service.addSegmentationRepresentation(viewportId, {
953
+ segmentationId: mockCornerstoneSegmentation.segmentationId,
954
+ type: csToolsEnums.SegmentationRepresentations.Labelmap,
955
+ });
956
+
957
+ // the native in-place resolver is consulted...
958
+ expect(
959
+ cstSegmentation.state.updateLabelmapSegmentationImageReferences
960
+ ).toHaveBeenCalledWith(viewportId, mockCornerstoneSegmentation.segmentationId);
961
+
962
+ // ...but the viewport is NEVER promoted to an ORTHOGRAPHIC volume viewport
963
+ expect(convertSpy).not.toHaveBeenCalled();
964
+ expect(
965
+ serviceManagerMock.services.viewportGridService.setDisplaySetsForViewport
966
+ ).not.toHaveBeenCalled();
967
+
968
+ // the representation is added in place, synchronously (isConverted === false)
969
+ expect(cstSegmentation.addSegmentationRepresentations).toHaveBeenCalledTimes(1);
970
+ expect(cstSegmentation.addSegmentationRepresentations).toHaveBeenCalledWith(viewportId, [
971
+ {
972
+ type: csToolsEnums.SegmentationRepresentations.Labelmap,
973
+ segmentationId: mockCornerstoneSegmentation.segmentationId,
974
+ config: { colorLUTOrIndex: undefined },
975
+ },
976
+ ]);
977
+
978
+ expect(callback).toHaveBeenCalledWith({
979
+ segmentationId: mockCornerstoneSegmentation.segmentationId,
980
+ });
981
+ });
982
+
983
+ it('never promotes on native even when the in-place resolver cannot map (returns isConverted:false unconditionally)', async () => {
984
+ jest
985
+ .spyOn(cstSegmentation.state, 'getSegmentation')
986
+ .mockReturnValue(mockCornerstoneSegmentation as cstTypes.Segmentation);
987
+ jest
988
+ .spyOn(serviceManagerMock.services.cornerstoneViewportService, 'getCornerstoneViewport')
989
+ .mockReturnValue(makeNextViewport() as unknown as csTypes.IStackViewport);
990
+ // resolver fails (FrameOfReference mismatch / mount-timing race): on legacy this
991
+ // would fall through to convertStackToVolumeViewport; on native it must not.
992
+ jest
993
+ .spyOn(cstSegmentation.state, 'updateLabelmapSegmentationImageReferences')
994
+ .mockReturnValue(undefined);
995
+ jest
996
+ .spyOn(cstSegmentation, 'addSegmentationRepresentations')
997
+ .mockReturnValueOnce(undefined);
998
+ const convertSpy = jest.spyOn(service, 'convertStackToVolumeViewport');
999
+
1000
+ await service.addSegmentationRepresentation(viewportId, {
1001
+ segmentationId: mockCornerstoneSegmentation.segmentationId,
1002
+ type: csToolsEnums.SegmentationRepresentations.Labelmap,
1003
+ });
1004
+
1005
+ expect(convertSpy).not.toHaveBeenCalled();
1006
+ expect(
1007
+ serviceManagerMock.services.viewportGridService.setDisplaySetsForViewport
1008
+ ).not.toHaveBeenCalled();
1009
+ expect(cstSegmentation.addSegmentationRepresentations).toHaveBeenCalledTimes(1);
1010
+ });
1011
+ });
1012
+
1013
+ describe('volume viewport', () => {
1014
+ it('should add a segmentation representation to volume viewport without need for handling', async () => {
1015
+ jest
1016
+ .spyOn(cstSegmentation.state, 'getSegmentation')
1017
+ .mockReturnValue(mockCornerstoneSegmentation as cstTypes.Segmentation);
1018
+ jest
1019
+ .spyOn(serviceManagerMock.services.cornerstoneViewportService, 'getCornerstoneViewport')
1020
+ // only needed interfaces for the addSegmentationRepresentation call
1021
+ .mockReturnValue(mockCornerstoneVolumeViewport as unknown as csTypes.IVolumeViewport);
1022
+ jest
1023
+ .spyOn(cstSegmentation, 'addSegmentationRepresentations')
1024
+ .mockReturnValueOnce(undefined);
1025
+
1026
+ const callback = jest.fn();
1027
+ service.subscribe(service.EVENTS.SEGMENTATION_REPRESENTATION_MODIFIED, callback);
1028
+
1029
+ await service.addSegmentationRepresentation(viewportId, {
1030
+ segmentationId: mockCornerstoneSegmentation.segmentationId,
1031
+ type: csToolsEnums.SegmentationRepresentations.Labelmap,
1032
+ });
1033
+
1034
+ expect(serviceManagerMock.services.viewportGridService.getState).not.toHaveBeenCalled();
1035
+
1036
+ expect(cstSegmentation.addSegmentationRepresentations).toHaveBeenCalledTimes(1);
1037
+ expect(cstSegmentation.addSegmentationRepresentations).toHaveBeenCalledWith(viewportId, [
1038
+ {
1039
+ type: csToolsEnums.SegmentationRepresentations.Surface,
1040
+ segmentationId: mockCornerstoneSegmentation.segmentationId,
1041
+ config: { colorLUTOrIndex: undefined },
1042
+ },
1043
+ ]);
1044
+
1045
+ expect(callback).toHaveBeenCalledTimes(1);
1046
+ expect(callback).toHaveBeenCalledWith({
1047
+ segmentationId: mockCornerstoneSegmentation.segmentationId,
1048
+ });
1049
+ });
1050
+
1051
+ it('should add a surface segmentation representation to volume viewport without need for handling', async () => {
1052
+ jest
1053
+ .spyOn(cstSegmentation.state, 'getSegmentation')
1054
+ .mockReturnValue(mockCornerstoneSegmentation as cstTypes.Segmentation);
1055
+ jest
1056
+ .spyOn(serviceManagerMock.services.cornerstoneViewportService, 'getCornerstoneViewport')
1057
+ // only needed interfaces for the addSegmentationRepresentation call
1058
+ .mockReturnValue({
1059
+ ...mockCornerstoneVolumeViewport,
1060
+ type: ViewportType.VOLUME_3D,
1061
+ } as unknown as csTypes.IVolumeViewport);
1062
+ jest
1063
+ .spyOn(cstSegmentation, 'addSegmentationRepresentations')
1064
+ .mockReturnValueOnce(undefined);
1065
+
1066
+ await service.addSegmentationRepresentation(viewportId, {
1067
+ segmentationId: mockCornerstoneSegmentation.segmentationId,
1068
+ });
1069
+
1070
+ expect(serviceManagerMock.services.viewportGridService.getState).not.toHaveBeenCalled();
1071
+
1072
+ expect(cstSegmentation.addSegmentationRepresentations).toHaveBeenCalledTimes(1);
1073
+ expect(cstSegmentation.addSegmentationRepresentations).toHaveBeenCalledWith(viewportId, [
1074
+ {
1075
+ type: csToolsEnums.SegmentationRepresentations.Surface,
1076
+ segmentationId: mockCornerstoneSegmentation.segmentationId,
1077
+ config: { colorLUTOrIndex: undefined },
1078
+ },
1079
+ ]);
1080
+ });
1081
+
1082
+ it('should add a volume segmentation representation to volume viewport through SegmentationService handling', async () => {
1083
+ mockCornerstoneVolumeViewport.type = ViewportType.ORTHOGRAPHIC;
1084
+ jest
1085
+ .spyOn(cstSegmentation.state, 'getSegmentation')
1086
+ .mockReturnValue(mockVolumeCornerstoneSegmentation as cstTypes.Segmentation);
1087
+ jest
1088
+ .spyOn(serviceManagerMock.services.cornerstoneViewportService, 'getCornerstoneViewport')
1089
+ .mockReturnValue(mockCornerstoneVolumeViewport as unknown as csTypes.IVolumeViewport);
1090
+ jest
1091
+ .spyOn(cstSegmentation, 'addSegmentationRepresentations')
1092
+ .mockReturnValueOnce(undefined);
1093
+
1094
+ const callback = jest.fn();
1095
+ service.subscribe(service.EVENTS.SEGMENTATION_REPRESENTATION_MODIFIED, callback);
1096
+
1097
+ await service.addSegmentationRepresentation(viewportId, {
1098
+ segmentationId: mockCornerstoneSegmentation.segmentationId,
1099
+ type: csToolsEnums.SegmentationRepresentations.Labelmap,
1100
+ });
1101
+
1102
+ expect(serviceManagerMock.services.viewportGridService.getState).not.toHaveBeenCalled();
1103
+
1104
+ expect(mockCornerstoneVolumeViewport.getFrameOfReferenceUID).not.toHaveBeenCalled();
1105
+
1106
+ expect(cstSegmentation.addSegmentationRepresentations).toHaveBeenCalledTimes(1);
1107
+ expect(cstSegmentation.addSegmentationRepresentations).toHaveBeenCalledWith(viewportId, [
1108
+ {
1109
+ type: csToolsEnums.SegmentationRepresentations.Labelmap,
1110
+ segmentationId: mockCornerstoneSegmentation.segmentationId,
1111
+ config: { colorLUTOrIndex: undefined },
1112
+ },
1113
+ ]);
1114
+
1115
+ expect(callback).toHaveBeenCalledTimes(1);
1116
+ expect(callback).toHaveBeenCalledWith({
1117
+ segmentationId: mockCornerstoneSegmentation.segmentationId,
1118
+ });
1119
+ mockCornerstoneVolumeViewport.type = ViewportType.VOLUME_3D;
1120
+ });
1121
+
1122
+ it('should add a volume segmentation representation to volume viewport through SegmentationService handling', async () => {
1123
+ const frameOfReferenceUID = 'frameOfReferenceUID';
1124
+ const imageId = 'imageId';
1125
+
1126
+ mockCornerstoneVolumeViewport.type = ViewportType.ORTHOGRAPHIC;
1127
+ mockCornerstoneVolumeViewport.getFrameOfReferenceUID.mockReturnValueOnce(
1128
+ frameOfReferenceUID
1129
+ );
1130
+
1131
+ jest
1132
+ .spyOn(cstSegmentation.state, 'getSegmentation')
1133
+ .mockReturnValue(mockCornerstoneSegmentation as cstTypes.Segmentation);
1134
+ jest
1135
+ .spyOn(serviceManagerMock.services.cornerstoneViewportService, 'getCornerstoneViewport')
1136
+ .mockReturnValue(mockCornerstoneVolumeViewport as unknown as csTypes.IVolumeViewport);
1137
+ jest
1138
+ .spyOn(cstSegmentation, 'addSegmentationRepresentations')
1139
+ .mockReturnValueOnce(undefined);
1140
+ jest.spyOn(cstSegmentation, 'getLabelmapImageIds').mockReturnValue([imageId]);
1141
+ jest
1142
+ .spyOn(cache, 'getImage')
1143
+ .mockReturnValueOnce({ FrameOfReferenceUID: frameOfReferenceUID } as csTypes.IImage);
1144
+ jest
1145
+ .spyOn(cstSegmentation.helpers, 'convertStackToVolumeLabelmap')
1146
+ .mockReturnValueOnce(undefined);
1147
+
1148
+ const callback = jest.fn();
1149
+ service.subscribe(service.EVENTS.SEGMENTATION_REPRESENTATION_MODIFIED, callback);
1150
+
1151
+ await service.addSegmentationRepresentation(viewportId, {
1152
+ segmentationId: mockCornerstoneSegmentation.segmentationId,
1153
+ type: csToolsEnums.SegmentationRepresentations.Labelmap,
1154
+ });
1155
+
1156
+ expect(mockCornerstoneVolumeViewport.getFrameOfReferenceUID).toHaveBeenCalledTimes(1);
1157
+ expect(mockCornerstoneVolumeViewport.getFrameOfReferenceUID).toHaveBeenCalledWith();
1158
+
1159
+ expect(cstSegmentation.getLabelmapImageIds).toHaveBeenCalledTimes(1);
1160
+ expect(cstSegmentation.getLabelmapImageIds).toHaveBeenCalledWith(
1161
+ mockCornerstoneSegmentation.segmentationId
1162
+ );
1163
+
1164
+ expect(cache.getImage).toHaveBeenCalledTimes(1);
1165
+ expect(cache.getImage).toHaveBeenCalledWith(imageId);
1166
+
1167
+ expect(cstSegmentation.helpers.convertStackToVolumeLabelmap).toHaveBeenCalledTimes(1);
1168
+ expect(cstSegmentation.helpers.convertStackToVolumeLabelmap).toHaveBeenCalledWith(
1169
+ mockCornerstoneSegmentation
1170
+ );
1171
+
1172
+ expect(cstSegmentation.addSegmentationRepresentations).toHaveBeenCalledTimes(1);
1173
+ expect(cstSegmentation.addSegmentationRepresentations).toHaveBeenCalledWith(viewportId, [
1174
+ {
1175
+ type: csToolsEnums.SegmentationRepresentations.Labelmap,
1176
+ segmentationId: mockCornerstoneSegmentation.segmentationId,
1177
+ config: { colorLUTOrIndex: undefined },
1178
+ },
1179
+ ]);
1180
+
1181
+ expect(callback).toHaveBeenCalledTimes(1);
1182
+ expect(callback).toHaveBeenCalledWith({
1183
+ segmentationId: mockCornerstoneSegmentation.segmentationId,
1184
+ });
1185
+ mockCornerstoneVolumeViewport.type = ViewportType.VOLUME_3D;
1186
+ });
1187
+ });
1188
+
1189
+ it('should early return if the viewport is not found', () => {
1190
+ jest
1191
+ .spyOn(cstSegmentation.state, 'getSegmentation')
1192
+ .mockReturnValue(mockCornerstoneSegmentation as cstTypes.Segmentation);
1193
+ jest
1194
+ .spyOn(serviceManagerMock.services.cornerstoneViewportService, 'getCornerstoneViewport')
1195
+ .mockReturnValue(null);
1196
+ jest.spyOn(console, 'warn').mockReturnValue(undefined);
1197
+
1198
+ const callback = jest.fn();
1199
+ service.subscribe(service.EVENTS.SEGMENTATION_REPRESENTATION_MODIFIED, callback);
1200
+
1201
+ service.addSegmentationRepresentation(viewportId, {
1202
+ segmentationId: mockCornerstoneSegmentation.segmentationId,
1203
+ });
1204
+
1205
+ expect(console.warn).toHaveBeenCalledTimes(1);
1206
+ expect(console.warn).toHaveBeenCalledWith(`Viewport with id ${viewportId} not found.`);
1207
+
1208
+ expect(callback).not.toHaveBeenCalled();
1209
+ });
1210
+ });
1211
+
1212
+ describe('createLabelmapForDisplaySet', () => {
1213
+ it('should create a labelmap for a non dynamic volume display set', async () => {
1214
+ const displaySet = {
1215
+ imageIds: ['imageId'],
1216
+ isDynamicVolume: false,
1217
+ SeriesNumber: 1,
1218
+ SeriesDescription: 'Series Description',
1219
+ Modality: 'SEG',
1220
+ } as unknown as AppTypes.DisplaySet;
1221
+
1222
+ jest
1223
+ .spyOn(imageLoader, 'createAndCacheDerivedLabelmapImages')
1224
+ .mockReturnValue([{ imageId: 'imageId' }] as csTypes.IImage[]);
1225
+ jest
1226
+ .spyOn(cstSegmentation.state, 'getSegmentations')
1227
+ .mockReturnValue([{ segmentationId: 'segmentationId' }] as cstTypes.Segmentation[]);
1228
+ jest.spyOn(service, 'addOrUpdateSegmentation').mockReturnValue(undefined);
1229
+
1230
+ const retrievedSegmentationId = await service.createLabelmapForDisplaySet(displaySet);
1231
+
1232
+ expect(imageLoader.createAndCacheDerivedLabelmapImages).toHaveBeenCalledTimes(1);
1233
+ expect(imageLoader.createAndCacheDerivedLabelmapImages).toHaveBeenCalledWith(['imageId']);
1234
+
1235
+ expect(cstSegmentation.state.getSegmentations).toHaveBeenCalledTimes(1);
1236
+ expect(cstSegmentation.state.getSegmentations).toHaveBeenCalledWith();
1237
+
1238
+ expect(service.addOrUpdateSegmentation).toHaveBeenCalledTimes(1);
1239
+ expect(service.addOrUpdateSegmentation).toHaveBeenCalledWith({
1240
+ config: {
1241
+ cachedStats: {
1242
+ info: 'S1: Series Description',
1243
+ },
1244
+ label: 'Segmentation 2',
1245
+ // The caller gave no label, so the service invented this one.
1246
+ labelIsGenerated: true,
1247
+ fallbackLabel: 'S:1 SEG',
1248
+ segments: {
1249
+ '1': {
1250
+ active: true,
1251
+ label: 'Segment 1',
1252
+ },
1253
+ },
1254
+ },
1255
+ representation: {
1256
+ data: {
1257
+ imageIds: ['imageId'],
1258
+ referencedImageIds: ['imageId'],
1259
+ },
1260
+ type: 'Labelmap',
1261
+ },
1262
+ segmentationId: expect.any(String),
1263
+ });
1264
+
1265
+ expect(retrievedSegmentationId).toEqual(expect.any(String));
1266
+ });
1267
+
1268
+ describe('labelIsGenerated', () => {
1269
+ // `storeSegmentation` offers the label of a segmentation as the first name
1270
+ // for a new series, but only when the user chose that name. The service
1271
+ // marks the label that the service invents, so the save can tell the two
1272
+ // apart without a comparison of two strings. The mark goes into the
1273
+ // public input, and `normalizeSegmentationInput` puts the mark on the
1274
+ // segmentation; the service writes nothing onto the state afterwards.
1275
+ const displaySet = {
1276
+ imageIds: ['imageId'],
1277
+ isDynamicVolume: false,
1278
+ SeriesNumber: 1,
1279
+ SeriesDescription: 'Series Description',
1280
+ Modality: 'SEG',
1281
+ } as unknown as AppTypes.DisplaySet;
1282
+
1283
+ const createWith = async (options?: Record<string, unknown>) => {
1284
+ jest
1285
+ .spyOn(imageLoader, 'createAndCacheDerivedLabelmapImages')
1286
+ .mockReturnValue([{ imageId: 'imageId' }] as csTypes.IImage[]);
1287
+ jest
1288
+ .spyOn(cstSegmentation.state, 'getSegmentations')
1289
+ .mockReturnValue([{ segmentationId: 'segmentationId' }] as cstTypes.Segmentation[]);
1290
+ const add = jest.spyOn(service, 'addOrUpdateSegmentation').mockReturnValue(undefined);
1291
+
1292
+ await service.createLabelmapForDisplaySet(displaySet, options);
1293
+ return (add.mock.calls[0][0] as cstTypes.SegmentationPublicInput).config;
1294
+ };
1295
+
1296
+ it('marks a label that the service invents', async () => {
1297
+ const config = await createWith();
1298
+
1299
+ expect(config.label).toBe('Segmentation 2');
1300
+ expect(config.labelIsGenerated).toBe(true);
1301
+ });
1302
+
1303
+ it('marks nothing for a label that the caller gives', async () => {
1304
+ const config = await createWith({ label: 'Liver' });
1305
+
1306
+ expect(config.label).toBe('Liver');
1307
+ expect(config.labelIsGenerated).toBe(false);
1308
+ });
1309
+
1310
+ it('marks a label that the caller reports as generated', async () => {
1311
+ const config = await createWith({ label: 'Segmentation 7', labelIsGenerated: true });
1312
+
1313
+ expect(config.label).toBe('Segmentation 7');
1314
+ expect(config.labelIsGenerated).toBe(true);
1315
+ });
1316
+ });
1317
+
1318
+ it('should create a labelmap for a dynamic volume display set', async () => {
1319
+ const segmentationId = 'segmentationId';
1320
+ const displaySet = {
1321
+ imageIds: ['imageId'],
1322
+ isDynamicVolume: true,
1323
+ SeriesNumber: 1,
1324
+ SeriesDescription: 'Series Description',
1325
+ dynamicVolumeInfo: {
1326
+ timePoints: ['timePoint1', 'timePoint2', 'timePoint3'],
1327
+ },
1328
+ Modality: 'SEG',
1329
+ } as unknown as AppTypes.DisplaySet;
1330
+
1331
+ jest
1332
+ .spyOn(imageLoader, 'createAndCacheDerivedLabelmapImages')
1333
+ .mockReturnValue([{ imageId: 'imageId' }] as csTypes.IImage[]);
1334
+ jest
1335
+ .spyOn(cstSegmentation.state, 'getSegmentations')
1336
+ .mockReturnValue([{ segmentationId }] as cstTypes.Segmentation[]);
1337
+ jest.spyOn(service, 'addOrUpdateSegmentation').mockReturnValue(undefined);
1338
+
1339
+ const options = {
1340
+ segmentationId,
1341
+ segments: {
1342
+ 1: {
1343
+ label: 'Custom Segment 1',
1344
+ active: true,
1345
+ },
1346
+ },
1347
+ FrameOfReferenceUID: 'frameOfReferenceUID',
1348
+ label: 'Segmentation 2',
1349
+ timePointScope: 'each' as const,
1350
+ };
1351
+
1352
+ const retrievedSegmentationId = await service.createLabelmapForDisplaySet(
1353
+ displaySet,
1354
+ options
1355
+ );
1356
+
1357
+ expect(imageLoader.createAndCacheDerivedLabelmapImages).toHaveBeenCalledTimes(1);
1358
+ // One RLE labelmap image for each frame of every time point.
1359
+ expect(imageLoader.createAndCacheDerivedLabelmapImages).toHaveBeenCalledWith(['imageId'], {
1360
+ voxelRepresentation: csEnums.VoxelManagerEnum.RLE,
1361
+ });
1362
+
1363
+ expect(service.addOrUpdateSegmentation).toHaveBeenCalledTimes(1);
1364
+ expect(service.addOrUpdateSegmentation).toHaveBeenCalledWith({
1365
+ config: {
1366
+ cachedStats: {
1367
+ info: 'S1: Series Description',
1368
+ },
1369
+ label: 'Segmentation 2',
1370
+ // The caller gave the label, so the label is not a generated one.
1371
+ labelIsGenerated: false,
1372
+ fallbackLabel: 'S:1 SEG',
1373
+ segments: {
1374
+ '1': {
1375
+ active: true,
1376
+ label: 'Custom Segment 1',
1377
+ },
1378
+ },
1379
+ },
1380
+ representation: {
1381
+ data: {
1382
+ imageIds: ['imageId'],
1383
+ referencedImageIds: ['imageId'],
1384
+ },
1385
+ type: 'Labelmap',
1386
+ },
1387
+ segmentationId: segmentationId,
1388
+ });
1389
+
1390
+ expect(retrievedSegmentationId).toEqual(segmentationId);
1391
+ });
1392
+
1393
+ it('creates one labelmap of the middle time point for a dynamic volume by default', async () => {
1394
+ const displaySet = {
1395
+ imageIds: ['a1', 'a2', 'b1', 'b2', 'c1', 'c2'],
1396
+ isDynamicVolume: true,
1397
+ dynamicVolumeInfo: {
1398
+ timePoints: [
1399
+ ['a1', 'a2'],
1400
+ ['b1', 'b2'],
1401
+ ['c1', 'c2'],
1402
+ ],
1403
+ },
1404
+ } as unknown as AppTypes.DisplaySet;
1405
+ jest
1406
+ .spyOn(imageLoader, 'createAndCacheDerivedLabelmapImages')
1407
+ .mockReturnValue([] as csTypes.IImage[]);
1408
+ jest.spyOn(cstSegmentation.state, 'getSegmentations').mockReturnValue([]);
1409
+ jest.spyOn(service, 'addOrUpdateSegmentation').mockReturnValue(undefined);
1410
+
1411
+ await service.createLabelmapForDisplaySet(displaySet);
1412
+ expect(imageLoader.createAndCacheDerivedLabelmapImages).toHaveBeenLastCalledWith(['b1', 'b2']);
1413
+
1414
+ await service.createLabelmapForDisplaySet(displaySet, { timePointIndex: 2 });
1415
+ expect(imageLoader.createAndCacheDerivedLabelmapImages).toHaveBeenLastCalledWith(['c1', 'c2']);
1416
+ });
1417
+
1418
+ it('should create a dedicated color LUT and remember its index so every viewport representation reuses it', async () => {
1419
+ const displaySet = {
1420
+ imageIds: ['imageId'],
1421
+ isDynamicVolume: false,
1422
+ SeriesNumber: 1,
1423
+ SeriesDescription: 'Series Description',
1424
+ } as unknown as AppTypes.DisplaySet;
1425
+
1426
+ jest
1427
+ .spyOn(imageLoader, 'createAndCacheDerivedLabelmapImages')
1428
+ .mockReturnValue([{ imageId: 'imageId' }] as csTypes.IImage[]);
1429
+ jest.spyOn(cstSegmentation.state, 'getSegmentations').mockReturnValue([]);
1430
+ jest.spyOn(service, 'addOrUpdateSegmentation').mockReturnValue(undefined);
1431
+ jest.mocked(cstSegmentation.state.addColorLUT).mockReturnValue(7);
1432
+
1433
+ const segmentationId = await service.createLabelmapForDisplaySet(displaySet);
1434
+
1435
+ expect(cstSegmentation.state.addColorLUT).toHaveBeenCalledWith([[0, 0, 0, 0]]);
1436
+ expect(service['_segmentationIdToColorLUTIndexMap'].get(segmentationId)).toBe(7);
1437
+ });
1438
+
1439
+ it('should keep the existing color LUT when called again with the same segmentation id', async () => {
1440
+ const displaySet = {
1441
+ imageIds: ['imageId'],
1442
+ isDynamicVolume: false,
1443
+ SeriesNumber: 1,
1444
+ SeriesDescription: 'Series Description',
1445
+ } as unknown as AppTypes.DisplaySet;
1446
+
1447
+ jest
1448
+ .spyOn(imageLoader, 'createAndCacheDerivedLabelmapImages')
1449
+ .mockReturnValue([{ imageId: 'imageId' }] as csTypes.IImage[]);
1450
+ jest.spyOn(cstSegmentation.state, 'getSegmentations').mockReturnValue([]);
1451
+ jest.spyOn(service, 'addOrUpdateSegmentation').mockReturnValue(undefined);
1452
+ jest.mocked(cstSegmentation.state.addColorLUT).mockReturnValueOnce(7).mockReturnValueOnce(8);
1453
+
1454
+ const segmentationId = await service.createLabelmapForDisplaySet(displaySet);
1455
+ await service.createLabelmapForDisplaySet(displaySet, { segmentationId });
1456
+
1457
+ // Updating an existing segmentation must not strand the representations
1458
+ // already rendering it on the previous LUT.
1459
+ expect(cstSegmentation.state.addColorLUT).toHaveBeenCalledTimes(1);
1460
+ expect(service['_segmentationIdToColorLUTIndexMap'].get(segmentationId)).toBe(7);
1461
+ });
1462
+ });
1463
+
1464
+ describe('createSegmentationForSEGDisplaySet', () => {
1465
+ it('should throw an error if the type is not labelmap', async () => {
1466
+ await expect(
1467
+ service.createSegmentationForSEGDisplaySet(
1468
+ {},
1469
+ {
1470
+ type: csToolsEnums.SegmentationRepresentations.Contour,
1471
+ }
1472
+ )
1473
+ ).rejects.toThrow('Only labelmap type is supported for SEG display sets right now');
1474
+ });
1475
+
1476
+ it('should throw and error if the labelmap images are not found', async () => {
1477
+ await expect(
1478
+ service.createSegmentationForSEGDisplaySet({
1479
+ labelMapImages: [],
1480
+ })
1481
+ ).rejects.toThrow('SEG reading failed');
1482
+ });
1483
+
1484
+ it('should throw an error if the referenced display set is not found', async () => {
1485
+ jest
1486
+ .spyOn(serviceManagerMock.services.displaySetService, 'getDisplaySetByUID')
1487
+ .mockReturnValue({
1488
+ instances: [],
1489
+ });
1490
+
1491
+ await expect(
1492
+ service.createSegmentationForSEGDisplaySet({
1493
+ displaySetInstanceUID: 'display-set-uid',
1494
+ referencedDisplaySetInstanceUID: 'non-existent-display-set-uid',
1495
+ labelMapImages: [{}, {}],
1496
+ })
1497
+ ).rejects.toThrow('No instances were provided for the referenced display set of the SEG');
1498
+ });
1499
+
1500
+ it('it should create a segmentation for a SEG display set', async () => {
1501
+ const segmentationId = 'segmentationId';
1502
+
1503
+ const voxelManager = {
1504
+ getScalarData: jest.fn().mockReturnValue([1, 0, 0]),
1505
+ setScalarData: jest.fn(),
1506
+ };
1507
+
1508
+ const segDisplaySet = {
1509
+ centroids: new Map([
1510
+ [0, { image: { x: 0, y: 0, z: 0 }, world: { x: 0, y: 0, z: 0 } }],
1511
+ [2, { image: { x: 200, y: 200, z: 200 }, world: { x: 200, y: 200, z: 200 } }],
1512
+ ]),
1513
+ displaySetInstanceUID: 'display-set-uid',
1514
+ referencedDisplaySetInstanceUID: 'existent-display-set-uid',
1515
+ labelMapImages: [
1516
+ { imageId: 'imageId1', referencedImageId: 'referencedImageId1', voxelManager },
1517
+ { imageId: 'imageId2', referencedImageId: 'referencedImageId2', voxelManager },
1518
+ ],
1519
+ segMetadata: {
1520
+ data: [
1521
+ {},
1522
+ {
1523
+ SegmentedPropertyCategoryCodeSequence: {
1524
+ CodeMeaning: 'Segmented Property Category Code Sequence',
1525
+ },
1526
+ SegmentNumber: '1',
1527
+ SegmentLabel: 'Segment 1',
1528
+ SegmentAlgorithmType: 'MANUAL',
1529
+ SegmentAlgorithmName: 'OHIF Brush',
1530
+ SegmentedPropertyTypeCodeSequence: {
1531
+ CodeMeaning: 'Segmented Property Category Code Sequence',
1532
+ },
1533
+ rgba: [255, 0, 0, 255],
1534
+ },
1535
+ {
1536
+ SegmentedPropertyCategoryCodeSequence: {
1537
+ CodeMeaning: 'Segmented Property Category Code Sequence',
1538
+ },
1539
+ SegmentNumber: '2',
1540
+ SegmentAlgorithmType: 'MANUAL',
1541
+ SegmentAlgorithmName: 'OHIF Brush',
1542
+ SegmentedPropertyTypeCodeSequence: {
1543
+ CodeMeaning: 'Segmented Property Type Code Sequence',
1544
+ },
1545
+ rgba: [0, 255, 0, 255],
1546
+ },
1547
+ ],
1548
+ },
1549
+ SeriesDate: '2025-01-01',
1550
+ SeriesDescription: 'Series Description',
1551
+ Modality: 'SEG',
1552
+ SeriesNumber: 1,
1553
+ };
1554
+
1555
+ const referencedDisplaySet = {
1556
+ instances: [{ imageId: 'referencedImageId1' }, { imageId: 'referencedImageId2' }],
1557
+ };
1558
+
1559
+ jest
1560
+ .spyOn(serviceManagerMock.services.displaySetService, 'getDisplaySetByUID')
1561
+ .mockReturnValue(referencedDisplaySet);
1562
+ // @ts-expect-error - jest can't handle Array.prototype.flat typing
1563
+ jest.spyOn(Array.prototype, 'flat');
1564
+ jest.spyOn(metaData, 'get').mockReturnValue({});
1565
+ jest.spyOn(service, 'addOrUpdateSegmentation').mockReturnValue(undefined);
1566
+
1567
+ const callback = jest.fn();
1568
+ service.subscribe(service.EVENTS.SEGMENTATION_LOADING_COMPLETE, callback);
1569
+
1570
+ const retrievedSegmentationId = await service.createSegmentationForSEGDisplaySet(
1571
+ segDisplaySet,
1572
+ {
1573
+ type: csToolsEnums.SegmentationRepresentations.Labelmap,
1574
+ segmentationId,
1575
+ }
1576
+ );
1577
+
1578
+ expect(
1579
+ serviceManagerMock.services.displaySetService.getDisplaySetByUID
1580
+ ).toHaveBeenCalledTimes(1);
1581
+ expect(serviceManagerMock.services.displaySetService.getDisplaySetByUID).toHaveBeenCalledWith(
1582
+ 'existent-display-set-uid'
1583
+ );
1584
+
1585
+ expect(Array.prototype.flat).toHaveBeenCalledTimes(1);
1586
+
1587
+ expect(metaData.get).toHaveBeenCalledTimes(2);
1588
+ expect(metaData.get).toHaveBeenCalledWith('instance', 'referencedImageId1');
1589
+ expect(metaData.get).toHaveBeenCalledWith('instance', 'referencedImageId2');
1590
+
1591
+ expect(voxelManager.getScalarData).toHaveBeenCalledTimes(2);
1592
+ expect(voxelManager.getScalarData).toHaveBeenCalledWith();
1593
+ expect(voxelManager.setScalarData).toHaveBeenCalledTimes(2);
1594
+ expect(voxelManager.setScalarData).toHaveBeenCalledWith([1, 0, 0]);
1595
+
1596
+ expect(cstSegmentation.state.addColorLUT).toHaveBeenCalledTimes(1);
1597
+ expect(cstSegmentation.state.addColorLUT).toHaveBeenCalledWith([
1598
+ [0, 0, 0, 0],
1599
+ [255, 0, 0, 255],
1600
+ [0, 255, 0, 255],
1601
+ ]);
1602
+
1603
+ expect(callback).toHaveBeenCalledTimes(1);
1604
+ expect(callback).toHaveBeenCalledWith({
1605
+ segmentationId,
1606
+ segDisplaySet,
1607
+ });
1608
+
1609
+ const expectedSegmentation = {
1610
+ config: {
1611
+ label: segDisplaySet.SeriesDescription,
1612
+ fallbackLabel: 'S:1 SEG',
1613
+ segments: {
1614
+ '1': {
1615
+ active: false,
1616
+ cachedStats: {
1617
+ algorithmName: 'OHIF Brush',
1618
+ algorithmType: 'MANUAL',
1619
+ category: 'Segmented Property Category Code Sequence',
1620
+ center: {
1621
+ image: [0, 0, 0],
1622
+ world: [0, 0, 0],
1623
+ },
1624
+ modifiedTime: '2025-01-01',
1625
+ type: 'Segmented Property Category Code Sequence',
1626
+ },
1627
+ label: 'Segment 1',
1628
+ locked: false,
1629
+ segmentIndex: 1,
1630
+ },
1631
+ '2': {
1632
+ active: false,
1633
+ cachedStats: {
1634
+ algorithmName: 'OHIF Brush',
1635
+ algorithmType: 'MANUAL',
1636
+ category: 'Segmented Property Category Code Sequence',
1637
+ center: {
1638
+ image: [200, 200, 200],
1639
+ world: [200, 200, 200],
1640
+ },
1641
+ modifiedTime: '2025-01-01',
1642
+ type: 'Segmented Property Type Code Sequence',
1643
+ },
1644
+ label: 'Segment 2',
1645
+ locked: false,
1646
+ segmentIndex: 2,
1647
+ },
1648
+ },
1649
+ },
1650
+ representation: {
1651
+ data: {
1652
+ imageIds: ['imageId1', 'imageId2'],
1653
+ referencedImageIds: ['referencedImageId1', 'referencedImageId2'],
1654
+ },
1655
+ type: csToolsEnums.SegmentationRepresentations.Labelmap,
1656
+ },
1657
+ segmentationId,
1658
+ };
1659
+
1660
+ expect(service.addOrUpdateSegmentation).toHaveBeenCalledTimes(1);
1661
+ expect(service.addOrUpdateSegmentation).toHaveBeenCalledWith(expectedSegmentation);
1662
+
1663
+ const expectedSegDisplaySet = {
1664
+ ...segDisplaySet,
1665
+ firstSegmentedSliceImageId: 'referencedImageId1',
1666
+ imageIds: ['imageId1', 'imageId2'],
1667
+ images: [
1668
+ {
1669
+ imageId: 'imageId1',
1670
+ referencedImageId: 'referencedImageId1',
1671
+ voxelManager,
1672
+ },
1673
+ {
1674
+ imageId: 'imageId2',
1675
+ referencedImageId: 'referencedImageId2',
1676
+ voxelManager,
1677
+ },
1678
+ ],
1679
+ isLoaded: true,
1680
+ labelMapImages: [
1681
+ {
1682
+ imageId: 'imageId1',
1683
+ referencedImageId: 'referencedImageId1',
1684
+ voxelManager,
1685
+ },
1686
+ {
1687
+ imageId: 'imageId2',
1688
+ referencedImageId: 'referencedImageId2',
1689
+ voxelManager,
1690
+ },
1691
+ ],
1692
+ };
1693
+
1694
+ expect(segDisplaySet).toEqual(expectedSegDisplaySet);
1695
+
1696
+ expect(retrievedSegmentationId).toEqual(segmentationId);
1697
+ });
1698
+
1699
+ describe('overlap / useSliceRendering (next backend)', () => {
1700
+ const segmentationId = 'segmentationId';
1701
+
1702
+ // The session flag selects the seg-backend lane at SEG-load; reset it so it
1703
+ // never leaks into the legacy-path tests that follow.
1704
+ afterEach(() => {
1705
+ setNextViewportsEnabled(false);
1706
+ });
1707
+
1708
+ const segMetadata = {
1709
+ data: [
1710
+ {},
1711
+ { SegmentNumber: '1', SegmentLabel: 'Segment 1', rgba: [255, 0, 0, 255] },
1712
+ { SegmentNumber: '2', SegmentLabel: 'Segment 2', rgba: [0, 255, 0, 255] },
1713
+ ],
1714
+ };
1715
+ const centroids = new Map([
1716
+ [1, { image: { x: 0, y: 0, z: 0 }, world: { x: 0, y: 0, z: 0 } }],
1717
+ [2, { image: { x: 1, y: 1, z: 1 }, world: { x: 1, y: 1, z: 1 } }],
1718
+ ]);
1719
+
1720
+ // labelMapImages is the adapter's array-of-GROUPS (one conflict-free group per
1721
+ // overlap layer). Two groups whose voxels carry values {1} and {2} respectively.
1722
+ const makeOverlapGroups = () => {
1723
+ const vm0 = { getScalarData: jest.fn().mockReturnValue([1, 0]), setScalarData: jest.fn() };
1724
+ const vm1 = { getScalarData: jest.fn().mockReturnValue([0, 2]), setScalarData: jest.fn() };
1725
+ return [
1726
+ [
1727
+ { imageId: 'g0i1', referencedImageId: 'r1', voxelManager: vm0 },
1728
+ { imageId: 'g0i2', referencedImageId: 'r2', voxelManager: vm0 },
1729
+ ],
1730
+ [
1731
+ { imageId: 'g1i1', referencedImageId: 'r1', voxelManager: vm1 },
1732
+ { imageId: 'g1i2', referencedImageId: 'r2', voxelManager: vm1 },
1733
+ ],
1734
+ ];
1735
+ };
1736
+
1737
+ const makeSegDisplaySet = (labelMapImages, overlappingSegments) => ({
1738
+ centroids,
1739
+ displaySetInstanceUID: 'display-set-uid',
1740
+ referencedDisplaySetInstanceUID: 'existent-display-set-uid',
1741
+ labelMapImages,
1742
+ overlappingSegments,
1743
+ segMetadata,
1744
+ SeriesDate: '2025-01-01',
1745
+ SeriesDescription: 'Series Description',
1746
+ Modality: 'SEG',
1747
+ SeriesNumber: 1,
1748
+ });
1749
+
1750
+ const primeMocks = () => {
1751
+ jest
1752
+ .spyOn(serviceManagerMock.services.displaySetService, 'getDisplaySetByUID')
1753
+ .mockReturnValue({ instances: [{ imageId: 'r1' }, { imageId: 'r2' }] });
1754
+ jest.spyOn(metaData, 'get').mockReturnValue({});
1755
+ jest.spyOn(service, 'addOrUpdateSegmentation').mockReturnValue(undefined);
1756
+ };
1757
+
1758
+ it('flag ON + overlapping SEG builds one labelmap layer per group + segmentBindings', async () => {
1759
+ setNextViewportsEnabled(true);
1760
+ primeMocks();
1761
+
1762
+ await service.createSegmentationForSEGDisplaySet(
1763
+ makeSegDisplaySet(makeOverlapGroups(), true),
1764
+ { type: csToolsEnums.SegmentationRepresentations.Labelmap, segmentationId }
1765
+ );
1766
+
1767
+ const seg = jest.mocked(service.addOrUpdateSegmentation).mock.calls[0][0];
1768
+ const data = seg.representation.data as Record<string, any>;
1769
+
1770
+ // one labelmap layer per conflict-free group, under ONE segmentationId
1771
+ expect(Object.keys(data.labelmaps)).toEqual([
1772
+ 'segmentationId-storage-0',
1773
+ 'segmentationId-storage-1',
1774
+ ]);
1775
+ expect(data.labelmaps['segmentationId-storage-0'].imageIds).toEqual(['g0i1', 'g0i2']);
1776
+ expect(data.labelmaps['segmentationId-storage-1'].imageIds).toEqual(['g1i1', 'g1i2']);
1777
+ expect(data.labelmaps['segmentationId-storage-0'].storageKind).toBe('stack');
1778
+
1779
+ // segment->layer bindings recovered from the distinct non-zero voxel values
1780
+ expect(data.segmentBindings).toEqual({
1781
+ 1: { labelmapId: 'segmentationId-storage-0', labelValue: 1 },
1782
+ 2: { labelmapId: 'segmentationId-storage-1', labelValue: 2 },
1783
+ });
1784
+ expect(data.primaryLabelmapId).toBe('segmentationId-storage-0');
1785
+ // flattened list retained for legacy singular readers
1786
+ expect(data.imageIds).toEqual(['g0i1', 'g0i2', 'g1i1', 'g1i2']);
1787
+ });
1788
+
1789
+ it('flag ON + non-overlapping SEG stays a single layer (no multi-layer map)', async () => {
1790
+ setNextViewportsEnabled(true);
1791
+ primeMocks();
1792
+
1793
+ const vm = { getScalarData: jest.fn().mockReturnValue([1, 0]), setScalarData: jest.fn() };
1794
+ const singleGroup = [
1795
+ [
1796
+ { imageId: 'i1', referencedImageId: 'r1', voxelManager: vm },
1797
+ { imageId: 'i2', referencedImageId: 'r2', voxelManager: vm },
1798
+ ],
1799
+ ];
1800
+
1801
+ await service.createSegmentationForSEGDisplaySet(makeSegDisplaySet(singleGroup, false), {
1802
+ type: csToolsEnums.SegmentationRepresentations.Labelmap,
1803
+ segmentationId,
1804
+ });
1805
+
1806
+ const seg = jest.mocked(service.addOrUpdateSegmentation).mock.calls[0][0];
1807
+ const data = seg.representation.data as Record<string, any>;
1808
+ expect(data.labelmaps).toBeUndefined();
1809
+ expect(data.segmentBindings).toBeUndefined();
1810
+ expect(data.imageIds).toEqual(['i1', 'i2']);
1811
+ });
1812
+
1813
+ it('flag OFF + overlapping SEG collapses to a single flattened layer (legacy byte-identical)', async () => {
1814
+ // flag stays off (default)
1815
+ primeMocks();
1816
+
1817
+ await service.createSegmentationForSEGDisplaySet(
1818
+ makeSegDisplaySet(makeOverlapGroups(), true),
1819
+ { type: csToolsEnums.SegmentationRepresentations.Labelmap, segmentationId }
1820
+ );
1821
+
1822
+ const seg = jest.mocked(service.addOrUpdateSegmentation).mock.calls[0][0];
1823
+ const data = seg.representation.data as Record<string, any>;
1824
+ expect(data.labelmaps).toBeUndefined();
1825
+ expect(data.imageIds).toEqual(['g0i1', 'g0i2', 'g1i1', 'g1i2']);
1826
+ });
1827
+ });
1828
+ });
1829
+
1830
+ describe('createSegmentationForRTDisplaySet', () => {
1831
+ it('should throw an error if the type is not contour', async () => {
1832
+ await expect(
1833
+ service.createSegmentationForRTDisplaySet(
1834
+ {
1835
+ modality: 'RTSTRUCT',
1836
+ },
1837
+ {
1838
+ type: csToolsEnums.SegmentationRepresentations.Labelmap,
1839
+ }
1840
+ )
1841
+ ).rejects.toThrow('Only contour type is supported for RT display sets right now');
1842
+ });
1843
+
1844
+ it('should throw an error if the structureSet is not loaded', async () => {
1845
+ await expect(
1846
+ service.createSegmentationForRTDisplaySet(
1847
+ {
1848
+ modality: 'RTSTRUCT',
1849
+ displaySetInstanceUID: 'display-set-uid',
1850
+ },
1851
+ {
1852
+ type: csToolsEnums.SegmentationRepresentations.Contour,
1853
+ }
1854
+ )
1855
+ ).rejects.toThrow(
1856
+ 'To create the contours from RT displaySet, the displaySet should be loaded first. You can perform rtDisplaySet.load() before calling this method.'
1857
+ );
1858
+ });
1859
+
1860
+ it('should throw and error if structureSet does not contain any ROIContours', async () => {
1861
+ const rtStructDisplaySet = {
1862
+ modality: 'RTSTRUCT',
1863
+ displaySetInstanceUID: 'display-set-uid',
1864
+ referencedDisplaySetInstanceUID: 'existent-display-set-uid',
1865
+ structureSet: {
1866
+ ReferencedSOPInstanceUIDsSet: new Set(['referencedImageId1', 'referencedImageId2']),
1867
+ ROIContours: [],
1868
+ },
1869
+ };
1870
+
1871
+ const referencedDisplaySet = {
1872
+ instances: [{ imageId: 'referencedImageId1' }, { imageId: 'referencedImageId2' }],
1873
+ };
1874
+
1875
+ jest
1876
+ .spyOn(serviceManagerMock.services.displaySetService, 'getDisplaySetByUID')
1877
+ .mockReturnValue(referencedDisplaySet);
1878
+
1879
+ await expect(
1880
+ service.createSegmentationForRTDisplaySet(rtStructDisplaySet, {
1881
+ type: csToolsEnums.SegmentationRepresentations.Contour,
1882
+ })
1883
+ ).rejects.toThrow(
1884
+ 'The structureSet does not contain any ROIContours. Please ensure the structureSet is loaded first.'
1885
+ );
1886
+
1887
+ expect(
1888
+ serviceManagerMock.services.displaySetService.getDisplaySetByUID
1889
+ ).toHaveBeenCalledTimes(1);
1890
+ expect(serviceManagerMock.services.displaySetService.getDisplaySetByUID).toHaveBeenCalledWith(
1891
+ 'existent-display-set-uid'
1892
+ );
1893
+ });
1894
+
1895
+ it('should create a segmentation for a RTSTRUCT display set', async () => {
1896
+ const segmentationId = 'segmentationId';
1897
+ const rtStructDisplaySet = {
1898
+ Modality: 'RTSTRUCT',
1899
+ displaySetInstanceUID: 'display-set-uid',
1900
+ referencedDisplaySetInstanceUID: 'existent-display-set-uid',
1901
+ SeriesDate: '2025-01-01',
1902
+ SeriesDescription: 'Series Description',
1903
+ structureSet: {
1904
+ ReferencedSOPInstanceUIDsSet: new Set(['referencedIsmageId1', 'referencedImageId2']),
1905
+ ROIContours: [{}, {}, {}],
1906
+ frameOfReferenceUID: 'frameOfReferenceUID',
1907
+ },
1908
+ SeriesNumber: 1,
1909
+ };
1910
+
1911
+ const referencedDisplaySet = {
1912
+ instances: [{ imageId: 'referencedImageId1' }, { imageId: 'referencedImageId2' }],
1913
+ imageIds: ['referencedImageId1', 'referencedImageId2'],
1914
+ };
1915
+
1916
+ const allRTStructData = [
1917
+ {
1918
+ data: {},
1919
+ id: 'id3',
1920
+ color: [255, 0, 0, 255],
1921
+ group: 'group3',
1922
+ segmentIndex: 3,
1923
+ geometryId: 'geometryId3',
1924
+ },
1925
+ {
1926
+ data: {},
1927
+ id: 'id2',
1928
+ color: [0, 255, 0, 255],
1929
+ group: 'group2',
1930
+ segmentIndex: 2,
1931
+ geometryId: 'geometryId2',
1932
+ },
1933
+ {
1934
+ data: {},
1935
+ id: 'id1',
1936
+ color: [0, 0, 255, 255],
1937
+ group: 'group1',
1938
+ segmentIndex: 1,
1939
+ geometryId: 'geometryId1',
1940
+ },
1941
+ ];
1942
+
1943
+ jest
1944
+ .spyOn(serviceManagerMock.services.displaySetService, 'getDisplaySetByUID')
1945
+ .mockReturnValue(referencedDisplaySet);
1946
+ jest
1947
+ .spyOn(MapROIContoursToRTStructData, 'mapROIContoursToRTStructData')
1948
+ .mockReturnValue(allRTStructData);
1949
+ jest.spyOn(service, 'addOrUpdateSegmentation').mockReturnValue(undefined);
1950
+ jest.spyOn(geometryLoader, 'createAndCacheGeometry').mockReturnValue({
1951
+ // @ts-expect-error - only mocking needed properties
1952
+ data: { centroid: [0, 0, 0] },
1953
+ });
1954
+
1955
+ const segmentLoadingCompleteCallback = jest.fn();
1956
+ service.subscribe(service.EVENTS.SEGMENT_LOADING_COMPLETE, segmentLoadingCompleteCallback);
1957
+
1958
+ const segmentationLoadingCompleteCallback = jest.fn();
1959
+ service.subscribe(
1960
+ service.EVENTS.SEGMENTATION_LOADING_COMPLETE,
1961
+ segmentationLoadingCompleteCallback
1962
+ );
1963
+
1964
+ const retrievedSegmentationId = await service.createSegmentationForRTDisplaySet(
1965
+ rtStructDisplaySet,
1966
+ {
1967
+ type: csToolsEnums.SegmentationRepresentations.Contour,
1968
+ segmentationId,
1969
+ }
1970
+ );
1971
+
1972
+ expect(MapROIContoursToRTStructData.mapROIContoursToRTStructData).toHaveBeenCalledTimes(1);
1973
+ expect(MapROIContoursToRTStructData.mapROIContoursToRTStructData).toHaveBeenCalledWith(
1974
+ rtStructDisplaySet.structureSet,
1975
+ rtStructDisplaySet.displaySetInstanceUID
1976
+ );
1977
+
1978
+ expect(geometryLoader.createAndCacheGeometry).toHaveBeenCalledTimes(3);
1979
+ allRTStructData.forEach(data => {
1980
+ expect(geometryLoader.createAndCacheGeometry).toHaveBeenCalledWith(data.geometryId, {
1981
+ geometryData: {
1982
+ data: data.data,
1983
+ id: data.id,
1984
+ color: data.color,
1985
+ frameOfReferenceUID: rtStructDisplaySet.structureSet.frameOfReferenceUID,
1986
+ segmentIndex: data.segmentIndex,
1987
+ },
1988
+ type: csEnums.GeometryType.CONTOUR,
1989
+ });
1990
+ });
1991
+
1992
+ expect(segmentLoadingCompleteCallback).toHaveBeenCalledTimes(3);
1993
+ expect(segmentLoadingCompleteCallback).toHaveBeenCalledWith({
1994
+ percentComplete: expect.any(Number),
1995
+ numSegments: 3,
1996
+ });
1997
+
1998
+ expect(cstSegmentation.state.addColorLUT).toHaveBeenCalledTimes(1);
1999
+ expect(cstSegmentation.state.addColorLUT).toHaveBeenCalledWith([
2000
+ [0, 0, 0, 0],
2001
+ [0, 0, 255, 255],
2002
+ [0, 255, 0, 255],
2003
+ [255, 0, 0, 255],
2004
+ ]);
2005
+
2006
+ expect(segmentationLoadingCompleteCallback).toHaveBeenCalledTimes(1);
2007
+ expect(segmentationLoadingCompleteCallback).toHaveBeenCalledWith({
2008
+ segmentationId,
2009
+ rtDisplaySet: rtStructDisplaySet,
2010
+ });
2011
+
2012
+ const expectedSegmentation = {
2013
+ config: {
2014
+ label: rtStructDisplaySet.SeriesDescription,
2015
+ fallbackLabel: 'S:1 RTSTRUCT',
2016
+ segments: {
2017
+ '1': {
2018
+ active: false,
2019
+ cachedStats: {
2020
+ center: {
2021
+ world: [0, 0, 0],
2022
+ },
2023
+ modifiedTime: rtStructDisplaySet.SeriesDate,
2024
+ },
2025
+ group: 'group1',
2026
+ label: 'id1',
2027
+ locked: false,
2028
+ segmentIndex: 1,
2029
+ },
2030
+ '2': {
2031
+ active: false,
2032
+ cachedStats: {
2033
+ center: {
2034
+ world: [0, 0, 0],
2035
+ },
2036
+ modifiedTime: rtStructDisplaySet.SeriesDate,
2037
+ },
2038
+ group: 'group2',
2039
+ label: 'id2',
2040
+ locked: false,
2041
+ segmentIndex: 2,
2042
+ },
2043
+ '3': {
2044
+ active: false,
2045
+ cachedStats: {
2046
+ center: {
2047
+ world: [0, 0, 0],
2048
+ },
2049
+ modifiedTime: rtStructDisplaySet.SeriesDate,
2050
+ },
2051
+ group: 'group3',
2052
+ label: 'id3',
2053
+ locked: false,
2054
+ segmentIndex: 3,
2055
+ },
2056
+ },
2057
+ },
2058
+ representation: {
2059
+ data: {
2060
+ geometryIds: ['geometryId1', 'geometryId2', 'geometryId3'],
2061
+ },
2062
+ type: csToolsEnums.SegmentationRepresentations.Contour,
2063
+ },
2064
+ segmentationId,
2065
+ };
2066
+ expect(service.addOrUpdateSegmentation).toHaveBeenCalledTimes(1);
2067
+ expect(service.addOrUpdateSegmentation).toHaveBeenCalledWith(expectedSegmentation);
2068
+
2069
+ expect(retrievedSegmentationId).toEqual(segmentationId);
2070
+
2071
+ const expectedRtStructDisplaySet = {
2072
+ ...rtStructDisplaySet,
2073
+ isLoaded: true,
2074
+ };
2075
+
2076
+ expect(rtStructDisplaySet).toEqual(expectedRtStructDisplaySet);
2077
+ });
2078
+
2079
+ it('should ignore when a segment fails to initialize', async () => {
2080
+ const segmentationId = 'segmentationId';
2081
+ const rtStructDisplaySet = {
2082
+ modality: 'RTSTRUCT',
2083
+ displaySetInstanceUID: 'display-set-uid',
2084
+ referencedDisplaySetInstanceUID: 'existent-display-set-uid',
2085
+ SeriesDate: '2025-01-01',
2086
+ SeriesDescription: 'Series Description',
2087
+ structureSet: {
2088
+ ReferencedSOPInstanceUIDsSet: new Set(['referencedIsmageId1', 'referencedImageId2']),
2089
+ ROIContours: [{}, {}, {}],
2090
+ frameOfReferenceUID: 'frameOfReferenceUID',
2091
+ },
2092
+ };
2093
+
2094
+ const referencedDisplaySet = {
2095
+ instances: [{ imageId: 'referencedImageId1' }, { imageId: 'referencedImageId2' }],
2096
+ };
2097
+
2098
+ const allRTStructData = [
2099
+ {
2100
+ data: {},
2101
+ id: 'id3',
2102
+ color: [255, 0, 0, 255],
2103
+ group: 'group3',
2104
+ segmentIndex: 3,
2105
+ geometryId: 'geometryId3',
2106
+ },
2107
+ ];
2108
+
2109
+ jest
2110
+ .spyOn(serviceManagerMock.services.displaySetService, 'getDisplaySetByUID')
2111
+ .mockReturnValue(referencedDisplaySet);
2112
+ jest
2113
+ .spyOn(MapROIContoursToRTStructData, 'mapROIContoursToRTStructData')
2114
+ .mockReturnValue(allRTStructData);
2115
+ jest
2116
+ .spyOn(geometryLoader, 'createAndCacheGeometry')
2117
+ .mockRejectedValue(new Error('Segment Initialization Error') as never);
2118
+ jest.spyOn(console, 'warn').mockImplementation(() => {});
2119
+ jest.spyOn(service, 'addOrUpdateSegmentation').mockReturnValue(undefined);
2120
+
2121
+ const segmentLoadingCompleteCallback = jest.fn();
2122
+ service.subscribe(service.EVENTS.SEGMENT_LOADING_COMPLETE, segmentLoadingCompleteCallback);
2123
+
2124
+ const segmentationLoadingCompleteCallback = jest.fn();
2125
+ service.subscribe(
2126
+ service.EVENTS.SEGMENTATION_LOADING_COMPLETE,
2127
+ segmentationLoadingCompleteCallback
2128
+ );
2129
+
2130
+ await expect(
2131
+ service.createSegmentationForRTDisplaySet(rtStructDisplaySet, {
2132
+ type: csToolsEnums.SegmentationRepresentations.Contour,
2133
+ segmentationId,
2134
+ })
2135
+ ).resolves.not.toThrow();
2136
+
2137
+ expect(segmentLoadingCompleteCallback).not.toHaveBeenCalled();
2138
+
2139
+ expect(console.warn).toHaveBeenCalledTimes(1);
2140
+ expect(console.warn).toHaveBeenCalledWith(
2141
+ `Error initializing contour for segment ${allRTStructData[0].segmentIndex}:`,
2142
+ expect.any(Error)
2143
+ );
2144
+
2145
+ expect(segmentationLoadingCompleteCallback).toHaveBeenCalledTimes(1);
2146
+
2147
+ expect(service.addOrUpdateSegmentation).toHaveBeenCalledTimes(1);
2148
+ });
2149
+ });
2150
+
2151
+ describe('addOrUpdateSegmentation', () => {
2152
+ it('should add new segmentation if it does not exist', () => {
2153
+ const segmentationId = 'segmentationId';
2154
+ const segmentationData = {
2155
+ segmentationId,
2156
+ representation: {
2157
+ type: csToolsEnums.SegmentationRepresentations.Labelmap,
2158
+ data: {},
2159
+ },
2160
+ config: {
2161
+ label: 'Segmentation 1',
2162
+ },
2163
+ };
2164
+
2165
+ jest.spyOn(cstSegmentation.state, 'getSegmentation').mockReturnValue(undefined);
2166
+ jest.spyOn(cstSegmentation, 'addSegmentations').mockReturnValue(undefined);
2167
+
2168
+ service.addOrUpdateSegmentation(segmentationData);
2169
+
2170
+ expect(cstSegmentation.state.getSegmentation).toHaveBeenCalledTimes(1);
2171
+ expect(cstSegmentation.state.getSegmentation).toHaveBeenCalledWith(segmentationId);
2172
+
2173
+ expect(cstSegmentation.addSegmentations).toHaveBeenCalledTimes(1);
2174
+ expect(cstSegmentation.addSegmentations).toHaveBeenCalledWith([segmentationData]);
2175
+ });
2176
+
2177
+ it('should update existing segmentation if it exists', () => {
2178
+ const segmentationId = 'segmentationId';
2179
+ const segmentationData = {
2180
+ segmentationId,
2181
+ config: {
2182
+ label: 'Segmentation 1',
2183
+ },
2184
+ };
2185
+
2186
+ jest
2187
+ .spyOn(cstSegmentation.state, 'getSegmentation')
2188
+ .mockReturnValue(mockCornerstoneSegmentation);
2189
+ jest.spyOn(cstSegmentation, 'updateSegmentations').mockReturnValue(undefined);
2190
+
2191
+ service.addOrUpdateSegmentation(segmentationData);
2192
+
2193
+ expect(cstSegmentation.updateSegmentations).toHaveBeenCalledTimes(1);
2194
+ expect(cstSegmentation.updateSegmentations).toHaveBeenCalledWith([
2195
+ { segmentationId, payload: segmentationData },
2196
+ ]);
2197
+ });
2198
+ });
2199
+
2200
+ describe('setActiveSegmentation', () => {
2201
+ it('should set the active segmentation for a viewport', () => {
2202
+ const viewportId = 'viewportId';
2203
+ const segmentationId = 'segmentationId';
2204
+
2205
+ service.setActiveSegmentation(viewportId, segmentationId);
2206
+
2207
+ expect(cstSegmentation.activeSegmentation.setActiveSegmentation).toHaveBeenCalledTimes(1);
2208
+ expect(cstSegmentation.activeSegmentation.setActiveSegmentation).toHaveBeenCalledWith(
2209
+ viewportId,
2210
+ segmentationId
2211
+ );
2212
+ });
2213
+ });
2214
+
2215
+ describe('getActiveSegmentation', () => {
2216
+ it('should get the active segmentation for a viewport', () => {
2217
+ const viewportId = 'viewportId';
2218
+
2219
+ service.getActiveSegmentation(viewportId);
2220
+
2221
+ expect(cstSegmentation.activeSegmentation.getActiveSegmentation).toHaveBeenCalledTimes(1);
2222
+ expect(cstSegmentation.activeSegmentation.getActiveSegmentation).toHaveBeenCalledWith(
2223
+ viewportId
2224
+ );
2225
+ });
2226
+ });
2227
+
2228
+ describe('getActiveSegment', () => {
2229
+ it('should return undefined if no active segmentation', () => {
2230
+ const viewportId = 'viewportId';
2231
+ jest.spyOn(cstSegmentation.activeSegmentation, 'getActiveSegmentation').mockReturnValue(null);
2232
+
2233
+ const activeSegment = service.getActiveSegment(viewportId);
2234
+
2235
+ expect(cstSegmentation.activeSegmentation.getActiveSegmentation).toHaveBeenCalledTimes(1);
2236
+ expect(cstSegmentation.activeSegmentation.getActiveSegmentation).toHaveBeenCalledWith(
2237
+ viewportId
2238
+ );
2239
+
2240
+ expect(activeSegment).toBeUndefined();
2241
+ });
2242
+
2243
+ it('should find and return the active segment', () => {
2244
+ const viewportId = 'viewportId';
2245
+ jest
2246
+ .spyOn(cstSegmentation.activeSegmentation, 'getActiveSegmentation')
2247
+ .mockReturnValue(mockCornerstoneSegmentation);
2248
+
2249
+ const activeSegment = service.getActiveSegment(viewportId);
2250
+
2251
+ expect(activeSegment).toEqual(mockCornerstoneSegmentation.segments['1']);
2252
+ });
2253
+ });
2254
+
2255
+ describe('hasCustomStyles', () => {
2256
+ it('should return true if the segmentation has custom styles', () => {
2257
+ const viewportId = 'viewportId';
2258
+ const segmentationId = 'segmentationId';
2259
+ const type = csToolsEnums.SegmentationRepresentations.Contour;
2260
+
2261
+ jest.spyOn(cstSegmentation.config.style, 'hasCustomStyle').mockReturnValue(true);
2262
+
2263
+ const hasCustomStyles = service.hasCustomStyles({ viewportId, segmentationId, type });
2264
+
2265
+ expect(cstSegmentation.config.style.hasCustomStyle).toHaveBeenCalledTimes(1);
2266
+ expect(cstSegmentation.config.style.hasCustomStyle).toHaveBeenCalledWith({
2267
+ viewportId,
2268
+ segmentationId,
2269
+ type,
2270
+ });
2271
+
2272
+ expect(hasCustomStyles).toBe(true);
2273
+ });
2274
+ });
2275
+
2276
+ describe('getStyle', () => {
2277
+ it('should return the style for the segmentation', () => {
2278
+ const viewportId = 'viewportId';
2279
+ const segmentationId = 'segmentationId';
2280
+ const type = csToolsEnums.SegmentationRepresentations.Contour;
2281
+ const segmentIndex = 1;
2282
+
2283
+ jest.spyOn(cstSegmentation.config.style, 'getStyle').mockReturnValue({});
2284
+
2285
+ const style = service.getStyle({ viewportId, segmentationId, type, segmentIndex });
2286
+
2287
+ expect(cstSegmentation.config.style.getStyle).toHaveBeenCalledTimes(1);
2288
+ expect(cstSegmentation.config.style.getStyle).toHaveBeenCalledWith({
2289
+ viewportId,
2290
+ segmentationId,
2291
+ type,
2292
+ segmentIndex,
2293
+ });
2294
+
2295
+ expect(style).toEqual({});
2296
+ });
2297
+ });
2298
+
2299
+ describe('setStyle', () => {
2300
+ it('should set the style for the segmentation', () => {
2301
+ const viewportId = 'viewportId';
2302
+ const segmentationId = 'segmentationId';
2303
+ const type = csToolsEnums.SegmentationRepresentations.Contour;
2304
+ const segmentIndex = 1;
2305
+ const style = {
2306
+ fillAlpha: 0.5,
2307
+ outlineWidth: 2,
2308
+ renderOutline: true,
2309
+ renderFill: true,
2310
+ };
2311
+
2312
+ jest.spyOn(cstSegmentation.config.style, 'setStyle').mockReturnValue(undefined);
2313
+
2314
+ service.setStyle({ viewportId, segmentationId, type, segmentIndex }, style);
2315
+
2316
+ expect(cstSegmentation.config.style.setStyle).toHaveBeenCalledTimes(1);
2317
+ expect(cstSegmentation.config.style.setStyle).toHaveBeenCalledWith(
2318
+ {
2319
+ viewportId,
2320
+ segmentationId,
2321
+ type,
2322
+ segmentIndex,
2323
+ },
2324
+ style,
2325
+ true
2326
+ );
2327
+ });
2328
+ });
2329
+
2330
+ describe('resetToGlobalStyle', () => {
2331
+ it('should reset the style for the segmentation', () => {
2332
+ jest.spyOn(cstSegmentation.config.style, 'resetToGlobalStyle').mockReturnValue(undefined);
2333
+
2334
+ service.resetToGlobalStyle();
2335
+
2336
+ expect(cstSegmentation.config.style.resetToGlobalStyle).toHaveBeenCalledTimes(1);
2337
+ expect(cstSegmentation.config.style.resetToGlobalStyle).toHaveBeenCalledWith();
2338
+ });
2339
+ });
2340
+
2341
+ describe('addSegment', () => {
2342
+ it('should throw an error if the segment index is 0', () => {
2343
+ const segmentationId = 'segmentationId';
2344
+ const config = {
2345
+ segmentIndex: 0,
2346
+ };
2347
+
2348
+ expect(() => service.addSegment(segmentationId, config)).toThrow(
2349
+ 'Segment index 0 is reserved for "no label"'
2350
+ );
2351
+ });
2352
+
2353
+ it('should add a new segment with next available index if not provided', () => {
2354
+ const segmentationId = 'segmentationId';
2355
+ const config = {
2356
+ label: 'New Segment 2',
2357
+ visibility: true,
2358
+ };
2359
+
2360
+ jest
2361
+ .spyOn(cstSegmentation.state, 'getSegmentation')
2362
+ .mockReturnValue(mockCornerstoneSegmentation);
2363
+ jest.spyOn(cstSegmentation, 'updateSegmentations').mockReturnValue(undefined);
2364
+ jest.spyOn(cstSegmentation.segmentIndex, 'setActiveSegmentIndex').mockReturnValue(undefined);
2365
+ jest
2366
+ .spyOn(cstSegmentation.state, 'getViewportIdsWithSegmentation')
2367
+ .mockReturnValue(['viewportId']);
2368
+ jest
2369
+ .spyOn(cstSegmentation.config.visibility, 'setSegmentIndexVisibility')
2370
+ .mockReturnValue(undefined);
2371
+
2372
+ service.addSegment(segmentationId, config);
2373
+
2374
+ expect(cstSegmentation.state.getSegmentation).toHaveBeenCalledTimes(2);
2375
+ expect(cstSegmentation.state.getSegmentation).toHaveBeenCalledWith(segmentationId);
2376
+
2377
+ expect(cstSegmentation.updateSegmentations).toHaveBeenCalledTimes(1);
2378
+ expect(cstSegmentation.updateSegmentations).toHaveBeenCalledWith([
2379
+ {
2380
+ segmentationId,
2381
+ payload: {
2382
+ segments: {
2383
+ ...mockCornerstoneSegmentation.segments,
2384
+ '2': {
2385
+ label: 'New Segment 2',
2386
+ segmentIndex: 2,
2387
+ cachedStats: {},
2388
+ locked: false,
2389
+ ...config,
2390
+ },
2391
+ },
2392
+ },
2393
+ },
2394
+ ]);
2395
+
2396
+ expect(cstSegmentation.segmentIndex.setActiveSegmentIndex).toHaveBeenCalledTimes(1);
2397
+ expect(cstSegmentation.segmentIndex.setActiveSegmentIndex).toHaveBeenCalledWith(
2398
+ segmentationId,
2399
+ 2
2400
+ );
2401
+
2402
+ expect(cstSegmentation.state.getViewportIdsWithSegmentation).toHaveBeenCalledTimes(1);
2403
+ expect(cstSegmentation.state.getViewportIdsWithSegmentation).toHaveBeenCalledWith(
2404
+ segmentationId
2405
+ );
2406
+
2407
+ expect(cstSegmentation.config.visibility.setSegmentIndexVisibility).toHaveBeenCalledTimes(1);
2408
+ expect(cstSegmentation.config.visibility.setSegmentIndexVisibility).toHaveBeenCalledWith(
2409
+ 'viewportId',
2410
+ { segmentationId, type: undefined },
2411
+ 2,
2412
+ config.visibility
2413
+ );
2414
+ });
2415
+
2416
+ it('should set properties if segment index already exists', () => {
2417
+ const segmentationId = 'segmentationId';
2418
+ const config = {
2419
+ segmentIndex: 1,
2420
+ isLocked: false,
2421
+ active: true,
2422
+ color: [255, 0, 0, 255] as csTypes.Color,
2423
+ };
2424
+
2425
+ jest
2426
+ .spyOn(cstSegmentation.state, 'getSegmentation')
2427
+ .mockReturnValue(mockCornerstoneSegmentation);
2428
+ jest.spyOn(cstSegmentation, 'updateSegmentations').mockReturnValue(undefined);
2429
+ jest.spyOn(cstSegmentation.segmentIndex, 'setActiveSegmentIndex').mockReturnValue(undefined);
2430
+ jest.spyOn(service, 'getViewportIdsWithSegmentation').mockReturnValue(['viewportId']);
2431
+ jest
2432
+ .spyOn(cstSegmentation.segmentLocking, 'setSegmentIndexLocked')
2433
+ .mockReturnValue(undefined);
2434
+ jest.spyOn(cstSegmentation.config.color, 'setSegmentIndexColor').mockReturnValue(undefined);
2435
+ jest
2436
+ .spyOn(cstSegmentation.state, 'getSegmentationRepresentations')
2437
+ .mockReturnValue([{ colorLUTIndex: 1 }] as cstTypes.SegmentationRepresentation[]);
2438
+
2439
+ service.addSegment(segmentationId, config);
2440
+
2441
+ expect(cstSegmentation.updateSegmentations).toHaveBeenCalledTimes(1);
2442
+ expect(cstSegmentation.updateSegmentations).toHaveBeenCalledWith([
2443
+ {
2444
+ segmentationId,
2445
+ payload: {
2446
+ segments: {
2447
+ ...mockCornerstoneSegmentation.segments,
2448
+ '1': {
2449
+ label: 'Segment 1',
2450
+ segmentIndex: 1,
2451
+ cachedStats: {},
2452
+ locked: false,
2453
+ active: true,
2454
+ ...config,
2455
+ },
2456
+ },
2457
+ },
2458
+ },
2459
+ ]);
2460
+
2461
+ expect(cstSegmentation.segmentLocking.setSegmentIndexLocked).toHaveBeenCalledTimes(1);
2462
+ expect(cstSegmentation.segmentLocking.setSegmentIndexLocked).toHaveBeenCalledWith(
2463
+ segmentationId,
2464
+ 1,
2465
+ config.isLocked
2466
+ );
2467
+
2468
+ expect(cstSegmentation.config.color.setSegmentIndexColor).toHaveBeenCalledTimes(1);
2469
+ expect(cstSegmentation.config.color.setSegmentIndexColor).toHaveBeenCalledWith(
2470
+ 'viewportId',
2471
+ segmentationId,
2472
+ 1,
2473
+ config.color
2474
+ );
2475
+ });
2476
+ });
2477
+
2478
+ describe('removeSegment', () => {
2479
+ it('should remove the segment', () => {
2480
+ const segmentationId = 'segmentationId';
2481
+ const segmentIndex = 1;
2482
+ jest.spyOn(cstSegmentation, 'removeSegment').mockReturnValue(undefined);
2483
+
2484
+ service.removeSegment(segmentationId, segmentIndex);
2485
+
2486
+ expect(cstSegmentation.removeSegment).toHaveBeenCalledTimes(1);
2487
+ expect(cstSegmentation.removeSegment).toHaveBeenCalledWith(segmentationId, segmentIndex, {
2488
+ recordHistory: true,
2489
+ });
2490
+ });
2491
+ });
2492
+
2493
+ describe('setSegmentVisibility', () => {
2494
+ it('should set the visibility of the segment', () => {
2495
+ const viewportId = 'viewportId';
2496
+ const segmentationId = 'segmentationId';
2497
+ const segmentIndex = 1;
2498
+ const isVisible = true;
2499
+ const type = csToolsEnums.SegmentationRepresentations.Contour;
2500
+
2501
+ jest
2502
+ .spyOn(cstSegmentation.config.visibility, 'setSegmentIndexVisibility')
2503
+ .mockReturnValue(undefined);
2504
+
2505
+ service.setSegmentVisibility(viewportId, segmentationId, segmentIndex, isVisible, type);
2506
+
2507
+ expect(cstSegmentation.config.visibility.setSegmentIndexVisibility).toHaveBeenCalledTimes(1);
2508
+ expect(cstSegmentation.config.visibility.setSegmentIndexVisibility).toHaveBeenCalledWith(
2509
+ viewportId,
2510
+ { segmentationId, type },
2511
+ segmentIndex,
2512
+ isVisible
2513
+ );
2514
+ });
2515
+ });
2516
+
2517
+ describe('setSegmentLocked', () => {
2518
+ it('should set the locked status of the segment', () => {
2519
+ const segmentationId = 'segmentationId';
2520
+ const segmentIndex = 1;
2521
+ const isLocked = true;
2522
+
2523
+ jest
2524
+ .spyOn(cstSegmentation.segmentLocking, 'setSegmentIndexLocked')
2525
+ .mockReturnValue(undefined);
2526
+
2527
+ service.setSegmentLocked(segmentationId, segmentIndex, isLocked);
2528
+
2529
+ expect(cstSegmentation.segmentLocking.setSegmentIndexLocked).toHaveBeenCalledTimes(1);
2530
+ expect(cstSegmentation.segmentLocking.setSegmentIndexLocked).toHaveBeenCalledWith(
2531
+ segmentationId,
2532
+ segmentIndex,
2533
+ isLocked
2534
+ );
2535
+ });
2536
+ });
2537
+
2538
+ describe('toggleSegmentLocked', () => {
2539
+ it('should toggle the locked status of the segment', () => {
2540
+ const segmentationId = 'segmentationId';
2541
+ const segmentIndex = 1;
2542
+ const isLocked = true;
2543
+
2544
+ jest.spyOn(cstSegmentation.segmentLocking, 'isSegmentIndexLocked').mockReturnValue(isLocked);
2545
+ jest
2546
+ .spyOn(cstSegmentation.segmentLocking, 'setSegmentIndexLocked')
2547
+ .mockReturnValue(undefined);
2548
+
2549
+ service.toggleSegmentLocked(segmentationId, segmentIndex);
2550
+
2551
+ expect(cstSegmentation.segmentLocking.isSegmentIndexLocked).toHaveBeenCalledTimes(1);
2552
+ expect(cstSegmentation.segmentLocking.isSegmentIndexLocked).toHaveBeenCalledWith(
2553
+ segmentationId,
2554
+ segmentIndex
2555
+ );
2556
+
2557
+ expect(cstSegmentation.segmentLocking.setSegmentIndexLocked).toHaveBeenCalledTimes(1);
2558
+ expect(cstSegmentation.segmentLocking.setSegmentIndexLocked).toHaveBeenCalledWith(
2559
+ segmentationId,
2560
+ segmentIndex,
2561
+ !isLocked
2562
+ );
2563
+ });
2564
+ });
2565
+
2566
+ describe('toggleSegmentVisibility', () => {
2567
+ it('should toggle the visibility of the segment', () => {
2568
+ const viewportId = 'viewportId';
2569
+ const segmentationId = 'segmentationId';
2570
+ const segmentIndex = 1;
2571
+ const isVisible = true;
2572
+ const type = csToolsEnums.SegmentationRepresentations.Contour;
2573
+
2574
+ jest
2575
+ .spyOn(cstSegmentation.config.visibility, 'getSegmentIndexVisibility')
2576
+ .mockReturnValue(isVisible);
2577
+ jest
2578
+ .spyOn(cstSegmentation.config.visibility, 'setSegmentIndexVisibility')
2579
+ .mockReturnValue(undefined);
2580
+
2581
+ service.toggleSegmentVisibility(viewportId, segmentationId, segmentIndex, type);
2582
+
2583
+ expect(cstSegmentation.config.visibility.getSegmentIndexVisibility).toHaveBeenCalledTimes(1);
2584
+ expect(cstSegmentation.config.visibility.getSegmentIndexVisibility).toHaveBeenCalledWith(
2585
+ viewportId,
2586
+ { segmentationId, type },
2587
+ segmentIndex
2588
+ );
2589
+
2590
+ expect(cstSegmentation.config.visibility.setSegmentIndexVisibility).toHaveBeenCalledTimes(1);
2591
+ expect(cstSegmentation.config.visibility.setSegmentIndexVisibility).toHaveBeenCalledWith(
2592
+ viewportId,
2593
+ { segmentationId, type },
2594
+ segmentIndex,
2595
+ !isVisible
2596
+ );
2597
+ });
2598
+ });
2599
+
2600
+ describe('setSegmentColor', () => {
2601
+ const viewportId = 'viewportId';
2602
+ const segmentationId = 'segmentationId';
2603
+ const segmentIndex = 1;
2604
+ const color = [255, 0, 0, 255] as csTypes.Color;
2605
+
2606
+ it('should set the color of the segment', () => {
2607
+ jest
2608
+ .spyOn(cstSegmentation.state, 'getSegmentationRepresentations')
2609
+ .mockReturnValue([{ colorLUTIndex: 1 }] as cstTypes.SegmentationRepresentation[]);
2610
+ jest.spyOn(cstSegmentation.config.color, 'setSegmentIndexColor').mockReturnValue(undefined);
2611
+
2612
+ service.setSegmentColor(viewportId, segmentationId, segmentIndex, color);
2613
+
2614
+ expect(cstSegmentation.state.getSegmentationRepresentations).toHaveBeenCalledTimes(1);
2615
+ expect(cstSegmentation.state.getSegmentationRepresentations).toHaveBeenCalledWith(
2616
+ viewportId,
2617
+ { segmentationId }
2618
+ );
2619
+
2620
+ expect(cstSegmentation.config.color.setSegmentIndexColor).toHaveBeenCalledTimes(1);
2621
+ expect(cstSegmentation.config.color.setSegmentIndexColor).toHaveBeenCalledWith(
2622
+ viewportId,
2623
+ segmentationId,
2624
+ segmentIndex,
2625
+ color
2626
+ );
2627
+ });
2628
+
2629
+ it('should set the color of the segment with the colorLUTIndex', async () => {
2630
+ jest
2631
+ .spyOn(cstSegmentation.state, 'getSegmentationRepresentations')
2632
+ .mockReturnValue([{ colorLUTIndex: 1 }] as cstTypes.SegmentationRepresentation[]);
2633
+ jest.spyOn(cstSegmentation.config.color, 'setSegmentIndexColor').mockReturnValue(undefined);
2634
+
2635
+ service.setSegmentColor(viewportId, segmentationId, segmentIndex, color);
2636
+
2637
+ jest
2638
+ .spyOn(cstSegmentation.state, 'getSegmentation')
2639
+ .mockReturnValue(mockCornerstoneSegmentation as cstTypes.Segmentation);
2640
+ jest
2641
+ .spyOn(serviceManagerMock.services.cornerstoneViewportService, 'getCornerstoneViewport')
2642
+ // only needed interfaces for the addSegmentationRepresentation call
2643
+ .mockReturnValue(mockCornerstoneStackViewport as unknown as csTypes.IStackViewport);
2644
+ jest
2645
+ .spyOn(cstSegmentation.state, 'updateLabelmapSegmentationImageReferences')
2646
+ .mockReturnValue('labelmapImageId');
2647
+ jest.spyOn(cstSegmentation, 'addSegmentationRepresentations').mockReturnValueOnce(undefined);
2648
+
2649
+ await service.addSegmentationRepresentation(viewportId, {
2650
+ segmentationId: segmentationId,
2651
+ type: csToolsEnums.SegmentationRepresentations.Labelmap,
2652
+ config: { blendMode: csEnums.BlendModes.COMPOSITE },
2653
+ suppressEvents: true,
2654
+ });
2655
+
2656
+ expect(cstSegmentation.addSegmentationRepresentations).toHaveBeenCalledTimes(1);
2657
+ expect(cstSegmentation.addSegmentationRepresentations).toHaveBeenCalledWith(viewportId, [
2658
+ {
2659
+ type: csToolsEnums.SegmentationRepresentations.Labelmap,
2660
+ segmentationId: segmentationId,
2661
+ config: { colorLUTOrIndex: 1, blendMode: csEnums.BlendModes.COMPOSITE },
2662
+ },
2663
+ ]);
2664
+ });
2665
+ });
2666
+
2667
+ describe('getSegmentColor', () => {
2668
+ it('should get the color of the segment', () => {
2669
+ const viewportId = 'viewportId';
2670
+ const segmentationId = 'segmentationId';
2671
+ const segmentIndex = 1;
2672
+ const color = [255, 0, 0, 255] as csTypes.Color;
2673
+
2674
+ jest.spyOn(cstSegmentation.config.color, 'getSegmentIndexColor').mockReturnValue(color);
2675
+
2676
+ const returnedColor = service.getSegmentColor(viewportId, segmentationId, segmentIndex);
2677
+
2678
+ expect(cstSegmentation.config.color.getSegmentIndexColor).toHaveBeenCalledTimes(1);
2679
+ expect(cstSegmentation.config.color.getSegmentIndexColor).toHaveBeenCalledWith(
2680
+ viewportId,
2681
+ segmentationId,
2682
+ segmentIndex
2683
+ );
2684
+
2685
+ expect(returnedColor).toEqual(color);
2686
+ });
2687
+ });
2688
+
2689
+ describe('getLabelmapVolume', () => {
2690
+ it('should get the labelmap volume for the segmentation', () => {
2691
+ const segmentationId = 'segmentationId';
2692
+ const labelmapVolume = { id: 'volumeId' };
2693
+ mockCornerstoneSegmentation.representationData.Labelmap = { volumeId: 'volumeId' };
2694
+ jest
2695
+ .spyOn(cstSegmentation.state, 'getSegmentation')
2696
+ .mockReturnValue(mockCornerstoneSegmentation);
2697
+ // @ts-expect-error - no need to mock every property for this test
2698
+ jest.spyOn(cache, 'getVolume').mockReturnValue(labelmapVolume);
2699
+
2700
+ const returnedLabelmapVolume = service.getLabelmapVolume(segmentationId);
2701
+
2702
+ expect(cstSegmentation.state.getSegmentation).toHaveBeenCalledTimes(1);
2703
+ expect(cstSegmentation.state.getSegmentation).toHaveBeenCalledWith(segmentationId);
2704
+
2705
+ expect(cache.getVolume).toHaveBeenCalledTimes(1);
2706
+ expect(cache.getVolume).toHaveBeenCalledWith(labelmapVolume.id);
2707
+
2708
+ expect(returnedLabelmapVolume).toEqual(labelmapVolume);
2709
+
2710
+ mockCornerstoneSegmentation.representationData.Labelmap = {};
2711
+ });
2712
+
2713
+ it('should return null if the segmentation does not have a labelmap volume', () => {
2714
+ const segmentationId = 'segmentationId';
2715
+ jest
2716
+ .spyOn(cstSegmentation.state, 'getSegmentation')
2717
+ .mockReturnValue(mockCornerstoneSegmentation);
2718
+
2719
+ const returnedLabelmapVolume = service.getLabelmapVolume(segmentationId);
2720
+
2721
+ expect(cstSegmentation.state.getSegmentation).toHaveBeenCalledTimes(1);
2722
+
2723
+ expect(returnedLabelmapVolume).toEqual(null);
2724
+ });
2725
+ });
2726
+
2727
+ describe('setSegmentLabel', () => {
2728
+ it('should set the label of the segment', () => {
2729
+ const segmentationId = 'segmentationId';
2730
+ const segmentIndex = 1;
2731
+ const label = 'New Segment 1';
2732
+
2733
+ jest
2734
+ .spyOn(cstSegmentation.state, 'getSegmentation')
2735
+ .mockReturnValue(mockCornerstoneSegmentation);
2736
+ jest.spyOn(cstSegmentation, 'updateSegmentations').mockReturnValue(undefined);
2737
+
2738
+ service.setSegmentLabel(segmentationId, segmentIndex, label);
2739
+
2740
+ expect(cstSegmentation.state.getSegmentation).toHaveBeenCalledTimes(1);
2741
+ expect(cstSegmentation.state.getSegmentation).toHaveBeenCalledWith(segmentationId);
2742
+
2743
+ expect(cstSegmentation.updateSegmentations).toHaveBeenCalledTimes(1);
2744
+ expect(cstSegmentation.updateSegmentations).toHaveBeenCalledWith([
2745
+ {
2746
+ segmentationId,
2747
+ payload: {
2748
+ segments: {
2749
+ ...mockCornerstoneSegmentation.segments,
2750
+ [segmentIndex]: { ...mockCornerstoneSegmentation.segments[segmentIndex], label },
2751
+ },
2752
+ },
2753
+ },
2754
+ ]);
2755
+ });
2756
+ });
2757
+
2758
+ describe('setActiveSegment', () => {
2759
+ it('should set the active segment for the segmentation', () => {
2760
+ const segmentationId = 'segmentationId';
2761
+ const segmentIndex = 1;
2762
+
2763
+ jest.spyOn(cstSegmentation.segmentIndex, 'setActiveSegmentIndex').mockReturnValue(undefined);
2764
+
2765
+ service.setActiveSegment(segmentationId, segmentIndex);
2766
+
2767
+ expect(cstSegmentation.segmentIndex.setActiveSegmentIndex).toHaveBeenCalledTimes(1);
2768
+ expect(cstSegmentation.segmentIndex.setActiveSegmentIndex).toHaveBeenCalledWith(
2769
+ segmentationId,
2770
+ segmentIndex
2771
+ );
2772
+ });
2773
+ });
2774
+
2775
+ describe('setRenderInactiveSegmentations', () => {
2776
+ it('should set the render inactive segmentations for the viewport', () => {
2777
+ const viewportId = 'viewportId';
2778
+ const renderInactive = true;
2779
+
2780
+ jest
2781
+ .spyOn(cstSegmentation.config.style, 'setRenderInactiveSegmentations')
2782
+ .mockReturnValue(undefined);
2783
+
2784
+ service.setRenderInactiveSegmentations(viewportId, renderInactive);
2785
+
2786
+ expect(cstSegmentation.config.style.setRenderInactiveSegmentations).toHaveBeenCalledTimes(1);
2787
+ expect(cstSegmentation.config.style.setRenderInactiveSegmentations).toHaveBeenCalledWith(
2788
+ viewportId,
2789
+ renderInactive
2790
+ );
2791
+ });
2792
+ });
2793
+
2794
+ describe('getRenderInactiveSegmentations', () => {
2795
+ it('should get the render inactive segmentations for the viewport', () => {
2796
+ const viewportId = 'viewportId';
2797
+ const renderInactive = true;
2798
+
2799
+ jest
2800
+ .spyOn(cstSegmentation.config.style, 'getRenderInactiveSegmentations')
2801
+ .mockReturnValue(renderInactive);
2802
+
2803
+ const returnedRenderInactive = service.getRenderInactiveSegmentations(viewportId);
2804
+
2805
+ expect(cstSegmentation.config.style.getRenderInactiveSegmentations).toHaveBeenCalledTimes(1);
2806
+ expect(cstSegmentation.config.style.getRenderInactiveSegmentations).toHaveBeenCalledWith(
2807
+ viewportId
2808
+ );
2809
+
2810
+ expect(returnedRenderInactive).toEqual(renderInactive);
2811
+ });
2812
+ });
2813
+
2814
+ describe('setSegmentationGroupStats', () => {
2815
+ it('should set the segmentation group stats', () => {
2816
+ const segmentationIds = ['segmentationId1', 'segmentationId2'];
2817
+ const stats = { key: 'value' };
2818
+
2819
+ service.setSegmentationGroupStats(segmentationIds, stats);
2820
+
2821
+ const returnedStats = service.getSegmentationGroupStats(segmentationIds);
2822
+
2823
+ expect(returnedStats).toEqual(stats);
2824
+ });
2825
+ });
2826
+
2827
+ describe('getSegmentationGroupStats', () => {
2828
+ it('should get the segmentation group stats', () => {
2829
+ const segmentationIds = ['segmentationId1', 'segmentationId2'];
2830
+ const stats = { key: 'value' };
2831
+
2832
+ let returnedStats = service.getSegmentationGroupStats(segmentationIds);
2833
+
2834
+ expect(returnedStats).toEqual(undefined);
2835
+
2836
+ service.setSegmentationGroupStats(segmentationIds, stats);
2837
+
2838
+ returnedStats = service.getSegmentationGroupStats(segmentationIds);
2839
+
2840
+ expect(returnedStats).toEqual(stats);
2841
+ });
2842
+ });
2843
+
2844
+ describe('toggleSegmentationRepresentationVisibility', () => {
2845
+ it('should toggle the visibility of the segmentation representation', () => {
2846
+ jest.spyOn(service, 'getSegmentationRepresentations').mockReturnValue(representations);
2847
+ jest
2848
+ .spyOn(cstSegmentation.config.visibility, 'getHiddenSegmentIndices')
2849
+ .mockReturnValue(new Set());
2850
+ jest
2851
+ .spyOn(cstSegmentation.config.visibility, 'setSegmentationRepresentationVisibility')
2852
+ .mockReturnValue(undefined);
2853
+
2854
+ service.toggleSegmentationRepresentationVisibility(viewportId, {
2855
+ segmentationId: representations[0].segmentationId,
2856
+ type: representations[0].type,
2857
+ });
2858
+
2859
+ expect(service.getSegmentationRepresentations).toHaveBeenCalledTimes(1);
2860
+ expect(service.getSegmentationRepresentations).toHaveBeenCalledWith(viewportId, {
2861
+ segmentationId: representations[0].segmentationId,
2862
+ type: representations[0].type,
2863
+ });
2864
+
2865
+ expect(cstSegmentation.config.visibility.getHiddenSegmentIndices).toHaveBeenCalledTimes(1);
2866
+ expect(cstSegmentation.config.visibility.getHiddenSegmentIndices).toHaveBeenCalledWith(
2867
+ viewportId,
2868
+ {
2869
+ segmentationId: representations[0].segmentationId,
2870
+ type: representations[0].type,
2871
+ }
2872
+ );
2873
+
2874
+ expect(
2875
+ cstSegmentation.config.visibility.setSegmentationRepresentationVisibility
2876
+ ).toHaveBeenCalledTimes(1);
2877
+ expect(
2878
+ cstSegmentation.config.visibility.setSegmentationRepresentationVisibility
2879
+ ).toHaveBeenCalledWith(
2880
+ viewportId,
2881
+ {
2882
+ segmentationId: representations[0].segmentationId,
2883
+ type: representations[0].type,
2884
+ },
2885
+ false
2886
+ );
2887
+ });
2888
+ });
2889
+
2890
+ describe('setSegmentationRepresentationVisibility', () => {
2891
+ it('should early return if the representation is not found', () => {
2892
+ jest.spyOn(service, 'getSegmentationRepresentations').mockReturnValueOnce([]);
2893
+ jest.spyOn(console, 'debug').mockReturnValue(undefined);
2894
+ jest.spyOn(cstSegmentation.config.visibility, 'setSegmentationRepresentationVisibility');
2895
+
2896
+ service['_setSegmentationRepresentationVisibility'](
2897
+ viewportId,
2898
+ representations[0].segmentationId,
2899
+ representations[0].type,
2900
+ true
2901
+ );
2902
+
2903
+ expect(console.debug).toHaveBeenCalledTimes(1);
2904
+ expect(console.debug).toHaveBeenCalledWith(
2905
+ 'No segmentation representation found for the given viewportId and segmentationId'
2906
+ );
2907
+
2908
+ expect(
2909
+ cstSegmentation.config.visibility.setSegmentationRepresentationVisibility
2910
+ ).not.toHaveBeenCalled();
2911
+ });
2912
+ });
2913
+
2914
+ describe('getViewportIdsWithSegmentation', () => {
2915
+ it('should get the viewport ids with the segmentation', () => {
2916
+ const segmentationId = 'segmentationId';
2917
+ const viewportIds = ['viewportId1', 'viewportId2'];
2918
+
2919
+ jest
2920
+ .spyOn(cstSegmentation.state, 'getViewportIdsWithSegmentation')
2921
+ .mockReturnValue(viewportIds);
2922
+
2923
+ const returnedViewportIds = service.getViewportIdsWithSegmentation(segmentationId);
2924
+
2925
+ expect(cstSegmentation.state.getViewportIdsWithSegmentation).toHaveBeenCalledTimes(1);
2926
+ expect(cstSegmentation.state.getViewportIdsWithSegmentation).toHaveBeenCalledWith(
2927
+ segmentationId
2928
+ );
2929
+
2930
+ expect(returnedViewportIds).toEqual(viewportIds);
2931
+ });
2932
+ });
2933
+
2934
+ describe('clearSegmentationRepresentations', () => {
2935
+ it('should clear the segmentation representations', () => {
2936
+ const viewportId = 'viewportId';
2937
+ jest.spyOn(service, 'removeRepresentationsFromViewport').mockReturnValue(undefined);
2938
+
2939
+ service.clearSegmentationRepresentations(viewportId);
2940
+
2941
+ expect(service.removeRepresentationsFromViewport).toHaveBeenCalledTimes(1);
2942
+ expect(service.removeRepresentationsFromViewport).toHaveBeenCalledWith(viewportId);
2943
+ });
2944
+ });
2945
+
2946
+ describe('remove', () => {
2947
+ it('should remove the segmentation', () => {
2948
+ const segmentationId = 'segmentationId';
2949
+
2950
+ jest.spyOn(cstSegmentation.state, 'removeSegmentation').mockReturnValue(undefined);
2951
+
2952
+ service.remove(segmentationId);
2953
+
2954
+ expect(cstSegmentation.state.removeSegmentation).toHaveBeenCalledTimes(1);
2955
+ expect(cstSegmentation.state.removeSegmentation).toHaveBeenCalledWith(segmentationId);
2956
+ });
2957
+ });
2958
+
2959
+ describe('removeAllSegmentations', () => {
2960
+ it('should remove all segmentations', () => {
2961
+ jest.spyOn(cstSegmentation.state, 'removeAllSegmentations').mockReturnValue(undefined);
2962
+
2963
+ service.removeAllSegmentations();
2964
+
2965
+ expect(cstSegmentation.state.removeAllSegmentations).toHaveBeenCalledTimes(1);
2966
+ expect(cstSegmentation.state.removeAllSegmentations).toHaveBeenCalledWith();
2967
+ });
2968
+ });
2969
+
2970
+ describe('removeRepresentationsFromViewport', () => {
2971
+ it('should remove the segmentation representations', () => {
2972
+ const viewportId = 'viewportId';
2973
+ const specifier = {
2974
+ segmentationId: 'segmentationId',
2975
+ type: csToolsEnums.SegmentationRepresentations.Labelmap,
2976
+ };
2977
+ jest.spyOn(cstSegmentation, 'removeSegmentationRepresentations').mockReturnValue(undefined);
2978
+
2979
+ service.removeRepresentationsFromViewport(viewportId, specifier);
2980
+
2981
+ expect(cstSegmentation.removeSegmentationRepresentations).toHaveBeenCalledTimes(1);
2982
+ expect(cstSegmentation.removeSegmentationRepresentations).toHaveBeenCalledWith(
2983
+ viewportId,
2984
+ specifier
2985
+ );
2986
+ });
2987
+ });
2988
+
2989
+ describe('jumpToSegmentCenter', () => {
2990
+ it('should early return if the center is not found', () => {
2991
+ const segmentationId = 'segmentationId';
2992
+ const segmentIndex = 1;
2993
+
2994
+ jest.spyOn(console, 'warn').mockReturnValue(undefined);
2995
+ jest.spyOn(cstSegmentation.state, 'getSegmentation').mockReturnValue(null);
2996
+ jest.spyOn(service, 'getViewportIdsWithSegmentation');
2997
+
2998
+ service.jumpToSegmentCenter(segmentationId, segmentIndex);
2999
+
3000
+ expect(console.warn).toHaveBeenCalledTimes(1);
3001
+ expect(console.warn).toHaveBeenCalledWith(
3002
+ 'No center found for segmentation',
3003
+ segmentationId,
3004
+ segmentIndex
3005
+ );
3006
+
3007
+ expect(service.getViewportIdsWithSegmentation).not.toHaveBeenCalled();
3008
+ });
3009
+
3010
+ it('should correctly handle scenario where viewportId is provided', () => {
3011
+ const segmentationId = 'segmentationId';
3012
+ const segmentIndex = 1;
3013
+ const viewportId = 'viewportId';
3014
+ const viewport = { jumpToWorld: jest.fn() };
3015
+
3016
+ const segmentationWithCenter = {
3017
+ ...mockCornerstoneSegmentation,
3018
+ segments: {
3019
+ ...mockCornerstoneSegmentation.segments,
3020
+ [segmentIndex]: {
3021
+ ...mockCornerstoneSegmentation.segments[segmentIndex],
3022
+ cachedStats: { center: { image: [1, 1, 1], world: [10, 10, 10] } },
3023
+ },
3024
+ },
3025
+ };
3026
+
3027
+ jest.spyOn(cstSegmentation.state, 'getSegmentation').mockReturnValue(segmentationWithCenter);
3028
+ jest.spyOn(service, 'getViewportIdsWithSegmentation');
3029
+ // @ts-expect-error - mock only needed properties
3030
+ getEnabledElementByViewportId.mockReturnValue({ viewport });
3031
+ jest.spyOn(service, 'highlightSegment').mockReturnValue(undefined);
3032
+
3033
+ service.jumpToSegmentCenter(segmentationId, segmentIndex, viewportId);
3034
+
3035
+ expect(cstSegmentation.state.getSegmentation).toHaveBeenCalledTimes(1);
3036
+ expect(cstSegmentation.state.getSegmentation).toHaveBeenCalledWith(segmentationId);
3037
+
3038
+ expect(service.getViewportIdsWithSegmentation).not.toHaveBeenCalled();
3039
+
3040
+ expect(viewport.jumpToWorld).toHaveBeenCalledTimes(1);
3041
+ expect(viewport.jumpToWorld).toHaveBeenCalledWith([10, 10, 10]);
3042
+
3043
+ expect(service.highlightSegment).toHaveBeenCalledTimes(1);
3044
+ expect(service.highlightSegment).toHaveBeenCalledWith(
3045
+ segmentationId,
3046
+ segmentIndex,
3047
+ viewportId,
3048
+ 0.9,
3049
+ 750,
3050
+ false,
3051
+ EasingFunctionEnum.EASE_IN_OUT
3052
+ );
3053
+ });
3054
+
3055
+ it('navigates a native viewport via setViewReference (no jumpToWorld) and still highlights', () => {
3056
+ const segmentationId = 'segmentationId';
3057
+ const segmentIndex = 1;
3058
+ const viewportId = 'viewportId';
3059
+ // A native PlanarViewport: csUtils.isGenericViewport is true (setDisplaySets +
3060
+ // setDisplaySetPresentation + setViewState) and it has setViewReference but NO
3061
+ // jumpToWorld, so jumpToSegmentCenter routes to the next twin.
3062
+ const viewport = {
3063
+ setDisplaySets: jest.fn(),
3064
+ setDisplaySetPresentation: jest.fn(),
3065
+ setViewState: jest.fn(),
3066
+ setViewReference: jest.fn(),
3067
+ render: jest.fn(),
3068
+ };
3069
+
3070
+ const segmentationWithCenter = {
3071
+ ...mockCornerstoneSegmentation,
3072
+ segments: {
3073
+ ...mockCornerstoneSegmentation.segments,
3074
+ [segmentIndex]: {
3075
+ ...mockCornerstoneSegmentation.segments[segmentIndex],
3076
+ cachedStats: { center: { image: [1, 1, 1], world: [10, 10, 10] } },
3077
+ },
3078
+ },
3079
+ };
3080
+
3081
+ jest.spyOn(cstSegmentation.state, 'getSegmentation').mockReturnValue(segmentationWithCenter);
3082
+ // @ts-expect-error - mock only needed properties
3083
+ getEnabledElementByViewportId.mockReturnValue({ viewport });
3084
+ jest.spyOn(service, 'highlightSegment').mockReturnValue(undefined);
3085
+
3086
+ service.jumpToSegmentCenter(segmentationId, segmentIndex, viewportId);
3087
+
3088
+ // native jump: a view reference centered on the segment world point, then render
3089
+ expect(viewport.setViewReference).toHaveBeenCalledTimes(1);
3090
+ expect(viewport.setViewReference).toHaveBeenCalledWith({ cameraFocalPoint: [10, 10, 10] });
3091
+ expect(viewport.render).toHaveBeenCalledTimes(1);
3092
+ // the recenter happened, so the highlight still runs
3093
+ expect(service.highlightSegment).toHaveBeenCalledTimes(1);
3094
+ });
3095
+
3096
+ it('should correctly handle custom animation parameters', () => {
3097
+ const segmentationId = 'segmentationId';
3098
+ const segmentIndex = 1;
3099
+ const viewportId = 'viewportId';
3100
+ const viewport = { jumpToWorld: jest.fn() };
3101
+
3102
+ const segmentationWithNamedStatsCenter = {
3103
+ ...mockCornerstoneSegmentation,
3104
+ segments: {
3105
+ ...mockCornerstoneSegmentation.segments,
3106
+ [segmentIndex]: {
3107
+ ...mockCornerstoneSegmentation.segments[segmentIndex],
3108
+ cachedStats: {
3109
+ namedStats: { center: { value: [1, 1, 1] } },
3110
+ },
3111
+ },
3112
+ },
3113
+ };
3114
+
3115
+ jest
3116
+ .spyOn(cstSegmentation.state, 'getSegmentation')
3117
+ .mockReturnValue(segmentationWithNamedStatsCenter);
3118
+ jest.spyOn(service, 'getViewportIdsWithSegmentation').mockReturnValue([viewportId]);
3119
+ // @ts-expect-error - mock only needed properties
3120
+ getEnabledElementByViewportId.mockReturnValue({ viewport });
3121
+ jest.spyOn(service, 'highlightSegment').mockReturnValue(undefined);
3122
+
3123
+ service.jumpToSegmentCenter(
3124
+ segmentationId,
3125
+ segmentIndex,
3126
+ undefined,
3127
+ 0.8,
3128
+ true,
3129
+ 800,
3130
+ false,
3131
+ EasingFunctionEnum.LINEAR
3132
+ );
3133
+
3134
+ expect(service.getViewportIdsWithSegmentation).toHaveBeenCalledTimes(1);
3135
+ expect(service.getViewportIdsWithSegmentation).toHaveBeenCalledWith(segmentationId);
3136
+
3137
+ expect(viewport.jumpToWorld).toHaveBeenCalledTimes(1);
3138
+ expect(viewport.jumpToWorld).toHaveBeenCalledWith([1, 1, 1]);
3139
+
3140
+ expect(service.highlightSegment).toHaveBeenCalledTimes(1);
3141
+ expect(service.highlightSegment).toHaveBeenCalledWith(
3142
+ segmentationId,
3143
+ segmentIndex,
3144
+ viewportId,
3145
+ 0.8,
3146
+ 800,
3147
+ false,
3148
+ EasingFunctionEnum.LINEAR
3149
+ );
3150
+ });
3151
+ });
3152
+
3153
+ describe('highlightSegment', () => {
3154
+ describe('LABELMAP Segmentation', () => {
3155
+ it('should correctly handle scenario where viewportId is provided', () => {
3156
+ const segmentIndex = 1;
3157
+ const viewportId = 'viewportId';
3158
+ const initialFillAlpha = 0.3;
3159
+ const animationDuration = 750;
3160
+ const animationFunctionConstant = 0.85;
3161
+ const easingFunction = jest.fn(() => animationFunctionConstant);
3162
+
3163
+ jest
3164
+ .spyOn(cstSegmentation.state, 'getSegmentation')
3165
+ .mockReturnValue(mockCornerstoneSegmentation);
3166
+ jest.spyOn(service, 'getViewportIdsWithSegmentation');
3167
+ jest.spyOn(service, 'getSegmentationRepresentations').mockReturnValue(representations);
3168
+ jest.spyOn(cstSegmentation.config.style, 'getStyle').mockReturnValue({
3169
+ fillAlpha: initialFillAlpha,
3170
+ });
3171
+ jest.spyOn(window, 'requestAnimationFrame').mockReturnValue(undefined);
3172
+ jest.spyOn(EasingFunctionMap, 'get').mockReturnValue(easingFunction);
3173
+
3174
+ service.highlightSegment(
3175
+ representations[0].segmentationId,
3176
+ segmentIndex,
3177
+ viewportId,
3178
+ 0.9,
3179
+ animationDuration,
3180
+ false,
3181
+ EasingFunctionEnum.EASE_IN_OUT
3182
+ );
3183
+
3184
+ expect(cstSegmentation.state.getSegmentation).toHaveBeenCalledTimes(1);
3185
+ expect(cstSegmentation.state.getSegmentation).toHaveBeenCalledWith(
3186
+ representations[0].segmentationId
3187
+ );
3188
+
3189
+ expect(service.getViewportIdsWithSegmentation).not.toHaveBeenCalled();
3190
+
3191
+ expect(service.getSegmentationRepresentations).toHaveBeenCalledTimes(1);
3192
+ expect(service.getSegmentationRepresentations).toHaveBeenCalledWith(viewportId, {
3193
+ segmentationId: representations[0].segmentationId,
3194
+ });
3195
+
3196
+ expect(cstSegmentation.config.style.getStyle).toHaveBeenCalledTimes(1);
3197
+ expect(cstSegmentation.config.style.getStyle).toHaveBeenCalledWith({
3198
+ viewportId,
3199
+ segmentationId: representations[0].segmentationId,
3200
+ type: csToolsEnums.SegmentationRepresentations.Labelmap,
3201
+ segmentIndex,
3202
+ });
3203
+
3204
+ expect(window.requestAnimationFrame).toHaveBeenCalledTimes(1);
3205
+ expect(window.requestAnimationFrame).toHaveBeenCalledWith(expect.any(Function));
3206
+
3207
+ const animationCallback = jest.mocked(window.requestAnimationFrame).mock.calls[0][0];
3208
+
3209
+ // during animation call
3210
+ animationCallback(0);
3211
+
3212
+ expect(EasingFunctionMap.get).toHaveBeenCalledTimes(1);
3213
+ expect(EasingFunctionMap.get).toHaveBeenCalledWith(EasingFunctionEnum.EASE_IN_OUT);
3214
+
3215
+ expect(cstSegmentation.config.style.setStyle).toHaveBeenCalledTimes(1);
3216
+ expect(cstSegmentation.config.style.setStyle).toHaveBeenCalledWith(
3217
+ {
3218
+ segmentationId: representations[0].segmentationId,
3219
+ segmentIndex,
3220
+ type: csToolsEnums.SegmentationRepresentations.Labelmap,
3221
+ },
3222
+ {
3223
+ fillAlpha: animationFunctionConstant,
3224
+ }
3225
+ );
3226
+
3227
+ expect(easingFunction).toHaveBeenCalledTimes(1);
3228
+ expect(easingFunction).toHaveBeenCalledWith(0, initialFillAlpha);
3229
+
3230
+ expect(window.requestAnimationFrame).toHaveBeenCalledTimes(2);
3231
+ expect(window.requestAnimationFrame).toHaveBeenCalledWith(expect.any(Function));
3232
+
3233
+ // end of animation call
3234
+ animationCallback(animationDuration);
3235
+
3236
+ expect(cstSegmentation.config.style.setStyle).toHaveBeenCalledTimes(3);
3237
+ expect(cstSegmentation.config.style.setStyle).toHaveBeenCalledWith(
3238
+ {
3239
+ segmentationId: representations[0].segmentationId,
3240
+ segmentIndex,
3241
+ type: csToolsEnums.SegmentationRepresentations.Labelmap,
3242
+ },
3243
+ {},
3244
+ false
3245
+ );
3246
+
3247
+ expect(window.requestAnimationFrame).not.toHaveBeenCalledTimes(3);
3248
+ });
3249
+
3250
+ it('should throw if hideOthers is true', () => {
3251
+ const segmentIndex = 1;
3252
+
3253
+ jest
3254
+ .spyOn(cstSegmentation.state, 'getSegmentation')
3255
+ .mockReturnValue(mockCornerstoneSegmentation);
3256
+ jest.spyOn(service, 'getViewportIdsWithSegmentation').mockReturnValue([viewportId]);
3257
+ jest.spyOn(service, 'getSegmentationRepresentations').mockReturnValue(representations);
3258
+
3259
+ expect(() =>
3260
+ service.highlightSegment(representations[0].segmentationId, segmentIndex)
3261
+ ).toThrow('hideOthers is not working right now');
3262
+
3263
+ expect(service.getViewportIdsWithSegmentation).toHaveBeenCalledTimes(1);
3264
+ expect(service.getViewportIdsWithSegmentation).toHaveBeenCalledWith(
3265
+ representations[0].segmentationId
3266
+ );
3267
+
3268
+ expect(service.getSegmentationRepresentations).toHaveBeenCalledTimes(1);
3269
+ expect(service.getSegmentationRepresentations).toHaveBeenCalledWith(viewportId, {
3270
+ segmentationId: representations[0].segmentationId,
3271
+ });
3272
+ });
3273
+ });
3274
+
3275
+ describe('CONTOUR Segmentation', () => {
3276
+ it('should correctly handle scenario where viewportId is provided', () => {
3277
+ const segmentIndex = 1;
3278
+ const viewportId = 'viewportId';
3279
+ const initialOutlineWidth = 3;
3280
+ const animationDuration = 750;
3281
+ const animationFunctionConstant = 5;
3282
+ const easingFunction = jest.fn(() => animationFunctionConstant);
3283
+
3284
+ const contourRepresentations = [
3285
+ {
3286
+ ...representations[0],
3287
+ type: csToolsEnums.SegmentationRepresentations.Contour,
3288
+ },
3289
+ ];
3290
+
3291
+ jest
3292
+ .spyOn(cstSegmentation.state, 'getSegmentation')
3293
+ .mockReturnValue(mockCornerstoneSegmentation);
3294
+ jest.spyOn(service, 'getViewportIdsWithSegmentation');
3295
+ jest
3296
+ .spyOn(service, 'getSegmentationRepresentations')
3297
+ .mockReturnValue(contourRepresentations);
3298
+ jest.spyOn(cstSegmentation.config.style, 'getStyle').mockReturnValue({
3299
+ outlineWidth: initialOutlineWidth,
3300
+ });
3301
+ jest.spyOn(window, 'requestAnimationFrame').mockReturnValue(undefined);
3302
+ jest.spyOn(EasingFunctionMap, 'get').mockReturnValue(easingFunction);
3303
+ jest.spyOn(cstSegmentation.config.style, 'resetToGlobalStyle').mockReturnValue(undefined);
3304
+
3305
+ service.highlightSegment(
3306
+ contourRepresentations[0].segmentationId,
3307
+ segmentIndex,
3308
+ viewportId,
3309
+ 0.9,
3310
+ animationDuration,
3311
+ false,
3312
+ EasingFunctionEnum.LINEAR
3313
+ );
3314
+
3315
+ expect(service.getViewportIdsWithSegmentation).not.toHaveBeenCalled();
3316
+
3317
+ expect(cstSegmentation.config.style.getStyle).toHaveBeenCalledTimes(1);
3318
+ expect(cstSegmentation.config.style.getStyle).toHaveBeenCalledWith({
3319
+ type: csToolsEnums.SegmentationRepresentations.Contour,
3320
+ });
3321
+
3322
+ expect(window.requestAnimationFrame).toHaveBeenCalledTimes(1);
3323
+ expect(window.requestAnimationFrame).toHaveBeenCalledWith(expect.any(Function));
3324
+
3325
+ const animationCallback = jest.mocked(window.requestAnimationFrame).mock.calls[0][0];
3326
+ const approximateStartTime = performance.now();
3327
+
3328
+ // during animation call
3329
+ animationCallback(approximateStartTime + 200);
3330
+
3331
+ expect(EasingFunctionMap.get).toHaveBeenCalledTimes(1);
3332
+ expect(EasingFunctionMap.get).toHaveBeenCalledWith(EasingFunctionEnum.LINEAR);
3333
+
3334
+ expect(cstSegmentation.config.style.setStyle).toHaveBeenCalledTimes(1);
3335
+ expect(cstSegmentation.config.style.setStyle).toHaveBeenCalledWith(
3336
+ {
3337
+ segmentationId: contourRepresentations[0].segmentationId,
3338
+ segmentIndex,
3339
+ type: csToolsEnums.SegmentationRepresentations.Contour,
3340
+ },
3341
+ {
3342
+ outlineWidth: animationFunctionConstant,
3343
+ }
3344
+ );
3345
+
3346
+ expect(easingFunction).toHaveBeenCalledTimes(1);
3347
+ expect(easingFunction).toHaveBeenCalledWith(expect.any(Number), initialOutlineWidth, 5);
3348
+
3349
+ expect(window.requestAnimationFrame).toHaveBeenCalledTimes(2);
3350
+ expect(window.requestAnimationFrame).toHaveBeenCalledWith(expect.any(Function));
3351
+
3352
+ // end of animation call
3353
+ animationCallback(approximateStartTime + animationDuration);
3354
+
3355
+ expect(cstSegmentation.config.style.setStyle).toHaveBeenCalledTimes(2);
3356
+ expect(cstSegmentation.config.style.setStyle).toHaveBeenLastCalledWith(
3357
+ {
3358
+ segmentationId: contourRepresentations[0].segmentationId,
3359
+ segmentIndex,
3360
+ type: csToolsEnums.SegmentationRepresentations.Contour,
3361
+ },
3362
+ {},
3363
+ false
3364
+ );
3365
+ expect(cstSegmentation.config.style.resetToGlobalStyle).not.toHaveBeenCalled();
3366
+
3367
+ expect(window.requestAnimationFrame).not.toHaveBeenCalledTimes(3);
3368
+ });
3369
+ });
3370
+
3371
+ describe('when highlights overlap', () => {
3372
+ const segmentationId = 'segmentationId';
3373
+ const defaultFillAlpha = 0.5;
3374
+ const labelmapKey = (segmentIndex: number) => `${segmentIndex}:Labelmap`;
3375
+ let frames: FrameRequestCallback[];
3376
+ let styles: Map<string, Record<string, number>>;
3377
+
3378
+ // Runs every queued animation frame once; the callbacks queue the next frames.
3379
+ const runFrame = (timestamp: number) => {
3380
+ const pending = frames;
3381
+ frames = [];
3382
+ pending.forEach(callback => callback(timestamp));
3383
+ };
3384
+
3385
+ const fillAlphaOf = (segmentIndex: number) =>
3386
+ styles.get(labelmapKey(segmentIndex))?.fillAlpha ?? defaultFillAlpha;
3387
+
3388
+ const mockRepresentation = (type: csToolsEnums.SegmentationRepresentations) => {
3389
+ jest
3390
+ .spyOn(service, 'getSegmentationRepresentations')
3391
+ .mockReturnValue([{ segmentationId, type }] as SegmentationRepresentation[]);
3392
+ };
3393
+
3394
+ beforeEach(() => {
3395
+ frames = [];
3396
+ jest.spyOn(window, 'requestAnimationFrame').mockImplementation(callback => {
3397
+ frames.push(callback);
3398
+ return frames.length;
3399
+ });
3400
+ jest.mocked(cstSegmentation.state.getSegmentation).mockReturnValue({
3401
+ segments: {},
3402
+ } as unknown as cstTypes.Segmentation);
3403
+
3404
+ // A per-segment style store, so a temporary highlight value is observable as
3405
+ // the start value of the next highlight that reads it.
3406
+ styles = new Map();
3407
+ jest
3408
+ .mocked(cstSegmentation.config.style.setStyle)
3409
+ .mockImplementation(({ segmentIndex, type }, style, merge = true) => {
3410
+ const key = `${segmentIndex}:${type}`;
3411
+ styles.set(key, merge ? { ...styles.get(key), ...style } : style);
3412
+ });
3413
+ jest
3414
+ .mocked(cstSegmentation.config.style.getStyle)
3415
+ .mockImplementation(({ segmentIndex, type }) =>
3416
+ type === 'Contour' ? { outlineWidth: 2 } : { fillAlpha: fillAlphaOf(segmentIndex) }
3417
+ );
3418
+ // Linear from the start value, so a frame's value shows the start it used.
3419
+ jest
3420
+ .spyOn(EasingFunctionMap, 'get')
3421
+ .mockReturnValue((progress: number, start: number) => start + progress);
3422
+ });
3423
+
3424
+ afterEach(() => {
3425
+ jest.mocked(window.requestAnimationFrame).mockRestore();
3426
+ jest.mocked(EasingFunctionMap.get).mockRestore();
3427
+ });
3428
+
3429
+ it('stops a superseded labelmap highlight and resets its fill at once', () => {
3430
+ mockRepresentation(csToolsEnums.SegmentationRepresentations.Labelmap);
3431
+
3432
+ service.highlightSegment(segmentationId, 1, viewportId, 0.9, 750, false);
3433
+ runFrame(0);
3434
+ runFrame(375);
3435
+ expect(fillAlphaOf(1)).toBe(defaultFillAlpha + 0.5);
3436
+
3437
+ service.highlightSegment(segmentationId, 2, viewportId, 0.9, 750, false);
3438
+
3439
+ expect(styles.get(labelmapKey(1))).toEqual({});
3440
+ expect(frames).toHaveLength(2);
3441
+ runFrame(400);
3442
+ expect(frames).toHaveLength(1);
3443
+ expect(styles.get(labelmapKey(1))).toEqual({});
3444
+ expect(fillAlphaOf(2)).toBe(defaultFillAlpha);
3445
+ });
3446
+
3447
+ it('stops a superseded contour highlight without resetting every other style', () => {
3448
+ mockRepresentation(csToolsEnums.SegmentationRepresentations.Contour);
3449
+
3450
+ service.highlightSegment(segmentationId, 1, viewportId);
3451
+ runFrame(performance.now());
3452
+ service.highlightSegment(segmentationId, 2, viewportId);
3453
+ jest.mocked(cstSegmentation.config.style.setStyle).mockClear();
3454
+
3455
+ runFrame(performance.now());
3456
+
3457
+ expect(frames).toHaveLength(1);
3458
+ expect(cstSegmentation.config.style.resetToGlobalStyle).not.toHaveBeenCalled();
3459
+ expect(styles.get('1:Contour')).toEqual({});
3460
+ expect(cstSegmentation.config.style.setStyle).toHaveBeenCalledTimes(1);
3461
+ expect(cstSegmentation.config.style.setStyle).toHaveBeenCalledWith(
3462
+ { segmentationId, segmentIndex: 2, type: 'Contour' },
3463
+ expect.objectContaining({ outlineWidth: expect.any(Number) })
3464
+ );
3465
+ });
3466
+
3467
+ it('continues a running highlight when the same segment is selected again', () => {
3468
+ mockRepresentation(csToolsEnums.SegmentationRepresentations.Labelmap);
3469
+
3470
+ service.highlightSegment(segmentationId, 1, viewportId, 0.9, 750, false);
3471
+ runFrame(0);
3472
+ runFrame(375);
3473
+ service.highlightSegment(segmentationId, 1, viewportId, 0.9, 750, false);
3474
+
3475
+ expect(frames).toHaveLength(1);
3476
+ runFrame(750);
3477
+ expect(frames).toHaveLength(0);
3478
+ expect(styles.get(labelmapKey(1))).toEqual({});
3479
+ });
3480
+
3481
+ it('starts a reselected segment from its real fill, even before the next frame', () => {
3482
+ mockRepresentation(csToolsEnums.SegmentationRepresentations.Labelmap);
3483
+
3484
+ service.highlightSegment(segmentationId, 1, viewportId, 0.9, 750, false);
3485
+ runFrame(0);
3486
+ runFrame(375);
3487
+ service.highlightSegment(segmentationId, 2, viewportId, 0.9, 750, false);
3488
+ service.highlightSegment(segmentationId, 1, viewportId, 0.9, 750, false);
3489
+ runFrame(400);
3490
+
3491
+ expect(fillAlphaOf(1)).toBe(defaultFillAlpha);
3492
+ runFrame(1150);
3493
+ expect(frames).toHaveLength(0);
3494
+ expect(styles.get(labelmapKey(1))).toEqual({});
3495
+ });
3496
+
3497
+ it('highlights a segment again after its highlight failed mid-animation', () => {
3498
+ mockRepresentation(csToolsEnums.SegmentationRepresentations.Labelmap);
3499
+
3500
+ service.highlightSegment(segmentationId, 1, viewportId, 0.9, 750, false);
3501
+ jest.mocked(cstSegmentation.config.style.setStyle).mockImplementationOnce(() => {
3502
+ throw new Error('segmentation is gone');
3503
+ });
3504
+ expect(() => runFrame(0)).toThrow('segmentation is gone');
3505
+
3506
+ service.highlightSegment(segmentationId, 1, viewportId, 0.9, 750, false);
3507
+
3508
+ expect(frames).toHaveLength(1);
3509
+ });
3510
+
3511
+ it('resets the temporary style when a frame fails after an earlier frame applied it', () => {
3512
+ mockRepresentation(csToolsEnums.SegmentationRepresentations.Labelmap);
3513
+
3514
+ service.highlightSegment(segmentationId, 1, viewportId, 0.9, 750, false);
3515
+ runFrame(0);
3516
+ expect(styles.get(labelmapKey(1))).not.toEqual({});
3517
+
3518
+ jest.mocked(cstSegmentation.config.style.setStyle).mockImplementationOnce(() => {
3519
+ throw new Error('frame failed');
3520
+ });
3521
+ expect(() => runFrame(375)).toThrow('frame failed');
3522
+
3523
+ expect(styles.get(labelmapKey(1))).toEqual({});
3524
+ });
3525
+
3526
+ it('reports the frame error when resetting the style also fails', () => {
3527
+ mockRepresentation(csToolsEnums.SegmentationRepresentations.Labelmap);
3528
+
3529
+ service.highlightSegment(segmentationId, 1, viewportId, 0.9, 750, false);
3530
+ runFrame(0);
3531
+ jest
3532
+ .mocked(cstSegmentation.config.style.setStyle)
3533
+ .mockImplementationOnce(() => {
3534
+ throw new Error('frame failed');
3535
+ })
3536
+ .mockImplementationOnce(() => {
3537
+ throw new Error('reset failed');
3538
+ });
3539
+
3540
+ expect(() => runFrame(375)).toThrow('frame failed');
3541
+ });
3542
+
3543
+ it('forgets the highlights of a removed segmentation', () => {
3544
+ mockRepresentation(csToolsEnums.SegmentationRepresentations.Labelmap);
3545
+
3546
+ service.highlightSegment(segmentationId, 1, viewportId, 0.9, 750, false);
3547
+ runFrame(0);
3548
+ (
3549
+ service as unknown as {
3550
+ _onSegmentationRemovedFromSource: (evt: { detail: { segmentationId: string } }) => void;
3551
+ }
3552
+ )._onSegmentationRemovedFromSource({ detail: { segmentationId } });
3553
+ runFrame(375);
3554
+ expect(frames).toHaveLength(0);
3555
+
3556
+ service.highlightSegment(segmentationId, 1, viewportId, 0.9, 750, false);
3557
+
3558
+ expect(frames).toHaveLength(1);
3559
+ });
3560
+
3561
+ it('replays the highlight when a segment whose highlight finished is selected again', () => {
3562
+ mockRepresentation(csToolsEnums.SegmentationRepresentations.Labelmap);
3563
+
3564
+ service.highlightSegment(segmentationId, 1, viewportId, 0.9, 750, false);
3565
+ runFrame(0);
3566
+ runFrame(750);
3567
+ service.highlightSegment(segmentationId, 1, viewportId, 0.9, 750, false);
3568
+
3569
+ expect(frames).toHaveLength(1);
3570
+ });
3571
+
3572
+ describe('when one jump highlights several viewports', () => {
3573
+ beforeEach(() => {
3574
+ jest.mocked(cstSegmentation.state.getSegmentation).mockReturnValue({
3575
+ segments: { 1: { cachedStats: { center: { world: [10, 10, 10] } } } },
3576
+ } as unknown as cstTypes.Segmentation);
3577
+ jest
3578
+ .spyOn(service, 'getViewportIdsWithSegmentation')
3579
+ .mockReturnValue(['viewportId1', 'viewportId2']);
3580
+ // @ts-expect-error - mock only needed properties
3581
+ getEnabledElementByViewportId.mockReturnValue({ viewport: { jumpToWorld: jest.fn() } });
3582
+ });
3583
+
3584
+ it('runs one animation for the style the viewports share', () => {
3585
+ mockRepresentation(csToolsEnums.SegmentationRepresentations.Labelmap);
3586
+
3587
+ service.jumpToSegmentCenter(segmentationId, 1);
3588
+ runFrame(0);
3589
+
3590
+ expect(frames).toHaveLength(1);
3591
+ expect(fillAlphaOf(1)).toBe(defaultFillAlpha);
3592
+ });
3593
+
3594
+ it('animates both a labelmap and a contour viewport', () => {
3595
+ jest.spyOn(service, 'getSegmentationRepresentations').mockImplementation(
3596
+ id =>
3597
+ [
3598
+ {
3599
+ segmentationId,
3600
+ type:
3601
+ id === 'viewportId1'
3602
+ ? csToolsEnums.SegmentationRepresentations.Labelmap
3603
+ : csToolsEnums.SegmentationRepresentations.Contour,
3604
+ },
3605
+ ] as SegmentationRepresentation[]
3606
+ );
3607
+
3608
+ service.jumpToSegmentCenter(segmentationId, 1);
3609
+ runFrame(performance.now());
3610
+
3611
+ expect(frames).toHaveLength(2);
3612
+ expect(cstSegmentation.config.style.setStyle).toHaveBeenCalledWith(
3613
+ { segmentationId, segmentIndex: 1, type: 'Labelmap' },
3614
+ expect.objectContaining({ fillAlpha: expect.any(Number) })
3615
+ );
3616
+ expect(cstSegmentation.config.style.setStyle).toHaveBeenCalledWith(
3617
+ { segmentationId, segmentIndex: 1, type: 'Contour' },
3618
+ expect.objectContaining({ outlineWidth: expect.any(Number) })
3619
+ );
3620
+ });
3621
+ });
3622
+ });
3623
+ });
3624
+
3625
+ describe('_onSegmentationDataModifiedFromSource', () => {
3626
+ it('should broadcast the event', () => {
3627
+ jest.spyOn(eventTarget, 'addEventListener').mockReturnValue(undefined);
3628
+
3629
+ const callback = jest.fn();
3630
+ service.subscribe(service.EVENTS.SEGMENTATION_DATA_MODIFIED, callback);
3631
+
3632
+ service.onModeEnter();
3633
+
3634
+ const _onSegmentationDataModifiedFromSource = jest.mocked(eventTarget.addEventListener).mock
3635
+ .calls[2][1];
3636
+
3637
+ _onSegmentationDataModifiedFromSource({
3638
+ detail: {
3639
+ segmentationId: 'segmentationId',
3640
+ },
3641
+ });
3642
+
3643
+ expect(callback).toHaveBeenCalledTimes(1);
3644
+ expect(callback).toHaveBeenCalledWith({
3645
+ segmentationId: 'segmentationId',
3646
+ });
3647
+ });
3648
+ });
3649
+
3650
+ describe('_onSegmentationRepresentationModifiedFromSource', () => {
3651
+ it('should broadcast the event', () => {
3652
+ jest.spyOn(eventTarget, 'addEventListener').mockReturnValue(undefined);
3653
+
3654
+ const callback = jest.fn();
3655
+ service.subscribe(service.EVENTS.SEGMENTATION_REPRESENTATION_MODIFIED, callback);
3656
+
3657
+ service.onModeEnter();
3658
+
3659
+ const _onSegmentationRepresentationModifiedFromSource = jest.mocked(
3660
+ eventTarget.addEventListener
3661
+ ).mock.calls[3][1];
3662
+
3663
+ _onSegmentationRepresentationModifiedFromSource({
3664
+ detail: {
3665
+ segmentationId: 'segmentationId',
3666
+ viewportId: 'viewportId',
3667
+ },
3668
+ });
3669
+
3670
+ expect(callback).toHaveBeenCalledTimes(1);
3671
+ expect(callback).toHaveBeenCalledWith({
3672
+ segmentationId: 'segmentationId',
3673
+ viewportId: 'viewportId',
3674
+ });
3675
+ });
3676
+ });
3677
+
3678
+ describe('_onSegmentationModifiedFromSource', () => {
3679
+ it('should broadcast the event', () => {
3680
+ jest.spyOn(eventTarget, 'addEventListener').mockReturnValue(undefined);
3681
+
3682
+ const callback = jest.fn();
3683
+ service.subscribe(service.EVENTS.SEGMENTATION_MODIFIED, callback);
3684
+
3685
+ service.onModeEnter();
3686
+
3687
+ const _onSegmentationModifiedFromSource = jest.mocked(eventTarget.addEventListener).mock
3688
+ .calls[0][1];
3689
+
3690
+ _onSegmentationModifiedFromSource({
3691
+ detail: {
3692
+ segmentationId: 'segmentationId',
3693
+ },
3694
+ });
3695
+
3696
+ expect(callback).toHaveBeenCalledTimes(1);
3697
+ expect(callback).toHaveBeenCalledWith({
3698
+ segmentationId: 'segmentationId',
3699
+ });
3700
+ });
3701
+ });
3702
+
3703
+ describe('_onSegmentationAddedFromSource', () => {
3704
+ it('should broadcast the event', () => {
3705
+ jest.spyOn(eventTarget, 'addEventListener').mockReturnValue(undefined);
3706
+
3707
+ const callback = jest.fn();
3708
+ service.subscribe(service.EVENTS.SEGMENTATION_ADDED, callback);
3709
+
3710
+ service.onModeEnter();
3711
+
3712
+ const _onSegmentationAddedFromSource = jest.mocked(eventTarget.addEventListener).mock
3713
+ .calls[6][1];
3714
+
3715
+ _onSegmentationAddedFromSource({
3716
+ detail: {
3717
+ segmentationId: 'segmentationId',
3718
+ },
3719
+ });
3720
+
3721
+ expect(callback).toHaveBeenCalledTimes(1);
3722
+ expect(callback).toHaveBeenCalledWith({
3723
+ segmentationId: 'segmentationId',
3724
+ });
3725
+ });
3726
+ });
3727
+ });