diff --git a/.gitignore b/.gitignore index ed3400749..245556be5 100644 --- a/.gitignore +++ b/.gitignore @@ -24,6 +24,7 @@ yarn-error.log .DS_Store .env *.code-workspace +.directory # Common Example Data Directories sampledata/ diff --git a/commit.txt b/commit.txt index 1590b5fff..90fdf8bec 100644 --- a/commit.txt +++ b/commit.txt @@ -1 +1 @@ -dc37802ec1f739a6ed602363bdf231d6fe58827e \ No newline at end of file +dc37802ec1f739a6ed602363bdf231d6fe58827e diff --git a/extensions/cornerstone-dicom-seg/package.json b/extensions/cornerstone-dicom-seg/package.json index cb50724e5..f5e84c27a 100644 --- a/extensions/cornerstone-dicom-seg/package.json +++ b/extensions/cornerstone-dicom-seg/package.json @@ -46,9 +46,9 @@ }, "dependencies": { "@babel/runtime": "^7.20.13", - "@cornerstonejs/adapters": "^1.68.1", - "@cornerstonejs/core": "^1.68.1", - "@kitware/vtk.js": "29.7.0", + "@cornerstonejs/adapters": "^1.70.0", + "@cornerstonejs/core": "^1.70.0", + "@kitware/vtk.js": "30.3.1", "react-color": "^2.19.3" } } diff --git a/extensions/cornerstone-dicom-seg/src/getPanelModule.tsx b/extensions/cornerstone-dicom-seg/src/getPanelModule.tsx index 12331caee..a86144d4f 100644 --- a/extensions/cornerstone-dicom-seg/src/getPanelModule.tsx +++ b/extensions/cornerstone-dicom-seg/src/getPanelModule.tsx @@ -3,7 +3,6 @@ import React from 'react'; import { useAppConfig } from '@state'; import { Toolbox } from '@ohif/ui'; import PanelSegmentation from './panels/PanelSegmentation'; -import { SegmentationPanelMode } from './types/segmentation'; const getPanelModule = ({ commandsManager, @@ -17,11 +16,6 @@ const getPanelModule = ({ const wrappedPanelSegmentation = configuration => { const [appConfig] = useAppConfig(); - const disableEditingForMode = customizationService.get('segmentation.disableEditing'); - const segmentationPanelMode = - customizationService.get('segmentation.segmentationPanelMode')?.value || - SegmentationPanelMode.Dropdown; - return ( ); @@ -38,9 +32,6 @@ const getPanelModule = ({ const wrappedPanelSegmentationWithTools = configuration => { const [appConfig] = useAppConfig(); - const segmentationPanelMode = - customizationService.get('segmentation.segmentationPanelMode')?.value || - SegmentationPanelMode.Dropdown; return ( <> @@ -60,7 +51,8 @@ const getPanelModule = ({ extensionManager={extensionManager} configuration={{ ...configuration, - segmentationPanelMode: segmentationPanelMode, + disableEditing: appConfig.disableEditing, + ...customizationService.get('segmentation.panel'), }} /> diff --git a/extensions/cornerstone-dicom-seg/src/getToolbarModule.ts b/extensions/cornerstone-dicom-seg/src/getToolbarModule.ts index 19390d2ac..0a06cf7eb 100644 --- a/extensions/cornerstone-dicom-seg/src/getToolbarModule.ts +++ b/extensions/cornerstone-dicom-seg/src/getToolbarModule.ts @@ -52,16 +52,22 @@ export function getToolbarModule({ commandsManager, servicesManager }) { ]; } +// Todo: this is duplicate, we should move it to a shared location function getToolNameForButton(button) { const { props } = button; const commands = props?.commands || button.commands; - - if (commands && commands.length) { - const command = commands[0]; - const { commandOptions } = command; - const { toolName } = commandOptions || { toolName: props?.id ?? button.id }; - return toolName; + const commandsArray = Array.isArray(commands) ? commands : [commands]; + const firstCommand = commandsArray[0]; + if (typeof firstCommand === 'string') { + // likely not a cornerstone tool + return null; } - return null; + + if ('commandOptions' in firstCommand) { + return firstCommand.commandOptions.toolName ?? props?.id ?? button.id; + } + + // use id as a fallback for toolName + return props?.id ?? button.id; } diff --git a/extensions/cornerstone-dicom-seg/src/index.tsx b/extensions/cornerstone-dicom-seg/src/index.tsx index 5fe0efef5..02db57545 100644 --- a/extensions/cornerstone-dicom-seg/src/index.tsx +++ b/extensions/cornerstone-dicom-seg/src/index.tsx @@ -6,7 +6,6 @@ import getHangingProtocolModule from './getHangingProtocolModule'; import getPanelModule from './getPanelModule'; import getCommandsModule from './commandsModule'; import { getToolbarModule } from './getToolbarModule'; -import preRegistration from './init'; const Component = React.lazy(() => { return import(/* webpackPrefetch: true */ './viewports/OHIFCornerstoneSEGViewport'); @@ -29,7 +28,6 @@ const extension = { * You ID can be anything you want, but it should be unique. */ id, - preRegistration, /** * PanelModule should provide a list of panels that will be available in OHIF * for Modes to consume and render. Each panel is defined by a {name, diff --git a/extensions/cornerstone-dicom-seg/src/init.ts b/extensions/cornerstone-dicom-seg/src/init.ts deleted file mode 100644 index c57e6a289..000000000 --- a/extensions/cornerstone-dicom-seg/src/init.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { addTool, BrushTool } from '@cornerstonejs/tools'; - -export default function init({ servicesManager }): void { - addTool(BrushTool); -} diff --git a/extensions/cornerstone-dicom-seg/src/panels/PanelSegmentation.tsx b/extensions/cornerstone-dicom-seg/src/panels/PanelSegmentation.tsx index 1a63ecd3a..c7f0232c9 100644 --- a/extensions/cornerstone-dicom-seg/src/panels/PanelSegmentation.tsx +++ b/extensions/cornerstone-dicom-seg/src/panels/PanelSegmentation.tsx @@ -242,7 +242,13 @@ export default function PanelSegmentation({ }); }; - const SegmentationGroupTableComponent = components[configuration?.segmentationPanelMode]; + const SegmentationGroupTableComponent = + components[configuration?.segmentationPanelMode] || SegmentationGroupTable; + const allowAddSegment = configuration?.addSegment; + const onSegmentationAddWrapper = + configuration?.onSegmentationAdd && typeof configuration?.onSegmentationAdd === 'function' + ? configuration?.onSegmentationAdd + : onSegmentationAdd; return ( { + return webpackCommon(env, argv, { SRC_DIR, DIST_DIR }); +}; diff --git a/extensions/cornerstone-dynamic-volume/.webpack/webpack.prod.js b/extensions/cornerstone-dynamic-volume/.webpack/webpack.prod.js new file mode 100644 index 000000000..66a3e9fc1 --- /dev/null +++ b/extensions/cornerstone-dynamic-volume/.webpack/webpack.prod.js @@ -0,0 +1,54 @@ +const webpack = require('webpack'); +const { merge } = require('webpack-merge'); +const path = require('path'); +const webpackCommon = require('./../../../.webpack/webpack.base.js'); +const MiniCssExtractPlugin = require('mini-css-extract-plugin'); + +const pkg = require('./../package.json'); + +const ROOT_DIR = path.join(__dirname, '../'); +const SRC_DIR = path.join(__dirname, '../src'); +const DIST_DIR = path.join(__dirname, '../dist'); +const ENTRY = { + app: `${SRC_DIR}/index.ts`, +}; + +const outputName = `ohif-${pkg.name.split('/').pop()}`; + +module.exports = (env, argv) => { + const commonConfig = webpackCommon(env, argv, { SRC_DIR, DIST_DIR, ENTRY }); + + return merge(commonConfig, { + stats: { + colors: true, + hash: true, + timings: true, + assets: true, + chunks: false, + chunkModules: false, + modules: false, + children: false, + warnings: true, + }, + optimization: { + minimize: true, + sideEffects: true, + }, + output: { + path: ROOT_DIR, + library: 'ohif-extension-cornerstone', + libraryTarget: 'umd', + filename: pkg.main, + }, + externals: [/\b(vtk.js)/, /\b(dcmjs)/, /\b(gl-matrix)/, /^@ohif/, /^@cornerstonejs/], + plugins: [ + new webpack.optimize.LimitChunkCountPlugin({ + maxChunks: 1, + }), + new MiniCssExtractPlugin({ + filename: `./dist/${outputName}.css`, + chunkFilename: `./dist/${outputName}.css`, + }), + ], + }); +}; diff --git a/extensions/cornerstone-dynamic-volume/LICENSE b/extensions/cornerstone-dynamic-volume/LICENSE new file mode 100644 index 000000000..24728a704 --- /dev/null +++ b/extensions/cornerstone-dynamic-volume/LICENSE @@ -0,0 +1,20 @@ +MIT License + +Copyright (c) 2023 cornerstone-dynamic-volume () + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/extensions/cornerstone-dynamic-volume/README.md b/extensions/cornerstone-dynamic-volume/README.md new file mode 100644 index 000000000..70949801a --- /dev/null +++ b/extensions/cornerstone-dynamic-volume/README.md @@ -0,0 +1,8 @@ +# cornerstone-dynamic-volume +## Description + +## Author +OHIF + +## License +MIT diff --git a/extensions/cornerstone-dynamic-volume/babel.config.js b/extensions/cornerstone-dynamic-volume/babel.config.js new file mode 100644 index 000000000..325ca2a8e --- /dev/null +++ b/extensions/cornerstone-dynamic-volume/babel.config.js @@ -0,0 +1 @@ +module.exports = require('../../babel.config.js'); diff --git a/extensions/cornerstone-dynamic-volume/package.json b/extensions/cornerstone-dynamic-volume/package.json new file mode 100644 index 000000000..39b8882fe --- /dev/null +++ b/extensions/cornerstone-dynamic-volume/package.json @@ -0,0 +1,50 @@ +{ + "name": "@ohif/extension-cornerstone-dynamic-volume", + "version": "3.8.0-beta.72", + "description": "OHIF extension for 4D volumes data", + "author": "OHIF", + "license": "MIT", + "repository": "OHIF/Viewers", + "main": "dist/ohif-extension-cornerstone-dynamic-volume.umd.js", + "module": "src/index.ts", + "exports": { + ".": "./src/index.ts", + "./types": "./src/types/index.ts" + }, + "files": [ + "dist", + "README.md" + ], + "publishConfig": { + "access": "public" + }, + "scripts": { + "dev": "cross-env NODE_ENV=development webpack --config .webpack/webpack.dev.js --watch --output-pathinfo", + "build": "cross-env NODE_ENV=production webpack --config .webpack/webpack.prod.js", + "build:package": "yarn run build", + "clean": "shx rm -rf dist", + "clean:deep": "yarn run clean && shx rm -rf node_modules", + "start": "yarn run dev", + "test:unit": "jest --watchAll", + "test:unit:ci": "jest --ci --runInBand --collectCoverage --passWithNoTests" + }, + "peerDependencies": { + "@ohif/core": "3.7.0-beta.76", + "@ohif/ui": "3.7.0-beta.76", + "@ohif/extension-default": "3.7.0-beta.76", + "@ohif/extension-cornerstone": "3.7.0-beta.76", + "@ohif/i18n": "3.7.0-beta.76", + "dcmjs": "^0.29.5", + "dicom-parser": "^1.8.21", + "hammerjs": "^2.0.8", + "prop-types": "^15.6.2", + "react": "^17.0.2" + }, + "dependencies": { + "@babel/runtime": "^7.20.13", + "@cornerstonejs/tools": "^1.70.0", + "@cornerstonejs/core": "^1.70.0", + "@cornerstonejs/streaming-image-volume-loader": "^1.70.0", + "classnames": "^2.3.2" + } +} diff --git a/extensions/cornerstone-dynamic-volume/src/actions/index.ts b/extensions/cornerstone-dynamic-volume/src/actions/index.ts new file mode 100644 index 000000000..45d2adfc2 --- /dev/null +++ b/extensions/cornerstone-dynamic-volume/src/actions/index.ts @@ -0,0 +1,3 @@ +import updateSegmentationsChartDisplaySet from './updateSegmentationsChartDisplaySet'; + +export { updateSegmentationsChartDisplaySet }; diff --git a/extensions/cornerstone-dynamic-volume/src/actions/updateSegmentationsChartDisplaySet.ts b/extensions/cornerstone-dynamic-volume/src/actions/updateSegmentationsChartDisplaySet.ts new file mode 100644 index 000000000..810d98488 --- /dev/null +++ b/extensions/cornerstone-dynamic-volume/src/actions/updateSegmentationsChartDisplaySet.ts @@ -0,0 +1,281 @@ +import { DicomMetadataStore, utils } from '@ohif/core'; + +import * as cs from '@cornerstonejs/core'; +import * as csTools from '@cornerstonejs/tools'; + +const CHART_MODALITY = 'CHT'; +const SEG_CHART_INSTANCE_UID = utils.guid(); + +// Private SOPClassUid for chart data +const ChartDataSOPClassUid = '1.9.451.13215.7.3.2.7.6.1'; + +const { utilities: csToolsUtils } = csTools; + +function _getDateTimeStr() { + const now = new Date(); + const date = + now.getFullYear() + ('0' + now.getUTCMonth()).slice(-2) + ('0' + now.getUTCDate()).slice(-2); + const time = + ('0' + now.getUTCHours()).slice(-2) + + ('0' + now.getUTCMinutes()).slice(-2) + + ('0' + now.getUTCSeconds()).slice(-2); + + return { date, time }; +} + +function _getTimePointsDataByTagName(volume, timePointsTag) { + const uniqueTimePoints = volume.imageIds.reduce((timePoints, imageId) => { + const instance = DicomMetadataStore.getInstanceByImageId(imageId); + const timePointValue = instance[timePointsTag]; + + if (timePointValue !== undefined) { + timePoints.add(timePointValue); + } + + return timePoints; + }, new Set()); + + return Array.from(uniqueTimePoints).sort((a: number, b: number) => a - b); +} + +function _convertTimePointsUnit(timePoints, timePointsUnit) { + const validUnits = ['ms', 's', 'm', 'h']; + const divisors = [1000, 60, 60]; + const currentUnitIndex = validUnits.indexOf(timePointsUnit); + let divisor = 1; + + if (currentUnitIndex !== -1) { + for (let i = currentUnitIndex; i < validUnits.length - 1; i++) { + const newDivisor = divisor * divisors[i]; + const greaterThanDivisorCount = timePoints.filter(timePoint => timePoint > newDivisor).length; + + // Change the scale only if more than 50% of the time points are + // greater than the new divisor. + if (greaterThanDivisorCount <= timePoints.length / 2) { + break; + } + + divisor = newDivisor; + timePointsUnit = validUnits[i + 1]; + } + + if (divisor > 1) { + timePoints = timePoints.map(timePoint => timePoint / divisor); + } + } + + return { timePoints, timePointsUnit }; +} + +// It currently supports only one tag but a few other will be added soon +// Supported 4D Tags +// (0018,1060) Trigger Time [NOK] +// (0018,0081) Echo Time [NOK] +// (0018,0086) Echo Number [NOK] +// (0020,0100) Temporal Position Identifier [NOK] +// (0054,1300) FrameReferenceTime [OK] +function _getTimePointsData(volume) { + const timePointsTags = { + FrameReferenceTime: { + unit: 'ms', + }, + }; + + const timePointsTagNames = Object.keys(timePointsTags); + let timePoints; + let timePointsUnit; + + for (let i = 0; i < timePointsTagNames.length; i++) { + const tagName = timePointsTagNames[i]; + const curTimePoints = _getTimePointsDataByTagName(volume, tagName); + + if (curTimePoints.length) { + timePoints = curTimePoints; + timePointsUnit = timePointsTags[tagName].unit; + break; + } + } + + if (!timePoints.length) { + const concatTagNames = timePointsTagNames.join(', '); + + throw new Error(`Could not extract time points data for the following tags: ${concatTagNames}`); + } + + const convertedTimePoints = _convertTimePointsUnit(timePoints, timePointsUnit); + + timePoints = convertedTimePoints.timePoints; + timePointsUnit = convertedTimePoints.timePointsUnit; + + return { timePoints, timePointsUnit }; +} + +function _getSegmentationData(segmentation, volumesTimePointsCache, displaySetService) { + const displaySets = displaySetService.getActiveDisplaySets(); + + const dynamic4DDisplaySet = displaySets.find(displaySet => { + const anInstance = displaySet.instances?.[0]; + + if (anInstance) { + return ( + anInstance.FrameReferenceTime !== undefined || anInstance.NumberOfTimeSlices !== undefined + ); + } + + return false; + }); + + // const referencedDynamicVolume = cs.cache.getVolume(dynamic4DDisplaySet.displaySetInstanceUID); + let volumeCacheKey: string | undefined; + const volumeId = dynamic4DDisplaySet.displaySetInstanceUID; + + for (const [key] of cs.cache._volumeCache) { + if (key.includes(volumeId)) { + volumeCacheKey = key; + break; + } + } + + let referencedDynamicVolume; + if (volumeCacheKey) { + referencedDynamicVolume = cs.cache.getVolume(volumeCacheKey); + } + + const { StudyInstanceUID, StudyDescription } = DicomMetadataStore.getInstanceByImageId( + referencedDynamicVolume.imageIds[0] + ); + + const [timeData, _] = csToolsUtils.dynamicVolume.getDataInTime(referencedDynamicVolume, { + maskVolumeId: segmentation.id, + }) as number[][]; + + const pixelCount = timeData.length; + + if (pixelCount === 0) { + return []; + } + + // since we only use one segmentation representation per segmentationId + // it is fine to pick the first one + const segmentationRepresentations = csTools.segmentation.state.getSegmentationIdRepresentations( + segmentation.id + ); + + const segmentationRepresentationUID = + segmentationRepresentations[0].segmentationRepresentationUID; + + const toolGroupId = csTools.segmentation.state.getToolGroupIdFromSegmentationRepresentationUID( + segmentationRepresentationUID + ); + + // Todo: this is useless we should be able to grab color with just segRepUID and segmentIndex + const color = csTools.segmentation.config.color.getColorForSegmentIndex( + toolGroupId, + segmentationRepresentationUID, + 1 // segmentIndex + ); + + const hexColor = cs.utilities.color.rgbToHex(...color); + let timePointsData = volumesTimePointsCache.get(referencedDynamicVolume); + + if (!timePointsData) { + timePointsData = _getTimePointsData(referencedDynamicVolume); + volumesTimePointsCache.set(referencedDynamicVolume, timePointsData); + } + + const { timePoints, timePointsUnit } = timePointsData; + + if (timePoints.length !== timeData[0].length) { + throw new Error('Invalid number of time points returned'); + } + + const timepointsCount = timePoints.length; + const chartSeriesData = new Array(timepointsCount); + + for (let i = 0; i < timepointsCount; i++) { + const average = timeData.reduce((acc, cur) => acc + cur[i] / pixelCount, 0); + + chartSeriesData[i] = [timePoints[i], average]; + } + + return { + StudyInstanceUID, + StudyDescription, + chartData: { + series: { + label: segmentation.label, + points: chartSeriesData, + color: hexColor, + }, + axis: { + x: { + label: `Time (${timePointsUnit})`, + }, + y: { + label: `Vl (Bq/ml)`, + }, + }, + }, + }; +} + +function _getInstanceFromSegmentations(segmentations, displaySetService) { + if (!segmentations.length) { + return; + } + + const volumesTimePointsCache = new WeakMap(); + const segmentationsData = segmentations.map(segmentation => + _getSegmentationData(segmentation, volumesTimePointsCache, displaySetService) + ); + + const { date: seriesDate, time: seriesTime } = _getDateTimeStr(); + const series = segmentationsData.reduce((allSeries, curSegData) => { + return [...allSeries, curSegData.chartData.series]; + }, []); + + const instance = { + SOPClassUID: ChartDataSOPClassUid, + Modality: CHART_MODALITY, + SOPInstanceUID: utils.guid(), + SeriesDate: seriesDate, + SeriesTime: seriesTime, + SeriesInstanceUID: SEG_CHART_INSTANCE_UID, + StudyInstanceUID: segmentationsData[0].StudyInstanceUID, + StudyDescription: segmentationsData[0].StudyDescription, + SeriesNumber: 100, + SeriesDescription: 'Segmentation chart series data', + chartData: { + series, + axis: { ...segmentationsData[0].chartData.axis }, + }, + }; + + const seriesMetadata = { + StudyInstanceUID: instance.StudyInstanceUID, + StudyDescription: instance.StudyDescription, + SeriesInstanceUID: instance.SeriesInstanceUID, + SeriesDescription: instance.SeriesDescription, + SeriesNumber: instance.SeriesNumber, + SeriesTime: instance.SeriesTime, + SOPClassUID: instance.SOPClassUID, + Modality: instance.Modality, + }; + + return { seriesMetadata, instance }; +} + +function updateSegmentationsChartDisplaySet({ servicesManager }): void { + const { segmentationService, displaySetService } = servicesManager.services; + const segmentations = segmentationService.getSegmentations(); + const { seriesMetadata, instance } = + _getInstanceFromSegmentations(segmentations, displaySetService) ?? {}; + + if (seriesMetadata && instance) { + // An event is triggered after adding the instance and the displaySet is created + DicomMetadataStore.addSeriesMetadata([seriesMetadata], true); + DicomMetadataStore.addInstances([instance], true); + } +} + +export { updateSegmentationsChartDisplaySet as default }; diff --git a/extensions/cornerstone-dynamic-volume/src/commandsModule.ts b/extensions/cornerstone-dynamic-volume/src/commandsModule.ts new file mode 100644 index 000000000..a6cdf6cda --- /dev/null +++ b/extensions/cornerstone-dynamic-volume/src/commandsModule.ts @@ -0,0 +1,407 @@ +import * as importedActions from './actions'; +import { utilities, Enums } from '@cornerstonejs/tools'; +import { cache } from '@cornerstonejs/core'; + +const LABELMAP = Enums.SegmentationRepresentations.Labelmap; + +const commandsModule = ({ commandsManager, servicesManager }) => { + const services = servicesManager.services; + const { displaySetService, viewportGridService, segmentationService } = services; + + const actions = { + ...importedActions, + getDynamic4DDisplaySet: () => { + const displaySets = displaySetService.getActiveDisplaySets(); + + const dynamic4DDisplaySet = displaySets.find(displaySet => { + const anInstance = displaySet.instances?.[0]; + + if (anInstance) { + return ( + anInstance.FrameReferenceTime !== undefined || + anInstance.NumberOfTimeSlices !== undefined || + anInstance.TemporalPositionIdentifier !== undefined + ); + } + + return false; + }); + + return dynamic4DDisplaySet; + }, + getComputedDisplaySets: () => { + const displaySetCache = displaySetService.getDisplaySetCache(); + const cachedDisplaySets = [...displaySetCache.values()]; + const computedDisplaySets = cachedDisplaySets.filter(displaySet => { + return displaySet.isDerived; + }); + return computedDisplaySets; + }, + exportTimeReportCSV: ({ segmentations, config, options, summaryStats }) => { + const dynamic4DDisplaySet = actions.getDynamic4DDisplaySet(); + + const volumeId = dynamic4DDisplaySet?.displaySetInstanceUID; + + // cache._volumeCache is a map that has a key that includes the volumeId + // it is not exactly the volumeId, but it is the key that includes the volumeId + // so we can't do cache._volumeCache.get(volumeId) we should iterate + // over the keys and find the one that includes the volumeId + let volumeCacheKey: string | undefined; + + for (const [key] of cache._volumeCache) { + if (key.includes(volumeId)) { + volumeCacheKey = key; + break; + } + } + + let dynamicVolume; + if (volumeCacheKey) { + dynamicVolume = cache.getVolume(volumeCacheKey); + } + + const instance = dynamic4DDisplaySet.instances[0]; + + const csv = []; + + // CSV header information with placeholder empty values for the metadata lines + csv.push(`Patient ID,${instance.PatientID},`); + csv.push(`Study Date,${instance.StudyDate},`); + csv.push(`StudyInstanceUID,${instance.StudyInstanceUID},`); + csv.push(`StudyDescription,${instance.StudyDescription},`); + csv.push(`SeriesInstanceUID,${instance.SeriesInstanceUID},`); + + // empty line + csv.push(''); + csv.push(''); + + // Helper function to calculate standard deviation + function calculateStandardDeviation(data) { + const n = data.length; + const mean = data.reduce((acc, value) => acc + value, 0) / n; + const squaredDifferences = data.map(value => (value - mean) ** 2); + const variance = squaredDifferences.reduce((acc, value) => acc + value, 0) / n; + const stdDeviation = Math.sqrt(variance); + return stdDeviation; + } + + // Iterate through each segmentation to get the timeData and ijkCoords + segmentations.forEach((segmentation, segmentationIndex) => { + const [timeData, ijkCoords] = utilities.dynamicVolume.getDataInTime(dynamicVolume, { + maskVolumeId: segmentation.id, + }) as number[][]; + + if (summaryStats) { + // Adding column headers for pixel identifier and segmentation label ids + let headers = 'Operation,Segmentation Label ID'; + const maxLength = dynamicVolume.numTimePoints; + for (let t = 0; t < maxLength; t++) { + headers += `,Time Point ${t}`; + } + csv.push(headers); + // // perform summary statistics on the timeData including for each time point, mean, median, min, max, and standard deviation for + // // all the voxels in the ROI + const mean = []; + const min = []; + const minIJK = []; + const max = []; + const maxIJK = []; + const std = []; + + const numVoxels = timeData.length; + // Helper function to calculate standard deviation + for (let timeIndex = 0; timeIndex < maxLength; timeIndex++) { + // for each voxel in the ROI, get the value at the current time point + const voxelValues = []; + for (let voxelIndex = 0; voxelIndex < numVoxels; voxelIndex++) { + voxelValues.push(timeData[voxelIndex][timeIndex]); + } + + mean.push(voxelValues.reduce((acc, value) => acc + value, 0) / numVoxels); + const minimum = Math.min(...voxelValues); + min.push(minimum); + minIJK.push(ijkCoords[voxelValues.indexOf(minimum)]); + const maximum = Math.max(...voxelValues); + max.push(maximum); + maxIJK.push(ijkCoords[voxelValues.indexOf(maximum)]); + std.push(calculateStandardDeviation(voxelValues)); + } + + let row = `Mean,${segmentation.label}`; + // Generate separate rows for each statistic + for (let t = 0; t < maxLength; t++) { + row += `,${mean[t]}`; + } + + csv.push(row); + + row = `Standard Deviation,${segmentation.label}`; + for (let t = 0; t < maxLength; t++) { + row += `,${std[t]}`; + } + + csv.push(row); + + row = `Min,${segmentation.label}`; + for (let t = 0; t < maxLength; t++) { + row += `,${min[t]}`; + } + + csv.push(row); + + row = `Max,${segmentation.label}`; + for (let t = 0; t < maxLength; t++) { + row += `,${max[t]}`; + } + + csv.push(row); + } else { + // Adding column headers for pixel identifier and segmentation label ids + let headers = 'Pixel Identifier (IJK),Segmentation Label ID'; + const maxLength = dynamicVolume.numTimePoints; + for (let t = 0; t < maxLength; t++) { + headers += `,Time Point ${t}`; + } + csv.push(headers); + // Assuming timeData and ijkCoords are of the same length + for (let i = 0; i < timeData.length; i++) { + // Generate the pixel identifier + const pixelIdentifier = `${ijkCoords[i][0]}_${ijkCoords[i][1]}_${ijkCoords[i][2]}`; + + // Start a new row for the current pixel + let row = `${pixelIdentifier},${segmentation.label}`; + + // Add time data points for this pixel + for (let t = 0; t < timeData[i].length; t++) { + row += `,${timeData[i][t]}`; + } + + // Append the row to the CSV array + csv.push(row); + } + } + }); + + // Convert to CSV string + const csvContent = csv.join('\n'); + + // Generate filename and trigger download + const filename = `${instance.PatientID}.csv`; + const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' }); + const link = document.createElement('a'); + const url = URL.createObjectURL(blob); + link.setAttribute('href', url); + link.setAttribute('download', filename); + link.style.visibility = 'hidden'; + document.body.appendChild(link); + link.click(); + document.body.removeChild(link); + }, + swapDynamicWithComputedDisplaySet: ({ displaySet }) => { + const computedDisplaySet = displaySet; + + const displaySetCache = displaySetService.getDisplaySetCache(); + const cachedDisplaySetKeys = [displaySetCache.keys()]; + const { displaySetInstanceUID } = computedDisplaySet; + // Check to see if computed display set is already in cache + if (!cachedDisplaySetKeys.includes(displaySetInstanceUID)) { + displaySetCache.set(displaySetInstanceUID, computedDisplaySet); + } + + // Get all viewports and their corresponding indices + const { viewports } = viewportGridService.getState(); + + // get the viewports in the grid + // iterate over them and find the ones that are showing a dynamic + // volume (displaySet), and replace that exact displaySet with the + // computed displaySet + + const dynamic4DDisplaySet = actions.getDynamic4DDisplaySet(); + + const viewportsToUpdate = []; + + for (const [key, value] of viewports) { + const viewport = value; + const viewportOptions = viewport.viewportOptions; + const { displaySetInstanceUIDs } = viewport; + const displaySetInstanceUIDIndex = displaySetInstanceUIDs.indexOf( + dynamic4DDisplaySet.displaySetInstanceUID + ); + if (displaySetInstanceUIDIndex !== -1) { + const newViewport = { + viewportId: viewport.viewportId, + // merge the other displaySetInstanceUIDs with the new one + displaySetInstanceUIDs: [ + ...displaySetInstanceUIDs.slice(0, displaySetInstanceUIDIndex), + displaySetInstanceUID, + ...displaySetInstanceUIDs.slice(displaySetInstanceUIDIndex + 1), + ], + viewportOptions: { + initialImageOptions: viewportOptions.initialImageOptions, + viewportType: 'volume', + orientation: viewportOptions.orientation, + background: viewportOptions.background, + }, + }; + viewportsToUpdate.push(newViewport); + } + } + + viewportGridService.setDisplaySetsForViewports(viewportsToUpdate); + }, + swapComputedWithDynamicDisplaySet: () => { + // Todo: this assumes there is only one dynamic display set in the viewer + const dynamicDisplaySet = actions.getDynamic4DDisplaySet(); + + const displaySetCache = displaySetService.getDisplaySetCache(); + const cachedDisplaySetKeys = [...displaySetCache.keys()]; // Fix: Spread to get the array + const { displaySetInstanceUID } = dynamicDisplaySet; + + // Check to see if dynamic display set is already in cache + if (!cachedDisplaySetKeys.includes(displaySetInstanceUID)) { + displaySetCache.set(displaySetInstanceUID, dynamicDisplaySet); + } + + // Get all viewports and their corresponding indices + const { viewports } = viewportGridService.getState(); + + // Get the computed 4D display set + const computed4DDisplaySet = actions.getComputedDisplaySets()[0]; + + const viewportsToUpdate = []; + + for (const [key, value] of viewports) { + const viewport = value; + const viewportOptions = viewport.viewportOptions; + const { displaySetInstanceUIDs } = viewport; + const displaySetInstanceUIDIndex = displaySetInstanceUIDs.indexOf( + computed4DDisplaySet.displaySetInstanceUID + ); + if (displaySetInstanceUIDIndex !== -1) { + const newViewport = { + viewportId: viewport.viewportId, + // merge the other displaySetInstanceUIDs with the new one + displaySetInstanceUIDs: [ + ...displaySetInstanceUIDs.slice(0, displaySetInstanceUIDIndex), + displaySetInstanceUID, + ...displaySetInstanceUIDs.slice(displaySetInstanceUIDIndex + 1), + ], + viewportOptions: { + initialImageOptions: viewportOptions.initialImageOptions, + viewportType: 'volume', + orientation: viewportOptions.orientation, + background: viewportOptions.background, + }, + }; + viewportsToUpdate.push(newViewport); + } + } + + viewportGridService.setDisplaySetsForViewports(viewportsToUpdate); + }, + createNewLabelMapForDynamicVolume: async ({ label }) => { + const { viewports, activeViewportId } = viewportGridService.getState(); + + // get the dynamic 4D display set + const dynamic4DDisplaySet = actions.getDynamic4DDisplaySet(); + const dynamic4DDisplaySetInstanceUID = dynamic4DDisplaySet.displaySetInstanceUID; + + // check if the dynamic 4D display set is in the display, if not we might have + // the computed volumes and we should choose them for the segmentation + // creation + + let referenceDisplaySet; + + const activeViewport = viewports.get(activeViewportId); + const activeDisplaySetInstanceUIDs = activeViewport.displaySetInstanceUIDs; + const dynamicIsInActiveViewport = activeDisplaySetInstanceUIDs.includes( + dynamic4DDisplaySetInstanceUID + ); + + if (dynamicIsInActiveViewport) { + referenceDisplaySet = dynamic4DDisplaySet; + } + + if (!referenceDisplaySet) { + // try to see if there is any derived displaySet in the active viewport + // which is referencing the dynamic 4D display set + + // Todo: this is wrong but I don't have time to fix it now + const cachedDisplaySets = displaySetService.getDisplaySetCache(); + for (const [key, displaySet] of cachedDisplaySets) { + if (displaySet.referenceDisplaySetUID === dynamic4DDisplaySetInstanceUID) { + referenceDisplaySet = displaySet; + break; + } + } + } + + if (!referenceDisplaySet) { + throw new Error('No reference display set found based on the dynamic data'); + } + + const segmentationId = await segmentationService.createSegmentationForDisplaySet( + referenceDisplaySet.displaySetInstanceUID, + { label } + ); + + // Add Segmentation to all toolGroupIds in the viewer + const toolGroupIds = Array.from( + viewports.values(), + viewport => viewport.viewportOptions.toolGroupId + ); + + const representationType = LABELMAP; + + for (const toolGroupId of toolGroupIds) { + const hydrateSegmentation = true; + await segmentationService.addSegmentationRepresentationToToolGroup( + toolGroupId, + segmentationId, + hydrateSegmentation, + representationType + ); + + segmentationService.setActiveSegmentationForToolGroup(segmentationId, toolGroupId); + } + + return segmentationId; + }, + }; + + const definitions = { + updateSegmentationsChartDisplaySet: { + commandFn: actions.updateSegmentationsChartDisplaySet, + storeContexts: [], + options: {}, + }, + exportTimeReportCSV: { + commandFn: actions.exportTimeReportCSV, + storeContexts: [], + options: {}, + }, + swapDynamicWithComputedDisplaySet: { + commandFn: actions.swapDynamicWithComputedDisplaySet, + storeContexts: [], + options: {}, + }, + createNewLabelMapForDynamicVolume: { + commandFn: actions.createNewLabelMapForDynamicVolume, + storeContexts: [], + options: {}, + }, + swapComputedWithDynamicDisplaySet: { + commandFn: actions.swapComputedWithDynamicDisplaySet, + storeContexts: [], + options: {}, + }, + }; + + return { + actions, + definitions, + defaultContext: 'DYNAMIC-VOLUME:CORNERSTONE', + }; +}; + +export default commandsModule; diff --git a/extensions/cornerstone-dynamic-volume/src/getHangingProtocolModule.ts b/extensions/cornerstone-dynamic-volume/src/getHangingProtocolModule.ts new file mode 100644 index 000000000..0a8b6d520 --- /dev/null +++ b/extensions/cornerstone-dynamic-volume/src/getHangingProtocolModule.ts @@ -0,0 +1,654 @@ +const DEFAULT_COLORMAP = '2hot'; +const toolGroupIds = { + pt: 'dynamic4D-pt', + fusion: 'dynamic4D-fusion', + ct: 'dynamic4D-ct', +}; + +function getPTOptions({ + colormap, + voiInverted, +}: { + colormap?: { + name: string; + opacity: + | number + | { + value: number; + opacity: number; + }[]; + }; + voiInverted?: boolean; +} = {}) { + return { + blendMode: 'MIP', + colormap, + voi: { + windowWidth: 5, + windowCenter: 2.5, + }, + voiInverted, + }; +} + +function getPTViewports() { + const ptOptionsParams = { + colormap: { + name: DEFAULT_COLORMAP, + opacity: [ + { value: 0, opacity: 0 }, + { value: 0.1, opacity: 1 }, + { value: 1, opacity: 1 }, + ], + }, + voiInverted: false, + }; + + return [ + { + viewportOptions: { + viewportId: 'ptAxial', + viewportType: 'volume', + orientation: 'axial', + toolGroupId: toolGroupIds.pt, + initialImageOptions: { + preset: 'middle', // 'first', 'last', 'middle' + }, + syncGroups: [ + { + type: 'cameraPosition', + id: 'axialSync', + source: true, + target: true, + }, + { + type: 'voi', + id: 'ptWLSync', + source: true, + target: true, + }, + ], + }, + displaySets: [ + { + id: 'ptDisplaySet', + options: { ...getPTOptions(ptOptionsParams) }, + }, + ], + }, + { + viewportOptions: { + viewportId: 'ptSagittal', + viewportType: 'volume', + orientation: 'sagittal', + toolGroupId: toolGroupIds.pt, + initialImageOptions: { + preset: 'middle', // 'first', 'last', 'middle' + }, + syncGroups: [ + { + type: 'cameraPosition', + id: 'sagittalSync', + source: true, + target: true, + }, + { + type: 'voi', + id: 'ptWLSync', + source: true, + target: true, + }, + ], + }, + displaySets: [ + { + id: 'ptDisplaySet', + options: { ...getPTOptions(ptOptionsParams) }, + }, + ], + }, + { + viewportOptions: { + viewportId: 'ptCoronal', + viewportType: 'volume', + orientation: 'coronal', + toolGroupId: toolGroupIds.pt, + initialImageOptions: { + preset: 'middle', // 'first', 'last', 'middle' + }, + syncGroups: [ + { + type: 'cameraPosition', + id: 'coronalSync', + source: true, + target: true, + }, + { + type: 'voi', + id: 'ptWLSync', + source: true, + target: true, + }, + ], + }, + displaySets: [ + { + id: 'ptDisplaySet', + options: { ...getPTOptions(ptOptionsParams) }, + }, + ], + }, + ]; +} + +function getFusionViewports() { + const ptOptionsParams = { + colormap: { + name: DEFAULT_COLORMAP, + opacity: [ + { value: 0, opacity: 0 }, + { value: 0.1, opacity: 0.3 }, + { value: 1, opacity: 0.3 }, + ], + }, + }; + + return [ + { + viewportOptions: { + viewportId: 'fusionAxial', + viewportType: 'volume', + orientation: 'axial', + toolGroupId: toolGroupIds.fusion, + initialImageOptions: { + preset: 'middle', // 'first', 'last', 'middle' + }, + syncGroups: [ + { + type: 'cameraPosition', + id: 'axialSync', + source: true, + target: true, + }, + { + type: 'voi', + id: 'ctWLSync', + source: false, + target: true, + }, + { + type: 'voi', + id: 'fusionWLSync', + source: true, + target: true, + }, + { + type: 'voi', + id: 'ptFusionWLSync', + source: false, + target: true, + options: { + syncInvertState: false, + }, + }, + ], + }, + displaySets: [ + { + id: 'ctDisplaySet', + }, + { + options: { ...getPTOptions(ptOptionsParams) }, + id: 'ptDisplaySet', + }, + ], + }, + { + viewportOptions: { + viewportId: 'fusionSagittal', + viewportType: 'volume', + orientation: 'sagittal', + toolGroupId: toolGroupIds.fusion, + initialImageOptions: { + preset: 'middle', // 'first', 'last', 'middle' + }, + syncGroups: [ + { + type: 'cameraPosition', + id: 'sagittalSync', + source: true, + target: true, + }, + { + type: 'voi', + id: 'ctWLSync', + source: false, + target: true, + }, + { + type: 'voi', + id: 'fusionWLSync', + source: true, + target: true, + }, + { + type: 'voi', + id: 'ptFusionWLSync', + source: false, + target: true, + options: { + syncInvertState: false, + }, + }, + ], + }, + displaySets: [ + { + id: 'ctDisplaySet', + }, + { + options: { ...getPTOptions(ptOptionsParams) }, + id: 'ptDisplaySet', + }, + ], + }, + { + viewportOptions: { + viewportId: 'fusionCoronal', + viewportType: 'volume', + orientation: 'coronal', + toolGroupId: toolGroupIds.fusion, + initialImageOptions: { + preset: 'middle', // 'first', 'last', 'middle' + }, + syncGroups: [ + { + type: 'cameraPosition', + id: 'coronalSync', + source: true, + target: true, + }, + { + type: 'voi', + id: 'ctWLSync', + source: false, + target: true, + }, + { + type: 'voi', + id: 'fusionWLSync', + source: true, + target: true, + }, + { + type: 'voi', + id: 'ptFusionWLSync', + source: false, + target: true, + options: { + syncInvertState: false, + }, + }, + ], + }, + displaySets: [ + { + id: 'ctDisplaySet', + }, + { + options: { ...getPTOptions(ptOptionsParams) }, + id: 'ptDisplaySet', + }, + ], + }, + ]; +} + +function getSeriesChartViewport() { + return { + viewportOptions: { + viewportId: 'seriesChart', + }, + displaySets: [ + { + id: 'chartDisplaySet', + options: { + // This dataset does not require the download of any instance since it is pre-computed locally, + // but interleaveTopToBottom.ts was not loading any series because it consider that all viewports + // are a Cornerstone viewport which is not true in this case and it waits for all viewports to + // have called interleaveTopToBottom(...). + skipLoading: true, + }, + }, + ], + }; +} + +function getCTViewports() { + return [ + { + viewportOptions: { + viewportId: 'ctAxial', + viewportType: 'volume', + orientation: 'axial', + toolGroupId: toolGroupIds.ct, + initialImageOptions: { + preset: 'middle', // 'first', 'last', 'middle' + }, + syncGroups: [ + { + type: 'cameraPosition', + id: 'axialSync', + source: true, + target: true, + }, + { + type: 'voi', + id: 'ctWLSync', + source: true, + target: true, + }, + ], + }, + displaySets: [ + { + id: 'ctDisplaySet', + }, + ], + }, + { + viewportOptions: { + viewportId: 'ctSagittal', + viewportType: 'volume', + orientation: 'sagittal', + toolGroupId: toolGroupIds.ct, + initialImageOptions: { + preset: 'middle', + }, + syncGroups: [ + { + type: 'cameraPosition', + id: 'sagittalSync', + source: true, + target: true, + }, + { + type: 'voi', + id: 'ctWLSync', + source: true, + target: true, + }, + ], + }, + displaySets: [ + { + id: 'ctDisplaySet', + }, + ], + }, + { + viewportOptions: { + viewportId: 'ctCoronal', + viewportType: 'volume', + orientation: 'coronal', + toolGroupId: toolGroupIds.ct, + initialImageOptions: { + preset: 'middle', + }, + syncGroups: [ + { + type: 'cameraPosition', + id: 'coronalSync', + source: true, + target: true, + }, + { + type: 'voi', + id: 'ctWLSync', + source: true, + target: true, + }, + ], + }, + displaySets: [ + { + id: 'ctDisplaySet', + }, + ], + }, + ]; +} + +const defaultProtocol = { + id: 'default4D', + locked: true, + // Don't store this hanging protocol as it applies to the currently active + // display set by default + // cacheId: null, + hasUpdatedPriorsInformation: false, + name: 'Default', + createdDate: '2023-01-01T00:00:00.000Z', + modifiedDate: '2023-01-01T00:00:00.000Z', + availableTo: {}, + editableBy: {}, + imageLoadStrategy: 'default', // "default" , "interleaveTopToBottom", "interleaveCenter" + protocolMatchingRules: [ + { + attribute: 'ModalitiesInStudy', + constraint: { + contains: ['CT', 'PT'], + }, + }, + ], + // -1 would be used to indicate active only, whereas other values are + // the number of required priors referenced - so 0 means active with + // 0 or more priors. + numberOfPriorsReferenced: -1, + displaySetSelectors: { + defaultDisplaySetId: { + // Unused currently + imageMatchingRules: [], + // Matches displaysets, NOT series + seriesMatchingRules: [ + // Try to match series with images by default, to prevent weird display + // on SEG/SR containing studies + { + attribute: 'numImageFrames', + constraint: { + greaterThan: { value: 0 }, + }, + }, + ], + // Can be used to select matching studies + // studyMatchingRules: [], + }, + ctDisplaySet: { + // Unused currently + imageMatchingRules: [], + // Matches displaysets, NOT series + seriesMatchingRules: [ + { + attribute: 'Modality', + constraint: { + equals: { + value: 'CT', + }, + }, + required: true, + }, + { + attribute: 'isReconstructable', + constraint: { + equals: { + value: true, + }, + }, + required: true, + }, + ], + // Can be used to select matching studies + // studyMatchingRules: [], + }, + ptDisplaySet: { + // Unused currently + imageMatchingRules: [], + // Matches displaysets, NOT series + seriesMatchingRules: [ + { + attribute: 'Modality', + constraint: { + equals: 'PT', + }, + required: true, + }, + { + attribute: 'isReconstructable', + constraint: { + equals: { + value: true, + }, + }, + required: true, + }, + { + attribute: 'SeriesDescription', + constraint: { + contains: 'Corrected', + }, + }, + { + weight: 2, + attribute: 'SeriesDescription', + constraint: { + doesNotContain: { + value: 'Uncorrected', + }, + }, + }, + + // Should we check if CorrectedImage contains ATTN? + // (0028,0051) (CorrectedImage): NORM\DTIM\ATTN\SCAT\RADL\DECY + ], + // Can be used to select matching studies + // studyMatchingRules: [], + }, + chartDisplaySet: { + // Unused currently + imageMatchingRules: [], + // Matches displaysets, NOT series + seriesMatchingRules: [ + { + attribute: 'Modality', + constraint: { + equals: { + value: 'CHT', + }, + }, + required: true, + }, + ], + }, + }, + stages: [ + { + id: 'dataPreparation', + name: 'Data Preparation', + viewportStructure: { + layoutType: 'grid', + properties: { + rows: 1, + columns: 3, + }, + }, + viewports: [...getPTViewports()], + createdDate: '2023-01-01T00:00:00.000Z', + }, + + { + id: 'registration', + name: 'Registration', + viewportStructure: { + layoutType: 'grid', + properties: { + rows: 3, + columns: 3, + }, + }, + viewports: [...getFusionViewports(), ...getCTViewports(), ...getPTViewports()], + createdDate: '2023-01-01T00:00:00.000Z', + }, + + { + id: 'roiQuantification', + name: 'ROI Quantification', + viewportStructure: { + layoutType: 'grid', + properties: { + rows: 1, + columns: 3, + }, + }, + viewports: [...getFusionViewports()], + createdDate: '2023-01-01T00:00:00.000Z', + }, + + { + id: 'kineticAnalysis', + name: 'Kinetic Analysis', + viewportStructure: { + layoutType: 'grid', + properties: { + rows: 2, + columns: 3, + layoutOptions: [ + { + x: 0, + y: 0, + width: 1 / 3, + height: 1 / 2, + }, + { + x: 1 / 3, + y: 0, + width: 1 / 3, + height: 1 / 2, + }, + { + x: 2 / 3, + y: 0, + width: 1 / 3, + height: 1 / 2, + }, + { + x: 0, + y: 1 / 2, + width: 1, + height: 1 / 2, + }, + ], + }, + }, + viewports: [...getFusionViewports(), getSeriesChartViewport()], + createdDate: '2023-01-01T00:00:00.000Z', + }, + ], +}; + +/** + * HangingProtocolModule should provide a list of hanging protocols that will be + * available in OHIF for Modes to use to decide on the structure of the viewports + * and also the series that hung in the viewports. Each hanging protocol is defined by + * { name, protocols}. Examples include the default hanging protocol provided by + * the default extension that shows 2x2 viewports. + */ + +function getHangingProtocolModule() { + return [ + { + name: defaultProtocol.id, + protocol: defaultProtocol, + }, + ]; +} + +export default getHangingProtocolModule; diff --git a/extensions/cornerstone-dynamic-volume/src/getPanelModule.tsx b/extensions/cornerstone-dynamic-volume/src/getPanelModule.tsx new file mode 100644 index 000000000..a32b5243d --- /dev/null +++ b/extensions/cornerstone-dynamic-volume/src/getPanelModule.tsx @@ -0,0 +1,68 @@ +import React from 'react'; +import { DynamicDataPanel } from './panels'; +import { Toolbox } from '@ohif/ui'; +import DynamicExport from './panels/DynamicExport'; + +function getPanelModule({ commandsManager, extensionManager, servicesManager }) { + const wrappedDynamicDataPanel = () => { + return ( + + ); + }; + + const wrappedDynamicToolbox = () => { + return ( + <> + + + ); + }; + + const wrappedDynamicExport = () => { + return ( + <> + + + ); + }; + + return [ + { + name: 'dynamic-volume', + iconName: 'group-layers', + iconLabel: '4D Workflow', + label: '4D Workflow', + component: wrappedDynamicDataPanel, + }, + { + name: 'dynamic-toolbox', + iconName: 'group-layers', + iconLabel: '4D Workflow', + label: 'Dynamic Toolbox', + component: wrappedDynamicToolbox, + }, + { + name: 'dynamic-export', + iconName: 'group-layers', + iconLabel: '4D Workflow', + label: '4D Workflow', + component: wrappedDynamicExport, + }, + ]; +} + +export default getPanelModule; diff --git a/extensions/cornerstone-dynamic-volume/src/id.js b/extensions/cornerstone-dynamic-volume/src/id.js new file mode 100644 index 000000000..b2dfe1809 --- /dev/null +++ b/extensions/cornerstone-dynamic-volume/src/id.js @@ -0,0 +1,6 @@ +import packageJson from '../package.json'; + +const id = packageJson.name; +const SOPClassHandlerName = 'dynamic-volume'; + +export { id, SOPClassHandlerName }; diff --git a/extensions/cornerstone-dynamic-volume/src/index.ts b/extensions/cornerstone-dynamic-volume/src/index.ts new file mode 100644 index 000000000..625899efe --- /dev/null +++ b/extensions/cornerstone-dynamic-volume/src/index.ts @@ -0,0 +1,57 @@ +import { id } from './id'; +import commandsModule from './commandsModule'; +import getPanelModule from './getPanelModule'; +import getHangingProtocolModule from './getHangingProtocolModule'; +import { cache } from '@cornerstonejs/core'; + +/** + * You can remove any of the following modules if you don't need them. + */ +const dynamicVolumeExtension = { + /** + * Only required property. Should be a unique value across all extensions. + * You ID can be anything you want, but it should be unique. + */ + id, + + /** + * Perform any pre-registration tasks here. This is called before the extension + * is registered. Usually we run tasks such as: configuring the libraries + * (e.g. cornerstone, cornerstoneTools, ...) or registering any services that + * this extension is providing. + */ + preRegistration: ({ servicesManager, commandsManager, configuration = {} }) => { + // TODO: look for the right fix + cache.setMaxCacheSize(5 * 1024 * 1024 * 1024); + }, + /** + * PanelModule should provide a list of panels that will be available in OHIF + * for Modes to consume and render. Each panel is defined by a {name, + * iconName, iconLabel, label, component} object. Example of a panel module + * is the StudyBrowserPanel that is provided by the default extension in OHIF. + */ + getPanelModule, + /** + * ViewportModule should provide a list of viewports that will be available in OHIF + * for Modes to consume and use in the viewports. Each viewport is defined by + * {name, component} object. Example of a viewport module is the CornerstoneViewport + * that is provided by the Cornerstone extension in OHIF. + */ + getHangingProtocolModule, + /** + * CommandsModule should provide a list of commands that will be available in OHIF + * for Modes to consume and use in the viewports. Each command is defined by + * an object of { actions, definitions, defaultContext } where actions is an + * object of functions, definitions is an object of available commands, their + * options, and defaultContext is the default context for the command to run against. + */ + getCommandsModule: ({ servicesManager, commandsManager, extensionManager }) => { + return commandsModule({ + servicesManager, + commandsManager, + extensionManager, + }); + }, +}; + +export { dynamicVolumeExtension as default }; diff --git a/extensions/cornerstone-dynamic-volume/src/panels/DynamicDataPanel.tsx b/extensions/cornerstone-dynamic-volume/src/panels/DynamicDataPanel.tsx new file mode 100644 index 000000000..6be93c1d3 --- /dev/null +++ b/extensions/cornerstone-dynamic-volume/src/panels/DynamicDataPanel.tsx @@ -0,0 +1,18 @@ +import React from 'react'; +import PanelGenerateImage from './PanelGenerateImage'; + +function DynamicDataPanel({ servicesManager, commandsManager }) { + return ( +
+ +
+ ); +} + +export default DynamicDataPanel; diff --git a/extensions/cornerstone-dynamic-volume/src/panels/DynamicExport.tsx b/extensions/cornerstone-dynamic-volume/src/panels/DynamicExport.tsx new file mode 100644 index 000000000..020278c4b --- /dev/null +++ b/extensions/cornerstone-dynamic-volume/src/panels/DynamicExport.tsx @@ -0,0 +1,76 @@ +import React, { useState, useEffect } from 'react'; +import { ActionButtons } from '@ohif/ui'; +import { useTranslation } from 'react-i18next'; + +function DynamicExport({ commandsManager, servicesManager, extensionManager }) { + const { segmentationService } = servicesManager.services; + const { t } = useTranslation('dynamicExport'); + + const [segmentations, setSegmentations] = useState(() => segmentationService.getSegmentations()); + + const actions = [ + { + label: 'Export Time Data', + onClick: () => { + commandsManager.runCommand('exportTimeReportCSV', { + segmentations, + options: { + filename: 'TimeData.csv', + }, + }); + }, + disabled: !segmentations?.length, + }, + { + label: 'Export ROI Stats', + onClick: () => { + commandsManager.runCommand('exportTimeReportCSV', { + segmentations, + summaryStats: true, + options: { + filename: 'ROIStats.csv', + }, + }); + }, + disabled: !segmentations?.length, + }, + ]; + + /** + * Update UI based on segmentation changes (added, removed, updated) + */ + useEffect(() => { + // ~~ Subscription + const added = segmentationService.EVENTS.SEGMENTATION_ADDED; + const updated = segmentationService.EVENTS.SEGMENTATION_UPDATED; + const removed = segmentationService.EVENTS.SEGMENTATION_REMOVED; + const subscriptions = []; + + [added, updated, removed].forEach(evt => { + const { unsubscribe } = segmentationService.subscribe(evt, () => { + const segmentations = segmentationService.getSegmentations(); + setSegmentations(segmentations); + }); + subscriptions.push(unsubscribe); + }); + + return () => { + subscriptions.forEach(unsub => { + unsub(); + }); + }; + }, []); + + return ( +
+
+ +
+
+ ); +} + +export default DynamicExport; diff --git a/extensions/cornerstone-dynamic-volume/src/panels/DynamicVolumeControls.tsx b/extensions/cornerstone-dynamic-volume/src/panels/DynamicVolumeControls.tsx new file mode 100644 index 000000000..337e9e0a3 --- /dev/null +++ b/extensions/cornerstone-dynamic-volume/src/panels/DynamicVolumeControls.tsx @@ -0,0 +1,220 @@ +import React, { useEffect, useState } from 'react'; +import { + InputDoubleRange, + Button, + PanelSection, + ButtonGroup, + IconButton, + InputNumber, + Icon, + Tooltip, +} from '@ohif/ui'; + +import { Enums } from '@cornerstonejs/core'; + +const controlClassNames = { + sizeClassName: 'w-[58px] h-[28px]', + arrowsDirection: 'horizontal', + labelPosition: 'bottom', +}; + +const Header = ({ title, tooltip }) => ( +
+ {tooltip}
} + position="bottom" + tight={true} + tooltipBoxClassName="max-w-xs" + > + + + {title} + +); + +const DynamicVolumeControls = ({ + isPlaying, + onPlayPauseChange, + // fps + fps, + onFpsChange, + minFps, + maxFps, + // Frames + currentFrameIndex, + onFrameChange, + framesLength, + onGenerate, + onDoubleRangeChange, + onDynamicClick, +}) => { + const [computedView, setComputedView] = useState(false); + + const [computeViewMode, setComputeViewMode] = useState(Enums.DynamicOperatorType.SUM); + + const [sliderRangeValues, setSliderRangeValues] = useState([framesLength / 4, framesLength / 2]); + + useEffect(() => { + setSliderRangeValues([framesLength / 4, framesLength / 2]); + }, [framesLength]); + + const handleSliderChange = newValues => { + onDoubleRangeChange(newValues); + + if (newValues[0] === sliderRangeValues[0] && newValues[1] === sliderRangeValues[1]) { + return; + } + setSliderRangeValues(newValues); + }; + + return ( +
+ +
+
+ + + + +
+
+ +
+
+
+ + + + + +
+ +
+ +
+
+
+ ); +}; + +export default DynamicVolumeControls; + +function FrameControls({ + isPlaying, + onPlayPauseChange, + fps, + minFps, + maxFps, + onFpsChange, + framesLength, + onFrameChange, + currentFrameIndex, + computedView, +}) { + const getPlayPauseIconName = () => (isPlaying ? 'icon-pause' : 'icon-play'); + + return ( +
+
+
+ onPlayPauseChange(!isPlaying)} + > + + + + +
+
+ ); +} diff --git a/extensions/cornerstone-dynamic-volume/src/panels/GenerateVolume.tsx b/extensions/cornerstone-dynamic-volume/src/panels/GenerateVolume.tsx new file mode 100644 index 000000000..516502a67 --- /dev/null +++ b/extensions/cornerstone-dynamic-volume/src/panels/GenerateVolume.tsx @@ -0,0 +1,71 @@ +import React from 'react'; +import { InputDoubleRange } from '@ohif/ui'; +import { Select } from '@ohif/ui'; +import { Button } from '@ohif/ui'; +import PropTypes from 'prop-types'; + +const GenerateVolume = ({ + rangeValues, + handleSliderChange, + operationsUI, + options, + handleGenerateOptionsChange, + onGenerateImage, + returnTo4D, + displayingComputedVolume, +}) => { + return ( + <> +
+
Computed Image
+ { - event.persist(); - setValue(value => ({ ...value, label: event.target.value })); - }} - onKeyPress={event => { - if (event.key === 'Enter') { - onSubmitHandler({ value, action: { id: 'save' } }); - } - }} - /> - ); - }, - }, - }); - } -} - -export default callInputDialog; diff --git a/extensions/tmtv/src/Panels/PanelROIThresholdSegmentation/colorPickerDialog.css b/extensions/tmtv/src/Panels/PanelROIThresholdSegmentation/colorPickerDialog.css deleted file mode 100644 index 1c6bb2067..000000000 --- a/extensions/tmtv/src/Panels/PanelROIThresholdSegmentation/colorPickerDialog.css +++ /dev/null @@ -1,3 +0,0 @@ -.chrome-picker { - background: #090c29 !important; -} diff --git a/extensions/tmtv/src/Panels/PanelROIThresholdSegmentation/colorPickerDialog.tsx b/extensions/tmtv/src/Panels/PanelROIThresholdSegmentation/colorPickerDialog.tsx deleted file mode 100644 index 38e85efb2..000000000 --- a/extensions/tmtv/src/Panels/PanelROIThresholdSegmentation/colorPickerDialog.tsx +++ /dev/null @@ -1,58 +0,0 @@ -import React from 'react'; -import { Dialog } from '@ohif/ui'; -import { ChromePicker } from 'react-color'; - -import './colorPickerDialog.css'; - -function callColorPickerDialog(uiDialogService, rgbaColor, callback) { - const dialogId = 'pick-color'; - - const onSubmitHandler = ({ action, value }) => { - switch (action.id) { - case 'save': - callback(value.rgbaColor, action.id); - break; - case 'cancel': - callback('', action.id); - break; - } - uiDialogService.dismiss({ id: dialogId }); - }; - - if (uiDialogService) { - uiDialogService.create({ - id: dialogId, - centralize: true, - isDraggable: false, - showOverlay: true, - content: Dialog, - contentProps: { - title: 'Segment Color', - value: { rgbaColor }, - noCloseButton: true, - onClose: () => uiDialogService.dismiss({ id: dialogId }), - actions: [ - { id: 'cancel', text: 'Cancel', type: 'primary' }, - { id: 'save', text: 'Save', type: 'secondary' }, - ], - onSubmit: onSubmitHandler, - body: ({ value, setValue }) => { - const handleChange = color => { - setValue({ rgbaColor: color.rgb }); - }; - - return ( - - ); - }, - }, - }); - } -} - -export default callColorPickerDialog; diff --git a/extensions/tmtv/src/Panels/PanelROIThresholdSegmentation/index.ts b/extensions/tmtv/src/Panels/PanelROIThresholdSegmentation/index.ts index 22404ee98..01ce5d64e 100644 --- a/extensions/tmtv/src/Panels/PanelROIThresholdSegmentation/index.ts +++ b/extensions/tmtv/src/Panels/PanelROIThresholdSegmentation/index.ts @@ -1,3 +1,3 @@ -import PanelROIThresholdSegmentation from './PanelROIThresholdSegmentation'; +import PanelROIThresholdExport from './PanelROIThresholdExport'; -export default PanelROIThresholdSegmentation; +export default PanelROIThresholdExport; diff --git a/extensions/tmtv/src/Panels/index.tsx b/extensions/tmtv/src/Panels/index.tsx index 0fa6418fd..255c923f4 100644 --- a/extensions/tmtv/src/Panels/index.tsx +++ b/extensions/tmtv/src/Panels/index.tsx @@ -1,4 +1,4 @@ import PanelPetSUV from './PanelPetSUV'; -import PanelROIThresholdSegmentation from './PanelROIThresholdSegmentation'; +import PanelROIThresholdExport from './PanelROIThresholdSegmentation'; -export { PanelPetSUV, PanelROIThresholdSegmentation }; +export { PanelPetSUV, PanelROIThresholdExport }; diff --git a/extensions/tmtv/src/commandsModule.js b/extensions/tmtv/src/commandsModule.js index 765ab7f5b..0898a01a8 100644 --- a/extensions/tmtv/src/commandsModule.js +++ b/extensions/tmtv/src/commandsModule.js @@ -11,7 +11,10 @@ import createAndDownloadTMTVReport from './utils/createAndDownloadTMTVReport'; import dicomRTAnnotationExport from './utils/dicomRTAnnotationExport/RTStructureSet'; const metadataProvider = classes.MetadataProvider; -const RECTANGLE_ROI_THRESHOLD_MANUAL = 'RectangleROIStartEndThreshold'; +const RECTANGLE_ROI_THRESHOLD_MANUAL_TOOL_IDS = [ + 'RectangleROIStartEndThreshold', + 'RectangleROIThreshold', +]; const LABELMAP = csTools.Enums.SegmentationRepresentations.Labelmap; const commandsModule = ({ servicesManager, commandsManager, extensionManager }) => { @@ -52,6 +55,15 @@ const commandsModule = ({ servicesManager, commandsManager, extensionManager }) return toolGroupIds; } + function _getAnnotationsSelectedByToolNames(toolNames) { + return toolNames.reduce((allAnnotationUIDs, toolName) => { + const annotationUIDs = + csTools.annotation.selection.getAnnotationsSelectedByToolName(toolName); + + return allAnnotationUIDs.concat(annotationUIDs); + }, []); + } + const actions = { getMatchingPTDisplaySet: ({ viewportMatchDetails }) => { // Todo: this is assuming that the hanging protocol has successfully matched @@ -108,7 +120,7 @@ const commandsModule = ({ servicesManager, commandsManager, extensionManager }) return metadata; }, - createNewLabelmapFromPT: async () => { + createNewLabelmapFromPT: async ({ label }) => { // Create a segmentation of the same resolution as the source data // using volumeLoader.createAndCacheDerivedVolume. const { viewportMatchDetails } = hangingProtocolService.getMatchDetails(); @@ -173,20 +185,8 @@ const commandsModule = ({ servicesManager, commandsManager, extensionManager }) const { volumeId: segVolumeId } = representationData[LABELMAP]; const { referencedVolumeId } = cs.cache.getVolume(segVolumeId); - const labelmapVolume = cs.cache.getVolume(segmentationId); - const referencedVolume = cs.cache.getVolume(referencedVolumeId); - const ctReferencedVolume = cs.cache.getVolume(ctVolumeId); - - if (!referencedVolume) { - throw new Error('No Reference volume found'); - } - - if (!labelmapVolume) { - throw new Error('No Reference labelmap found'); - } - - const annotationUIDs = csTools.annotation.selection.getAnnotationsSelectedByToolName( - RECTANGLE_ROI_THRESHOLD_MANUAL + const annotationUIDs = _getAnnotationsSelectedByToolNames( + RECTANGLE_ROI_THRESHOLD_MANUAL_TOOL_IDS ); if (annotationUIDs.length === 0) { @@ -198,6 +198,57 @@ const commandsModule = ({ servicesManager, commandsManager, extensionManager }) return; } + const labelmapVolume = cs.cache.getVolume(segmentationId); + let referencedVolume = cs.cache.getVolume(referencedVolumeId); + const ctReferencedVolume = cs.cache.getVolume(ctVolumeId); + + // check if viewport is + + if (!referencedVolume) { + throw new Error('No Reference volume found'); + } + + if (!labelmapVolume) { + throw new Error('No Reference labelmap found'); + } + + const annotation = csTools.annotation.state.getAnnotation(annotationUIDs[0]); + + const { + metadata: { + enabledElement: { viewport }, + }, + } = annotation; + + const showingReferenceVolume = viewport.hasVolumeId(referencedVolumeId); + + if (!showingReferenceVolume) { + // if the reference volume is not being displayed, we can't + // rely on it for thresholding, we have couple of options here + // 1. We choose whatever volume is being displayed + // 2. We check if it is a fusion viewport, we pick the volume + // that matches the size and dimensions of the labelmap. This might + // happen if the 4D PT is converted to a computed volume and displayed + // and wants to threshold the labelmap + // 3. We throw an error + const displaySetInstanceUIDs = viewportGridService.getDisplaySetsUIDsForViewport( + viewport.id + ); + + displaySetInstanceUIDs.forEach(displaySetInstanceUID => { + const volume = cs.cache + .getVolumes() + .find(volume => volume.volumeId.includes(displaySetInstanceUID)); + + if ( + cs.utilities.isEqual(volume.dimensions, labelmapVolume.dimensions) && + cs.utilities.isEqual(volume.spacing, labelmapVolume.spacing) + ) { + referencedVolume = volume; + } + }); + } + const { ptLower, ptUpper, ctLower, ctUpper } = getThresholdValues( annotationUIDs, [referencedVolume, ctReferencedVolume], @@ -218,8 +269,8 @@ const commandsModule = ({ servicesManager, commandsManager, extensionManager }) const { referencedVolumeId } = labelmap; const referencedVolume = cs.cache.getVolume(referencedVolumeId); - const annotationUIDs = csTools.annotation.selection.getAnnotationsSelectedByToolName( - RECTANGLE_ROI_THRESHOLD_MANUAL + const annotationUIDs = _getAnnotationsSelectedByToolNames( + RECTANGLE_ROI_THRESHOLD_MANUAL_TOOL_IDS ); const annotations = annotationUIDs.map(annotationUID => @@ -236,8 +287,7 @@ const commandsModule = ({ servicesManager, commandsManager, extensionManager }) }, getLesionStats: ({ labelmap, segmentIndex = 1 }) => { const { scalarData, spacing } = labelmap; - - const { scalarData: referencedScalarData } = cs.cache.getVolume(labelmap.referencedVolumeId); + const referencedScalarData = cs.cache.getVolume(labelmap.referencedVolumeId).getScalarData(); let segmentationMax = -Infinity; let segmentationMin = Infinity; @@ -287,19 +337,25 @@ const commandsModule = ({ servicesManager, commandsManager, extensionManager }) return calculateTMTV(labelmaps); }, - exportTMTVReportCSV: ({ segmentations, tmtv, config }) => { + exportTMTVReportCSV: ({ segmentations, tmtv, config, options }) => { const segReport = commandsManager.runCommand('getSegmentationCSVReport', { segmentations, }); const tlg = actions.getTotalLesionGlycolysis({ segmentations }); const additionalReportRows = [ - { key: 'Total Metabolic Tumor Volume', value: { tmtv } }, { key: 'Total Lesion Glycolysis', value: { tlg: tlg.toFixed(4) } }, { key: 'Threshold Configuration', value: { ...config } }, ]; - createAndDownloadTMTVReport(segReport, additionalReportRows); + if (tmtv !== undefined) { + additionalReportRows.unshift({ + key: 'Total Metabolic Tumor Volume', + value: { tmtv }, + }); + } + + createAndDownloadTMTVReport(segReport, additionalReportRows, options); }, getTotalLesionGlycolysis: ({ segmentations }) => { const labelmapVolumes = segmentations.map(s => segmentationService.getLabelmapVolume(s.id)); @@ -323,9 +379,9 @@ const commandsModule = ({ servicesManager, commandsManager, extensionManager }) } const ptVolume = cs.cache.getVolume(referencedVolumeId); - const mergedLabelData = mergedLabelmap.scalarData; + const mergedLabelData = mergedLabelmap.getScalarData(); - if (mergedLabelData.length !== ptVolume.scalarData.length) { + if (mergedLabelData.length !== ptVolume.getScalarData().length) { console.error( 'commandsModule::getTotalLesionGlycolysis:Labelmap and ptVolume are not the same size' ); @@ -336,7 +392,7 @@ const commandsModule = ({ servicesManager, commandsManager, extensionManager }) for (let i = 0; i < mergedLabelData.length; i++) { // if not background if (mergedLabelData[i] !== 0) { - suv += ptVolume.scalarData[i]; + suv += ptVolume.getScalarData()[i]; totalLesionVoxelCount += 1; } } @@ -351,8 +407,8 @@ const commandsModule = ({ servicesManager, commandsManager, extensionManager }) const { viewport } = _getActiveViewportsEnabledElement(); const { focalPoint, viewPlaneNormal } = viewport.getCamera(); - const selectedAnnotationUIDs = csTools.annotation.selection.getAnnotationsSelectedByToolName( - RECTANGLE_ROI_THRESHOLD_MANUAL + const selectedAnnotationUIDs = _getAnnotationsSelectedByToolNames( + RECTANGLE_ROI_THRESHOLD_MANUAL_TOOL_IDS ); const annotationUID = selectedAnnotationUIDs[0]; @@ -389,8 +445,8 @@ const commandsModule = ({ servicesManager, commandsManager, extensionManager }) setEndSliceForROIThresholdTool: () => { const { viewport } = _getActiveViewportsEnabledElement(); - const selectedAnnotationUIDs = csTools.annotation.selection.getAnnotationsSelectedByToolName( - RECTANGLE_ROI_THRESHOLD_MANUAL + const selectedAnnotationUIDs = _getAnnotationsSelectedByToolNames( + RECTANGLE_ROI_THRESHOLD_MANUAL_TOOL_IDS ); const annotationUID = selectedAnnotationUIDs[0]; @@ -415,7 +471,11 @@ const commandsModule = ({ servicesManager, commandsManager, extensionManager }) Object.keys(stateManager.annotations).forEach(frameOfReferenceUID => { const forAnnotations = stateManager.annotations[frameOfReferenceUID]; - const ROIAnnotations = forAnnotations[RECTANGLE_ROI_THRESHOLD_MANUAL]; + const ROIAnnotations = RECTANGLE_ROI_THRESHOLD_MANUAL_TOOL_IDS.reduce( + (annotations, toolName) => [...annotations, ...(forAnnotations[toolName] ?? [])], + [] + ); + annotations.push(...ROIAnnotations); }); @@ -483,7 +543,7 @@ const commandsModule = ({ servicesManager, commandsManager, extensionManager }) report[id] = { ...segReport, - PatientID: instance.PatientID, + PatientID: instance.PatientID ?? '000000', PatientName: instance.PatientName.Alphabetic, StudyInstanceUID: instance.StudyInstanceUID, SeriesInstanceUID: instance.SeriesInstanceUID, diff --git a/extensions/tmtv/src/getPanelModule.tsx b/extensions/tmtv/src/getPanelModule.tsx index 39a955df3..239233978 100644 --- a/extensions/tmtv/src/getPanelModule.tsx +++ b/extensions/tmtv/src/getPanelModule.tsx @@ -1,5 +1,5 @@ import React from 'react'; -import { PanelPetSUV, PanelROIThresholdSegmentation } from './Panels'; +import { PanelPetSUV, PanelROIThresholdExport } from './Panels'; import { Toolbox } from '@ohif/ui'; // TODO: @@ -17,20 +17,26 @@ function getPanelModule({ commandsManager, extensionManager, servicesManager }) ); }; - const wrappedROIThresholdSeg = () => { + const wrappedROIThresholdToolbox = () => { return ( <> - + ); + }; + + const wrappedROIThresholdExport = () => { + return ( + <> + ); @@ -45,11 +51,18 @@ function getPanelModule({ commandsManager, extensionManager, servicesManager }) component: wrappedPanelPetSuv, }, { - name: 'ROIThresholdSeg', + name: 'tmtvBox', iconName: 'tab-segmentation', iconLabel: 'Segmentation', - label: 'Segmentation', - component: wrappedROIThresholdSeg, + label: 'Segmentation Toolbox', + component: wrappedROIThresholdToolbox, + }, + { + name: 'tmtvExport', + iconName: 'tab-segmentation', + iconLabel: 'Segmentation', + label: 'Segmentation Export', + component: wrappedROIThresholdExport, }, ]; } diff --git a/extensions/tmtv/src/utils/calculateSUVPeak.ts b/extensions/tmtv/src/utils/calculateSUVPeak.ts index 302300f5b..6627d2e2b 100644 --- a/extensions/tmtv/src/utils/calculateSUVPeak.ts +++ b/extensions/tmtv/src/utils/calculateSUVPeak.ts @@ -40,17 +40,19 @@ function calculateSuvPeak( return; } - if (labelmap.scalarData.length !== referenceVolume.scalarData.length) { + const labelmapData = labelmap.getScalarData(); + const referenceVolumeData = referenceVolume.getScalarData(); + + if (labelmapData.length !== referenceVolumeData.length) { throw new Error('labelmap and referenceVolume must have the same number of pixels'); } - const { scalarData: labelmapData, dimensions, imageData: labelmapImageData } = labelmap; - - const { scalarData: referenceVolumeData, imageData: referenceVolumeImageData } = referenceVolume; + const { dimensions, imageData: labelmapImageData } = labelmap; + const { imageData: referenceVolumeImageData } = referenceVolume; let boundsIJK; // Todo: using the first annotation for now - if (annotations && annotations[0].data?.cachedStats) { + if (annotations?.length && annotations[0].data?.cachedStats) { const { projectionPoints } = annotations[0].data.cachedStats; const pointsToUse = [].concat(...projectionPoints); // cannot use flat() because of typescript compiler right now diff --git a/extensions/tmtv/src/utils/createAndDownloadTMTVReport.js b/extensions/tmtv/src/utils/createAndDownloadTMTVReport.js index b36787293..615d384fe 100644 --- a/extensions/tmtv/src/utils/createAndDownloadTMTVReport.js +++ b/extensions/tmtv/src/utils/createAndDownloadTMTVReport.js @@ -1,4 +1,4 @@ -export default function createAndDownloadTMTVReport(segReport, additionalReportRows) { +export default function createAndDownloadTMTVReport(segReport, additionalReportRows, options = {}) { const firstReport = segReport[Object.keys(segReport)[0]]; const columns = Object.keys(firstReport); const csv = [columns.join(',')]; @@ -40,6 +40,6 @@ export default function createAndDownloadTMTVReport(segReport, additionalReportR const a = document.createElement('a'); a.href = url; - a.download = `${firstReport.PatientID}_tmtv.csv`; + a.download = options.filename ?? `${firstReport.PatientID}_tmtv.csv`; a.click(); } diff --git a/modes/basic-test-mode/src/index.ts b/modes/basic-test-mode/src/index.ts index 155fc7013..52dc5ebc1 100644 --- a/modes/basic-test-mode/src/index.ts +++ b/modes/basic-test-mode/src/index.ts @@ -136,7 +136,7 @@ function modeFactory() { props: { leftPanels: [tracked.thumbnailList], rightPanels: [dicomSeg.panel, tracked.measurements], - // rightPanelDefaultClosed: true, // optional prop to start with collapse panels + // rightPanelClosed: true, // optional prop to start with collapse panels viewports: [ { namespace: tracked.viewport, diff --git a/modes/basic-test-mode/src/moreTools.ts b/modes/basic-test-mode/src/moreTools.ts index 1369bc629..5f49e08ad 100644 --- a/modes/basic-test-mode/src/moreTools.ts +++ b/modes/basic-test-mode/src/moreTools.ts @@ -11,6 +11,13 @@ const ReferenceLinesListeners: RunCommand = [ }, ]; +export const toggleEnabledDisabledToolbar = { + commandName: 'toggleEnabledDisabledToolbar', + commandOptions: { + toolGroupIds: ['default', 'mpr', 'SRToolGroup', 'volume3d'], + }, +}; + const moreTools = [ { id: 'MoreTools', @@ -80,13 +87,7 @@ const moreTools = [ icon: 'tool-referenceLines', label: 'Reference Lines', tooltip: 'Show Reference Lines', - commands: { - commandName: 'setToolEnabled', - commandOptions: { - toolName: 'ReferenceLines', - toggle: true, - }, - }, + commands: toggleEnabledDisabledToolbar, listeners: { [ViewportGridService.EVENTS.ACTIVE_VIEWPORT_ID_CHANGED]: ReferenceLinesListeners, [ViewportGridService.EVENTS.VIEWPORTS_READY]: ReferenceLinesListeners, @@ -94,17 +95,11 @@ const moreTools = [ evaluate: 'evaluate.cornerstoneTool.toggle', }), createButton({ - id: 'ImageOverlay', + id: 'ImageOverlayViewer', icon: 'toggle-dicom-overlay', label: 'Image Overlay', tooltip: 'Toggle Image Overlay', - commands: { - commandName: 'setToolEnabled', - commandOptions: { - toolName: 'ImageOverlayViewer', - toggle: true, - }, - }, + commands: toggleEnabledDisabledToolbar, evaluate: 'evaluate.cornerstoneTool.toggle', }), createButton({ diff --git a/modes/longitudinal/src/index.js b/modes/longitudinal/src/index.js index 6925384fb..bfa6792ca 100644 --- a/modes/longitudinal/src/index.js +++ b/modes/longitudinal/src/index.js @@ -108,8 +108,8 @@ function modeFactory({ modeConfiguration }) { customizationService.addModeCustomizations([ { - id: 'segmentation.disableEditing', - value: true, + id: 'segmentation.panel', + disableEditing: true, }, ]); @@ -183,7 +183,7 @@ function modeFactory({ modeConfiguration }) { props: { leftPanels: [tracked.thumbnailList], rightPanels: [dicomSeg.panel, tracked.measurements], - rightPanelDefaultClosed: true, + rightPanelClosed: true, viewports: [ { namespace: tracked.viewport, diff --git a/modes/longitudinal/src/initToolGroups.js b/modes/longitudinal/src/initToolGroups.js index d1dfe3324..f5bae8d86 100644 --- a/modes/longitudinal/src/initToolGroups.js +++ b/modes/longitudinal/src/initToolGroups.js @@ -64,7 +64,12 @@ function initDefaultToolGroup( { toolName: toolNames.Magnify }, { toolName: toolNames.SegmentationDisplay }, { toolName: toolNames.CalibrationLine }, - { toolName: toolNames.AdvancedMagnify }, + { + toolName: toolNames.AdvancedMagnify, + configuration: { + disableOnPassive: true, + }, + }, { toolName: toolNames.UltrasoundDirectional }, { toolName: toolNames.PlanarFreehandROI }, { toolName: toolNames.SplineROI }, diff --git a/modes/longitudinal/src/moreTools.ts b/modes/longitudinal/src/moreTools.ts index f9b1189c6..267114f73 100644 --- a/modes/longitudinal/src/moreTools.ts +++ b/modes/longitudinal/src/moreTools.ts @@ -11,6 +11,20 @@ const ReferenceLinesListeners: RunCommand = [ }, ]; +export const toggleEnabledDisabledToolbar = { + commandName: 'toggleEnabledDisabledToolbar', + commandOptions: { + toolGroupIds: ['default', 'mpr', 'SRToolGroup', 'volume3d'], + }, +}; + +export const toggleActiveDisabledToolbar = { + commandName: 'toggleActiveDisabledToolbar', + commandOptions: { + toolGroupIds: ['default', 'mpr', 'SRToolGroup'], + }, +}; + const moreTools = [ { id: 'MoreTools', @@ -80,13 +94,7 @@ const moreTools = [ icon: 'tool-referenceLines', label: 'Reference Lines', tooltip: 'Show Reference Lines', - commands: { - commandName: 'setToolEnabled', - commandOptions: { - toolName: 'ReferenceLines', - toggle: true, // Toggle the tool on/off upon click - }, - }, + commands: toggleEnabledDisabledToolbar, listeners: { [ViewportGridService.EVENTS.ACTIVE_VIEWPORT_ID_CHANGED]: ReferenceLinesListeners, [ViewportGridService.EVENTS.VIEWPORTS_READY]: ReferenceLinesListeners, @@ -94,17 +102,11 @@ const moreTools = [ evaluate: 'evaluate.cornerstoneTool.toggle', }), createButton({ - id: 'ImageOverlay', + id: 'ImageOverlayViewer', icon: 'toggle-dicom-overlay', label: 'Image Overlay', tooltip: 'Toggle Image Overlay', - commands: { - commandName: 'setToolEnabled', - commandOptions: { - toolName: 'ImageOverlayViewer', - toggle: true, // Toggle the tool on/off upon click - }, - }, + commands: toggleEnabledDisabledToolbar, evaluate: 'evaluate.cornerstoneTool.toggle', }), createButton({ @@ -175,8 +177,8 @@ const moreTools = [ icon: 'icon-tool-loupe', label: 'Loupe', tooltip: 'Loupe', - commands: setToolActiveToolbar, - evaluate: 'evaluate.cornerstoneTool', + commands: toggleActiveDisabledToolbar, + evaluate: 'evaluate.cornerstoneTool.toggle', }), createButton({ id: 'UltrasoundDirectionalTool', diff --git a/modes/longitudinal/src/toolbarButtons.ts b/modes/longitudinal/src/toolbarButtons.ts index 7abe57f2c..dc5700fe6 100644 --- a/modes/longitudinal/src/toolbarButtons.ts +++ b/modes/longitudinal/src/toolbarButtons.ts @@ -1,10 +1,8 @@ // TODO: torn, can either bake this here; or have to create a whole new button type // Only ways that you can pass in a custom React component for render :l -import { WindowLevelMenuItem } from '@ohif/ui'; import { defaults, ToolbarService } from '@ohif/core'; import type { Button } from '@ohif/core/types'; -const { windowLevelPresets } = defaults; const { createButton } = ToolbarService; export const setToolActiveToolbar = { diff --git a/modes/microscopy/src/index.tsx b/modes/microscopy/src/index.tsx index e7d30d396..5c0bdba80 100644 --- a/modes/microscopy/src/index.tsx +++ b/modes/microscopy/src/index.tsx @@ -87,8 +87,8 @@ function modeFactory({ modeConfiguration }) { id: ohif.layout, props: { leftPanels: [ohif.leftPanel], - leftPanelDefaultClosed: true, // we have problem with rendering thumbnails for microscopy images - rightPanelDefaultClosed: true, // we do not have the save microscopy measurements yet + leftPanelClosed: true, // we have problem with rendering thumbnails for microscopy images + rightPanelClosed: true, // we do not have the save microscopy measurements yet rightPanels: ['@ohif/extension-dicom-microscopy.panelModule.measure'], viewports: [ { diff --git a/modes/preclinical-4d/.webpack/webpack.dev.js b/modes/preclinical-4d/.webpack/webpack.dev.js new file mode 100644 index 000000000..6aea859ca --- /dev/null +++ b/modes/preclinical-4d/.webpack/webpack.dev.js @@ -0,0 +1,12 @@ +const path = require('path'); +const webpackCommon = require('./../../../.webpack/webpack.base.js'); +const SRC_DIR = path.join(__dirname, '../src'); +const DIST_DIR = path.join(__dirname, '../dist'); + +const ENTRY = { + app: `${SRC_DIR}/index.tsx`, +}; + +module.exports = (env, argv) => { + return webpackCommon(env, argv, { SRC_DIR, DIST_DIR, ENTRY }); +}; diff --git a/modes/preclinical-4d/.webpack/webpack.prod.js b/modes/preclinical-4d/.webpack/webpack.prod.js new file mode 100644 index 000000000..f8b0a79f8 --- /dev/null +++ b/modes/preclinical-4d/.webpack/webpack.prod.js @@ -0,0 +1,53 @@ +const webpack = require('webpack'); +const { merge } = require('webpack-merge'); +const path = require('path'); +const MiniCssExtractPlugin = require('mini-css-extract-plugin'); + +const pkg = require('./../package.json'); +const webpackCommon = require('./../../../.webpack/webpack.base.js'); + +const ROOT_DIR = path.join(__dirname, './../'); +const SRC_DIR = path.join(__dirname, '../src'); +const DIST_DIR = path.join(__dirname, '../dist'); +const ENTRY = { + app: `${SRC_DIR}/index.tsx`, +}; + +module.exports = (env, argv) => { + const commonConfig = webpackCommon(env, argv, { SRC_DIR, DIST_DIR, ENTRY }); + + return merge(commonConfig, { + stats: { + colors: true, + hash: true, + timings: true, + assets: true, + chunks: false, + chunkModules: false, + modules: false, + children: false, + warnings: true, + }, + optimization: { + minimize: true, + sideEffects: false, + }, + output: { + path: ROOT_DIR, + library: 'ohif-mode-preclinical-4d', + libraryTarget: 'umd', + libraryExport: 'default', + filename: pkg.main, + }, + externals: [/\b(vtk.js)/, /\b(dcmjs)/, /\b(gl-matrix)/, /^@ohif/, /^@cornerstonejs/], + plugins: [ + new webpack.optimize.LimitChunkCountPlugin({ + maxChunks: 1, + }), + // new MiniCssExtractPlugin({ + // filename: './dist/[name].css', + // chunkFilename: './dist/[id].css', + // }), + ], + }); +}; diff --git a/modes/preclinical-4d/LICENSE b/modes/preclinical-4d/LICENSE new file mode 100644 index 000000000..5f35ab7d8 --- /dev/null +++ b/modes/preclinical-4d/LICENSE @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) 2023 4d () + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/modes/preclinical-4d/README.md b/modes/preclinical-4d/README.md new file mode 100644 index 000000000..0f6870d2f --- /dev/null +++ b/modes/preclinical-4d/README.md @@ -0,0 +1,7 @@ +# 4d +## Description + +## Author +OHIF +## License +MIT \ No newline at end of file diff --git a/modes/preclinical-4d/babel.config.js b/modes/preclinical-4d/babel.config.js new file mode 100644 index 000000000..a38ddda21 --- /dev/null +++ b/modes/preclinical-4d/babel.config.js @@ -0,0 +1,44 @@ +module.exports = { + plugins: ['inline-react-svg', '@babel/plugin-proposal-class-properties'], + env: { + test: { + presets: [ + [ + // TODO: https://babeljs.io/blog/2019/03/19/7.4.0#migration-from-core-js-2 + '@babel/preset-env', + { + modules: 'commonjs', + debug: false, + }, + '@babel/preset-typescript', + ], + '@babel/preset-react', + ], + plugins: [ + '@babel/plugin-proposal-object-rest-spread', + '@babel/plugin-syntax-dynamic-import', + '@babel/plugin-transform-regenerator', + '@babel/plugin-transform-runtime', + ], + }, + production: { + presets: [ + // WebPack handles ES6 --> Target Syntax + ['@babel/preset-env', { modules: false }], + '@babel/preset-react', + '@babel/preset-typescript', + ], + ignore: ['**/*.test.jsx', '**/*.test.js', '__snapshots__', '__tests__'], + }, + development: { + presets: [ + // WebPack handles ES6 --> Target Syntax + ['@babel/preset-env', { modules: false }], + '@babel/preset-react', + '@babel/preset-typescript', + ], + plugins: ['react-hot-loader/babel'], + ignore: ['**/*.test.jsx', '**/*.test.js', '__snapshots__', '__tests__'], + }, + }, +}; diff --git a/modes/preclinical-4d/package.json b/modes/preclinical-4d/package.json new file mode 100644 index 000000000..37f66ca9e --- /dev/null +++ b/modes/preclinical-4d/package.json @@ -0,0 +1,47 @@ +{ + "name": "@ohif/mode-preclinical-4d", + "version": "3.7.0-beta.76", + "description": "4D Workflow", + "author": "OHIF", + "license": "MIT", + "repository": "OHIF/Viewers", + "main": "dist/index.umd.js", + "module": "src/index.tsx", + "engines": { + "node": ">=14", + "npm": ">=6", + "yarn": ">=1.16.0" + }, + "files": [ + "dist/**", + "public/**", + "README.md" + ], + "keywords": [ + "ohif-mode" + ], + "scripts": { + "dev": "cross-env NODE_ENV=development webpack --config .webpack/webpack.dev.js --watch --debug --output-pathinfo", + "dev:cornerstone": "yarn run dev", + "build": "cross-env NODE_ENV=production webpack --config .webpack/webpack.prod.js", + "build:package": "yarn run build", + "start": "yarn run dev", + "test:unit": "jest --watchAll", + "test:unit:ci": "jest --ci --runInBand --collectCoverage --passWithNoTests" + }, + "peerDependencies": { + "@ohif/core": "3.7.0-beta.76", + "@ohif/extension-default": "3.7.0-beta.76", + "@ohif/extension-cornerstone": "3.7.0-beta.76", + "@ohif/extension-cornerstone-dynamic-volume": "3.7.0-beta.76", + "@ohif/extension-cornerstone-dicom-seg": "3.7.0-beta.76", + "@ohif/extension-tmtv": "3.7.0-beta.76" + }, + "dependencies": { + "@babel/runtime": "^7.20.13" + }, + "devDependencies": { + "webpack": "^5.50.0", + "webpack-merge": "^5.7.3" + } +} diff --git a/modes/preclinical-4d/src/getWorkflowSettings.ts b/modes/preclinical-4d/src/getWorkflowSettings.ts new file mode 100644 index 000000000..efaab9b1f --- /dev/null +++ b/modes/preclinical-4d/src/getWorkflowSettings.ts @@ -0,0 +1,104 @@ +const dynamicVolume = { + sopClassHandler: + '@ohif/extension-cornerstone-dynamic-volume.sopClassHandlerModule.dynamic-volume', + leftPanel: '@ohif/extension-cornerstone-dynamic-volume.panelModule.dynamic-volume', + toolBox: '@ohif/extension-cornerstone-dynamic-volume.panelModule.dynamic-toolbox', + export: '@ohif/extension-cornerstone-dynamic-volume.panelModule.dynamic-export', +}; + +const cornerstone = { + segmentation: '@ohif/extension-cornerstone-dicom-seg.panelModule.panelSegmentation', + activeViewportWindowLevel: '@ohif/extension-cornerstone.panelModule.activeViewportWindowLevel', +}; + +const defaultButtons = { + buttonSection: 'primary', + buttons: ['MeasurementTools', 'Zoom', 'WindowLevel', 'Crosshairs', 'Pan'], +}; + +const defaultLeftPanel = [[dynamicVolume.leftPanel, cornerstone.activeViewportWindowLevel]]; + +const defaultLayout = { + panels: { + left: defaultLeftPanel, + right: [], + }, +}; + +function getWorkflowSettings({ servicesManager }) { + return { + steps: [ + { + id: 'dataPreparation', + name: 'Data Preparation', + layout: { + panels: { + left: defaultLeftPanel, + }, + }, + toolbarButtons: defaultButtons, + hangingProtocol: { + protocolId: 'default4D', + stageId: 'dataPreparation', + }, + info: 'In the Data Preparation step, you can visualize the dynamic PT volume data in three orthogonal views: axial, sagittal, and coronal. Use the left panel controls to adjust the visualization settings, such as playback speed, or navigate between different frames. This step allows you to assess the quality of the PT data and prepare for further analysis or registration with other modalities.', + }, + { + id: 'registration', + name: 'Registration', + layout: defaultLayout, + toolbarButtons: defaultButtons, + hangingProtocol: { + protocolId: 'default4D', + stageId: 'registration', + }, + info: 'The Registration step provides a comprehensive view of the CT, PT, and fused CT-PT volume data in multiple orientations. The fusion viewports display the CT and PT volumes overlaid, allowing you to visually assess the alignment and registration between the two modalities. The individual CT and PT viewports are also available for side-by-side comparison. This step is crucial for ensuring proper registration before proceeding with further analysis or quantification.', + }, + { + id: 'roiQuantification', + name: 'ROI Quantification', + layout: { + panels: { + left: defaultLeftPanel, + right: [[dynamicVolume.toolBox, cornerstone.segmentation, dynamicVolume.export]], + }, + options: { + leftPanelClosed: false, + rightPanelClosed: false, + }, + }, + toolbarButtons: [ + defaultButtons, + { + buttonSection: 'dynamic-toolbox', + buttons: ['BrushTools', 'RectangleROIStartEndThreshold'], + }, + ], + hangingProtocol: { + protocolId: 'default4D', + stageId: 'roiQuantification', + }, + info: 'The ROI quantification step allows you to define regions of interest (ROIs) with labelmap segmentations, on the fused CT-PT volume data using the labelmap tools. The left panel provides controls for adjusting the dynamic volume visualization, while the right panel offers tools for segmentation, editing, and exporting the ROI data. This step enables you to quantify the uptake or other measures within the defined ROIs for further analysis.', + }, + { + id: 'kineticAnalysis', + name: 'Kinetic Analysis', + layout: defaultLayout, + toolbarButtons: defaultButtons, + hangingProtocol: { + protocolId: 'default4D', + stageId: 'kineticAnalysis', + }, + onEnter: [ + { + commandName: 'updateSegmentationsChartDisplaySet', + options: { servicesManager }, + }, + ], + info: 'The Kinetic Analysis step provides a comprehensive view for visualizing and analyzing the dynamic data derived from the ROI segmentations. The fusion viewports display the combined CT-PT volume data, while a dedicated viewport shows a series chart representing the data over time. This step allows you to explore the temporal dynamics of the uptake or other kinetic measures within the defined regions of interest, enabling further quantitative analysis and modeling.', + }, + ], + }; +} + +export { getWorkflowSettings as default }; diff --git a/modes/preclinical-4d/src/id.js b/modes/preclinical-4d/src/id.js new file mode 100644 index 000000000..ebe5acd98 --- /dev/null +++ b/modes/preclinical-4d/src/id.js @@ -0,0 +1,5 @@ +import packageJson from '../package.json'; + +const id = packageJson.name; + +export { id }; diff --git a/modes/preclinical-4d/src/index.tsx b/modes/preclinical-4d/src/index.tsx new file mode 100644 index 000000000..c74fb985c --- /dev/null +++ b/modes/preclinical-4d/src/index.tsx @@ -0,0 +1,176 @@ +import { id } from './id'; +import { hotkeys } from '@ohif/core'; +import initWorkflowSteps from './initWorkflowSteps'; +import initToolGroups from './initToolGroups'; +import toolbarButtons from './toolbarButtons'; +import segmentationButtons from './segmentationButtons'; + +const extensionDependencies = { + '@ohif/extension-default': '3.7.0-beta.76', + '@ohif/extension-cornerstone': '3.7.0-beta.76', + '@ohif/extension-cornerstone-dynamic-volume': '3.7.0-beta.76', + '@ohif/extension-cornerstone-dicom-seg': '3.7.0-beta.76', + '@ohif/extension-tmtv': '3.7.0-beta.76', +}; + +const ohif = { + layout: '@ohif/extension-default.layoutTemplateModule.viewerLayout', + defaultSopClassHandler: '@ohif/extension-default.sopClassHandlerModule.stack', + chartSopClassHandler: '@ohif/extension-default.sopClassHandlerModule.chart', + hangingProtocol: '@ohif/extension-default.hangingProtocolModule.default', + leftPanel: '@ohif/extension-default.panelModule.seriesList', + rightPanel: '@ohif/extension-default.panelModule.measure', + chartViewport: '@ohif/extension-default.viewportModule.chartViewport', +}; + +const dynamicVolume = { + leftPanel: '@ohif/extension-cornerstone-dynamic-volume.panelModule.dynamic-volume', +}; + +const cornerstone = { + viewport: '@ohif/extension-cornerstone.viewportModule.cornerstone', + activeViewportWindowLevel: '@ohif/extension-cornerstone.panelModule.activeViewportWindowLevel', +}; + +function modeFactory({ modeConfiguration }) { + return { + id, + routeName: 'dynamic-volume', + displayName: '4D PT/CT', + onModeEnter: function ({ servicesManager, extensionManager, commandsManager }) { + const { + measurementService, + toolbarService, + cineService, + cornerstoneViewportService, + toolGroupService, + customizationService, + viewportGridService, + } = servicesManager.services; + + const utilityModule = extensionManager.getModuleEntry( + '@ohif/extension-cornerstone.utilityModule.tools' + ); + + const { toolNames, Enums } = utilityModule.exports; + + measurementService.clearMeasurements(); + initToolGroups({ toolNames, Enums, toolGroupService, commandsManager }); + + toolbarService.addButtons([...toolbarButtons, ...segmentationButtons]); + toolbarService.createButtonSection('secondary', ['ProgressDropdown']); + + // the primary button section is created in the workflow steps + // specific to the step + customizationService.addModeCustomizations([ + { + id: 'segmentation.panel', + segmentationPanelMode: 'expanded', + addSegment: false, + onSegmentationAdd: () => { + commandsManager.run('createNewLabelmapFromPT'); + }, + }, + ]); + + // Auto play the clip initially when the volumes are loaded + const { unsubscribe } = cornerstoneViewportService.subscribe( + cornerstoneViewportService.EVENTS.VIEWPORT_VOLUMES_CHANGED, + () => { + const viewportId = viewportGridService.getActiveViewportId(); + const csViewport = cornerstoneViewportService.getCornerstoneViewport(viewportId); + cineService.playClip(csViewport.element); + // cineService.setIsCineEnabled(true); + + unsubscribe(); + } + ); + }, + onSetupRouteComplete: ({ servicesManager }) => { + // This needs to run after hanging protocol matching process because + // it may change the protocol/stage based on workflow stage settings + initWorkflowSteps({ servicesManager }); + }, + onModeExit: ({ servicesManager }) => { + const { + toolGroupService, + syncGroupService, + segmentationService, + cornerstoneViewportService, + } = servicesManager.services; + + toolGroupService.destroy(); + syncGroupService.destroy(); + segmentationService.destroy(); + cornerstoneViewportService.destroy(); + }, + get validationTags() { + return { + study: [], + series: [], + }; + }, + isValidMode: ({ modalities, study }) => { + // Todo: we need to find a better way to validate the mode + return { + valid: study.mrn === 'M1', + description: 'This mode is only available for 4D PET/CT studies.', + }; + }, + + /** + * Mode Routes are used to define the mode's behavior. A list of Mode Route + * that includes the mode's path and the layout to be used. The layout will + * include the components that are used in the layout. For instance, if the + * default layoutTemplate is used (id: '@ohif/extension-default.layoutTemplateModule.viewerLayout') + * it will include the leftPanels, rightPanels, and viewports. However, if + * you define another layoutTemplate that includes a Footer for instance, + * you should provide the Footer component here too. Note: We use Strings + * to reference the component's ID as they are registered in the internal + * ExtensionManager. The template for the string is: + * `${extensionId}.{moduleType}.${componentId}`. + */ + routes: [ + { + path: 'preclinical-4d', + layoutTemplate: ({ location, servicesManager }) => { + return { + id: ohif.layout, + props: { + leftPanels: [[dynamicVolume.leftPanel, cornerstone.activeViewportWindowLevel]], + rightPanels: [], + rightPanelClosed: true, + viewports: [ + { + namespace: cornerstone.viewport, + displaySetsToDisplay: [ohif.defaultSopClassHandler], + }, + { + namespace: ohif.chartViewport, + displaySetsToDisplay: [ohif.chartSopClassHandler], + }, + ], + }, + }; + }, + }, + ], + extensions: extensionDependencies, + // Default protocol gets self-registered by default in the init + hangingProtocol: 'default4D', + // Order is important in sop class handlers when two handlers both use + // the same sop class under different situations. In that case, the more + // general handler needs to come last. For this case, the dicomvideo must + // come first to remove video transfer syntax before ohif uses images + sopClassHandlers: [ohif.chartSopClassHandler, ohif.defaultSopClassHandler], + hotkeys: [...hotkeys.defaults.hotkeyBindings], + }; +} + +const mode = { + id, + modeFactory, + extensionDependencies, +}; + +export default mode; diff --git a/modes/preclinical-4d/src/initToolGroups.tsx b/modes/preclinical-4d/src/initToolGroups.tsx new file mode 100644 index 000000000..9a6457618 --- /dev/null +++ b/modes/preclinical-4d/src/initToolGroups.tsx @@ -0,0 +1,130 @@ +const toolGroupIds = { + default: 'dynamic4D-default', + PT: 'dynamic4D-pt', + Fusion: 'dynamic4D-fusion', + CT: 'dynamic4D-ct', +}; + +function _initToolGroups(toolNames, Enums, toolGroupService, commandsManager) { + const tools = { + active: [ + { + toolName: toolNames.WindowLevel, + bindings: [{ mouseButton: Enums.MouseBindings.Primary }], + }, + { + toolName: toolNames.Pan, + bindings: [{ mouseButton: Enums.MouseBindings.Auxiliary }], + }, + { + toolName: toolNames.Zoom, + bindings: [{ mouseButton: Enums.MouseBindings.Secondary }], + }, + { toolName: toolNames.StackScrollMouseWheel, bindings: [] }, + ], + passive: [ + { toolName: toolNames.Length }, + { toolName: toolNames.ArrowAnnotate }, + { toolName: toolNames.Bidirectional }, + { toolName: toolNames.Probe }, + { toolName: toolNames.EllipticalROI }, + { toolName: toolNames.RectangleROI }, + { toolName: toolNames.RectangleROIThreshold }, + { toolName: toolNames.RectangleScissors }, + { toolName: toolNames.PaintFill }, + { toolName: toolNames.StackScroll }, + { toolName: toolNames.Magnify }, + { + toolName: 'CircularBrush', + parentTool: 'Brush', + configuration: { + activeStrategy: 'FILL_INSIDE_CIRCLE', + brushSize: 7, + }, + }, + { + toolName: 'CircularEraser', + parentTool: 'Brush', + configuration: { + activeStrategy: 'ERASE_INSIDE_CIRCLE', + brushSize: 7, + }, + }, + { + toolName: 'SphereBrush', + parentTool: 'Brush', + configuration: { + activeStrategy: 'FILL_INSIDE_SPHERE', + brushSize: 7, + }, + }, + { + toolName: 'SphereEraser', + parentTool: 'Brush', + configuration: { + activeStrategy: 'ERASE_INSIDE_SPHERE', + brushSize: 7, + }, + }, + { + toolName: 'ThresholdCircularBrush', + parentTool: 'Brush', + configuration: { + activeStrategy: 'THRESHOLD_INSIDE_CIRCLE', + brushSize: 7, + }, + }, + { + toolName: 'ThresholdSphereBrush', + parentTool: 'Brush', + configuration: { + activeStrategy: 'THRESHOLD_INSIDE_SPHERE', + brushSize: 7, + }, + }, + { toolName: toolNames.CircleScissors }, + { toolName: toolNames.RectangleScissors }, + { toolName: toolNames.SphereScissors }, + { toolName: toolNames.StackScroll }, + { toolName: toolNames.Magnify }, + { toolName: toolNames.SegmentationDisplay }, + ], + enabled: [{ toolName: toolNames.SegmentationDisplay }], + disabled: [ + { + toolName: toolNames.Crosshairs, + configuration: { + viewportIndicators: false, + disableOnPassive: true, + autoPan: { + enabled: false, + panSize: 10, + }, + }, + }, + ], + }; + + toolGroupService.createToolGroupAndAddTools(toolGroupIds.PT, { + ...tools, + passive: [...tools.passive, { toolName: 'RectangleROIStartEndThreshold' }], + }); + + toolGroupService.createToolGroupAndAddTools(toolGroupIds.CT, { + ...tools, + passive: [...tools.passive, { toolName: 'RectangleROIStartEndThreshold' }], + }); + + toolGroupService.createToolGroupAndAddTools(toolGroupIds.Fusion, { + ...tools, + passive: [...tools.passive, { toolName: 'RectangleROIStartEndThreshold' }], + }); + + toolGroupService.createToolGroupAndAddTools(toolGroupIds.default, tools); +} + +function initToolGroups({ toolNames, Enums, toolGroupService, commandsManager }) { + _initToolGroups(toolNames, Enums, toolGroupService, commandsManager); +} + +export { initToolGroups as default, toolGroupIds }; diff --git a/modes/preclinical-4d/src/initWorkflowSteps.ts b/modes/preclinical-4d/src/initWorkflowSteps.ts new file mode 100644 index 000000000..8b36fe48d --- /dev/null +++ b/modes/preclinical-4d/src/initWorkflowSteps.ts @@ -0,0 +1,9 @@ +import getWorkflowSettings from './getWorkflowSettings'; + +export default function initWorkflowSteps({ servicesManager }): void { + const { workflowStepsService } = servicesManager.services; + const workflowSettings = getWorkflowSettings({ servicesManager }); + + workflowStepsService.addWorkflowSteps(workflowSettings.steps); + workflowStepsService.setActiveWorkflowStep(workflowSettings.steps[0].id); +} diff --git a/modes/preclinical-4d/src/segmentationButtons.ts b/modes/preclinical-4d/src/segmentationButtons.ts new file mode 100644 index 000000000..b4efbe04d --- /dev/null +++ b/modes/preclinical-4d/src/segmentationButtons.ts @@ -0,0 +1,180 @@ +import type { Button } from '@ohif/core/types'; + +function _createSetToolActiveCommands(toolName) { + return [ + { + commandName: 'setToolActive', + commandOptions: { + toolName, + }, + }, + ]; +} + +const toolbarButtons: Button[] = [ + { + id: 'BrushTools', + uiType: 'ohif.buttonGroup', + props: { + groupId: 'BrushTools', + items: [ + { + id: 'Brush', + icon: 'icon-tool-brush', + label: 'Brush', + evaluate: { + name: 'evaluate.cornerstone.segmentation', + options: { toolNames: ['CircularBrush', 'SphereBrush'] }, + }, + commands: _createSetToolActiveCommands('CircularBrush'), + options: [ + { + name: 'Radius (mm)', + id: 'brush-radius', + type: 'range', + min: 0.5, + max: 99.5, + step: 0.5, + value: 7, + commands: { + commandName: 'setBrushSize', + commandOptions: { toolNames: ['CircularBrush', 'SphereBrush'] }, + }, + }, + { + name: 'Shape', + type: 'radio', + id: 'brush-mode', + value: 'CircularBrush', + values: [ + { value: 'CircularBrush', label: 'Circle' }, + { value: 'SphereBrush', label: 'Sphere' }, + ], + commands: 'setToolActiveToolbar', + }, + ], + }, + { + id: 'Eraser', + icon: 'icon-tool-eraser', + label: 'Eraser', + evaluate: { + name: 'evaluate.cornerstone.segmentation', + options: { + toolNames: ['CircularEraser', 'SphereEraser'], + }, + }, + commands: _createSetToolActiveCommands('CircularEraser'), + options: [ + { + name: 'Radius (mm)', + id: 'eraser-radius', + type: 'range', + min: 0.5, + max: 99.5, + step: 0.5, + value: 7, + commands: { + commandName: 'setBrushSize', + commandOptions: { toolNames: ['CircularEraser', 'SphereEraser'] }, + }, + }, + { + name: 'Shape', + type: 'radio', + id: 'eraser-mode', + value: 'CircularEraser', + values: [ + { value: 'CircularEraser', label: 'Circle' }, + { value: 'SphereEraser', label: 'Sphere' }, + ], + commands: 'setToolActiveToolbar', + }, + ], + }, + { + id: 'Threshold', + icon: 'icon-tool-threshold', + label: 'Eraser', + evaluate: { + name: 'evaluate.cornerstone.segmentation', + options: { toolNames: ['ThresholdCircularBrush', 'ThresholdSphereBrush'] }, + }, + commands: _createSetToolActiveCommands('ThresholdCircularBrush'), + options: [ + { + name: 'Radius (mm)', + id: 'threshold-radius', + type: 'range', + min: 0.5, + max: 99.5, + step: 0.5, + value: 7, + commands: { + commandName: 'setBrushSize', + commandOptions: { + toolNames: ['ThresholdCircularBrush', 'ThresholdSphereBrush'], + }, + }, + }, + { + name: 'Shape', + type: 'radio', + id: 'eraser-mode', + value: 'ThresholdCircularBrush', + values: [ + { value: 'ThresholdCircularBrush', label: 'Circle' }, + { value: 'ThresholdSphereBrush', label: 'Sphere' }, + ], + commands: 'setToolActiveToolbar', + }, + { + name: 'ThresholdRange', + type: 'double-range', + id: 'threshold-range', + min: 0, + max: 10, + step: 1, + values: [2, 5], + commands: { + commandName: 'setThresholdRange', + commandOptions: { + toolNames: ['ThresholdCircularBrush', 'ThresholdSphereBrush'], + }, + }, + }, + ], + }, + ], + }, + }, + { + id: 'Shapes', + uiType: 'ohif.radioGroup', + props: { + label: 'Shapes', + evaluate: { + name: 'evaluate.cornerstone.segmentation', + options: { toolNames: ['CircleScissor', 'SphereScissor', 'RectangleScissor'] }, + }, + icon: 'icon-tool-shape', + commands: _createSetToolActiveCommands('CircleScissor'), + options: [ + { + name: 'Shape', + type: 'radio', + value: 'CircleScissor', + id: 'shape-mode', + values: [ + { value: 'CircleScissor', label: 'Circle' }, + { value: 'SphereScissor', label: 'Sphere' }, + { value: 'RectangleScissor', label: 'Rectangle' }, + ], + commands: 'setToolActiveToolbar', + }, + ], + }, + }, +]; + +export default toolbarButtons; diff --git a/modes/preclinical-4d/src/toolbarButtons.tsx b/modes/preclinical-4d/src/toolbarButtons.tsx new file mode 100644 index 000000000..3c6fc47b5 --- /dev/null +++ b/modes/preclinical-4d/src/toolbarButtons.tsx @@ -0,0 +1,160 @@ +import { defaults, ToolbarService } from '@ohif/core'; +import { toolGroupIds } from './initToolGroups'; + +const { createButton } = ToolbarService; + +const setToolActiveToolbar = { + commandName: 'setToolActiveToolbar', + commandOptions: { + toolGroupIds: [toolGroupIds.PT, toolGroupIds.CT, toolGroupIds.Fusion, toolGroupIds.default], + }, +}; + +const toolbarButtons = [ + { + id: 'MeasurementTools', + uiType: 'ohif.splitButton', + props: { + groupId: 'MeasurementTools', + evaluate: 'evaluate.group.promoteToPrimaryIfCornerstoneToolNotActiveInTheList', + primary: createButton({ + id: 'Length', + icon: 'tool-length', + label: 'Length', + tooltip: 'Length Tool', + commands: setToolActiveToolbar, + evaluate: 'evaluate.cornerstoneTool', + }), + secondary: { + icon: 'chevron-down', + tooltip: 'More Measure Tools', + }, + items: [ + { + id: 'Length', + icon: 'tool-length', + label: 'Length', + tooltip: 'Length Tool', + commands: setToolActiveToolbar, + evaluate: 'evaluate.cornerstoneTool', + }, + { + id: 'Bidirectional', + icon: 'tool-bidirectional', + label: 'Bidirectional', + tooltip: 'Bidirectional Tool', + commands: setToolActiveToolbar, + evaluate: 'evaluate.cornerstoneTool', + }, + { + id: 'ArrowAnnotate', + icon: 'tool-annotate', + label: 'Annotation', + tooltip: 'Arrow Annotate', + commands: setToolActiveToolbar, + evaluate: 'evaluate.cornerstoneTool', + }, + { + id: 'EllipticalROI', + icon: 'tool-ellipse', + label: 'Ellipse', + tooltip: 'Ellipse ROI', + commands: setToolActiveToolbar, + evaluate: 'evaluate.cornerstoneTool', + }, + ], + }, + }, + { + id: 'Zoom', + uiType: 'ohif.radioGroup', + props: { + icon: 'tool-zoom', + label: 'Zoom', + commands: setToolActiveToolbar, + evaluate: 'evaluate.cornerstoneTool', + }, + }, + { + id: 'WindowLevel', + uiType: 'ohif.radioGroup', + props: { + icon: 'tool-window-level', + label: 'Window Level', + commands: setToolActiveToolbar, + evaluate: 'evaluate.cornerstoneTool', + }, + }, + { + id: 'Pan', + uiType: 'ohif.radioGroup', + props: { + type: 'tool', + icon: 'tool-move', + label: 'Pan', + commands: setToolActiveToolbar, + evaluate: 'evaluate.cornerstoneTool', + }, + }, + { + id: 'TrackballRotate', + uiType: 'ohif.radioGroup', + props: { + type: 'tool', + icon: 'tool-3d-rotate', + label: '3D Rotate', + commands: setToolActiveToolbar, + evaluate: 'evaluate.cornerstoneTool', + }, + }, + { + id: 'Capture', + uiType: 'ohif.radioGroup', + props: { + icon: 'tool-capture', + label: 'Capture', + commands: 'showDownloadViewportModal', + evaluate: 'evaluate.action', + }, + }, + { + id: 'Layout', + uiType: 'ohif.layoutSelector', + props: { + rows: 3, + columns: 4, + evaluate: 'evaluate.action', + }, + }, + { + id: 'Crosshairs', + uiType: 'ohif.radioGroup', + props: { + type: 'tool', + icon: 'tool-crosshair', + label: 'Crosshairs', + commands: setToolActiveToolbar, + evaluate: 'evaluate.cornerstoneTool', + }, + }, + { + id: 'ProgressDropdown', + uiType: 'ohif.progressDropdown', + }, + { + id: 'RectangleROIStartEndThreshold', + uiType: 'ohif.radioGroup', + props: { + icon: 'tool-create-threshold', + label: 'Rectangle ROI Threshold', + commands: setToolActiveToolbar, + evaluate: { + name: 'evaluate.cornerstone.segmentation', + toolNames: ['RectangleROIStartEndThreshold'], + }, + options: 'tmtv.RectangleROIThresholdOptions', + }, + }, +]; + +export default toolbarButtons; diff --git a/modes/segmentation/src/toolbarButtons.ts b/modes/segmentation/src/toolbarButtons.ts index 5232312cc..58e12eca8 100644 --- a/modes/segmentation/src/toolbarButtons.ts +++ b/modes/segmentation/src/toolbarButtons.ts @@ -1,8 +1,6 @@ import type { Button } from '@ohif/core/types'; import { defaults, ToolbarService, ViewportGridService } from '@ohif/core'; -import { WindowLevelMenuItem } from '@ohif/ui'; -const { windowLevelPresets } = defaults; const { createButton } = ToolbarService; const ReferenceLinesListeners: RunCommand = [ @@ -12,23 +10,6 @@ const ReferenceLinesListeners: RunCommand = [ }, ]; -function _createWwwcPreset(preset, title, subtitle) { - return { - id: preset.toString(), - title, - subtitle, - commands: [ - { - commandName: 'setWindowLevel', - commandOptions: { - ...windowLevelPresets[preset], - }, - context: 'CORNERSTONE', - }, - ], - }; -} - export const setToolActiveToolbar = { commandName: 'setToolActiveToolbar', commandOptions: { @@ -36,6 +17,20 @@ export const setToolActiveToolbar = { }, }; +export const toggleEnabledDisabledToolbar = { + commandName: 'toggleEnabledDisabledToolbar', + commandOptions: { + toolGroupIds: ['default', 'mpr', 'SRToolGroup'], + }, +}; + +export const toggleActiveDisabledToolbar = { + commandName: 'toggleActiveDisabledToolbar', + commandOptions: { + toolGroupIds: ['default', 'mpr', 'SRToolGroup'], + }, +}; + const toolbarButtons: Button[] = [ { id: 'Zoom', @@ -168,13 +163,7 @@ const toolbarButtons: Button[] = [ icon: 'tool-referenceLines', label: 'Reference Lines', tooltip: 'Show Reference Lines', - commands: { - commandName: 'setToolEnabled', - commandOptions: { - toolName: 'ReferenceLines', - toggle: true, // Toggle the tool on/off upon click - }, - }, + commands: toggleEnabledDisabledToolbar, listeners: { [ViewportGridService.EVENTS.ACTIVE_VIEWPORT_ID_CHANGED]: ReferenceLinesListeners, [ViewportGridService.EVENTS.VIEWPORTS_READY]: ReferenceLinesListeners, @@ -182,17 +171,11 @@ const toolbarButtons: Button[] = [ evaluate: 'evaluate.cornerstoneTool.toggle', }), createButton({ - id: 'ImageOverlay', + id: 'ImageOverlayViewer', icon: 'toggle-dicom-overlay', label: 'Image Overlay', tooltip: 'Toggle Image Overlay', - commands: { - commandName: 'setToolEnabled', - commandOptions: { - toolName: 'ImageOverlayViewer', - toggle: true, // Toggle the tool on/off upon click - }, - }, + commands: toggleEnabledDisabledToolbar, evaluate: 'evaluate.cornerstoneTool.toggle', }), createButton({ @@ -271,7 +254,7 @@ const toolbarButtons: Button[] = [ icon: 'icon-tool-loupe', label: 'Loupe', tooltip: 'Loupe', - commands: setToolActiveToolbar, + commands: toggleActiveDisabledToolbar, evaluate: 'evaluate.cornerstoneTool', }), createButton({ diff --git a/modes/tmtv/src/index.js b/modes/tmtv/src/index.js index 6f4fb65f5..491294220 100644 --- a/modes/tmtv/src/index.js +++ b/modes/tmtv/src/index.js @@ -17,18 +17,21 @@ const ohif = { const cs3d = { viewport: '@ohif/extension-cornerstone.viewportModule.cornerstone', + segPanel: '@ohif/extension-cornerstone-dicom-seg.panelModule.panelSegmentation', }; const tmtv = { hangingProtocol: '@ohif/extension-tmtv.hangingProtocolModule.ptCT', petSUV: '@ohif/extension-tmtv.panelModule.petSUV', - ROIThresholdPanel: '@ohif/extension-tmtv.panelModule.ROIThresholdSeg', + toolbox: '@ohif/extension-tmtv.panelModule.tmtvBox', + export: '@ohif/extension-tmtv.panelModule.tmtvExport', }; const extensionDependencies = { // Can derive the versions at least process.env.from npm_package_version '@ohif/extension-default': '^3.0.0', '@ohif/extension-cornerstone': '^3.0.0', + '@ohif/extension-cornerstone-dicom-seg': '^3.0.0', '@ohif/extension-tmtv': '^3.0.0', }; @@ -47,6 +50,7 @@ function modeFactory({ modeConfiguration }) { const { toolbarService, toolGroupService, + customizationService, hangingProtocolService, displaySetService, } = servicesManager.services; @@ -94,7 +98,18 @@ function modeFactory({ modeConfiguration }) { 'Pan', 'SyncToggle', ]); - toolbarService.createButtonSection('tmtvToolbox', ['RectangleROIStartEndThreshold']); + toolbarService.createButtonSection('ROIThresholdToolbox', ['RectangleROIStartEndThreshold']); + + customizationService.addModeCustomizations([ + { + id: 'segmentation.panel', + segmentationPanelMode: 'expanded', + addSegment: false, + onSegmentationAdd: () => { + commandsManager.run('createNewLabelmapFromPT'); + }, + }, + ]); // For the hanging protocol we need to decide on the window level // based on whether the SUV is corrected or not, hence we can't hard @@ -176,13 +191,13 @@ function modeFactory({ modeConfiguration }) { /*init: ({ servicesManager, extensionManager }) => { //defaultViewerRouteInit },*/ - layoutTemplate: ({ location, servicesManager }) => { + layoutTemplate: () => { return { id: ohif.layout, props: { leftPanels: [ohif.thumbnailList], - leftPanelDefaultClosed: true, - rightPanels: [tmtv.ROIThresholdPanel, tmtv.petSUV], + leftPanelClosed: true, + rightPanels: [[tmtv.toolbox, cs3d.segPanel, tmtv.export], tmtv.petSUV], viewports: [ { namespace: cs3d.viewport, diff --git a/package.json b/package.json index 81b792ec6..1c82d2442 100644 --- a/package.json +++ b/package.json @@ -33,6 +33,7 @@ "dev:no:cache": "lerna run dev:no:cache --stream", "dev:project": ".scripts/dev.sh", "dev:orthanc": "lerna run dev:orthanc --stream", + "dev:orthanc:no:cache": "lerna run dev:orthanc:no:cache --stream", "dev:dcm4chee": "lerna run dev:dcm4chee --stream", "dev:static": "lerna run dev:static --stream", "orthanc:up": "docker-compose -f platform/app/.recipes/OpenResty-Orthanc/docker-compose.yml up", @@ -59,7 +60,7 @@ }, "dependencies": { "@babel/runtime": "^7.20.13", - "@kitware/vtk.js": "29.7.0", + "@kitware/vtk.js": "30.3.1", "core-js": "^3.2.1" }, "peerDependencies": { diff --git a/platform/app/cypress/integration/measurement-tracking/OHIFCornerstoneToolbar.spec.js b/platform/app/cypress/integration/measurement-tracking/OHIFCornerstoneToolbar.spec.js index 595cfd3dd..444ed5a09 100644 --- a/platform/app/cypress/integration/measurement-tracking/OHIFCornerstoneToolbar.spec.js +++ b/platform/app/cypress/integration/measurement-tracking/OHIFCornerstoneToolbar.spec.js @@ -110,7 +110,8 @@ describe('OHIF Cornerstone Toolbar', () => { //Click on button and verify if icon is active on toolbar cy.addLengthMeasurement(); cy.get('[data-cy="viewport-notification"]').as('notif').should('exist'); - cy.get('[data-cy="viewport-notification"]').as('notif').should('be.visible'); + // cy.get('[data-cy="viewport-notification"]').as('notif').should('be.visible'); + cy.get('[data-cy="prompt-begin-tracking-yes-btn"]').as('yesBtn').click(); //Verify the measurement exists in the table diff --git a/platform/app/cypress/integration/study-list/OHIFStudyList.spec.js b/platform/app/cypress/integration/study-list/OHIFStudyList.spec.js index d1c32e088..e59df25cf 100644 --- a/platform/app/cypress/integration/study-list/OHIFStudyList.spec.js +++ b/platform/app/cypress/integration/study-list/OHIFStudyList.spec.js @@ -122,6 +122,8 @@ describe('OHIF Study List', function () { '[data-cy="mode-basic-test-1.3.6.1.4.1.25403.345050719074.3824.20170125113417.1"]' ).click(); cy.get('[data-cy="return-to-work-list"]').click(); + + cy.wait(1000); cy.get('@searchResult2').should($list => { expect($list.length).to.be.eq(1); expect($list).to.contain('PETCT'); diff --git a/platform/app/package.json b/platform/app/package.json index 499ba4b8c..fbf5e5503 100644 --- a/platform/app/package.json +++ b/platform/app/package.json @@ -30,6 +30,7 @@ "dev": "cross-env NODE_ENV=development webpack serve --config .webpack/webpack.pwa.js", "dev:no:cache": "cross-env NODE_ENV=development webpack serve --no-cache --config .webpack/webpack.pwa.js", "dev:orthanc": "cross-env NODE_ENV=development PROXY_TARGET=/dicom-web PROXY_DOMAIN=http://localhost:8042 APP_CONFIG=config/docker_nginx-orthanc.js webpack serve --config .webpack/webpack.pwa.js", + "dev:orthanc:no:cache": "cross-env NODE_ENV=development PROXY_TARGET=/dicom-web PROXY_DOMAIN=http://localhost:8042 APP_CONFIG=config/docker_nginx-orthanc.js webpack serve --no-cache --config .webpack/webpack.pwa.js", "dev:dcm4chee": "cross-env NODE_ENV=development APP_CONFIG=config/local_dcm4chee.js webpack serve --config .webpack/webpack.pwa.js", "dev:static": "cross-env NODE_ENV=development APP_CONFIG=config/local_static.js webpack serve --config .webpack/webpack.pwa.js", "dev:viewer": "yarn run dev", @@ -53,7 +54,7 @@ "@cornerstonejs/codec-libjpeg-turbo-8bit": "^1.2.2", "@cornerstonejs/codec-openjpeg": "^1.2.2", "@cornerstonejs/codec-openjph": "^2.4.5", - "@cornerstonejs/dicom-image-loader": "^1.68.1", + "@cornerstonejs/dicom-image-loader": "^1.70.0", "@emotion/serialize": "^1.1.3", "@ohif/core": "3.8.0-beta.73", "@ohif/extension-cornerstone": "3.8.0-beta.73", @@ -98,7 +99,7 @@ "devDependencies": { "@babel/plugin-proposal-private-methods": "^7.18.6", "@percy/cypress": "^3.1.1", - "cypress": "13.6.2", + "cypress": "13.7.2", "cypress-file-upload": "^3.5.3", "glob": "^8.0.3", "identity-obj-proxy": "3.0.x", diff --git a/platform/app/pluginConfig.json b/platform/app/pluginConfig.json index 08a42deb0..a910bee9f 100644 --- a/platform/app/pluginConfig.json +++ b/platform/app/pluginConfig.json @@ -22,6 +22,11 @@ "default": false, "version": "3.0.0" }, + { + "packageName": "@ohif/extension-cornerstone-dynamic-volume", + "default": false, + "version": "3.0.0" + }, { "packageName": "@ohif/extension-dicom-microscopy", "default": false, @@ -66,6 +71,9 @@ { "packageName": "@ohif/mode-microscopy" }, + { + "packageName": "@ohif/mode-preclinical-4d" + }, { "packageName": "@ohif/mode-test", "default": false, diff --git a/platform/app/public/config/local_orthanc.js b/platform/app/public/config/local_orthanc.js index f8ae80c86..9fd18992c 100644 --- a/platform/app/public/config/local_orthanc.js +++ b/platform/app/public/config/local_orthanc.js @@ -29,6 +29,7 @@ window.config = { imageRendering: 'wadors', thumbnailRendering: 'wadors', enableStudyLazyLoad: true, + useBulkDataURI: false, supportsFuzzyMatching: true, supportsWildcard: true, dicomUploadEnabled: true, diff --git a/platform/app/src/appInit.js b/platform/app/src/appInit.js index 867534bd2..4e26eee21 100644 --- a/platform/app/src/appInit.js +++ b/platform/app/src/appInit.js @@ -19,6 +19,7 @@ import { errorHandler, CustomizationService, PanelService, + WorkflowStepsService, // utils, } from '@ohif/core'; @@ -68,6 +69,7 @@ async function appInit(appConfigOrFunc, defaultExtensions, defaultModes) { CineService.REGISTRATION, UserAuthenticationService.REGISTRATION, PanelService.REGISTRATION, + WorkflowStepsService.REGISTRATION, StateSyncService.REGISTRATION, ]); diff --git a/platform/app/src/routes/Mode/Mode.tsx b/platform/app/src/routes/Mode/Mode.tsx index 6c7fccf50..53b881e51 100644 --- a/platform/app/src/routes/Mode/Mode.tsx +++ b/platform/app/src/routes/Mode/Mode.tsx @@ -1,4 +1,4 @@ -import React, { useEffect, useState, useRef, useContext, createContext } from 'react'; +import React, { useEffect, useState, useRef } from 'react'; import { useParams, useLocation, useNavigate } from 'react-router'; import PropTypes from 'prop-types'; import { ServicesManager, utils } from '@ohif/core'; @@ -60,7 +60,7 @@ export default function ModeRoute({ locationRef.current = location; } - const { displaySetService, hangingProtocolService, userAuthenticationService } = ( + const { displaySetService, panelService, hangingProtocolService, userAuthenticationService } = ( servicesManager as ServicesManager ).services; @@ -141,7 +141,17 @@ export default function ModeRoute({ servicesManager, studyInstanceUIDs, }); + if (isMounted.current) { + const { leftPanels = [], rightPanels = [], ...layoutProps } = layoutData.props; + + panelService.reset(); + panelService.addPanels(panelService.PanelPosition.Left, leftPanels); + panelService.addPanels(panelService.PanelPosition.Right, rightPanels); + + // layoutProps contains all props but leftPanels and rightPanels + layoutData.props = layoutProps; + layoutTemplateData.current = layoutData; setRefresh(!refresh); } @@ -244,8 +254,10 @@ export default function ModeRoute({ } }, {}) ?? {}; + let unsubs; + if (route.init) { - return await route.init( + unsubs = await route.init( { servicesManager, extensionManager, @@ -273,6 +285,14 @@ export default function ModeRoute({ let unsubscriptions; setupRouteInit().then(unsubs => { unsubscriptions = unsubs; + + // Some code may need to run after hanging protocol initialization + // (eg: workflowStepsService initialization on 4D mode) + mode?.onSetupRouteComplete?.({ + servicesManager, + extensionManager, + commandsManager, + }); }); return () => { diff --git a/platform/app/src/routes/Mode/defaultRouteInit.ts b/platform/app/src/routes/Mode/defaultRouteInit.ts index 3f8aafaa7..975ac4d8b 100644 --- a/platform/app/src/routes/Mode/defaultRouteInit.ts +++ b/platform/app/src/routes/Mode/defaultRouteInit.ts @@ -15,7 +15,7 @@ const { sortingCriteria } = utils; * @param props.filters filters from query params to read the data from * @returns array of subscriptions to cancel */ -export function defaultRouteInit( +export async function defaultRouteInit( { servicesManager, studyInstanceUIDs, dataSource, filters, appConfig }, hangingProtocolId ) { @@ -95,7 +95,7 @@ export function defaultRouteInit( }); }); - Promise.allSettled(allRetrieves).then(promises => { + await Promise.allSettled(allRetrieves).then(async promises => { log.timeEnd(Enums.TimingEnum.STUDY_TO_DISPLAY_SETS); log.time(Enums.TimingEnum.DISPLAY_SETS_TO_FIRST_IMAGE); log.time(Enums.TimingEnum.DISPLAY_SETS_TO_ALL_IMAGES); @@ -120,7 +120,7 @@ export function defaultRouteInit( } }); - Promise.allSettled(allPromises).then(applyHangingProtocol); + await Promise.allSettled(allPromises).then(applyHangingProtocol); startRemainingPromises(remainingPromises); applyHangingProtocol(); }); diff --git a/platform/core/package.json b/platform/core/package.json index a4005a9e6..1b22d884d 100644 --- a/platform/core/package.json +++ b/platform/core/package.json @@ -37,7 +37,7 @@ "@cornerstonejs/codec-libjpeg-turbo-8bit": "^1.2.2", "@cornerstonejs/codec-openjpeg": "^1.2.2", "@cornerstonejs/codec-openjph": "^2.4.2", - "@cornerstonejs/dicom-image-loader": "^1.68.1", + "@cornerstonejs/dicom-image-loader": "^1.70.0", "@ohif/ui": "3.8.0-beta.73", "cornerstone-math": "0.1.9", "dicom-parser": "^1.8.21" diff --git a/platform/core/src/classes/MetadataProvider.ts b/platform/core/src/classes/MetadataProvider.ts index 650466a0a..73238568c 100644 --- a/platform/core/src/classes/MetadataProvider.ts +++ b/platform/core/src/classes/MetadataProvider.ts @@ -241,6 +241,12 @@ class MetadataProvider { sopInstanceUID: instance.SOPInstanceUID, }; break; + case WADO_IMAGE_LOADER_TAGS.PET_IMAGE_MODULE: + metadata = { + frameReferenceTime: instance.FrameReferenceTime, + actualFrameDuration: instance.ActualFrameDuration, + }; + break; case WADO_IMAGE_LOADER_TAGS.PET_ISOTOPE_MODULE: const { RadiopharmaceuticalInformationSequence } = instance; @@ -393,6 +399,41 @@ class MetadataProvider { decayCorrection: instance.DecayCorrection, }; break; + case WADO_IMAGE_LOADER_TAGS.CALIBRATION_MODULE: + // map the DICOM tags to the cornerstone tags since cornerstone tags + // are camelCase and instance tags are all caps + metadata = { + sequenceOfUltrasoundRegions: instance.SequenceOfUltrasoundRegions?.map(region => { + return { + regionSpatialFormat: region.RegionSpatialFormat, + regionDataType: region.RegionDataType, + regionFlags: region.RegionFlags, + regionLocationMinX0: region.RegionLocationMinX0, + regionLocationMinY0: region.RegionLocationMinY0, + regionLocationMaxX1: region.RegionLocationMaxX1, + regionLocationMaxY1: region.RegionLocationMaxY1, + referencePixelX0: region.ReferencePixelX0, + referencePixelY0: region.ReferencePixelY0, + referencePixelPhysicalValueX: region.ReferencePixelPhysicalValueX, + referencePixelPhysicalValueY: region.ReferencePixelPhysicalValueY, + physicalUnitsXDirection: region.PhysicalUnitsXDirection, + physicalUnitsYDirection: region.PhysicalUnitsYDirection, + physicalDeltaX: region.PhysicalDeltaX, + physicalDeltaY: region.PhysicalDeltaY, + }; + }), + }; + break; + + /** + * Below are the tags and not the modules since they are not really + * consistent with the modules above + */ + case 'temporalPositionIdentifier': + metadata = { + temporalPositionIdentifier: instance.TemporalPositionIdentifier, + }; + break; default: return; @@ -539,6 +580,7 @@ const WADO_IMAGE_LOADER_TAGS = { VOI_LUT_MODULE: 'voiLutModule', MODALITY_LUT_MODULE: 'modalityLutModule', SOP_COMMON_MODULE: 'sopCommonModule', + PET_IMAGE_MODULE: 'petImageModule', PET_ISOTOPE_MODULE: 'petIsotopeModule', PER_SERIES_MODULE: 'petSeriesModule', OVERLAY_PLANE_MODULE: 'overlayPlaneModule', @@ -549,6 +591,7 @@ const WADO_IMAGE_LOADER_TAGS = { GENERAL_IMAGE_MODULE: 'generalImageModule', GENERAL_STUDY_MODULE: 'generalStudyModule', CINE_MODULE: 'cineModule', + CALIBRATION_MODULE: 'calibrationModule', }; const INSTANCE = 'instance'; diff --git a/platform/core/src/extensions/ExtensionManager.ts b/platform/core/src/extensions/ExtensionManager.ts index ed4a9c4c5..d7997c9fc 100644 --- a/platform/core/src/extensions/ExtensionManager.ts +++ b/platform/core/src/extensions/ExtensionManager.ts @@ -48,6 +48,7 @@ export interface Extension { getCustomizationModule?: (p: ExtensionParams) => unknown; getSopClassHandlerModule?: (p: ExtensionParams) => unknown; getToolbarModule?: (p: ExtensionParams) => unknown; + getPanelModule?: (p: ExtensionParams) => unknown; onModeEnter?: () => void; onModeExit?: () => void; } diff --git a/platform/core/src/index.test.js b/platform/core/src/index.test.js index 6b2f6efae..7649a8702 100644 --- a/platform/core/src/index.test.js +++ b/platform/core/src/index.test.js @@ -1,7 +1,7 @@ import * as OHIF from './index'; describe('Top level exports', () => { - test('have not changed', () => { + test.only('have not changed', () => { const expectedExports = [ 'MODULE_TYPES', // @@ -46,6 +46,7 @@ describe('Top level exports', () => { 'pubSubServiceInterface', 'PubSubService', 'PanelService', + 'WorkflowStepsService', 'useToolbar', ].sort(); diff --git a/platform/core/src/index.ts b/platform/core/src/index.ts index a04b6569f..d548e6e7b 100644 --- a/platform/core/src/index.ts +++ b/platform/core/src/index.ts @@ -33,6 +33,7 @@ import { CustomizationService, StateSyncService, PanelService, + WorkflowStepsService, } from './services'; import { DisplaySetMessage, DisplaySetMessageList } from './services/DisplaySetService'; @@ -84,6 +85,7 @@ const OHIF = { PubSubService, PanelService, useToolbar, + WorkflowStepsService, }; export { @@ -128,6 +130,7 @@ export { Enums, Types, PanelService, + WorkflowStepsService, useToolbar, }; diff --git a/platform/core/src/services/CineService/CineService.ts b/platform/core/src/services/CineService/CineService.ts index 9c027afb2..d7f054b82 100644 --- a/platform/core/src/services/CineService/CineService.ts +++ b/platform/core/src/services/CineService/CineService.ts @@ -34,29 +34,46 @@ class CineService extends PubSubService { // reducer state does not get updated right away and if we publish the // event and we use the cineService.getState() it will return the old state setTimeout(() => { - this._broadcastEvent(this.EVENTS.CINE_STATE_CHANGED, isCineEnabled); + this._broadcastEvent(this.EVENTS.CINE_STATE_CHANGED, { isCineEnabled }); }, 0); } public playClip(element, playClipOptions) { - return this.serviceImplementation._playClip(element, playClipOptions); + const res = this.serviceImplementation._playClip(element, playClipOptions); + + this._broadcastEvent(this.EVENTS.CINE_STATE_CHANGED, { isPlaying: true }); + + return res; } public stopClip(element) { - return this.serviceImplementation._stopClip(element); + const res = this.serviceImplementation._stopClip(element); + + this._broadcastEvent(this.EVENTS.CINE_STATE_CHANGED, { isPlaying: false }); + + return res; } public _onModeExit() { this.setIsCineEnabled(false); } + public getSyncedViewports(viewportId) { + return this.serviceImplementation._getSyncedViewports(viewportId); + } + public setServiceImplementation({ getState: getStateImplementation, setCine: setCineImplementation, setIsCineEnabled: setIsCineEnabledImplementation, playClip: playClipImplementation, stopClip: stopClipImplementation, + getSyncedViewports: getSyncedViewportsImplementation, }) { + if (getSyncedViewportsImplementation) { + this.serviceImplementation._getSyncedViewports = getSyncedViewportsImplementation; + } + if (getStateImplementation) { this.serviceImplementation._getState = getStateImplementation; } diff --git a/platform/core/src/services/HangingProtocolService/HangingProtocolService.ts b/platform/core/src/services/HangingProtocolService/HangingProtocolService.ts index 7c20251a3..0246a28e9 100644 --- a/platform/core/src/services/HangingProtocolService/HangingProtocolService.ts +++ b/platform/core/src/services/HangingProtocolService/HangingProtocolService.ts @@ -1314,18 +1314,19 @@ export default class HangingProtocolService extends PubSubService { ); // Use the display set provided instead - if (reuseDisplaySetUID) { - if (viewportOptions.allowUnmatchedView !== true) { - this.validateDisplaySetSelectMatch(viewportDisplaySet, id, reuseDisplaySetUID); - } - const displaySetInfo: HangingProtocol.DisplaySetInfo = { - displaySetInstanceUID: reuseDisplaySetUID, - displaySetOptions, - }; + // Todo: find out what is wrong here + // if (reuseDisplaySetUID) { + // if (viewportOptions.allowUnmatchedView !== true) { + // this.validateDisplaySetSelectMatch(viewportDisplaySet, id, reuseDisplaySetUID); + // } + // const displaySetInfo: HangingProtocol.DisplaySetInfo = { + // displaySetInstanceUID: reuseDisplaySetUID, + // displaySetOptions, + // }; - displaySetsInfo.push(displaySetInfo); - return; - } + // displaySetsInfo.push(displaySetInfo); + // return; + // } // Use the display set index to allow getting the "next" match, eg // matching all display sets, and get the matchedDisplaySetsIndex'th item diff --git a/platform/core/src/services/PanelService/PanelService.ts b/platform/core/src/services/PanelService/PanelService.ts deleted file mode 100644 index c22194b11..000000000 --- a/platform/core/src/services/PanelService/PanelService.ts +++ /dev/null @@ -1,61 +0,0 @@ -import { ActivatePanelTriggers } from '../../types'; -import { Subscription } from '../../types/IPubSub'; -import { PubSubService } from '../_shared/pubSubServiceInterface'; - -export const EVENTS = { - ACTIVATE_PANEL: 'event::panelService:activatePanel', -}; - -export default class PanelService extends PubSubService { - public static REGISTRATION = { - name: 'panelService', - create: (): PanelService => { - return new PanelService(); - }, - }; - - constructor() { - super(EVENTS); - } - - /** - * Activates the panel with the given id. If the forceActive flag is false - * then it is up to the component containing the panel whether to activate - * it immediately or not. For instance, the panel might not be activated when - * the forceActive flag is false in the case where the user might have - * activated/displayed and then closed the panel already. - * Note that this method simply fires a broadcast event: ActivatePanelEvent. - * @param panelId the panel's id - * @param forceActive optional flag indicating if the panel should be forced to be activated or not - */ - activatePanel(panelId: string, forceActive = false): void { - this._broadcastEvent(EVENTS.ACTIVATE_PANEL, { panelId, forceActive }); - } - - /** - * Adds a mapping of events (activatePanelTriggers.sourceEvents) broadcast by - * activatePanelTrigger.sourcePubSubService that - * when fired/broadcasted must in turn activate the panel with the given id. - * The subscriptions created are returned such that they can be managed and unsubscribed - * as appropriate. - * @param panelId the id of the panel to activate - * @param activatePanelTriggers an array of triggers - * @param forceActive optional flag indicating if the panel should be forced to be activated or not - * @returns an array of the subscriptions subscribed to - */ - addActivatePanelTriggers( - panelId: string, - activatePanelTriggers: ActivatePanelTriggers[], - forceActive = false - ): Subscription[] { - return activatePanelTriggers - .map(trigger => - trigger.sourceEvents.map(eventName => - trigger.sourcePubSubService.subscribe(eventName, () => - this.activatePanel(panelId, forceActive) - ) - ) - ) - .flat(); - } -} diff --git a/platform/core/src/services/PanelService/PanelService.tsx b/platform/core/src/services/PanelService/PanelService.tsx new file mode 100644 index 000000000..b7e0b13f4 --- /dev/null +++ b/platform/core/src/services/PanelService/PanelService.tsx @@ -0,0 +1,195 @@ +import React from 'react'; +import { ActivatePanelTriggers } from '../../types'; +import { Subscription } from '../../types/IPubSub'; +import { PubSubService } from '../_shared/pubSubServiceInterface'; +import { ExtensionManager } from '../../extensions'; + +export const EVENTS = { + PANELS_CHANGED: 'event::panelService:panelsChanged', + ACTIVATE_PANEL: 'event::panelService:activatePanel', +}; + +type PanelData = { + id: string; + iconName: string; + iconLabel: string; + label: string; + name: string; + content: unknown; +}; + +export enum PanelPosition { + Left = 'left', + Right = 'right', + Bottom = 'bottom', +} + +export default class PanelService extends PubSubService { + private _extensionManager: ExtensionManager; + + public static REGISTRATION = { + name: 'panelService', + create: ({ extensionManager }): PanelService => { + return new PanelService(extensionManager); + }, + }; + + private _panelsGroups: Map = new Map(); + + constructor(extensionManager: ExtensionManager) { + super(EVENTS); + this._extensionManager = extensionManager; + } + + public get PanelPosition(): typeof PanelPosition { + return PanelPosition; + } + + private _getPanelComponent(panelId: string) { + const entry = this._extensionManager.getModuleEntry(panelId); + + if (!entry) { + throw new Error( + `${panelId} is not a valid entry for an extension module, please check your configuration or make sure the extension is registered.` + ); + } + + if (!entry?.component) { + throw new Error( + `No component found from extension ${panelId}. Check the reference string to the extension in your Mode configuration` + ); + } + + const content = entry.component; + + return { entry, content }; + } + + public getPanelData(panelId): PanelData { + let content, entry; + if (Array.isArray(panelId)) { + const panelsData = panelId.map(id => this._getPanelComponent(id)); + + // use the first panel's entry for the combined panel + entry = panelsData[0].entry; + + // stack the content of the panels in one react component + content = () => ( + <> + {panelsData.map(({ content: PanelContent }) => ( + + ))} + + ); + } else { + ({ content, entry } = this._getPanelComponent(panelId)); + } + + return { + id: entry.id, + iconName: entry.iconName, + iconLabel: entry.iconLabel, + label: entry.label, + name: entry.name, + content, + }; + } + + public addPanel(position: PanelPosition, panelId: string, options): void { + let panels = this._panelsGroups.get(position); + + if (!panels) { + panels = []; + this._panelsGroups.set(position, panels); + } + + const panelComponent = this.getPanelData(panelId); + + panels.push(panelComponent); + this._broadcastEvent(EVENTS.PANELS_CHANGED, { position, options }); + } + + public addPanels(position: PanelPosition, panelsIds: string[], options): void { + if (!Array.isArray(panelsIds)) { + throw new Error('Invalid "panelsIds" array'); + } + + panelsIds.forEach(panelId => this.addPanel(position, panelId, options)); + } + + public setPanels( + panels: { [key in PanelPosition]: string[] }, + options: { + rightPanelClosed?: boolean; + leftPanelClosed?: boolean; + } + ): void { + this.reset(); + + Object.keys(panels).forEach((position: PanelPosition) => { + this.addPanels(position, panels[position], options); + }); + } + + public getPanels(position: PanelPosition): PanelData[] { + const panels = this._panelsGroups.get(position) ?? []; + + // Return a new array to preserve the internal state + return [...panels]; + } + + public reset(): void { + const affectedPositions = Array.from(this._panelsGroups.keys()); + + this._panelsGroups.clear(); + + affectedPositions.forEach(position => + this._broadcastEvent(EVENTS.PANELS_CHANGED, { position }) + ); + } + + public onModeExit(): void { + this.reset(); + } + + /**5 + * Activates the panel with the given id. If the forceActive flag is false + * then it is up to the component containing the panel whether to activate + * it immediately or not. For instance, the panel might not be activated when + * the forceActive flag is false in the case where the user might have + * activated/displayed and then closed the panel already. + * Note that this method simply fires a broadcast event: ActivatePanelEvent. + * @param panelId the panel's id + * @param forceActive optional flag indicating if the panel should be forced to be activated or not + */ + public activatePanel(panelId: string, forceActive = false): void { + this._broadcastEvent(EVENTS.ACTIVATE_PANEL, { panelId, forceActive }); + } + + /** + * Adds a mapping of events (activatePanelTriggers.sourceEvents) broadcast by + * activatePanelTrigger.sourcePubSubService that + * when fired/broadcasted must in turn activate the panel with the given id. + * The subscriptions created are returned such that they can be managed and unsubscribed + * as appropriate. + * @param panelId the id of the panel to activate + * @param activatePanelTriggers an array of triggers + * @param forceActive optional flag indicating if the panel should be forced to be activated or not + * @returns an array of the subscriptions subscribed to + */ + public addActivatePanelTriggers( + panelId: string, + activatePanelTriggers: ActivatePanelTriggers[], + forceActive = false + ): Subscription[] { + return activatePanelTriggers + .map(trigger => + trigger.sourceEvents.map(eventName => + trigger.sourcePubSubService.subscribe(eventName, () => + this.activatePanel(panelId, forceActive) + ) + ) + ) + .flat(); + } +} diff --git a/platform/core/src/services/ServicesManager.ts b/platform/core/src/services/ServicesManager.ts index b7419639a..fb96db0f9 100644 --- a/platform/core/src/services/ServicesManager.ts +++ b/platform/core/src/services/ServicesManager.ts @@ -11,6 +11,7 @@ export default class ServicesManager { constructor(commandsManager: CommandsManager) { this._commandsManager = commandsManager; + this._extensionManager = null; this.services = {}; this.registeredServiceNames = []; } @@ -46,6 +47,7 @@ export default class ServicesManager { if (service.create) { this.services[service.name] = service.create({ configuration, + extensionManager: this._extensionManager, commandsManager: this._commandsManager, servicesManager: this, extensionManager: this._extensionManager, diff --git a/platform/core/src/services/ToolBarService/ToolbarService.ts b/platform/core/src/services/ToolBarService/ToolbarService.ts index 0f84b0b6e..b9dfea404 100644 --- a/platform/core/src/services/ToolBarService/ToolbarService.ts +++ b/platform/core/src/services/ToolBarService/ToolbarService.ts @@ -68,7 +68,7 @@ export default class ToolbarService extends PubSubService { } public reset(): void { - this.unsubscriptions.forEach(unsub => unsub()); + // this.unsubscriptions.forEach(unsub => unsub()); this.state = { buttons: {}, buttonSections: {}, @@ -120,6 +120,10 @@ export default class ToolbarService extends PubSubService { public addButtons(buttons: Button[]): void { buttons.forEach(button => { if (!this.state.buttons[button.id]) { + if (!button.props) { + button.props = {}; + } + this.state.buttons[button.id] = button; } }); @@ -350,6 +354,7 @@ export default class ToolbarService extends PubSubService { * @param {Array} buttons - The buttons to be added to the section. */ createButtonSection(key, buttons) { + // make sure all buttons have at least an empty props this.state.buttonSections[key] = buttons; this._broadcastEvent(this.EVENTS.TOOL_BAR_MODIFIED, { ...this.state }); } diff --git a/platform/core/src/services/WorkflowStepsService/WorkflowStepsService.ts b/platform/core/src/services/WorkflowStepsService/WorkflowStepsService.ts new file mode 100644 index 000000000..8a5d33782 --- /dev/null +++ b/platform/core/src/services/WorkflowStepsService/WorkflowStepsService.ts @@ -0,0 +1,238 @@ +import { CommandsManager } from '../../classes'; +import { ExtensionManager } from '../../extensions'; +import { ServicesManager } from '../../services'; +import { PubSubService } from '../_shared/pubSubServiceInterface'; + +export const EVENTS = { + ACTIVE_STEP_CHANGED: 'event::workflowStepsService:activateStepChanged', + STEPS_CHANGED: 'event::workflowStepsService:stepsChanged', +}; + +/* + A mode may define a workflow and each workflow may have one or more steps. + Each step may define a different set of tools, hanging protocol and panels + layout that will be applied to the viewer once it gets activated making the + viewer work in a more dynamic way. + + Example: + All keys inside brackets are optionals. + + workflow: { + [initialStepId]: 'step1', + steps: [ + { + id: 'firstStep', + name: 'First Step', + [toolbar]: { + buttons: firstStepToolbarButtons, + sections: [ + { + key: 'primary', + buttons: [ 'MeasurementTools', 'Zoom', ... ], + }, + ], + }, + [layout]: { + [panels]: { + left: ['firstLeftPanelId', 'secondLeftPanelId'], + right: ['firstRightPanelId'], + }, + }, + [hangingProtocol]: { + protocolId: 'default', + [stepId]: 'firstStep', + }, + }, + { + id: 'secondStep', + name: 'Second Step', + ... + }, + ] + } + + If workflow steps are defined but `initialStepId` is not set then the first + step is set as active during mode initialization. +*/ + +type CommandCallback = { + commandName: string; + options: Record; +}; + +export type WorkflowStep = { + id: string; + name: string; + toolbarButtons?: { + buttonSection: string; + buttons: string[]; + }[]; + hangingProtocol?: { + protocolId: string; + stageId?: string; + }; + layout?: { + panels: { + left?: string[]; + right?: string[]; + }; + }; + onEnter: () => void | CommandCallback[]; +}; + +class WorkflowStepsService extends PubSubService { + private _extensionManager: ExtensionManager; + private _servicesManager: ServicesManager; + private _commandsManager: CommandsManager; + private _workflowSteps: WorkflowStep[]; + private _activeWorkflowStep: WorkflowStep; + + constructor( + extensionManager: ExtensionManager, + commandsManager: CommandsManager, + servicesManager: ServicesManager + ) { + super(EVENTS); + this._workflowSteps = []; + this._activeWorkflowStep = null; + this._extensionManager = extensionManager; + this._commandsManager = commandsManager; + this._servicesManager = servicesManager; + } + + public get workflowSteps(): WorkflowStep[] { + return [...this._workflowSteps]; + } + + public get activeWorkflowStep(): WorkflowStep { + return this._activeWorkflowStep; + } + + public addWorkflowSteps(workflowSteps: WorkflowStep[]): void { + let workflowStepAdded = false; + + workflowSteps.forEach(newWorkflowStep => { + const workflowStepExists = this._workflowSteps.some( + workflowStep => workflowStep.id === newWorkflowStep.id + ); + + if (workflowStepExists) { + throw new Error(`Duplicated workflow step id (${newWorkflowStep.id})`); + } + + this._workflowSteps.push(newWorkflowStep); + workflowStepAdded = true; + }); + + if (workflowStepAdded) { + this._broadcastEvent(EVENTS.STEPS_CHANGED, {}); + } + } + + private _updateToolBar(workflowStep: WorkflowStep) { + const { toolbarService } = this._servicesManager.services; + const { toolbarButtons } = workflowStep; + + const toUse = Array.isArray(toolbarButtons) ? toolbarButtons : [toolbarButtons]; + + toUse.forEach(({ buttonSection, buttons }) => { + toolbarService.createButtonSection(buttonSection, buttons); + }); + } + + private _updatePanels(workflowStep: WorkflowStep) { + const { panelService } = this._servicesManager.services; + const panels = workflowStep?.layout?.panels; + + if (!panels) { + return; + } + + panelService.setPanels(panels, workflowStep?.layout?.options); + } + + private _updateHangingProtocol(workflowStep: WorkflowStep) { + const { hangingProtocol } = workflowStep; + + if (!hangingProtocol) { + return; + } + + this._commandsManager.runCommand('setHangingProtocol', { + protocolId: hangingProtocol.protocolId, + stageId: hangingProtocol.stageId, + stageIndex: hangingProtocol.stageIndex, + }); + } + + private _invokeCallbacks(callbacks) { + if (!callbacks) { + return; + } + + const commandsManager = this._commandsManager; + + if (!Array.isArray) { + callbacks = [callbacks]; + } + + // Invoke all callbacks which may be a function or an object like + // { commandName: string, options?: object } + callbacks.forEach(callback => { + let fn = callback; + + if (callback?.commandName) { + const { commandName, options } = callback; + fn = () => commandsManager.runCommand(commandName, options); + } + + fn(); + }); + } + + public setActiveWorkflowStep(workflowStepId: string): void { + const previousWorkflowStep = this._activeWorkflowStep; + + if (workflowStepId === previousWorkflowStep?.id) { + return; + } + + const newWorkflowStep = this._workflowSteps.find(step => step.id === workflowStepId); + + if (!newWorkflowStep) { + throw new Error(`Invalid workflowStepId (${workflowStepId})`); + } + + // onEnter needs to be called before updating the Hanging Protocol because + // some displaySets need to be created before moving to the next HP stage + // (eg: convert segmentations into a chart displaySet). If needed we can + // change it to onBeforeEnter and onAfterEnter in the future. + this._invokeCallbacks(newWorkflowStep.onEnter); + + this._activeWorkflowStep = newWorkflowStep; + this._updateToolBar(newWorkflowStep); + this._updatePanels(newWorkflowStep); + this._updateHangingProtocol(newWorkflowStep); + this._broadcastEvent(EVENTS.ACTIVE_STEP_CHANGED, { + activeWorkflowStep: newWorkflowStep, + }); + } + + public reset(): void { + this._activeWorkflowStep = null; + this._workflowSteps = []; + } + + public onModeEnter(): void { + this.reset(); + } + + public static REGISTRATION = { + name: 'workflowStepsService', + create: ({ extensionManager, commandsManager, servicesManager }): WorkflowStepsService => { + return new WorkflowStepsService(extensionManager, commandsManager, servicesManager); + }, + }; +} + +export { WorkflowStepsService as default, WorkflowStepsService }; diff --git a/platform/core/src/services/WorkflowStepsService/index.ts b/platform/core/src/services/WorkflowStepsService/index.ts new file mode 100644 index 000000000..39db00b4a --- /dev/null +++ b/platform/core/src/services/WorkflowStepsService/index.ts @@ -0,0 +1,3 @@ +import WorkflowStepsService from './WorkflowStepsService'; + +export default WorkflowStepsService; diff --git a/platform/core/src/services/index.ts b/platform/core/src/services/index.ts index bee9afd54..f8d972057 100644 --- a/platform/core/src/services/index.ts +++ b/platform/core/src/services/index.ts @@ -16,6 +16,7 @@ import UserAuthenticationService from './UserAuthenticationService'; import CustomizationService from './CustomizationService'; import StateSyncService from './StateSyncService'; import PanelService from './PanelService'; +import WorkflowStepsService from './WorkflowStepsService'; import type Services from '../types/Services'; @@ -40,4 +41,5 @@ export { PubSubService, UserAuthenticationService, PanelService, + WorkflowStepsService, }; diff --git a/platform/core/src/types/Services.ts b/platform/core/src/types/Services.ts index bf5d78591..9cedd0ad3 100644 --- a/platform/core/src/types/Services.ts +++ b/platform/core/src/types/Services.ts @@ -8,6 +8,7 @@ import { StateSyncService, UINotificationService, UIModalService, + WorkflowStepsService, } from '../services'; /** @@ -23,6 +24,7 @@ export default interface Services { uiModalService?: UIModalService; uiNotificationService?: UINotificationService; stateSyncService?: StateSyncService; + workflowStepsService: WorkflowStepsService; cineService?: unknown; userAuthenticationService?: unknown; cornerstoneViewportService?: unknown; diff --git a/platform/docs/docs/assets/img/progressDropdown.png b/platform/docs/docs/assets/img/progressDropdown.png new file mode 100644 index 000000000..263e99ae4 Binary files /dev/null and b/platform/docs/docs/assets/img/progressDropdown.png differ diff --git a/platform/docs/docs/configuration/configurationFiles.md b/platform/docs/docs/configuration/configurationFiles.md index 8182f0c27..be62938f3 100644 --- a/platform/docs/docs/configuration/configurationFiles.md +++ b/platform/docs/docs/configuration/configurationFiles.md @@ -145,7 +145,7 @@ if auth headers are used, a preflight request is required. props: { leftPanels: [tracked.thumbnailList], rightPanels: [dicomSeg.panel, tracked.measurements], - rightPanelDefaultClosed: true, + rightPanelClosed: true, viewports: [ { namespace: tracked.viewport, @@ -242,6 +242,19 @@ Example usage:
This configuration would allow the user to build a dicomweb configuration from a GCP healthcare api path e.g. http://localhost:3000/projects/your-gcp-project/locations/us-central1/datasets/your-dataset/dicomStores/your-dicom-store/study/1.3.6.1.4.1.1234.5.2.1.1234.1234.123123123123123123123123123123 +:::note +You can stack multiple panel components on top of each other by providing an array of panel components in the `rightPanels` or `leftPanels` properties. + +For instance we can use + +``` +rightPanels: [[dicomSeg.panel, tracked.measurements], [dicomSeg.panel, tracked.measurements]] +``` + +This will result in two panels, one with `dicomSeg.panel` and `tracked.measurements` and the other with `dicomSeg.panel` and `tracked.measurements` stacked on top of each other. + +::: + ### More on Accept Header Configuration In the previous section we showed that you can modify the `acceptHeader` configuration to request specific dicom transfer syntax. By default diff --git a/platform/docs/docs/platform/extensions/modules/panel.md b/platform/docs/docs/platform/extensions/modules/panel.md index 8704206c1..9a9235cee 100644 --- a/platform/docs/docs/platform/extensions/modules/panel.md +++ b/platform/docs/docs/platform/extensions/modules/panel.md @@ -107,7 +107,7 @@ function modeFactory({ modeConfiguration }) { rightPanels: [ '@ohif/extension-measurement-tracking.panelModule.trackedMeasurements', ], - rightPanelDefaultClosed: true, + rightPanelClosed: true, viewports, }, }; @@ -147,5 +147,17 @@ const mode = { }; export default mode; +``` + +:::note +You can stack multiple panel components on top of each other by providing an array of panel components in the `rightPanels` or `leftPanels` properties. + +For instance we can use ``` +rightPanels: [[dicomSeg.panel, tracked.measurements], [dicomSeg.panel, tracked.measurements]] +``` + +This will result in two panels, one with `dicomSeg.panel` and `tracked.measurements` and the other with `dicomSeg.panel` and `tracked.measurements` stacked on top of each other. + +::: diff --git a/platform/docs/docs/platform/modes/index.md b/platform/docs/docs/platform/modes/index.md index 35678edc7..aded22bd0 100644 --- a/platform/docs/docs/platform/modes/index.md +++ b/platform/docs/docs/platform/modes/index.md @@ -362,7 +362,6 @@ function modeFactory() { // exports ``` -### Toolbar @@ -398,3 +397,17 @@ Use the provided `cli` to add/remove/install/uninstall modes. Read more [here](. ::: The final registration and import of the modes happen inside a non-tracked file `pluginImport.js` (this file is also for internal use only). + + +:::note +You can stack multiple panel components on top of each other by providing an array of panel components in the `rightPanels` or `leftPanels` properties. + +For instance we can use + +``` +rightPanels: [[dicomSeg.panel, tracked.measurements], [dicomSeg.panel, tracked.measurements]] +``` + +This will result in two panels, one with `dicomSeg.panel` and `tracked.measurements` and the other with `dicomSeg.panel` and `tracked.measurements` stacked on top of each other. + +::: diff --git a/platform/docs/docs/platform/modes/routes.md b/platform/docs/docs/platform/modes/routes.md index cc5c722bc..4f4130164 100644 --- a/platform/docs/docs/platform/modes/routes.md +++ b/platform/docs/docs/platform/modes/routes.md @@ -274,6 +274,19 @@ layoutTemplate: ({ location, servicesManager }) => { */ ``` +:::note +You can stack multiple panel components on top of each other by providing an array of panel components in the `rightPanels` or `leftPanels` properties. + +For instance we can use + +``` +rightPanels: [[dicomSeg.panel, tracked.measurements], [dicomSeg.panel, tracked.measurements]] +``` + +This will result in two panels, one with `dicomSeg.panel` and `tracked.measurements` and the other with `dicomSeg.panel` and `tracked.measurements` stacked on top of each other. + +::: + ## FAQ > What is the difference between `onModeEnter` and `route.init` diff --git a/platform/docs/docs/platform/services/data/WorkflowStepService.md b/platform/docs/docs/platform/services/data/WorkflowStepService.md new file mode 100644 index 000000000..7070cade4 --- /dev/null +++ b/platform/docs/docs/platform/services/data/WorkflowStepService.md @@ -0,0 +1,174 @@ +--- +sidebar_position: 9 +sidebar_label: WorkflowStep Service +--- + +# Workflow Step Service + +This service allows you to manage your workflow in smaller steps. It provides a structured way to define and navigate through different stages +or phases of a larger process or workflow. Each step can have its own configuration, layout, toolbar buttons, and other settings tailored to the specific requirements of that stage. + +## Anatomy of a Workflow Step + +The anatomy of a workflow step refers to the different components or properties that define and configure each individual step within the workflow. Each step can be customized with various settings to tailor the user interface, available tools, and behavior of the application for that specific stage of the workflow. Here are the key components that make up a workflow step: + +- `id`: A unique identifier for the step +- `name`: A human-readable name or title for the step, which can be displayed in the user interface to help users understand the current stage of the workflow. +- `hangingProtocol`: The hanging protocol configuration specifies the protocol and stage ID to be used for displaying the images. This ensures that the appropriate data viewports and presentation are used for the current workflow step. +- `layout`: The layout configuration defines the arrangement and visibility of various panels or viewports within the application's user interface for the specific step. This can include specifying which panels should be visible on the left or right side of the screen, as well as any options for panel visibility or behavior. +- `toolbarButtons`: Each step can define a set of toolbar buttons that should be available and displayed in the application's toolbar during that step. Remember the button definitions should already be registered to toolbarService beforehand, here we are just referencing the buttons id in each section. +- `info` : An optional description or additional information about the current workflow step can be provided. which +will be displayed as tooltip in the UI. + +- Step Callbacks or Commands: Some workflow steps may require specific actions or commands to be executed when the step is entered or exited. These callbacks or commands can be defined within the step configuration and can be used to update the application's state, perform data processing, or trigger other relevant actions. For instance you have access to `onEnter` hook to run a command right after the step is entered. + +For instance, a simplified example of our pre-clinical 4D workflow steps configuration might look like this: + +```js +const dynamicVolume = { + sopClassHandler: + "@ohif/extension-cornerstone-dynamic-volume.sopClassHandlerModule.dynamic-volume", + leftPanel: + "@ohif/extension-cornerstone-dynamic-volume.panelModule.dynamic-volume", + toolBox: + "@ohif/extension-cornerstone-dynamic-volume.panelModule.dynamic-toolbox", + export: + "@ohif/extension-cornerstone-dynamic-volume.panelModule.dynamic-export", +} + +const cs3d = { + segmentation: + "@ohif/extension-cornerstone-dicom-seg.panelModule.panelSegmentation", +} + + + +const steps = [ + { + id: "dataPreparation", + name: "Data Preparation", + layout: { + panels: { + left: [dynamicVolume.leftPanel], + }, + }, + toolbarButtons: { + buttonSection: "primary", + buttons: ["MeasurementTools", "Zoom", "WindowLevel", "Crosshairs", "Pan"], + }, + hangingProtocol: { + protocolId: "default4D", + stageId: "dataPreparation", + }, + info: "In the Data Preparation step...", + }, + { + id: "roiQuantification", + name: "ROI Quantification", + layout: { + panels: { + left: [dynamicVolume.leftPanel], + right: [ + [dynamicVolume.toolBox, cs3d.segmentation, dynamicVolume.export], + ], + }, + options: { + leftPanelClosed: false, + rightPanelClosed: false, + }, + }, + toolbarButtons: [ + { + buttonSection: "primary", + buttons: [ + "MeasurementTools", + "Zoom", + "WindowLevel", + "Crosshairs", + "Pan", + ], + }, + { + buttonSection: "dynamic-toolbox", + buttons: ["BrushTools", "RectangleROIStartEndThreshold"], + }, + ], + hangingProtocol: { + protocolId: "default4D", + stageId: "roiQuantification", + }, + info: "The ROI quantification step ...", + }, + { + id: "kineticAnalysis", + name: "Kinetic Analysis", + layout: { + panels: { + left: [dynamicVolume.leftPanel], + right: [], + }, + }, + toolbarButtons: { + buttonSection: "primary", + buttons: ["MeasurementTools", "Zoom", "WindowLevel", "Crosshairs", "Pan"], + }, + hangingProtocol: { + protocolId: "default4D", + stageId: "kineticAnalysis", + }, + onEnter: [ + { + commandName: "updateSegmentationsChartDisplaySet", + options: { servicesManager }, + }, + ], + info: "The Kinetic Analysis step ...", + }, +] + +``` + +## Integration + +After you have defined your workflow steps, you can integrate them into your application by using the `workflowStepsService`. + +These steps should be called on `onSetupRouteComplete` in your mode factory. + + +Note: onModeEnter is too soon to call these steps as the mode is not yet fully initialized. + + +```js +onSetupRouteComplete: ({ servicesManager }) => { + workflowStepsService.addWorkflowSteps(workflowSettings.steps); + workflowStepsService.setActiveWorkflowStep(workflowSettings.steps[0].id); +}, +``` + +check out the `modes/preclinical-4d/src/index.tsx` for a complete example. + + +## User Interface + +We have developed a simple dropdown UI element that you can use to navigate between the different steps of your workflow. This dropdown can be added to the toolbar like below: + +```js +toolbarService.addButtons([ + { + id: 'ProgressDropdown', + uiType: 'ohif.progressDropdown', + }, +]) +toolbarService.createButtonSection('secondary', ['ProgressDropdown']); +``` + +It will appear in the `secondary` location in the toolbar. + +![alt text](../../../assets/img/progressDropdown.png) + +:::note +if you like to place the progressbar in a different location, you can use the Toolbox component +to create a button section and place the progress bar there. + +Read more in the [Toolbar module](../../extensions//modules/toolbar.md) +::: diff --git a/platform/ui/CHANGELOG.md b/platform/ui/CHANGELOG.md index 6e9843ebf..ce16ce187 100644 --- a/platform/ui/CHANGELOG.md +++ b/platform/ui/CHANGELOG.md @@ -996,7 +996,9 @@ See [Conventional Commits](https://conventionalcommits.org) for commit guideline **Note:** Version bump only for package @ohif/ui +# [3.7.0-beta.69](https://github.com/OHIF/Viewers/compare/v3.7.0-beta.68...v3.7.0-beta.69) (2023-09-11) +**Note:** Version bump only for package @ohif/ui @@ -1037,6 +1039,7 @@ See [Conventional Commits](https://conventionalcommits.org) for commit guideline **Note:** Version bump only for package @ohif/ui +**Note:** Version bump only for package @ohif/ui @@ -1044,9 +1047,11 @@ See [Conventional Commits](https://conventionalcommits.org) for commit guideline **Note:** Version bump only for package @ohif/ui +# [3.7.0-beta.63](https://github.com/OHIF/Viewers/compare/v3.7.0-beta.62...v3.7.0-beta.63) (2023-09-01) +* **grid:** remove viewportIndex and only rely on viewportId ([#3591](https://github.com/OHIF/Viewers/issues/3591)) ([4c6ff87](https://github.com/OHIF/Viewers/commit/4c6ff873e887cc30ffc09223f5cb99e5f94c9cdd)) # [3.7.0-beta.66](https://github.com/OHIF/Viewers/compare/v3.7.0-beta.65...v3.7.0-beta.66) (2023-09-06) @@ -1054,49 +1059,64 @@ See [Conventional Commits](https://conventionalcommits.org) for commit guideline - - -# [3.7.0-beta.65](https://github.com/OHIF/Viewers/compare/v3.7.0-beta.64...v3.7.0-beta.65) (2023-09-06) - - -### Features - -* **ImageOverlayViewerTool:** add ImageOverlayViewer tool that can render image overlay (pixel overlay) of the DICOM images ([#3163](https://github.com/OHIF/Viewers/issues/3163)) ([69115da](https://github.com/OHIF/Viewers/commit/69115da06d2d437b57e66608b435bb0bc919a90f)) - - - - - -# [3.7.0-beta.64](https://github.com/OHIF/Viewers/compare/v3.7.0-beta.63...v3.7.0-beta.64) (2023-09-05) - -**Note:** Version bump only for package @ohif/ui - - - - - -# [3.7.0-beta.63](https://github.com/OHIF/Viewers/compare/v3.7.0-beta.62...v3.7.0-beta.63) (2023-09-01) - - -### Features - -* **grid:** remove viewportIndex and only rely on viewportId ([#3591](https://github.com/OHIF/Viewers/issues/3591)) ([4c6ff87](https://github.com/OHIF/Viewers/commit/4c6ff873e887cc30ffc09223f5cb99e5f94c9cdd)) - - - - - # Change Log All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. -# [3.7.0-beta.62](https://github.com/OHIF/Viewers/compare/v3.7.0-beta.61...v3.7.0-beta.62) (2023-08-30) +# [3.7.0-beta.65](https://github.com/OHIF/Viewers/compare/v3.7.0-beta.64...v3.7.0-beta.65) (2023-09-06) **Note:** Version bump only for package @ohif/ui # [3.7.0-beta.61](https://github.com/OHIF/Viewers/compare/v3.7.0-beta.60...v3.7.0-beta.61) (2023-08-29) +* **ImageOverlayViewerTool:** add ImageOverlayViewer tool that can render image overlay (pixel overlay) of the DICOM images ([#3163](https://github.com/OHIF/Viewers/issues/3163)) ([69115da](https://github.com/OHIF/Viewers/commit/69115da06d2d437b57e66608b435bb0bc919a90f)) + +# [3.7.0-beta.60](https://github.com/OHIF/Viewers/compare/v3.7.0-beta.59...v3.7.0-beta.60) (2023-08-29) + +**Note:** Version bump only for package @ohif/ui + +# [3.7.0-beta.59](https://github.com/OHIF/Viewers/compare/v3.7.0-beta.58...v3.7.0-beta.59) (2023-08-29) + +**Note:** Version bump only for package @ohif/ui + +# [3.7.0-beta.64](https://github.com/OHIF/Viewers/compare/v3.7.0-beta.63...v3.7.0-beta.64) (2023-09-05) + +**Note:** Version bump only for package @ohif/ui + + + +**Note:** Version bump only for package @ohif/ui + +## [1.4.4](https://github.com/OHIF/Viewers/compare/@ohif/ui@1.4.3...@ohif/ui@1.4.4) (2020-05-04) + +# [3.7.0-beta.63](https://github.com/OHIF/Viewers/compare/v3.7.0-beta.62...v3.7.0-beta.63) (2023-09-01) + +- 🐛 Proper error handling for derived display sets + ([#1708](https://github.com/OHIF/Viewers/issues/1708)) + ([5b20d8f](https://github.com/OHIF/Viewers/commit/5b20d8f323e4b3ef9988f2f2ab672d697b6da409)) + +### Features + +* **grid:** remove viewportIndex and only rely on viewportId ([#3591](https://github.com/OHIF/Viewers/issues/3591)) ([4c6ff87](https://github.com/OHIF/Viewers/commit/4c6ff873e887cc30ffc09223f5cb99e5f94c9cdd)) + + + +## [1.4.2](https://github.com/OHIF/Viewers/compare/@ohif/ui@1.4.1...@ohif/ui@1.4.2) (2020-04-06) + +**Note:** Version bump only for package @ohif/ui + +# Change Log + +All notable changes to this project will be documented in this file. See +[Conventional Commits](https://conventionalcommits.org) for commit guidelines. + +# [3.7.0-beta.62](https://github.com/OHIF/Viewers/compare/v3.7.0-beta.61...v3.7.0-beta.62) (2023-08-30) + +# [1.4.0](https://github.com/OHIF/Viewers/compare/@ohif/ui@1.3.3...@ohif/ui@1.4.0) (2020-03-13) + +# [3.7.0-beta.61](https://github.com/OHIF/Viewers/compare/v3.7.0-beta.60...v3.7.0-beta.61) (2023-08-29) + **Note:** Version bump only for package @ohif/ui # [3.7.0-beta.60](https://github.com/OHIF/Viewers/compare/v3.7.0-beta.59...v3.7.0-beta.60) (2023-08-29) @@ -1139,7 +1159,9 @@ All notable changes to this project will be documented in this file. See ## [1.4.2](https://github.com/OHIF/Viewers/compare/@ohif/ui@1.4.1...@ohif/ui@1.4.2) (2020-04-06) -**Note:** Version bump only for package @ohif/ui +- Combined Hotkeys for special characters + ([#1233](https://github.com/OHIF/Viewers/issues/1233)) + ([2f30e7a](https://github.com/OHIF/Viewers/commit/2f30e7a821a238144c49c56f37d8e5565540b4bd)) ## [1.4.1](https://github.com/OHIF/Viewers/compare/@ohif/ui@1.4.0...@ohif/ui@1.4.1) (2020-03-17) diff --git a/platform/ui/package.json b/platform/ui/package.json index efe72cdcf..d6845eafd 100644 --- a/platform/ui/package.json +++ b/platform/ui/package.json @@ -36,6 +36,13 @@ "@testing-library/react-hooks": "^3.2.1", "browser-detect": "^0.2.28", "classnames": "^2.3.2", + "d3-array": "3", + "d3-axis": "3", + "d3-scale": "4", + "d3-scale-chromatic": "3", + "d3-selection": "3", + "d3-shape": "3", + "d3-zoom": "3", "lodash.debounce": "4.0.8", "moment": "2.29.4", "mousetrap": "^1.6.5", @@ -57,14 +64,14 @@ }, "devDependencies": { "@babel/core": "^7.23.2", - "@storybook/addon-actions": "^7.2.2", - "@storybook/addon-docs": "^7.2.2", - "@storybook/addon-essentials": "^7.2.2", - "@storybook/addon-links": "^7.2.2", - "@storybook/cli": "^7.2.2", - "@storybook/react": "^7.2.2", - "@storybook/react-webpack5": "^7.2.2", - "@storybook/source-loader": "^7.2.2", + "@storybook/addon-actions": "^7.6.10", + "@storybook/addon-docs": "^7.6.10", + "@storybook/addon-essentials": "^7.6.10", + "@storybook/addon-links": "^7.6.10", + "@storybook/cli": "^7.6.10", + "@storybook/react": "^7.6.10", + "@storybook/react-webpack5": "^7.6.10", + "@storybook/source-loader": "^7.6.10", "autoprefixer": "^10.4.14", "babel-loader": "^9.1.2", "dotenv-webpack": "^8.0.1", @@ -72,7 +79,7 @@ "postcss-loader": "^7.2.4", "prop-types": "^15.8.1", "remark-gfm": "^3.0.1", - "storybook": "^7.2.2", + "storybook": "^7.6.10", "tailwindcss": "3.2.4" } } diff --git a/platform/ui/src/assets/icons/arrow-right.svg b/platform/ui/src/assets/icons/arrow-right.svg new file mode 100644 index 000000000..307f8ffdf --- /dev/null +++ b/platform/ui/src/assets/icons/arrow-right.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/platform/ui/src/assets/icons/tool-brush.svg b/platform/ui/src/assets/icons/tool-brush.svg new file mode 100644 index 000000000..b00be0fe5 --- /dev/null +++ b/platform/ui/src/assets/icons/tool-brush.svg @@ -0,0 +1,22 @@ + + + + + diff --git a/platform/ui/src/assets/icons/tool-eraser.svg b/platform/ui/src/assets/icons/tool-eraser.svg new file mode 100644 index 000000000..4c81a34a5 --- /dev/null +++ b/platform/ui/src/assets/icons/tool-eraser.svg @@ -0,0 +1,21 @@ + + + + + + + diff --git a/platform/ui/src/assets/icons/tool-paint-fill.svg b/platform/ui/src/assets/icons/tool-paint-fill.svg new file mode 100644 index 000000000..4e671c2b9 --- /dev/null +++ b/platform/ui/src/assets/icons/tool-paint-fill.svg @@ -0,0 +1,12 @@ + + + + + diff --git a/platform/ui/src/assets/icons/tool-scissor-circle.svg b/platform/ui/src/assets/icons/tool-scissor-circle.svg new file mode 100644 index 000000000..58b996572 --- /dev/null +++ b/platform/ui/src/assets/icons/tool-scissor-circle.svg @@ -0,0 +1,9 @@ + + + + + + + diff --git a/platform/ui/src/assets/icons/tool-scissor-rect.svg b/platform/ui/src/assets/icons/tool-scissor-rect.svg new file mode 100644 index 000000000..b8b449878 --- /dev/null +++ b/platform/ui/src/assets/icons/tool-scissor-rect.svg @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + diff --git a/platform/ui/src/components/ActionButtons/ActionButtons.tsx b/platform/ui/src/components/ActionButtons/ActionButtons.tsx new file mode 100644 index 000000000..ae58b985b --- /dev/null +++ b/platform/ui/src/components/ActionButtons/ActionButtons.tsx @@ -0,0 +1,40 @@ +import React from 'react'; +import PropTypes from 'prop-types'; + +import { Button, ButtonEnums } from '../../components'; + +function ActionButtons({ actions, disabled, t }) { + return ( + + {actions.map((action, index) => ( + + ))} + + ); +} + +ActionButtons.propTypes = { + actions: PropTypes.arrayOf( + PropTypes.shape({ + label: PropTypes.string.isRequired, + onClick: PropTypes.func.isRequired, + disabled: PropTypes.bool, + }) + ).isRequired, + disabled: PropTypes.bool, +}; + +ActionButtons.defaultProps = { + disabled: false, +}; + +export default ActionButtons; diff --git a/platform/ui/src/components/ActionButtons/index.ts b/platform/ui/src/components/ActionButtons/index.ts new file mode 100644 index 000000000..d3cc681b9 --- /dev/null +++ b/platform/ui/src/components/ActionButtons/index.ts @@ -0,0 +1,3 @@ +import ActionButtons from './ActionButtons'; + +export default ActionButtons; diff --git a/platform/ui/src/components/ButtonGroup/ButtonGroup.tsx b/platform/ui/src/components/ButtonGroup/ButtonGroup.tsx index 916b72ad0..a8f89d249 100644 --- a/platform/ui/src/components/ButtonGroup/ButtonGroup.tsx +++ b/platform/ui/src/components/ButtonGroup/ButtonGroup.tsx @@ -9,6 +9,7 @@ const ButtonGroup = ({ orientation = ButtonEnums.orientation.horizontal, activeIndex: defaultActiveIndex = 0, onActiveIndexChange, + separated = false, disabled = false, }) => { const [activeIndex, setActiveIndex] = useState(defaultActiveIndex); @@ -28,33 +29,62 @@ const ButtonGroup = ({ }; const wrapperClasses = classnames( - 'items-stretch inline-flex', + `${separated ? '' : 'inline-flex'}`, orientationClasses[orientation], className ); return ( -
- {Children.map(children, (child, index) => { - if (React.isValidElement(child)) { - return cloneElement(child, { - key: index, - className: classnames( - 'rounded-[4px] px-2 py-1 text-center', - index === activeIndex - ? 'bg-customblue-40 text-white' - : 'text-primary-active bg-black', - child.props.className, - disabled ? 'ohif-disabled' : '' - ), - onClick: e => { - child.props.onClick && child.props.onClick(e); - handleButtonClick(index); - }, - }); - } - return child; +
+ {!separated && + Children.map(children, (child, index) => { + if (React.isValidElement(child)) { + return cloneElement(child, { + key: index, + className: classnames( + 'rounded-[4px] px-2 py-1', + index === activeIndex + ? 'bg-customblue-40 text-white' + : 'text-primary-active bg-black', + child.props.className, + disabled ? 'ohif-disabled' : '' + ), + onClick: e => { + child.props.onClick && child.props.onClick(e); + handleButtonClick(index); + }, + }); + } + return child; + })} + {separated && ( +
+ {Children.map(children, (child, index) => { + if (React.isValidElement(child)) { + return cloneElement(child, { + key: index, + className: classnames( + 'rounded-[4px] px-2 py-1', + index === activeIndex + ? 'bg-customblue-40 text-white' + : 'text-primary-active bg-black border-secondary-light rounded-[5px] border', + child.props.className, + disabled ? 'ohif-disabled' : '' + ), + onClick: e => { + child.props.onClick && child.props.onClick(e); + handleButtonClick(index); + }, + }); + } + return child; + })} +
+ )}
); }; @@ -66,6 +96,7 @@ ButtonGroup.propTypes = { onActiveIndexChange: PropTypes.func, className: PropTypes.string, disabled: PropTypes.bool, + separated: PropTypes.bool, }; export default ButtonGroup; diff --git a/platform/ui/src/components/CheckBox/CheckBox.tsx b/platform/ui/src/components/CheckBox/CheckBox.tsx index cb787fb34..1767abdec 100644 --- a/platform/ui/src/components/CheckBox/CheckBox.tsx +++ b/platform/ui/src/components/CheckBox/CheckBox.tsx @@ -1,7 +1,6 @@ import React, { useState, useCallback } from 'react'; -import PropTypes, { string } from 'prop-types'; -import Icon from '../Icon'; -import Typography from '../Typography'; +import PropTypes from 'prop-types'; +import { Icon, Typography } from '../../'; /** * REACT CheckBox component diff --git a/platform/ui/src/components/CinePlayer/CinePlayer.tsx b/platform/ui/src/components/CinePlayer/CinePlayer.tsx index 34afa7807..a628754cc 100644 --- a/platform/ui/src/components/CinePlayer/CinePlayer.tsx +++ b/platform/ui/src/components/CinePlayer/CinePlayer.tsx @@ -1,4 +1,4 @@ -import React, { useEffect, useState } from 'react'; +import React, { useEffect, useState, useCallback } from 'react'; import PropTypes from 'prop-types'; import debounce from 'lodash.debounce'; @@ -7,7 +7,6 @@ import Tooltip from '../Tooltip'; import InputRange from '../InputRange'; import './CinePlayer.css'; -import classNames from 'classnames'; export type CinePlayerProps = { className: string; @@ -19,6 +18,12 @@ export type CinePlayerProps = { onFrameRateChange: (value: number) => void; onPlayPauseChange: (value: boolean) => void; onClose: () => void; + updateDynamicInfo?: () => void; + dynamicInfo?: { + timePointIndex: number; + numTimePoints: number; + label?: string; + }; }; const fpsButtonClassNames = @@ -31,12 +36,15 @@ const CinePlayer: React.FC = ({ maxFrameRate, stepFrameRate, frameRate: defaultFrameRate, + dynamicInfo = {}, onFrameRateChange, onPlayPauseChange, onClose, + updateDynamicInfo, }) => { + const isDynamic = !!dynamicInfo?.numTimePoints; const [frameRate, setFrameRate] = useState(defaultFrameRate); - const debouncedSetFrameRate = debounce(onFrameRateChange, 300); + const debouncedSetFrameRate = useCallback(debounce(onFrameRateChange, 100), [onFrameRateChange]); const getPlayPauseIconName = () => (isPlaying ? 'icon-pause' : 'icon-play'); @@ -52,45 +60,92 @@ const CinePlayer: React.FC = ({ setFrameRate(defaultFrameRate); }, [defaultFrameRate]); + const handleTimePointChange = useCallback( + (newIndex: number) => { + if (isDynamic && dynamicInfo) { + // Here, you would update the component's state or context that controls the current time point index + // For demonstration, assuming a hypothetical function that updates the time point index + updateDynamicInfo({ + ...dynamicInfo, + timePointIndex: newIndex, + }); + } + }, + [isDynamic, dynamicInfo] + ); + return ( -
+ {isDynamic && dynamicInfo && ( + )} - > - onPlayPauseChange(!isPlaying)} - /> - +
-
+ onPlayPauseChange(!isPlaying)} + /> + {isDynamic && dynamicInfo && ( +
+ {/* Add Tailwind classes for monospace font and center alignment */} +
+ {dynamicInfo.timePointIndex}{' '} + {`/${dynamicInfo.numTimePoints}`} +
+
{dynamicInfo.label}
+
+ )} + +
handleSetFrameRate(frameRate - 1)} >
-
- {`${frameRate} FPS`} -
+ + } + > +
+
+ {`${frameRate} `} + {' FPS'} +
+
+
+
handleSetFrameRate(frameRate + 1)} @@ -98,12 +153,12 @@ const CinePlayer: React.FC = ({
- - + +
); }; @@ -119,6 +174,8 @@ CinePlayer.defaultProps = { onPlayPauseChange: noop, onFrameRateChange: noop, onClose: noop, + isDynamic: false, + dynamicInfo: {}, }; CinePlayer.propTypes = { @@ -134,6 +191,12 @@ CinePlayer.propTypes = { onPlayPauseChange: PropTypes.func, onFrameRateChange: PropTypes.func, onClose: PropTypes.func, + isDynamic: PropTypes.bool, + dynamicInfo: PropTypes.shape({ + timePointIndex: PropTypes.number, + numTimePoints: PropTypes.number, + label: PropTypes.string, + }), }; export default CinePlayer; diff --git a/platform/ui/src/components/CinePlayer/__stories__/cinePlayer.stories.mdx b/platform/ui/src/components/CinePlayer/__stories__/cinePlayer.stories.mdx new file mode 100644 index 000000000..9f2ea521c --- /dev/null +++ b/platform/ui/src/components/CinePlayer/__stories__/cinePlayer.stories.mdx @@ -0,0 +1,57 @@ +import { CinePlayer } from '../../../components'; +import { ArgsTable, Story, Canvas, Meta } from '@storybook/addon-docs'; + +export const argTypes = { + component: CinePlayer, + title: 'Components/CinePlayer', +}; + + + +export const CinePlayerTemplate = args => ( +
+
+ +
+
+); + + + +- [Overview](#overview) +- [Props](#props) +- [Contribute](#contribute) + +## Overview + +CinePlayer is a component that allows you to use as a boolean value + + + + {CinePlayerTemplate.bind({})} + + + +## Props + + + +## Contribute + +
diff --git a/platform/ui/src/components/Header/Header.tsx b/platform/ui/src/components/Header/Header.tsx index 5d4cd63e9..2ba958b08 100644 --- a/platform/ui/src/components/Header/Header.tsx +++ b/platform/ui/src/components/Header/Header.tsx @@ -20,6 +20,8 @@ function Header({ WhiteLabeling, showPatientInfo = PatientInfoVisibility.VISIBLE_COLLAPSED, servicesManager, + Secondary, + appConfig, ...props }): ReactNode { const { t } = useTranslation('Header'); @@ -58,14 +60,17 @@ function Header({
- {/*
{future left component}
*/} +
{Secondary}
{children}
{(showPatientInfo === PatientInfoVisibility.VISIBLE || showPatientInfo === PatientInfoVisibility.VISIBLE_COLLAPSED) && ( - + )}
diff --git a/platform/ui/src/components/HeaderPatientInfo/HeaderPatientInfo.tsx b/platform/ui/src/components/HeaderPatientInfo/HeaderPatientInfo.tsx index ec665a7a9..21a43f984 100644 --- a/platform/ui/src/components/HeaderPatientInfo/HeaderPatientInfo.tsx +++ b/platform/ui/src/components/HeaderPatientInfo/HeaderPatientInfo.tsx @@ -2,7 +2,6 @@ import React, { useState, useEffect } from 'react'; import PropTypes from 'prop-types'; import { Icon } from '@ohif/ui'; import { utils } from '@ohif/core'; -import { useAppConfig } from '@state'; const { formatDate, formatPN } = utils; @@ -70,8 +69,7 @@ function usePatientInfo(servicesManager) { return { patientInfo, isMixedPatients }; } -function HeaderPatientInfo({ servicesManager }) { - const [appConfig] = useAppConfig(); +function HeaderPatientInfo({ servicesManager, appConfig }) { const initialExpandedState = appConfig.showPatientInfo === 'visible'; const [expanded, setExpanded] = useState(initialExpandedState); const { patientInfo, isMixedPatients } = usePatientInfo(servicesManager); diff --git a/platform/ui/src/components/Icon/getIcon.js b/platform/ui/src/components/Icon/getIcon.js index 7bd5c5042..c2edee38d 100644 --- a/platform/ui/src/components/Icon/getIcon.js +++ b/platform/ui/src/components/Icon/getIcon.js @@ -3,6 +3,7 @@ import React from 'react'; import arrowDown from './../../assets/icons/arrow-down.svg'; import arrowLeft from './../../assets/icons/arrow-left.svg'; +import arrowRight from './../../assets/icons/arrow-right.svg'; import arrowLeftSmall from './../../assets/icons/arrow-left-small.svg'; import arrowRightSmall from './../../assets/icons/arrow-right-small.svg'; import calendar from './../../assets/icons/calendar.svg'; @@ -119,6 +120,11 @@ import toolCalibration from './../../assets/icons/tool-calibrate.svg'; import toolFreehand from './../../assets/icons/tool-freehand.svg'; import toolFreehandPolygon from './../../assets/icons/tool-freehand-polygon.svg'; import toolPolygon from './../../assets/icons/tool-polygon.svg'; +import toolBrush from './../../assets/icons/tool-brush.svg'; +import toolEraser from './../../assets/icons/tool-eraser.svg'; +import toolScissorRect from './../../assets/icons/tool-scissor-rect.svg'; +import toolScissorCircle from './../../assets/icons/tool-scissor-circle.svg'; +import toolPaintFill from './../../assets/icons/tool-paint-fill.svg'; import editPatient from './../../assets/icons/edit-patient.svg'; import panelGroupMore from './../../assets/icons/panel-group-more.svg'; import panelGroupOpenClose from './../../assets/icons/panel-group-open-close.svg'; @@ -216,6 +222,7 @@ import investigationalUse from './../../assets/icons/illustration-investigationa const ICONS = { 'arrow-down': arrowDown, 'arrow-left': arrowLeft, + 'arrow-right': arrowRight, 'arrow-left-small': arrowLeftSmall, 'arrow-right-small': arrowRightSmall, calendar: calendar, diff --git a/platform/ui/src/components/InputDoubleRange/InputDoubleRange.tsx b/platform/ui/src/components/InputDoubleRange/InputDoubleRange.tsx index b8aadf26d..d5ea68165 100644 --- a/platform/ui/src/components/InputDoubleRange/InputDoubleRange.tsx +++ b/platform/ui/src/components/InputDoubleRange/InputDoubleRange.tsx @@ -1,4 +1,4 @@ -import React, { useState, useCallback, useEffect, useRef } from 'react'; +import React, { useState, useEffect, useRef } from 'react'; import classNames from 'classnames'; import { InputNumber } from '../../components'; // Import InputNumber component import './InputDoubleRange.css'; @@ -19,6 +19,7 @@ type InputDoubleRangeProps = { trackColor?: string; allowNumberEdit?: boolean; showAdjustmentArrows?: boolean; + allowOutOfRange?: boolean; }; const InputDoubleRange: React.FC = ({ @@ -36,6 +37,7 @@ const InputDoubleRange: React.FC = ({ labelPosition, trackColor, allowNumberEdit, + allowOutOfRange = false, showAdjustmentArrows, }) => { // Set initial thumb positions as percentages @@ -55,7 +57,15 @@ const InputDoubleRange: React.FC = ({ updatedRangeValue[index] = newValues; } - const calculatePercentage = value => ((value - minValue) / (maxValue - minValue)) * 100; + const calculatePercentage = value => { + if (value < minValue) { + return 0; + } + if (value > maxValue) { + return 100; + } + return ((value - minValue) / (maxValue - minValue)) * 100; + }; const newPercentageStart = calculatePercentage(updatedRangeValue[0]); const newPercentageEnd = calculatePercentage(updatedRangeValue[1]); @@ -73,17 +83,22 @@ const InputDoubleRange: React.FC = ({ const LabelOrEditableNumber = (val, index) => { return allowNumberEdit ? ( - { - updateRangeValues(newValue, index); - }} - step={step} - labelClassName="text-white" - showAdjustmentArrows={showAdjustmentArrows} - /> + // the pl-[2px] class is used to align the thumb so that it doesn't + // go over the label when the value is full, not sure what is wrong + // with the implementation, we need to fix it properly +
+ { + updateRangeValues(newValue, index); + }} + step={step} + labelClassName={classNames(labelClassName ?? 'text-white')} + showAdjustmentArrows={showAdjustmentArrows} + /> +
) : ( {val} @@ -138,31 +153,52 @@ const InputDoubleRange: React.FC = ({ const newValue = Math.round(((x / rect.width) * (maxValue - minValue) + minValue) / step) * step; - // Make sure newValue is within [minValue, maxValue] - const clampedValue = Math.min(Math.max(newValue, minValue), maxValue); + if (!allowOutOfRange) { + const clampedValue = Math.min(Math.max(newValue, minValue), maxValue); - // Ensure that left and right thumbs don't switch positions - if (selectedThumbValue === 0 && clampedValue >= rangeValue[1]) { - return; - } - if (selectedThumbValue === 1 && clampedValue <= rangeValue[0]) { - return; + const updatedRangeValue = [...rangeValue]; + updatedRangeValue[selectedThumbValue] = clampedValue; + setRangeValue(updatedRangeValue); + + onChange(updatedRangeValue); + + const percentage = Math.round(((clampedValue - minValue) / (maxValue - minValue)) * 100); + if (selectedThumbValue === 0) { + setPercentageStart(percentage); + } else { + setPercentageEnd(percentage); + } + } else { + const updatedRangeValue = [...rangeValue]; + updatedRangeValue[selectedThumbValue] = newValue; + setRangeValue(updatedRangeValue); + + onChange(updatedRangeValue); + + // Update the thumb position + const percentage = Math.round(((newValue - minValue) / (maxValue - minValue)) * 100); + if (percentage < 0) { + if (selectedThumbValue === 0) { + setPercentageStart(0); + } else { + setPercentageEnd(0); + } + } else if (percentage > 100) { + if (selectedThumbValue === 0) { + setPercentageStart(100); + } else { + setPercentageEnd(100); + } + } else { + if (selectedThumbValue === 0) { + setPercentageStart(percentage); + } else { + setPercentageEnd(percentage); + } + } } // Update the correct values in the rangeValue array - const updatedRangeValue = [...rangeValue]; - updatedRangeValue[selectedThumbValue] = clampedValue; - setRangeValue(updatedRangeValue); - - onChange(updatedRangeValue); - - // Update the thumb position - const percentage = Math.round(((clampedValue - minValue) / (maxValue - minValue)) * 100); - if (selectedThumbValue === 0) { - setPercentageStart(percentage); - } else { - setPercentageEnd(percentage); - } }; // Calculate the range values percentages for gradient background diff --git a/platform/ui/src/components/InputNumber/InputNumber.tsx b/platform/ui/src/components/InputNumber/InputNumber.tsx index b3d9bbec5..bb29b4ca9 100644 --- a/platform/ui/src/components/InputNumber/InputNumber.tsx +++ b/platform/ui/src/components/InputNumber/InputNumber.tsx @@ -5,6 +5,9 @@ import './InputNumber.css'; import Label from '../Label'; import getMaxDigits from '../../utils/getMaxDigits'; +const arrowHorizontalClassName = + 'cursor-pointer text-primary-active active:text-primary-light hover:opacity-70 w-4 flex items-center justify-center'; + /** * React Number Input component' * it has two props, value and onChange @@ -16,6 +19,7 @@ import getMaxDigits from '../../utils/getMaxDigits'; const sizesClasses = { sm: 'w-[45px] h-[28px]', + md: 'w-[58px] h-[28px]', lg: 'w-[206px] h-[35px]', }; @@ -25,11 +29,16 @@ const InputNumber: React.FC<{ minValue?: number; maxValue?: number; step?: number; - size?: 'sm' | 'lg'; + size?: 'sm' | 'lg' | 'md'; className?: string; labelClassName?: string; label?: string; showAdjustmentArrows?: boolean; + arrowsDirection: 'vertical' | 'horizontal'; + labelPosition?: 'left' | 'bottom' | 'right' | 'top'; + inputClassName?: string; + sizeClassName?: string; + inputContainerClassName?: string; }> = ({ value, onChange, @@ -38,19 +47,24 @@ const InputNumber: React.FC<{ size = 'sm', minValue = 0, maxValue = 100, - labelClassName, + labelClassName = 'text-aqua-pale text-[11px] mx-auto', label, showAdjustmentArrows = true, + arrowsDirection = 'vertical', + labelPosition = 'left', + inputClassName = 'text-white bg-primary-dark text-[14px]', + sizeClassName, + inputContainerClassName = 'bg-primary-dark border-secondary-light border rounded-[4px]', }) => { const [numberValue, setNumberValue] = useState(value); const [isFocused, setIsFocused] = useState(false); const maxDigits = getMaxDigits(maxValue, step); const inputWidth = Math.max(maxDigits * 10, showAdjustmentArrows ? 20 : 28); - const arrowWidth = showAdjustmentArrows ? 20 : 0; - const containerWidth = `${inputWidth + arrowWidth}px`; const decimalPlaces = Number.isInteger(step) ? 0 : step.toString().split('.')[1].length; + const sizeToUse = sizeClassName ? sizeClassName : sizesClasses[size]; + useEffect(() => { setNumberValue(value); }, [value]); @@ -95,21 +109,31 @@ const InputNumber: React.FC<{ const increment = () => updateValue(parseFloat(numberValue) + step); const decrement = () => updateValue(parseFloat(numberValue) - step); + const labelElement = label && ( +