Chore/kill yalc with fire (#629)
* init * more shifting * Move @babel dependencies up to workspace root * Begin updating dependent libraries to use sync'd webpack builds w/ watches * Commit changes before a long weekend * Split packages into platform and extensions * Consolidate how/where we specify file/module type entrypoints * Make it possible to pass in extensions as App props * Resolve viewer's modules * Target for UMD bundle * Add Webpack Stylus loader * Provide WebPack build options for microscopy, vtk, and ui * Better entrypoint for extensions * Push changes up to switch PCs * Fix ESM symlink build for Viewers * Shift docs to root * Specify additional lerna config props * Begin providing basic readme info * Rename example extension folder * Shift links to bottom of doc * First attempt at a netlify deploy preview * Attempt to fix deploy preview build * push workspace enabled to initial command; remove second yarn install; use npx to call gitbook cli commands * Try to use global gitbook-cli * Export node_modules path * More agressive with modifying PATH * Follow deploy log output advice * try again to set bin path * Try swapping bash with a new shell * Try bash -l instead of exec bash * Annd let's try again * and again * We may have figured it out johnny, boy * We need to pull cornerstone-wado-image-loader files from hoisted node_modules * Attempt to fix ticks/escapes * Change copy syntax; try running tests on viewers from root for circleci * Lower version to match circleci image * Try alternative jest-canvas-mock location and version file syntax * Run version command instead of calling node directly * Try alternative jest transform * Set path and enable workspaces * Add codecov flags * Use cpx so our copying finishes? * Get all platform unit tests to run * Run and report individually and in parallel * Try once relying on codecov yaml to split w/ flags * Add projects to split by flags * Generate separate reports * Trigger codecov after everything has finished running; these may not support flags * Use recommended flags from issue comments for codecov * Fix typo * Remove clear flag * Shift back to calling codecov from root * Generate example for codecov issue * Try fixing paths * Simplify * Try using codecov orb * Bump circleci version * Upload core and viewer * Use full string paths * Remove individual codecov calls * Fix dir * Combine files before upload * Escape anchors * tryfix syntax * Escape string literal * Combine lines to reduce path * long paths * Use home alias * Fix filename * Try to see the contents of our cat'd file * Also upload `core` * Try running with aliased folder * Fix path; split PR and Merge unit tests into separate jobs * Set default threshold * Fix typo * Changing to scoped package names * Adding note * Catch more updates * chore(release): publish %s [skip ci] - @ohif/extension-cornerstone@0.0.39-alpha.0 - @ohif/extension-dicom-html@0.0.4-alpha.0 - @ohif/extension-dicom-microscopy@0.0.9-alpha.0 - @ohif/extension-dicom-pdf@0.0.8-alpha.0 - @ohif/extension-vtk@0.1.4-alpha.0 - @ohif/core@0.11.1-alpha.0 - @ohif/i18n@0.2.3-alpha.0 - @ohif/ui@0.2.18-alpha.0 - @ohif/viewer@0.0.22-alpha.0 * Clean up primary readme * Support for dev and dev:* commands * Shift build command; satisfy default PWA build * Remove old scripts * Clean up UI to set webpack scripts * Tidy up project links * Clean duplicate code in UI project * Update UI project's docs * Clean up ui and i18n config * Reduce duplicate code in `@ohif/core` * Fix @ohif/ui versions * bump @ohif/core versions * Redux testkit dep * Remove unused/duplicate config files for projects/packages * ohif-core --> @ohif/core * Safer publish command * chore(release): publish %s [skip ci] - @ohif/extension-cornerstone@0.0.39-alpha.1 - @ohif/extension-dicom-html@0.0.4-alpha.1 - @ohif/extension-dicom-microscopy@0.0.9-alpha.1 - @ohif/extension-dicom-pdf@0.0.8-alpha.1 - @ohif/extension-vtk@0.1.4-alpha.1 - @ohif/core@0.11.1-alpha.1 - @ohif/i18n@0.2.3-alpha.1 - @ohif/ui@0.2.18-alpha.1 - @ohif/viewer@0.0.22-alpha.1 * test version bump * Add global prettier config * chore(release): publish %s [skip ci] - @ohif/viewer@0.0.22-alpha.2 * test lerna publish * Update package.jsons * Fix build scripts * catch changes * chore(release): publish %s [skip ci] - @ohif/extension-cornerstone@0.0.39-alpha.2 - @ohif/extension-dicom-html@0.0.4-alpha.2 - @ohif/extension-dicom-microscopy@0.0.9-alpha.2 - @ohif/extension-dicom-pdf@0.0.8-alpha.2 - @ohif/extension-vtk@0.1.4-alpha.2 - @ohif/core@0.11.1-alpha.2 - @ohif/i18n@0.2.3-alpha.2 - @ohif/ui@0.2.18-alpha.2 - @ohif/viewer@0.0.22-alpha.3 * fix eslint issues caused by eslint 6 and our react-app config * Publish with canary tag * chore(release): publish %s [skip ci] - @ohif/extension-cornerstone@0.0.39-alpha.3 - @ohif/extension-dicom-html@0.0.4-alpha.3 - @ohif/extension-dicom-microscopy@0.0.9-alpha.3 - @ohif/extension-dicom-pdf@0.0.8-alpha.3 - @ohif/extension-vtk@0.1.4-alpha.3 - @ohif/core@0.11.1-alpha.3 - @ohif/i18n@0.2.3-alpha.3 - @ohif/ui@0.2.18-alpha.3 - @ohif/viewer@0.0.22-alpha.4 * chore(release): publish %s [skip ci] - @ohif/extension-cornerstone@0.0.39-alpha.4 - @ohif/extension-dicom-html@0.0.4-alpha.4 - @ohif/extension-dicom-microscopy@0.0.9-alpha.4 - @ohif/extension-dicom-pdf@0.0.8-alpha.4 - @ohif/extension-vtk@0.1.4-alpha.4 - @ohif/core@0.11.1-alpha.4 - @ohif/i18n@0.2.3-alpha.4 - @ohif/ui@0.2.18-alpha.4 - @ohif/viewer@0.0.22-alpha.5 * Simplify build * chore(release): publish %s [skip ci] - @ohif/extension-cornerstone@0.0.39-alpha.5 - @ohif/extension-dicom-html@0.0.4-alpha.5 - @ohif/extension-dicom-microscopy@0.0.9-alpha.5 - @ohif/extension-dicom-pdf@0.0.8-alpha.5 - @ohif/extension-vtk@0.1.4-alpha.5 - @ohif/core@0.11.1-alpha.5 - @ohif/i18n@0.2.3-alpha.5 - @ohif/ui@0.2.18-alpha.5 - @ohif/viewer@0.0.22-alpha.6 * chore(release): publish %s [skip ci] - @ohif/extension-cornerstone@0.0.39-alpha.6 - @ohif/extension-dicom-html@0.0.4-alpha.6 - @ohif/extension-dicom-microscopy@0.0.9-alpha.6 - @ohif/extension-dicom-pdf@0.0.8-alpha.6 - @ohif/extension-vtk@0.1.4-alpha.6 - @ohif/core@0.11.1-alpha.6 - @ohif/i18n@0.2.3-alpha.6 - @ohif/ui@0.2.18-alpha.6 - @ohif/viewer@0.0.22-alpha.7 * Split version and publish * chore(release): publish %s [skip ci] - @ohif/extension-cornerstone@0.0.39-alpha.7 - @ohif/extension-dicom-html@0.0.4-alpha.7 - @ohif/extension-dicom-microscopy@0.0.9-alpha.7 - @ohif/extension-dicom-pdf@0.0.8-alpha.7 - @ohif/extension-vtk@0.1.4-alpha.7 - @ohif/core@0.11.1-alpha.7 - @ohif/i18n@0.2.3-alpha.7 - @ohif/ui@0.2.18-alpha.7 - @ohif/viewer@0.0.22-alpha.8 * Try simplify netlify build * react-viewerbase --> @ohif/ui * add test for stylus loader * Try new way to specify publish path * Use an output folder that won't be ignored * Try move command * fiddle with paths * Dig for some information * Make sure we're in root for our commands * Remove discovery * Setup script-tag example * Fix typo * Move config folder * Update cornerstone extension to use shared/root webpack configs * capture changes * Update extension webpack configs * Don't check in docz output * Fix babel runtime resolution issue * Simplify ui build steps * Push in progress * Shift directories * Get viewer dev path to work * Fix viewer commonjs build * Fix build pwa config for viewers * Make sure our package specific command can be called from root * Update notes * Fix imports and misc. merge notes * Bump wado-image-loader version * Switch up commands to remove webworkers copy * Fix CI config * Fix more broken package references * Add react-dropzone * Persist so e2e test can use * Fix lockfile * Use cypress orb to simplify CI * Fix config * Try again * Install yarn latest for orb * Install yarn a different way * Wait on correct port * Run tests in viewer project * Fix cypress config * Make Cypress happier - use default location * Simplify e2e testing * Capture UI changes since fork * Catch core up * Grab latest deps after merge * Fix broken import * Make sure cornerstone-wado-image-loader resolves to 3+ * Note regarding orbs * Fix refresh on 404 routes * Fix odd error for cornerstone-wado-image-loader * Different target for UMD * Simplify dev script * Try to get fancy with netlify output * Let's do it again * Try to fix measurementTools issue * See if we can get our lerna magic to work on merge to monorepo branch
This commit is contained in:
1 parent
cac911f08e
commit
08ff214ea6
919 files changed
+45652
-52097
No files matched your search
@@ -0,0 +1,1000 @@
|
||||
import cornerstoneTools from 'cornerstone-tools';
|
||||
import log from '../../log';
|
||||
import getLabel from '../lib/getLabel';
|
||||
import getDescription from '../lib/getDescription';
|
||||
import getImageIdForImagePath from '../lib/getImageIdForImagePath';
|
||||
import guid from '../../utils/guid';
|
||||
import studyMetadataManager from '../../utils/studyMetadataManager';
|
||||
|
||||
const configuration = {
|
||||
measurementTools: [],
|
||||
};
|
||||
|
||||
export default class MeasurementApi {
|
||||
static Instance;
|
||||
|
||||
static setConfiguration(config) {
|
||||
Object.assign(configuration, config);
|
||||
}
|
||||
|
||||
static getConfiguration() {
|
||||
return configuration;
|
||||
}
|
||||
|
||||
static getToolsGroupsMap() {
|
||||
const toolsGroupsMap = {};
|
||||
configuration.measurementTools.forEach(toolGroup => {
|
||||
toolGroup.childTools.forEach(
|
||||
tool => (toolsGroupsMap[tool.id] = toolGroup.id)
|
||||
);
|
||||
});
|
||||
|
||||
return toolsGroupsMap;
|
||||
}
|
||||
|
||||
static getToolGroupTools(toolsGroupsMap) {
|
||||
const result = {};
|
||||
Object.keys(toolsGroupsMap).forEach(toolType => {
|
||||
const toolGroupId = toolsGroupsMap[toolType];
|
||||
if (!result[toolGroupId]) {
|
||||
result[toolGroupId] = [];
|
||||
}
|
||||
|
||||
result[toolGroupId].push(toolType);
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
static getToolConfiguration(toolType) {
|
||||
const configuration = MeasurementApi.getConfiguration();
|
||||
const toolsGroupsMap = MeasurementApi.getToolsGroupsMap();
|
||||
|
||||
const toolGroupId = toolsGroupsMap[toolType];
|
||||
const toolGroup = configuration.measurementTools.find(
|
||||
toolGroup => toolGroup.id === toolGroupId
|
||||
);
|
||||
|
||||
let tool;
|
||||
if (toolGroup) {
|
||||
tool = toolGroup.childTools.find(tool => tool.id === toolType);
|
||||
}
|
||||
|
||||
return {
|
||||
toolGroupId,
|
||||
toolGroup,
|
||||
tool,
|
||||
};
|
||||
}
|
||||
|
||||
static syncMeasurementAndToolData(measurement) {
|
||||
log.info('syncMeasurementAndToolData');
|
||||
|
||||
const measurementLabel = getLabel(measurement);
|
||||
if (measurementLabel) {
|
||||
measurement.labels = [measurementLabel];
|
||||
}
|
||||
|
||||
const toolState = cornerstoneTools.globalImageIdSpecificToolStateManager.saveToolState();
|
||||
|
||||
// Stop here if the metadata for the measurement's study is not loaded yet
|
||||
const { studyInstanceUid } = measurement;
|
||||
const metadata = studyMetadataManager.get(studyInstanceUid);
|
||||
if (!metadata) return;
|
||||
|
||||
// Iterate each child tool if the current tool has children
|
||||
const toolType = measurement.toolType;
|
||||
const { tool } = MeasurementApi.getToolConfiguration(toolType);
|
||||
if (Array.isArray(tool.childTools)) {
|
||||
tool.childTools.forEach(childToolKey => {
|
||||
const childMeasurement = measurement[childToolKey];
|
||||
if (!childMeasurement) return;
|
||||
childMeasurement._id = measurement._id;
|
||||
childMeasurement.measurementNumber = measurement.measurementNumber;
|
||||
childMeasurement.lesionNamingNumber = measurement.lesionNamingNumber;
|
||||
|
||||
MeasurementApi.syncMeasurementAndToolData(childMeasurement);
|
||||
});
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const imageId = getImageIdForImagePath(measurement.imagePath);
|
||||
|
||||
// If no tool state exists for this imageId, create an empty object to store it
|
||||
if (!toolState[imageId]) {
|
||||
toolState[imageId] = {};
|
||||
}
|
||||
|
||||
const currentToolState = toolState[imageId][toolType];
|
||||
const toolData = currentToolState && currentToolState.data;
|
||||
|
||||
// Check if we already have toolData for this imageId and toolType
|
||||
if (toolData && toolData.length) {
|
||||
// If we have toolData, we should search it for any data related to the current Measurement
|
||||
const toolData = toolState[imageId][toolType].data;
|
||||
|
||||
// Create a flag so we know if we've successfully updated the Measurement in the toolData
|
||||
let alreadyExists = false;
|
||||
|
||||
// Loop through the toolData to search for this Measurement
|
||||
toolData.forEach(tool => {
|
||||
// Break the loop if this isn't the Measurement we are looking for
|
||||
if (tool._id !== measurement._id) {
|
||||
return;
|
||||
}
|
||||
|
||||
// If we have found the Measurement, set the flag to True
|
||||
alreadyExists = true;
|
||||
|
||||
// Update the toolData from the Measurement data
|
||||
Object.assign(tool, measurement);
|
||||
return false;
|
||||
});
|
||||
|
||||
// If we have found the Measurement we intended to update, we can stop this function here
|
||||
if (alreadyExists === true) {
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
// If no toolData exists for this toolType, create an empty array to hold some
|
||||
toolState[imageId][toolType] = {
|
||||
data: [],
|
||||
};
|
||||
}
|
||||
|
||||
// If we have reached this point, it means we haven't found the Measurement we are looking for
|
||||
// in the current toolData. This means we need to add it.
|
||||
|
||||
// Add the MeasurementData into the toolData for this imageId
|
||||
toolState[imageId][toolType].data.push(measurement);
|
||||
|
||||
cornerstoneTools.globalImageIdSpecificToolStateManager.restoreToolState(
|
||||
toolState
|
||||
);
|
||||
}
|
||||
|
||||
static isToolIncluded(tool) {
|
||||
return (
|
||||
tool.options &&
|
||||
tool.options.caseProgress &&
|
||||
tool.options.caseProgress.include
|
||||
);
|
||||
}
|
||||
|
||||
constructor(timepointApi, options = {}) {
|
||||
if (MeasurementApi.Instance) {
|
||||
MeasurementApi.Instance.initialize(timepointApi, options);
|
||||
return MeasurementApi.Instance;
|
||||
}
|
||||
|
||||
this.initialize(timepointApi, options);
|
||||
MeasurementApi.Instance = this;
|
||||
}
|
||||
|
||||
initialize(timepointApi, options = {}) {
|
||||
this.timepointApi = timepointApi;
|
||||
this.options = options;
|
||||
this.toolGroups = {};
|
||||
this.tools = {};
|
||||
this.toolsGroupsMap = MeasurementApi.getToolsGroupsMap();
|
||||
this.toolGroupTools = MeasurementApi.getToolGroupTools(this.toolsGroupsMap);
|
||||
|
||||
// Iterate over each tool group and create collection
|
||||
configuration.measurementTools.forEach(toolGroup => {
|
||||
this.toolGroups[toolGroup.id] = [];
|
||||
|
||||
// Iterate over each tool group child tools (e.g. bidirectional, targetCR, etc.) and create collection
|
||||
toolGroup.childTools.forEach(tool => {
|
||||
this.tools[tool.id] = [];
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
onMeasurementsUpdated() {
|
||||
if (typeof this.options.onMeasurementsUpdated !== 'function') {
|
||||
log.warn('Measurements update callback is not defined');
|
||||
return;
|
||||
}
|
||||
|
||||
this.options.onMeasurementsUpdated(Object.assign({}, this.tools));
|
||||
}
|
||||
|
||||
retrieveMeasurements(patientId, timepointIds) {
|
||||
const retrievalFn = configuration.dataExchange.retrieve;
|
||||
if (typeof retrievalFn !== 'function') {
|
||||
log.error('Measurement retrieval function has not been configured.');
|
||||
return;
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
retrievalFn(patientId, timepointIds).then(measurementData => {
|
||||
if (measurementData) {
|
||||
log.info('Measurement data retrieval');
|
||||
log.info(measurementData);
|
||||
|
||||
Object.keys(measurementData).forEach(measurementTypeId => {
|
||||
const measurements = measurementData[measurementTypeId];
|
||||
|
||||
measurements.forEach(measurement => {
|
||||
const { toolType } = measurement;
|
||||
|
||||
this.addMeasurement(toolType, measurement);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
resolve();
|
||||
|
||||
// Synchronize the new tool data
|
||||
this.syncMeasurementsAndToolData();
|
||||
|
||||
// Let others know that the measurements are updated
|
||||
this.onMeasurementsUpdated();
|
||||
}, reject);
|
||||
});
|
||||
}
|
||||
|
||||
storeMeasurements(timepointId) {
|
||||
const storeFn = configuration.dataExchange.store;
|
||||
if (typeof storeFn !== 'function') {
|
||||
log.error('Measurement store function has not been configured.');
|
||||
return;
|
||||
}
|
||||
|
||||
let measurementData = {};
|
||||
configuration.measurementTools.forEach(toolGroup => {
|
||||
// Skip the tool groups excluded from case progress
|
||||
if (!MeasurementApi.isToolIncluded(toolGroup)) {
|
||||
return;
|
||||
}
|
||||
|
||||
toolGroup.childTools.forEach(tool => {
|
||||
// Skip the tools excluded from case progress
|
||||
if (!MeasurementApi.isToolIncluded(tool)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!measurementData[toolGroup.id]) {
|
||||
measurementData[toolGroup.id] = [];
|
||||
}
|
||||
|
||||
measurementData[toolGroup.id] = measurementData[toolGroup.id].concat(
|
||||
this.tools[tool.id]
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
const timepointFilter = timepointId
|
||||
? tp => tp.timepointId === timepointId
|
||||
: null;
|
||||
const timepoints = this.timepointApi.all(timepointFilter);
|
||||
const timepointIds = timepoints.map(t => t.timepointId);
|
||||
const patientId = timepoints[0].patientId;
|
||||
const filter = {
|
||||
patientId,
|
||||
timepointIds,
|
||||
};
|
||||
|
||||
log.info('Saving Measurements for timepoints:', timepoints);
|
||||
return storeFn(measurementData, filter).then(() => {
|
||||
log.info('Measurement storage completed');
|
||||
});
|
||||
}
|
||||
|
||||
calculateLesionNamingNumber(measurements) {
|
||||
const sortedMeasurements = measurements.sort((a, b) => {
|
||||
if (a.lesionNamingNumber > b.lesionNamingNumber) {
|
||||
return 1;
|
||||
} else if (a.lesionNamingNumber < b.lesionNamingNumber) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
});
|
||||
|
||||
// Calculate lesion naming number starting from 1 not to miss any measurement (as seen in MM)
|
||||
// A measurement from beginning of the list might be deleted, so a new measurement should replace that
|
||||
let i;
|
||||
for (i = 1; i < sortedMeasurements.length + 1; i++) {
|
||||
if (i < sortedMeasurements[i - 1].lesionNamingNumber) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return i;
|
||||
}
|
||||
|
||||
fetch(toolGroupId, filter) {
|
||||
if (!this.toolGroups[toolGroupId]) {
|
||||
throw new Error(
|
||||
`MeasurementApi: No Collection with the id: ${toolGroupId}`
|
||||
);
|
||||
}
|
||||
|
||||
let items;
|
||||
if (filter) {
|
||||
items = this.toolGroups[toolGroupId].filter(filter);
|
||||
} else {
|
||||
items = this.toolGroups[toolGroupId];
|
||||
}
|
||||
|
||||
return items.map(item => {
|
||||
if (item.toolId) {
|
||||
return this.tools[item.toolId].find(
|
||||
tool => tool._id === item.toolItemId
|
||||
);
|
||||
}
|
||||
|
||||
return { lesionNamingNumber: item.lesionNamingNumber };
|
||||
});
|
||||
}
|
||||
|
||||
getFirstMeasurement(timepointId) {
|
||||
// Get child tools from all included tool groups
|
||||
let childTools = [];
|
||||
configuration.measurementTools.forEach(toolGroup => {
|
||||
// Skip the tool groups excluded from case progress
|
||||
if (!MeasurementApi.isToolIncluded(toolGroup)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
childTools = childTools.concat(toolGroup.childTools);
|
||||
});
|
||||
|
||||
// Get all included child tools
|
||||
const includedChildTools = childTools.filter(tool =>
|
||||
MeasurementApi.isToolIncluded(tool)
|
||||
);
|
||||
|
||||
// Get the first measurement for the given timepoint
|
||||
let measurement = undefined;
|
||||
includedChildTools.every(tool => {
|
||||
measurement = this.tools[tool.id].find(
|
||||
t => t.timepointId === timepointId && t.measurementNumber === 1
|
||||
);
|
||||
|
||||
return !measurement;
|
||||
});
|
||||
|
||||
// Return the found measurement object or undefined if not found
|
||||
return measurement;
|
||||
}
|
||||
|
||||
lesionExistsAtTimepoints(lesionNamingNumber, toolGroupId, timepointIds) {
|
||||
// Retrieve all the data for the given tool group (e.g. 'targets')
|
||||
const measurementsAtTimepoint = this.fetch(toolGroupId, tool =>
|
||||
timepointIds.includes(tool.timepointId)
|
||||
);
|
||||
|
||||
// Return whether or not any lesion at this timepoint has the same lesionNamingNumber
|
||||
return !!measurementsAtTimepoint.find(
|
||||
m => m.lesionNamingNumber === lesionNamingNumber
|
||||
);
|
||||
}
|
||||
|
||||
isNewLesionsMeasurement(measurementData) {
|
||||
if (!measurementData) {
|
||||
return;
|
||||
}
|
||||
|
||||
const toolConfig = MeasurementApi.getToolConfiguration(
|
||||
measurementData.toolType
|
||||
);
|
||||
const toolType = toolConfig.tool.parentTool || measurementData.toolType;
|
||||
const { timepointApi } = this;
|
||||
const currentMeasurement =
|
||||
this.tools[toolType].find(tool => tool._id === measurementData._id) || {};
|
||||
const timepointId =
|
||||
currentMeasurement.timepointId || measurementData.timepointId;
|
||||
const lesionNamingNumber =
|
||||
currentMeasurement.lesionNamingNumber ||
|
||||
measurementData.lesionNamingNumber;
|
||||
|
||||
// Stop here if the needed information is not set
|
||||
if (!timepointApi || !timepointId || !toolConfig) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { toolGroupId } = toolConfig;
|
||||
const current = timepointApi.timepoints.find(
|
||||
tp => tp.timepointId === timepointId
|
||||
);
|
||||
const initialTimepointIds = timepointApi.initialTimepointIds();
|
||||
|
||||
// Stop here if there's no initial timepoint, or if the current is any initial
|
||||
if (
|
||||
!initialTimepointIds ||
|
||||
initialTimepointIds.length < 1 ||
|
||||
initialTimepointIds.some(
|
||||
initialtpid => initialtpid === current.timepointId
|
||||
)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return (
|
||||
this.lesionExistsAtTimepoints(
|
||||
lesionNamingNumber,
|
||||
toolGroupId,
|
||||
initialTimepointIds
|
||||
) === false
|
||||
);
|
||||
}
|
||||
|
||||
calculateLesionMaxMeasurementNumber(groupId, filter) {
|
||||
let measurements = [];
|
||||
if (groupId) {
|
||||
// Get the measurements of the group
|
||||
measurements = this.toolGroups[groupId] || [];
|
||||
} else {
|
||||
// Get all measurements of all groups
|
||||
measurements = Object.keys(this.toolGroups).reduce((acc, val) => {
|
||||
acc.push(...this.toolGroups[val]);
|
||||
return acc;
|
||||
}, []);
|
||||
}
|
||||
|
||||
const sortedMeasurements = measurements.filter(filter).sort((tp1, tp2) => {
|
||||
return tp1.measurementNumber < tp2.measurementNumber ? 1 : -1;
|
||||
});
|
||||
|
||||
for (let i = 0; i < sortedMeasurements.length; i++) {
|
||||
const toolGroupMeasurement = sortedMeasurements[i];
|
||||
const measurement = this.tools[toolGroupMeasurement.toolId].find(
|
||||
tool => tool._id === toolGroupMeasurement.toolItemId
|
||||
);
|
||||
const isNew = this.isNewLesionsMeasurement(measurement);
|
||||
if (!isNew) {
|
||||
return measurement.measurementNumber;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
calculateNewLesionMaxMeasurementNumber(groupId, filter) {
|
||||
const sortedMeasurements = this.toolGroups[groupId]
|
||||
.filter(filter)
|
||||
.sort((tp1, tp2) => {
|
||||
return tp1.measurementNumber < tp2.measurementNumber ? 1 : -1;
|
||||
});
|
||||
|
||||
for (let i = 0; i < sortedMeasurements.length; i++) {
|
||||
const toolGroupMeasurement = sortedMeasurements[i];
|
||||
const measurement = this.tools[toolGroupMeasurement.toolId].find(
|
||||
tool => tool._id === toolGroupMeasurement.toolItemId
|
||||
);
|
||||
const isNew = this.isNewLesionsMeasurement(measurement);
|
||||
if (isNew) {
|
||||
return measurement.measurementNumber;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
calculateMeasurementNumber(measurement) {
|
||||
const toolGroupId = this.toolsGroupsMap[measurement.toolType];
|
||||
|
||||
const filter = tool => tool._id !== measurement._id;
|
||||
|
||||
const isNew = this.isNewLesionsMeasurement(measurement);
|
||||
|
||||
if (isNew) {
|
||||
const maxTargetMeasurementNumber = this.calculateLesionMaxMeasurementNumber(
|
||||
'targets',
|
||||
filter
|
||||
);
|
||||
const maxNonTargetMeasurementNumber = this.calculateLesionMaxMeasurementNumber(
|
||||
'nonTargets',
|
||||
filter
|
||||
);
|
||||
const maxNewTargetMeasurementNumber = this.calculateNewLesionMaxMeasurementNumber(
|
||||
'targets',
|
||||
filter
|
||||
);
|
||||
if (toolGroupId === 'targets') {
|
||||
return Math.max(
|
||||
maxTargetMeasurementNumber,
|
||||
maxNonTargetMeasurementNumber,
|
||||
maxNewTargetMeasurementNumber
|
||||
);
|
||||
} else if (toolGroupId === 'nonTargets') {
|
||||
const maxNewNonTargetMeasurementNumber = this.calculateNewLesionMaxMeasurementNumber(
|
||||
'nonTargets',
|
||||
filter
|
||||
);
|
||||
return Math.max(
|
||||
maxTargetMeasurementNumber,
|
||||
maxNonTargetMeasurementNumber,
|
||||
maxNewTargetMeasurementNumber,
|
||||
maxNewNonTargetMeasurementNumber
|
||||
);
|
||||
}
|
||||
} else {
|
||||
const maxTargetMeasurementNumber = this.calculateLesionMaxMeasurementNumber(
|
||||
'targets',
|
||||
filter
|
||||
);
|
||||
if (toolGroupId === 'targets') {
|
||||
return maxTargetMeasurementNumber;
|
||||
} else if (toolGroupId === 'nonTargets') {
|
||||
const maxNonTargetMeasurementNumber = this.calculateLesionMaxMeasurementNumber(
|
||||
'nonTargets',
|
||||
filter
|
||||
);
|
||||
return Math.max(
|
||||
maxTargetMeasurementNumber,
|
||||
maxNonTargetMeasurementNumber
|
||||
);
|
||||
} else {
|
||||
return this.calculateLesionMaxMeasurementNumber(null, filter);
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
getPreviousMeasurement(measurementData) {
|
||||
if (!measurementData) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { timepointId, toolType, lesionNamingNumber } = measurementData;
|
||||
if (!timepointId || !toolType || !lesionNamingNumber) {
|
||||
return;
|
||||
}
|
||||
|
||||
const toolGroupId = this.toolsGroupsMap[measurementData.toolType];
|
||||
|
||||
// TODO: Remove TrialPatientLocationUid from here and override it somehow
|
||||
// by dependant applications. Here we should use the location attribute instead of the uid
|
||||
let filter;
|
||||
const uid =
|
||||
measurementData.additionalData &&
|
||||
measurementData.additionalData.TrialPatientLocationUid;
|
||||
if (uid) {
|
||||
filter = tool =>
|
||||
tool._id !== measurementData._id &&
|
||||
tool.additionalData &&
|
||||
tool.additionalData.TrialPatientLocationUid === uid;
|
||||
} else {
|
||||
filter = tool =>
|
||||
tool._id !== measurementData._id &&
|
||||
tool.lesionNamingNumber === lesionNamingNumber;
|
||||
}
|
||||
|
||||
const childToolTypes = this.toolGroupTools[toolGroupId];
|
||||
for (let i = 0; i < childToolTypes.length; i++) {
|
||||
const childToolType = childToolTypes[i];
|
||||
const toolCollection = this.tools[childToolType];
|
||||
const item = toolCollection.find(filter);
|
||||
|
||||
if (item) {
|
||||
return item;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
hasDuplicateMeasurementNumber(measurementData) {
|
||||
if (!measurementData) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { toolType, measurementNumber } = measurementData;
|
||||
if (!toolType || !measurementNumber) {
|
||||
return;
|
||||
}
|
||||
|
||||
const filter = tool =>
|
||||
tool._id !== measurementData._id &&
|
||||
tool.measurementNumber === measurementData.measurementNumber;
|
||||
|
||||
return configuration.measurementTools
|
||||
.filter(toolGroup => toolGroup.id !== 'temp')
|
||||
.some(toolGroup => {
|
||||
if (this.toolGroups[toolGroup.id].find(filter)) {
|
||||
return true;
|
||||
}
|
||||
return toolGroup.childTools.some(tool => {
|
||||
if (this.tools[tool.id].find(filter)) {
|
||||
return true;
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
updateNumbering(collectionToUpdate, propertyFilter, propertyName, increment) {
|
||||
collectionToUpdate.filter(propertyFilter).forEach(item => {
|
||||
item[propertyName] += increment;
|
||||
});
|
||||
}
|
||||
|
||||
updateMeasurementNumberForAllMeasurements(measurement, increment) {
|
||||
const filter = tool =>
|
||||
tool._id !== measurement._id &&
|
||||
tool.measurementNumber >= measurement.measurementNumber;
|
||||
|
||||
configuration.measurementTools
|
||||
.filter(toolGroup => toolGroup.id !== 'temp')
|
||||
.forEach(toolGroup => {
|
||||
this.updateNumbering(
|
||||
this.toolGroups[toolGroup.id],
|
||||
filter,
|
||||
'measurementNumber',
|
||||
increment
|
||||
);
|
||||
|
||||
toolGroup.childTools.forEach(tool => {
|
||||
this.updateNumbering(
|
||||
this.tools[tool.id],
|
||||
filter,
|
||||
'measurementNumber',
|
||||
increment
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
addMeasurement(toolType, measurement) {
|
||||
const toolGroup = this.toolsGroupsMap[toolType];
|
||||
const groupCollection = this.toolGroups[toolGroup];
|
||||
const collection = this.tools[toolType];
|
||||
|
||||
// Get the related measurement by the measurement number and use its location if defined
|
||||
const relatedMeasurement = collection.find(
|
||||
t =>
|
||||
t.lesionNamingNumber === measurement.lesionNamingNumber &&
|
||||
t.toolType === measurement.toolType
|
||||
);
|
||||
|
||||
// Use the related measurement location if found and defined
|
||||
if (relatedMeasurement && relatedMeasurement.location) {
|
||||
measurement.location = relatedMeasurement.location;
|
||||
}
|
||||
|
||||
// Use the related measurement description if found and defined
|
||||
if (relatedMeasurement && relatedMeasurement.description) {
|
||||
measurement.description = relatedMeasurement.description;
|
||||
}
|
||||
|
||||
measurement._id = guid();
|
||||
|
||||
// Get the timepoint
|
||||
let timepoint;
|
||||
if (measurement.studyInstanceUid) {
|
||||
timepoint = this.timepointApi.study(measurement.studyInstanceUid)[0];
|
||||
} else {
|
||||
const { timepointId } = measurement;
|
||||
timepoint = this.timepointApi.timepoints.find(
|
||||
t => t.timepointId === timepointId
|
||||
);
|
||||
}
|
||||
|
||||
// Preventing errors thrown when non-associated (standalone) study is opened...
|
||||
// @TODO: Make sure this logic is correct.
|
||||
if (!timepoint) return;
|
||||
|
||||
// Empty Item is the lesion just added in cornerstoneTools, but does not have measurement data yet
|
||||
const emptyItem = groupCollection.find(
|
||||
groupTool =>
|
||||
!groupTool.toolId && groupTool.timepointId === timepoint.timepointId
|
||||
);
|
||||
|
||||
// Set the timepointId attribute to measurement to make it easier to filter measurements by timepoint
|
||||
measurement.timepointId = timepoint.timepointId;
|
||||
|
||||
// Check if the measurement data is just added by a cornerstone tool and is still empty
|
||||
if (emptyItem) {
|
||||
// Set relevant initial data and measurement number to the measurement
|
||||
measurement.lesionNamingNumber = emptyItem.lesionNamingNumber;
|
||||
measurement.measurementNumber = emptyItem.measurementNumber;
|
||||
|
||||
groupCollection
|
||||
.filter(
|
||||
groupTool =>
|
||||
groupTool.timepointId === timepoint.timepointId &&
|
||||
groupTool.lesionNamingNumber === measurement.lesionNamingNumber
|
||||
)
|
||||
.forEach(groupTool => {
|
||||
groupTool.toolId = tool.id;
|
||||
groupTool.toolItemId = measurement._id;
|
||||
groupTool.createdAt = measurement.createdAt;
|
||||
groupTool.measurementNumber = measurement.measurementNumber;
|
||||
});
|
||||
} else {
|
||||
// Handle measurements not added by cornerstone tools and update its number
|
||||
const measurementsInTimepoint = groupCollection.filter(
|
||||
groupTool => groupTool.timepointId === timepoint.timepointId
|
||||
);
|
||||
measurement.lesionNamingNumber = this.calculateLesionNamingNumber(
|
||||
measurementsInTimepoint
|
||||
);
|
||||
measurement.measurementNumber =
|
||||
measurement.measurementNumber ||
|
||||
this.calculateMeasurementNumber(measurement) + 1;
|
||||
}
|
||||
|
||||
// Define an update object to reflect the changes in the collection
|
||||
const updateObject = {
|
||||
timepointId: timepoint.timepointId,
|
||||
lesionNamingNumber: measurement.lesionNamingNumber,
|
||||
measurementNumber: measurement.measurementNumber,
|
||||
};
|
||||
|
||||
// Find the matched measurement from other timepoints
|
||||
const found = this.getPreviousMeasurement(measurement);
|
||||
|
||||
// Check if a previous related meausurement was found on other timepoints
|
||||
if (found) {
|
||||
// Use the same number as the previous measurement
|
||||
measurement.lesionNamingNumber = found.lesionNamingNumber;
|
||||
measurement.measurementNumber = found.measurementNumber;
|
||||
|
||||
// TODO: Remove TrialPatientLocationUid from here and override it somehow
|
||||
// by dependant applications
|
||||
|
||||
// Change the update object to set the same number, additionalData,
|
||||
// location, label and description to the current measurement
|
||||
updateObject.lesionNamingNumber = found.lesionNamingNumber;
|
||||
updateObject.measurementNumber = found.measurementNumber;
|
||||
updateObject.additionalData = measurement.additionalData || {};
|
||||
updateObject.additionalData.TrialPatientLocationUid =
|
||||
found.additionalData && found.additionalData.TrialPatientLocationUid;
|
||||
updateObject.location = found.location;
|
||||
updateObject.label = found.label;
|
||||
updateObject.description = found.description;
|
||||
updateObject.isSplitLesion = found.isSplitLesion;
|
||||
updateObject.isNodal = found.isNodal;
|
||||
|
||||
const description = getDescription(found, measurement);
|
||||
if (description) {
|
||||
updateObject.description = description;
|
||||
}
|
||||
} else if (this.hasDuplicateMeasurementNumber(measurement)) {
|
||||
// Update measurementNumber for the measurements with masurementNumber greater or equal than
|
||||
// measurementNumber of the added measurement (except the added one)
|
||||
// only if there is another measurement with the same measurementNumber
|
||||
this.updateMeasurementNumberForAllMeasurements(measurement, 1);
|
||||
}
|
||||
|
||||
let addedMeasurement;
|
||||
|
||||
// Upsert the measurement in collection
|
||||
const toolIndex = collection.findIndex(
|
||||
tool => tool._id === measurement._id
|
||||
);
|
||||
if (toolIndex > -1) {
|
||||
addedMeasurement = Object.assign({}, collection[toolIndex], updateObject);
|
||||
collection[toolIndex] = addedMeasurement;
|
||||
} else {
|
||||
addedMeasurement = Object.assign({}, measurement, updateObject);
|
||||
collection.push(addedMeasurement);
|
||||
}
|
||||
|
||||
if (!emptyItem) {
|
||||
// Reflect the entry in the tool group collection
|
||||
groupCollection.push({
|
||||
toolId: toolType,
|
||||
toolItemId: addedMeasurement._id,
|
||||
timepointId: timepoint.timepointId,
|
||||
studyInstanceUid: addedMeasurement.studyInstanceUid,
|
||||
createdAt: addedMeasurement.createdAt,
|
||||
lesionNamingNumber: addedMeasurement.lesionNamingNumber,
|
||||
measurementNumber: addedMeasurement.measurementNumber,
|
||||
});
|
||||
}
|
||||
|
||||
// Let others know that the measurements are updated
|
||||
this.onMeasurementsUpdated();
|
||||
|
||||
// TODO: Enable reactivity
|
||||
// this.timepointChanged.set(timepoint.timepointId);
|
||||
|
||||
return addedMeasurement;
|
||||
}
|
||||
|
||||
updateMeasurement(toolType, measurement) {
|
||||
const collection = this.tools[toolType];
|
||||
|
||||
const toolIndex = collection.findIndex(
|
||||
tool => tool._id === measurement._id
|
||||
);
|
||||
if (toolIndex < 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
collection[toolIndex] = Object.assign({}, measurement);
|
||||
|
||||
// Let others know that the measurements are updated
|
||||
this.onMeasurementsUpdated();
|
||||
|
||||
// TODO: Enable reactivity
|
||||
// this.timepointChanged.set(timepoint.timepointId);
|
||||
}
|
||||
|
||||
onMeasurementRemoved(toolType, measurement) {
|
||||
const { lesionNamingNumber, measurementNumber } = measurement;
|
||||
|
||||
const toolGroupId = this.toolsGroupsMap[toolType];
|
||||
const groupCollection = this.toolGroups[toolGroupId];
|
||||
|
||||
const groupIndex = groupCollection.findIndex(
|
||||
group => group.toolItemId === measurement._id
|
||||
);
|
||||
if (groupIndex < 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Remove the deleted measurement only in its timepoint from the collection
|
||||
groupCollection.splice(groupIndex, 1);
|
||||
|
||||
// Check which timepoints have the deleted measurement
|
||||
const timepointsWithDeletedMeasurement = groupCollection
|
||||
.filter(tool => tool.measurementNumber === measurementNumber)
|
||||
.map(tool => tool.timepointId);
|
||||
|
||||
// Update lesionNamingNumber and measurementNumber only if there is no timepoint with that measurement
|
||||
if (timepointsWithDeletedMeasurement.length < 1) {
|
||||
// Decrease lesionNamingNumber of all measurements with lesionNamingNumber greater than lesionNamingNumber of the deleted measurement by 1
|
||||
const lesionNamingNumberFilter = tool =>
|
||||
tool.lesionNamingNumber >= lesionNamingNumber;
|
||||
this.updateNumbering(
|
||||
groupCollection,
|
||||
lesionNamingNumberFilter,
|
||||
'lesionNamingNumber',
|
||||
-1
|
||||
);
|
||||
|
||||
const toolGroup = configuration.measurementTools.find(
|
||||
tGroup => tGroup.id === toolGroupId
|
||||
);
|
||||
if (toolGroup && toolGroup.childTools) {
|
||||
toolGroup.childTools.forEach(childTool => {
|
||||
const collection = this.tools[childTool.id];
|
||||
this.updateNumbering(
|
||||
collection,
|
||||
lesionNamingNumberFilter,
|
||||
'lesionNamingNumber',
|
||||
-1
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
// Decrease measurementNumber of all measurements with measurementNumber greater than measurementNumber of the deleted measurement by 1
|
||||
this.updateMeasurementNumberForAllMeasurements(measurement, -1);
|
||||
}
|
||||
|
||||
// Synchronize the new tool data
|
||||
this.syncMeasurementsAndToolData();
|
||||
|
||||
// Let others know that the measurements are updated
|
||||
this.onMeasurementsUpdated();
|
||||
|
||||
// TODO: Enable reactivity
|
||||
// this.timepointChanged.set(timepoint.timepointId);
|
||||
}
|
||||
|
||||
syncMeasurementsAndToolData() {
|
||||
configuration.measurementTools.forEach(toolGroup => {
|
||||
// Skip the tool groups excluded from case progress
|
||||
if (!MeasurementApi.isToolIncluded(toolGroup)) {
|
||||
return;
|
||||
}
|
||||
toolGroup.childTools.forEach(tool => {
|
||||
// Skip the tools excluded from case progress
|
||||
if (!MeasurementApi.isToolIncluded(tool)) {
|
||||
return;
|
||||
}
|
||||
const measurements = this.tools[tool.id];
|
||||
measurements.forEach(measurement => {
|
||||
MeasurementApi.syncMeasurementAndToolData(measurement);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
deleteMeasurements(toolType, measurementTypeId, filter) {
|
||||
const filterKeys = Object.keys(filter);
|
||||
const groupCollection = this.toolGroups[measurementTypeId];
|
||||
|
||||
// Stop here if it is a temporary toolGroups
|
||||
if (!groupCollection) return;
|
||||
|
||||
// Get the entries information before removing them
|
||||
const groupItems = groupCollection.filter(toolGroup => {
|
||||
return filterKeys.every(
|
||||
filterKey => toolGroup[filterKey] === filter[filterKey]
|
||||
);
|
||||
});
|
||||
const entries = [];
|
||||
groupItems.forEach(groupItem => {
|
||||
if (!groupItem.toolId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const collection = this.tools[groupItem.toolId];
|
||||
const toolIndex = collection.findIndex(
|
||||
tool => tool._id === groupItem.toolItemId
|
||||
);
|
||||
if (toolIndex > -1) {
|
||||
entries.push(collection[toolIndex]);
|
||||
collection.splice(toolIndex, 1);
|
||||
}
|
||||
});
|
||||
|
||||
// Stop here if no entries were found
|
||||
if (!entries.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
// If the filter doesn't have the measurement number, get it from the first entry
|
||||
const lesionNamingNumber =
|
||||
filter.lesionNamingNumber || entries[0].lesionNamingNumber;
|
||||
|
||||
// Synchronize the new data with cornerstone tools
|
||||
const toolState = cornerstoneTools.globalImageIdSpecificToolStateManager.saveToolState();
|
||||
|
||||
entries.forEach(entry => {
|
||||
const measurementsData = [];
|
||||
const { tool } = MeasurementApi.getToolConfiguration(entry.toolType);
|
||||
if (Array.isArray(tool.childTools)) {
|
||||
tool.childTools.forEach(key => {
|
||||
const childMeasurement = entry[key];
|
||||
if (!childMeasurement) return;
|
||||
measurementsData.push(childMeasurement);
|
||||
});
|
||||
} else {
|
||||
measurementsData.push(entry);
|
||||
}
|
||||
|
||||
measurementsData.forEach(measurementData => {
|
||||
const { imagePath, toolType } = measurementData;
|
||||
const imageId = getImageIdForImagePath(imagePath);
|
||||
if (imageId && toolState[imageId]) {
|
||||
const toolData = toolState[imageId][toolType];
|
||||
const measurementEntries = toolData && toolData.data;
|
||||
const measurementEntry = measurementEntries.find(
|
||||
mEntry => mEntry._id === entry._id
|
||||
);
|
||||
if (measurementEntry) {
|
||||
const index = measurementEntries.indexOf(measurementEntry);
|
||||
measurementEntries.splice(index, 1);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
this.onMeasurementRemoved(toolType, entry);
|
||||
});
|
||||
|
||||
cornerstoneTools.globalImageIdSpecificToolStateManager.restoreToolState(
|
||||
toolState
|
||||
);
|
||||
|
||||
// Synchronize the updated measurements with Cornerstone Tools
|
||||
// toolData to make sure the displayed measurements show 'Target X' correctly
|
||||
const syncFilter = Object.assign({}, filter);
|
||||
delete syncFilter.timepointId;
|
||||
delete syncFilter.lesionNamingNumber;
|
||||
|
||||
const syncFilterKeys = Object.keys(syncFilter);
|
||||
|
||||
const toolTypes = [...new Set(entries.map(entry => entry.toolType))];
|
||||
toolTypes.forEach(toolType => {
|
||||
const collection = this.tools[toolType];
|
||||
collection
|
||||
.filter(tool => {
|
||||
return (
|
||||
tool.lesionNamingNumber > lesionNamingNumber - 1 &&
|
||||
syncFilterKeys.every(
|
||||
syncFilterKey => tool[syncFilterKey] === filter[syncFilterKey]
|
||||
)
|
||||
);
|
||||
})
|
||||
.forEach(measurement => {
|
||||
MeasurementApi.syncMeasurementAndToolData(measurement);
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,576 @@
|
||||
import log from '../../log';
|
||||
|
||||
const configuration = {};
|
||||
|
||||
const TIMEPOINT_TYPE_NAMES = {
|
||||
prebaseline: 'Pre-Baseline',
|
||||
baseline: 'Baseline',
|
||||
followup: 'Follow-up',
|
||||
};
|
||||
|
||||
export default class TimepointApi {
|
||||
static Instance;
|
||||
|
||||
static setConfiguration(config) {
|
||||
Object.assign(configuration, config);
|
||||
}
|
||||
|
||||
static getConfiguration() {
|
||||
return configuration;
|
||||
}
|
||||
|
||||
constructor(currentTimepointId, options = {}) {
|
||||
if (TimepointApi.Instance) {
|
||||
TimepointApi.Instance.initialize(currentTimepointId, options);
|
||||
return TimepointApi.Instance;
|
||||
}
|
||||
|
||||
this.initialize(currentTimepointId, options);
|
||||
TimepointApi.Instance = this;
|
||||
}
|
||||
|
||||
initialize(currentTimepointId, options = {}) {
|
||||
this.currentTimepointId = currentTimepointId;
|
||||
this.comparisonTimepointKey = options.comparisonTimepointKey || 'baseline';
|
||||
this.options = options;
|
||||
this.timepoints = [];
|
||||
}
|
||||
|
||||
onTimepointsUpdated() {
|
||||
if (typeof this.options.onTimepointsUpdated !== 'function') {
|
||||
log.warn('Timepoints update callback is not defined');
|
||||
return;
|
||||
}
|
||||
|
||||
this.options.onTimepointsUpdated(Object.assign([], this.timepoints));
|
||||
}
|
||||
|
||||
calculateVisitNumber(timepoint) {
|
||||
// Retrieve all of the relevant follow-up timepoints for this patient
|
||||
const sortedTimepoints = this.timepoints.sort((tp1, tp2) => {
|
||||
return tp1.visitDate > tp2.visitDate ? 1 : -1;
|
||||
});
|
||||
const filteredTimepoints = sortedTimepoints.find(
|
||||
tp =>
|
||||
tp.patientId === timepoint.patientId &&
|
||||
tp.timepointType === timepoint.timepointType
|
||||
);
|
||||
|
||||
// Create an array of just timepointIds, so we can use indexOf
|
||||
// on it to find the current timepoint's relative position
|
||||
const timepointIds = filteredTimepoints.map(
|
||||
timepoint => timepoint.timepointId
|
||||
);
|
||||
|
||||
// Calculate the index of the current timepoint in the array of all
|
||||
// relevant follow-up timepoints
|
||||
const visitNumber = timepointIds.indexOf(timepoint.timepointId) + 1;
|
||||
|
||||
// If visitNumber is 0, it means that the current timepoint was not in the list
|
||||
if (!visitNumber) {
|
||||
throw new Error(
|
||||
'Current timepoint was not in the list of relevant timepoints?'
|
||||
);
|
||||
}
|
||||
|
||||
return visitNumber;
|
||||
}
|
||||
|
||||
retrieveTimepoints(filter) {
|
||||
const retrievalFn = configuration.dataExchange.retrieve;
|
||||
if (typeof retrievalFn !== 'function') {
|
||||
log.error('Timepoint retrieval function has not been configured.');
|
||||
return;
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
retrievalFn(filter)
|
||||
.then(timepointData => {
|
||||
log.info('Timepoint data retrieval');
|
||||
|
||||
timepointData.forEach(timepoint => {
|
||||
const timepointIndex = this.timepoints.findIndex(
|
||||
tp => tp.timepointId === timepoint.timepointId
|
||||
);
|
||||
if (timepointIndex < 0) {
|
||||
this.timepoints.push(timepoint);
|
||||
} else {
|
||||
this.timepoints[timepointIndex] = timepoint;
|
||||
}
|
||||
});
|
||||
|
||||
// Let others know that the timepoints are updated
|
||||
this.onTimepointsUpdated();
|
||||
|
||||
resolve();
|
||||
})
|
||||
.catch(reason => {
|
||||
log.error(`Timepoint retrieval function failed: ${reason}`);
|
||||
reject(reason);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
storeTimepoints() {
|
||||
const storeFn = configuration.dataExchange.store;
|
||||
if (typeof storeFn !== 'function') {
|
||||
log.error('Timepoint store function has not been configured.');
|
||||
return;
|
||||
}
|
||||
|
||||
log.info('Preparing to store timepoints');
|
||||
log.info(JSON.stringify(this.timepoints, null, 2));
|
||||
|
||||
storeFn(this.timepoints).then(() =>
|
||||
log.info('Timepoint storage completed')
|
||||
);
|
||||
}
|
||||
|
||||
disassociateStudy(timepointIds, studyInstanceUid) {
|
||||
const disassociateFn = configuration.dataExchange.disassociate;
|
||||
if (typeof disassociateFn !== 'function') {
|
||||
log.error('Study disassociate function has not been configured.');
|
||||
return;
|
||||
}
|
||||
|
||||
disassociateFn(timepointIds, studyInstanceUid).then(() => {
|
||||
log.info('Disassociation completed');
|
||||
|
||||
this.timepoints = [];
|
||||
this.retrieveTimepoints({});
|
||||
});
|
||||
}
|
||||
|
||||
removeTimepoint(timepointId) {
|
||||
const removeFn = configuration.dataExchange.remove;
|
||||
if (typeof removeFn !== 'function') {
|
||||
log.error('Timepoint remove function has not been configured.');
|
||||
return;
|
||||
}
|
||||
|
||||
const timepointData = {
|
||||
timepointId,
|
||||
};
|
||||
|
||||
log.info('Preparing to remove timepoint');
|
||||
log.info(JSON.stringify(timepointData, null, 2));
|
||||
|
||||
removeFn(timepointData).then(() => {
|
||||
log.info('Timepoint removal completed');
|
||||
|
||||
const tpIndex = this.timepoints.findIndex(
|
||||
tp => tp.timepointId === timepointId
|
||||
);
|
||||
if (tpIndex > -1) {
|
||||
this.timepoints.splice(tpIndex, 1);
|
||||
}
|
||||
|
||||
// Let others know that the timepoints are updated
|
||||
this.onTimepointsUpdated();
|
||||
});
|
||||
}
|
||||
|
||||
updateTimepoint(timepointId, query) {
|
||||
const updateFn = configuration.dataExchange.update;
|
||||
if (typeof updateFn !== 'function') {
|
||||
log.error('Timepoint update function has not been configured.');
|
||||
return;
|
||||
}
|
||||
|
||||
const timepointData = {
|
||||
timepointId,
|
||||
};
|
||||
|
||||
log.info('Preparing to update timepoint');
|
||||
log.info(JSON.stringify(timepointData, null, 2));
|
||||
log.info(JSON.stringify(query, null, 2));
|
||||
|
||||
updateFn(timepointData, query).then(() => {
|
||||
log.info('Timepoint updated completed');
|
||||
|
||||
const tpIndex = this.timepoints.findIndex(
|
||||
tp => tp.timepointId === timepointId
|
||||
);
|
||||
if (tpIndex > -1) {
|
||||
this.timepoints[tpIndex] = Object.assign(
|
||||
{},
|
||||
this.timepoints[tpIndex],
|
||||
query
|
||||
);
|
||||
}
|
||||
|
||||
// Let others know that the timepoints are updated
|
||||
this.onTimepointsUpdated();
|
||||
});
|
||||
}
|
||||
|
||||
// Return all timepoints
|
||||
all(filter) {
|
||||
let timepointsToReturn;
|
||||
if (filter) {
|
||||
timepointsToReturn = this.timepoints.filter(filter);
|
||||
} else {
|
||||
timepointsToReturn = this.timepoints;
|
||||
}
|
||||
|
||||
return timepointsToReturn.sort((tp1, tp2) => {
|
||||
return tp1.visitDate < tp2.visitDate ? 1 : -1;
|
||||
});
|
||||
}
|
||||
|
||||
// Return only the current timepoint
|
||||
current() {
|
||||
return this.timepoints.find(
|
||||
tp => tp.timepointId === this.currentTimepointId
|
||||
);
|
||||
}
|
||||
|
||||
lock() {
|
||||
const tpIndex = this.timepoints.findIndex(
|
||||
tp => tp.timepointId === this.currentTimepointId
|
||||
);
|
||||
if (tpIndex < 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.timepoints[tpIndex] = Object.assign({}, this.timepoints[tpIndex], {
|
||||
locked: true,
|
||||
});
|
||||
}
|
||||
|
||||
// Return the prior timepoint
|
||||
prior() {
|
||||
const current = this.current();
|
||||
if (!current) {
|
||||
return;
|
||||
}
|
||||
|
||||
return this.all().find(tp => tp.visitDate < current.visitDate);
|
||||
}
|
||||
|
||||
// Return only the current and prior timepoints
|
||||
currentAndPrior() {
|
||||
const timepoints = [];
|
||||
|
||||
const current = this.current();
|
||||
if (current) {
|
||||
timepoints.push(current);
|
||||
}
|
||||
|
||||
const prior = this.prior();
|
||||
if (current && prior && prior.timepointId !== current.timepointId) {
|
||||
timepoints.push(prior);
|
||||
}
|
||||
|
||||
return timepoints;
|
||||
}
|
||||
|
||||
// Return the current and the comparison timepoints
|
||||
currentAndComparison(comparisonTimepointKey = this.comparisonTimepointKey) {
|
||||
const current = this.current();
|
||||
const comparisonTimepoint = this.comparison(comparisonTimepointKey);
|
||||
const timepoints = [current];
|
||||
|
||||
if (
|
||||
comparisonTimepoint &&
|
||||
!timepoints.find(tp => tp.timepointId === comparisonTimepoint.timepointId)
|
||||
) {
|
||||
timepoints.push(comparisonTimepoint);
|
||||
}
|
||||
|
||||
return timepoints;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if there are 2 or more baseline timepoints before and at the current timepoint, otherwise false
|
||||
* @returns {boolean}
|
||||
*/
|
||||
isRebaseline(timepointId) {
|
||||
const current = timepointId
|
||||
? this.timepoints.find(tp => tp.timepointId === timepointId)
|
||||
: this.current();
|
||||
if (!current) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const baselines = this.timepoints.filter(
|
||||
tp => tp.timepointType === 'baseline' && tp.visitDate <= current.visitDate
|
||||
);
|
||||
return baselines.length > 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the next (closest future) baseline after current timepoint
|
||||
* @returns {*}
|
||||
*/
|
||||
nextBaselineAfterCurrent() {
|
||||
let current = this.current();
|
||||
|
||||
// Get all next timepoints newer than the current timepoint sorted by visitDate ascending
|
||||
const sortedTimepoints = this.timepoints.sort((tp1, tp2) => {
|
||||
return tp1.visitDate > tp2.visitDate ? 1 : -1;
|
||||
});
|
||||
return sortedTimepoints.find(
|
||||
tp => tp.visitDate > current.visitDate && tp.timepointType === 'baseline'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the current timepoint id
|
||||
* @param timepointId
|
||||
*/
|
||||
setCurrentTimepointId(timepointId) {
|
||||
this.currentTimepointId = timepointId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the comparison timepoint that overrides the default comparison timepoint (called based on user selection in a viewport)
|
||||
* @param timepoint
|
||||
*/
|
||||
setUserComparison(timepoint) {
|
||||
this.userComparison = timepoint;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return only the comparison timepoint
|
||||
* @param {String} [comparisonTimepointKey]
|
||||
* @return {*}
|
||||
*/
|
||||
comparison(comparisonTimepointKey = this.comparisonTimepointKey) {
|
||||
// Return the comparison timepoint set by user if exists
|
||||
if (this.userComparison) {
|
||||
return this.userComparison;
|
||||
}
|
||||
|
||||
const current = this.current();
|
||||
if (!current) {
|
||||
return;
|
||||
}
|
||||
|
||||
// If current timepoint is prebaseline, the first (closest future) BL after current is comparison regardless of default comparison timepoint
|
||||
if (current.timepointType === 'prebaseline') {
|
||||
const nextBaselineAfterCurrent = this.nextBaselineAfterCurrent();
|
||||
// If there is a next baseline, make it comparison, otherwise comparison is done by default comparison timepoint
|
||||
if (nextBaselineAfterCurrent) {
|
||||
return nextBaselineAfterCurrent;
|
||||
}
|
||||
}
|
||||
|
||||
// If current timepoint is baseline, the prior is comparison if exists regardless of default comparison timepoint
|
||||
if (current.timepointType === 'baseline') {
|
||||
const prior = this.prior();
|
||||
if (prior) {
|
||||
return prior;
|
||||
}
|
||||
}
|
||||
|
||||
const comparison = this[comparisonTimepointKey]();
|
||||
|
||||
// Do not return a comparison if it would be identical to
|
||||
// the current.
|
||||
if (comparison && comparison.timepointId === current.timepointId) {
|
||||
return;
|
||||
}
|
||||
|
||||
return comparison;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the latest initial (prebaseline or baseline) timepoint after current and before the next followup timepoint
|
||||
* @returns {*}
|
||||
*/
|
||||
latestInitialTimepointAfterCurrent() {
|
||||
let currentTimepoint = this.current();
|
||||
|
||||
// Skip if the current timepoint is FU since there is no initial timepoint after follow-up
|
||||
if (currentTimepoint.timepointType === 'followup') {
|
||||
return;
|
||||
}
|
||||
|
||||
// Get all next timepoints newer than the current timepoint sorted by visitDate ascending
|
||||
const sortedTimepoints = this.timepoints.sort((tp1, tp2) => {
|
||||
return tp1.visitDate > tp2.visitDate ? 1 : -1;
|
||||
});
|
||||
const allNextTimepoints = sortedTimepoints.filter(
|
||||
tp => tp.visitDate > currentTimepoint.visitDate
|
||||
);
|
||||
|
||||
const nextFollowupIndex = allNextTimepoints.findIndex(
|
||||
tp => tp.timepointType === 'followup'
|
||||
);
|
||||
const latestInitialBeforeNextFUIndex = nextFollowupIndex - 1;
|
||||
|
||||
if (latestInitialBeforeNextFUIndex < 0) {
|
||||
// There is no FU and all next timepoints are initial, so return the last one
|
||||
return allNextTimepoints[allNextTimepoints.length - 1];
|
||||
}
|
||||
|
||||
// Return the latest initial timepoint before the next FU
|
||||
return allNextTimepoints[latestInitialBeforeNextFUIndex];
|
||||
}
|
||||
|
||||
/**
|
||||
* Return timepoint ids of initial timepoints which are prebaseline and baseline
|
||||
* @returns {*}
|
||||
*/
|
||||
initialTimepointIds() {
|
||||
let timepointToCheck = this.current();
|
||||
|
||||
// If the current timepoint is PBL or BL, then get the recent PBL/BL of the current timepoint by its first FU
|
||||
// If it does not exist, then there is no newer initial timepoint, so the current timepoint is used to determine initial timepoint ids
|
||||
if (
|
||||
timepointToCheck.timepointType === 'prebaseline' ||
|
||||
timepointToCheck.timepointType === 'baseline'
|
||||
) {
|
||||
timepointToCheck =
|
||||
this.latestInitialTimepointAfterCurrent() || timepointToCheck;
|
||||
}
|
||||
|
||||
const visitDateToCheck = timepointToCheck.visitDate;
|
||||
|
||||
const preBaselineTimepoints =
|
||||
this.timepoints.filter(
|
||||
tp =>
|
||||
tp.timepointType === 'prebaseline' && tp.visitDate <= visitDateToCheck
|
||||
) || [];
|
||||
const preBaselineTimepointIds = preBaselineTimepoints.map(
|
||||
timepoint => timepoint.timepointId
|
||||
);
|
||||
|
||||
const baselineTimepoints =
|
||||
this.timepoints.filter(
|
||||
tp =>
|
||||
tp.timepointType === 'baseline' && tp.visitDate <= visitDateToCheck
|
||||
) || [];
|
||||
const baselineTimepointIds = baselineTimepoints.map(
|
||||
timepoint => timepoint.timepointId
|
||||
);
|
||||
|
||||
return preBaselineTimepointIds.concat(baselineTimepointIds);
|
||||
}
|
||||
|
||||
// Return only the baseline timepoint
|
||||
baseline() {
|
||||
const currentVisitDate = this.current().visitDate;
|
||||
return this.all().find(
|
||||
tp => tp.timepointType === 'baseline' && tp.visitDate <= currentVisitDate
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return only the nadir timepoint. Must be prior to the current timepoint
|
||||
* @return {any}
|
||||
*/
|
||||
nadir() {
|
||||
const current = this.current();
|
||||
const nadir = this.all().find(
|
||||
tp =>
|
||||
tp.timepointId !== current.timepointId &&
|
||||
tp.timepointKey === 'nadir' &&
|
||||
tp.visitDate <= current.visitDate
|
||||
);
|
||||
|
||||
// If we have found a nadir, return that
|
||||
if (nadir) {
|
||||
return nadir;
|
||||
}
|
||||
|
||||
// Otherwise, return the most recent baseline
|
||||
// This should only happen if we are only at FU1,
|
||||
// so the baseline is the nadir.
|
||||
return this.baseline();
|
||||
}
|
||||
|
||||
// Return only the key timepoints (current, prior, nadir and baseline)
|
||||
key() {
|
||||
const result = [this.current()];
|
||||
const prior = this.prior();
|
||||
const nadir = this.nadir();
|
||||
const baseline = this.baseline();
|
||||
|
||||
const resultIncludes = timepoint =>
|
||||
!!result.find(x => x.timepointId === timepoint.timepointId);
|
||||
|
||||
if (prior && resultIncludes(prior) === false) {
|
||||
result.push(prior);
|
||||
}
|
||||
|
||||
if (nadir && resultIncludes(nadir) === false) {
|
||||
result.push(nadir);
|
||||
}
|
||||
|
||||
if (baseline && resultIncludes(baseline) === false) {
|
||||
result.push(baseline);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// Return only the timepoints for the given study
|
||||
study(studyInstanceUid) {
|
||||
return this.all().filter(timepoint =>
|
||||
timepoint.studyInstanceUids.includes(studyInstanceUid)
|
||||
);
|
||||
}
|
||||
|
||||
// Return the timepoint's name
|
||||
name(timepoint) {
|
||||
const timepointTypeName = TIMEPOINT_TYPE_NAMES[timepoint.timepointType];
|
||||
|
||||
// Check if this is a Baseline timepoint, if it is, return 'Baseline'
|
||||
if (timepoint.timepointType === 'baseline') {
|
||||
return 'Baseline';
|
||||
} else if (timepoint.visitNumber) {
|
||||
return `${timepointTypeName} ${timepoint.visitNumber}`;
|
||||
}
|
||||
|
||||
const visitNumber = this.calculateVisitNumber(timepoint);
|
||||
|
||||
// Return the timepoint name as 'Follow-up N'
|
||||
return `${timepointTypeName} ${visitNumber}`;
|
||||
}
|
||||
|
||||
// Build the timepoint title based on its date
|
||||
title(timepoint) {
|
||||
const timepointName = this.name(timepoint);
|
||||
|
||||
const all = this.all();
|
||||
let index = -1;
|
||||
let currentIndex = null;
|
||||
for (let i = 0; i < all.length; i++) {
|
||||
const currentTimepoint = all[i];
|
||||
|
||||
// Skip the iterations until we can't find the selected timepoint on study list
|
||||
if (this.currentTimepointId === currentTimepoint.timepointId) {
|
||||
currentIndex = 0;
|
||||
}
|
||||
|
||||
if (currentIndex !== null) {
|
||||
index = currentIndex++;
|
||||
}
|
||||
|
||||
// Break the loop if reached the timepoint to get the title
|
||||
if (currentTimepoint.timepointId === timepoint.timepointId) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const states = {
|
||||
0: ['Current'],
|
||||
1: ['Prior'],
|
||||
};
|
||||
const parenthesis = states[index] || [];
|
||||
const nadir = this.nadir();
|
||||
|
||||
if (nadir && nadir.timepointId === timepoint.timepointId) {
|
||||
parenthesis.push('Nadir');
|
||||
}
|
||||
|
||||
let parenthesisText = '';
|
||||
if (parenthesis.length) {
|
||||
parenthesisText = `(${parenthesis.join(', ')})`;
|
||||
}
|
||||
|
||||
return `${timepointName} ${parenthesisText}`;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
import MeasurementApi from './MeasurementApi';
|
||||
import TimepointApi from './TimepointApi';
|
||||
|
||||
export { TimepointApi, MeasurementApi };
|
||||
Reference in new issue
Block a user