@ohif/extension-cornerstone 3.14.0-beta.11 → 3.14.0-beta.111

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 (328) 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 +2962 -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 +448 -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 +3698 -0
  158. package/src/services/SegmentationService/SegmentationService.ts +2376 -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 +671 -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.ts +83 -0
  227. package/src/utils/dicomLoaderService.js +225 -0
  228. package/src/utils/ecgMetadata.test.ts +137 -0
  229. package/src/utils/ecgMetadata.ts +109 -0
  230. package/src/utils/findNearbyToolData.test.ts +125 -0
  231. package/src/utils/findNearbyToolData.ts +21 -0
  232. package/src/utils/generateSegmentationCSVReport.test.ts +324 -0
  233. package/src/utils/generateSegmentationCSVReport.ts +131 -0
  234. package/src/utils/getActiveViewportEnabledElement.test.ts +70 -0
  235. package/src/utils/getActiveViewportEnabledElement.ts +8 -0
  236. package/src/utils/getCenterExtent.test.ts +313 -0
  237. package/src/utils/getCenterExtent.ts +46 -0
  238. package/src/utils/getCornerstoneBlendMode.test.ts +59 -0
  239. package/src/utils/getCornerstoneBlendMode.ts +25 -0
  240. package/src/utils/getCornerstoneOrientation.test.ts +78 -0
  241. package/src/utils/getCornerstoneOrientation.ts +31 -0
  242. package/src/utils/getCornerstoneViewportType.test.ts +169 -0
  243. package/src/utils/getCornerstoneViewportType.ts +88 -0
  244. package/src/utils/getInterleavedFrames.test.ts +85 -0
  245. package/src/utils/getInterleavedFrames.ts +73 -0
  246. package/src/utils/getLegacyViewportType.ts +64 -0
  247. package/src/utils/getNthFrames.test.ts +145 -0
  248. package/src/utils/getNthFrames.ts +31 -0
  249. package/src/utils/getViewportEnabledElement.test.ts +83 -0
  250. package/src/utils/getViewportEnabledElement.ts +8 -0
  251. package/src/utils/getViewportOrientationFromImageOrientationPatient.test.ts +50 -0
  252. package/src/utils/getViewportOrientationFromImageOrientationPatient.ts +56 -0
  253. package/src/utils/hydrationUtils.test.ts +572 -0
  254. package/src/utils/hydrationUtils.ts +197 -0
  255. package/src/utils/imageSliceSync/calculateViewportRegistrations.ts +28 -0
  256. package/src/utils/imageSliceSync/toggleImageSliceSync.ts +101 -0
  257. package/src/utils/index.ts +29 -0
  258. package/src/utils/initGpuSettingsPreset.ts +51 -0
  259. package/src/utils/initViewTiming.test.ts +342 -0
  260. package/src/utils/initViewTiming.ts +52 -0
  261. package/src/utils/initWebWorkerProgressHandler.test.ts +381 -0
  262. package/src/utils/initWebWorkerProgressHandler.ts +110 -0
  263. package/src/utils/interleave.test.ts +304 -0
  264. package/src/utils/interleave.ts +32 -0
  265. package/src/utils/interleaveCenterLoader.test.ts +547 -0
  266. package/src/utils/interleaveCenterLoader.ts +143 -0
  267. package/src/utils/interleaveTopToBottom.test.ts +487 -0
  268. package/src/utils/interleaveTopToBottom.ts +132 -0
  269. package/src/utils/isAnyDisplaySetCommon.ts +18 -0
  270. package/src/utils/isDisplaySetOverlayable.ts +96 -0
  271. package/src/utils/isMeasurementWithinViewport.test.ts +340 -0
  272. package/src/utils/isMeasurementWithinViewport.ts +33 -0
  273. package/src/utils/isReferenceViewable.test.ts +581 -0
  274. package/src/utils/isReferenceViewable.ts +95 -0
  275. package/src/utils/loadDisplaySetData.ts +49 -0
  276. package/src/utils/measurementServiceMappings/Angle.ts +200 -0
  277. package/src/utils/measurementServiceMappings/ArrowAnnotate.ts +176 -0
  278. package/src/utils/measurementServiceMappings/Bidirectional.ts +193 -0
  279. package/src/utils/measurementServiceMappings/CircleROI.ts +227 -0
  280. package/src/utils/measurementServiceMappings/CobbAngle.ts +206 -0
  281. package/src/utils/measurementServiceMappings/EllipticalROI.ts +221 -0
  282. package/src/utils/measurementServiceMappings/Length.ts +206 -0
  283. package/src/utils/measurementServiceMappings/LivewireContour.ts +175 -0
  284. package/src/utils/measurementServiceMappings/PlanarFreehandROI.ts +228 -0
  285. package/src/utils/measurementServiceMappings/Probe.ts +192 -0
  286. package/src/utils/measurementServiceMappings/RectangleROI.ts +225 -0
  287. package/src/utils/measurementServiceMappings/SegmentBidirectional.ts +184 -0
  288. package/src/utils/measurementServiceMappings/SplineROI.ts +227 -0
  289. package/src/utils/measurementServiceMappings/UltrasoundDirectional.ts +214 -0
  290. package/src/utils/measurementServiceMappings/UltrasoundPleuraBLine.ts +179 -0
  291. package/src/utils/measurementServiceMappings/constants/supportedTools.js +21 -0
  292. package/src/utils/measurementServiceMappings/index.ts +3 -0
  293. package/src/utils/measurementServiceMappings/measurementServiceMappingsFactory.ts +324 -0
  294. package/src/utils/measurementServiceMappings/utils/getDisplayUnit.js +3 -0
  295. package/src/utils/measurementServiceMappings/utils/getHandlesFromPoints.js +14 -0
  296. package/src/utils/measurementServiceMappings/utils/getIsLocked.ts +5 -0
  297. package/src/utils/measurementServiceMappings/utils/getIsVisible.ts +6 -0
  298. package/src/utils/measurementServiceMappings/utils/getSOPInstanceAttributes.js +66 -0
  299. package/src/utils/measurementServiceMappings/utils/getValueDisplayString.js +12 -0
  300. package/src/utils/measurementServiceMappings/utils/index.ts +17 -0
  301. package/src/utils/measurementServiceMappings/utils/selection.ts +33 -0
  302. package/src/utils/mpr/getProtocolViewportStructureFromGridViewports.ts +74 -0
  303. package/src/utils/nextViewportPolicies.ts +41 -0
  304. package/src/utils/nextViewports.ts +157 -0
  305. package/src/utils/nthLoader.test.ts +317 -0
  306. package/src/utils/nthLoader.ts +78 -0
  307. package/src/utils/presentations/getViewportPresentations.test.ts +280 -0
  308. package/src/utils/presentations/getViewportPresentations.ts +151 -0
  309. package/src/utils/promptHydrationDialog.test.ts +490 -0
  310. package/src/utils/promptHydrationDialog.ts +197 -0
  311. package/src/utils/removeViewportSegmentationRepresentations.test.ts +129 -0
  312. package/src/utils/removeViewportSegmentationRepresentations.ts +17 -0
  313. package/src/utils/segmentUtils.test.ts +515 -0
  314. package/src/utils/segmentUtils.ts +46 -0
  315. package/src/utils/segmentationExportUtils.test.ts +100 -0
  316. package/src/utils/segmentationExportUtils.ts +171 -0
  317. package/src/utils/segmentationHandlers.test.ts +614 -0
  318. package/src/utils/segmentationHandlers.ts +164 -0
  319. package/src/utils/setUpAnnotationEventHandlers.ts +26 -0
  320. package/src/utils/setUpSegmentationEventHandlers.test.ts +372 -0
  321. package/src/utils/setUpSegmentationEventHandlers.ts +122 -0
  322. package/src/utils/toggleVOISliceSync.test.ts +606 -0
  323. package/src/utils/toggleVOISliceSync.ts +103 -0
  324. package/src/utils/transitions.test.ts +351 -0
  325. package/src/utils/transitions.ts +300 -0
  326. package/src/utils/updateSegmentationStats.test.ts +942 -0
  327. package/src/utils/updateSegmentationStats.ts +192 -0
  328. package/src/utils/viewportDataShape.ts +85 -0
