Compare commits

..
Author SHA1 Message Date
ohif-bot 77a421cdc0 chore(release): publish [skip ci]
- @ohif/extension-vtk@1.5.2
 - @ohif/core@2.9.2
 - @ohif/viewer@3.11.4
2020-05-04 08:15:19 +00:00
Sanders DeNardiandSanders DeNardi 7033886697 fix: use bit-appropriate array for palette lookup tables (#1698)
Co-authored-by: Sanders DeNardi <sdenardi@summusglobal.com>
2020-05-04 10:13:04 +02:00
ohif-bot 256563d7ee chore(release): publish [skip ci]
- @ohif/viewer@3.11.3
2020-04-29 12:56:38 +00:00
Erik Ziegler f7162ce617 fix: Add IHEInvokeImageDisplay routes back into viewer (#1695) 2020-04-29 08:54:40 -04:00
ohif-bot 027ef4f93c chore(release): publish [skip ci]
- @ohif/extension-dicom-html@1.2.1
 - @ohif/extension-dicom-rt@0.1.1
 - @ohif/extension-dicom-segmentation@0.2.2
 - @ohif/extension-vtk@1.5.1
 - @ohif/core@2.9.1
 - @ohif/viewer@3.11.2
2020-04-28 10:52:19 +00:00
Khalid Williams f09ebbe2e8 chore: cleanup dcmjs imports
* Update imports in /platform

* Update dcmjs imports in /extentions
2020-04-28 06:49:57 -04:00
David Connaughtonandeolasd 51b4e60161 docs: updated deployment section with info for using JSON (#1676)
* update deploy section with non-dicomweb info

* fix typo and add info re. case sensitive json

* Add CORS info and reformat inline links

Co-authored-by: eolasd <pacsradwp@gmail.com>
2020-04-27 16:11:35 -04:00
ohif-bot 08de987711 chore(release): publish [skip ci]
- @ohif/extension-dicom-segmentation@0.2.1
 - @ohif/viewer@3.11.1
2020-04-27 08:41:40 +00:00
Igor Octaviano 20e366ffbd fix: 🐛 Dropdown not updating when selecting segment (#1675)
Observe selectedSegmentation changes to refresh segment list

✅ Closes: #1669
2020-04-27 10:39:11 +02:00
ohif-bot 561911056a chore(release): publish [skip ci]
- @ohif/extension-cornerstone@2.7.0
 - @ohif/extension-dicom-html@1.2.0
 - @ohif/extension-dicom-rt@0.1.0
 - @ohif/extension-dicom-segmentation@0.2.0
 - @ohif/extension-vtk@1.5.0
 - @ohif/core@2.9.0
 - @ohif/viewer@3.11.0
2020-04-24 10:29:19 +00:00
Igor OctavianoandJames Petts 835f64d47a feat: 🎸 Seg jump to slice + show/hide
* Add segment part 2 (jump to frame and visibility toggle)

* Cr updates

* Filter displaysets with images

* feat: 🎸 Seg jump to slice + show/hide

Co-authored-by: James Petts <jamesapetts@gmail.com>
2020-04-24 12:25:05 +02:00
ohif-bot fc40d84092 chore(release): publish [skip ci]
- @ohif/viewer@3.10.2
2020-04-23 16:20:51 +00:00
Danny Brown 709f14708e fix: undefined errorHandler in cornerstoneWadoImageLoader configuration (#1664) 2020-04-23 12:17:49 -04:00
ohif-bot 5f4c4ab5e7 chore(release): publish [skip ci]
- @ohif/extension-cornerstone@2.6.1
 - @ohif/extension-vtk@1.4.1
 - @ohif/core@2.8.1
 - @ohif/viewer@3.10.1
2020-04-23 10:04:47 +00:00
James Petts 71205618ec fix: 🐛 Multiframe fix (#1661) 2020-04-23 12:02:51 +02:00
ohif-bot 5014ba864b chore(release): publish [skip ci]
- @ohif/extension-cornerstone@2.6.0
 - @ohif/extension-dicom-p10-downloader@0.1.0
 - @ohif/extension-vtk@1.4.0
 - @ohif/core@2.8.0
 - @ohif/viewer@3.10.0
2020-04-23 02:06:44 +00:00
James Pettsanddannyrb e96205de35 feat: configuration to hook into XHR Error handling
* Error handling.

* Fix error handling, add redirect example.

* remove debugger

* docs: whitelabeling and httpErrorHandler

* bump dicomweb-client version

* bump cornerstone-wado-image-loader version

* Add more documentation around httpErrorHandler callback

* test: add errorHandler as an expected top level export

Co-authored-by: dannyrb <danny.ri.brown@gmail.com>
2020-04-22 22:01:34 -04:00
ohif-bot 273f31ad56 chore(release): publish [skip ci]
- @ohif/extension-vtk@1.3.14
 - @ohif/core@2.7.1
 - @ohif/viewer@3.9.2
2020-04-22 20:19:12 +00:00
Danny Brown 2093a00365 fix: whiteLabeling should support component creation by passing React to defined fn (#1659) 2020-04-22 16:16:53 -04:00
dependabot[bot] b1dad6b61b chore(deps): bump https-proxy-agent from 2.2.1 to 2.2.4 in /docs/latest (#1641)
Bumps [https-proxy-agent](https://github.com/TooTallNate/node-https-proxy-agent) from 2.2.1 to 2.2.4.
- [Release notes](https://github.com/TooTallNate/node-https-proxy-agent/releases)
- [Commits](https://github.com/TooTallNate/node-https-proxy-agent/compare/2.2.1...2.2.4)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2020-04-18 22:05:44 -04:00
ohif-bot 3a587f4e4b chore(release): publish [skip ci]
- @ohif/viewer@3.9.1
2020-04-17 16:28:57 +00:00
Danny Brown d9fc7bbb0e fix: showStudyList config (#1647)
* fix: `showStudyList` config

* showStudyList should default to true if not defined
2020-04-17 12:26:09 -04:00
ohif-bot b0cfc45f83 chore(release): publish [skip ci]
- @ohif/extension-vtk@1.3.13
 - @ohif/core@2.7.0
 - @ohif/viewer@3.9.0
2020-04-17 14:16:04 +00:00
Danny Brown 450c80b9d5 feat: set the authorization header for DICOMWeb requests if provided in query string (#1646) 2020-04-17 10:14:13 -04:00
ohif-bot d3eefb50f5 chore(release): publish [skip ci]
- @ohif/extension-dicom-p10-downloader@0.0.2
 - @ohif/extension-vtk@1.3.12
 - @ohif/core@2.6.11
 - @ohif/viewer@3.8.21
2020-04-15 17:00:38 +00:00
Emanuel Fiuza de OliveiraandJames Petts 29d4955980 Feat #1130 [WIP] Adding support for downloading and zipping files (#1501)
* Feat #1130 Adding support for downloading and zipping files

@ This is a combination of 12 commits.
 - Feat #1130 Initial Commit
 - Feat #1130 Adding support for hierachical lists
 - Feat #1130 [WIP] Adding support for downloading and zipping files
 - Feat #1130 Adding support for hierarchical folder structure study, series, instances on generated zip file
 - Feat #1130 Adding unit tests and addressing code review feedbacks
 - Feat #1130 POC (adding module to support on progress handling)
 - Feat #1130 Improving logic from progress tracking utils
 - Feat #1130 Renaming module with progress tracking utils
 - Feat #1130 Beta version of Progress Tracking utils
 - Feat #1130 Adding unit tests for Progress Tracking Utils
 - Feat #1130 Documenting public methods from progress tracking utils module
 - Feat #1130 Adding support for download and zip progress reporting

* Feat #1130 Addressing code review feedback

* Feat #1130 Preventing multiple downloads from executing at once

* Feat #1130 Improving error message for concurrent downloads

* Remove downloadAndZipSeriesOnViewports

Co-authored-by: James Petts <jamesapetts@gmail.com>
2020-04-15 18:57:57 +02:00
Nisal Upendra 2412c08595 docs: Embedding in existing react App (#1626)
Added how to embed OHIF viewer in an existing React application
2020-04-10 08:28:37 -04:00
ohif-bot d769e5c296 chore(release): publish [skip ci]
- @ohif/extension-vtk@1.3.11
 - @ohif/core@2.6.10
 - @ohif/viewer@3.8.20
2020-04-09 11:08:07 +00:00
Danny Brown d21af3f133 fix: Revert "refactor: Reduce bundle size (#1575)" (#1622)
This reverts commit 81dcbe294d.
2020-04-09 07:06:41 -04:00
114 changed files with 3353 additions and 694 deletions

No files matched your search

+100 -3
View File
@@ -127,10 +127,107 @@ appropriate headers. You can find an example of this setup in our
#### What if my archive doesn't support DicomWeb?
> This is possible to do with the OHIF Viewer, but not as straightforward. Look
> out for documentation on this subject in the near future.
It's possible to supply all Study data via JSON format, in the event you do not have a DicomWeb endpoint.
You can host all of the relevant files on any web accessible server (Amazon S3, Azure Blob Storage, Local file server etc.)
This JSON is supplied via the '?url=' query parameter.
It should reference an endpoint that returns **application/json** formatted text.
If you do not have an API, you can simply return a text file containing the JSON from any web server.
You tell the OHIF viewer to use JSON by appending the `'?url='` query to the `/Viewer` route:
eg. `https://my-test-ohif-server/viewer?url=https://my-json-server/study-uid.json`
The returned JSON object must contain a single root object with a 'studies' array.
*Sample JSON format:*
```JSON
{
"studies": [
{
"StudyInstanceUID": "1.2.840.113619.2.5.1762583153.215519.978957063.78",
"StudyDescription": "BRAIN SELLA",
"StudyDate": "20010108",
"StudyTime": "120022",
"PatientName": "MISTER^MR",
"PatientId": "832040",
"series": [
{
"SeriesDescription": "SAG T-1",
"SeriesInstanceUID": "1.2.840.113619.2.5.1762583153.215519.978957063.121",
"SeriesNumber": 2,
"SeriesDate": "20010108",
"SeriesTime": "120318",
"Modality": "MR",
"instances": [
{
"metadata": {
"Columns": 512,
"Rows": 512,
"InstanceNumber": 3,
"AcquisitionNumber": 0,
"PhotometricInterpretation": "MONOCHROME2",
"BitsAllocated": 16,
"BitsStored": 16,
"PixelRepresentation": 1,
"SamplesPerPixel": 1,
"PixelSpacing": [0.390625, 0.390625],
"HighBit": 15,
"ImageOrientationPatient": [0,1,0,0,0,-1],
"ImagePositionPatient": [11.600000,-92.500000, 98.099998],
"FrameOfReferenceUID": "1.2.840.113619.2.5.1762583153.223134.978956938.470",
"ImageType": ["ORIGINAL","PRIMARY","OTHER"],
"Modality": "MR",
"SOPInstanceUID": "1.2.840.113619.2.5.1762583153.215519.978957063.124",
"SeriesInstanceUID": "1.2.840.113619.2.5.1762583153.215519.978957063.121",
"StudyInstanceUID": "1.2.840.113619.2.5.1762583153.215519.978957063.78"
},
"url": "dicomweb://s3.amazonaws.com/lury/MRStudy/1.2.840.113619.2.5.1762583153.215519.978957063.124.dcm"
}
]
}
]
}
]
}
```
More info on this JSON format can be found here [Issue #1500](https://github.com/OHIF/Viewers/issues/1500)
**Implementation Notes:**
1. When hosting the viewer, you will also need to host a /viewer route on the server - or the browser may not be able to find the route.
2. For each instance url (dicom object) in the returned JSON, you must prefix the `url` with `dicomweb:` in order for the cornerstone image loader to retrieve it correctly.
eg. `https://image-server/my-image.dcm` ---> `dicomweb:https://image-server/my-image.dcm`
3. The JSON format above is compatible with >= v3.7.8 of the application. Older versions of the viewer used a different JSON format. As of 20/04/20 the public [https://viewer.ohif.org/] is a pre 3.0 version that does not support this format yet.
4. The JSON format is case-sensitive. Please ensure you have matched casing with the naturalised Dicom format referenced in [Issue #1500](https://github.com/OHIF/Viewers/issues/1500).
*CORS Issues (Cross-Origin Resource Sharing)*
If you host a JSON API or Images on a different domain from the the app itself, you will likely have CORS issues. This will also happen when testing from Localhost and reaching out to remote servers.
Even if the domain is the same, different ports, subdomains or protocols (https vs http) will also cause CORS errors.
You will to need add a configuration on each server hosting these assets to allow your App server origin.
For example:
Lets assume your application is hosted on `https://my-ohif-server.com`.
Your JSON API is hosted on `https://my-json-api.aws.com`
And your images are stored on Amazon S3 at `https://my-s3-bucket.aws.com`
When you first start your application, browsing to `https://my-ohif-server.com/viewer?url=https://my-json-api.aws.com/api/my-json-study-info.json`, you will likely get a CORS error in the browser console as it tries to connect to `https://my-json-api.aws.com`.
Adding a setting on the JSON server to allow the CORS origin = `https://my-ohif-server.com` should solve this.
Next, you will likely get a similar CORS error, as the browser tries to go to `https://my-s3-bucket.aws.com`.
You will need to go to the S3 bucket configuration, and add a CORS setting to allow origin = `https://my-ohif-server.com`.
Essentially, whenever the application connects to a remote resource, you will need to add the applications url to the allowed CORS Origins on that resource. Adding an origin similar to https://localhost:3000 will also allow for local testing.
...
### Securing Your Data
@@ -126,12 +126,39 @@ globally defined styles/scripts.
> We're trying to embed the OHIF Viewer into an existing React App, but seeing
> react-dom and react conflicts. What can we do?
If you are installing OHIF viewer inside another react app, you may use `installViewer` as follows:
```
import { installViewer } from '@ohif/viewer'
const ohifViewerConfig = window.config // or set it here
const containerId = 'ohif'
const componentRenderedOrUpdatedCallback = function() {
console.log('OHIF Viewer rendered/updated');
};
componentDidMount() {
installViewer(
ohifViewerConfig,
containerId,
componentRenderedOrUpdatedCallback
);
}
render () {
...
//you can render in any element you wish
<AnyTag id={containerId}/>
}
```
`installViewer` is a convenience method that pulls in some dependencies that may
not be compatible with existing `react` apps. `@ohif/viewer` also exports `App`
which is a react component that takes the `configuration` outlined above as
props. You can use it as a reusable component, and to avoid `react` version
conflict issues.
<!--
LINKS
-->
+53 -1
View File
@@ -11,7 +11,59 @@ are:
```js
window.config = {
routerBasename: '/',
whiteLabelling: {},
/**
* "White Labeling" is used to change the branding, look, and feel of the OHIF
* Viewer. These settings, and the color variables that are used by our components,
* are the easiest way to rebrand the application.
*
* More extensive changes are made possible through swapping out the UI library,
* Viewer project, or extensions.
*/
whiteLabeling: {
/* Optional: Should return a React component to be rendered in the "Logo" section of the application's Top Navigation bar */
createLogoComponentFn: function(React) {
return React.createElement('a', {
target: '_self',
rel: 'noopener noreferrer',
className: 'header-brand',
href: '/',
style: {
display: 'block',
textIndent: '-9999px',
background: 'url(/svg-file-hosted-at-domain-root.svg)',
backgroundSize: 'contain',
backgroundRepeat: 'no-repeat',
width: '200px',
},
});
},
},
/**
* Internally, the OHIF Viewer fetches data primarily with the
* `cornerstoneWADOImageLoader` and the `DICOMWebClient`. If either of these
* receive a non-200 response, this method allows you to handle that error.
*
* Common use cases include:
* - Showing a notification with the UINotificationService
* - Redirecting the user
* - Refreshing an auth token
*
* @param {Object} error - JS new Error()
* @param {XMLHttpRequest} error.request - The XHR request that's onreadystate change triggered this callback
* @param {string} error.response - The XHR's response property
* @param {number} error.status - The XHR's status property
*/
httpErrorHandler: error => {
const { request: xhr, response, status } = err;
const { responseType, statusText } = xhr;
// In local files, status is 0 upon success in Firefox
if (xhr.readyState === XMLHttpRequest.DONE) {
console.log(statusText, response, responseType);
} else {
console.warn('Likely CORS error');
}
},
extensions: [],
showStudyList: true,
filterQueryParam: false,
+4 -4
View File
@@ -66,11 +66,11 @@ open to pull requests and discussion issues.
Current white-labeling options are limited. We expose the ability to replace the
"Logo" section of the application with a custom "Logo" component. You can do
this by adding a `whiteLabelling` key to your
this by adding a `whiteLabeling` key to your
[configuration file](./configuration.md).
```js
function RadicalImagingLogo() {
function RadicalImagingLogo(React) {
return React.createElement(
'a',
{
@@ -83,8 +83,8 @@ function RadicalImagingLogo() {
);
}
props.whiteLabelling = {
logoComponent: RadicalImagingLogo(),
props.whiteLabeling = {
createLogoComponentFn: RadicalImagingLogo,
};
```
+17 -12
View File
@@ -20,10 +20,10 @@ abbrev@~1.0.9:
resolved "https://registry.yarnpkg.com/abbrev/-/abbrev-1.0.9.tgz#91b4792588a7738c25f35dd6f63752a2f8776135"
integrity sha1-kbR5JYinc4wl813W9jdSovh3YTU=
agent-base@4, agent-base@^4.1.0:
version "4.2.1"
resolved "https://registry.yarnpkg.com/agent-base/-/agent-base-4.2.1.tgz#d89e5999f797875674c07d87f260fc41e83e8ca9"
integrity sha512-JVwXMr9nHYTUXsBFKUqhJwvlcYU/blreOEUkhNR2eXZIvwd+c+o5V4MgDPKWnMS/56awN3TRzIP+KoPn+roQtg==
agent-base@4, agent-base@^4.1.0, agent-base@^4.3.0:
version "4.3.0"
resolved "https://registry.yarnpkg.com/agent-base/-/agent-base-4.3.0.tgz#8165f01c436009bccad0b1d122f05ed770efc6ee"
integrity sha512-salcGninV0nPrwpGNn4VTXBb1SOuXQBiqbrNXoeizJsHrsL6ERFM2Ne3JUSBWRE6aeNJI2ROP/WEEIDUiDe3cg==
dependencies:
es6-promisify "^5.0.0"
@@ -773,9 +773,9 @@ err-code@^1.0.0:
prr "~1.0.1"
es6-promise@^4.0.3:
version "4.2.6"
resolved "https://registry.yarnpkg.com/es6-promise/-/es6-promise-4.2.6.tgz#b685edd8258886365ea62b57d30de28fadcd974f"
integrity sha512-aRVgGdnmW2OiySVPUC9e6m+plolMAJKjZnQlCwNSuK5yQ0JN61DZSO1X1Ufd1foqWRAlig0rhduTCHe7sVtK5Q==
version "4.2.8"
resolved "https://registry.yarnpkg.com/es6-promise/-/es6-promise-4.2.8.tgz#4eb21594c972bc40553d276e510539143db53e0a"
integrity sha512-HJDGx5daxeIvxdBxvG2cb9g4tEvwIk3i8+nhX0yGrYmZUzbkdg8QbDevheDB8gd0//uPj4c1EQua8Q+MViT0/w==
es6-promisify@^5.0.0:
version "5.0.0"
@@ -1289,11 +1289,11 @@ http-signature@~1.2.0:
sshpk "^1.7.0"
https-proxy-agent@^2.1.0:
version "2.2.1"
resolved "https://registry.yarnpkg.com/https-proxy-agent/-/https-proxy-agent-2.2.1.tgz#51552970fa04d723e04c56d04178c3f92592bbc0"
integrity sha512-HPCTS1LW51bcyMYbxUIOO4HEOlQ1/1qRaFWcyxvwaqUS9TY88aoEuHUY33kuAh1YhVVaDQhLZsnPd+XNARWZlQ==
version "2.2.4"
resolved "https://registry.yarnpkg.com/https-proxy-agent/-/https-proxy-agent-2.2.4.tgz#4ee7a737abd92678a293d9b34a1af4d0d08c787b"
integrity sha512-OmvfoQ53WLjtA9HeYP9RNrWMJzzAz1JGaSFr1nijg0PVR1JaD/xbJq1mdEIIlxGpXp9eSe/O2LgU9DJmTPd0Eg==
dependencies:
agent-base "^4.1.0"
agent-base "^4.3.0"
debug "^3.1.0"
humanize-ms@^1.2.1:
@@ -1807,11 +1807,16 @@ ms@2.0.0:
resolved "https://registry.yarnpkg.com/ms/-/ms-2.0.0.tgz#5608aeadfc00be6c2901df5f9861788de0d597c8"
integrity sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=
ms@^2.0.0, ms@^2.1.1:
ms@^2.0.0:
version "2.1.1"
resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.1.tgz#30a5864eb3ebb0a66f2ebe6d727af06a09d86e0a"
integrity sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==
ms@^2.1.1:
version "2.1.2"
resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.2.tgz#d09d1f357b443f493382a8eb3ccd183872ae6009"
integrity sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==
mute-stream@~0.0.4:
version "0.0.8"
resolved "https://registry.yarnpkg.com/mute-stream/-/mute-stream-0.0.8.tgz#1630c42b2251ff81e2a283de96a5497ea92e5e0d"
+33
View File
@@ -3,6 +3,39 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
# [2.7.0](https://github.com/OHIF/Viewers/compare/@ohif/extension-cornerstone@2.6.1...@ohif/extension-cornerstone@2.7.0) (2020-04-24)
### Features
* 🎸 Seg jump to slice + show/hide ([835f64d](https://github.com/OHIF/Viewers/commit/835f64d47a9994f6a25aaf3941a4974e215e7e7f))
## [2.6.1](https://github.com/OHIF/Viewers/compare/@ohif/extension-cornerstone@2.6.0...@ohif/extension-cornerstone@2.6.1) (2020-04-23)
### Bug Fixes
* 🐛 Multiframe fix ([#1661](https://github.com/OHIF/Viewers/issues/1661)) ([7120561](https://github.com/OHIF/Viewers/commit/71205618ecb8b592247c5acb32284bfe7e18fce5))
# [2.6.0](https://github.com/OHIF/Viewers/compare/@ohif/extension-cornerstone@2.5.2...@ohif/extension-cornerstone@2.6.0) (2020-04-23)
### Features
* configuration to hook into XHR Error handling ([e96205d](https://github.com/OHIF/Viewers/commit/e96205de35e5bec14dc8a9a8509db3dd4e6ecdb6))
## [2.5.2](https://github.com/OHIF/Viewers/compare/@ohif/extension-cornerstone@2.5.1...@ohif/extension-cornerstone@2.5.2) (2020-04-09)
**Note:** Version bump only for package @ohif/extension-cornerstone
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@ohif/extension-cornerstone",
"version": "2.5.2",
"version": "2.7.0",
"description": "OHIF extension for Cornerstone",
"author": "OHIF",
"license": "MIT",
@@ -35,8 +35,8 @@
"cornerstone-core": "^2.2.8",
"cornerstone-math": "^0.1.8",
"cornerstone-tools": "4.12.5",
"cornerstone-wado-image-loader": "^3.0.0",
"dcmjs": "^0.10.1",
"cornerstone-wado-image-loader": "^3.1.0",
"dcmjs": "^0.12.2",
"dicom-parser": "^1.8.3",
"hammerjs": "^2.0.8",
"prop-types": "^15.6.2",
+1 -1
View File
@@ -267,7 +267,7 @@ const commandsModule = ({ servicesManager }) => {
const study = studyMetadataManager.get(StudyInstanceUID);
const displaySet = study.findDisplaySet(ds => {
return ds.images.find(i => i.getSOPInstanceUID() === SOPInstanceUID)
return ds.images && ds.images.find(i => i.getSOPInstanceUID() === SOPInstanceUID)
});
displaySet.SOPInstanceUID = SOPInstanceUID;
@@ -2,6 +2,9 @@ import Hammer from 'hammerjs';
import cornerstone from 'cornerstone-core';
import cornerstoneMath from 'cornerstone-math';
import cornerstoneTools from 'cornerstone-tools';
import OHIF from '@ohif/core';
const { log } = OHIF;
export default function(configuration = {}) {
// For debugging
@@ -12,6 +15,13 @@ export default function(configuration = {}) {
cornerstoneTools.external.cornerstoneMath = cornerstoneMath;
cornerstoneTools.init(configuration);
cornerstoneTools.loadHandlerManager.setErrorLoadingHandler(
(element, imageId, error) => {
log.error(imageId);
throw error;
}
);
// Set the tool font and font size
// context.font = "[style] [variant] [weight] [size]/[line height] [font family]";
const fontFamily =
+19
View File
@@ -3,6 +3,25 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.2.1](https://github.com/OHIF/Viewers/compare/@ohif/extension-dicom-html@1.2.0...@ohif/extension-dicom-html@1.2.1) (2020-04-28)
**Note:** Version bump only for package @ohif/extension-dicom-html
# [1.2.0](https://github.com/OHIF/Viewers/compare/@ohif/extension-dicom-html@1.1.2...@ohif/extension-dicom-html@1.2.0) (2020-04-24)
### Features
* 🎸 Seg jump to slice + show/hide ([835f64d](https://github.com/OHIF/Viewers/commit/835f64d47a9994f6a25aaf3941a4974e215e7e7f))
## [1.1.2](https://github.com/OHIF/Viewers/compare/@ohif/extension-dicom-html@1.1.1...@ohif/extension-dicom-html@1.1.2) (2020-04-02)
**Note:** Version bump only for package @ohif/extension-dicom-html
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@ohif/extension-dicom-html",
"version": "1.1.2",
"version": "1.2.1",
"description": "OHIF extension for rendering structured reports to HTML",
"author": "OHIF",
"license": "MIT",
@@ -29,7 +29,7 @@
},
"peerDependencies": {
"@ohif/core": "^0.50.0",
"dcmjs": "^0.10.1",
"dcmjs": "^0.12.2",
"prop-types": "^15.6.2",
"react": "^16.8.6",
"react-dom": "^16.8.6"
@@ -1,6 +1,6 @@
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import * as dcmjs from 'dcmjs';
import dcmjs from 'dcmjs';
import TypedArrayProp from './TypedArrayProp';
import './DicomHtmlViewport.css';
@@ -0,0 +1,8 @@
const path = require('path');
const webpackCommon = require('./../../../.webpack/webpack.commonjs.js');
const SRC_DIR = path.join(__dirname, '../src');
const DIST_DIR = path.join(__dirname, '../dist');
module.exports = (env, argv) => {
return webpackCommon(env, argv, { SRC_DIR, DIST_DIR });
};
@@ -0,0 +1,38 @@
const merge = require('webpack-merge');
const path = require('path');
const webpackCommon = require('./../../../.webpack/webpack.commonjs.js');
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');
module.exports = (env, argv) => {
const commonConfig = webpackCommon(env, argv, { SRC_DIR, DIST_DIR });
return merge(commonConfig, {
devtool: 'source-map',
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: 'OHIFExtDicomP10Downloader',
libraryTarget: 'umd',
libraryExport: 'default',
filename: pkg.main,
},
});
};
@@ -0,0 +1,28 @@
# Change Log
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
# [0.1.0](https://github.com/OHIF/Viewers/compare/@ohif/extension-dicom-p10-downloader@0.0.2...@ohif/extension-dicom-p10-downloader@0.1.0) (2020-04-23)
### Features
* configuration to hook into XHR Error handling ([e96205d](https://github.com/OHIF/Viewers/commit/e96205de35e5bec14dc8a9a8509db3dd4e6ecdb6))
## 0.0.2 (2020-04-15)
**Note:** Version bump only for package @ohif/extension-dicom-p10-downloader
# Change Log
All notable changes to this project will be documented in this file. See
[Conventional Commits](https://conventionalcommits.org) for commit guidelines.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2018 Open Health Imaging Foundation
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.
@@ -0,0 +1 @@
# @ohif/extension-dicom-p10-downloader
@@ -0,0 +1,40 @@
{
"name": "@ohif/extension-dicom-p10-downloader",
"version": "0.1.0",
"description": "OHIF extension for downloading DICOM P10 files",
"author": "OHIF",
"license": "MIT",
"repository": "OHIF/Viewers",
"main": "dist/index.umd.js",
"module": "src/index.js",
"publishConfig": {
"access": "public"
},
"engines": {
"node": ">=10",
"npm": ">=6",
"yarn": ">=1.16.0"
},
"files": [
"dist",
"README.md"
],
"scripts": {
"dev": "cross-env NODE_ENV=development webpack --config .webpack/webpack.dev.js --watch --debug --output-pathinfo",
"build": "cross-env NODE_ENV=production webpack --config .webpack/webpack.prod.js",
"build:package": "yarn run build",
"prepublishOnly": "yarn run build",
"start": "yarn run dev"
},
"peerDependencies": {
"@ohif/core": "^2.6.0",
"dicom-parser": "^1.8.3",
"dicomweb-client": "^0.5.2"
},
"dependencies": {
"@babel/runtime": "^7.5.5",
"dicomweb-client": "^0.6.0",
"file-saver": "^2.0.2",
"jszip": "^3.2.2"
}
}
@@ -0,0 +1,105 @@
import OHIF from '@ohif/core';
import {
save,
getDicomWebClientFromContext,
getSOPInstanceReferenceFromActiveViewport,
getSOPInstanceReferencesFromViewports,
} from './utils';
import _downloadAndZip from './downloadAndZip';
const {
utils: {
Queue,
},
} = OHIF;
export function getCommands(context) {
const queue = new Queue(1);
const actions = {
/**
* @example Running this command using Commands Manager
* commandsManager.runCommand(
* 'downloadAndZip',
* {
* listOfUIDs: [...],
* options: {
* progress(status) {
* console.info('Progress:', (status.progress * 100).toFixed(2) + '%');
* }
* }
* },
* 'VIEWER'
* );
*/
downloadAndZip({ servers, dicomWebClient, listOfUIDs, options }) {
return save(
_downloadAndZip(
dicomWebClient || getDicomWebClientFromContext(context, servers),
listOfUIDs,
options
),
listOfUIDs
);
},
downloadAndZipSeriesOnViewports({ servers, viewports, progress }) {
const dicomWebClient = getDicomWebClientFromContext(context, servers);
const listOfUIDs = getSOPInstanceReferencesFromViewports(viewports);
return save(
_downloadAndZip(dicomWebClient, listOfUIDs, { progress }),
listOfUIDs
);
},
downloadAndZipSeriesOnActiveViewport({ servers, viewports, progress }) {
const dicomWebClient = getDicomWebClientFromContext(context, servers);
const listOfUIDs = getSOPInstanceReferenceFromActiveViewport(viewports);
return save(
_downloadAndZip(dicomWebClient, listOfUIDs, { progress }),
listOfUIDs
);
},
};
const definitions = {
downloadAndZip: {
commandFn: queue.bindSafe(actions.downloadAndZip, error),
storeContexts: ['servers'],
},
downloadAndZipSeriesOnViewports: {
commandFn: queue.bindSafe(actions.downloadAndZipSeriesOnViewports, error),
storeContexts: ['servers', 'viewports'],
options: { progress },
},
downloadAndZipSeriesOnActiveViewport: {
commandFn: queue.bindSafe(
actions.downloadAndZipSeriesOnActiveViewport,
error
),
storeContexts: ['servers', 'viewports'],
options: { progress },
},
};
return {
actions,
definitions,
};
}
/**
* Utils
*/
function progress(status) {
OHIF.log.info(
'Download and Zip Progress:',
(status.progress * 100.0).toFixed(2) + '%'
);
}
function error(e) {
if (e.message === 'Queue limit reached') {
OHIF.log.warn('A download is already in progress, please wait.');
} else {
OHIF.log.error(e);
}
}
@@ -0,0 +1,244 @@
import OHIF from '@ohif/core';
import { api } from 'dicomweb-client';
import dicomParser from 'dicom-parser';
import JSZip from 'jszip';
/**
* Constants
*/
const {
utils: {
isDicomUid,
hierarchicalListUtils,
progressTrackingUtils: progressUtils,
},
} = OHIF;
/**
* Public Methods
*/
/**
* Download and Zip all DICOM P10 instances from specified DICOM Web Client
* based on an hierarchical list of UIDs;
*
* @param {DICOMwebClient} dicomWebClient A DICOMwebClient instance through
* which the referenced instances will be retrieved;
* @param {Array} listOfUIDs The hierarchical list of UIDs from the instances
* that should be retrieved:
* A hierarchical list of UIDs is a regular JS Array where the type of the UID
* (study, series, instance) is determined by its nasting lavel. For example:
* @ The following list instructs the library to download all the instances
* from both studies "A" and "B":
*
* ['studyUIDFromA', 'studyUIDFromB']
*
* @ In the previous example both UIDs are treated as STUDY UIDs because both
* of them are listed in the same (top) level of the list. If, on the other
* hand, only instances from series "I" and "J" from the study "B"
* are to be downloaded, the expected hierarchical list would be:
*
* ['studyUIDFromA', ['studyUIDFromB', ['seriesUIDFromI', 'seriesUIDFromJ']]]
*
* @ Which, when prettified, reads like this:
*
* [
* 'studyUIDFromA',
* ['studyUIDFromB', [
* 'seriesUIDFromI',
* 'seriesUIDFromJ'
* ]]
* ]
*
* @ Furthermore, if only instances "X", "Y" and "Z" from series "J" need to
* be downloaded (instead of all the instances from that series), the list
* could be changed to:
*
* [
* 'studyUIDFromA',
* ['studyUIDFromB', [
* 'seriesUIDFromI',
* ['seriesUIDFromJ', [
* 'instanceUIDFromX',
* 'instanceUIDFromY',
* 'instanceUIDFromZ'
* ]]
* ]]
* ]
*
* Please refer to hierarchicalListUtils.js for more information and utilities;
*
* @param {Object} options A plain object with options;
* @param {function} options.progress A callback to retrieve notifications
* @returns {Promise} A promise that resolves to an URL from which the ZIP file
* can be downloaded;
*/
async function downloadAndZip(dicomWebClient, listOfUIDs, options) {
if (dicomWebClient instanceof api.DICOMwebClient) {
const settings = buildSettings(listOfUIDs, options);
const { compression } = settings.tasks;
// Register user-provided progress handler as a task list observer
progressUtils.addObserver(settings.taskList, settings.options.progress);
const buffers = await downloadAll(dicomWebClient, settings).catch(error => {
// Reject promise from compression task on download failure
compression.deferred.reject(error);
throw error;
});
compression.deferred.resolve(zipAll(buffers, settings));
const url = await compression.deferred.promise;
return url;
}
throw new Error('A valid DICOM Web Client instance is expected');
}
/**
* Utils
*/
async function zipAll(buffers, settings) {
const zip = new JSZip();
OHIF.log.info('Adding DICOM P10 files to archive:', buffers.length);
buffers.forEach((buffer, i) => {
const path = buildPath(buffer) || `${i}.dcm`;
zip.file(path, buffer);
});
// Set compression task progress to 50%
progressUtils.update(settings.tasks.compression.task, 0.5);
const blob = await zip.generateAsync({ type: 'blob' });
return URL.createObjectURL(blob);
}
function buildSettings(listOfUIDs, options) {
const taskList = progressUtils.createList();
const compression = progressUtils.addDeferred(taskList);
const downloads = [];
// Build downloads list
hierarchicalListUtils.forEach(
listOfUIDs,
(StudyInstanceUID, SeriesInstanceUID, SOPInstanceUID) => {
if (isDicomUid(StudyInstanceUID)) {
downloads.push({
tracking: progressUtils.addDeferred(taskList),
parameters: [StudyInstanceUID, SeriesInstanceUID, SOPInstanceUID],
});
}
}
);
// Print tree of hierarchical references
OHIF.log.info('Downloading DICOM P10 files for references:');
OHIF.log.info(hierarchicalListUtils.print(listOfUIDs));
return {
options: Object(options),
taskList,
tasks: {
downloads,
compression,
},
};
}
function buildPath(buffer) {
let path;
try {
const byteArray = new Uint8Array(buffer);
const dataSet = dicomParser.parseDicom(byteArray, {
// Stop parsing after SeriesInstanceUID is found
untilTag: 'x0020000e',
});
const StudyInstanceUID = dataSet.string('x0020000d');
const SeriesInstanceUID = dataSet.string('x0020000e');
const SOPInstanceUID = dataSet.string('x00080018');
if (StudyInstanceUID && SeriesInstanceUID && SOPInstanceUID) {
path = `${StudyInstanceUID}/${SeriesInstanceUID}/${SOPInstanceUID}.dcm`;
}
} catch (e) {
OHIF.log.error('Error parsing downloaded DICOM P10 file...', e);
}
return path;
}
async function downloadAll(dicomWebClient, settings) {
const { downloads } = settings.tasks;
// Make sure at least one download was initiated
if (downloads.length < 1) {
throw new Error('No valid reference to be downloaded');
}
const promises = downloads.map(item => {
const {
parameters,
tracking: { deferred, task },
} = item;
deferred.resolve(download(task, dicomWebClient, ...parameters));
return deferred.promise;
});
// Wait on created download promises
return Promise.all(promises).then(results => {
const buffers = [];
// The "results" array may directly contain buffers (ArrayBuffer instances)
// or arrays of buffers, depending on the type of downloads initiated on the
// previous step (retrieveStudy, retrieveSeries or retrieveinstance). Ex:
// results = [buf1, [buf2, buf3], buf4, [buf5], ...];
results.forEach(
function select(nesting, result) {
if (result instanceof ArrayBuffer) {
buffers.push(result);
} else if (nesting && Array.isArray(result)) {
// "nesting" argument is important to make sure only two levels
// of arrays are visited. For example, "bufX" should not be visited:
// [buf1, [buf2, buf3, [bufX]], buf4, [buf5], ...];
result.forEach(select.bind(null, false));
}
}.bind(null, true)
);
return buffers;
});
}
async function download(
task,
dicomWebClient,
studyInstanceUID,
seriesInstanceUID,
sopInstanceUID
) {
// Strict DICOM-formatted variable names COULDN'T be used here because the
// DICOM Web client interface expects them in this specific format.
// @TODO: Add support for download progress handler which will use the
// currently not use "task" param
if (!isDicomUid(studyInstanceUID)) {
throw new Error('Download requires at least a "StudyInstanceUID" property');
}
if (!isDicomUid(seriesInstanceUID)) {
// Download entire study
return dicomWebClient.retrieveStudy({
studyInstanceUID,
});
}
if (!isDicomUid(sopInstanceUID)) {
// Download entire series
return dicomWebClient.retrieveSeries({
studyInstanceUID,
seriesInstanceUID,
});
}
// Download specific instance
return dicomWebClient.retrieveInstance({
studyInstanceUID,
seriesInstanceUID,
sopInstanceUID,
});
}
/**
* Exports
*/
export { downloadAndZip as default, downloadAndZip };
@@ -0,0 +1,43 @@
import { getDicomWebClientFromConfig } from './utils';
import { getCommands } from './commandsModule';
/**
* Constants
*/
/**
* Globals
*/
const sharedContext = {
dicomWebClient: null,
};
/**
* Extension
*/
export default {
/**
* Only required property. Should be a unique value across all extensions.
*/
id: 'dicom-p10-downloader',
/**
* LIFECYCLE HOOKS
*/
preRegistration({ appConfig }) {
const dicomWebClient = getDicomWebClientFromConfig(appConfig);
if (dicomWebClient) {
sharedContext.dicomWebClient = dicomWebClient;
}
},
/**
* MODULE GETTERS
*/
getCommandsModule() {
return getCommands(sharedContext);
},
};
@@ -0,0 +1,110 @@
import OHIF from '@ohif/core';
import { api } from 'dicomweb-client';
import { saveAs } from 'file-saver';
const {
utils: { isDicomUid, resolveObjectPath, hierarchicalListUtils },
DICOMWeb,
} = OHIF;
function validDicomUid(subject) {
if (isDicomUid(subject)) {
return subject;
}
}
function getActiveServerFromServersStore(store) {
const servers = resolveObjectPath(store, 'servers');
if (Array.isArray(servers) && servers.length > 0) {
return servers.find(server => resolveObjectPath(server, 'active') === true);
}
}
function getDicomWebClientFromConfig(config) {
const servers = resolveObjectPath(config, 'servers.dicomWeb');
if (Array.isArray(servers) && servers.length > 0) {
const server = servers[0];
return new api.DICOMwebClient({
url: server.wadoRoot,
headers: DICOMWeb.getAuthorizationHeader(server),
});
}
}
function getDicomWebClientFromContext(context, store) {
const activeServer = getActiveServerFromServersStore(store);
if (activeServer) {
return new api.DICOMwebClient({
url: activeServer.wadoRoot,
headers: DICOMWeb.getAuthorizationHeader(activeServer),
});
} else if (context.dicomWebClient instanceof api.DICOMwebClient) {
return context.dicomWebClient;
}
}
function getSOPInstanceReference(viewports, index) {
if (index >= 0) {
const { StudyInstanceUID, SeriesInstanceUID, SOPInstanceUID } = Object(
resolveObjectPath(viewports, `viewportSpecificData.${index}`)
);
return Object.freeze(
hierarchicalListUtils.addToList(
[],
validDicomUid(StudyInstanceUID),
validDicomUid(SeriesInstanceUID),
validDicomUid(SOPInstanceUID)
)
);
}
}
function getSOPInstanceReferenceFromActiveViewport(viewports) {
return getSOPInstanceReference(
viewports,
resolveObjectPath(viewports, 'activeViewportIndex')
);
}
function getSOPInstanceReferencesFromViewports(viewports) {
const list = [];
const viewportSpecificData = resolveObjectPath(
viewports,
'viewportSpecificData'
);
Object.keys(viewportSpecificData).forEach(index => {
const { StudyInstanceUID, SeriesInstanceUID, SOPInstanceUID } = Object(
viewportSpecificData[index]
);
hierarchicalListUtils.addToList(
list,
validDicomUid(StudyInstanceUID),
validDicomUid(SeriesInstanceUID),
validDicomUid(SOPInstanceUID)
);
});
return list;
}
function save(promise, listOfUIDs) {
return Promise.resolve(promise)
.then(url => {
OHIF.log.info('Files successfully compressed:', url);
const StudyInstanceUID = hierarchicalListUtils.getItem(listOfUIDs, 0);
saveAs(url, `${StudyInstanceUID}.zip`);
return url;
})
.catch(error => {
OHIF.log.error('Failed to create Zip file...', error);
return null;
});
}
export {
save,
validDicomUid,
getDicomWebClientFromConfig,
getDicomWebClientFromContext,
getSOPInstanceReferenceFromActiveViewport,
getSOPInstanceReferencesFromViewports,
};
+19
View File
@@ -3,6 +3,25 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [0.1.1](https://github.com/OHIF/Viewers/compare/@ohif/extension-dicom-rt@0.1.0...@ohif/extension-dicom-rt@0.1.1) (2020-04-28)
**Note:** Version bump only for package @ohif/extension-dicom-rt
# [0.1.0](https://github.com/OHIF/Viewers/compare/@ohif/extension-dicom-rt@0.0.2...@ohif/extension-dicom-rt@0.1.0) (2020-04-24)
### Features
* 🎸 Seg jump to slice + show/hide ([835f64d](https://github.com/OHIF/Viewers/commit/835f64d47a9994f6a25aaf3941a4974e215e7e7f))
## 0.0.2 (2020-04-09)
**Note:** Version bump only for package @ohif/extension-dicom-rt
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@ohif/extension-dicom-rt",
"version": "0.0.2",
"version": "0.1.1",
"description": "OHIF extension for rendering DICOM RTSTRUCTs on top of cornerstone images.",
"author": "OHIF",
"license": "MIT",
@@ -31,7 +31,7 @@
"@ohif/core": "^0.50.0",
"cornerstone-core": "^2.2.8",
"cornerstone-tools": "^4.0.9",
"dcmjs": "^0.8.3",
"dcmjs": "^0.12.2",
"prop-types": "^15.6.2",
"react": "^16.8.6",
"react-dom": "^16.8.6"
@@ -61,14 +61,17 @@
}
.dcmrt-structure-set-item .item-label {
overflow: hidden;
max-width: calc(100% - 15px); /* calc(100% - 50px); 20px = eye icon */
text-overflow: ellipsis;
overflow-wrap: normal;
white-space: nowrap;
display: flex;
justify-content: space-between;
padding-right: 10px;
}
.dcmrt-structure-set-item .item-label span {
overflow-wrap: normal;
white-space: nowrap;
overflow: hidden;
max-width: calc(100% - 40px); /* calc(100% - 50px); 20px = eye icon */
text-overflow: ellipsis;
}
.dcmrt-structure-set-item .item-label .eye-icon {
@@ -41,7 +41,7 @@ const StructureSetItem = ({
>
<div>
<div className="item-label" style={{ marginBottom: 4 }}>
{label}
<span>{label}</span>
<Icon
className={`eye-icon ${isVisible && '--visible'}`}
name={isVisible ? 'eye' : 'eye-closed'}
+5 -6
View File
@@ -27,10 +27,7 @@ export default {
};
return (
<RTPanel
{...props}
onContourItemClick={contourItemClickHandler}
/>
<RTPanel {...props} onContourItemClick={contourItemClickHandler} />
);
};
@@ -51,8 +48,10 @@ export default {
if (study && study.series) {
for (let j = 0; j < study.series.length; j++) {
const series = study.series[j];
console.log(studies);
if (['RTSTRUCT', 'RTPLAN', 'RTDOSE'].includes(series.Modality)) {
if (
/* Could be expanded to contain RTPLAN and RTDOSE information in the future */
['RTSTRUCT'].includes(series.Modality)
) {
return false;
}
}
+1 -1
View File
@@ -1,5 +1,5 @@
import OHIF from '@ohif/core';
import * as dcmjs from 'dcmjs';
import dcmjs from 'dcmjs';
import cornerstone from 'cornerstone-core';
import cornerstoneTools from 'cornerstone-tools';
import transformPointsToImagePlane from './utils/transformPointsToImagePlane';
@@ -3,6 +3,36 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [0.2.2](https://github.com/OHIF/Viewers/compare/@ohif/extension-dicom-segmentation@0.2.1...@ohif/extension-dicom-segmentation@0.2.2) (2020-04-28)
**Note:** Version bump only for package @ohif/extension-dicom-segmentation
## [0.2.1](https://github.com/OHIF/Viewers/compare/@ohif/extension-dicom-segmentation@0.2.0...@ohif/extension-dicom-segmentation@0.2.1) (2020-04-27)
### Bug Fixes
* 🐛 Dropdown not updating when selecting segment ([#1675](https://github.com/OHIF/Viewers/issues/1675)) ([20e366f](https://github.com/OHIF/Viewers/commit/20e366ffbd76781f48dc99c9f59e24b255b5e5df)), closes [#1669](https://github.com/OHIF/Viewers/issues/1669)
# [0.2.0](https://github.com/OHIF/Viewers/compare/@ohif/extension-dicom-segmentation@0.1.2...@ohif/extension-dicom-segmentation@0.2.0) (2020-04-24)
### Features
* 🎸 Seg jump to slice + show/hide ([835f64d](https://github.com/OHIF/Viewers/commit/835f64d47a9994f6a25aaf3941a4974e215e7e7f))
## [0.1.2](https://github.com/OHIF/Viewers/compare/@ohif/extension-dicom-segmentation@0.1.1...@ohif/extension-dicom-segmentation@0.1.2) (2020-04-09)
**Note:** Version bump only for package @ohif/extension-dicom-segmentation
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@ohif/extension-dicom-segmentation",
"version": "0.1.2",
"version": "0.2.2",
"description": "OHIF extension for viewing segmentations in the 2D MPR view",
"author": "OHIF",
"license": "MIT",
@@ -31,7 +31,7 @@
"@ohif/core": "^0.50.0",
"cornerstone-core": "^2.2.8",
"cornerstone-tools": "4.12.5",
"dcmjs": "^0.6.1",
"dcmjs": "^0.12.2",
"prop-types": "^15.6.2",
"react": "^16.8.6",
"react-dom": "^16.8.6"
@@ -12,14 +12,6 @@
height: 20px;
}
.dcmseg-segment-item .segment-label {
overflow: hidden;
max-width: calc(100% - 50px);
text-overflow: ellipsis;
overflow-wrap: normal;
white-space: nowrap;
}
.dcmseg-segment-item .segment-info {
display: inline-block;
margin-top: 9px;
@@ -62,3 +54,30 @@
.dcmseg-segment-item .segment-actions .btnAction i {
margin-right: 4px;
}
.dcmseg-segment-item .segment-label {
display: flex;
justify-content: space-between;
padding-right: 20px;
}
.dcmseg-segment-item .segment-label span {
overflow-wrap: normal;
white-space: nowrap;
overflow: hidden;
max-width: calc(100% - 40px); /* calc(100% - 50px); 20px = eye icon */
text-overflow: ellipsis;
}
.dcmseg-segment-item .segment-label .eye-icon {
cursor: pointer;
color: var(--active-color);
}
.dcmseg-segment-item .segment-label .eye-icon:hover {
color: var(--hover-color);
}
.dcmseg-segment-item .segment-label .eye-icon.--visible {
color: var(--default-color);
}
@@ -1,4 +1,4 @@
import React from 'react';
import React, { useState } from 'react';
import PropTypes from 'prop-types';
import { TableListItem, Icon } from '@ohif/ui';
@@ -17,48 +17,63 @@ ColoredCircle.propTypes = {
color: PropTypes.array.isRequired,
};
const SegmentItem = ({ index, label, onClick, itemClass, color }) => (
<div className="dcmseg-segment-item">
<TableListItem
key={index}
itemKey={index}
itemIndex={index}
itemClass={itemClass}
itemMeta={<ColoredCircle color={color} />}
itemMetaClass="segment-color-section"
onItemClick={onClick}
>
<div>
<div className="segment-label" style={{ marginBottom: 4 }}>
{label}
</div>
{false && <div className="segment-info">{'...'}</div>}
{false && (
<div className="segment-actions">
<button
className="btnAction"
onClick={() => console.log('Relabelling...')}
>
<span style={{ marginRight: '4px' }}>
<Icon name="edit" width="14px" height="14px" />
</span>
const SegmentItem = ({ index, label, onClick, itemClass, color, visible = true, onVisibilityChange }) => {
const [isVisible, setIsVisible] = useState(visible);
return (
<div className="dcmseg-segment-item">
<TableListItem
key={index}
itemKey={index}
itemIndex={index}
itemClass={itemClass}
itemMeta={<ColoredCircle color={color} />}
itemMetaClass="segment-color-section"
onItemClick={onClick}
>
<div>
<div className="segment-label" style={{ marginBottom: 4 }}>
<span>{label}</span>
<Icon
className={`eye-icon ${isVisible && '--visible'}`}
name={isVisible ? 'eye' : 'eye-closed'}
width="20px"
height="20px"
onClick={event => {
event.stopPropagation();
const newVisibility = !isVisible;
setIsVisible(newVisibility);
onVisibilityChange(newVisibility);
}}
/>
</div>
{false && <div className="segment-info">{'...'}</div>}
{false && (
<div className="segment-actions">
<button
className="btnAction"
onClick={() => console.log('Relabelling...')}
>
<span style={{ marginRight: '4px' }}>
<Icon name="edit" width="14px" height="14px" />
</span>
Relabel
</button>
<button
className="btnAction"
onClick={() => console.log('Editing description...')}
>
<span style={{ marginRight: '4px' }}>
<Icon name="edit" width="14px" height="14px" />
</span>
<button
className="btnAction"
onClick={() => console.log('Editing description...')}
>
<span style={{ marginRight: '4px' }}>
<Icon name="edit" width="14px" height="14px" />
</span>
Description
</button>
</div>
)}
</div>
</TableListItem>
</div>
);
</div>
)}
</div>
</TableListItem>
</div>
);
};
SegmentItem.propTypes = {
index: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
@@ -1,4 +1,4 @@
import React, { useState, useEffect } from 'react';
import React, { useState, useEffect, useCallback } from 'react';
import PropTypes from 'prop-types';
import cornerstoneTools from 'cornerstone-tools';
import cornerstone from 'cornerstone-core';
@@ -28,13 +28,20 @@ const refreshViewport = () => {
/**
* SegmentationPanel component
*
* @param {Object} props
* @param {Array} props.studies
* @param {Array} props.viewports - viewportSpecificData
* @param {number} props.activeIndex - activeViewportIndex
* @param {Array} props.studies - Studies data
* @param {Array} props.viewports - Viewports data (viewportSpecificData)
* @param {number} props.activeIndex - Active viewport index
* @param {boolean} props.isOpen - Boolean that indicates if the panel is expanded
* @param {Function} props.onSegItemClick - Segment click handler
* @returns component
*/
const SegmentationPanel = ({ studies, viewports, activeIndex, isOpen }) => {
const SegmentationPanel = ({
studies,
viewports,
activeIndex,
isOpen,
onSegItemClick,
}) => {
/*
* TODO: wrap get/set interactions with the cornerstoneTools
* store with context to make these kind of things less blurry.
@@ -43,13 +50,14 @@ const SegmentationPanel = ({ studies, viewports, activeIndex, isOpen }) => {
const DEFAULT_BRUSH_RADIUS = configuration.radius || 10;
const [state, setState] = useState({
brushRadius: DEFAULT_BRUSH_RADIUS,
brushColor: 'rgba(221, 85, 85, 1)', /* TODO: We shouldn't hardcode this color, in the future the SEG may set the colorLUT to whatever it wants. */
brushColor:
'rgba(221, 85, 85, 1)' /* TODO: We shouldn't hardcode this color, in the future the SEG may set the colorLUT to whatever it wants. */,
selectedSegment: null,
selectedSegmentation: null,
showSegSettings: false,
brushStackState: null,
labelmapList: [],
segmentList: []
segmentList: [],
});
useEffect(() => {
@@ -57,7 +65,12 @@ const SegmentationPanel = ({ studies, viewports, activeIndex, isOpen }) => {
log.warn('Segmentation Panel: labelmap modified', event);
const module = cornerstoneTools.getModule('segmentation');
const activeViewport = viewports[activeIndex];
const firstImageId = studyMetadata.getFirstImageId(activeViewport.displaySetInstanceUID);
const studyMetadata = studyMetadataManager.get(
activeViewport.StudyInstanceUID
);
const firstImageId = studyMetadata.getFirstImageId(
activeViewport.displaySetInstanceUID
);
updateState('brushStackState', module.state.series[firstImageId]);
};
@@ -86,20 +99,29 @@ const SegmentationPanel = ({ studies, viewports, activeIndex, isOpen }) => {
useEffect(() => {
const module = cornerstoneTools.getModule('segmentation');
const activeViewport = viewports[activeIndex];
const studyMetadata = studyMetadataManager.get(activeViewport.StudyInstanceUID);
const firstImageId = studyMetadata.getFirstImageId(activeViewport.displaySetInstanceUID);
const studyMetadata = studyMetadataManager.get(
activeViewport.StudyInstanceUID
);
const firstImageId = studyMetadata.getFirstImageId(
activeViewport.displaySetInstanceUID
);
const brushStackState = module.state.series[firstImageId];
if (brushStackState) {
const labelmap3D = brushStackState.labelmaps3D[brushStackState.activeLabelmapIndex];
const labelmapList = getLabelmapList(brushStackState, firstImageId, activeViewport);
const segmentList = getSegmentList(labelmap3D, firstImageId);
const labelmap3D =
brushStackState.labelmaps3D[brushStackState.activeLabelmapIndex];
const labelmapList = getLabelmapList(
brushStackState,
firstImageId,
activeViewport
);
const segmentList = getSegmentList(labelmap3D, firstImageId, brushStackState);
setState(state => ({
...state,
brushStackState,
selectedSegmentation: brushStackState.activeLabelmapIndex,
labelmapList,
segmentList
segmentList,
}));
} else {
setState(state => ({
@@ -108,126 +130,201 @@ const SegmentationPanel = ({ studies, viewports, activeIndex, isOpen }) => {
segmentList: [],
}));
}
}, [studies, viewports, activeIndex]);
}, [studies, viewports, activeIndex, getLabelmapList, getSegmentList, state.selectedSegmentation]);
/* Handle open/closed panel behaviour */
useEffect(() => {
updateState('showSegSettings', state.showSegSettings && !isOpen);
setState(state => ({
...state,
showSegSettings: state.showSegSettings && !isOpen,
}));
}, [isOpen]);
const getLabelmapList = (brushStackState, firstImageId, activeViewport) => {
/* Get list of SEG labelmaps specific to active viewport (reference series) */
const referencedSegDisplaysets = _getReferencedSegDisplaysets(
activeViewport.StudyInstanceUID,
activeViewport.SeriesInstanceUID
);
const getLabelmapList = useCallback(
(brushStackState, firstImageId, activeViewport) => {
/* Get list of SEG labelmaps specific to active viewport (reference series) */
const referencedSegDisplaysets = _getReferencedSegDisplaysets(
activeViewport.StudyInstanceUID,
activeViewport.SeriesInstanceUID
);
return referencedSegDisplaysets.map((displaySet, index) => {
const { labelmapIndex, SeriesDate, SeriesTime } = displaySet;
return referencedSegDisplaysets.map((displaySet, index) => {
const { labelmapIndex, SeriesDate, SeriesTime } = displaySet;
/* Map to display representation */
const dateStr = `${SeriesDate}:${SeriesTime}`.split('.')[0];
const date = moment(dateStr, 'YYYYMMDD:HHmmss');
const isActiveLabelmap =
labelmapIndex === brushStackState.activeLabelmapIndex;
const displayDate = date.format('ddd, MMM Do YYYY');
const displayTime = date.format('h:mm:ss a');
const displayDescription = displaySet.SeriesDescription;
/* Map to display representation */
const dateStr = `${SeriesDate}:${SeriesTime}`.split('.')[0];
const date = moment(dateStr, 'YYYYMMDD:HHmmss');
const isActiveLabelmap =
labelmapIndex === brushStackState.activeLabelmapIndex;
const displayDate = date.format('ddd, MMM Do YYYY');
const displayTime = date.format('h:mm:ss a');
const displayDescription = displaySet.SeriesDescription;
return {
value: labelmapIndex,
title: displayDescription,
description: displayDate,
onClick: async () => {
const activatedLabelmapIndex = await _setActiveLabelmap(
activeViewport,
studies,
displaySet,
firstImageId,
brushStackState.activeLabelmapIndex
);
updateState('selectedSegmentation', activatedLabelmapIndex);
},
};
});
};
return {
value: labelmapIndex,
title: displayDescription,
description: displayDate,
onClick: async () => {
const activatedLabelmapIndex = await _setActiveLabelmap(
activeViewport,
studies,
displaySet,
firstImageId,
brushStackState.activeLabelmapIndex
);
updateState('selectedSegmentation', activatedLabelmapIndex);
},
};
});
},
[studies]
);
const getSegmentList = (labelmap3D, firstImageId) => {
/*
* Newly created segments have no `meta`
* So we instead build a list of all segment indexes in use
* Then find any associated metadata
*/
const uniqueSegmentIndexes = labelmap3D.labelmaps2D
.reduce((acc, labelmap2D) => {
if (labelmap2D) {
const segmentIndexes = labelmap2D.segmentsOnLabelmap;
const getSegmentList = useCallback(
(labelmap3D, firstImageId, brushStackState) => {
/*
* Newly created segments have no `meta`
* So we instead build a list of all segment indexes in use
* Then find any associated metadata
*/
const uniqueSegmentIndexes = labelmap3D.labelmaps2D
.reduce((acc, labelmap2D) => {
if (labelmap2D) {
const segmentIndexes = labelmap2D.segmentsOnLabelmap;
for (let i = 0; i < segmentIndexes.length; i++) {
if (!acc.includes(segmentIndexes[i]) && segmentIndexes[i] !== 0) {
acc.push(segmentIndexes[i]);
for (let i = 0; i < segmentIndexes.length; i++) {
if (!acc.includes(segmentIndexes[i]) && segmentIndexes[i] !== 0) {
acc.push(segmentIndexes[i]);
}
}
}
return acc;
}, [])
.sort((a, b) => a - b);
const module = cornerstoneTools.getModule('segmentation');
const colorLutTable =
module.state.colorLutTables[labelmap3D.colorLUTIndex];
const hasLabelmapMeta = labelmap3D.metadata && labelmap3D.metadata.data;
const segmentList = [];
for (let i = 0; i < uniqueSegmentIndexes.length; i++) {
const segmentIndex = uniqueSegmentIndexes[i];
const color = colorLutTable[segmentIndex];
let segmentLabel = '(unlabeled)';
let segmentNumber = segmentIndex;
/* Meta */
if (hasLabelmapMeta) {
const segmentMeta = labelmap3D.metadata.data[segmentIndex];
if (segmentMeta) {
segmentNumber = segmentMeta.SegmentNumber;
segmentLabel = segmentMeta.SegmentLabel;
}
}
return acc;
}, [])
.sort((a, b) => a - b);
const sameSegment = state.selectedSegment === segmentNumber;
const setCurrentSelectedSegment = () => {
_setActiveSegment(
firstImageId,
segmentNumber,
labelmap3D.activeSegmentIndex
);
updateState('selectedSegment', sameSegment ? null : segmentNumber);
const module = cornerstoneTools.getModule('segmentation');
const colorLutTable =
module.state.colorLutTables[labelmap3D.colorLUTIndex];
const hasLabelmapMeta = labelmap3D.metadata && labelmap3D.metadata.data;
const validIndexList = [];
labelmap3D.labelmaps2D.forEach((labelMap2D, index) => {
if (labelMap2D.segmentsOnLabelmap.includes(segmentNumber)) {
validIndexList.push(index);
}
});
const avg = array => array.reduce((a, b) => a + b) / array.length;
const average = avg(validIndexList);
const closest = validIndexList.reduce((prev, curr) => {
return Math.abs(curr - average) < Math.abs(prev - average)
? curr
: prev;
});
const segmentList = [];
for (let i = 0; i < uniqueSegmentIndexes.length; i++) {
const segmentIndex = uniqueSegmentIndexes[i];
const enabledElements = cornerstone.getEnabledElements();
const element = enabledElements[activeIndex].element;
const toolState = cornerstoneTools.getToolState(element, 'stack');
const color = colorLutTable[segmentIndex];
let segmentLabel = '(unlabeled)';
let segmentNumber = segmentIndex;
if (!toolState) {
return;
}
/* Meta */
if (hasLabelmapMeta) {
const segmentMeta = labelmap3D.metadata.data[segmentIndex];
const imageIds = toolState.data[0].imageIds;
const imageId = imageIds[closest];
const frameIndex = imageIds.indexOf(imageId);
if (segmentMeta) {
segmentNumber = segmentMeta.SegmentNumber;
segmentLabel = segmentMeta.SegmentLabel;
const SOPInstanceUID = cornerstone.metaData.get(
'SOPInstanceUID',
imageId
);
const StudyInstanceUID = cornerstone.metaData.get(
'StudyInstanceUID',
imageId
);
onSegItemClick({
StudyInstanceUID,
SOPInstanceUID,
frameIndex,
activeViewportIndex: activeIndex,
});
};
const enabledElements = cornerstone.getEnabledElements();
const enabledElementViewport = enabledElements[activeIndex];
let isVisible = true;
if (enabledElementViewport) {
const element = enabledElementViewport.element;
const module = cornerstoneTools.getModule('segmentation');
isVisible = module.getters.isSegmentVisible(
element,
segmentNumber,
brushStackState.activeLabelmapIndex
);
}
segmentList.push(
<SegmentItem
key={segmentNumber}
itemClass={`segment-item ${sameSegment && 'selected'}`}
onClick={setCurrentSelectedSegment}
label={segmentLabel}
index={segmentNumber}
color={color}
visible={isVisible}
onVisibilityChange={() => {
const element = enabledElements[activeIndex].element;
module.setters.toggleSegmentVisibility(
element,
segmentNumber,
brushStackState.activeLabelmapIndex
);
refreshViewport();
}}
/>
);
}
const sameSegment = state.selectedSegment === segmentNumber;
const setCurrentSelectedSegment = () => {
_setActiveSegment(
firstImageId,
segmentNumber,
labelmap3D.activeSegmentIndex
);
updateState('selectedSegment', sameSegment ? null : segmentNumber);
};
return segmentList;
segmentList.push(
<SegmentItem
key={segmentNumber}
itemClass={`segment-item ${sameSegment && 'selected'}`}
onClick={setCurrentSelectedSegment}
label={segmentLabel}
index={segmentNumber}
color={color}
/>
);
}
return segmentList;
/*
* Let's iterate over segmentIndexes ^ above
* If meta has a match, use it to show info
* If now, add "no-meta" class
* Show default name
*/
};
/*
* Let's iterate over segmentIndexes ^ above
* If meta has a match, use it to show info
* If now, add "no-meta" class
* Show default name
*/
},
[activeIndex, onSegItemClick, state.selectedSegment]
);
const updateState = (field, value) => {
setState(state => ({ ...state, [field]: value }));
@@ -270,8 +367,7 @@ const SegmentationPanel = ({ studies, viewports, activeIndex, isOpen }) => {
}
const module = cornerstoneTools.getModule('segmentation');
const colorLutTable =
module.state.colorLutTables[labelmap3D.colorLUTIndex];
const colorLutTable = module.state.colorLutTables[labelmap3D.colorLUTIndex];
const color = colorLutTable[labelmap3D.activeSegmentIndex];
return `rgba(${color.join(',')})`;
@@ -328,9 +424,7 @@ const SegmentationPanel = ({ studies, viewports, activeIndex, isOpen }) => {
<h3>Segmentations</h3>
<div className="segmentations">
<SegmentationSelect
value={
state.labelmapList.find(i => i.value === state.selectedSegmentation) || null
}
value={state.labelmapList.find(i => i.value === state.selectedSegmentation)}
formatOptionLabel={SegmentationItem}
options={state.labelmapList}
/>
@@ -17,6 +17,10 @@ const defaultColor = computedstyle.getPropertyValue('--default-color');
const uiGrayDark = computedstyle.getPropertyValue('--ui-gray-dark');
const segmentationSelectStyles = {
singleValue: (base, state) => ({
...base,
width: '100%'
}),
control: (base, state) => ({
...base,
cursor: 'pointer',
+51 -3
View File
@@ -1,7 +1,9 @@
import React from 'react';
import init from './init.js';
import toolbarModule from './toolbarModule.js';
import panelModule from './panelModule.js';
import sopClassHandlerModule from './OHIFDicomSegSopClassHandler.js';
import SegmentationPanel from './components/SegmentationPanel/SegmentationPanel.js';
export default {
/**
@@ -21,8 +23,54 @@ export default {
getToolbarModule({ servicesManager }) {
return toolbarModule;
},
getPanelModule({ servicesManager }) {
return panelModule;
getPanelModule({ commandsManager }) {
const ExtendedSegmentationPanel = props => {
const segItemClickHandler = segData => {
commandsManager.runCommand('jumpToImage', segData);
};
return (
<SegmentationPanel {...props} onSegItemClick={segItemClickHandler} />
);
};
return {
menuOptions: [
{
icon: 'list',
label: 'Segmentations',
target: 'segmentation-panel',
isDisabled: studies => {
if (!studies) {
return true;
}
for (let i = 0; i < studies.length; i++) {
const study = studies[i];
if (study && study.series) {
for (let j = 0; j < study.series.length; j++) {
const series = study.series[j];
if (series.Modality === 'SEG') {
return false;
}
}
}
}
return true;
},
},
],
components: [
{
id: 'segmentation-panel',
component: ExtendedSegmentationPanel,
},
],
defaultContext: ['VIEWER'],
};
},
getSopClassHandlerModule({ servicesManager }) {
return sopClassHandlerModule;
@@ -1,5 +1,5 @@
import OHIF from '@ohif/core';
import * as dcmjs from 'dcmjs';
import dcmjs from 'dcmjs';
import cornerstone from 'cornerstone-core';
import cornerstoneTools from 'cornerstone-tools';
@@ -1,39 +0,0 @@
import SegmentationPanel from './components/SegmentationPanel/SegmentationPanel.js';
export default {
menuOptions: [
{
icon: 'list',
label: 'Segmentations',
target: 'segmentation-panel',
isDisabled: studies => {
if (!studies) {
return true;
}
for (let i = 0; i < studies.length; i++) {
const study = studies[i];
if (study && study.series) {
for (let j = 0; j < study.series.length; j++) {
const series = study.series[j];
if (series.Modality === 'SEG') {
return false;
}
}
}
}
return true;
},
},
],
components: [
{
id: 'segmentation-panel',
component: SegmentationPanel,
},
],
defaultContext: ['VIEWER'],
};
+81
View File
@@ -3,6 +3,87 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.5.2](https://github.com/OHIF/Viewers/compare/@ohif/extension-vtk@1.5.1...@ohif/extension-vtk@1.5.2) (2020-05-04)
**Note:** Version bump only for package @ohif/extension-vtk
## [1.5.1](https://github.com/OHIF/Viewers/compare/@ohif/extension-vtk@1.5.0...@ohif/extension-vtk@1.5.1) (2020-04-28)
**Note:** Version bump only for package @ohif/extension-vtk
# [1.5.0](https://github.com/OHIF/Viewers/compare/@ohif/extension-vtk@1.4.1...@ohif/extension-vtk@1.5.0) (2020-04-24)
### Features
* 🎸 Seg jump to slice + show/hide ([835f64d](https://github.com/OHIF/Viewers/commit/835f64d47a9994f6a25aaf3941a4974e215e7e7f))
## [1.4.1](https://github.com/OHIF/Viewers/compare/@ohif/extension-vtk@1.4.0...@ohif/extension-vtk@1.4.1) (2020-04-23)
**Note:** Version bump only for package @ohif/extension-vtk
# [1.4.0](https://github.com/OHIF/Viewers/compare/@ohif/extension-vtk@1.3.14...@ohif/extension-vtk@1.4.0) (2020-04-23)
### Features
* configuration to hook into XHR Error handling ([e96205d](https://github.com/OHIF/Viewers/commit/e96205de35e5bec14dc8a9a8509db3dd4e6ecdb6))
## [1.3.14](https://github.com/OHIF/Viewers/compare/@ohif/extension-vtk@1.3.13...@ohif/extension-vtk@1.3.14) (2020-04-22)
**Note:** Version bump only for package @ohif/extension-vtk
## [1.3.13](https://github.com/OHIF/Viewers/compare/@ohif/extension-vtk@1.3.12...@ohif/extension-vtk@1.3.13) (2020-04-17)
**Note:** Version bump only for package @ohif/extension-vtk
## [1.3.12](https://github.com/OHIF/Viewers/compare/@ohif/extension-vtk@1.3.11...@ohif/extension-vtk@1.3.12) (2020-04-15)
**Note:** Version bump only for package @ohif/extension-vtk
## [1.3.11](https://github.com/OHIF/Viewers/compare/@ohif/extension-vtk@1.3.10...@ohif/extension-vtk@1.3.11) (2020-04-09)
### Bug Fixes
* Revert "refactor: Reduce bundle size ([#1575](https://github.com/OHIF/Viewers/issues/1575))" ([#1622](https://github.com/OHIF/Viewers/issues/1622)) ([d21af3f](https://github.com/OHIF/Viewers/commit/d21af3f133492fa31492413b8782936c9ff18b44))
## [1.3.10](https://github.com/OHIF/Viewers/compare/@ohif/extension-vtk@1.3.9...@ohif/extension-vtk@1.3.10) (2020-04-09)
**Note:** Version bump only for package @ohif/extension-vtk
+5 -5
View File
@@ -1,6 +1,6 @@
{
"name": "@ohif/extension-vtk",
"version": "1.3.10",
"version": "1.5.2",
"description": "OHIF extension for VTK.js",
"author": "OHIF",
"license": "MIT",
@@ -34,8 +34,8 @@
"@ohif/ui": "^0.50.0",
"cornerstone-core": "^2.2.8",
"cornerstone-tools": "4.12.5",
"cornerstone-wado-image-loader": "^3.0.0",
"dcmjs": "^0.10.1",
"cornerstone-wado-image-loader": "^3.1.0",
"dcmjs": "^0.12.2",
"dicom-parser": "^1.8.3",
"i18next": "^17.0.3",
"i18next-browser-languagedetector": "^3.0.1",
@@ -53,10 +53,10 @@
"react-vtkjs-viewport": "^0.8.3"
},
"devDependencies": {
"@ohif/core": "^2.6.9",
"@ohif/core": "^2.9.2",
"@ohif/ui": "^1.4.3",
"cornerstone-tools": "4.12.5",
"cornerstone-wado-image-loader": "^3.0.0",
"cornerstone-wado-image-loader": "^3.1.0",
"dicom-parser": "^1.8.3",
"gh-pages": "^2.0.1",
"i18next": "^17.0.3",
+14 -22
View File
@@ -1,5 +1,5 @@
import React, { Component } from 'react';
import { getReactVtkjsViewport } from './utils/getReactVtkjsViewport';
import { getImageData, loadImageData } from 'react-vtkjs-viewport';
import ConnectedVTKViewport from './ConnectedVTKViewport';
import LoadingIndicator from './LoadingIndicator.js';
import OHIF from '@ohif/core';
@@ -69,7 +69,7 @@ class OHIFVTKViewport extends Component {
};
static defaultProps = {
onScroll: () => { },
onScroll: () => {},
};
static id = 'OHIFVTKViewport';
@@ -133,8 +133,7 @@ class OHIFVTKViewport extends Component {
displaySetInstanceUID,
SOPClassUID,
SOPInstanceUID,
frameIndex,
reactVtkjsViewport
frameIndex
) => {
const stack = OHIFVTKViewport.getCornerstoneStack(
studies,
@@ -145,10 +144,7 @@ class OHIFVTKViewport extends Component {
frameIndex
);
const imageDataObject = reactVtkjsViewport.getImageData(
stack.imageIds,
displaySetInstanceUID
);
const imageDataObject = getImageData(stack.imageIds, displaySetInstanceUID);
let labelmapDataObject;
let labelmapColorLUT;
@@ -261,9 +257,7 @@ class OHIFVTKViewport extends Component {
return volumeActor;
}
async setStateFromProps() {
const reactVtkjsViewport = await getReactVtkjsViewport();
setStateFromProps() {
const { studies, displaySet } = this.props.viewportData;
const {
StudyInstanceUID,
@@ -301,10 +295,8 @@ class OHIFVTKViewport extends Component {
studies,
StudyInstanceUID,
displaySetInstanceUID,
sopClassUIDs[0],
SOPInstanceUID,
frameIndex,
reactVtkjsViewport
frameIndex
);
this.imageDataObject = imageDataObject;
@@ -325,7 +317,7 @@ class OHIFVTKViewport extends Component {
dataDetails,
},
() => {
this.loadProgressively(imageDataObject, reactVtkjsViewport);
this.loadProgressively(imageDataObject);
// TODO: There must be a better way to do this.
// We do this so that if all the data is available the react-vtkjs-viewport
@@ -343,26 +335,26 @@ class OHIFVTKViewport extends Component {
);
}
async componentDidMount() {
await this.setStateFromProps();
componentDidMount() {
this.setStateFromProps();
}
async componentDidUpdate(prevProps) {
componentDidUpdate(prevProps) {
const { displaySet } = this.props.viewportData;
const prevDisplaySet = prevProps.viewportData.displaySet;
if (
displaySet.displaySetInstanceUID !==
prevDisplaySet.displaySetInstanceUID ||
prevDisplaySet.displaySetInstanceUID ||
displaySet.SOPInstanceUID !== prevDisplaySet.SOPInstanceUID ||
displaySet.frameIndex !== prevDisplaySet.frameIndex
) {
await this.setStateFromProps();
this.setStateFromProps();
}
}
loadProgressively(imageDataObject, reactVtkjsViewport) {
reactVtkjsViewport.loadImageData(imageDataObject);
loadProgressively(imageDataObject) {
loadImageData(imageDataObject);
const { isLoading, insertPixelDataPromises } = imageDataObject;
+2 -9
View File
@@ -1,16 +1,9 @@
import React, { useEffect, useCallback } from 'react';
// import { View2D } from 'react-vtkjs-viewport';
import { View2D } from 'react-vtkjs-viewport';
import PropTypes from 'prop-types';
import asyncComponent from './asyncComponent.js';
import { getReactVtkjsViewport } from './utils/getReactVtkjsViewport';
import './VTKViewport.css';
const View2D = asyncComponent(async () => {
const reactVtkjsViewport = await getReactVtkjsViewport();
return { default: reactVtkjsViewport.View2D };
});
const VTKViewport = props => {
const style = { width: '100%', height: '100%', position: 'relative' };
@@ -59,7 +52,7 @@ VTKViewport.propTypes = {
};
VTKViewport.defaultProps = {
onScroll: () => { },
onScroll: () => {},
};
export default VTKViewport;
+14 -13
View File
@@ -1,5 +1,10 @@
import throttle from 'lodash.throttle';
import { getReactVtkjsViewport } from './utils/getReactVtkjsViewport';
import {
vtkInteractorStyleMPRCrosshairs,
vtkInteractorStyleMPRWindowLevel,
vtkInteractorStyleMPRRotate,
vtkSVGCrosshairsWidget,
} from 'react-vtkjs-viewport';
import setMPRLayout from './utils/setMPRLayout.js';
import setViewportToVTK from './utils/setViewportToVTK.js';
@@ -119,18 +124,16 @@ const commandsModule = ({ commandsManager }) => {
_setView(api, [0, 1, 0], [0, 0, 1]);
},
enableRotateTool: async () => {
const reactVtkjsViewport = await getReactVtkjsViewport();
enableRotateTool: () => {
apis.forEach(api => {
const istyle = reactVtkjsViewport.vtkInteractorStyleMPRRotate.newInstance();
const istyle = vtkInteractorStyleMPRRotate.newInstance();
api.setInteractorStyle({ istyle });
});
},
enableCrosshairsTool: async () => {
const reactVtkjsViewport = await getReactVtkjsViewport();
enableCrosshairsTool: () => {
apis.forEach((api, apiIndex) => {
const istyle = reactVtkjsViewport.vtkInteractorStyleMPRCrosshairs.newInstance();
const istyle = vtkInteractorStyleMPRCrosshairs.newInstance();
api.setInteractorStyle({
istyle,
@@ -138,7 +141,7 @@ const commandsModule = ({ commandsManager }) => {
});
});
},
enableLevelTool: async () => {
enableLevelTool: () => {
function updateVOI(apis, windowWidth, windowCenter) {
apis.forEach(api => {
api.updateVOI(windowWidth, windowCenter);
@@ -159,9 +162,8 @@ const commandsModule = ({ commandsManager }) => {
},
};
const reactVtkjsViewport = await getReactVtkjsViewport();
apis.forEach(api => {
const istyle = reactVtkjsViewport.vtkInteractorStyleMPRWindowLevel.newInstance();
const istyle = vtkInteractorStyleMPRWindowLevel.newInstance();
api.setInteractorStyle({ istyle, callbacks });
});
@@ -258,15 +260,14 @@ const commandsModule = ({ commandsManager }) => {
}
// Add widgets and set default interactorStyle of each viewport.
const reactVtkjsViewport = await getReactVtkjsViewport();
apis.forEach((api, apiIndex) => {
api.addSVGWidget(
reactVtkjsViewport.vtkSVGCrosshairsWidget.newInstance(),
vtkSVGCrosshairsWidget.newInstance(),
'crosshairsWidget'
);
const uid = api.uid;
const istyle = reactVtkjsViewport.vtkInteractorStyleMPRCrosshairs.newInstance();
const istyle = vtkInteractorStyleMPRCrosshairs.newInstance();
api.setInteractorStyle({
istyle,
@@ -1,5 +0,0 @@
export function getReactVtkjsViewport() {
return import(
/* webpackChunkName: "ReactVtkjsViewport" */ 'react-vtkjs-viewport'
);
}
+93
View File
@@ -3,6 +3,99 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [2.9.2](https://github.com/OHIF/Viewers/compare/@ohif/core@2.9.1...@ohif/core@2.9.2) (2020-05-04)
### Bug Fixes
* use bit-appropriate array for palette lookup tables ([#1698](https://github.com/OHIF/Viewers/issues/1698)) ([7033886](https://github.com/OHIF/Viewers/commit/70338866978a76fa026c18d7c3c05257c5ece762))
## [2.9.1](https://github.com/OHIF/Viewers/compare/@ohif/core@2.9.0...@ohif/core@2.9.1) (2020-04-28)
**Note:** Version bump only for package @ohif/core
# [2.9.0](https://github.com/OHIF/Viewers/compare/@ohif/core@2.8.1...@ohif/core@2.9.0) (2020-04-24)
### Features
* 🎸 Seg jump to slice + show/hide ([835f64d](https://github.com/OHIF/Viewers/commit/835f64d47a9994f6a25aaf3941a4974e215e7e7f))
## [2.8.1](https://github.com/OHIF/Viewers/compare/@ohif/core@2.8.0...@ohif/core@2.8.1) (2020-04-23)
### Bug Fixes
* 🐛 Multiframe fix ([#1661](https://github.com/OHIF/Viewers/issues/1661)) ([7120561](https://github.com/OHIF/Viewers/commit/71205618ecb8b592247c5acb32284bfe7e18fce5))
# [2.8.0](https://github.com/OHIF/Viewers/compare/@ohif/core@2.7.1...@ohif/core@2.8.0) (2020-04-23)
### Features
* configuration to hook into XHR Error handling ([e96205d](https://github.com/OHIF/Viewers/commit/e96205de35e5bec14dc8a9a8509db3dd4e6ecdb6))
## [2.7.1](https://github.com/OHIF/Viewers/compare/@ohif/core@2.7.0...@ohif/core@2.7.1) (2020-04-22)
### Bug Fixes
* whiteLabeling should support component creation by passing React to defined fn ([#1659](https://github.com/OHIF/Viewers/issues/1659)) ([2093a00](https://github.com/OHIF/Viewers/commit/2093a0036584b2cc698c8f06fe62b334523b1029))
# [2.7.0](https://github.com/OHIF/Viewers/compare/@ohif/core@2.6.11...@ohif/core@2.7.0) (2020-04-17)
### Features
* set the authorization header for DICOMWeb requests if provided in query string ([#1646](https://github.com/OHIF/Viewers/issues/1646)) ([450c80b](https://github.com/OHIF/Viewers/commit/450c80b9d5f172be8b5713b422370360325a0afc))
## [2.6.11](https://github.com/OHIF/Viewers/compare/@ohif/core@2.6.10...@ohif/core@2.6.11) (2020-04-15)
**Note:** Version bump only for package @ohif/core
## [2.6.10](https://github.com/OHIF/Viewers/compare/@ohif/core@2.6.9...@ohif/core@2.6.10) (2020-04-09)
### Bug Fixes
* Revert "refactor: Reduce bundle size ([#1575](https://github.com/OHIF/Viewers/issues/1575))" ([#1622](https://github.com/OHIF/Viewers/issues/1622)) ([d21af3f](https://github.com/OHIF/Viewers/commit/d21af3f133492fa31492413b8782936c9ff18b44))
## [2.6.9](https://github.com/OHIF/Viewers/compare/@ohif/core@2.6.8...@ohif/core@2.6.9) (2020-04-09)
**Note:** Version bump only for package @ohif/core
+4 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@ohif/core",
"version": "2.6.9",
"version": "2.9.2",
"description": "Generic business logic for web-based medical imaging applications",
"author": "OHIF Core Team",
"license": "MIT",
@@ -33,14 +33,14 @@
"peerDependencies": {
"cornerstone-core": "^2.2.8",
"cornerstone-tools": "4.12.5",
"cornerstone-wado-image-loader": "^3.0.0",
"cornerstone-wado-image-loader": "^3.1.0",
"dicom-parser": "^1.8.3"
},
"dependencies": {
"@babel/runtime": "^7.5.5",
"ajv": "^6.10.0",
"dcmjs": "^0.12.0",
"dicomweb-client": "^0.5.2",
"dcmjs": "^0.12.2",
"dicomweb-client": "^0.6.0",
"immer": "6.0.2",
"isomorphic-base64": "^1.0.2",
"lodash.clonedeep": "^4.5.0",
@@ -1,10 +1,11 @@
import * as dcmjs from 'dcmjs';
import dcmjs from 'dcmjs';
import { api } from 'dicomweb-client';
import DICOMWeb from '../DICOMWeb';
import parseDicomStructuredReport from './parseDicomStructuredReport';
import parseMeasurementsData from './parseMeasurementsData';
import getAllDisplaySets from './utils/getAllDisplaySets';
import errorHandler from '../errorHandler';
const VERSION_NAME = 'dcmjs-0.0';
const TRANSFER_SYNTAX_UID = '1.2.840.10008.1.2.1';
@@ -21,6 +22,7 @@ const retrieveMeasurementFromSR = async (series, studies, serverUrl) => {
const config = {
url: serverUrl,
headers: DICOMWeb.getAuthorizationHeader(),
errorInterceptor: errorHandler.getHTTPErrorHandler(),
};
const dicomWeb = new api.DICOMwebClient(config);
@@ -71,6 +73,7 @@ const stowSRFromMeasurements = async (measurements, serverUrl) => {
const config = {
url: serverUrl,
headers: DICOMWeb.getAuthorizationHeader(),
errorInterceptor: errorHandler.getHTTPErrorHandler(),
};
const dicomWeb = new api.DICOMwebClient(config);
@@ -1,4 +1,4 @@
import * as dcmjs from 'dcmjs';
import dcmjs from 'dcmjs';
import findInstanceMetadataBySopInstanceUID from './utils/findInstanceMetadataBySopInstanceUid';
@@ -1,4 +1,4 @@
import * as dcmjs from 'dcmjs';
import dcmjs from 'dcmjs';
import cornerstone from 'cornerstone-core';
import log from '../log';
@@ -1,4 +1,4 @@
import * as dcmjs from 'dcmjs';
import dcmjs from 'dcmjs';
/**
* Checks if dcmjs has support to determined tool
@@ -1,6 +1,3 @@
// Commenting this out for now since it looks like Rollup is pulling in the
// Node.js version instead of the Browser version of this package
//import { btoa } from 'isomorphic-base64';
import user from '../user';
/**
@@ -18,6 +15,7 @@ export default function getAuthorizationHeader({ requestOptions } = {}) {
// Check for OHIF.user since this can also be run on the server
const accessToken = user && user.getAccessToken && user.getAccessToken();
// Auth for a specific server
if (requestOptions && requestOptions.auth) {
if (typeof requestOptions.auth === 'function') {
// Custom Auth Header
@@ -26,7 +24,9 @@ export default function getAuthorizationHeader({ requestOptions } = {}) {
// HTTP Basic Auth (user:password)
headers.Authorization = `Basic ${btoa(requestOptions.auth)}`;
}
} else if (accessToken) {
}
// Auth for the user's default
else if (accessToken) {
headers.Authorization = `Bearer ${accessToken}`;
}
@@ -1,4 +1,4 @@
import * as dcmjs from 'dcmjs';
import dcmjs from 'dcmjs';
import queryString from 'query-string';
import dicomParser from 'dicom-parser';
import getPixelSpacingInformation from '../utils/metadataProvider/getPixelSpacingInformation';
@@ -378,7 +378,7 @@ class MetadataProvider {
}
metadata = {
overlays
overlays,
};
break;
@@ -400,6 +400,7 @@ class MetadataProvider {
case WADO_IMAGE_LOADER_TAGS.GENERAL_IMAGE_MODULE:
metadata = {
sopInstanceUid: instance.SOPInstanceUID,
instanceNumber: instance.InstanceNumber,
lossyImageCompression: instance.LossyImageCompression,
lossyImageCompressionRatio: instance.LossyImageCompressionRatio,
@@ -1,10 +1,10 @@
import cornerstone from 'cornerstone-core';
import cornerstoneWADOImageLoader from 'cornerstone-wado-image-loader';
import {
clearStudyLoadingProgress,
setStudyLoadingProgress,
} from '../redux/actions';
import StackManager from '../utils/StackManager';
import { getCornerstoneWADOImageLoader } from '../utils/cornerstoneWADOImageLoader';
class BaseLoadingListener {
constructor(stack, options = {}) {
@@ -103,8 +103,7 @@ class DICOMFileLoadingListener extends BaseLoadingListener {
this._checkCachedData();
}
async _checkCachedData() {
const cornerstoneWADOImageLoader = await getCornerstoneWADOImageLoader();
_checkCachedData() {
const dataSet = cornerstoneWADOImageLoader.wadouri.dataSetCacheManager.get(
this._dataSetUrl
);
@@ -11,6 +11,7 @@ import { api } from 'dicomweb-client';
import { isImage } from '../../utils/isImage';
import isDisplaySetReconstructable from '../../utils/isDisplaySetReconstructable';
import isLowPriorityModality from '../../utils/isLowPriorityModality';
import errorHandler from '../../errorHandler';
export class StudyMetadata extends Metadata {
constructor(data, uid) {
@@ -102,10 +103,7 @@ export class StudyMetadata extends Metadata {
* @param {SeriesMetadata} series The series metadata object from which the display sets will be created
* @returns {Array} The list of display sets created for the given series object
*/
_createDisplaySetsForSeries(
sopClassHandlerModules,
series,
) {
_createDisplaySetsForSeries(sopClassHandlerModules, series) {
const study = this;
const displaySets = [];
@@ -293,14 +291,13 @@ export class StudyMetadata extends Metadata {
}
// Loop through the series (SeriesMetadata)
this.forEachSeries(
series => {
const displaySetsForSeries = this._createDisplaySetsForSeries(
sopClassHandlerModules,
series,
);
this.forEachSeries(series => {
const displaySetsForSeries = this._createDisplaySetsForSeries(
sopClassHandlerModules,
series
);
displaySets.push(...displaySetsForSeries);
displaySets.push(...displaySetsForSeries);
});
return sortDisplaySetList(displaySets);
@@ -321,7 +318,10 @@ export class StudyMetadata extends Metadata {
return false;
}
const displaySets = this._createDisplaySetsForSeries(sopClassHandlerModules, series)
const displaySets = this._createDisplaySetsForSeries(
sopClassHandlerModules,
series
);
// Note: filtering in place because this._displaySets has writable: false
for (let i = this._displaySets.length - 1; i >= 0; i--) {
@@ -835,9 +835,11 @@ function _getDisplaySetFromSopClassModule(
const plugin = handlersForSopClassUID[0];
const headers = DICOMWeb.getAuthorizationHeader();
const errorInterceptor = errorHandler.getHTTPErrorHandler();
const dicomWebClient = new dwc({
url: study.getData().wadoRoot,
headers,
errorInterceptor,
});
let displaySet = plugin.getDisplaySetFromSeries(
+6
View File
@@ -0,0 +1,6 @@
// These should be overridden by the implementation
const errorHandler = {
getHTTPErrorHandler: () => null,
};
export default errorHandler;
+3
View File
@@ -18,6 +18,7 @@ import string from './string.js';
import studies from './studies/';
import ui from './ui';
import user from './user.js';
import errorHandler from './errorHandler.js';
import utils, { hotkeys } from './utils/';
import {
@@ -46,6 +47,7 @@ const OHIF = {
string,
ui,
user,
errorHandler,
object,
log,
DICOMWeb,
@@ -79,6 +81,7 @@ export {
string,
ui,
user,
errorHandler,
object,
log,
DICOMWeb,
+1
View File
@@ -24,6 +24,7 @@ describe('Top level exports', () => {
'header',
'cornerstone',
'default', //
'errorHandler',
'string',
'ui',
'user',
@@ -1,6 +1,8 @@
import DICOMWeb from '../../../DICOMWeb/';
import { api } from 'dicomweb-client';
import errorHandler from '../../../errorHandler';
/**
* Parses data returned from a QIDO search and transforms it into
* an array of series that are present in the study
@@ -79,6 +81,7 @@ export default function Instances(server, StudyInstanceUID) {
const config = {
url: server.qidoRoot,
headers: DICOMWeb.getAuthorizationHeader(server),
errorInterceptor: errorHandler.getHTTPErrorHandler(),
};
const dicomWeb = new api.DICOMwebClient(config);
const queryParams = getQIDOQueryParams(
@@ -1,6 +1,8 @@
import { api } from 'dicomweb-client';
import DICOMWeb from '../../../DICOMWeb/';
import errorHandler from '../../../errorHandler';
/**
* Creates a QIDO date string for a date range query
* Assumes the year is positive, at most 4 digits long.
@@ -115,6 +117,7 @@ export default function Studies(server, filter) {
const config = {
url: server.qidoRoot,
headers: DICOMWeb.getAuthorizationHeader(server),
errorInterceptor: errorHandler.getHTTPErrorHandler(),
};
const dicomWeb = new api.DICOMwebClient(config);
@@ -9,6 +9,8 @@ import {
addInstancesToStudy,
} from './studyInstanceHelpers';
import errorHandler from '../../../errorHandler';
const { naturalizeDataset } = dcmjs.data.DicomMetaDictionary;
/**
@@ -73,6 +75,7 @@ export default class RetrieveMetadataLoaderAsync extends RetrieveMetadataLoader
const client = new api.DICOMwebClient({
url: server.qidoRoot,
headers: DICOMWeb.getAuthorizationHeader(server),
errorInterceptor: errorHandler.getHTTPErrorHandler(),
});
this.client = client;
@@ -117,7 +120,7 @@ export default class RetrieveMetadataLoaderAsync extends RetrieveMetadataLoader
return {
seriesInstanceUIDsMap,
seriesData
seriesData,
};
}
@@ -155,11 +158,14 @@ export default class RetrieveMetadataLoaderAsync extends RetrieveMetadataLoader
SeriesDescription: series.SeriesDescription,
SeriesNumber: series.SeriesNumber,
Modality: series.Modality,
instances: []
instances: [],
};
if (study.series[idx]) {
study.series[idx] = Object.assign(seriesDataFromQIDO, study.series[idx]);
study.series[idx] = Object.assign(
seriesDataFromQIDO,
study.series[idx]
);
} else {
study.series[idx] = seriesDataFromQIDO;
}
@@ -3,6 +3,8 @@ import DICOMWeb from '../../../DICOMWeb/';
import { createStudyFromSOPInstanceList } from './studyInstanceHelpers';
import RetrieveMetadataLoader from './retrieveMetadataLoader';
import errorHandler from '../../../errorHandler';
/**
* Class for sync load of study metadata.
* It inherits from RetrieveMetadataLoader
@@ -58,6 +60,7 @@ export default class RetrieveMetadataLoaderSync extends RetrieveMetadataLoader {
const client = new api.DICOMwebClient({
url: server.wadoRoot,
headers: DICOMWeb.getAuthorizationHeader(server),
errorInterceptor: errorHandler.getHTTPErrorHandler(),
});
this.client = client;
@@ -1,8 +1,8 @@
import DICOMWeb from '../../../DICOMWeb';
import metadataProvider from '../../../classes/MetadataProvider';
import getWADORSImageId from '../../../utils/getWADORSImageId';
import cornerstoneWADOImageLoader from 'cornerstone-wado-image-loader';
import getReferencedSeriesSequence from './getReferencedSeriesSequence';
import { getCornerstoneWADOImageLoader } from '../../../utils/cornerstoneWADOImageLoader';
/**
* Create a plain JS object that describes a study (a study descriptor object)
@@ -144,7 +144,7 @@ async function makeSOPInstance(server, study, instance) {
wadorsuri,
wadoRoot: server.wadoRoot,
imageRendering: server.imageRendering,
thumbnailRendering: server.thumbnailRendering
thumbnailRendering: server.thumbnailRendering,
};
series.instances.push(sopInstance);
@@ -160,9 +160,10 @@ async function makeSOPInstance(server, study, instance) {
const wadoRSMetadata = Object.assign(instance);
const cornerstoneWADOImageLoader = await getCornerstoneWADOImageLoader();
if (sopInstance.NumberOfFrames) {
for (let i = 0; i < sopInstance.NumberOfFrames; i++) {
const { NumberOfFrames } = sopInstance.metadata;
if (NumberOfFrames) {
for (let i = 0; i < NumberOfFrames; i++) {
const wadorsImageId = getWADORSImageId(sopInstance, i);
cornerstoneWADOImageLoader.wadors.metaDataManager.add(
@@ -191,7 +192,7 @@ async function makeSOPInstance(server, study, instance) {
*/
async function addInstancesToStudy(server, study, sopInstanceList) {
return Promise.all(
sopInstanceList.map(function (sopInstance) {
sopInstanceList.map(function(sopInstance) {
return makeSOPInstance(server, study, sopInstance);
})
);
+66
View File
@@ -0,0 +1,66 @@
export default class Queue {
constructor(limit) {
this.limit = limit;
this.size = 0;
this.awaiting = null;
}
/**
* Creates a new "proxy" function associated with the current execution queue
* instance. When the returned function is invoked, the queue limit is checked
* to make sure the limit of scheduled tasks is repected (throwing an
* exception when the limit has been reached and before calling the original
* function). The original function is only invoked after all the previously
* scheduled tasks have finished executing (their returned promises have
* resolved/rejected);
*
* @param {function} task The function whose execution will be associated
* with the current Queue instance;
* @returns {function} The "proxy" function bound to the current Queue
* instance;
*/
bind(task) {
return bind(this, task);
}
bindSafe(task, onError) {
const boundTask = bind(this, task);
return async function safeTask(...args) {
try {
return await boundTask(...args);
} catch (e) {
onError(e);
}
};
}
}
/**
* Utils
*/
function bind(queue, task) {
const cleaner = clean.bind(null, queue);
return async function boundTask(...args) {
if (queue.size >= queue.limit) {
throw new Error('Queue limit reached');
}
const promise = chain(queue.awaiting, task, args);
queue.awaiting = promise.then(cleaner, cleaner);
queue.size++;
return promise;
};
}
function clean(queue) {
if (queue.size > 0 && --queue.size === 0) {
queue.awaiting = null;
}
}
async function chain(prev, task, args) {
await prev;
return task(...args);
}
+66
View File
@@ -0,0 +1,66 @@
import makeDeferred from './makeDeferred';
import Queue from './Queue';
/**
* Utils
*/
function timeout(delay) {
const { resolve, promise } = makeDeferred();
setTimeout(() => void resolve(Date.now()), delay);
return promise;
}
/**
* Tests
*/
describe('Queue', () => {
it('should bind functions to the queue', async () => {
const queue = new Queue(2);
const mockedTimeout = jest.fn(timeout);
const timer = queue.bind(mockedTimeout);
const start = Date.now();
timer(120).then(now => {
const elapsed = now - start;
expect(elapsed >= 120 && elapsed < 240).toBe(true);
});
const end = await timer(120);
expect(end - start > 240).toBe(true);
expect(mockedTimeout).toBeCalledTimes(2);
});
it('should prevent task execution when queue limit is reached', async () => {
const queue = new Queue(1);
const mockedTimeout = jest.fn(timeout);
const timer = queue.bind(mockedTimeout);
const start = Date.now();
const promise = timer(120).then(time => time - start);
try {
await timer(120);
} catch (e) {
expect(Date.now() - start < 120).toBe(true);
expect(e.message).toBe('Queue limit reached');
}
const elapsed = await promise;
expect(elapsed >= 120 && elapsed < 240).toBe(true);
expect(mockedTimeout).toBeCalledTimes(1);
});
it('should safely bind tasks to the queue', async () => {
const queue = new Queue(1);
const mockedErrorHandler = jest.fn();
const mockedTimeout = jest.fn(timeout);
const timer = queue.bindSafe(mockedTimeout, mockedErrorHandler);
const start = Date.now();
const promise = timer(120).then(time => time - start);
await timer(120);
expect(Date.now() - start < 120).toBe(true);
expect(mockedErrorHandler).toBeCalledTimes(1);
expect(mockedErrorHandler).nthCalledWith(
1,
expect.objectContaining({ message: 'Queue limit reached' })
);
const elapsed = await promise;
expect(elapsed >= 120 && elapsed < 240).toBe(true);
expect(mockedTimeout).toBeCalledTimes(1);
});
});
@@ -1,5 +0,0 @@
export function getCornerstoneWADOImageLoader() {
return import(
/* webpackChunkName: "CornerstoneWADOImageLoader" */ 'cornerstone-wado-image-loader'
);
}
+11 -8
View File
@@ -1,7 +1,9 @@
import cornerstone from 'cornerstone-core';
import cornerstoneWADOImageLoader from 'cornerstone-wado-image-loader';
import { api } from 'dicomweb-client';
import DICOMWeb from '../DICOMWeb';
import { getCornerstoneWADOImageLoader } from './cornerstoneWADOImageLoader';
import errorHandler from '../errorHandler';
const getImageId = imageObj => {
if (!imageObj) {
@@ -57,11 +59,13 @@ const wadorsRetriever = (
studyInstanceUID,
seriesInstanceUID,
sopInstanceUID,
headers = DICOMWeb.getAuthorizationHeader()
headers = DICOMWeb.getAuthorizationHeader(),
errorInterceptor = errorHandler.getHTTPErrorHandler()
) => {
const config = {
url,
headers,
errorInterceptor,
};
const dicomWeb = new api.DICOMwebClient(config);
@@ -86,7 +90,7 @@ const getImageLoaderType = imageId => {
};
class DicomLoaderService {
async getLocalData(dataset, studies) {
getLocalData(dataset, studies) {
if (dataset && dataset.localFile) {
// Use referenced imageInstance
const imageInstance = getImageInstance(dataset);
@@ -98,7 +102,6 @@ class DicomLoaderService {
}
if (!someInvalidStrings(imageId)) {
const cornerstoneWADOImageLoader = await getCornerstoneWADOImageLoader();
return cornerstoneWADOImageLoader.wadouri.loadFileRequest(imageId);
}
}
@@ -177,16 +180,16 @@ class DicomLoaderService {
}
}
async *getLoaderIterator(dataset, studies) {
yield await this.getLocalData(dataset, studies);
*getLoaderIterator(dataset, studies) {
yield this.getLocalData(dataset, studies);
yield this.getDataByImageType(dataset);
yield this.getDataByDatasetType(dataset);
}
async findDicomDataPromise(dataset, studies) {
findDicomDataPromise(dataset, studies) {
const loaderIterator = this.getLoaderIterator(dataset, studies);
// it returns first valid retriever method.
for await (const loader of loaderIterator) {
for (const loader of loaderIterator) {
if (loader) {
return loader;
}
@@ -0,0 +1,193 @@
/**
* Constants
*/
const SEPARATOR = '/';
/**
* API
*/
/**
* Add values to a list hierarchically.
* @ For example:
* addToList([], 'a', 'b', 'c');
* will add the following hierarchy to the list:
* a > b > c
* resulting in the following array:
* [['a', [['b', ['c']]]]]
* @param {Array} list The target list;
* @param {...string} values The values to be hierarchically added to the list;
* @returns {Array} Returns the provided list possibly updated with the given
* values or null when a bad list (not an actual array) is provided
*/
function addToList(list, ...values) {
if (Array.isArray(list)) {
if (values.length > 0) {
addValuesToList(list, values);
}
return list;
}
return null;
}
/**
* Iterates through the provided hierarchical list executing the callback
* once for each leaf-node of the tree. The ancestors of the leaf-node being
* visited are passed to the callback function along with the leaf-node in
* the exact same order they appear on the tree (from root to leaf);
* @ For example, if the hierachy `a > b > c` appears on the tree ("a" being
* the root and "c" being the leaf) the callback function will be called as:
* callback('a', 'b', 'c');
* @param {Array} list The hierarchical list to be iterated
* @param {function} callback The callback which will be exected once for
* each leaf-node of the hierarchical list;
* @returns {Array} Returns the provided list or null for bad arguments;
*/
function forEach(list, callback) {
if (Array.isArray(list)) {
if (typeof callback === 'function') {
forEachValue(list, callback);
}
return list;
}
return null;
}
/**
* Retrieves an item from the given hierarchical list based on an index (number)
* or a path (string).
* @ For example:
* getItem(list, '1/0/4')
* will retrieve the fourth grandchild, from the first child of the second
* element of the list;
* @param {Array} list The source list;
* @param {string|number} indexOrPath The index of the element inside list
* (number) or the path to reach the desired element (string). The slash "/"
* character is cosidered the path separator;
*/
function getItem(list, indexOrPath) {
if (Array.isArray(list)) {
let subpath = null;
let index = typeof indexOrPath === 'number' ? indexOrPath : -1;
if (typeof indexOrPath === 'string') {
const separator = indexOrPath.indexOf(SEPARATOR);
if (separator > 0) {
index = parseInt(indexOrPath.slice(0, separator), 10);
if (separator + 1 < indexOrPath.length) {
subpath = indexOrPath.slice(separator + 1, indexOrPath.length);
}
} else {
index = parseInt(indexOrPath, 10);
}
}
if (index >= 0 && index < list.length) {
const item = list[index];
if (isSublist(item)) {
if (subpath !== null) {
return getItem(item[1], subpath);
}
return item[0];
}
return item;
}
}
}
/**
* Pretty-print the provided hierarchical list;
* @param {Array} list The source list;
* @returns {string} The textual representation of the hierarchical list;
*/
function print(list) {
let text = '';
if (Array.isArray(list)) {
let prev = [];
forEachValue(list, function(...args) {
let prevLen = prev.length;
for (let i = 0, l = args.length; i < l; ++i) {
if (i < prevLen && args[i] === prev[i]) {
continue;
}
text += ' '.repeat(i) + args[i] + '\n';
}
prev = args;
});
}
return text;
}
/**
* Utils
*/
function forEachValue(list, callback) {
for (let i = 0, l = list.length; i < l; ++i) {
let item = list[i];
if (isSublist(item)) {
if (item[1].length > 0) {
forEachValue(item[1], callback.bind(null, item[0]));
continue;
}
item = item[0];
}
callback(item);
}
}
function addValuesToList(list, values) {
let value = values.shift();
let index = add(list, value);
if (index >= 0) {
if (values.length > 0) {
let sublist = list[index];
if (!isSublist(sublist)) {
sublist = toSublist(value);
list[index] = sublist;
}
return addValuesToList(sublist[1], values);
}
return true;
}
return false;
}
function add(list, value) {
let index = find(list, value);
if (index === -2) {
index = list.push(value) - 1;
}
return index;
}
function find(list, value) {
if (typeof value === 'string') {
for (let i = 0, l = list.length; i < l; ++i) {
let item = list[i];
if (item === value || (isSublist(item) && item[0] === value)) {
return i;
}
}
return -2;
}
return -1;
}
function isSublist(subject) {
return (
Array.isArray(subject) &&
subject.length === 2 &&
typeof subject[0] === 'string' &&
Array.isArray(subject[1])
);
}
function toSublist(value) {
return [value + '', []];
}
/**
* Exports
*/
export { addToList, getItem, forEach, print };
@@ -0,0 +1,96 @@
import { addToList, forEach, getItem, print } from './hierarchicalListUtils';
describe('hierarchicalListUtils', function() {
let sharedList;
beforeEach(function() {
sharedList = [
['1.2.3.1', ['1.2.3.1.1', '1.2.3.1.2']],
'1.2.3.2',
['1.2.3.3', ['1.2.3.3.1', ['1.2.3.3.2', ['1.2.3.3.2.1', '1.2.3.3.2.2']]]],
];
});
describe('getItem', function() {
it('should retrieve elements from a list by index', function() {
expect(getItem(sharedList, 0)).toBe('1.2.3.1');
expect(getItem(sharedList, 1)).toBe('1.2.3.2');
expect(getItem(sharedList, 2)).toBe('1.2.3.3');
expect(getItem(sharedList, 3)).toBeUndefined();
});
it('should retrieve elements from a list by path', function() {
expect(getItem(sharedList, '0')).toBe('1.2.3.1');
expect(getItem(sharedList, '0/0')).toBe('1.2.3.1.1');
expect(getItem(sharedList, '0/1')).toBe('1.2.3.1.2');
expect(getItem(sharedList, '0/2')).toBeUndefined();
expect(getItem(sharedList, '1')).toBe('1.2.3.2');
expect(getItem(sharedList, '2')).toBe('1.2.3.3');
expect(getItem(sharedList, '2/0')).toBe('1.2.3.3.1');
expect(getItem(sharedList, '2/1')).toBe('1.2.3.3.2');
expect(getItem(sharedList, '2/2')).toBeUndefined();
expect(getItem(sharedList, '2/1/0')).toBe('1.2.3.3.2.1');
expect(getItem(sharedList, '2/1/1')).toBe('1.2.3.3.2.2');
expect(getItem(sharedList, '2/1/2')).toBeUndefined();
expect(getItem(sharedList, '3')).toBeUndefined();
});
});
describe('addToList', function() {
it('should support adding elements to a list hierarchically', function() {
const list = [];
addToList(list, '1.2.3.1', '1.2.3.1.1');
addToList(list, '1.2.3.1', '1.2.3.1.2');
addToList(list, '1.2.3.2');
addToList(list, '1.2.3.3', '1.2.3.3.1');
addToList(list, '1.2.3.3', '1.2.3.3.2', '1.2.3.3.2.1');
addToList(list, '1.2.3.3', '1.2.3.3.2', '1.2.3.3.2.2');
expect(list).toStrictEqual(sharedList);
});
it('should change leaf nodes into non-leaf nodes', function() {
const listw = [];
const listx = [['x.1', ['x.1.1', 'x.1.2']], 'x.2'];
const listy = [
['x.1', [['x.1.1', ['x.1.1.1']], 'x.1.2']],
['x.2', ['x.2.1']],
];
addToList(listw, 'x.1');
addToList(listw, 'x.1', 'x.1.1');
addToList(listw, 'x.1', 'x.1.2');
addToList(listw, 'x.2');
expect(listw).toStrictEqual(listx);
addToList(listw, 'x.2', 'x.2.1');
addToList(listw, 'x.1', 'x.1.1', 'x.1.1.1');
expect(listw).toStrictEqual(listy);
});
});
describe('forEach', function() {
it('should iterate through all leaf nodes of the tree', function() {
const fn = jest.fn();
forEach(sharedList, fn);
expect(fn).toHaveBeenCalledTimes(6);
expect(fn).nthCalledWith(1, '1.2.3.1', '1.2.3.1.1');
expect(fn).nthCalledWith(2, '1.2.3.1', '1.2.3.1.2');
expect(fn).nthCalledWith(3, '1.2.3.2');
expect(fn).nthCalledWith(4, '1.2.3.3', '1.2.3.3.1');
expect(fn).nthCalledWith(5, '1.2.3.3', '1.2.3.3.2', '1.2.3.3.2.1');
expect(fn).nthCalledWith(6, '1.2.3.3', '1.2.3.3.2', '1.2.3.3.2.2');
});
});
describe('print', function() {
it('should pretty-print the hierarchical list', function() {
expect(print(sharedList)).toBe(
'1.2.3.1\n' +
' 1.2.3.1.1\n' +
' 1.2.3.1.2\n' +
'1.2.3.2\n' +
'1.2.3.3\n' +
' 1.2.3.3.1\n' +
' 1.2.3.3.2\n' +
' 1.2.3.3.2.1\n' +
' 1.2.3.3.2.2\n'
);
});
});
});
+18
View File
@@ -10,8 +10,14 @@ import DicomLoaderService from './dicomLoaderService.js';
import b64toBlob from './b64toBlob.js';
import loadAndCacheDerivedDisplaySets from './loadAndCacheDerivedDisplaySets.js';
import * as urlUtil from './urlUtil';
import makeDeferred from './makeDeferred';
import makeCancelable from './makeCancelable';
import hotkeys from './hotkeys';
import Queue from './Queue';
import isDicomUid from './isDicomUid';
import resolveObjectPath from './resolveObjectPath';
import * as hierarchicalListUtils from './hierarchicalListUtils';
import * as progressTrackingUtils from './progressTrackingUtils';
const utils = {
guid,
@@ -26,8 +32,14 @@ const utils = {
DicomLoaderService,
urlUtil,
loadAndCacheDerivedDisplaySets,
makeDeferred,
makeCancelable,
hotkeys,
Queue,
isDicomUid,
resolveObjectPath,
hierarchicalListUtils,
progressTrackingUtils,
};
export {
@@ -43,8 +55,14 @@ export {
DicomLoaderService,
urlUtil,
loadAndCacheDerivedDisplaySets,
makeDeferred,
makeCancelable,
hotkeys,
Queue,
isDicomUid,
resolveObjectPath,
hierarchicalListUtils,
progressTrackingUtils,
};
export default utils;
+6
View File
@@ -15,8 +15,14 @@ describe('Top level exports', () => {
'loadAndCacheDerivedDisplaySets',
'DicomLoaderService',
'urlUtil',
'makeDeferred',
'makeCancelable',
'hotkeys',
'Queue',
'isDicomUid',
'resolveObjectPath',
'hierarchicalListUtils',
'progressTrackingUtils',
].sort();
const exports = Object.keys(utils.default).sort();
+4
View File
@@ -0,0 +1,4 @@
export default function isDicomUid(subject) {
const regex = /^\d+(?:\.\d+)*$/;
return typeof subject === 'string' && regex.test(subject.trim());
}
@@ -0,0 +1,16 @@
import isDicomUid from './isDicomUid';
describe('isDicomUid', function() {
it('should return true for valid DICOM UIDs', function() {
expect(isDicomUid('1')).toBe(true);
expect(isDicomUid('1.2')).toBe(true);
expect(isDicomUid('1.2.3')).toBe(true);
expect(isDicomUid('1.2.3.4')).toBe(true);
});
it('should return false for invalid DICOM UIDs', function() {
expect(isDicomUid('x')).toBe(false);
expect(isDicomUid('1.')).toBe(false);
expect(isDicomUid('1. 2')).toBe(false);
expect(isDicomUid('1.2.n.4')).toBe(false);
});
});
+7
View File
@@ -0,0 +1,7 @@
export default function makeDeferred() {
let reject, resolve, promise = new Promise(function (res, rej) {
resolve = res;
reject = rej;
});
return Object.freeze({ promise, resolve, reject });
}
@@ -0,0 +1,14 @@
import makeDeferred from './makeDeferred';
describe('makeDeferred', () => {
it('should provide a promise to be resolved externally', () => {
const deferred = makeDeferred();
setTimeout(() => void deferred.resolve('Yay!'));
return deferred.promise.then(result => void expect(result).toBe('Yay!'));
});
it('should provide a promise to be rejected externally', () => {
const deferred = makeDeferred();
setTimeout(() => void deferred.reject('Oops...'));
return deferred.promise.catch(error => void expect(error).toBe('Oops...'));
});
});
@@ -3,6 +3,8 @@ import DICOMWeb from '../../DICOMWeb';
import str2ab from '../str2ab';
import unpackOverlay from './unpackOverlay';
import errorHandler from '../../errorHandler';
export default async function fetchOverlayData(instance, server) {
const OverlayDataPromises = [];
const OverlayDataTags = [];
@@ -21,14 +23,20 @@ export default async function fetchOverlayData(instance, server) {
const inlineBinaryData = atob(instance[OverlayDataTag].InlineBinary);
const arraybuffer = str2ab(inlineBinaryData);
instance[OverlayDataTag] = unpackOverlay(arraybuffer)
} else if (instance[OverlayDataTag] && instance[OverlayDataTag].BulkDataURI) {
instance[OverlayDataTag] = unpackOverlay(arraybuffer);
} else if (
instance[OverlayDataTag] &&
instance[OverlayDataTag].BulkDataURI
) {
OverlayDataPromises.push(
_getOverlayData(instance[OverlayDataTag], server)
);
OverlayDataTags.push(OverlayDataTag);
} else if (instance[OverlayDataTag] && instance[OverlayDataTag] instanceof ArrayBuffer) {
instance[OverlayDataTag] = unpackOverlay(instance[OverlayDataTag])
} else if (
instance[OverlayDataTag] &&
instance[OverlayDataTag] instanceof ArrayBuffer
) {
instance[OverlayDataTag] = unpackOverlay(instance[OverlayDataTag]);
}
}
@@ -60,6 +68,7 @@ async function _getOverlayData(tag, server) {
const config = {
url: server.wadoRoot, //BulkDataURI is absolute, so this isn't used
headers: DICOMWeb.getAuthorizationHeader(server),
errorInterceptor: errorHandler.getHTTPErrorHandler(),
};
const dicomWeb = new api.DICOMwebClient(config);
const options = {
@@ -71,5 +80,3 @@ async function _getOverlayData(tag, server) {
.then(result => result[0])
.then(unpackOverlay);
}
@@ -2,6 +2,8 @@ import { api } from 'dicomweb-client';
import DICOMWeb from '../../DICOMWeb';
import str2ab from '../str2ab';
import errorHandler from '../../errorHandler';
export default async function fetchPaletteColorLookupTableData(
instance,
server
@@ -113,22 +115,14 @@ function _getPaletteColor(server, paletteColorLookupTableData, lutDescriptor) {
const numLutEntries = lutDescriptor[0];
const bits = lutDescriptor[2];
const readUInt16 = (byteArray, position) => {
return byteArray[position] + byteArray[position + 1] * 256;
};
const arrayBufferToPaletteColorLUT = arraybuffer => {
const byteArray = new Uint8Array(arraybuffer);
const byteArray = bits === 16 ?
new Uint16Array(arraybuffer) :
new Uint8Array(arraybuffer);
const lut = [];
if (bits === 16) {
for (let i = 0; i < numLutEntries; i++) {
lut[i] = readUInt16(byteArray, i * 2);
}
} else {
for (let i = 0; i < numLutEntries; i++) {
lut[i] = byteArray[i];
}
for (let i = 0; i < numLutEntries; i++) {
lut[i] = byteArray[i];
}
return lut;
@@ -146,6 +140,7 @@ function _getPaletteColor(server, paletteColorLookupTableData, lutDescriptor) {
const config = {
url: server.wadoRoot, //BulkDataURI is absolute, so this isn't used
headers: DICOMWeb.getAuthorizationHeader(server),
errorInterceptor: errorHandler.getHTTPErrorHandler(),
};
const dicomWeb = new api.DICOMwebClient(config);
const options = {
@@ -164,6 +159,8 @@ function _getPaletteColor(server, paletteColorLookupTableData, lutDescriptor) {
resolve(arrayBufferToPaletteColorLUT(arraybuffer));
});
} else {
return Promise.resolve(arrayBufferToPaletteColorLUT(paletteColorLookupTableData));
return Promise.resolve(
arrayBufferToPaletteColorLUT(paletteColorLookupTableData)
);
}
}
@@ -0,0 +1,336 @@
import makeDeferred from './makeDeferred';
/**
* Constants
*/
const TYPE = Symbol('Type');
const TASK = Symbol('Task');
const LIST = Symbol('List');
/**
* Public Methods
*/
/**
* Creates an instance of a task list
* @returns {Object} A task list object
*/
function createList() {
return objectWithType(LIST, {
head: null,
named: Object.create(null),
observers: [],
});
}
/**
* Checks if the given argument is a List instance
* @param {any} subject The value to be tested
* @returns {boolean} true if a valid List instance is given, false otherwise
*/
function isList(subject) {
return isOfType(LIST, subject);
}
/**
* Creates an instance of a task
* @param {Object} list The List instance related to this task
* @param {Object} next The next Task instance to link to
* @returns {Object} A task object
*/
function createTask(list, next) {
return objectWithType(TASK, {
list: isList(list) ? list : null,
next: isTask(next) ? next : null,
failed: false,
awaiting: null,
progress: 0.0,
});
}
/**
* Checks if the given argument is a Task instance
* @param {any} subject The value to be tested
* @returns {boolean} true if a valid Task instance is given, false otherwise
*/
function isTask(subject) {
return isOfType(TASK, subject);
}
/**
* Appends a new Task to the given List instance and notifies the list observers
* @param {Object} list A List instance
* @returns {Object} The new Task instance appended to the List or null if the
* given List instanc is not valid
*/
function increaseList(list) {
if (isList(list)) {
const task = createTask(list, list.head);
list.head = task;
notify(list, getOverallProgress(list));
return task;
}
return null;
}
/**
* Updates the internal progress value of the given Task instance and notifies
* the observers of the associated list.
* @param {Object} task The Task instance to be updated
* @param {number} value A number between 0 (inclusive) and 1 (exclusive)
* indicating the progress of the task;
* @returns {void} Nothing is returned
*/
function update(task, value) {
if (isTask(task) && isValidProgress(value) && value < 1.0) {
if (task.progress !== value) {
task.progress = value;
if (isList(task.list)) {
notify(task.list, getOverallProgress(task.list));
}
}
}
}
/**
* Sets a Task instance as finished (progress = 1.0), freezes it in order to
* prevent further modifications and notifies the observers of the associated
* list.
* @param {Object} task The Task instance to be finalized
* @returns {void} Nothing is returned
*/
function finish(task) {
if (isTask(task)) {
task.progress = 1.0;
task.awaiting = null;
Object.freeze(task);
if (isList(task.list)) {
notify(task.list, getOverallProgress(task.list));
}
}
}
/**
* Generate a summarized snapshot of the current status of the given task List
* @param {Object} list The List instance to be scanned
* @returns {Object} An obeject representing the summarized status of the list
*/
function getOverallProgress(list) {
const status = createStatus();
if (isList(list)) {
let task = list.head;
while (isTask(task)) {
status.total++;
if (isValidProgress(task.progress)) {
status.partial += task.progress;
if (task.progress === 1.0 && task.failed) status.failures++;
}
task = task.next;
}
}
if (status.total > 0) {
status.progress = status.partial / status.total;
}
return Object.freeze(status);
}
/**
* Adds a Task instance to the given list that waits on a given "thenable". When
* the thenable resolves the "finish" method is called on the newly created
* instance thus notifying the observers of the list.
* @param {Object} list The List instance to which the new task will be added
* @param {Object|Promise} thenable The thenable to be waited on
* @returns {Object} A reference to the newly created Task;
*/
function waitOn(list, thenable) {
const task = increaseList(list);
if (isTask(task)) {
task.awaiting = Promise.resolve(thenable).then(
function() {
finish(task);
},
function() {
task.failed = true;
finish(task);
}
);
return task;
}
return null;
}
/**
* Adds a Task instance to the given list using a deferred (a Promise that can
* be externally resolved) notifying the observers of the list.
* @param {Object} list The List instance to which the new task will be added
* @returns {Object} An object with references to the created deferred and task
*/
function addDeferred(list) {
const deferred = makeDeferred();
const task = waitOn(list, deferred.promise);
return Object.freeze({
deferred,
task,
});
}
/**
* Assigns a name to a specific task of the list
* @param {Object} list The List instance whose task will be named
* @param {Object} task The specified Task instance
* @param {string} name The name of the task
* @returns {boolean} Returns true on success, false otherwise
*/
function setTaskName(list, task, name) {
if (
contains(list, task) &&
list.named !== null &&
typeof list.named === 'object' &&
typeof name === 'string'
) {
list.named[name] = task;
return true;
}
return false;
}
/**
* Retrieves a task by name
* @param {Object} list The List instance whose task will be retrieved
* @param {string} name The name of the task to be retrieved
* @returns {Object} The Task instance or null if not found
*/
function getTaskByName(list, name) {
if (
isList(list) &&
list.named !== null &&
typeof list.named === 'object' &&
typeof name === 'string'
) {
const task = list.named[name];
if (isTask(task)) {
return task;
}
}
return null;
}
/**
* Adds an observer (callback function) to a given List instance
* @param {Object} list The List instance to which the observer will be appended
* @param {Function} observer The observer (function) that will be executed
* every time a change happens within the list
* @returns {boolean} Returns true on success and false otherewise
*/
function addObserver(list, observer) {
if (
isList(list) &&
Array.isArray(list.observers) &&
typeof observer === 'function'
) {
list.observers.push(observer);
return true;
}
return false;
}
/**
* Removes an observer (callback function) from a given List instance
* @param {Object} list The instance List from which the observer will removed
* @param {Function} observer The observer function to be removed
* @returns {boolean} Returns true on success and false otherewise
*/
function removeObserver(list, observer) {
if (
isList(list) &&
Array.isArray(list.observers) &&
list.observers.length > 0
) {
const index = list.observers.indexOf(observer);
if (index >= 0) {
list.observers.splice(index, 1);
return true;
}
}
return false;
}
/**
* Utils
*/
function createStatus() {
return Object.seal({
total: 0,
partial: 0.0,
progress: 0.0,
failures: 0,
});
}
function objectWithType(type, object) {
return Object.seal(Object.defineProperty(object, TYPE, { value: type }));
}
function isOfType(type, subject) {
return (
subject !== null && typeof subject === 'object' && subject[TYPE] === type
);
}
function isValidProgress(value) {
return typeof value === 'number' && value >= 0.0 && value <= 1.0;
}
function contains(list, task) {
if (isList(list) && isTask(task)) {
let item = list.head;
while (isTask(item)) {
if (item === task) {
return true;
}
item = item.next;
}
}
return false;
}
function notify(list, data) {
if (
isList(list) &&
Array.isArray(list.observers) &&
list.observers.length > 0
) {
list.observers.slice().forEach(function(observer) {
if (typeof observer === 'function') {
try {
observer(data, list);
} catch (e) {
/* Oops! */
}
}
});
}
}
/**
* Exports
*/
export {
createList,
isList,
createTask,
isTask,
increaseList,
update,
finish,
getOverallProgress,
waitOn,
addDeferred,
setTaskName,
getTaskByName,
addObserver,
removeObserver,
};
@@ -0,0 +1,175 @@
import * as utils from './progressTrackingUtils';
describe('progressTrackingUtils', () => {
describe('Creation of lists of tasks to be tracked', () => {
it('should support creation of task lists', () => {
expect(utils.createList()).toBeInstanceOf(Object);
});
it('should support validation of task lists', () => {
const list = utils.createList();
expect(utils.isList(list)).toBe(true);
expect(utils.isList(JSON.parse(JSON.stringify(list)))).toBe(false);
});
});
describe('Usage of lists of tasks to be tracked', () => {
let context;
// Mock for download
function fakeRequest(callback) {
return new Promise(resolve => {
let progress = 0.0;
setTimeout(function step() {
if (progress < 1.0) {
progress += 1 / 4;
callback(progress);
setTimeout(step);
return;
}
resolve(true);
});
});
}
beforeEach(() => {
const list = utils.createList();
const observer = jest.fn();
utils.addObserver(list, observer);
context = { list, observer };
});
it('should call observer twice for each task', () => {
const { list, observer } = context;
const promises = [
Promise.resolve('A'),
Promise.resolve('B'),
Promise.resolve('C'),
];
promises.forEach(promise => void utils.waitOn(list, promise));
return Promise.all(promises).then(() => {
expect(observer).toBeCalledTimes(6);
[
{
failures: 0,
partial: 0,
progress: 0,
total: 1,
},
{
failures: 0,
partial: 0,
progress: 0,
total: 2,
},
{
failures: 0,
partial: 0,
progress: 0,
total: 3,
},
{
failures: 0,
partial: 1.0,
progress: 1 / 3,
total: 3,
},
{
failures: 0,
partial: 2.0,
progress: 2 / 3,
total: 3,
},
{
failures: 0,
partial: 3.0,
progress: 1.0,
total: 3,
},
].forEach((item, i) => {
const result = expect.objectContaining(item);
expect(observer).nthCalledWith(i + 1, result, list);
});
expect(utils.getOverallProgress(list)).toStrictEqual({
failures: 0,
partial: 3.0,
progress: 1.0,
total: 3,
});
});
});
it('should support tasks with internal progress updates', () => {
const { list, observer } = context;
const download = utils.addDeferred(list);
const processing = download.deferred.promise.then(result => result);
const update = jest.fn(p => void utils.update(download.task, p));
download.deferred.resolve(fakeRequest(update));
utils.waitOn(list, processing);
return processing.then(() => {
expect(update).toBeCalledTimes(4);
[0.25, 0.5, 0.75, 1.0].forEach(
(value, i) => void expect(update).nthCalledWith(i + 1, value)
);
expect(observer).toBeCalledTimes(7);
[
{
failures: 0,
partial: 0,
progress: 0,
total: 1,
},
{
failures: 0,
partial: 0,
progress: 0,
total: 2,
},
{
failures: 0,
partial: 0.25,
progress: 0.125,
total: 2,
},
{
failures: 0,
partial: 0.5,
progress: 0.25,
total: 2,
},
{
failures: 0,
partial: 0.75,
progress: 0.375,
total: 2,
},
{
failures: 0,
partial: 1.0,
progress: 0.5,
total: 2,
},
{
failures: 0,
partial: 2.0,
progress: 1.0,
total: 2,
},
].forEach((item, i) => {
const result = expect.objectContaining(item);
expect(observer).nthCalledWith(i + 1, result, list);
});
});
});
});
describe('Naming of specific tasks', () => {
it('should support naming specific tasks', () => {
const list = utils.createList();
const tasks = [utils.increaseList(list), utils.increaseList(list)];
expect(utils.setTaskName(list, tasks[0], 'firstTask')).toBe(true);
expect(utils.setTaskName(list, tasks[1], 'secondTask')).toBe(true);
expect(utils.getTaskByName(list, 'secondTask')).toBe(tasks[1]);
expect(utils.getTaskByName(list, 'firstTask')).toBe(tasks[0]);
});
});
});
@@ -0,0 +1,17 @@
export default function resolveObjectPath(root, path, defaultValue) {
if (root !== null && typeof root === 'object' && typeof path === 'string') {
let value,
separator = path.indexOf('.');
if (separator >= 0) {
return resolveObjectPath(
root[path.slice(0, separator)],
path.slice(separator + 1, path.length),
defaultValue
);
}
value = root[path];
return value === undefined && defaultValue !== undefined
? defaultValue
: value;
}
}
@@ -0,0 +1,35 @@
import resolveObjectPath from './resolveObjectPath';
describe('resolveObjectPath', function() {
let config;
beforeEach(function() {
config = {
active: {
user: {
name: {
first: 'John',
last: 'Doe',
},
},
servers: [
{
ipv4: '10.0.0.1',
},
],
},
};
});
it('should safely return deeply nested values from an object', function() {
expect(resolveObjectPath(config, 'active.user.name.first')).toBe('John');
expect(resolveObjectPath(config, 'active.user.name.last')).toBe('Doe');
expect(resolveObjectPath(config, 'active.servers.0.ipv4')).toBe('10.0.0.1');
});
it('should silently return undefined when intermediate values are not valid objects', function() {
expect(resolveObjectPath(config, 'active.usr.name.first')).toBeUndefined();
expect(resolveObjectPath(config, 'active.name.last')).toBeUndefined();
expect(resolveObjectPath(config, 'active.servers.7.ipv4')).toBeUndefined();
});
});
+128
View File
@@ -3,6 +3,134 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [3.11.4](https://github.com/OHIF/Viewers/compare/@ohif/viewer@3.11.3...@ohif/viewer@3.11.4) (2020-05-04)
**Note:** Version bump only for package @ohif/viewer
## [3.11.3](https://github.com/OHIF/Viewers/compare/@ohif/viewer@3.11.2...@ohif/viewer@3.11.3) (2020-04-29)
### Bug Fixes
* Add IHEInvokeImageDisplay routes back into viewer ([#1695](https://github.com/OHIF/Viewers/issues/1695)) ([f7162ce](https://github.com/OHIF/Viewers/commit/f7162ce61708776a6c192732b0904a022bcc6b3a))
## [3.11.2](https://github.com/OHIF/Viewers/compare/@ohif/viewer@3.11.1...@ohif/viewer@3.11.2) (2020-04-28)
**Note:** Version bump only for package @ohif/viewer
## [3.11.1](https://github.com/OHIF/Viewers/compare/@ohif/viewer@3.11.0...@ohif/viewer@3.11.1) (2020-04-27)
**Note:** Version bump only for package @ohif/viewer
# [3.11.0](https://github.com/OHIF/Viewers/compare/@ohif/viewer@3.10.2...@ohif/viewer@3.11.0) (2020-04-24)
### Features
* 🎸 Seg jump to slice + show/hide ([835f64d](https://github.com/OHIF/Viewers/commit/835f64d47a9994f6a25aaf3941a4974e215e7e7f))
## [3.10.2](https://github.com/OHIF/Viewers/compare/@ohif/viewer@3.10.1...@ohif/viewer@3.10.2) (2020-04-23)
### Bug Fixes
* undefined `errorHandler` in cornerstoneWadoImageLoader configuration ([#1664](https://github.com/OHIF/Viewers/issues/1664)) ([709f147](https://github.com/OHIF/Viewers/commit/709f14708e2b0f912b5ea509114acd87af3149cb))
## [3.10.1](https://github.com/OHIF/Viewers/compare/@ohif/viewer@3.10.0...@ohif/viewer@3.10.1) (2020-04-23)
**Note:** Version bump only for package @ohif/viewer
# [3.10.0](https://github.com/OHIF/Viewers/compare/@ohif/viewer@3.9.2...@ohif/viewer@3.10.0) (2020-04-23)
### Features
* configuration to hook into XHR Error handling ([e96205d](https://github.com/OHIF/Viewers/commit/e96205de35e5bec14dc8a9a8509db3dd4e6ecdb6))
## [3.9.2](https://github.com/OHIF/Viewers/compare/@ohif/viewer@3.9.1...@ohif/viewer@3.9.2) (2020-04-22)
### Bug Fixes
* whiteLabeling should support component creation by passing React to defined fn ([#1659](https://github.com/OHIF/Viewers/issues/1659)) ([2093a00](https://github.com/OHIF/Viewers/commit/2093a0036584b2cc698c8f06fe62b334523b1029))
## [3.9.1](https://github.com/OHIF/Viewers/compare/@ohif/viewer@3.9.0...@ohif/viewer@3.9.1) (2020-04-17)
### Bug Fixes
* `showStudyList` config ([#1647](https://github.com/OHIF/Viewers/issues/1647)) ([d9fc7bb](https://github.com/OHIF/Viewers/commit/d9fc7bbb0e6d868f507c515f031aaf88a2353e2f))
# [3.9.0](https://github.com/OHIF/Viewers/compare/@ohif/viewer@3.8.21...@ohif/viewer@3.9.0) (2020-04-17)
### Features
* set the authorization header for DICOMWeb requests if provided in query string ([#1646](https://github.com/OHIF/Viewers/issues/1646)) ([450c80b](https://github.com/OHIF/Viewers/commit/450c80b9d5f172be8b5713b422370360325a0afc))
## [3.8.21](https://github.com/OHIF/Viewers/compare/@ohif/viewer@3.8.20...@ohif/viewer@3.8.21) (2020-04-15)
**Note:** Version bump only for package @ohif/viewer
## [3.8.20](https://github.com/OHIF/Viewers/compare/@ohif/viewer@3.8.19...@ohif/viewer@3.8.20) (2020-04-09)
### Bug Fixes
* Revert "refactor: Reduce bundle size ([#1575](https://github.com/OHIF/Viewers/issues/1575))" ([#1622](https://github.com/OHIF/Viewers/issues/1622)) ([d21af3f](https://github.com/OHIF/Viewers/commit/d21af3f133492fa31492413b8782936c9ff18b44))
## [3.8.19](https://github.com/OHIF/Viewers/compare/@ohif/viewer@3.8.18...@ohif/viewer@3.8.19) (2020-04-09)
**Note:** Version bump only for package @ohif/viewer
+10 -9
View File
@@ -1,6 +1,6 @@
{
"name": "@ohif/viewer",
"version": "3.8.19",
"version": "3.11.4",
"description": "OHIF Viewer",
"author": "OHIF Contributors",
"license": "MIT",
@@ -48,15 +48,16 @@
},
"dependencies": {
"@babel/runtime": "^7.5.5",
"@ohif/core": "^2.6.9",
"@ohif/extension-cornerstone": "^2.5.2",
"@ohif/extension-dicom-html": "^1.1.2",
"@ohif/core": "^2.9.2",
"@ohif/extension-cornerstone": "^2.7.0",
"@ohif/extension-dicom-html": "^1.2.1",
"@ohif/extension-dicom-microscopy": "^0.50.9",
"@ohif/extension-dicom-p10-downloader": "^0.1.0",
"@ohif/extension-dicom-pdf": "^1.0.3",
"@ohif/extension-dicom-rt": "^0.0.2",
"@ohif/extension-dicom-segmentation": "^0.1.2",
"@ohif/extension-dicom-rt": "^0.1.1",
"@ohif/extension-dicom-segmentation": "^0.2.2",
"@ohif/extension-lesion-tracker": "^0.2.0",
"@ohif/extension-vtk": "^1.3.10",
"@ohif/extension-vtk": "^1.5.2",
"@ohif/i18n": "^0.52.8",
"@ohif/ui": "^1.4.3",
"@tanem/react-nprogress": "^1.1.25",
@@ -65,8 +66,8 @@
"cornerstone-core": "^2.2.8",
"cornerstone-math": "^0.1.8",
"cornerstone-tools": "4.12.5",
"cornerstone-wado-image-loader": "^3.0.0",
"dcmjs": "^0.12.0",
"cornerstone-wado-image-loader": "^3.1.0",
"dcmjs": "^0.12.2",
"dicom-parser": "^1.8.3",
"dicomweb-client": "^0.4.4",
"hammerjs": "^2.0.8",
-1
View File
@@ -1,7 +1,6 @@
window.config = {
// default: '/'
routerBasename: '/',
whiteLabelling: {},
extensions: [],
showStudyList: true,
filterQueryParam: false,
-1
View File
@@ -1,6 +1,5 @@
window.config = {
routerBasename: '/',
whiteLabelling: {},
extensions: [],
showStudyList: true,
servers: {
@@ -1,6 +1,5 @@
window.config = {
routerBasename: '/',
whiteLabelling: {},
showStudyList: true,
servers: {
dicomWeb: [
@@ -1,6 +1,5 @@
window.config = {
routerBasename: '/',
whiteLabelling: {},
showStudyList: true,
servers: {
// This is an array, but we'll only use the first entry for now
@@ -1,6 +1,5 @@
window.config = {
routerBasename: '/',
whiteLabelling: {},
showStudyList: true,
servers: {
// This is an array, but we'll only use the first entry for now
-1
View File
@@ -1,6 +1,5 @@
window.config = {
routerBasename: '/',
whiteLabelling: {},
enableGoogleCloudAdapter: true,
healthcareApiEndpoint: 'https://healthcare.googleapis.com/v1beta1',
servers: {
+19
View File
@@ -0,0 +1,19 @@
window.config = function(props) {
var servicesManager = props.servicesManager;
return {
routerBasename: '/',
enableGoogleCloudAdapter: true,
enableGoogleCloudAdapterUI: false,
showStudyList: true,
httpErrorHandler: error => {
// This is 429 when rejected from the public idc sandbox too often.
console.warn(error.status);
// Could use services manager here to bring up a dialog/modal if needed.
console.warn('test, navigate to https://ohif.org/');
window.location = 'https://ohif.org/';
},
healthcareApiEndpoint: 'https://idc-sandbox-002.appspot.com/v1beta1',
};
};
@@ -1,7 +1,6 @@
window.config = {
// default: '/'
routerBasename: '/',
whiteLabelling: {},
// default: ''
showStudyList: true,
servers: {
-1
View File
@@ -1,6 +1,5 @@
window.config = {
routerBasename: '/pwa',
whiteLabelling: {},
showStudyList: true,
servers: {
dicomWeb: [
@@ -1,6 +1,5 @@
window.config = {
routerBasename: '/',
whiteLabelling: {},
showStudyList: true,
servers: {
dicomWeb: [
+20 -11
View File
@@ -31,10 +31,14 @@ import {
import i18n from '@ohif/i18n';
// TODO: This should not be here
import './config';
//import './config';
import { setConfiguration } from './config';
/** Utils */
import { getUserManagerForOpenIdConnectClient } from './utils/index.js';
import {
getUserManagerForOpenIdConnectClient,
initWebWorkers,
} from './utils/index.js';
/** Extensions */
import { GenericViewerCommands, MeasurementsPanel } from './appExtensions';
@@ -47,7 +51,7 @@ import { getActiveContexts } from './store/layout/selectors.js';
import store from './store';
/** Contexts */
import WhiteLabellingContext from './context/WhiteLabellingContext';
import WhiteLabelingContext from './context/WhiteLabelingContext';
import UserManagerContext from './context/UserManagerContext';
import AppContext from './context/AppContext';
@@ -74,7 +78,9 @@ class App extends Component {
PropTypes.shape({
routerBasename: PropTypes.string.isRequired,
oidc: PropTypes.array,
whiteLabelling: PropTypes.object,
whiteLabeling: PropTypes.shape({
createLogoComponentFn: PropTypes.func,
}),
extensions: PropTypes.array,
}),
]).isRequired,
@@ -83,7 +89,7 @@ class App extends Component {
static defaultProps = {
config: {
whiteLabelling: {},
showStudyList: true,
oidc: [],
extensions: [],
},
@@ -99,10 +105,10 @@ class App extends Component {
const { config, defaultExtensions } = props;
const appDefaultConfig = {
showStudyList: true,
cornerstoneExtensionConfig: {},
extensions: [],
routerBasename: '/',
whiteLabelling: {},
};
this._appConfig = {
@@ -118,6 +124,8 @@ class App extends Component {
oidc,
} = this._appConfig;
setConfiguration(this._appConfig);
this.initUserManager(oidc);
_initServices([
UINotificationService,
@@ -137,10 +145,11 @@ class App extends Component {
*/
_initHotkeys(appConfigHotkeys);
_initServers(servers);
initWebWorkers();
}
render() {
const { whiteLabelling, routerBasename } = this._appConfig;
const { whiteLabeling, routerBasename } = this._appConfig;
const {
UINotificationService,
UIDialogService,
@@ -156,7 +165,7 @@ class App extends Component {
<OidcProvider store={store} userManager={this._userManager}>
<UserManagerContext.Provider value={this._userManager}>
<Router basename={routerBasename}>
<WhiteLabellingContext.Provider value={whiteLabelling}>
<WhiteLabelingContext.Provider value={whiteLabeling}>
<SnackbarProvider service={UINotificationService}>
<DialogProvider service={UIDialogService}>
<ModalProvider
@@ -169,7 +178,7 @@ class App extends Component {
</ModalProvider>
</DialogProvider>
</SnackbarProvider>
</WhiteLabellingContext.Provider>
</WhiteLabelingContext.Provider>
</Router>
</UserManagerContext.Provider>
</OidcProvider>
@@ -184,7 +193,7 @@ class App extends Component {
<Provider store={store}>
<I18nextProvider i18n={i18n}>
<Router basename={routerBasename}>
<WhiteLabellingContext.Provider value={whiteLabelling}>
<WhiteLabelingContext.Provider value={whiteLabeling}>
<SnackbarProvider service={UINotificationService}>
<DialogProvider service={UIDialogService}>
<ModalProvider modal={OHIFModal} service={UIModalService}>
@@ -192,7 +201,7 @@ class App extends Component {
</ModalProvider>
</DialogProvider>
</SnackbarProvider>
</WhiteLabellingContext.Provider>
</WhiteLabelingContext.Provider>
</Router>
</I18nextProvider>
</Provider>
@@ -4,8 +4,16 @@
height: var(--top-bar-height);
}
.dd-item {
width: 100%;
.header-left-box {
display: inline-block;
position: relative;
}
.header-brand {
text-decoration: none;
height: 30px;
float: left;
clear: both;
}
/* Home Page */
@@ -17,35 +25,11 @@
width: 100%;
}
.header-left-box {
display: inline-block;
position: relative;
}
.header-viewerLink {
float: left;
}
.header-brand {
height: 30px;
text-decoration: none;
float: left;
clear: both;
}
.entry-header.header-big .header-brand {
height: auto;
height: 50px;
padding: 0;
}
.header-logo-image {
fill: transparent;
height: 100%;
margin: 0 8px 0 0;
width: 30px;
float: left;
}
.entry-header.header-big .header-logo-image {
margin-right: 20px;
width: 50px;
@@ -57,6 +41,24 @@
height: auto;
}
/** OTHER STYLES **/
.dd-item {
width: 100%;
}
.header-viewerLink {
float: left;
}
.header-logo-image {
fill: transparent;
height: 100%;
margin: 0 8px 0 0;
width: 30px;
float: left;
}
.header-btn {
color: var(--text-secondary-color);
cursor: pointer;
@@ -130,13 +132,6 @@
width: 40%;
}
/* Account for notification bar height */
.entry-header.header-big .header-brand {
}
.dd-menu {
}
/* Toggle Notification Bar */
.notification-bar {
display: block;
+18 -18
View File
@@ -1,30 +1,29 @@
import React, { useState, useEffect } from 'react';
import { Link, withRouter } from 'react-router-dom';
import { withTranslation } from 'react-i18next';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { Dropdown, AboutContent, withModal } from '@ohif/ui';
//
import { UserPreferences } from './../UserPreferences';
import OHIFLogo from '../OHIFLogo/OHIFLogo.js';
import './Header.css';
// Context
import AppContext from './../../context/AppContext';
function Header(props) {
const {
t,
user,
userManager,
modal: { show },
home,
useLargeLogo,
linkPath,
linkText,
location,
children,
} = props;
const [options, setOptions] = useState([]);
const hasLink = linkText && linkPath;
useEffect(() => {
const optionsValue = [
@@ -61,15 +60,12 @@ function Header(props) {
setOptions(optionsValue);
}, [setOptions, show, t, user, userManager]);
const { appConfig = {} } = AppContext;
const showStudyList =
appConfig.showStudyList !== undefined ? appConfig.showStudyList : true;
// ANTD -- Hamburger, Drawer, Menu
return (
<>
<div className="notification-bar">{t('INVESTIGATIONAL USE ONLY')}</div>
<div className={`entry-header ${home ? 'header-big' : ''}`}>
<div
className={classNames('entry-header', { 'header-big': useLargeLogo })}
>
<div className="header-left-box">
{location && location.studyLink && (
<Link
@@ -82,15 +78,15 @@ function Header(props) {
{children}
{showStudyList && !home && (
{hasLink && (
<Link
className="header-btn header-studyListLinkSection"
to={{
pathname: '/',
pathname: linkPath,
state: { studyLink: location.pathname },
}}
>
{t('Study list')}
{t(linkText)}
</Link>
)}
</div>
@@ -105,7 +101,11 @@ function Header(props) {
}
Header.propTypes = {
home: PropTypes.bool.isRequired,
// Study list, /
linkText: PropTypes.string,
linkPath: PropTypes.string,
useLargeLogo: PropTypes.bool,
//
location: PropTypes.object.isRequired,
children: PropTypes.node,
t: PropTypes.func.isRequired,
@@ -115,7 +115,7 @@ Header.propTypes = {
};
Header.defaultProps = {
home: true,
useLargeLogo: false,
children: OHIFLogo(),
};
+57 -11
View File
@@ -1,15 +1,61 @@
import OHIF from '@ohif/core';
import cornerstone from 'cornerstone-core';
import cornerstoneWADOImageLoader from 'cornerstone-wado-image-loader';
import dicomParser from 'dicom-parser';
import version from './version.js';
import AppContext from './context/AppContext';
let homepage;
const { process } = window;
if (process && process.env && process.env.PUBLIC_URL) {
homepage = process.env.PUBLIC_URL;
export function setConfiguration(appConfig) {
let homepage;
const { process } = window;
if (process && process.env && process.env.PUBLIC_URL) {
homepage = process.env.PUBLIC_URL;
}
window.info = {
version,
homepage,
};
// For debugging
//if (process.env.node_env === 'development') {
window.cornerstone = cornerstone;
window.cornerstoneWADOImageLoader = cornerstoneWADOImageLoader;
//}
cornerstoneWADOImageLoader.external.cornerstone = cornerstone;
cornerstoneWADOImageLoader.external.dicomParser = dicomParser;
OHIF.user.getAccessToken = () => {
// TODO: Get the Redux store from somewhere else
const state = window.store.getState();
if (!state.oidc || !state.oidc.user) {
return;
}
return state.oidc.user.access_token;
};
OHIF.errorHandler.getHTTPErrorHandler = () => {
// const { appConfig = {} } = AppContext;
return appConfig.httpErrorHandler;
};
cornerstoneWADOImageLoader.configure({
beforeSend: function(xhr) {
const headers = OHIF.DICOMWeb.getAuthorizationHeader();
if (headers.Authorization) {
xhr.setRequestHeader('Authorization', headers.Authorization);
}
},
errorInterceptor: error => {
// const { appConfig = {} } = AppContext;
if (typeof appConfig.httpErrorHandler === 'function') {
appConfig.httpErrorHandler(error);
}
},
});
}
window.info = {
version,
homepage,
};
window.cornerstone = cornerstone;
@@ -14,8 +14,9 @@ import SidePanel from './../components/SidePanel.js';
import { extensionManager } from './../App.js';
// Contexts
import WhiteLabellingContext from '../context/WhiteLabellingContext.js';
import WhiteLabelingContext from '../context/WhiteLabelingContext.js';
import UserManagerContext from '../context/UserManagerContext';
import AppContext from '../context/AppContext';
import './Viewer.css';
@@ -226,17 +227,33 @@ class Viewer extends Component {
return (
<>
{/* HEADER */}
<WhiteLabellingContext.Consumer>
{whiteLabelling => (
<WhiteLabelingContext.Consumer>
{whiteLabeling => (
<UserManagerContext.Consumer>
{userManager => (
<ConnectedHeader home={false} userManager={userManager}>
{whiteLabelling.logoComponent}
</ConnectedHeader>
<AppContext.Consumer>
{appContext => (
<ConnectedHeader
linkText={
appContext.appConfig.showStudyList
? 'Study List'
: undefined
}
linkPath={
appContext.appConfig.showStudyList ? '/' : undefined
}
userManager={userManager}
>
{whiteLabeling &&
whiteLabeling.createLogoComponentFn &&
whiteLabeling.createLogoComponentFn(React)}
</ConnectedHeader>
)}
</AppContext.Consumer>
)}
</UserManagerContext.Consumer>
)}
</WhiteLabellingContext.Consumer>
</WhiteLabelingContext.Consumer>
{/* TOOLBAR */}
<ConnectedToolbarRow
@@ -290,11 +307,11 @@ class Viewer extends Component {
activeIndex={this.props.activeViewportIndex}
/>
) : (
<ConnectedStudyBrowser
studies={this.state.thumbnails}
studyMetadata={this.props.studies}
/>
)}
<ConnectedStudyBrowser
studies={this.state.thumbnails}
studyMetadata={this.props.studies}
/>
)}
</SidePanel>
{/* MAIN */}
@@ -332,7 +349,7 @@ export default withDialog(Viewer);
* @param {Study[]} studies
* @param {DisplaySet[]} studies[].displaySets
*/
const _mapStudiesToThumbnails = function (studies) {
const _mapStudiesToThumbnails = function(studies) {
return studies.map(study => {
const { StudyInstanceUID } = study;
@@ -0,0 +1,10 @@
import OHIFLogo from '../components/OHIFLogo/OHIFLogo.js';
import React from 'react';
const defaultContextValues = {
createLogoComponentFn: React => OHIFLogo(),
};
const WhiteLabelingContext = React.createContext(defaultContextValues);
export default WhiteLabelingContext;
@@ -1,10 +0,0 @@
import OHIFLogo from '../components/OHIFLogo/OHIFLogo.js';
import React from 'react';
const defaultContextValues = {
logoComponent: OHIFLogo(),
};
const WhiteLabellingContext = React.createContext(defaultContextValues);
export default WhiteLabellingContext;
@@ -0,0 +1,11 @@
import { useLocation } from 'react-router-dom';
/**
* hook that builds on useLocation to parse
* the query string for you.
*
* @name useQuery
*/
export default function() {
return new URLSearchParams(useLocation().search);
}
@@ -1,5 +1,6 @@
import { httpErrorToStr, checkDicomFile } from '../utils/helpers';
import { api } from 'dicomweb-client';
import { errorHandler } from '@ohif/core';
class DicomUploadService {
async smartUpload(files, url, uploadCallback, cancellationToken) {
@@ -22,8 +23,7 @@ class DicomUploadService {
let error = null;
try {
if (chunk.length > 1) throw new Error('Not implemented');
if (chunk.length === 1)
await this.simpleUpload(chunk[0], url);
if (chunk.length === 1) await this.simpleUpload(chunk[0], url);
} catch (err) {
// It looks like a stupid bug of Babel that err is not an actual Exception object
error = httpErrorToStr(err);
@@ -76,11 +76,12 @@ class DicomUploadService {
getClient(url) {
const headers = this.retrieveAuthHeaderFunc();
const errorInterceptor = errorHandler.getHTTPErrorHandler();
// TODO: a bit weird we are creating a new dicomweb client instance for every upload
return new api.DICOMwebClient({
url,
headers
headers,
});
}
}
Loaded 100 of 114 files, more files were not shown because too many files have changed in this diff. Show more