@@ -0,0 +1,3698 @@
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
+ };
1350
+
1351
+ const retrievedSegmentationId = await service.createLabelmapForDisplaySet(
1352
+ displaySet,
1353
+ options
1354
+ );
1355
+
1356
+ expect(imageLoader.createAndCacheDerivedLabelmapImages).toHaveBeenCalledTimes(1);
1357
+ expect(imageLoader.createAndCacheDerivedLabelmapImages).toHaveBeenCalledWith('timePoint2');
1358
+
1359
+ expect(service.addOrUpdateSegmentation).toHaveBeenCalledTimes(1);
1360
+ expect(service.addOrUpdateSegmentation).toHaveBeenCalledWith({
1361
+ config: {
1362
+ cachedStats: {
1363
+ info: 'S1: Series Description',
1364
+ },
1365
+ label: 'Segmentation 2',
1366
+ // The caller gave the label, so the label is not a generated one.
1367
+ labelIsGenerated: false,
1368
+ fallbackLabel: 'S:1 SEG',
1369
+ segments: {
1370
+ '1': {
1371
+ active: true,
1372
+ label: 'Custom Segment 1',
1373
+ },
1374
+ },
1375
+ },
1376
+ representation: {
1377
+ data: {
1378
+ imageIds: ['imageId'],
1379
+ referencedImageIds: 'timePoint2',
1380
+ },
1381
+ type: 'Labelmap',
1382
+ },
1383
+ segmentationId: segmentationId,
1384
+ });
1385
+
1386
+ expect(retrievedSegmentationId).toEqual(segmentationId);
1387
+ });
1388
+
1389
+ it('should create a dedicated color LUT and remember its index so every viewport representation reuses it', async () => {
1390
+ const displaySet = {
1391
+ imageIds: ['imageId'],
1392
+ isDynamicVolume: false,
1393
+ SeriesNumber: 1,
1394
+ SeriesDescription: 'Series Description',
1395
+ } as unknown as AppTypes.DisplaySet;
1396
+
1397
+ jest
1398
+ .spyOn(imageLoader, 'createAndCacheDerivedLabelmapImages')
1399
+ .mockReturnValue([{ imageId: 'imageId' }] as csTypes.IImage[]);
1400
+ jest.spyOn(cstSegmentation.state, 'getSegmentations').mockReturnValue([]);
1401
+ jest.spyOn(service, 'addOrUpdateSegmentation').mockReturnValue(undefined);
1402
+ jest.mocked(cstSegmentation.state.addColorLUT).mockReturnValue(7);
1403
+
1404
+ const segmentationId = await service.createLabelmapForDisplaySet(displaySet);
1405
+
1406
+ expect(cstSegmentation.state.addColorLUT).toHaveBeenCalledWith([[0, 0, 0, 0]]);
1407
+ expect(service['_segmentationIdToColorLUTIndexMap'].get(segmentationId)).toBe(7);
1408
+ });
1409
+
1410
+ it('should keep the existing color LUT when called again with the same segmentation id', async () => {
1411
+ const displaySet = {
1412
+ imageIds: ['imageId'],
1413
+ isDynamicVolume: false,
1414
+ SeriesNumber: 1,
1415
+ SeriesDescription: 'Series Description',
1416
+ } as unknown as AppTypes.DisplaySet;
1417
+
1418
+ jest
1419
+ .spyOn(imageLoader, 'createAndCacheDerivedLabelmapImages')
1420
+ .mockReturnValue([{ imageId: 'imageId' }] as csTypes.IImage[]);
1421
+ jest.spyOn(cstSegmentation.state, 'getSegmentations').mockReturnValue([]);
1422
+ jest.spyOn(service, 'addOrUpdateSegmentation').mockReturnValue(undefined);
1423
+ jest.mocked(cstSegmentation.state.addColorLUT).mockReturnValueOnce(7).mockReturnValueOnce(8);
1424
+
1425
+ const segmentationId = await service.createLabelmapForDisplaySet(displaySet);
1426
+ await service.createLabelmapForDisplaySet(displaySet, { segmentationId });
1427
+
1428
+ // Updating an existing segmentation must not strand the representations
1429
+ // already rendering it on the previous LUT.
1430
+ expect(cstSegmentation.state.addColorLUT).toHaveBeenCalledTimes(1);
1431
+ expect(service['_segmentationIdToColorLUTIndexMap'].get(segmentationId)).toBe(7);
1432
+ });
1433
+ });
1434
+
1435
+ describe('createSegmentationForSEGDisplaySet', () => {
1436
+ it('should throw an error if the type is not labelmap', async () => {
1437
+ await expect(
1438
+ service.createSegmentationForSEGDisplaySet(
1439
+ {},
1440
+ {
1441
+ type: csToolsEnums.SegmentationRepresentations.Contour,
1442
+ }
1443
+ )
1444
+ ).rejects.toThrow('Only labelmap type is supported for SEG display sets right now');
1445
+ });
1446
+
1447
+ it('should throw and error if the labelmap images are not found', async () => {
1448
+ await expect(
1449
+ service.createSegmentationForSEGDisplaySet({
1450
+ labelMapImages: [],
1451
+ })
1452
+ ).rejects.toThrow('SEG reading failed');
1453
+ });
1454
+
1455
+ it('should throw an error if the referenced display set is not found', async () => {
1456
+ jest
1457
+ .spyOn(serviceManagerMock.services.displaySetService, 'getDisplaySetByUID')
1458
+ .mockReturnValue({
1459
+ instances: [],
1460
+ });
1461
+
1462
+ await expect(
1463
+ service.createSegmentationForSEGDisplaySet({
1464
+ displaySetInstanceUID: 'display-set-uid',
1465
+ referencedDisplaySetInstanceUID: 'non-existent-display-set-uid',
1466
+ labelMapImages: [{}, {}],
1467
+ })
1468
+ ).rejects.toThrow('No instances were provided for the referenced display set of the SEG');
1469
+ });
1470
+
1471
+ it('it should create a segmentation for a SEG display set', async () => {
1472
+ const segmentationId = 'segmentationId';
1473
+
1474
+ const voxelManager = {
1475
+ getScalarData: jest.fn().mockReturnValue([1, 0, 0]),
1476
+ setScalarData: jest.fn(),
1477
+ };
1478
+
1479
+ const segDisplaySet = {
1480
+ centroids: new Map([
1481
+ [0, { image: { x: 0, y: 0, z: 0 }, world: { x: 0, y: 0, z: 0 } }],
1482
+ [2, { image: { x: 200, y: 200, z: 200 }, world: { x: 200, y: 200, z: 200 } }],
1483
+ ]),
1484
+ displaySetInstanceUID: 'display-set-uid',
1485
+ referencedDisplaySetInstanceUID: 'existent-display-set-uid',
1486
+ labelMapImages: [
1487
+ { imageId: 'imageId1', referencedImageId: 'referencedImageId1', voxelManager },
1488
+ { imageId: 'imageId2', referencedImageId: 'referencedImageId2', voxelManager },
1489
+ ],
1490
+ segMetadata: {
1491
+ data: [
1492
+ {},
1493
+ {
1494
+ SegmentedPropertyCategoryCodeSequence: {
1495
+ CodeMeaning: 'Segmented Property Category Code Sequence',
1496
+ },
1497
+ SegmentNumber: '1',
1498
+ SegmentLabel: 'Segment 1',
1499
+ SegmentAlgorithmType: 'MANUAL',
1500
+ SegmentAlgorithmName: 'OHIF Brush',
1501
+ SegmentedPropertyTypeCodeSequence: {
1502
+ CodeMeaning: 'Segmented Property Category Code Sequence',
1503
+ },
1504
+ rgba: [255, 0, 0, 255],
1505
+ },
1506
+ {
1507
+ SegmentedPropertyCategoryCodeSequence: {
1508
+ CodeMeaning: 'Segmented Property Category Code Sequence',
1509
+ },
1510
+ SegmentNumber: '2',
1511
+ SegmentAlgorithmType: 'MANUAL',
1512
+ SegmentAlgorithmName: 'OHIF Brush',
1513
+ SegmentedPropertyTypeCodeSequence: {
1514
+ CodeMeaning: 'Segmented Property Type Code Sequence',
1515
+ },
1516
+ rgba: [0, 255, 0, 255],
1517
+ },
1518
+ ],
1519
+ },
1520
+ SeriesDate: '2025-01-01',
1521
+ SeriesDescription: 'Series Description',
1522
+ Modality: 'SEG',
1523
+ SeriesNumber: 1,
1524
+ };
1525
+
1526
+ const referencedDisplaySet = {
1527
+ instances: [{ imageId: 'referencedImageId1' }, { imageId: 'referencedImageId2' }],
1528
+ };
1529
+
1530
+ jest
1531
+ .spyOn(serviceManagerMock.services.displaySetService, 'getDisplaySetByUID')
1532
+ .mockReturnValue(referencedDisplaySet);
1533
+ // @ts-expect-error - jest can't handle Array.prototype.flat typing
1534
+ jest.spyOn(Array.prototype, 'flat');
1535
+ jest.spyOn(metaData, 'get').mockReturnValue({});
1536
+ jest.spyOn(service, 'addOrUpdateSegmentation').mockReturnValue(undefined);
1537
+
1538
+ const callback = jest.fn();
1539
+ service.subscribe(service.EVENTS.SEGMENTATION_LOADING_COMPLETE, callback);
1540
+
1541
+ const retrievedSegmentationId = await service.createSegmentationForSEGDisplaySet(
1542
+ segDisplaySet,
1543
+ {
1544
+ type: csToolsEnums.SegmentationRepresentations.Labelmap,
1545
+ segmentationId,
1546
+ }
1547
+ );
1548
+
1549
+ expect(
1550
+ serviceManagerMock.services.displaySetService.getDisplaySetByUID
1551
+ ).toHaveBeenCalledTimes(1);
1552
+ expect(serviceManagerMock.services.displaySetService.getDisplaySetByUID).toHaveBeenCalledWith(
1553
+ 'existent-display-set-uid'
1554
+ );
1555
+
1556
+ expect(Array.prototype.flat).toHaveBeenCalledTimes(1);
1557
+
1558
+ expect(metaData.get).toHaveBeenCalledTimes(2);
1559
+ expect(metaData.get).toHaveBeenCalledWith('instance', 'referencedImageId1');
1560
+ expect(metaData.get).toHaveBeenCalledWith('instance', 'referencedImageId2');
1561
+
1562
+ expect(voxelManager.getScalarData).toHaveBeenCalledTimes(2);
1563
+ expect(voxelManager.getScalarData).toHaveBeenCalledWith();
1564
+ expect(voxelManager.setScalarData).toHaveBeenCalledTimes(2);
1565
+ expect(voxelManager.setScalarData).toHaveBeenCalledWith([1, 0, 0]);
1566
+
1567
+ expect(cstSegmentation.state.addColorLUT).toHaveBeenCalledTimes(1);
1568
+ expect(cstSegmentation.state.addColorLUT).toHaveBeenCalledWith([
1569
+ [0, 0, 0, 0],
1570
+ [255, 0, 0, 255],
1571
+ [0, 255, 0, 255],
1572
+ ]);
1573
+
1574
+ expect(callback).toHaveBeenCalledTimes(1);
1575
+ expect(callback).toHaveBeenCalledWith({
1576
+ segmentationId,
1577
+ segDisplaySet,
1578
+ });
1579
+
1580
+ const expectedSegmentation = {
1581
+ config: {
1582
+ label: segDisplaySet.SeriesDescription,
1583
+ fallbackLabel: 'S:1 SEG',
1584
+ segments: {
1585
+ '1': {
1586
+ active: false,
1587
+ cachedStats: {
1588
+ algorithmName: 'OHIF Brush',
1589
+ algorithmType: 'MANUAL',
1590
+ category: 'Segmented Property Category Code Sequence',
1591
+ center: {
1592
+ image: [0, 0, 0],
1593
+ world: [0, 0, 0],
1594
+ },
1595
+ modifiedTime: '2025-01-01',
1596
+ type: 'Segmented Property Category Code Sequence',
1597
+ },
1598
+ label: 'Segment 1',
1599
+ locked: false,
1600
+ segmentIndex: 1,
1601
+ },
1602
+ '2': {
1603
+ active: false,
1604
+ cachedStats: {
1605
+ algorithmName: 'OHIF Brush',
1606
+ algorithmType: 'MANUAL',
1607
+ category: 'Segmented Property Category Code Sequence',
1608
+ center: {
1609
+ image: [200, 200, 200],
1610
+ world: [200, 200, 200],
1611
+ },
1612
+ modifiedTime: '2025-01-01',
1613
+ type: 'Segmented Property Type Code Sequence',
1614
+ },
1615
+ label: 'Segment 2',
1616
+ locked: false,
1617
+ segmentIndex: 2,
1618
+ },
1619
+ },
1620
+ },
1621
+ representation: {
1622
+ data: {
1623
+ imageIds: ['imageId1', 'imageId2'],
1624
+ referencedImageIds: ['referencedImageId1', 'referencedImageId2'],
1625
+ },
1626
+ type: csToolsEnums.SegmentationRepresentations.Labelmap,
1627
+ },
1628
+ segmentationId,
1629
+ };
1630
+
1631
+ expect(service.addOrUpdateSegmentation).toHaveBeenCalledTimes(1);
1632
+ expect(service.addOrUpdateSegmentation).toHaveBeenCalledWith(expectedSegmentation);
1633
+
1634
+ const expectedSegDisplaySet = {
1635
+ ...segDisplaySet,
1636
+ firstSegmentedSliceImageId: 'referencedImageId1',
1637
+ imageIds: ['imageId1', 'imageId2'],
1638
+ images: [
1639
+ {
1640
+ imageId: 'imageId1',
1641
+ referencedImageId: 'referencedImageId1',
1642
+ voxelManager,
1643
+ },
1644
+ {
1645
+ imageId: 'imageId2',
1646
+ referencedImageId: 'referencedImageId2',
1647
+ voxelManager,
1648
+ },
1649
+ ],
1650
+ isLoaded: true,
1651
+ labelMapImages: [
1652
+ {
1653
+ imageId: 'imageId1',
1654
+ referencedImageId: 'referencedImageId1',
1655
+ voxelManager,
1656
+ },
1657
+ {
1658
+ imageId: 'imageId2',
1659
+ referencedImageId: 'referencedImageId2',
1660
+ voxelManager,
1661
+ },
1662
+ ],
1663
+ };
1664
+
1665
+ expect(segDisplaySet).toEqual(expectedSegDisplaySet);
1666
+
1667
+ expect(retrievedSegmentationId).toEqual(segmentationId);
1668
+ });
1669
+
1670
+ describe('overlap / useSliceRendering (next backend)', () => {
1671
+ const segmentationId = 'segmentationId';
1672
+
1673
+ // The session flag selects the seg-backend lane at SEG-load; reset it so it
1674
+ // never leaks into the legacy-path tests that follow.
1675
+ afterEach(() => {
1676
+ setNextViewportsEnabled(false);
1677
+ });
1678
+
1679
+ const segMetadata = {
1680
+ data: [
1681
+ {},
1682
+ { SegmentNumber: '1', SegmentLabel: 'Segment 1', rgba: [255, 0, 0, 255] },
1683
+ { SegmentNumber: '2', SegmentLabel: 'Segment 2', rgba: [0, 255, 0, 255] },
1684
+ ],
1685
+ };
1686
+ const centroids = new Map([
1687
+ [1, { image: { x: 0, y: 0, z: 0 }, world: { x: 0, y: 0, z: 0 } }],
1688
+ [2, { image: { x: 1, y: 1, z: 1 }, world: { x: 1, y: 1, z: 1 } }],
1689
+ ]);
1690
+
1691
+ // labelMapImages is the adapter's array-of-GROUPS (one conflict-free group per
1692
+ // overlap layer). Two groups whose voxels carry values {1} and {2} respectively.
1693
+ const makeOverlapGroups = () => {
1694
+ const vm0 = { getScalarData: jest.fn().mockReturnValue([1, 0]), setScalarData: jest.fn() };
1695
+ const vm1 = { getScalarData: jest.fn().mockReturnValue([0, 2]), setScalarData: jest.fn() };
1696
+ return [
1697
+ [
1698
+ { imageId: 'g0i1', referencedImageId: 'r1', voxelManager: vm0 },
1699
+ { imageId: 'g0i2', referencedImageId: 'r2', voxelManager: vm0 },
1700
+ ],
1701
+ [
1702
+ { imageId: 'g1i1', referencedImageId: 'r1', voxelManager: vm1 },
1703
+ { imageId: 'g1i2', referencedImageId: 'r2', voxelManager: vm1 },
1704
+ ],
1705
+ ];
1706
+ };
1707
+
1708
+ const makeSegDisplaySet = (labelMapImages, overlappingSegments) => ({
1709
+ centroids,
1710
+ displaySetInstanceUID: 'display-set-uid',
1711
+ referencedDisplaySetInstanceUID: 'existent-display-set-uid',
1712
+ labelMapImages,
1713
+ overlappingSegments,
1714
+ segMetadata,
1715
+ SeriesDate: '2025-01-01',
1716
+ SeriesDescription: 'Series Description',
1717
+ Modality: 'SEG',
1718
+ SeriesNumber: 1,
1719
+ });
1720
+
1721
+ const primeMocks = () => {
1722
+ jest
1723
+ .spyOn(serviceManagerMock.services.displaySetService, 'getDisplaySetByUID')
1724
+ .mockReturnValue({ instances: [{ imageId: 'r1' }, { imageId: 'r2' }] });
1725
+ jest.spyOn(metaData, 'get').mockReturnValue({});
1726
+ jest.spyOn(service, 'addOrUpdateSegmentation').mockReturnValue(undefined);
1727
+ };
1728
+
1729
+ it('flag ON + overlapping SEG builds one labelmap layer per group + segmentBindings', async () => {
1730
+ setNextViewportsEnabled(true);
1731
+ primeMocks();
1732
+
1733
+ await service.createSegmentationForSEGDisplaySet(
1734
+ makeSegDisplaySet(makeOverlapGroups(), true),
1735
+ { type: csToolsEnums.SegmentationRepresentations.Labelmap, segmentationId }
1736
+ );
1737
+
1738
+ const seg = jest.mocked(service.addOrUpdateSegmentation).mock.calls[0][0];
1739
+ const data = seg.representation.data as Record<string, any>;
1740
+
1741
+ // one labelmap layer per conflict-free group, under ONE segmentationId
1742
+ expect(Object.keys(data.labelmaps)).toEqual([
1743
+ 'segmentationId-storage-0',
1744
+ 'segmentationId-storage-1',
1745
+ ]);
1746
+ expect(data.labelmaps['segmentationId-storage-0'].imageIds).toEqual(['g0i1', 'g0i2']);
1747
+ expect(data.labelmaps['segmentationId-storage-1'].imageIds).toEqual(['g1i1', 'g1i2']);
1748
+ expect(data.labelmaps['segmentationId-storage-0'].storageKind).toBe('stack');
1749
+
1750
+ // segment->layer bindings recovered from the distinct non-zero voxel values
1751
+ expect(data.segmentBindings).toEqual({
1752
+ 1: { labelmapId: 'segmentationId-storage-0', labelValue: 1 },
1753
+ 2: { labelmapId: 'segmentationId-storage-1', labelValue: 2 },
1754
+ });
1755
+ expect(data.primaryLabelmapId).toBe('segmentationId-storage-0');
1756
+ // flattened list retained for legacy singular readers
1757
+ expect(data.imageIds).toEqual(['g0i1', 'g0i2', 'g1i1', 'g1i2']);
1758
+ });
1759
+
1760
+ it('flag ON + non-overlapping SEG stays a single layer (no multi-layer map)', async () => {
1761
+ setNextViewportsEnabled(true);
1762
+ primeMocks();
1763
+
1764
+ const vm = { getScalarData: jest.fn().mockReturnValue([1, 0]), setScalarData: jest.fn() };
1765
+ const singleGroup = [
1766
+ [
1767
+ { imageId: 'i1', referencedImageId: 'r1', voxelManager: vm },
1768
+ { imageId: 'i2', referencedImageId: 'r2', voxelManager: vm },
1769
+ ],
1770
+ ];
1771
+
1772
+ await service.createSegmentationForSEGDisplaySet(makeSegDisplaySet(singleGroup, false), {
1773
+ type: csToolsEnums.SegmentationRepresentations.Labelmap,
1774
+ segmentationId,
1775
+ });
1776
+
1777
+ const seg = jest.mocked(service.addOrUpdateSegmentation).mock.calls[0][0];
1778
+ const data = seg.representation.data as Record<string, any>;
1779
+ expect(data.labelmaps).toBeUndefined();
1780
+ expect(data.segmentBindings).toBeUndefined();
1781
+ expect(data.imageIds).toEqual(['i1', 'i2']);
1782
+ });
1783
+
1784
+ it('flag OFF + overlapping SEG collapses to a single flattened layer (legacy byte-identical)', async () => {
1785
+ // flag stays off (default)
1786
+ primeMocks();
1787
+
1788
+ await service.createSegmentationForSEGDisplaySet(
1789
+ makeSegDisplaySet(makeOverlapGroups(), true),
1790
+ { type: csToolsEnums.SegmentationRepresentations.Labelmap, segmentationId }
1791
+ );
1792
+
1793
+ const seg = jest.mocked(service.addOrUpdateSegmentation).mock.calls[0][0];
1794
+ const data = seg.representation.data as Record<string, any>;
1795
+ expect(data.labelmaps).toBeUndefined();
1796
+ expect(data.imageIds).toEqual(['g0i1', 'g0i2', 'g1i1', 'g1i2']);
1797
+ });
1798
+ });
1799
+ });
1800
+
1801
+ describe('createSegmentationForRTDisplaySet', () => {
1802
+ it('should throw an error if the type is not contour', async () => {
1803
+ await expect(
1804
+ service.createSegmentationForRTDisplaySet(
1805
+ {
1806
+ modality: 'RTSTRUCT',
1807
+ },
1808
+ {
1809
+ type: csToolsEnums.SegmentationRepresentations.Labelmap,
1810
+ }
1811
+ )
1812
+ ).rejects.toThrow('Only contour type is supported for RT display sets right now');
1813
+ });
1814
+
1815
+ it('should throw an error if the structureSet is not loaded', async () => {
1816
+ await expect(
1817
+ service.createSegmentationForRTDisplaySet(
1818
+ {
1819
+ modality: 'RTSTRUCT',
1820
+ displaySetInstanceUID: 'display-set-uid',
1821
+ },
1822
+ {
1823
+ type: csToolsEnums.SegmentationRepresentations.Contour,
1824
+ }
1825
+ )
1826
+ ).rejects.toThrow(
1827
+ 'To create the contours from RT displaySet, the displaySet should be loaded first. You can perform rtDisplaySet.load() before calling this method.'
1828
+ );
1829
+ });
1830
+
1831
+ it('should throw and error if structureSet does not contain any ROIContours', async () => {
1832
+ const rtStructDisplaySet = {
1833
+ modality: 'RTSTRUCT',
1834
+ displaySetInstanceUID: 'display-set-uid',
1835
+ referencedDisplaySetInstanceUID: 'existent-display-set-uid',
1836
+ structureSet: {
1837
+ ReferencedSOPInstanceUIDsSet: new Set(['referencedImageId1', 'referencedImageId2']),
1838
+ ROIContours: [],
1839
+ },
1840
+ };
1841
+
1842
+ const referencedDisplaySet = {
1843
+ instances: [{ imageId: 'referencedImageId1' }, { imageId: 'referencedImageId2' }],
1844
+ };
1845
+
1846
+ jest
1847
+ .spyOn(serviceManagerMock.services.displaySetService, 'getDisplaySetByUID')
1848
+ .mockReturnValue(referencedDisplaySet);
1849
+
1850
+ await expect(
1851
+ service.createSegmentationForRTDisplaySet(rtStructDisplaySet, {
1852
+ type: csToolsEnums.SegmentationRepresentations.Contour,
1853
+ })
1854
+ ).rejects.toThrow(
1855
+ 'The structureSet does not contain any ROIContours. Please ensure the structureSet is loaded first.'
1856
+ );
1857
+
1858
+ expect(
1859
+ serviceManagerMock.services.displaySetService.getDisplaySetByUID
1860
+ ).toHaveBeenCalledTimes(1);
1861
+ expect(serviceManagerMock.services.displaySetService.getDisplaySetByUID).toHaveBeenCalledWith(
1862
+ 'existent-display-set-uid'
1863
+ );
1864
+ });
1865
+
1866
+ it('should create a segmentation for a RTSTRUCT display set', async () => {
1867
+ const segmentationId = 'segmentationId';
1868
+ const rtStructDisplaySet = {
1869
+ Modality: 'RTSTRUCT',
1870
+ displaySetInstanceUID: 'display-set-uid',
1871
+ referencedDisplaySetInstanceUID: 'existent-display-set-uid',
1872
+ SeriesDate: '2025-01-01',
1873
+ SeriesDescription: 'Series Description',
1874
+ structureSet: {
1875
+ ReferencedSOPInstanceUIDsSet: new Set(['referencedIsmageId1', 'referencedImageId2']),
1876
+ ROIContours: [{}, {}, {}],
1877
+ frameOfReferenceUID: 'frameOfReferenceUID',
1878
+ },
1879
+ SeriesNumber: 1,
1880
+ };
1881
+
1882
+ const referencedDisplaySet = {
1883
+ instances: [{ imageId: 'referencedImageId1' }, { imageId: 'referencedImageId2' }],
1884
+ imageIds: ['referencedImageId1', 'referencedImageId2'],
1885
+ };
1886
+
1887
+ const allRTStructData = [
1888
+ {
1889
+ data: {},
1890
+ id: 'id3',
1891
+ color: [255, 0, 0, 255],
1892
+ group: 'group3',
1893
+ segmentIndex: 3,
1894
+ geometryId: 'geometryId3',
1895
+ },
1896
+ {
1897
+ data: {},
1898
+ id: 'id2',
1899
+ color: [0, 255, 0, 255],
1900
+ group: 'group2',
1901
+ segmentIndex: 2,
1902
+ geometryId: 'geometryId2',
1903
+ },
1904
+ {
1905
+ data: {},
1906
+ id: 'id1',
1907
+ color: [0, 0, 255, 255],
1908
+ group: 'group1',
1909
+ segmentIndex: 1,
1910
+ geometryId: 'geometryId1',
1911
+ },
1912
+ ];
1913
+
1914
+ jest
1915
+ .spyOn(serviceManagerMock.services.displaySetService, 'getDisplaySetByUID')
1916
+ .mockReturnValue(referencedDisplaySet);
1917
+ jest
1918
+ .spyOn(MapROIContoursToRTStructData, 'mapROIContoursToRTStructData')
1919
+ .mockReturnValue(allRTStructData);
1920
+ jest.spyOn(service, 'addOrUpdateSegmentation').mockReturnValue(undefined);
1921
+ jest.spyOn(geometryLoader, 'createAndCacheGeometry').mockReturnValue({
1922
+ // @ts-expect-error - only mocking needed properties
1923
+ data: { centroid: [0, 0, 0] },
1924
+ });
1925
+
1926
+ const segmentLoadingCompleteCallback = jest.fn();
1927
+ service.subscribe(service.EVENTS.SEGMENT_LOADING_COMPLETE, segmentLoadingCompleteCallback);
1928
+
1929
+ const segmentationLoadingCompleteCallback = jest.fn();
1930
+ service.subscribe(
1931
+ service.EVENTS.SEGMENTATION_LOADING_COMPLETE,
1932
+ segmentationLoadingCompleteCallback
1933
+ );
1934
+
1935
+ const retrievedSegmentationId = await service.createSegmentationForRTDisplaySet(
1936
+ rtStructDisplaySet,
1937
+ {
1938
+ type: csToolsEnums.SegmentationRepresentations.Contour,
1939
+ segmentationId,
1940
+ }
1941
+ );
1942
+
1943
+ expect(MapROIContoursToRTStructData.mapROIContoursToRTStructData).toHaveBeenCalledTimes(1);
1944
+ expect(MapROIContoursToRTStructData.mapROIContoursToRTStructData).toHaveBeenCalledWith(
1945
+ rtStructDisplaySet.structureSet,
1946
+ rtStructDisplaySet.displaySetInstanceUID
1947
+ );
1948
+
1949
+ expect(geometryLoader.createAndCacheGeometry).toHaveBeenCalledTimes(3);
1950
+ allRTStructData.forEach(data => {
1951
+ expect(geometryLoader.createAndCacheGeometry).toHaveBeenCalledWith(data.geometryId, {
1952
+ geometryData: {
1953
+ data: data.data,
1954
+ id: data.id,
1955
+ color: data.color,
1956
+ frameOfReferenceUID: rtStructDisplaySet.structureSet.frameOfReferenceUID,
1957
+ segmentIndex: data.segmentIndex,
1958
+ },
1959
+ type: csEnums.GeometryType.CONTOUR,
1960
+ });
1961
+ });
1962
+
1963
+ expect(segmentLoadingCompleteCallback).toHaveBeenCalledTimes(3);
1964
+ expect(segmentLoadingCompleteCallback).toHaveBeenCalledWith({
1965
+ percentComplete: expect.any(Number),
1966
+ numSegments: 3,
1967
+ });
1968
+
1969
+ expect(cstSegmentation.state.addColorLUT).toHaveBeenCalledTimes(1);
1970
+ expect(cstSegmentation.state.addColorLUT).toHaveBeenCalledWith([
1971
+ [0, 0, 0, 0],
1972
+ [0, 0, 255, 255],
1973
+ [0, 255, 0, 255],
1974
+ [255, 0, 0, 255],
1975
+ ]);
1976
+
1977
+ expect(segmentationLoadingCompleteCallback).toHaveBeenCalledTimes(1);
1978
+ expect(segmentationLoadingCompleteCallback).toHaveBeenCalledWith({
1979
+ segmentationId,
1980
+ rtDisplaySet: rtStructDisplaySet,
1981
+ });
1982
+
1983
+ const expectedSegmentation = {
1984
+ config: {
1985
+ label: rtStructDisplaySet.SeriesDescription,
1986
+ fallbackLabel: 'S:1 RTSTRUCT',
1987
+ segments: {
1988
+ '1': {
1989
+ active: false,
1990
+ cachedStats: {
1991
+ center: {
1992
+ world: [0, 0, 0],
1993
+ },
1994
+ modifiedTime: rtStructDisplaySet.SeriesDate,
1995
+ },
1996
+ group: 'group1',
1997
+ label: 'id1',
1998
+ locked: false,
1999
+ segmentIndex: 1,
2000
+ },
2001
+ '2': {
2002
+ active: false,
2003
+ cachedStats: {
2004
+ center: {
2005
+ world: [0, 0, 0],
2006
+ },
2007
+ modifiedTime: rtStructDisplaySet.SeriesDate,
2008
+ },
2009
+ group: 'group2',
2010
+ label: 'id2',
2011
+ locked: false,
2012
+ segmentIndex: 2,
2013
+ },
2014
+ '3': {
2015
+ active: false,
2016
+ cachedStats: {
2017
+ center: {
2018
+ world: [0, 0, 0],
2019
+ },
2020
+ modifiedTime: rtStructDisplaySet.SeriesDate,
2021
+ },
2022
+ group: 'group3',
2023
+ label: 'id3',
2024
+ locked: false,
2025
+ segmentIndex: 3,
2026
+ },
2027
+ },
2028
+ },
2029
+ representation: {
2030
+ data: {
2031
+ geometryIds: ['geometryId1', 'geometryId2', 'geometryId3'],
2032
+ },
2033
+ type: csToolsEnums.SegmentationRepresentations.Contour,
2034
+ },
2035
+ segmentationId,
2036
+ };
2037
+ expect(service.addOrUpdateSegmentation).toHaveBeenCalledTimes(1);
2038
+ expect(service.addOrUpdateSegmentation).toHaveBeenCalledWith(expectedSegmentation);
2039
+
2040
+ expect(retrievedSegmentationId).toEqual(segmentationId);
2041
+
2042
+ const expectedRtStructDisplaySet = {
2043
+ ...rtStructDisplaySet,
2044
+ isLoaded: true,
2045
+ };
2046
+
2047
+ expect(rtStructDisplaySet).toEqual(expectedRtStructDisplaySet);
2048
+ });
2049
+
2050
+ it('should ignore when a segment fails to initialize', async () => {
2051
+ const segmentationId = 'segmentationId';
2052
+ const rtStructDisplaySet = {
2053
+ modality: 'RTSTRUCT',
2054
+ displaySetInstanceUID: 'display-set-uid',
2055
+ referencedDisplaySetInstanceUID: 'existent-display-set-uid',
2056
+ SeriesDate: '2025-01-01',
2057
+ SeriesDescription: 'Series Description',
2058
+ structureSet: {
2059
+ ReferencedSOPInstanceUIDsSet: new Set(['referencedIsmageId1', 'referencedImageId2']),
2060
+ ROIContours: [{}, {}, {}],
2061
+ frameOfReferenceUID: 'frameOfReferenceUID',
2062
+ },
2063
+ };
2064
+
2065
+ const referencedDisplaySet = {
2066
+ instances: [{ imageId: 'referencedImageId1' }, { imageId: 'referencedImageId2' }],
2067
+ };
2068
+
2069
+ const allRTStructData = [
2070
+ {
2071
+ data: {},
2072
+ id: 'id3',
2073
+ color: [255, 0, 0, 255],
2074
+ group: 'group3',
2075
+ segmentIndex: 3,
2076
+ geometryId: 'geometryId3',
2077
+ },
2078
+ ];
2079
+
2080
+ jest
2081
+ .spyOn(serviceManagerMock.services.displaySetService, 'getDisplaySetByUID')
2082
+ .mockReturnValue(referencedDisplaySet);
2083
+ jest
2084
+ .spyOn(MapROIContoursToRTStructData, 'mapROIContoursToRTStructData')
2085
+ .mockReturnValue(allRTStructData);
2086
+ jest
2087
+ .spyOn(geometryLoader, 'createAndCacheGeometry')
2088
+ .mockRejectedValue(new Error('Segment Initialization Error') as never);
2089
+ jest.spyOn(console, 'warn').mockImplementation(() => {});
2090
+ jest.spyOn(service, 'addOrUpdateSegmentation').mockReturnValue(undefined);
2091
+
2092
+ const segmentLoadingCompleteCallback = jest.fn();
2093
+ service.subscribe(service.EVENTS.SEGMENT_LOADING_COMPLETE, segmentLoadingCompleteCallback);
2094
+
2095
+ const segmentationLoadingCompleteCallback = jest.fn();
2096
+ service.subscribe(
2097
+ service.EVENTS.SEGMENTATION_LOADING_COMPLETE,
2098
+ segmentationLoadingCompleteCallback
2099
+ );
2100
+
2101
+ await expect(
2102
+ service.createSegmentationForRTDisplaySet(rtStructDisplaySet, {
2103
+ type: csToolsEnums.SegmentationRepresentations.Contour,
2104
+ segmentationId,
2105
+ })
2106
+ ).resolves.not.toThrow();
2107
+
2108
+ expect(segmentLoadingCompleteCallback).not.toHaveBeenCalled();
2109
+
2110
+ expect(console.warn).toHaveBeenCalledTimes(1);
2111
+ expect(console.warn).toHaveBeenCalledWith(
2112
+ `Error initializing contour for segment ${allRTStructData[0].segmentIndex}:`,
2113
+ expect.any(Error)
2114
+ );
2115
+
2116
+ expect(segmentationLoadingCompleteCallback).toHaveBeenCalledTimes(1);
2117
+
2118
+ expect(service.addOrUpdateSegmentation).toHaveBeenCalledTimes(1);
2119
+ });
2120
+ });
2121
+
2122
+ describe('addOrUpdateSegmentation', () => {
2123
+ it('should add new segmentation if it does not exist', () => {
2124
+ const segmentationId = 'segmentationId';
2125
+ const segmentationData = {
2126
+ segmentationId,
2127
+ representation: {
2128
+ type: csToolsEnums.SegmentationRepresentations.Labelmap,
2129
+ data: {},
2130
+ },
2131
+ config: {
2132
+ label: 'Segmentation 1',
2133
+ },
2134
+ };
2135
+
2136
+ jest.spyOn(cstSegmentation.state, 'getSegmentation').mockReturnValue(undefined);
2137
+ jest.spyOn(cstSegmentation, 'addSegmentations').mockReturnValue(undefined);
2138
+
2139
+ service.addOrUpdateSegmentation(segmentationData);
2140
+
2141
+ expect(cstSegmentation.state.getSegmentation).toHaveBeenCalledTimes(1);
2142
+ expect(cstSegmentation.state.getSegmentation).toHaveBeenCalledWith(segmentationId);
2143
+
2144
+ expect(cstSegmentation.addSegmentations).toHaveBeenCalledTimes(1);
2145
+ expect(cstSegmentation.addSegmentations).toHaveBeenCalledWith([segmentationData]);
2146
+ });
2147
+
2148
+ it('should update existing segmentation if it exists', () => {
2149
+ const segmentationId = 'segmentationId';
2150
+ const segmentationData = {
2151
+ segmentationId,
2152
+ config: {
2153
+ label: 'Segmentation 1',
2154
+ },
2155
+ };
2156
+
2157
+ jest
2158
+ .spyOn(cstSegmentation.state, 'getSegmentation')
2159
+ .mockReturnValue(mockCornerstoneSegmentation);
2160
+ jest.spyOn(cstSegmentation, 'updateSegmentations').mockReturnValue(undefined);
2161
+
2162
+ service.addOrUpdateSegmentation(segmentationData);
2163
+
2164
+ expect(cstSegmentation.updateSegmentations).toHaveBeenCalledTimes(1);
2165
+ expect(cstSegmentation.updateSegmentations).toHaveBeenCalledWith([
2166
+ { segmentationId, payload: segmentationData },
2167
+ ]);
2168
+ });
2169
+ });
2170
+
2171
+ describe('setActiveSegmentation', () => {
2172
+ it('should set the active segmentation for a viewport', () => {
2173
+ const viewportId = 'viewportId';
2174
+ const segmentationId = 'segmentationId';
2175
+
2176
+ service.setActiveSegmentation(viewportId, segmentationId);
2177
+
2178
+ expect(cstSegmentation.activeSegmentation.setActiveSegmentation).toHaveBeenCalledTimes(1);
2179
+ expect(cstSegmentation.activeSegmentation.setActiveSegmentation).toHaveBeenCalledWith(
2180
+ viewportId,
2181
+ segmentationId
2182
+ );
2183
+ });
2184
+ });
2185
+
2186
+ describe('getActiveSegmentation', () => {
2187
+ it('should get the active segmentation for a viewport', () => {
2188
+ const viewportId = 'viewportId';
2189
+
2190
+ service.getActiveSegmentation(viewportId);
2191
+
2192
+ expect(cstSegmentation.activeSegmentation.getActiveSegmentation).toHaveBeenCalledTimes(1);
2193
+ expect(cstSegmentation.activeSegmentation.getActiveSegmentation).toHaveBeenCalledWith(
2194
+ viewportId
2195
+ );
2196
+ });
2197
+ });
2198
+
2199
+ describe('getActiveSegment', () => {
2200
+ it('should return undefined if no active segmentation', () => {
2201
+ const viewportId = 'viewportId';
2202
+ jest.spyOn(cstSegmentation.activeSegmentation, 'getActiveSegmentation').mockReturnValue(null);
2203
+
2204
+ const activeSegment = service.getActiveSegment(viewportId);
2205
+
2206
+ expect(cstSegmentation.activeSegmentation.getActiveSegmentation).toHaveBeenCalledTimes(1);
2207
+ expect(cstSegmentation.activeSegmentation.getActiveSegmentation).toHaveBeenCalledWith(
2208
+ viewportId
2209
+ );
2210
+
2211
+ expect(activeSegment).toBeUndefined();
2212
+ });
2213
+
2214
+ it('should find and return the active segment', () => {
2215
+ const viewportId = 'viewportId';
2216
+ jest
2217
+ .spyOn(cstSegmentation.activeSegmentation, 'getActiveSegmentation')
2218
+ .mockReturnValue(mockCornerstoneSegmentation);
2219
+
2220
+ const activeSegment = service.getActiveSegment(viewportId);
2221
+
2222
+ expect(activeSegment).toEqual(mockCornerstoneSegmentation.segments['1']);
2223
+ });
2224
+ });
2225
+
2226
+ describe('hasCustomStyles', () => {
2227
+ it('should return true if the segmentation has custom styles', () => {
2228
+ const viewportId = 'viewportId';
2229
+ const segmentationId = 'segmentationId';
2230
+ const type = csToolsEnums.SegmentationRepresentations.Contour;
2231
+
2232
+ jest.spyOn(cstSegmentation.config.style, 'hasCustomStyle').mockReturnValue(true);
2233
+
2234
+ const hasCustomStyles = service.hasCustomStyles({ viewportId, segmentationId, type });
2235
+
2236
+ expect(cstSegmentation.config.style.hasCustomStyle).toHaveBeenCalledTimes(1);
2237
+ expect(cstSegmentation.config.style.hasCustomStyle).toHaveBeenCalledWith({
2238
+ viewportId,
2239
+ segmentationId,
2240
+ type,
2241
+ });
2242
+
2243
+ expect(hasCustomStyles).toBe(true);
2244
+ });
2245
+ });
2246
+
2247
+ describe('getStyle', () => {
2248
+ it('should return the style for the segmentation', () => {
2249
+ const viewportId = 'viewportId';
2250
+ const segmentationId = 'segmentationId';
2251
+ const type = csToolsEnums.SegmentationRepresentations.Contour;
2252
+ const segmentIndex = 1;
2253
+
2254
+ jest.spyOn(cstSegmentation.config.style, 'getStyle').mockReturnValue({});
2255
+
2256
+ const style = service.getStyle({ viewportId, segmentationId, type, segmentIndex });
2257
+
2258
+ expect(cstSegmentation.config.style.getStyle).toHaveBeenCalledTimes(1);
2259
+ expect(cstSegmentation.config.style.getStyle).toHaveBeenCalledWith({
2260
+ viewportId,
2261
+ segmentationId,
2262
+ type,
2263
+ segmentIndex,
2264
+ });
2265
+
2266
+ expect(style).toEqual({});
2267
+ });
2268
+ });
2269
+
2270
+ describe('setStyle', () => {
2271
+ it('should set the style for the segmentation', () => {
2272
+ const viewportId = 'viewportId';
2273
+ const segmentationId = 'segmentationId';
2274
+ const type = csToolsEnums.SegmentationRepresentations.Contour;
2275
+ const segmentIndex = 1;
2276
+ const style = {
2277
+ fillAlpha: 0.5,
2278
+ outlineWidth: 2,
2279
+ renderOutline: true,
2280
+ renderFill: true,
2281
+ };
2282
+
2283
+ jest.spyOn(cstSegmentation.config.style, 'setStyle').mockReturnValue(undefined);
2284
+
2285
+ service.setStyle({ viewportId, segmentationId, type, segmentIndex }, style);
2286
+
2287
+ expect(cstSegmentation.config.style.setStyle).toHaveBeenCalledTimes(1);
2288
+ expect(cstSegmentation.config.style.setStyle).toHaveBeenCalledWith(
2289
+ {
2290
+ viewportId,
2291
+ segmentationId,
2292
+ type,
2293
+ segmentIndex,
2294
+ },
2295
+ style,
2296
+ true
2297
+ );
2298
+ });
2299
+ });
2300
+
2301
+ describe('resetToGlobalStyle', () => {
2302
+ it('should reset the style for the segmentation', () => {
2303
+ jest.spyOn(cstSegmentation.config.style, 'resetToGlobalStyle').mockReturnValue(undefined);
2304
+
2305
+ service.resetToGlobalStyle();
2306
+
2307
+ expect(cstSegmentation.config.style.resetToGlobalStyle).toHaveBeenCalledTimes(1);
2308
+ expect(cstSegmentation.config.style.resetToGlobalStyle).toHaveBeenCalledWith();
2309
+ });
2310
+ });
2311
+
2312
+ describe('addSegment', () => {
2313
+ it('should throw an error if the segment index is 0', () => {
2314
+ const segmentationId = 'segmentationId';
2315
+ const config = {
2316
+ segmentIndex: 0,
2317
+ };
2318
+
2319
+ expect(() => service.addSegment(segmentationId, config)).toThrow(
2320
+ 'Segment index 0 is reserved for "no label"'
2321
+ );
2322
+ });
2323
+
2324
+ it('should add a new segment with next available index if not provided', () => {
2325
+ const segmentationId = 'segmentationId';
2326
+ const config = {
2327
+ label: 'New Segment 2',
2328
+ visibility: true,
2329
+ };
2330
+
2331
+ jest
2332
+ .spyOn(cstSegmentation.state, 'getSegmentation')
2333
+ .mockReturnValue(mockCornerstoneSegmentation);
2334
+ jest.spyOn(cstSegmentation, 'updateSegmentations').mockReturnValue(undefined);
2335
+ jest.spyOn(cstSegmentation.segmentIndex, 'setActiveSegmentIndex').mockReturnValue(undefined);
2336
+ jest
2337
+ .spyOn(cstSegmentation.state, 'getViewportIdsWithSegmentation')
2338
+ .mockReturnValue(['viewportId']);
2339
+ jest
2340
+ .spyOn(cstSegmentation.config.visibility, 'setSegmentIndexVisibility')
2341
+ .mockReturnValue(undefined);
2342
+
2343
+ service.addSegment(segmentationId, config);
2344
+
2345
+ expect(cstSegmentation.state.getSegmentation).toHaveBeenCalledTimes(2);
2346
+ expect(cstSegmentation.state.getSegmentation).toHaveBeenCalledWith(segmentationId);
2347
+
2348
+ expect(cstSegmentation.updateSegmentations).toHaveBeenCalledTimes(1);
2349
+ expect(cstSegmentation.updateSegmentations).toHaveBeenCalledWith([
2350
+ {
2351
+ segmentationId,
2352
+ payload: {
2353
+ segments: {
2354
+ ...mockCornerstoneSegmentation.segments,
2355
+ '2': {
2356
+ label: 'New Segment 2',
2357
+ segmentIndex: 2,
2358
+ cachedStats: {},
2359
+ locked: false,
2360
+ ...config,
2361
+ },
2362
+ },
2363
+ },
2364
+ },
2365
+ ]);
2366
+
2367
+ expect(cstSegmentation.segmentIndex.setActiveSegmentIndex).toHaveBeenCalledTimes(1);
2368
+ expect(cstSegmentation.segmentIndex.setActiveSegmentIndex).toHaveBeenCalledWith(
2369
+ segmentationId,
2370
+ 2
2371
+ );
2372
+
2373
+ expect(cstSegmentation.state.getViewportIdsWithSegmentation).toHaveBeenCalledTimes(1);
2374
+ expect(cstSegmentation.state.getViewportIdsWithSegmentation).toHaveBeenCalledWith(
2375
+ segmentationId
2376
+ );
2377
+
2378
+ expect(cstSegmentation.config.visibility.setSegmentIndexVisibility).toHaveBeenCalledTimes(1);
2379
+ expect(cstSegmentation.config.visibility.setSegmentIndexVisibility).toHaveBeenCalledWith(
2380
+ 'viewportId',
2381
+ { segmentationId, type: undefined },
2382
+ 2,
2383
+ config.visibility
2384
+ );
2385
+ });
2386
+
2387
+ it('should set properties if segment index already exists', () => {
2388
+ const segmentationId = 'segmentationId';
2389
+ const config = {
2390
+ segmentIndex: 1,
2391
+ isLocked: false,
2392
+ active: true,
2393
+ color: [255, 0, 0, 255] as csTypes.Color,
2394
+ };
2395
+
2396
+ jest
2397
+ .spyOn(cstSegmentation.state, 'getSegmentation')
2398
+ .mockReturnValue(mockCornerstoneSegmentation);
2399
+ jest.spyOn(cstSegmentation, 'updateSegmentations').mockReturnValue(undefined);
2400
+ jest.spyOn(cstSegmentation.segmentIndex, 'setActiveSegmentIndex').mockReturnValue(undefined);
2401
+ jest.spyOn(service, 'getViewportIdsWithSegmentation').mockReturnValue(['viewportId']);
2402
+ jest
2403
+ .spyOn(cstSegmentation.segmentLocking, 'setSegmentIndexLocked')
2404
+ .mockReturnValue(undefined);
2405
+ jest.spyOn(cstSegmentation.config.color, 'setSegmentIndexColor').mockReturnValue(undefined);
2406
+ jest
2407
+ .spyOn(cstSegmentation.state, 'getSegmentationRepresentations')
2408
+ .mockReturnValue([{ colorLUTIndex: 1 }] as cstTypes.SegmentationRepresentation[]);
2409
+
2410
+ service.addSegment(segmentationId, config);
2411
+
2412
+ expect(cstSegmentation.updateSegmentations).toHaveBeenCalledTimes(1);
2413
+ expect(cstSegmentation.updateSegmentations).toHaveBeenCalledWith([
2414
+ {
2415
+ segmentationId,
2416
+ payload: {
2417
+ segments: {
2418
+ ...mockCornerstoneSegmentation.segments,
2419
+ '1': {
2420
+ label: 'Segment 1',
2421
+ segmentIndex: 1,
2422
+ cachedStats: {},
2423
+ locked: false,
2424
+ active: true,
2425
+ ...config,
2426
+ },
2427
+ },
2428
+ },
2429
+ },
2430
+ ]);
2431
+
2432
+ expect(cstSegmentation.segmentLocking.setSegmentIndexLocked).toHaveBeenCalledTimes(1);
2433
+ expect(cstSegmentation.segmentLocking.setSegmentIndexLocked).toHaveBeenCalledWith(
2434
+ segmentationId,
2435
+ 1,
2436
+ config.isLocked
2437
+ );
2438
+
2439
+ expect(cstSegmentation.config.color.setSegmentIndexColor).toHaveBeenCalledTimes(1);
2440
+ expect(cstSegmentation.config.color.setSegmentIndexColor).toHaveBeenCalledWith(
2441
+ 'viewportId',
2442
+ segmentationId,
2443
+ 1,
2444
+ config.color
2445
+ );
2446
+ });
2447
+ });
2448
+
2449
+ describe('removeSegment', () => {
2450
+ it('should remove the segment', () => {
2451
+ const segmentationId = 'segmentationId';
2452
+ const segmentIndex = 1;
2453
+ jest.spyOn(cstSegmentation, 'removeSegment').mockReturnValue(undefined);
2454
+
2455
+ service.removeSegment(segmentationId, segmentIndex);
2456
+
2457
+ expect(cstSegmentation.removeSegment).toHaveBeenCalledTimes(1);
2458
+ expect(cstSegmentation.removeSegment).toHaveBeenCalledWith(segmentationId, segmentIndex, {
2459
+ recordHistory: true,
2460
+ });
2461
+ });
2462
+ });
2463
+
2464
+ describe('setSegmentVisibility', () => {
2465
+ it('should set the visibility of the segment', () => {
2466
+ const viewportId = 'viewportId';
2467
+ const segmentationId = 'segmentationId';
2468
+ const segmentIndex = 1;
2469
+ const isVisible = true;
2470
+ const type = csToolsEnums.SegmentationRepresentations.Contour;
2471
+
2472
+ jest
2473
+ .spyOn(cstSegmentation.config.visibility, 'setSegmentIndexVisibility')
2474
+ .mockReturnValue(undefined);
2475
+
2476
+ service.setSegmentVisibility(viewportId, segmentationId, segmentIndex, isVisible, type);
2477
+
2478
+ expect(cstSegmentation.config.visibility.setSegmentIndexVisibility).toHaveBeenCalledTimes(1);
2479
+ expect(cstSegmentation.config.visibility.setSegmentIndexVisibility).toHaveBeenCalledWith(
2480
+ viewportId,
2481
+ { segmentationId, type },
2482
+ segmentIndex,
2483
+ isVisible
2484
+ );
2485
+ });
2486
+ });
2487
+
2488
+ describe('setSegmentLocked', () => {
2489
+ it('should set the locked status of the segment', () => {
2490
+ const segmentationId = 'segmentationId';
2491
+ const segmentIndex = 1;
2492
+ const isLocked = true;
2493
+
2494
+ jest
2495
+ .spyOn(cstSegmentation.segmentLocking, 'setSegmentIndexLocked')
2496
+ .mockReturnValue(undefined);
2497
+
2498
+ service.setSegmentLocked(segmentationId, segmentIndex, isLocked);
2499
+
2500
+ expect(cstSegmentation.segmentLocking.setSegmentIndexLocked).toHaveBeenCalledTimes(1);
2501
+ expect(cstSegmentation.segmentLocking.setSegmentIndexLocked).toHaveBeenCalledWith(
2502
+ segmentationId,
2503
+ segmentIndex,
2504
+ isLocked
2505
+ );
2506
+ });
2507
+ });
2508
+
2509
+ describe('toggleSegmentLocked', () => {
2510
+ it('should toggle the locked status of the segment', () => {
2511
+ const segmentationId = 'segmentationId';
2512
+ const segmentIndex = 1;
2513
+ const isLocked = true;
2514
+
2515
+ jest.spyOn(cstSegmentation.segmentLocking, 'isSegmentIndexLocked').mockReturnValue(isLocked);
2516
+ jest
2517
+ .spyOn(cstSegmentation.segmentLocking, 'setSegmentIndexLocked')
2518
+ .mockReturnValue(undefined);
2519
+
2520
+ service.toggleSegmentLocked(segmentationId, segmentIndex);
2521
+
2522
+ expect(cstSegmentation.segmentLocking.isSegmentIndexLocked).toHaveBeenCalledTimes(1);
2523
+ expect(cstSegmentation.segmentLocking.isSegmentIndexLocked).toHaveBeenCalledWith(
2524
+ segmentationId,
2525
+ segmentIndex
2526
+ );
2527
+
2528
+ expect(cstSegmentation.segmentLocking.setSegmentIndexLocked).toHaveBeenCalledTimes(1);
2529
+ expect(cstSegmentation.segmentLocking.setSegmentIndexLocked).toHaveBeenCalledWith(
2530
+ segmentationId,
2531
+ segmentIndex,
2532
+ !isLocked
2533
+ );
2534
+ });
2535
+ });
2536
+
2537
+ describe('toggleSegmentVisibility', () => {
2538
+ it('should toggle the visibility of the segment', () => {
2539
+ const viewportId = 'viewportId';
2540
+ const segmentationId = 'segmentationId';
2541
+ const segmentIndex = 1;
2542
+ const isVisible = true;
2543
+ const type = csToolsEnums.SegmentationRepresentations.Contour;
2544
+
2545
+ jest
2546
+ .spyOn(cstSegmentation.config.visibility, 'getSegmentIndexVisibility')
2547
+ .mockReturnValue(isVisible);
2548
+ jest
2549
+ .spyOn(cstSegmentation.config.visibility, 'setSegmentIndexVisibility')
2550
+ .mockReturnValue(undefined);
2551
+
2552
+ service.toggleSegmentVisibility(viewportId, segmentationId, segmentIndex, type);
2553
+
2554
+ expect(cstSegmentation.config.visibility.getSegmentIndexVisibility).toHaveBeenCalledTimes(1);
2555
+ expect(cstSegmentation.config.visibility.getSegmentIndexVisibility).toHaveBeenCalledWith(
2556
+ viewportId,
2557
+ { segmentationId, type },
2558
+ segmentIndex
2559
+ );
2560
+
2561
+ expect(cstSegmentation.config.visibility.setSegmentIndexVisibility).toHaveBeenCalledTimes(1);
2562
+ expect(cstSegmentation.config.visibility.setSegmentIndexVisibility).toHaveBeenCalledWith(
2563
+ viewportId,
2564
+ { segmentationId, type },
2565
+ segmentIndex,
2566
+ !isVisible
2567
+ );
2568
+ });
2569
+ });
2570
+
2571
+ describe('setSegmentColor', () => {
2572
+ const viewportId = 'viewportId';
2573
+ const segmentationId = 'segmentationId';
2574
+ const segmentIndex = 1;
2575
+ const color = [255, 0, 0, 255] as csTypes.Color;
2576
+
2577
+ it('should set the color of the segment', () => {
2578
+ jest
2579
+ .spyOn(cstSegmentation.state, 'getSegmentationRepresentations')
2580
+ .mockReturnValue([{ colorLUTIndex: 1 }] as cstTypes.SegmentationRepresentation[]);
2581
+ jest.spyOn(cstSegmentation.config.color, 'setSegmentIndexColor').mockReturnValue(undefined);
2582
+
2583
+ service.setSegmentColor(viewportId, segmentationId, segmentIndex, color);
2584
+
2585
+ expect(cstSegmentation.state.getSegmentationRepresentations).toHaveBeenCalledTimes(1);
2586
+ expect(cstSegmentation.state.getSegmentationRepresentations).toHaveBeenCalledWith(
2587
+ viewportId,
2588
+ { segmentationId }
2589
+ );
2590
+
2591
+ expect(cstSegmentation.config.color.setSegmentIndexColor).toHaveBeenCalledTimes(1);
2592
+ expect(cstSegmentation.config.color.setSegmentIndexColor).toHaveBeenCalledWith(
2593
+ viewportId,
2594
+ segmentationId,
2595
+ segmentIndex,
2596
+ color
2597
+ );
2598
+ });
2599
+
2600
+ it('should set the color of the segment with the colorLUTIndex', async () => {
2601
+ jest
2602
+ .spyOn(cstSegmentation.state, 'getSegmentationRepresentations')
2603
+ .mockReturnValue([{ colorLUTIndex: 1 }] as cstTypes.SegmentationRepresentation[]);
2604
+ jest.spyOn(cstSegmentation.config.color, 'setSegmentIndexColor').mockReturnValue(undefined);
2605
+
2606
+ service.setSegmentColor(viewportId, segmentationId, segmentIndex, color);
2607
+
2608
+ jest
2609
+ .spyOn(cstSegmentation.state, 'getSegmentation')
2610
+ .mockReturnValue(mockCornerstoneSegmentation as cstTypes.Segmentation);
2611
+ jest
2612
+ .spyOn(serviceManagerMock.services.cornerstoneViewportService, 'getCornerstoneViewport')
2613
+ // only needed interfaces for the addSegmentationRepresentation call
2614
+ .mockReturnValue(mockCornerstoneStackViewport as unknown as csTypes.IStackViewport);
2615
+ jest
2616
+ .spyOn(cstSegmentation.state, 'updateLabelmapSegmentationImageReferences')
2617
+ .mockReturnValue('labelmapImageId');
2618
+ jest.spyOn(cstSegmentation, 'addSegmentationRepresentations').mockReturnValueOnce(undefined);
2619
+
2620
+ await service.addSegmentationRepresentation(viewportId, {
2621
+ segmentationId: segmentationId,
2622
+ type: csToolsEnums.SegmentationRepresentations.Labelmap,
2623
+ config: { blendMode: csEnums.BlendModes.COMPOSITE },
2624
+ suppressEvents: true,
2625
+ });
2626
+
2627
+ expect(cstSegmentation.addSegmentationRepresentations).toHaveBeenCalledTimes(1);
2628
+ expect(cstSegmentation.addSegmentationRepresentations).toHaveBeenCalledWith(viewportId, [
2629
+ {
2630
+ type: csToolsEnums.SegmentationRepresentations.Labelmap,
2631
+ segmentationId: segmentationId,
2632
+ config: { colorLUTOrIndex: 1, blendMode: csEnums.BlendModes.COMPOSITE },
2633
+ },
2634
+ ]);
2635
+ });
2636
+ });
2637
+
2638
+ describe('getSegmentColor', () => {
2639
+ it('should get the color of the segment', () => {
2640
+ const viewportId = 'viewportId';
2641
+ const segmentationId = 'segmentationId';
2642
+ const segmentIndex = 1;
2643
+ const color = [255, 0, 0, 255] as csTypes.Color;
2644
+
2645
+ jest.spyOn(cstSegmentation.config.color, 'getSegmentIndexColor').mockReturnValue(color);
2646
+
2647
+ const returnedColor = service.getSegmentColor(viewportId, segmentationId, segmentIndex);
2648
+
2649
+ expect(cstSegmentation.config.color.getSegmentIndexColor).toHaveBeenCalledTimes(1);
2650
+ expect(cstSegmentation.config.color.getSegmentIndexColor).toHaveBeenCalledWith(
2651
+ viewportId,
2652
+ segmentationId,
2653
+ segmentIndex
2654
+ );
2655
+
2656
+ expect(returnedColor).toEqual(color);
2657
+ });
2658
+ });
2659
+
2660
+ describe('getLabelmapVolume', () => {
2661
+ it('should get the labelmap volume for the segmentation', () => {
2662
+ const segmentationId = 'segmentationId';
2663
+ const labelmapVolume = { id: 'volumeId' };
2664
+ mockCornerstoneSegmentation.representationData.Labelmap = { volumeId: 'volumeId' };
2665
+ jest
2666
+ .spyOn(cstSegmentation.state, 'getSegmentation')
2667
+ .mockReturnValue(mockCornerstoneSegmentation);
2668
+ // @ts-expect-error - no need to mock every property for this test
2669
+ jest.spyOn(cache, 'getVolume').mockReturnValue(labelmapVolume);
2670
+
2671
+ const returnedLabelmapVolume = service.getLabelmapVolume(segmentationId);
2672
+
2673
+ expect(cstSegmentation.state.getSegmentation).toHaveBeenCalledTimes(1);
2674
+ expect(cstSegmentation.state.getSegmentation).toHaveBeenCalledWith(segmentationId);
2675
+
2676
+ expect(cache.getVolume).toHaveBeenCalledTimes(1);
2677
+ expect(cache.getVolume).toHaveBeenCalledWith(labelmapVolume.id);
2678
+
2679
+ expect(returnedLabelmapVolume).toEqual(labelmapVolume);
2680
+
2681
+ mockCornerstoneSegmentation.representationData.Labelmap = {};
2682
+ });
2683
+
2684
+ it('should return null if the segmentation does not have a labelmap volume', () => {
2685
+ const segmentationId = 'segmentationId';
2686
+ jest
2687
+ .spyOn(cstSegmentation.state, 'getSegmentation')
2688
+ .mockReturnValue(mockCornerstoneSegmentation);
2689
+
2690
+ const returnedLabelmapVolume = service.getLabelmapVolume(segmentationId);
2691
+
2692
+ expect(cstSegmentation.state.getSegmentation).toHaveBeenCalledTimes(1);
2693
+
2694
+ expect(returnedLabelmapVolume).toEqual(null);
2695
+ });
2696
+ });
2697
+
2698
+ describe('setSegmentLabel', () => {
2699
+ it('should set the label of the segment', () => {
2700
+ const segmentationId = 'segmentationId';
2701
+ const segmentIndex = 1;
2702
+ const label = 'New Segment 1';
2703
+
2704
+ jest
2705
+ .spyOn(cstSegmentation.state, 'getSegmentation')
2706
+ .mockReturnValue(mockCornerstoneSegmentation);
2707
+ jest.spyOn(cstSegmentation, 'updateSegmentations').mockReturnValue(undefined);
2708
+
2709
+ service.setSegmentLabel(segmentationId, segmentIndex, label);
2710
+
2711
+ expect(cstSegmentation.state.getSegmentation).toHaveBeenCalledTimes(1);
2712
+ expect(cstSegmentation.state.getSegmentation).toHaveBeenCalledWith(segmentationId);
2713
+
2714
+ expect(cstSegmentation.updateSegmentations).toHaveBeenCalledTimes(1);
2715
+ expect(cstSegmentation.updateSegmentations).toHaveBeenCalledWith([
2716
+ {
2717
+ segmentationId,
2718
+ payload: {
2719
+ segments: {
2720
+ ...mockCornerstoneSegmentation.segments,
2721
+ [segmentIndex]: { ...mockCornerstoneSegmentation.segments[segmentIndex], label },
2722
+ },
2723
+ },
2724
+ },
2725
+ ]);
2726
+ });
2727
+ });
2728
+
2729
+ describe('setActiveSegment', () => {
2730
+ it('should set the active segment for the segmentation', () => {
2731
+ const segmentationId = 'segmentationId';
2732
+ const segmentIndex = 1;
2733
+
2734
+ jest.spyOn(cstSegmentation.segmentIndex, 'setActiveSegmentIndex').mockReturnValue(undefined);
2735
+
2736
+ service.setActiveSegment(segmentationId, segmentIndex);
2737
+
2738
+ expect(cstSegmentation.segmentIndex.setActiveSegmentIndex).toHaveBeenCalledTimes(1);
2739
+ expect(cstSegmentation.segmentIndex.setActiveSegmentIndex).toHaveBeenCalledWith(
2740
+ segmentationId,
2741
+ segmentIndex
2742
+ );
2743
+ });
2744
+ });
2745
+
2746
+ describe('setRenderInactiveSegmentations', () => {
2747
+ it('should set the render inactive segmentations for the viewport', () => {
2748
+ const viewportId = 'viewportId';
2749
+ const renderInactive = true;
2750
+
2751
+ jest
2752
+ .spyOn(cstSegmentation.config.style, 'setRenderInactiveSegmentations')
2753
+ .mockReturnValue(undefined);
2754
+
2755
+ service.setRenderInactiveSegmentations(viewportId, renderInactive);
2756
+
2757
+ expect(cstSegmentation.config.style.setRenderInactiveSegmentations).toHaveBeenCalledTimes(1);
2758
+ expect(cstSegmentation.config.style.setRenderInactiveSegmentations).toHaveBeenCalledWith(
2759
+ viewportId,
2760
+ renderInactive
2761
+ );
2762
+ });
2763
+ });
2764
+
2765
+ describe('getRenderInactiveSegmentations', () => {
2766
+ it('should get the render inactive segmentations for the viewport', () => {
2767
+ const viewportId = 'viewportId';
2768
+ const renderInactive = true;
2769
+
2770
+ jest
2771
+ .spyOn(cstSegmentation.config.style, 'getRenderInactiveSegmentations')
2772
+ .mockReturnValue(renderInactive);
2773
+
2774
+ const returnedRenderInactive = service.getRenderInactiveSegmentations(viewportId);
2775
+
2776
+ expect(cstSegmentation.config.style.getRenderInactiveSegmentations).toHaveBeenCalledTimes(1);
2777
+ expect(cstSegmentation.config.style.getRenderInactiveSegmentations).toHaveBeenCalledWith(
2778
+ viewportId
2779
+ );
2780
+
2781
+ expect(returnedRenderInactive).toEqual(renderInactive);
2782
+ });
2783
+ });
2784
+
2785
+ describe('setSegmentationGroupStats', () => {
2786
+ it('should set the segmentation group stats', () => {
2787
+ const segmentationIds = ['segmentationId1', 'segmentationId2'];
2788
+ const stats = { key: 'value' };
2789
+
2790
+ service.setSegmentationGroupStats(segmentationIds, stats);
2791
+
2792
+ const returnedStats = service.getSegmentationGroupStats(segmentationIds);
2793
+
2794
+ expect(returnedStats).toEqual(stats);
2795
+ });
2796
+ });
2797
+
2798
+ describe('getSegmentationGroupStats', () => {
2799
+ it('should get the segmentation group stats', () => {
2800
+ const segmentationIds = ['segmentationId1', 'segmentationId2'];
2801
+ const stats = { key: 'value' };
2802
+
2803
+ let returnedStats = service.getSegmentationGroupStats(segmentationIds);
2804
+
2805
+ expect(returnedStats).toEqual(undefined);
2806
+
2807
+ service.setSegmentationGroupStats(segmentationIds, stats);
2808
+
2809
+ returnedStats = service.getSegmentationGroupStats(segmentationIds);
2810
+
2811
+ expect(returnedStats).toEqual(stats);
2812
+ });
2813
+ });
2814
+
2815
+ describe('toggleSegmentationRepresentationVisibility', () => {
2816
+ it('should toggle the visibility of the segmentation representation', () => {
2817
+ jest.spyOn(service, 'getSegmentationRepresentations').mockReturnValue(representations);
2818
+ jest
2819
+ .spyOn(cstSegmentation.config.visibility, 'getHiddenSegmentIndices')
2820
+ .mockReturnValue(new Set());
2821
+ jest
2822
+ .spyOn(cstSegmentation.config.visibility, 'setSegmentationRepresentationVisibility')
2823
+ .mockReturnValue(undefined);
2824
+
2825
+ service.toggleSegmentationRepresentationVisibility(viewportId, {
2826
+ segmentationId: representations[0].segmentationId,
2827
+ type: representations[0].type,
2828
+ });
2829
+
2830
+ expect(service.getSegmentationRepresentations).toHaveBeenCalledTimes(1);
2831
+ expect(service.getSegmentationRepresentations).toHaveBeenCalledWith(viewportId, {
2832
+ segmentationId: representations[0].segmentationId,
2833
+ type: representations[0].type,
2834
+ });
2835
+
2836
+ expect(cstSegmentation.config.visibility.getHiddenSegmentIndices).toHaveBeenCalledTimes(1);
2837
+ expect(cstSegmentation.config.visibility.getHiddenSegmentIndices).toHaveBeenCalledWith(
2838
+ viewportId,
2839
+ {
2840
+ segmentationId: representations[0].segmentationId,
2841
+ type: representations[0].type,
2842
+ }
2843
+ );
2844
+
2845
+ expect(
2846
+ cstSegmentation.config.visibility.setSegmentationRepresentationVisibility
2847
+ ).toHaveBeenCalledTimes(1);
2848
+ expect(
2849
+ cstSegmentation.config.visibility.setSegmentationRepresentationVisibility
2850
+ ).toHaveBeenCalledWith(
2851
+ viewportId,
2852
+ {
2853
+ segmentationId: representations[0].segmentationId,
2854
+ type: representations[0].type,
2855
+ },
2856
+ false
2857
+ );
2858
+ });
2859
+ });
2860
+
2861
+ describe('setSegmentationRepresentationVisibility', () => {
2862
+ it('should early return if the representation is not found', () => {
2863
+ jest.spyOn(service, 'getSegmentationRepresentations').mockReturnValueOnce([]);
2864
+ jest.spyOn(console, 'debug').mockReturnValue(undefined);
2865
+ jest.spyOn(cstSegmentation.config.visibility, 'setSegmentationRepresentationVisibility');
2866
+
2867
+ service['_setSegmentationRepresentationVisibility'](
2868
+ viewportId,
2869
+ representations[0].segmentationId,
2870
+ representations[0].type,
2871
+ true
2872
+ );
2873
+
2874
+ expect(console.debug).toHaveBeenCalledTimes(1);
2875
+ expect(console.debug).toHaveBeenCalledWith(
2876
+ 'No segmentation representation found for the given viewportId and segmentationId'
2877
+ );
2878
+
2879
+ expect(
2880
+ cstSegmentation.config.visibility.setSegmentationRepresentationVisibility
2881
+ ).not.toHaveBeenCalled();
2882
+ });
2883
+ });
2884
+
2885
+ describe('getViewportIdsWithSegmentation', () => {
2886
+ it('should get the viewport ids with the segmentation', () => {
2887
+ const segmentationId = 'segmentationId';
2888
+ const viewportIds = ['viewportId1', 'viewportId2'];
2889
+
2890
+ jest
2891
+ .spyOn(cstSegmentation.state, 'getViewportIdsWithSegmentation')
2892
+ .mockReturnValue(viewportIds);
2893
+
2894
+ const returnedViewportIds = service.getViewportIdsWithSegmentation(segmentationId);
2895
+
2896
+ expect(cstSegmentation.state.getViewportIdsWithSegmentation).toHaveBeenCalledTimes(1);
2897
+ expect(cstSegmentation.state.getViewportIdsWithSegmentation).toHaveBeenCalledWith(
2898
+ segmentationId
2899
+ );
2900
+
2901
+ expect(returnedViewportIds).toEqual(viewportIds);
2902
+ });
2903
+ });
2904
+
2905
+ describe('clearSegmentationRepresentations', () => {
2906
+ it('should clear the segmentation representations', () => {
2907
+ const viewportId = 'viewportId';
2908
+ jest.spyOn(service, 'removeRepresentationsFromViewport').mockReturnValue(undefined);
2909
+
2910
+ service.clearSegmentationRepresentations(viewportId);
2911
+
2912
+ expect(service.removeRepresentationsFromViewport).toHaveBeenCalledTimes(1);
2913
+ expect(service.removeRepresentationsFromViewport).toHaveBeenCalledWith(viewportId);
2914
+ });
2915
+ });
2916
+
2917
+ describe('remove', () => {
2918
+ it('should remove the segmentation', () => {
2919
+ const segmentationId = 'segmentationId';
2920
+
2921
+ jest.spyOn(cstSegmentation.state, 'removeSegmentation').mockReturnValue(undefined);
2922
+
2923
+ service.remove(segmentationId);
2924
+
2925
+ expect(cstSegmentation.state.removeSegmentation).toHaveBeenCalledTimes(1);
2926
+ expect(cstSegmentation.state.removeSegmentation).toHaveBeenCalledWith(segmentationId);
2927
+ });
2928
+ });
2929
+
2930
+ describe('removeAllSegmentations', () => {
2931
+ it('should remove all segmentations', () => {
2932
+ jest.spyOn(cstSegmentation.state, 'removeAllSegmentations').mockReturnValue(undefined);
2933
+
2934
+ service.removeAllSegmentations();
2935
+
2936
+ expect(cstSegmentation.state.removeAllSegmentations).toHaveBeenCalledTimes(1);
2937
+ expect(cstSegmentation.state.removeAllSegmentations).toHaveBeenCalledWith();
2938
+ });
2939
+ });
2940
+
2941
+ describe('removeRepresentationsFromViewport', () => {
2942
+ it('should remove the segmentation representations', () => {
2943
+ const viewportId = 'viewportId';
2944
+ const specifier = {
2945
+ segmentationId: 'segmentationId',
2946
+ type: csToolsEnums.SegmentationRepresentations.Labelmap,
2947
+ };
2948
+ jest.spyOn(cstSegmentation, 'removeSegmentationRepresentations').mockReturnValue(undefined);
2949
+
2950
+ service.removeRepresentationsFromViewport(viewportId, specifier);
2951
+
2952
+ expect(cstSegmentation.removeSegmentationRepresentations).toHaveBeenCalledTimes(1);
2953
+ expect(cstSegmentation.removeSegmentationRepresentations).toHaveBeenCalledWith(
2954
+ viewportId,
2955
+ specifier
2956
+ );
2957
+ });
2958
+ });
2959
+
2960
+ describe('jumpToSegmentCenter', () => {
2961
+ it('should early return if the center is not found', () => {
2962
+ const segmentationId = 'segmentationId';
2963
+ const segmentIndex = 1;
2964
+
2965
+ jest.spyOn(console, 'warn').mockReturnValue(undefined);
2966
+ jest.spyOn(cstSegmentation.state, 'getSegmentation').mockReturnValue(null);
2967
+ jest.spyOn(service, 'getViewportIdsWithSegmentation');
2968
+
2969
+ service.jumpToSegmentCenter(segmentationId, segmentIndex);
2970
+
2971
+ expect(console.warn).toHaveBeenCalledTimes(1);
2972
+ expect(console.warn).toHaveBeenCalledWith(
2973
+ 'No center found for segmentation',
2974
+ segmentationId,
2975
+ segmentIndex
2976
+ );
2977
+
2978
+ expect(service.getViewportIdsWithSegmentation).not.toHaveBeenCalled();
2979
+ });
2980
+
2981
+ it('should correctly handle scenario where viewportId is provided', () => {
2982
+ const segmentationId = 'segmentationId';
2983
+ const segmentIndex = 1;
2984
+ const viewportId = 'viewportId';
2985
+ const viewport = { jumpToWorld: jest.fn() };
2986
+
2987
+ const segmentationWithCenter = {
2988
+ ...mockCornerstoneSegmentation,
2989
+ segments: {
2990
+ ...mockCornerstoneSegmentation.segments,
2991
+ [segmentIndex]: {
2992
+ ...mockCornerstoneSegmentation.segments[segmentIndex],
2993
+ cachedStats: { center: { image: [1, 1, 1], world: [10, 10, 10] } },
2994
+ },
2995
+ },
2996
+ };
2997
+
2998
+ jest.spyOn(cstSegmentation.state, 'getSegmentation').mockReturnValue(segmentationWithCenter);
2999
+ jest.spyOn(service, 'getViewportIdsWithSegmentation');
3000
+ // @ts-expect-error - mock only needed properties
3001
+ getEnabledElementByViewportId.mockReturnValue({ viewport });
3002
+ jest.spyOn(service, 'highlightSegment').mockReturnValue(undefined);
3003
+
3004
+ service.jumpToSegmentCenter(segmentationId, segmentIndex, viewportId);
3005
+
3006
+ expect(cstSegmentation.state.getSegmentation).toHaveBeenCalledTimes(1);
3007
+ expect(cstSegmentation.state.getSegmentation).toHaveBeenCalledWith(segmentationId);
3008
+
3009
+ expect(service.getViewportIdsWithSegmentation).not.toHaveBeenCalled();
3010
+
3011
+ expect(viewport.jumpToWorld).toHaveBeenCalledTimes(1);
3012
+ expect(viewport.jumpToWorld).toHaveBeenCalledWith([10, 10, 10]);
3013
+
3014
+ expect(service.highlightSegment).toHaveBeenCalledTimes(1);
3015
+ expect(service.highlightSegment).toHaveBeenCalledWith(
3016
+ segmentationId,
3017
+ segmentIndex,
3018
+ viewportId,
3019
+ 0.9,
3020
+ 750,
3021
+ false,
3022
+ EasingFunctionEnum.EASE_IN_OUT
3023
+ );
3024
+ });
3025
+
3026
+ it('navigates a native viewport via setViewReference (no jumpToWorld) and still highlights', () => {
3027
+ const segmentationId = 'segmentationId';
3028
+ const segmentIndex = 1;
3029
+ const viewportId = 'viewportId';
3030
+ // A native PlanarViewport: csUtils.isGenericViewport is true (setDisplaySets +
3031
+ // setDisplaySetPresentation + setViewState) and it has setViewReference but NO
3032
+ // jumpToWorld, so jumpToSegmentCenter routes to the next twin.
3033
+ const viewport = {
3034
+ setDisplaySets: jest.fn(),
3035
+ setDisplaySetPresentation: jest.fn(),
3036
+ setViewState: jest.fn(),
3037
+ setViewReference: jest.fn(),
3038
+ render: jest.fn(),
3039
+ };
3040
+
3041
+ const segmentationWithCenter = {
3042
+ ...mockCornerstoneSegmentation,
3043
+ segments: {
3044
+ ...mockCornerstoneSegmentation.segments,
3045
+ [segmentIndex]: {
3046
+ ...mockCornerstoneSegmentation.segments[segmentIndex],
3047
+ cachedStats: { center: { image: [1, 1, 1], world: [10, 10, 10] } },
3048
+ },
3049
+ },
3050
+ };
3051
+
3052
+ jest.spyOn(cstSegmentation.state, 'getSegmentation').mockReturnValue(segmentationWithCenter);
3053
+ // @ts-expect-error - mock only needed properties
3054
+ getEnabledElementByViewportId.mockReturnValue({ viewport });
3055
+ jest.spyOn(service, 'highlightSegment').mockReturnValue(undefined);
3056
+
3057
+ service.jumpToSegmentCenter(segmentationId, segmentIndex, viewportId);
3058
+
3059
+ // native jump: a view reference centered on the segment world point, then render
3060
+ expect(viewport.setViewReference).toHaveBeenCalledTimes(1);
3061
+ expect(viewport.setViewReference).toHaveBeenCalledWith({ cameraFocalPoint: [10, 10, 10] });
3062
+ expect(viewport.render).toHaveBeenCalledTimes(1);
3063
+ // the recenter happened, so the highlight still runs
3064
+ expect(service.highlightSegment).toHaveBeenCalledTimes(1);
3065
+ });
3066
+
3067
+ it('should correctly handle custom animation parameters', () => {
3068
+ const segmentationId = 'segmentationId';
3069
+ const segmentIndex = 1;
3070
+ const viewportId = 'viewportId';
3071
+ const viewport = { jumpToWorld: jest.fn() };
3072
+
3073
+ const segmentationWithNamedStatsCenter = {
3074
+ ...mockCornerstoneSegmentation,
3075
+ segments: {
3076
+ ...mockCornerstoneSegmentation.segments,
3077
+ [segmentIndex]: {
3078
+ ...mockCornerstoneSegmentation.segments[segmentIndex],
3079
+ cachedStats: {
3080
+ namedStats: { center: { value: [1, 1, 1] } },
3081
+ },
3082
+ },
3083
+ },
3084
+ };
3085
+
3086
+ jest
3087
+ .spyOn(cstSegmentation.state, 'getSegmentation')
3088
+ .mockReturnValue(segmentationWithNamedStatsCenter);
3089
+ jest.spyOn(service, 'getViewportIdsWithSegmentation').mockReturnValue([viewportId]);
3090
+ // @ts-expect-error - mock only needed properties
3091
+ getEnabledElementByViewportId.mockReturnValue({ viewport });
3092
+ jest.spyOn(service, 'highlightSegment').mockReturnValue(undefined);
3093
+
3094
+ service.jumpToSegmentCenter(
3095
+ segmentationId,
3096
+ segmentIndex,
3097
+ undefined,
3098
+ 0.8,
3099
+ true,
3100
+ 800,
3101
+ false,
3102
+ EasingFunctionEnum.LINEAR
3103
+ );
3104
+
3105
+ expect(service.getViewportIdsWithSegmentation).toHaveBeenCalledTimes(1);
3106
+ expect(service.getViewportIdsWithSegmentation).toHaveBeenCalledWith(segmentationId);
3107
+
3108
+ expect(viewport.jumpToWorld).toHaveBeenCalledTimes(1);
3109
+ expect(viewport.jumpToWorld).toHaveBeenCalledWith([1, 1, 1]);
3110
+
3111
+ expect(service.highlightSegment).toHaveBeenCalledTimes(1);
3112
+ expect(service.highlightSegment).toHaveBeenCalledWith(
3113
+ segmentationId,
3114
+ segmentIndex,
3115
+ viewportId,
3116
+ 0.8,
3117
+ 800,
3118
+ false,
3119
+ EasingFunctionEnum.LINEAR
3120
+ );
3121
+ });
3122
+ });
3123
+
3124
+ describe('highlightSegment', () => {
3125
+ describe('LABELMAP Segmentation', () => {
3126
+ it('should correctly handle scenario where viewportId is provided', () => {
3127
+ const segmentIndex = 1;
3128
+ const viewportId = 'viewportId';
3129
+ const initialFillAlpha = 0.3;
3130
+ const animationDuration = 750;
3131
+ const animationFunctionConstant = 0.85;
3132
+ const easingFunction = jest.fn(() => animationFunctionConstant);
3133
+
3134
+ jest
3135
+ .spyOn(cstSegmentation.state, 'getSegmentation')
3136
+ .mockReturnValue(mockCornerstoneSegmentation);
3137
+ jest.spyOn(service, 'getViewportIdsWithSegmentation');
3138
+ jest.spyOn(service, 'getSegmentationRepresentations').mockReturnValue(representations);
3139
+ jest.spyOn(cstSegmentation.config.style, 'getStyle').mockReturnValue({
3140
+ fillAlpha: initialFillAlpha,
3141
+ });
3142
+ jest.spyOn(window, 'requestAnimationFrame').mockReturnValue(undefined);
3143
+ jest.spyOn(EasingFunctionMap, 'get').mockReturnValue(easingFunction);
3144
+
3145
+ service.highlightSegment(
3146
+ representations[0].segmentationId,
3147
+ segmentIndex,
3148
+ viewportId,
3149
+ 0.9,
3150
+ animationDuration,
3151
+ false,
3152
+ EasingFunctionEnum.EASE_IN_OUT
3153
+ );
3154
+
3155
+ expect(cstSegmentation.state.getSegmentation).toHaveBeenCalledTimes(1);
3156
+ expect(cstSegmentation.state.getSegmentation).toHaveBeenCalledWith(
3157
+ representations[0].segmentationId
3158
+ );
3159
+
3160
+ expect(service.getViewportIdsWithSegmentation).not.toHaveBeenCalled();
3161
+
3162
+ expect(service.getSegmentationRepresentations).toHaveBeenCalledTimes(1);
3163
+ expect(service.getSegmentationRepresentations).toHaveBeenCalledWith(viewportId, {
3164
+ segmentationId: representations[0].segmentationId,
3165
+ });
3166
+
3167
+ expect(cstSegmentation.config.style.getStyle).toHaveBeenCalledTimes(1);
3168
+ expect(cstSegmentation.config.style.getStyle).toHaveBeenCalledWith({
3169
+ viewportId,
3170
+ segmentationId: representations[0].segmentationId,
3171
+ type: csToolsEnums.SegmentationRepresentations.Labelmap,
3172
+ segmentIndex,
3173
+ });
3174
+
3175
+ expect(window.requestAnimationFrame).toHaveBeenCalledTimes(1);
3176
+ expect(window.requestAnimationFrame).toHaveBeenCalledWith(expect.any(Function));
3177
+
3178
+ const animationCallback = jest.mocked(window.requestAnimationFrame).mock.calls[0][0];
3179
+
3180
+ // during animation call
3181
+ animationCallback(0);
3182
+
3183
+ expect(EasingFunctionMap.get).toHaveBeenCalledTimes(1);
3184
+ expect(EasingFunctionMap.get).toHaveBeenCalledWith(EasingFunctionEnum.EASE_IN_OUT);
3185
+
3186
+ expect(cstSegmentation.config.style.setStyle).toHaveBeenCalledTimes(1);
3187
+ expect(cstSegmentation.config.style.setStyle).toHaveBeenCalledWith(
3188
+ {
3189
+ segmentationId: representations[0].segmentationId,
3190
+ segmentIndex,
3191
+ type: csToolsEnums.SegmentationRepresentations.Labelmap,
3192
+ },
3193
+ {
3194
+ fillAlpha: animationFunctionConstant,
3195
+ }
3196
+ );
3197
+
3198
+ expect(easingFunction).toHaveBeenCalledTimes(1);
3199
+ expect(easingFunction).toHaveBeenCalledWith(0, initialFillAlpha);
3200
+
3201
+ expect(window.requestAnimationFrame).toHaveBeenCalledTimes(2);
3202
+ expect(window.requestAnimationFrame).toHaveBeenCalledWith(expect.any(Function));
3203
+
3204
+ // end of animation call
3205
+ animationCallback(animationDuration);
3206
+
3207
+ expect(cstSegmentation.config.style.setStyle).toHaveBeenCalledTimes(3);
3208
+ expect(cstSegmentation.config.style.setStyle).toHaveBeenCalledWith(
3209
+ {
3210
+ segmentationId: representations[0].segmentationId,
3211
+ segmentIndex,
3212
+ type: csToolsEnums.SegmentationRepresentations.Labelmap,
3213
+ },
3214
+ {},
3215
+ false
3216
+ );
3217
+
3218
+ expect(window.requestAnimationFrame).not.toHaveBeenCalledTimes(3);
3219
+ });
3220
+
3221
+ it('should throw if hideOthers is true', () => {
3222
+ const segmentIndex = 1;
3223
+
3224
+ jest
3225
+ .spyOn(cstSegmentation.state, 'getSegmentation')
3226
+ .mockReturnValue(mockCornerstoneSegmentation);
3227
+ jest.spyOn(service, 'getViewportIdsWithSegmentation').mockReturnValue([viewportId]);
3228
+ jest.spyOn(service, 'getSegmentationRepresentations').mockReturnValue(representations);
3229
+
3230
+ expect(() =>
3231
+ service.highlightSegment(representations[0].segmentationId, segmentIndex)
3232
+ ).toThrow('hideOthers is not working right now');
3233
+
3234
+ expect(service.getViewportIdsWithSegmentation).toHaveBeenCalledTimes(1);
3235
+ expect(service.getViewportIdsWithSegmentation).toHaveBeenCalledWith(
3236
+ representations[0].segmentationId
3237
+ );
3238
+
3239
+ expect(service.getSegmentationRepresentations).toHaveBeenCalledTimes(1);
3240
+ expect(service.getSegmentationRepresentations).toHaveBeenCalledWith(viewportId, {
3241
+ segmentationId: representations[0].segmentationId,
3242
+ });
3243
+ });
3244
+ });
3245
+
3246
+ describe('CONTOUR Segmentation', () => {
3247
+ it('should correctly handle scenario where viewportId is provided', () => {
3248
+ const segmentIndex = 1;
3249
+ const viewportId = 'viewportId';
3250
+ const initialOutlineWidth = 3;
3251
+ const animationDuration = 750;
3252
+ const animationFunctionConstant = 5;
3253
+ const easingFunction = jest.fn(() => animationFunctionConstant);
3254
+
3255
+ const contourRepresentations = [
3256
+ {
3257
+ ...representations[0],
3258
+ type: csToolsEnums.SegmentationRepresentations.Contour,
3259
+ },
3260
+ ];
3261
+
3262
+ jest
3263
+ .spyOn(cstSegmentation.state, 'getSegmentation')
3264
+ .mockReturnValue(mockCornerstoneSegmentation);
3265
+ jest.spyOn(service, 'getViewportIdsWithSegmentation');
3266
+ jest
3267
+ .spyOn(service, 'getSegmentationRepresentations')
3268
+ .mockReturnValue(contourRepresentations);
3269
+ jest.spyOn(cstSegmentation.config.style, 'getStyle').mockReturnValue({
3270
+ outlineWidth: initialOutlineWidth,
3271
+ });
3272
+ jest.spyOn(window, 'requestAnimationFrame').mockReturnValue(undefined);
3273
+ jest.spyOn(EasingFunctionMap, 'get').mockReturnValue(easingFunction);
3274
+ jest.spyOn(cstSegmentation.config.style, 'resetToGlobalStyle').mockReturnValue(undefined);
3275
+
3276
+ service.highlightSegment(
3277
+ contourRepresentations[0].segmentationId,
3278
+ segmentIndex,
3279
+ viewportId,
3280
+ 0.9,
3281
+ animationDuration,
3282
+ false,
3283
+ EasingFunctionEnum.LINEAR
3284
+ );
3285
+
3286
+ expect(service.getViewportIdsWithSegmentation).not.toHaveBeenCalled();
3287
+
3288
+ expect(cstSegmentation.config.style.getStyle).toHaveBeenCalledTimes(1);
3289
+ expect(cstSegmentation.config.style.getStyle).toHaveBeenCalledWith({
3290
+ type: csToolsEnums.SegmentationRepresentations.Contour,
3291
+ });
3292
+
3293
+ expect(window.requestAnimationFrame).toHaveBeenCalledTimes(1);
3294
+ expect(window.requestAnimationFrame).toHaveBeenCalledWith(expect.any(Function));
3295
+
3296
+ const animationCallback = jest.mocked(window.requestAnimationFrame).mock.calls[0][0];
3297
+ const approximateStartTime = performance.now();
3298
+
3299
+ // during animation call
3300
+ animationCallback(approximateStartTime + 200);
3301
+
3302
+ expect(EasingFunctionMap.get).toHaveBeenCalledTimes(1);
3303
+ expect(EasingFunctionMap.get).toHaveBeenCalledWith(EasingFunctionEnum.LINEAR);
3304
+
3305
+ expect(cstSegmentation.config.style.setStyle).toHaveBeenCalledTimes(1);
3306
+ expect(cstSegmentation.config.style.setStyle).toHaveBeenCalledWith(
3307
+ {
3308
+ segmentationId: contourRepresentations[0].segmentationId,
3309
+ segmentIndex,
3310
+ type: csToolsEnums.SegmentationRepresentations.Contour,
3311
+ },
3312
+ {
3313
+ outlineWidth: animationFunctionConstant,
3314
+ }
3315
+ );
3316
+
3317
+ expect(easingFunction).toHaveBeenCalledTimes(1);
3318
+ expect(easingFunction).toHaveBeenCalledWith(expect.any(Number), initialOutlineWidth, 5);
3319
+
3320
+ expect(window.requestAnimationFrame).toHaveBeenCalledTimes(2);
3321
+ expect(window.requestAnimationFrame).toHaveBeenCalledWith(expect.any(Function));
3322
+
3323
+ // end of animation call
3324
+ animationCallback(approximateStartTime + animationDuration);
3325
+
3326
+ expect(cstSegmentation.config.style.setStyle).toHaveBeenCalledTimes(2);
3327
+ expect(cstSegmentation.config.style.setStyle).toHaveBeenLastCalledWith(
3328
+ {
3329
+ segmentationId: contourRepresentations[0].segmentationId,
3330
+ segmentIndex,
3331
+ type: csToolsEnums.SegmentationRepresentations.Contour,
3332
+ },
3333
+ {},
3334
+ false
3335
+ );
3336
+ expect(cstSegmentation.config.style.resetToGlobalStyle).not.toHaveBeenCalled();
3337
+
3338
+ expect(window.requestAnimationFrame).not.toHaveBeenCalledTimes(3);
3339
+ });
3340
+ });
3341
+
3342
+ describe('when highlights overlap', () => {
3343
+ const segmentationId = 'segmentationId';
3344
+ const defaultFillAlpha = 0.5;
3345
+ const labelmapKey = (segmentIndex: number) => `${segmentIndex}:Labelmap`;
3346
+ let frames: FrameRequestCallback[];
3347
+ let styles: Map<string, Record<string, number>>;
3348
+
3349
+ // Runs every queued animation frame once; the callbacks queue the next frames.
3350
+ const runFrame = (timestamp: number) => {
3351
+ const pending = frames;
3352
+ frames = [];
3353
+ pending.forEach(callback => callback(timestamp));
3354
+ };
3355
+
3356
+ const fillAlphaOf = (segmentIndex: number) =>
3357
+ styles.get(labelmapKey(segmentIndex))?.fillAlpha ?? defaultFillAlpha;
3358
+
3359
+ const mockRepresentation = (type: csToolsEnums.SegmentationRepresentations) => {
3360
+ jest
3361
+ .spyOn(service, 'getSegmentationRepresentations')
3362
+ .mockReturnValue([{ segmentationId, type }] as SegmentationRepresentation[]);
3363
+ };
3364
+
3365
+ beforeEach(() => {
3366
+ frames = [];
3367
+ jest.spyOn(window, 'requestAnimationFrame').mockImplementation(callback => {
3368
+ frames.push(callback);
3369
+ return frames.length;
3370
+ });
3371
+ jest.mocked(cstSegmentation.state.getSegmentation).mockReturnValue({
3372
+ segments: {},
3373
+ } as unknown as cstTypes.Segmentation);
3374
+
3375
+ // A per-segment style store, so a temporary highlight value is observable as
3376
+ // the start value of the next highlight that reads it.
3377
+ styles = new Map();
3378
+ jest
3379
+ .mocked(cstSegmentation.config.style.setStyle)
3380
+ .mockImplementation(({ segmentIndex, type }, style, merge = true) => {
3381
+ const key = `${segmentIndex}:${type}`;
3382
+ styles.set(key, merge ? { ...styles.get(key), ...style } : style);
3383
+ });
3384
+ jest
3385
+ .mocked(cstSegmentation.config.style.getStyle)
3386
+ .mockImplementation(({ segmentIndex, type }) =>
3387
+ type === 'Contour' ? { outlineWidth: 2 } : { fillAlpha: fillAlphaOf(segmentIndex) }
3388
+ );
3389
+ // Linear from the start value, so a frame's value shows the start it used.
3390
+ jest
3391
+ .spyOn(EasingFunctionMap, 'get')
3392
+ .mockReturnValue((progress: number, start: number) => start + progress);
3393
+ });
3394
+
3395
+ afterEach(() => {
3396
+ jest.mocked(window.requestAnimationFrame).mockRestore();
3397
+ jest.mocked(EasingFunctionMap.get).mockRestore();
3398
+ });
3399
+
3400
+ it('stops a superseded labelmap highlight and resets its fill at once', () => {
3401
+ mockRepresentation(csToolsEnums.SegmentationRepresentations.Labelmap);
3402
+
3403
+ service.highlightSegment(segmentationId, 1, viewportId, 0.9, 750, false);
3404
+ runFrame(0);
3405
+ runFrame(375);
3406
+ expect(fillAlphaOf(1)).toBe(defaultFillAlpha + 0.5);
3407
+
3408
+ service.highlightSegment(segmentationId, 2, viewportId, 0.9, 750, false);
3409
+
3410
+ expect(styles.get(labelmapKey(1))).toEqual({});
3411
+ expect(frames).toHaveLength(2);
3412
+ runFrame(400);
3413
+ expect(frames).toHaveLength(1);
3414
+ expect(styles.get(labelmapKey(1))).toEqual({});
3415
+ expect(fillAlphaOf(2)).toBe(defaultFillAlpha);
3416
+ });
3417
+
3418
+ it('stops a superseded contour highlight without resetting every other style', () => {
3419
+ mockRepresentation(csToolsEnums.SegmentationRepresentations.Contour);
3420
+
3421
+ service.highlightSegment(segmentationId, 1, viewportId);
3422
+ runFrame(performance.now());
3423
+ service.highlightSegment(segmentationId, 2, viewportId);
3424
+ jest.mocked(cstSegmentation.config.style.setStyle).mockClear();
3425
+
3426
+ runFrame(performance.now());
3427
+
3428
+ expect(frames).toHaveLength(1);
3429
+ expect(cstSegmentation.config.style.resetToGlobalStyle).not.toHaveBeenCalled();
3430
+ expect(styles.get('1:Contour')).toEqual({});
3431
+ expect(cstSegmentation.config.style.setStyle).toHaveBeenCalledTimes(1);
3432
+ expect(cstSegmentation.config.style.setStyle).toHaveBeenCalledWith(
3433
+ { segmentationId, segmentIndex: 2, type: 'Contour' },
3434
+ expect.objectContaining({ outlineWidth: expect.any(Number) })
3435
+ );
3436
+ });
3437
+
3438
+ it('continues a running highlight when the same segment is selected again', () => {
3439
+ mockRepresentation(csToolsEnums.SegmentationRepresentations.Labelmap);
3440
+
3441
+ service.highlightSegment(segmentationId, 1, viewportId, 0.9, 750, false);
3442
+ runFrame(0);
3443
+ runFrame(375);
3444
+ service.highlightSegment(segmentationId, 1, viewportId, 0.9, 750, false);
3445
+
3446
+ expect(frames).toHaveLength(1);
3447
+ runFrame(750);
3448
+ expect(frames).toHaveLength(0);
3449
+ expect(styles.get(labelmapKey(1))).toEqual({});
3450
+ });
3451
+
3452
+ it('starts a reselected segment from its real fill, even before the next frame', () => {
3453
+ mockRepresentation(csToolsEnums.SegmentationRepresentations.Labelmap);
3454
+
3455
+ service.highlightSegment(segmentationId, 1, viewportId, 0.9, 750, false);
3456
+ runFrame(0);
3457
+ runFrame(375);
3458
+ service.highlightSegment(segmentationId, 2, viewportId, 0.9, 750, false);
3459
+ service.highlightSegment(segmentationId, 1, viewportId, 0.9, 750, false);
3460
+ runFrame(400);
3461
+
3462
+ expect(fillAlphaOf(1)).toBe(defaultFillAlpha);
3463
+ runFrame(1150);
3464
+ expect(frames).toHaveLength(0);
3465
+ expect(styles.get(labelmapKey(1))).toEqual({});
3466
+ });
3467
+
3468
+ it('highlights a segment again after its highlight failed mid-animation', () => {
3469
+ mockRepresentation(csToolsEnums.SegmentationRepresentations.Labelmap);
3470
+
3471
+ service.highlightSegment(segmentationId, 1, viewportId, 0.9, 750, false);
3472
+ jest.mocked(cstSegmentation.config.style.setStyle).mockImplementationOnce(() => {
3473
+ throw new Error('segmentation is gone');
3474
+ });
3475
+ expect(() => runFrame(0)).toThrow('segmentation is gone');
3476
+
3477
+ service.highlightSegment(segmentationId, 1, viewportId, 0.9, 750, false);
3478
+
3479
+ expect(frames).toHaveLength(1);
3480
+ });
3481
+
3482
+ it('resets the temporary style when a frame fails after an earlier frame applied it', () => {
3483
+ mockRepresentation(csToolsEnums.SegmentationRepresentations.Labelmap);
3484
+
3485
+ service.highlightSegment(segmentationId, 1, viewportId, 0.9, 750, false);
3486
+ runFrame(0);
3487
+ expect(styles.get(labelmapKey(1))).not.toEqual({});
3488
+
3489
+ jest.mocked(cstSegmentation.config.style.setStyle).mockImplementationOnce(() => {
3490
+ throw new Error('frame failed');
3491
+ });
3492
+ expect(() => runFrame(375)).toThrow('frame failed');
3493
+
3494
+ expect(styles.get(labelmapKey(1))).toEqual({});
3495
+ });
3496
+
3497
+ it('reports the frame error when resetting the style also fails', () => {
3498
+ mockRepresentation(csToolsEnums.SegmentationRepresentations.Labelmap);
3499
+
3500
+ service.highlightSegment(segmentationId, 1, viewportId, 0.9, 750, false);
3501
+ runFrame(0);
3502
+ jest
3503
+ .mocked(cstSegmentation.config.style.setStyle)
3504
+ .mockImplementationOnce(() => {
3505
+ throw new Error('frame failed');
3506
+ })
3507
+ .mockImplementationOnce(() => {
3508
+ throw new Error('reset failed');
3509
+ });
3510
+
3511
+ expect(() => runFrame(375)).toThrow('frame failed');
3512
+ });
3513
+
3514
+ it('forgets the highlights of a removed segmentation', () => {
3515
+ mockRepresentation(csToolsEnums.SegmentationRepresentations.Labelmap);
3516
+
3517
+ service.highlightSegment(segmentationId, 1, viewportId, 0.9, 750, false);
3518
+ runFrame(0);
3519
+ (
3520
+ service as unknown as {
3521
+ _onSegmentationRemovedFromSource: (evt: { detail: { segmentationId: string } }) => void;
3522
+ }
3523
+ )._onSegmentationRemovedFromSource({ detail: { segmentationId } });
3524
+ runFrame(375);
3525
+ expect(frames).toHaveLength(0);
3526
+
3527
+ service.highlightSegment(segmentationId, 1, viewportId, 0.9, 750, false);
3528
+
3529
+ expect(frames).toHaveLength(1);
3530
+ });
3531
+
3532
+ it('replays the highlight when a segment whose highlight finished is selected again', () => {
3533
+ mockRepresentation(csToolsEnums.SegmentationRepresentations.Labelmap);
3534
+
3535
+ service.highlightSegment(segmentationId, 1, viewportId, 0.9, 750, false);
3536
+ runFrame(0);
3537
+ runFrame(750);
3538
+ service.highlightSegment(segmentationId, 1, viewportId, 0.9, 750, false);
3539
+
3540
+ expect(frames).toHaveLength(1);
3541
+ });
3542
+
3543
+ describe('when one jump highlights several viewports', () => {
3544
+ beforeEach(() => {
3545
+ jest.mocked(cstSegmentation.state.getSegmentation).mockReturnValue({
3546
+ segments: { 1: { cachedStats: { center: { world: [10, 10, 10] } } } },
3547
+ } as unknown as cstTypes.Segmentation);
3548
+ jest
3549
+ .spyOn(service, 'getViewportIdsWithSegmentation')
3550
+ .mockReturnValue(['viewportId1', 'viewportId2']);
3551
+ // @ts-expect-error - mock only needed properties
3552
+ getEnabledElementByViewportId.mockReturnValue({ viewport: { jumpToWorld: jest.fn() } });
3553
+ });
3554
+
3555
+ it('runs one animation for the style the viewports share', () => {
3556
+ mockRepresentation(csToolsEnums.SegmentationRepresentations.Labelmap);
3557
+
3558
+ service.jumpToSegmentCenter(segmentationId, 1);
3559
+ runFrame(0);
3560
+
3561
+ expect(frames).toHaveLength(1);
3562
+ expect(fillAlphaOf(1)).toBe(defaultFillAlpha);
3563
+ });
3564
+
3565
+ it('animates both a labelmap and a contour viewport', () => {
3566
+ jest.spyOn(service, 'getSegmentationRepresentations').mockImplementation(
3567
+ id =>
3568
+ [
3569
+ {
3570
+ segmentationId,
3571
+ type:
3572
+ id === 'viewportId1'
3573
+ ? csToolsEnums.SegmentationRepresentations.Labelmap
3574
+ : csToolsEnums.SegmentationRepresentations.Contour,
3575
+ },
3576
+ ] as SegmentationRepresentation[]
3577
+ );
3578
+
3579
+ service.jumpToSegmentCenter(segmentationId, 1);
3580
+ runFrame(performance.now());
3581
+
3582
+ expect(frames).toHaveLength(2);
3583
+ expect(cstSegmentation.config.style.setStyle).toHaveBeenCalledWith(
3584
+ { segmentationId, segmentIndex: 1, type: 'Labelmap' },
3585
+ expect.objectContaining({ fillAlpha: expect.any(Number) })
3586
+ );
3587
+ expect(cstSegmentation.config.style.setStyle).toHaveBeenCalledWith(
3588
+ { segmentationId, segmentIndex: 1, type: 'Contour' },
3589
+ expect.objectContaining({ outlineWidth: expect.any(Number) })
3590
+ );
3591
+ });
3592
+ });
3593
+ });
3594
+ });
3595
+
3596
+ describe('_onSegmentationDataModifiedFromSource', () => {
3597
+ it('should broadcast the event', () => {
3598
+ jest.spyOn(eventTarget, 'addEventListener').mockReturnValue(undefined);
3599
+
3600
+ const callback = jest.fn();
3601
+ service.subscribe(service.EVENTS.SEGMENTATION_DATA_MODIFIED, callback);
3602
+
3603
+ service.onModeEnter();
3604
+
3605
+ const _onSegmentationDataModifiedFromSource = jest.mocked(eventTarget.addEventListener).mock
3606
+ .calls[2][1];
3607
+
3608
+ _onSegmentationDataModifiedFromSource({
3609
+ detail: {
3610
+ segmentationId: 'segmentationId',
3611
+ },
3612
+ });
3613
+
3614
+ expect(callback).toHaveBeenCalledTimes(1);
3615
+ expect(callback).toHaveBeenCalledWith({
3616
+ segmentationId: 'segmentationId',
3617
+ });
3618
+ });
3619
+ });
3620
+
3621
+ describe('_onSegmentationRepresentationModifiedFromSource', () => {
3622
+ it('should broadcast the event', () => {
3623
+ jest.spyOn(eventTarget, 'addEventListener').mockReturnValue(undefined);
3624
+
3625
+ const callback = jest.fn();
3626
+ service.subscribe(service.EVENTS.SEGMENTATION_REPRESENTATION_MODIFIED, callback);
3627
+
3628
+ service.onModeEnter();
3629
+
3630
+ const _onSegmentationRepresentationModifiedFromSource = jest.mocked(
3631
+ eventTarget.addEventListener
3632
+ ).mock.calls[3][1];
3633
+
3634
+ _onSegmentationRepresentationModifiedFromSource({
3635
+ detail: {
3636
+ segmentationId: 'segmentationId',
3637
+ viewportId: 'viewportId',
3638
+ },
3639
+ });
3640
+
3641
+ expect(callback).toHaveBeenCalledTimes(1);
3642
+ expect(callback).toHaveBeenCalledWith({
3643
+ segmentationId: 'segmentationId',
3644
+ viewportId: 'viewportId',
3645
+ });
3646
+ });
3647
+ });
3648
+
3649
+ describe('_onSegmentationModifiedFromSource', () => {
3650
+ it('should broadcast the event', () => {
3651
+ jest.spyOn(eventTarget, 'addEventListener').mockReturnValue(undefined);
3652
+
3653
+ const callback = jest.fn();
3654
+ service.subscribe(service.EVENTS.SEGMENTATION_MODIFIED, callback);
3655
+
3656
+ service.onModeEnter();
3657
+
3658
+ const _onSegmentationModifiedFromSource = jest.mocked(eventTarget.addEventListener).mock
3659
+ .calls[0][1];
3660
+
3661
+ _onSegmentationModifiedFromSource({
3662
+ detail: {
3663
+ segmentationId: 'segmentationId',
3664
+ },
3665
+ });
3666
+
3667
+ expect(callback).toHaveBeenCalledTimes(1);
3668
+ expect(callback).toHaveBeenCalledWith({
3669
+ segmentationId: 'segmentationId',
3670
+ });
3671
+ });
3672
+ });
3673
+
3674
+ describe('_onSegmentationAddedFromSource', () => {
3675
+ it('should broadcast the event', () => {
3676
+ jest.spyOn(eventTarget, 'addEventListener').mockReturnValue(undefined);
3677
+
3678
+ const callback = jest.fn();
3679
+ service.subscribe(service.EVENTS.SEGMENTATION_ADDED, callback);
3680
+
3681
+ service.onModeEnter();
3682
+
3683
+ const _onSegmentationAddedFromSource = jest.mocked(eventTarget.addEventListener).mock
3684
+ .calls[6][1];
3685
+
3686
+ _onSegmentationAddedFromSource({
3687
+ detail: {
3688
+ segmentationId: 'segmentationId',
3689
+ },
3690
+ });
3691
+
3692
+ expect(callback).toHaveBeenCalledTimes(1);
3693
+ expect(callback).toHaveBeenCalledWith({
3694
+ segmentationId: 'segmentationId',
3695
+ });
3696
+ });
3697
+ });
3698
+ });