This commit is contained in:
dannyrb 2019-07-04 16:12:43 -04:00
parent 5ac9048ef0
commit b73ea99971
714 changed files with 32644 additions and 541 deletions

View File

@ -1,93 +0,0 @@
{
// JSHint Default Configuration File (as on JSHint website)
// See http://jshint.com/docs/ for more details
"maxerr" : 50, // {int} Maximum error before stopping
// Enforcing
"bitwise" : true, // true: Prohibit bitwise operators (&, |, ^, etc.)
"camelcase" : false, // true: Identifiers must be in camelCase
"curly" : false, // true: Require {} for every new block or scope
"eqeqeq" : true, // true: Require triple equals (===) for comparison
"forin" : true, // true: Require filtering for..in loops with obj.hasOwnProperty()
"freeze" : true, // true: prohibits overwriting prototypes of native objects such as Array, Date etc.
"immed" : false, // true: Require immediate invocations to be wrapped in parens e.g. `(function () { } ());`
"latedef" : false, // true: Require variables/functions to be defined before being used
"newcap" : false, // true: Require capitalization of all constructor functions e.g. `new F()`
"noarg" : true, // true: Prohibit use of `arguments.caller` and `arguments.callee`
"noempty" : true, // true: Prohibit use of empty blocks
"nonbsp" : true, // true: Prohibit "non-breaking whitespace" characters.
"nonew" : false, // true: Prohibit use of constructors for side-effects (without assignment)
"plusplus" : false, // true: Prohibit use of `++` and `--`
"quotmark" : false, // Quotation mark consistency:
// false : do nothing (default)
// true : ensure whatever is used is consistent
// "single" : require single quotes
// "double" : require double quotes
"undef" : true, // true: Require all non-global variables to be declared (prevents global leaks)
"unused" : "vars", // Unused variables:
// true : all variables, last function parameter
// "vars" : all variables only
// "strict" : all variables, all function parameters
"strict" : false, // true: Requires all functions run in ES5 Strict Mode
"maxparams" : false, // {int} Max number of formal params allowed per function
"maxdepth" : false, // {int} Max depth of nested blocks (within functions)
"maxstatements" : false, // {int} Max number statements per function
"maxcomplexity" : false, // {int} Max cyclomatic complexity per function
"maxlen" : false, // {int} Max number of characters per line
"varstmt" : false, // true: Disallow any var statements. Only `let` and `const` are allowed.
// Relaxing
"asi" : false, // true: Tolerate Automatic Semicolon Insertion (no semicolons)
"boss" : false, // true: Tolerate assignments where comparisons would be expected
"debug" : false, // true: Allow debugger statements e.g. browser breakpoints.
"eqnull" : false, // true: Tolerate use of `== null`
"es5" : true, // true: Allow ES5 syntax (ex: getters and setters)
"esnext" : true, // true: Allow ES.next (ES6) syntax (ex: `const`)
"moz" : false, // true: Allow Mozilla specific syntax (extends and overrides esnext features)
// (ex: `for each`, multiple try/catch, function expression…)
"evil" : false, // true: Tolerate use of `eval` and `new Function()`
"expr" : false, // true: Tolerate `ExpressionStatement` as Programs
"funcscope" : false, // true: Tolerate defining variables inside control statements
"globalstrict" : false, // true: Allow global "use strict" (also enables 'strict')
"iterator" : false, // true: Tolerate using the `__iterator__` property
"lastsemic" : false, // true: Tolerate omitting a semicolon for the last statement of a 1-line block
"laxbreak" : false, // true: Tolerate possibly unsafe line breakings
"laxcomma" : false, // true: Tolerate comma-first style coding
"loopfunc" : false, // true: Tolerate functions being defined in loops
"multistr" : false, // true: Tolerate multi-line strings
"noyield" : false, // true: Tolerate generator functions with no yield statement in them.
"notypeof" : false, // true: Tolerate invalid typeof operator values
"proto" : false, // true: Tolerate using the `__proto__` property
"scripturl" : false, // true: Tolerate script-targeted URLs
"shadow" : false, // true: Allows re-define variables later in code e.g. `var x=1; x=2;`
"sub" : false, // true: Tolerate using `[]` notation when it can still be expressed in dot notation
"supernew" : false, // true: Tolerate `new function () { ... };` and `new Object;`
"validthis" : false, // true: Tolerate using this in a non-constructor function
// Environments
"browser" : true, // Web Browser (window, document, etc)
"browserify" : false, // Browserify (node.js code in the browser)
"couch" : false, // CouchDB
"devel" : false, // Development/debugging (alert, confirm, etc)
"dojo" : false, // Dojo Toolkit
"jasmine" : false, // Jasmine
"jquery" : true, // jQuery
"mocha" : false, // Mocha
"mootools" : false, // MooTools
"node" : false, // Node.js
"nonstandard" : false, // Widely adopted globals (escape, unescape, etc)
"phantom" : false, // PhantomJS
"prototypejs" : false, // Prototype and Scriptaculous
"qunit" : false, // QUnit
"rhino" : false, // Rhino
"shelljs" : false, // ShellJS
"typed" : false, // Globals for typed array constructions
"worker" : false, // Web Workers
"wsh" : false, // Windows Scripting Host
"yui" : false, // Yahoo User Interface
"globals" : {
"require": true,
"Package": true // Meteor Package definition
}
}

295
README.md
View File

@ -1,295 +1,6 @@
<!-- prettier-ignore-start -->
<!-- markdownlint-disable -->
<div align="center">
<h1>ohif-viewer</h1>
<p><strong>ohif-viewer</strong> is a zero-footprint medical image viewer provided by the <a href="http://ohif.org/">Open Health Imaging Foundation (OHIF)</a>. It is a configurable and extensible progressive web application with out-of-the-box support for image archives which support <a href="https://www.dicomstandard.org/dicomweb/">DICOMweb</a>.</p>
</div>
<div align="center">
<a href="https://docs.ohif.org/"><strong>Read The Docs</strong></a> |
<a href="https://github.com/OHIF/Viewers/tree/master/docs/latest">Edit the docs</a>
</div>
<div align="center">
<a href="https://docs.ohif.org/demo">Demo</a> |
<a href="https://ohif.canny.io/">Roadmap</a> |
<a href="https://react.ohif.org/">Component Library</a>
</div>
<hr />
[![CircleCI][circleci-image]][circleci-url]
[![codecov][codecov-image]][codecov-url]
[![All Contributors](https://img.shields.io/badge/all_contributors-9-orange.svg?style=flat-square)](#contributors)
[![code style: prettier][prettier-image]][prettier-url]
[![semantic-release][semantic-image]][semantic-url]
[![NPM version][npm-version-image]][npm-url]
[![NPM downloads][npm-downloads-image]][npm-url]
[![Pulls][docker-pulls-img]][docker-image-url]
[![MIT License][license-image]][license-url]
<!-- markdownlint-enable -->
<!-- prettier-ignore-end -->
> ATTENTION: If you are looking for Version 1 (the Meteor Version) of this
> repository, it lives on
> [the `v1.x` branch](https://github.com/OHIF/Viewers/tree/v1.x)
## Why?
Building a web based medical imaging viewer from scratch is time intensive, hard
to get right, and expensive. Instead of re-inventing the wheel, you can use the
OHIF Viewer as a rock solid platform to build on top of. The Viewer is a
[React][react-url] [Progressive Web Application][pwa-url] that can be embedded
in existing applications via it's [packaged source
(ohif-viewer)][ohif-viewer-url] or hosted stand-alone. The Viewer exposes
[configuration][configuration-url] and [extensions][extensions-url] to support
workflow customization and advanced functionality at common integration points.
If you're interested in using the OHIF Viewer, but you're not sure it supports
your use case [check out our docs](https://docs.ohif.org/). Still not sure, or
you would like to propose new features? Don't hesitate to
[create an issue](https://github.com/OHIF/Viewers/issues) or open a pull
request.
## Getting Started
This readme is specific to testing and developing locally. If you're more
interested in production deployment strategies,
[you can check out our documentation on publishing](https://docs.ohif.org/).
Want to play around before you dig in?
[Check out our LIVE Demo](https://viewer.ohif.org/)
### Setup
_Requirements:_
- [NodeJS & NPM](https://nodejs.org/en/download/)
- [Yarn](https://yarnpkg.com/lang/en/docs/install/)
_Steps:_
1. Fork this repository
2. Clone your forked repository (your `origin`)
- `git clone git@github.com:YOUR_GITHUB_USERNAME/Viewers.git`
3. Add `OHIF/Viewers` as a `remote` repository (the `upstream`)
- `git remote add upstream git@github.com:OHIF/Viewers.git`
### Developing Locally
In your cloned repository's root folder, run:
# OHIF Medical Imaging Platform
```js
// Restore dependencies
yarn install
// Stands up local server to host Viewer.
// Viewer connects to our public cloud PACS by default
yarn start
// Add shared dev dependency for workspace
yarn add --dev -W package-name
```
For more advanced local development scenarios, like using your own locally
hosted PACS and test data,
[check out our Essential: Getting Started](https://docs.ohif.org/essentials/getting-started.html)
guide.
### E2E Tests
Using [Cypress](https://www.cypress.io/) to create End-to-End tests and check whether the application flow is performing correctly, ensuring that the integrated components are working as expected.
#### Why Cypress?
Cypress is a next generation front end testing tool built for the modern web.
With Cypress is easy to set up, write, run and debug tests
It allow us to write different types of tests:
- End-to-End tests
- Integration tests
- Unit tets
All tests must be in `./cypress/integration` folder.
Commands to run the tests:
```js
// Open Cypress Dashboard that provides insight into what happened when your tests ran
yarn run cy
// Run all tests using Electron browser headless
yarn run cy:run
// Run all tests in CI mode
yarn run cy:run:ci
```
### Contributing
> Large portions of the Viewer's functionality are maintained in other
> repositories. To get a better understanding of the Viewer's architecture and
> "where things live", read
> [our docs on the Viewer's architecture](https://docs.ohif.org/advanced/architecture.html#diagram)
It is notoriously difficult to setup multiple dependent repositories for
end-to-end testing and development. That's why we recommend writing and running
unit tests when adding and modifying features. This allows us to program in
isolation without a complex setup, and has the added benefit of producing
well-tested business logic.
1. Clone this repository
2. Navigate to the project directory, and `yarn install`
3. To begin making changes, `yarn run dev`
4. To commit changes, run `yarn run cm`
When creating tests, place the test file "next to" the file you're testing.
[For example](https://github.com/OHIF/Viewers/blob/master/src/utils/index.test.js):
```js
// File
index.js
// Test for file
index.test.js
```
As you add and modify code, `jest` will watch for uncommitted changes and run
your tests, reporting the results to your terminal. Make a pull request with
your changes to `master`, and a core team member will review your work. If you
have any questions, please don't hesitate to reach out via a GitHub issue.
## Issues
_Looking to contribute? Look for the [Good First Issue][good-first-issue]
label._
### 🐛 Bugs
Please file an issue for bugs, missing documentation, or unexpected behavior.
[**See Bugs**][bugs]
### 💡 Feature Requests
Please file an issue to suggest new features. Vote on feature requests by adding
a 👍. This helps maintainers prioritize what to work on.
[**See Feature Requests**][requests-feature]
### ❓ Questions
For questions related to using the library, please visit our support community,
or file an issue on GitHub.
[Google Group][google-group]
## Roadmap
If you want to know what's planned for the very near future,
[check out our roadmap](https://ohif.canny.io/). The best way to influence when
and what is worked on is to contribute to the conversation by creating GitHub
issues, and contributing code through pull requests. OHIF's high level
priorities for the near future are:
- Feature parity with version 1
- Extension and configuration improvements with key integration partners
- Continued Developer Experience Improvements
- Segmentation Tools, and improved VTK.js support
More granular information will make it's way to the backlog as these items
become scoped for development by core maintainers.
> Don't hesitate to ask questions, propose features, or create pull requests.
> We're here, we're listening, and we're ready to build the best open source
> medical imaging viewer on the web.
#### Roadmap Generously Powered by Canny.io
<a href="https://ohif.canny.io/">
<img height="30" src="docs/latest/assets/img/canny-full.png" />
</a>
## Contributors
Thanks goes to these wonderful people
([emoji key](https://allcontributors.org/docs/en/emoji-key)):
<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
<!-- prettier-ignore -->
<table><tr><td align="center"><a href="https://github.com/swederik"><img src="https://avatars3.githubusercontent.com/u/607793?v=4" width="100px;" alt="Erik Ziegler"/><br /><sub><b>Erik Ziegler</b></sub></a><br /><a href="https://github.com/OHIF/Viewers/commits?author=swederik" title="Code">💻</a> <a href="#infra-swederik" title="Infrastructure (Hosting, Build-Tools, etc)">🚇</a></td><td align="center"><a href="https://github.com/evren217"><img src="https://avatars1.githubusercontent.com/u/4920551?v=4" width="100px;" alt="Evren Ozkan"/><br /><sub><b>Evren Ozkan</b></sub></a><br /><a href="https://github.com/OHIF/Viewers/commits?author=evren217" title="Code">💻</a></td><td align="center"><a href="https://github.com/galelis"><img src="https://avatars3.githubusercontent.com/u/2378326?v=4" width="100px;" alt="Gustavo André Lelis"/><br /><sub><b>Gustavo André Lelis</b></sub></a><br /><a href="https://github.com/OHIF/Viewers/commits?author=galelis" title="Code">💻</a></td><td align="center"><a href="http://dannyrb.com/"><img src="https://avatars1.githubusercontent.com/u/5797588?v=4" width="100px;" alt="Danny Brown"/><br /><sub><b>Danny Brown</b></sub></a><br /><a href="https://github.com/OHIF/Viewers/commits?author=dannyrb" title="Code">💻</a> <a href="#infra-dannyrb" title="Infrastructure (Hosting, Build-Tools, etc)">🚇</a></td><td align="center"><a href="https://github.com/all-contributors/all-contributors-bot"><img src="https://avatars3.githubusercontent.com/u/46843839?v=4" width="100px;" alt="allcontributors[bot]"/><br /><sub><b>allcontributors[bot]</b></sub></a><br /><a href="https://github.com/OHIF/Viewers/commits?author=allcontributors" title="Documentation">📖</a></td><td align="center"><a href="https://www.linkedin.com/in/siliconvalleynextgeneration/"><img src="https://avatars0.githubusercontent.com/u/1230575?v=4" width="100px;" alt="Esref Durna"/><br /><sub><b>Esref Durna</b></sub></a><br /><a href="#question-EsrefDurna" title="Answering Questions">💬</a></td><td align="center"><a href="https://github.com/diego0020"><img src="https://avatars3.githubusercontent.com/u/7297450?v=4" width="100px;" alt="diego0020"/><br /><sub><b>diego0020</b></sub></a><br /><a href="https://github.com/OHIF/Viewers/commits?author=diego0020" title="Code">💻</a></td></tr><tr><td align="center"><a href="https://github.com/dlwire"><img src="https://avatars3.githubusercontent.com/u/1167291?v=4" width="100px;" alt="David Wire"/><br /><sub><b>David Wire</b></sub></a><br /><a href="https://github.com/OHIF/Viewers/commits?author=dlwire" title="Code">💻</a></td><td align="center"><a href="https://github.com/jfmedeiros1820"><img src="https://avatars1.githubusercontent.com/u/2211708?v=4" width="100px;" alt="João Felipe de Medeiros Moreira"/><br /><sub><b>João Felipe de Medeiros Moreira</b></sub></a><br /><a href="https://github.com/OHIF/Viewers/commits?author=jfmedeiros1820" title="Tests">⚠️</a></td></tr></table>
<!-- ALL-CONTRIBUTORS-LIST:END -->
This project follows the
[all-contributors](https://github.com/all-contributors/all-contributors)
specification. Contributions of any kind welcome!
## License
MIT © [OHIF](https://github.com/OHIF)
## Acknowledgments
To acknowledge the OHIF Viewer in an academic publication, please cite
> _LesionTracker: Extensible Open-Source Zero-Footprint Web Viewer for Cancer
> Imaging Research and Clinical Trials_
>
> Trinity Urban, Erik Ziegler, Rob Lewis, Chris Hafey, Cheryl Sadow, Annick D.
> Van den Abbeele and Gordon J. Harris
>
> _Cancer Research_, November 1 2017 (77) (21) e119-e122 DOI:
> [10.1158/0008-5472.CAN-17-0334](https://www.doi.org/10.1158/0008-5472.CAN-17-0334)
**Note:** If you use or find this repository helpful, please take the time to
star this repository on Github. This is an easy way for us to assess adoption
and it can help us obtain future funding for the project.
This work is supported primarily by the National Institutes of Health, National
Cancer Institute, Informatics Technology for Cancer Research (ITCR) program,
under a
[grant to Dr. Gordon Harris at Massachusetts General Hospital (U24 CA199460)](https://projectreporter.nih.gov/project_info_description.cfm?aid=8971104).
<!--
Links:
-->
<!-- prettier-ignore-start -->
<!-- ROW -->
[all-contributors-image]: https://img.shields.io/badge/all_contributors-0-orange.svg?style=flat-square
[contributing-url]: https://github.com/OHIF/Viewers/blob/react/CONTRIBUTING.md
[circleci-image]: https://circleci.com/gh/OHIF/Viewers.svg?style=svg
[circleci-url]: https://circleci.com/gh/OHIF/Viewers
[codecov-image]: https://codecov.io/gh/OHIF/Viewers/branch/react/graph/badge.svg
[codecov-url]: https://codecov.io/gh/OHIF/Viewers/branch/react
[prettier-image]: https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square
[prettier-url]: https://github.com/prettier/prettier
[semantic-image]: https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg
[semantic-url]: https://github.com/semantic-release/semantic-release
<!-- ROW -->
[npm-url]: https://npmjs.org/package/ohif-viewer
[npm-downloads-image]: https://img.shields.io/npm/dm/ohif-viewer.svg?style=flat-square
[npm-version-image]: https://img.shields.io/npm/v/ohif-viewer.svg?style=flat-square
[docker-pulls-img]: https://img.shields.io/docker/pulls/ohif/viewer.svg?style=flat-square
[docker-image-url]: https://hub.docker.com/r/ohif/viewer
[license-image]: https://img.shields.io/badge/license-MIT-blue.svg?style=flat-square
[license-url]: LICENSE
<!-- DOCS -->
[react-url]: https://reactjs.org/
[pwa-url]: https://developers.google.com/web/progressive-web-apps/
[ohif-viewer-url]: https://www.npmjs.com/package/ohif-viewer
[configuration-url]: https://docs.ohif.org/essentials/configuration.html
[extensions-url]: https://docs.ohif.org/advanced/extensions.html
<!-- Misc. -->
[react-viewer]: https://github.com/OHIF/Viewers/tree/react
<!-- Issue Boilerplate -->
[bugs]: https://github.com/OHIF/Viewers/labels/bug
[requests-feature]: https://github.com/OHIF/Viewers/labels/enhancement
[good-first-issue]: https://github.com/OHIF/Viewers/labels/good%20first%20issue
[google-group]: https://groups.google.com/forum/#!forum/cornerstone-platform
<!-- prettier-ignore-end -->

20
babel.config.js Normal file
View File

@ -0,0 +1,20 @@
module.exports = {
presets: [
[
"@babel/preset-env",
{
targets: {
ie: "11"
}
}
],
"@babel/preset-react"
],
plugins: [
"@babel/plugin-proposal-class-properties",
"@babel/plugin-proposal-object-rest-spread",
"@babel/plugin-syntax-dynamic-import",
"@babel/plugin-transform-regenerator",
"@babel/plugin-transform-runtime"
]
};

6
lerna.json Normal file
View File

@ -0,0 +1,6 @@
{
"packages": ["packages/*"],
"npmClient": "yarn",
"useWorkspaces": true,
"version": "independent"
}

View File

@ -1,162 +1,13 @@
{
"name": "ohif-viewer",
"version": "0.0.21",
"description": "OHIF Viewer",
"author": "OHIF Contributors",
"license": "MIT",
"repository": "OHIF/Viewers",
"main": "dist/index.umd.js",
"browser": "dist/index.umd.js",
"module": "dist/index.es.js",
"jsnext:main": "dist/index.es.js",
"engines": {
"node": ">=8",
"npm": ">=5"
},
"proxy": "http://localhost:8042",
"scripts": {
"cm": "npx git-cz",
"dev": "yarn run preBuild && cross-env PORT=5000 react-scripts start",
"dev:debug": "cross-env PORT=5000 react-scripts start",
"build:package": "yarn run preBuild && node --max-old-space-size=4096 node_modules/rollup/bin/rollup -c",
"build:package:ci": "yarn run preBuild && node --max-old-space-size=4096 node_modules/rollup/bin/rollup -c",
"build:web": "yarn run preBuild && react-scripts --max_old_space_size=4096 build",
"build:web:ci": "yarn run preBuild && cross-env PUBLIC_URL=/demo REACT_APP_CONFIG=config/netlify.js react-scripts --max_old_space_size=4096 build && cpx 'build/**/*' docs/latest/_book/demo --verbose",
"build:demo:ci": "yarn run preBuild && cross-env PUBLIC_URL=/ REACT_APP_CONFIG=config/demo.js react-scripts --max_old_space_size=4096 build",
"lint": "eslint -c .eslintrc --fix src && prettier --single-quote --write src/**/*.{js,jsx,json,css}",
"test:unit": "jest",
"test:unit:ci": "jest --ci --runInBand --collectCoverage --reporters=default --reporters=jest-junit && codecov",
"test:e2e": "",
"test:e2e:ci": "start-server-and-test start http://localhost:5000 cy:run:ci",
"staticDeploy": "./generateStaticSite.sh",
"docs:publish": "./publishStaticSite.sh",
"start": "yarn run dev",
"predeploy": "cd example && npm install && yarn run build:package",
"preBuild": "yarn run version && yarn run copy:webworkers",
"orthanc:up": "docker-compose -f docker/Nginx-Orthanc/docker-compose.yml up",
"dev:orthanc": "yarn run preBuild && cross-env PORT=5000 REACT_APP_CONFIG=config/docker_nginx-orthanc.js react-scripts start",
"version": "node -p -e \"'export default \\'' + require('./package.json').version + '\\';'\" > src/version.js",
"copy:webworkers": "cpx \"node_modules/cornerstone-wado-image-loader/dist/*.min.js*\" \"public\" -v",
"cy": "cypress open",
"cy:run": "cypress run",
"cy:run:ci": "yarn run cy:run -- --record"
},
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"src/**/*.{js,jsx,json,css}": [
"prettier --single-quote --write",
"git add"
]
},
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
"name": "root",
"private": true,
"workspaces": [
"packages/*"
],
"resolutions": {
"browserslist": "4.6.2",
"caniuse-lite": "1.0.30000974"
},
"files": [
"dist"
],
"config": {
"commitizen": {
"path": "./node_modules/cz-conventional-changelog"
}
},
"peerDependencies": {
"react": "^16.8.6",
"react-dom": "^16.8.6"
},
"dependencies": {
"@babel/runtime": "^7.4.5",
"@ohif/extension-cornerstone": "0.0.38",
"@ohif/extension-dicom-html": "0.0.3",
"@ohif/extension-dicom-microscopy": "0.0.8",
"@ohif/extension-dicom-pdf": "0.0.7",
"@ohif/extension-vtk": "0.1.3",
"@ohif/i18n": "0.2.2",
"@tanem/react-nprogress": "^1.1.25",
"classnames": "^2.2.6",
"cornerstone-core": "^2.2.8",
"cornerstone-math": "^0.1.8",
"cornerstone-tools": "^3.15.1",
"cornerstone-wado-image-loader": "^2.2.3",
"dcmjs": "^0.4.7",
"dicom-parser": "^1.8.3",
"dicomweb-client": "^0.4.4",
"hammerjs": "^2.0.8",
"i18next": "^17.0.3",
"i18next-browser-languagedetector": "^3.0.1",
"lodash.isequal": "4.5.0",
"moment": "^2.24.0",
"ohif-core": "0.9.1",
"oidc-client": "1.7.x",
"prop-types": "^15.7.2",
"react-i18next": "^10.11.0",
"react-redux": "^7.1.0",
"react-resize-detector": "^4.2.0",
"react-router": "^5.0.1",
"react-router-dom": "^5.0.1",
"react-transition-group": "^4.1.1",
"react-viewerbase": "0.15.3",
"redux": "^4.0.1",
"redux-logger": "^3.0.6",
"redux-oidc": "3.1.x",
"redux-thunk": "^2.3.0",
"reselect": "^4.0.0"
},
"devDependencies": {
"@babel/core": "^7.4.5",
"@babel/plugin-proposal-class-properties": "^7.4.4",
"@babel/plugin-syntax-dynamic-import": "^7.2.0",
"@babel/plugin-transform-runtime": "^7.4.4",
"@babel/preset-env": "^7.4.5",
"@babel/core": "^7.5.0",
"@babel/preset-env": "^7.5.0",
"@babel/preset-react": "^7.0.0",
"@semantic-release/exec": "3.3.3",
"@svgr/rollup": "^4.3.0",
"babel-eslint": "10.0.1",
"codecov": "3.5.0",
"commitizen": "3.1.x",
"core-js": "^3.1.4",
"cpx": "1.5.0",
"cross-env": "^5.2.0",
"cypress": "^3.3.1",
"cz-conventional-changelog": "2.1.0",
"eslint": "5.16.0",
"eslint-plugin-import": "^2.17.3",
"eslint-plugin-node": "^9.1.0",
"eslint-plugin-promise": "^4.1.1",
"eslint-plugin-react": "^7.13.0",
"gh-pages": "2.0.1",
"husky": "2.4.x",
"identity-obj-proxy": "3.0.x",
"jest-canvas-mock": "2.1.0",
"jest-junit": "6.4.x",
"lint-staged": "^8.2.1",
"lodash": "4.17.11",
"lodash.clonedeep": "4.5.0",
"prettier": "1.18.x",
"react": "^16.7.0",
"react-dom": "^16.7.0",
"react-scripts": "^3.0.1",
"rollup": "^1.15.5",
"rollup-plugin-babel": "^4.3.2",
"rollup-plugin-commonjs": "^10.0.0",
"rollup-plugin-json": "^4.0.0",
"rollup-plugin-node-builtins": "^2.1.2",
"rollup-plugin-node-resolve": "^5.0.2",
"rollup-plugin-peer-deps-external": "^2.2.0",
"rollup-plugin-postcss": "^2.0.3",
"rollup-plugin-url": "^2.2.2",
"semantic-release": "15.13.x",
"start-server-and-test": "^1.9.1",
"stylelint": "^10.1.0"
"lerna": "^3.15.0"
}
}

View File

@ -0,0 +1,69 @@
{
"files": [
"README.md"
],
"imageSize": 100,
"commit": false,
"contributors": [
{
"login": "swederik",
"name": "Erik Ziegler",
"avatar_url": "https://avatars3.githubusercontent.com/u/607793?v=4",
"profile": "https://github.com/swederik",
"contributions": [
"code"
]
},
{
"login": "evren217",
"name": "Evren Ozkan",
"avatar_url": "https://avatars1.githubusercontent.com/u/4920551?v=4",
"profile": "https://github.com/evren217",
"contributions": [
"code"
]
},
{
"login": "galelis",
"name": "Gustavo André Lelis",
"avatar_url": "https://avatars3.githubusercontent.com/u/2378326?v=4",
"profile": "https://github.com/galelis",
"contributions": [
"code"
]
},
{
"login": "dannyrb",
"name": "Danny Brown",
"avatar_url": "https://avatars1.githubusercontent.com/u/5797588?v=4",
"profile": "http://dannyrb.com/",
"contributions": [
"code"
]
},
{
"login": "allcontributors",
"name": "allcontributors[bot]",
"avatar_url": "https://avatars3.githubusercontent.com/u/46843839?v=4",
"profile": "https://github.com/all-contributors/all-contributors-bot",
"contributions": [
"doc"
]
},
{
"login": "ivan-aksamentov",
"name": "Ivan Aksamentov",
"avatar_url": "https://avatars0.githubusercontent.com/u/9403403?v=4",
"profile": "https://github.com/ivan-aksamentov",
"contributions": [
"code",
"test"
]
}
],
"contributorsPerLine": 7,
"projectName": "ohif-core",
"projectOwner": "OHIF",
"repoType": "github",
"repoHost": "https://github.com"
}

7
packages/_core/.eslintrc Normal file
View File

@ -0,0 +1,7 @@
{
"extends": ["eslint:recommended", "plugin:prettier/recommended"],
"parser": "babel-eslint",
"env": {
"jest": true
}
}

1
packages/_core/.gitattributes vendored Normal file
View File

@ -0,0 +1 @@
* text eol=lf

27
packages/_core/.gitignore vendored Normal file
View File

@ -0,0 +1,27 @@
# See https://help.github.com/ignore-files/ for more about ignoring files.
# dependencies
node_modules
# builds
build
dist
.rpt2_cache
coverage/
junit.xml
# misc
.DS_Store
.env
.env.local
.env.development.local
.env.test.local
.env.production.local
package-lock.json
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.idea
.yalc
yalc.lock

View File

@ -0,0 +1,3 @@
{
"recommendations": ["esbenp.prettier-vscode", "dbaeumer.vscode-eslint"]
}

29
packages/_core/.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,29 @@
{
"editor.rulers": [80, 120],
// ===
// Spacing
// ===
"editor.insertSpaces": true,
"editor.tabSize": 2,
"editor.trimAutoWhitespace": true,
"files.trimTrailingWhitespace": true,
"files.eol": "\n",
"files.insertFinalNewline": true,
"files.trimFinalNewlines": true,
// ===
// Event Triggers
// ===
"editor.formatOnSave": true,
"eslint.autoFixOnSave": true,
"eslint.run": "onSave",
"eslint.validate": [
{ "language": "javascript", "autoFix": true },
{ "language": "javascriptreact", "autoFix": true }
],
"prettier.disableLanguages": [],
"prettier.endOfLine": "lf"
}

181
packages/_core/README.md Normal file
View File

@ -0,0 +1,181 @@
<!-- prettier-ignore-start -->
<!-- markdownlint-disable -->
<div align="center">
<h1>ohif-core</h1>
<p><strong>ohif-core</strong> is a collection of useful functions and classes for building web-based medical imaging applications. This library helps power OHIF's <a href="https://github.com/OHIF/Viewers">zero-footprint DICOM viewer</a>.</p>
</div>
<hr />
[![CircleCI][circleci-image]][circleci-url]
[![codecov][codecov-image]][codecov-url]
[![All Contributors](https://img.shields.io/badge/all_contributors-6-orange.svg?style=flat-square)](#contributors)
[![code style: prettier][prettier-image]][prettier-url]
[![semantic-release][semantic-image]][semantic-url]
[![NPM version][npm-version-image]][npm-url]
[![NPM downloads][npm-downloads-image]][npm-url]
[![MIT License][license-image]][license-url]
<!-- markdownlint-enable -->
<!-- prettier-ignore-end -->
## Why?
This library offers pre-packaged solutions for features common to Web-based
medical imaging viewers. For example:
- Hotkeys
- DICOM Web
- Hanging Protocols
- Managing a study's measurements
- Managing a study's DICOM metadata
- A flexible pattern for extensions
- And many others
It does this while remaining decoupled from any particular view library or
rendering logic. While we use it to power our [React Viewer][react-viewer], it
can be used with Vue, React, Vanilla JS, or any number of other frameworks.
## Getting Started
The documentation for this library is sparse. The best way to get started is to
look at its
[top level exports](https://github.com/OHIF/ohif-core/blob/master/src/index.js),
and explore the source code of features that interest you. If you want to see
how we use this library, you can check out [our viewer
implementation][react-viewer].
### Install
> This library is pre- v1.0. All realeases until a v1.0 have the possibility of
> introducing breaking changes. Please depend on an "exact" version in your
> projects to prevent issues caused by loose versioning.
```
// with npm
npm i ohif-core --save-exact
// with yarn
yarn add ohif-core --exact
```
### Usage
Usage is dependent on the feature(s) you want to leverage. The bulk of
`ohif-core`'s features are "pure" and can be imported and used in place.
_Example: retrieving study metadata from a server_
```js
import { studies } from 'ohif-core'
const studiesMetadata = await studies.retrieveStudiesMetadata(
server, // Object
studyInstanceUids, // Array
seriesInstanceUids // Array (optional)
)
```
### Contributing
It is notoriously difficult to setup multiple dependent repositories for
end-to-end testing and development. That's why we recommend writing and running
unit tests when adding and modifying features for this library. This allows us
to program in isolation without a complex setup, and has the added benefit of
producing well-tested business logic.
1. Clone this repository
2. Navigate to the project directory, and `yarn install`
3. To begin making changes, `yarn run dev`
4. To commit changes, run `yarn run cm`
When creating tests, place the test file "next to" the file you're testing.
[For example](https://github.com/OHIF/ohif-core/blob/master/src/index.test.js):
```js
// File
index.js
// Test for file
index.test.js
```
As you add and modify code, `jest` will watch for uncommitted changes and run
your tests, reporting the results to your terminal. Make a pull request with
your changes to `master`, and a core team member will review your work. If you
have any questions, please don't hesitate to reach out via a GitHub issue.
## Issues
_Looking to contribute? Look for the [Good First Issue][good-first-issue]
label._
### 🐛 Bugs
Please file an issue for bugs, missing documentation, or unexpected behavior.
[**See Bugs**][bugs]
### 💡 Feature Requests
Please file an issue to suggest new features. Vote on feature requests by adding
a 👍. This helps maintainers prioritize what to work on.
[**See Feature Requests**][requests-feature]
### ❓ Questions
For questions related to using the library, please visit our support community,
or file an issue on GitHub.
[Google Group][google-group]
## Contributors
Thanks goes to these wonderful people
([emoji key](https://allcontributors.org/docs/en/emoji-key)):
<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
<!-- prettier-ignore -->
<table><tr><td align="center"><a href="https://github.com/swederik"><img src="https://avatars3.githubusercontent.com/u/607793?v=4" width="100px;" alt="Erik Ziegler"/><br /><sub><b>Erik Ziegler</b></sub></a><br /><a href="https://github.com/OHIF/ohif-core/commits?author=swederik" title="Code">💻</a></td><td align="center"><a href="https://github.com/evren217"><img src="https://avatars1.githubusercontent.com/u/4920551?v=4" width="100px;" alt="Evren Ozkan"/><br /><sub><b>Evren Ozkan</b></sub></a><br /><a href="https://github.com/OHIF/ohif-core/commits?author=evren217" title="Code">💻</a></td><td align="center"><a href="https://github.com/galelis"><img src="https://avatars3.githubusercontent.com/u/2378326?v=4" width="100px;" alt="Gustavo André Lelis"/><br /><sub><b>Gustavo André Lelis</b></sub></a><br /><a href="https://github.com/OHIF/ohif-core/commits?author=galelis" title="Code">💻</a></td><td align="center"><a href="http://dannyrb.com/"><img src="https://avatars1.githubusercontent.com/u/5797588?v=4" width="100px;" alt="Danny Brown"/><br /><sub><b>Danny Brown</b></sub></a><br /><a href="https://github.com/OHIF/ohif-core/commits?author=dannyrb" title="Code">💻</a></td><td align="center"><a href="https://github.com/all-contributors/all-contributors-bot"><img src="https://avatars3.githubusercontent.com/u/46843839?v=4" width="100px;" alt="allcontributors[bot]"/><br /><sub><b>allcontributors[bot]</b></sub></a><br /><a href="https://github.com/OHIF/ohif-core/commits?author=allcontributors" title="Documentation">📖</a></td><td align="center"><a href="https://github.com/ivan-aksamentov"><img src="https://avatars0.githubusercontent.com/u/9403403?v=4" width="100px;" alt="Ivan Aksamentov"/><br /><sub><b>Ivan Aksamentov</b></sub></a><br /><a href="https://github.com/OHIF/ohif-core/commits?author=ivan-aksamentov" title="Code">💻</a> <a href="https://github.com/OHIF/ohif-core/commits?author=ivan-aksamentov" title="Tests">⚠️</a></td></tr></table>
<!-- ALL-CONTRIBUTORS-LIST:END -->
This project follows the
[all-contributors](https://github.com/all-contributors/all-contributors)
specification. Contributions of any kind welcome!
## License
MIT © [OHIF](https://github.com/OHIF)
<!--
Links:
-->
<!-- prettier-ignore-start -->
<!-- ROW -->
[all-contributors-image]: https://img.shields.io/badge/all_contributors-0-orange.svg?style=flat-square
[contributing-url]: https://github.com/OHIF/ohif-core/blob/master/CONTRIBUTING.md
[circleci-image]: https://circleci.com/gh/OHIF/ohif-core.svg?style=svg
[circleci-url]: https://circleci.com/gh/OHIF/ohif-core
[codecov-image]: https://codecov.io/gh/OHIF/ohif-core/branch/master/graph/badge.svg
[codecov-url]: https://codecov.io/gh/OHIF/ohif-core
[prettier-image]: https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square
[prettier-url]: https://github.com/prettier/prettier
[semantic-image]: https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg
[semantic-url]: https://github.com/semantic-release/semantic-release
<!-- ROW -->
[npm-url]: https://npmjs.org/package/ohif-core
[npm-downloads-image]: https://img.shields.io/npm/dm/ohif-core.svg?style=flat-square
[npm-version-image]: https://img.shields.io/npm/v/ohif-core.svg?style=flat-square
[license-image]: https://img.shields.io/badge/license-MIT-blue.svg?style=flat-square
[license-url]: LICENSE
<!-- Misc. -->
[react-viewer]: https://github.com/OHIF/Viewers/tree/react
<!-- Issue Boilerplate -->
[bugs]: https://github.com/OHIF/ohif-core/labels/bug
[requests-feature]: https://github.com/OHIF/ohif-core/labels/enhancement
[good-first-issue]: https://github.com/OHIF/ohif-core/labels/good%20first%20issue
[google-group]: https://groups.google.com/forum/#!forum/cornerstone-platform
<!-- prettier-ignore-end -->

View File

@ -0,0 +1,13 @@
module.exports = {
verbose: true,
testPathIgnorePatterns: ["<rootDir>/node_modules/"],
testMatch: ["<rootDir>/src/**/*.test.js"],
//
collectCoverage: false,
collectCoverageFrom: [
"**/*.{js,jsx}",
"!**/node_modules/**",
"!<rootDir>/dist/**"
],
reporters: ["default", "jest-junit"]
};

106
packages/_core/package.json Normal file
View File

@ -0,0 +1,106 @@
{
"name": "ohif-core",
"version": "0.4.0",
"description": "Useful functions and classes for building web-based medical imaging applications",
"author": "OHIF",
"license": "MIT",
"repository": "OHIF/ohif-core",
"main": "dist/index.umd.js",
"module": "dist/index.es.js",
"jsnext:main": "dist/index.es.js",
"engines": {
"node": ">=8",
"npm": ">=5"
},
"scripts": {
"cm": "npx git-cz",
"build": "rollup -c",
"dev": "jest --watch",
"start": "rollup -c -w",
"test": "jest",
"test:ci": "jest --ci --runInBand --collectCoverage --reporters=default --reporters=jest-junit && codecov",
"lint": "eslint -c .eslintrc --fix src && prettier --single-quote --write src/**/*.{js,jsx,json,css}",
"prepublishOnly": "npm run build"
},
"peerDependencies": {
"cornerstone-core": "^2.2.8",
"cornerstone-tools": "^3.9.0",
"cornerstone-wado-image-loader": "^2.2.3",
"dicom-parser": "^1.8.3"
},
"dependencies": {
"@babel/runtime": "^7.2.0",
"ajv": "^6.10.0",
"dicomweb-client": "^0.4.2",
"isomorphic-base64": "^1.0.2",
"lodash.clonedeep": "^4.5.0",
"lodash.merge": "^4.6.1",
"mousetrap": "^1.6.3",
"validate.js": "^0.12.0"
},
"devDependencies": {
"@babel/core": "^7.2.0",
"@babel/plugin-external-helpers": "^7.2.0",
"@babel/plugin-proposal-class-properties": "^7.2.1",
"@babel/plugin-proposal-object-rest-spread": "^7.4.4",
"@babel/plugin-transform-runtime": "^7.2.0",
"@babel/preset-env": "^7.2.0",
"@babel/preset-react": "^7.0.0",
"@svgr/rollup": "^4.1.0",
"babel-eslint": "10.0.1",
"babel-jest": "^24.7.1",
"codecov": "^3.3.0",
"commitizen": "3.1.x",
"cross-env": "^5.2.0",
"cz-conventional-changelog": "2.1.x",
"eslint": "5.13.0",
"eslint-config-prettier": "^4.3.0",
"eslint-plugin-import": "^2.14.0",
"eslint-plugin-node": "^8.0.0",
"eslint-plugin-prettier": "^3.1.0",
"eslint-plugin-promise": "^4.0.1",
"husky": "^1.2.1",
"jest": "^24.7.1",
"jest-junit": "^6.3.0",
"lint-staged": "^8.1.0",
"prettier": "^1.15.3",
"redux-testkit": "^1.0.6",
"rollup": "^1.1.2",
"rollup-plugin-babel": "^4.1.0",
"rollup-plugin-commonjs": "^9.2.0",
"rollup-plugin-json": "^4.0.0",
"rollup-plugin-node-resolve": "^4.0.0",
"rollup-plugin-peer-deps-external": "^2.2.0",
"rollup-plugin-postcss": "^2.0.3",
"rollup-plugin-url": "^2.1.0",
"semantic-release": "15.13.x",
"stylelint": "^9.9.0",
"stylelint-config-recommended": "^2.1.0",
"stylus": "^0.54.5"
},
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"src/**/*.{js,jsx,json,css}": [
"prettier --single-quote --write",
"git add"
]
},
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
],
"files": [
"dist"
],
"config": {
"commitizen": {
"path": "./node_modules/cz-conventional-changelog"
}
}
}

View File

@ -0,0 +1,64 @@
import babel from 'rollup-plugin-babel'
import commonjs from 'rollup-plugin-commonjs'
import external from 'rollup-plugin-peer-deps-external'
import postcss from 'rollup-plugin-postcss'
import resolve from 'rollup-plugin-node-resolve'
import url from 'rollup-plugin-url'
import json from 'rollup-plugin-json'
import svgr from '@svgr/rollup'
import pkg from './package.json'
const globals = {
'react': 'React',
'react-dom': 'ReactDOM',
'cornerstone-core': 'cornerstone',
'cornerstone-math': 'cornerstoneMath',
'cornerstone-tools': 'cornerstoneTools',
'cornerstone-wado-image-loader': 'cornerstoneWADOImageLoader',
'dicom-parser': 'dicomParser'
};
export default {
input: 'src/index.js',
output: [
{
file: pkg.main,
format: 'umd',
name: 'OHIF',
sourcemap: true,
exports: 'named',
globals
},
{
file: pkg.module,
format: 'es',
sourcemap: true,
exports: 'named',
globals
},
],
plugins: [
external(),
postcss({
modules: false
}),
url(),
json(),
svgr(),
babel({
exclude: 'node_modules/**',
externalHelpers: false,
runtimeHelpers: true
}),
resolve(),
commonjs({
include: 'node_modules/**',
namedExports: {
'node_modules/dicomweb-client/build/dicomweb-client.js': [
'api'
]
}
}),
],
external: Object.keys(pkg.peerDependencies || {}),
}

View File

@ -0,0 +1,44 @@
/**
* Returns the specified element as a dicom attribute group/element.
*
* @param element - The group/element of the element (e.g. '00280009')
* @param [defaultValue] - The value to return if the element is not present
* @returns {*}
*/
export default function getAttribute(element, defaultValue) {
if (!element) {
return defaultValue;
}
// Value is not present if the attribute has a zero length value
if (!element.Value) {
return defaultValue;
}
// Sanity check to make sure we have at least one entry in the array.
if (!element.Value.length) {
return defaultValue;
}
return convertToInt(element.Value);
}
function convertToInt(input) {
function padFour(input) {
var l = input.length;
if (l == 0) return '0000';
if (l == 1) return '000' + input;
if (l == 2) return '00' + input;
if (l == 3) return '0' + input;
return input;
}
var output = '';
for (var i = 0; i < input.length; i++) {
for (var j = 0; j < input[i].length; j++) {
output += padFour(input[i].charCodeAt(j).toString(16));
}
}
return parseInt(output, 16);
}

View File

@ -0,0 +1,25 @@
// 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';
/**
* Returns the Authorization header as part of an Object.
*
* @returns {Object}
*/
export default function getAuthorizationHeader(server) {
const headers = {};
// Check for OHIF.user since this can also be run on the server
const accessToken = user && user.getAccessToken && user.getAccessToken();
if (server && server.requestOptions && server.requestOptions.auth) {
// HTTP Basic Auth (user:password)
headers.Authorization = `Basic ${btoa(server.requestOptions.auth)}`;
} else if (accessToken) {
headers.Authorization = `Bearer ${accessToken}`;
}
return headers;
}

View File

@ -0,0 +1,21 @@
export default function getModalities(modality, modalitiesInStudy) {
var modalities = {};
if (modality) {
modalities = modality;
}
if (modalitiesInStudy) {
// Find vr in modalities
if (modalities.vr && modalities.vr === modalitiesInStudy.vr) {
for (var i = 0; i < modalitiesInStudy.Value.length; i++) {
var value = modalitiesInStudy.Value[i];
if (modalities.Value.indexOf(value) === -1) {
modalities.Value.push(value);
}
}
} else {
modalities = modalitiesInStudy;
}
}
return modalities;
}

View File

@ -0,0 +1,26 @@
/**
* Returns the Alphabetic version of a PN
*
* @param element - The group/element of the element (e.g. '00200013')
* @param [defaultValue] - The default value to return if the element is not found
* @returns {*}
*/
export default function getName(element, defaultValue) {
if (!element) {
return defaultValue;
}
// Value is not present if the attribute has a zero length value
if (!element.Value) {
return defaultValue;
}
// Sanity check to make sure we have at least one entry in the array.
if (!element.Value.length) {
return defaultValue;
}
// Return the Alphabetic component group
if (element.Value[0].Alphabetic) {
return element.Value[0].Alphabetic;
}
// Orthanc does not return PN properly so this is a temporary workaround
return element.Value[0];
}

View File

@ -0,0 +1,21 @@
/**
* Returns the first string value as a Javascript Number
* @param element - The group/element of the element (e.g. '00200013')
* @param [defaultValue] - The default value to return if the element does not exist
* @returns {*}
*/
export default function getNumber(element, defaultValue) {
if (!element) {
return defaultValue;
}
// Value is not present if the attribute has a zero length value
if (!element.Value) {
return defaultValue;
}
// Sanity check to make sure we have at least one entry in the array.
if (!element.Value.length) {
return defaultValue;
}
return parseFloat(element.Value[0]);
}

View File

@ -0,0 +1,23 @@
/**
* Returns the specified element as a string. Multi-valued elements will be separated by a backslash
*
* @param element - The group/element of the element (e.g. '00200013')
* @param [defaultValue] - The value to return if the element is not present
* @returns {*}
*/
export default function getString(element, defaultValue) {
if (!element) {
return defaultValue;
}
// Value is not present if the attribute has a zero length value
if (!element.Value) {
return defaultValue;
}
// Sanity check to make sure we have at least one entry in the array.
if (!element.Value.length) {
return defaultValue;
}
// Join the array together separated by backslash
// NOTE: Orthanc does not correctly split values into an array so the join is a no-op
return element.Value.join('\\');
}

View File

@ -0,0 +1,17 @@
import getAttribute from './getAttribute.js';
import getAuthorizationHeader from './getAuthorizationHeader.js';
import getModalities from './getModalities.js';
import getName from './getName.js';
import getNumber from './getNumber.js';
import getString from './getString.js';
const DICOMWeb = {
getAttribute,
getAuthorizationHeader,
getModalities,
getName,
getNumber,
getString,
};
export default DICOMWeb;

View File

@ -0,0 +1 @@
export default {};

View File

@ -0,0 +1 @@
export default {};

View File

@ -0,0 +1 @@
export default {};

View File

@ -0,0 +1 @@
export default {};

View File

@ -0,0 +1,15 @@
// import { api } from 'dicomweb-client'
const api = {
DICOMwebClient: jest.fn().mockImplementation(() => {
return {
retrieveStudyMetadata: jest.fn().mockResolvedValue([]),
};
}),
};
export default {
api,
};
export { api };

View File

@ -0,0 +1,4 @@
export default {
warn: jest.fn(),
error: jest.fn(),
};

View File

@ -0,0 +1,189 @@
import log from '../log.js';
/**
* The definition of a command
*
* @typedef {Object} CommandDefinition
* @property {Function} commandFn - Command to call
* @property {Array} storeContexts - Array of string of modules required from store
* @property {Object} options - Object of params to pass action
*/
/**
* The Commands Manager tracks named commands (or functions) that are scoped to
* a context. When we attempt to run a command with a given name, we look for it
* in our active contexts. If found, we run the command, passing in any application
* or call specific data specified in the command's definition.
*
* NOTE: A more robust version of the CommandsManager lives in v1. If you're looking
* to extend this class, please check it's source before adding new methods.
*/
export class CommandsManager {
constructor({ getAppState, getActiveContexts } = {}) {
this.contexts = {};
if (!getAppState || !getActiveContexts) {
log.warn(
'CommandsManager was instantiated without getAppState() or getActiveContexts()'
);
}
this._getAppState = getAppState;
this._getActiveContexts = getActiveContexts;
}
/**
* Allows us to create commands "per context". An example would be the "Cornerstone"
* context having a `SaveImage` command, and the "VTK" context having a `SaveImage`
* command. The distinction of a context allows us to call the command in either
* context, and have faith that the correct command will be run.
*
* @method
* @param {string} contextName - Namespace for commands
* @returns {undefined}
*/
createContext(contextName) {
if (!contextName) {
return;
}
if (this.contexts[contextName]) {
return this.clearContext(contextName);
}
this.contexts[contextName] = {};
}
/**
* Returns all command definitions for a given context
*
* @method
* @param {string} contextName - Namespace for commands
* @returs {Object} - the matched context
*/
getContext(contextName) {
const context = this.contexts[contextName];
if (!context) {
return;
}
return context;
}
/**
* Clears all registered commands for a given context.
*
* @param {string} contextName - Namespace for commands
* @returns {undefined}
*/
clearContext(contextName) {
if (!contextName) {
return;
}
this.contexts[contextName] = {};
}
/**
* Register a new command with the command manager. Scoped to a context, and
* with a definition to assist command callers w/ providing the necessary params
*
* @method
* @param {string} contextName - Namespace for command; often scoped to the extension that added it
* @param {string} commandName - Unique name identifying the command
* @param {CommandDefinition} definition - {@link CommandDefinition}
*/
registerCommand(contextName, commandName, definition) {
if (typeof definition !== 'object') {
return;
}
const context = this.getContext(contextName);
if (!context) {
return;
}
context[commandName] = definition;
}
/**
* Finds a command with the provided name if it exists in the specified context,
* or a currently active context.
*
* @method
* @param {String} commandName - Command to find
* @param {String} [contextName] - Specific command to look in. Defaults to current activeContexts
*/
getCommand(commandName, contextName) {
let contexts = [];
if (contextName) {
const context = this.getContext(contextName);
if (context) {
contexts.push(context);
}
} else {
const activeContexts = this._getActiveContexts();
activeContexts.forEach(activeContext => {
const context = this.getContext(activeContext);
if (context) {
contexts.push(context);
}
});
}
if (contexts.length === 0) {
return;
}
let foundCommand;
contexts.forEach(context => {
if (context[commandName]) {
foundCommand = context[commandName];
}
});
return foundCommand;
}
/**
*
* @method
* @param {String} commandName
* @param {Object} [options={}] - Extra options to pass the command. Like a mousedown event
* @param {String} [contextName]
*/
runCommand(commandName, options = {}, contextName) {
const definition = this.getCommand(commandName, contextName);
if (!definition) {
log.warn(`Command "${commandName}" not found in current context`);
return;
}
const { commandFn, storeContexts } = definition;
const definitionOptions = definition.options;
let commandParams = {};
const appState = this._getAppState();
storeContexts.forEach(context => {
commandParams[context] = appState[context];
});
commandParams = Object.assign(
{},
commandParams, // Required store contexts
definitionOptions, // "Command configuration"
options // "Time of call" info
);
if (typeof commandFn !== 'function') {
log.warn(`No commandFn was defined for command "${commandName}"`);
return;
} else {
return commandFn(commandParams);
}
}
}
export default CommandsManager;

View File

@ -0,0 +1,225 @@
import CommandsManager from './CommandsManager.js';
import log from './../log.js';
jest.mock('./../log.js');
describe('CommandsManager', () => {
let commandsManager,
contextName = 'VTK',
command = {
commandFn: jest.fn().mockReturnValue(true),
storeContexts: ['viewers'],
options: { passMeToCommandFn: ':wave:' },
},
commandsManagerConfig = {
getAppState: () => {
return {
viewers: 'Test',
};
},
getActiveContexts: () => ['VIEWER', 'ACTIVE_VIEWER::CORNERSTONE'],
};
beforeEach(() => {
commandsManager = new CommandsManager(commandsManagerConfig);
commandsManager.createContext('VIEWER');
commandsManager.createContext('ACTIVE_VIEWER::CORNERSTONE');
jest.clearAllMocks();
});
it('has a contexts property', () => {
const localCommandsManager = new CommandsManager(commandsManagerConfig);
expect(localCommandsManager).toHaveProperty('contexts');
expect(localCommandsManager.contexts).toEqual({});
});
it('logs a warning if instantiated without getAppState or getActiveContexts', () => {
new CommandsManager();
expect(log.warn.mock.calls.length).toBe(1);
});
describe('createContext()', () => {
it('creates a context', () => {
commandsManager.createContext(contextName);
expect(commandsManager.contexts).toHaveProperty(contextName);
});
it('clears the context if it already exists', () => {
commandsManager.createContext(contextName);
commandsManager.registerCommand(contextName, 'TestCommand', command);
commandsManager.registerCommand(contextName, 'TestCommand2', command);
commandsManager.createContext(contextName);
const registeredCommands = commandsManager.getContext(contextName);
expect(registeredCommands).toEqual({});
});
});
describe('getContext()', () => {
it('returns all registered commands for a context', () => {
commandsManager.createContext(contextName);
commandsManager.registerCommand(contextName, 'TestCommand', command);
const registeredCommands = commandsManager.getContext(contextName);
expect(registeredCommands).toHaveProperty('TestCommand');
expect(registeredCommands['TestCommand']).toEqual(command);
});
it('returns undefined if the context does not exist', () => {
const registeredCommands = commandsManager.getContext(contextName);
expect(registeredCommands).toBe(undefined);
});
});
describe('clearContext()', () => {
it('clears all registered commands for a context', () => {
commandsManager.createContext(contextName);
commandsManager.registerCommand(contextName, 'TestCommand', command);
commandsManager.registerCommand(contextName, 'TestCommand2', command);
commandsManager.clearContext(contextName);
const registeredCommands = commandsManager.getContext(contextName);
expect(registeredCommands).toEqual({});
});
});
describe('registerCommand()', () => {
it('registers commands to a context', () => {
commandsManager.createContext(contextName);
commandsManager.registerCommand(contextName, 'TestCommand', command);
const registeredCommands = commandsManager.getContext(contextName);
expect(registeredCommands).toHaveProperty('TestCommand');
expect(registeredCommands['TestCommand']).toEqual(command);
});
});
describe('getCommand()', () => {
it('returns undefined if context does not exist', () => {
const result = commandsManager.getCommand(
'TestCommand',
'NonExistentContext'
);
expect(result).toBe(undefined);
});
it('returns undefined if command does not exist in context', () => {
commandsManager.createContext(contextName);
const result = commandsManager.getCommand('TestCommand', contextName);
expect(result).toBe(undefined);
});
it('uses contextName param to get command', () => {
commandsManager.createContext('GLOBAL');
commandsManager.registerCommand('GLOBAL', 'TestCommand', command);
const foundCommand = commandsManager.getCommand('TestCommand', 'GLOBAL');
expect(foundCommand).toBe(command);
});
it('uses activeContexts, if contextName is not provided, to get command', () => {
commandsManager.registerCommand('VIEWER', 'TestCommand', command);
const foundCommand = commandsManager.getCommand('TestCommand');
expect(foundCommand).toBe(command);
});
it('returns the expected command', () => {
commandsManager.createContext(contextName);
commandsManager.registerCommand(contextName, 'TestCommand', command);
const result = commandsManager.getCommand('TestCommand', contextName);
expect(result).toEqual(command);
});
});
describe('runCommand()', () => {
it('Logs a warning if commandName not found in context', () => {
const result = commandsManager.runCommand(
'CommandThatDoesNotExistInAnyContext'
);
expect(result).toBe(undefined);
expect(log.warn.mock.calls[0][0]).toEqual(
'Command "CommandThatDoesNotExistInAnyContext" not found in current context'
);
});
it('Logs a warning if command definition does not have a commandFn', () => {
const commandWithNoCommmandFn = {
commandFn: undefined,
storeContexts: [],
options: {},
};
commandsManager.createContext(contextName);
commandsManager.registerCommand(
contextName,
'TestCommand',
commandWithNoCommmandFn
);
const result = commandsManager.runCommand(
'TestCommand',
null,
contextName
);
expect(result).toBe(undefined);
expect(log.warn.mock.calls[0][0]).toEqual(
'No commandFn was defined for command "TestCommand"'
);
});
it('Calls commandFn', () => {
commandsManager.registerCommand('VIEWER', 'TestCommand', command);
commandsManager.runCommand('TestCommand', {}, 'VIEWER');
expect(command.commandFn.mock.calls.length).toBe(1);
});
it('Calls commandFn w/ properties from appState', () => {
commandsManager.registerCommand('VIEWER', 'TestCommand', command);
commandsManager.runCommand('TestCommand', {}, 'VIEWER');
expect(command.commandFn.mock.calls.length).toBe(1);
expect(command.commandFn.mock.calls[0][0].viewers).toEqual(
commandsManagerConfig.getAppState().viewers
);
});
it('Calls commandFn w/ command definition options', () => {
commandsManager.registerCommand('VIEWER', 'TestCommand', command);
commandsManager.runCommand('TestCommand', {}, 'VIEWER');
expect(command.commandFn.mock.calls.length).toBe(1);
expect(command.commandFn.mock.calls[0][0].passMeToCommandFn).toEqual(
command.options.passMeToCommandFn
);
});
it('Calls commandFn w/ runCommand "options" parameter', () => {
const runCommandOptions = {
test: ':+1:',
};
commandsManager.registerCommand('VIEWER', 'TestCommand', command);
commandsManager.runCommand('TestCommand', runCommandOptions, 'VIEWER');
expect(command.commandFn.mock.calls.length).toBe(1);
expect(command.commandFn.mock.calls[0][0].test).toEqual(
runCommandOptions.test
);
});
it('Returns the result of commandFn', () => {
commandsManager.registerCommand('VIEWER', 'TestCommand', command);
const result = commandsManager.runCommand('TestCommand', {}, 'VIEWER');
expect(command.commandFn.mock.calls.length).toBe(1);
expect(result).toBe(true);
});
});
});

View File

@ -0,0 +1,162 @@
import hotkeys from './hotkeys';
import log from './../log.js';
/**
*
*
* @typedef {Object} HotkeyDefinition
* @property {String} commandName - Command to call
* @property {String} label - Display name for hotkey
* @property {String[]} keys - Keys to bind; Follows Mousetrap.js binding syntax
*/
export class HotkeysManager {
constructor(commandsManager) {
this.hotkeyDefinitions = {};
this.hotkeyDefaults = [];
this.isEnabled = true;
if (!commandsManager) {
log.warn(
'HotkeysManager instantiated without a commandsManager. Hotkeys will be unable to find and run commands.'
);
}
this._commandsManager = commandsManager;
}
/**
* Disables all hotkeys. Hotkeys added while disabled will not listen for
* input.
*/
disable() {
this.isEnabled = false;
hotkeys.pause();
}
/**
* Enables all hotkeys.
*/
enable() {
this.isEnabled = true;
hotkeys.unpause();
}
/**
* Registers a list of hotkeydefinitions. Optionally, sets the
* default hotkey bindings for all provided definitions. These
* values are used in `this.restoreDefaultBindings`.
*
* @param {HotkeyDefinition[]} hotkeyDefinitions
* @param {Boolean} [isDefaultDefinitions]
*/
setHotkeys(hotkeyDefinitions, isDefaultDefinitions = false) {
hotkeyDefinitions.forEach(definition => this.registerHotkeys(definition));
if (isDefaultDefinitions) {
this.hotkeyDefaults = hotkeyDefinitions;
}
}
/**
* (unbinds and) binds the specified command to one or more key combinations.
* When a hotkey combination is triggered, the command name and active contexts
* are used to locate the correct command to call.
*
* @param {HotkeyDefinition} commandName
* @param {String} extension
* @returns {undefined}
*/
registerHotkeys({ commandName, keys, label } = {}, extension) {
if (!commandName) {
log.warn(`No command was defined for hotkey "${keys}"`);
return;
}
const previouslyRegisteredDefinition = this.hotkeyDefinitions[commandName];
if (previouslyRegisteredDefinition) {
const previouslyRegisteredKeys = previouslyRegisteredDefinition.keys;
this._unbindHotkeys(commandName, previouslyRegisteredKeys);
}
// Set definition & bind
this.hotkeyDefinitions[commandName] = { keys, label };
this._bindHotkeys(commandName, keys);
}
/**
* Uses most recent
*
* @returns {undefined}
*/
restoreDefaultBindings() {
this.setHotkeys(this.hotkeyDefaults);
}
/**
*
*/
destroy() {
this.hotkeyDefaults = [];
this.hotkeyDefinitions = {};
hotkeys.reset();
}
/**
* Binds one or more set of hotkey combinations for a given command
*
* @private
* @param {string} commandName - The name of the command to trigger when hotkeys are used
* @param {string[]} keys - One or more key combinations that should trigger command
* @returns {undefined}
*/
_bindHotkeys(commandName, keys) {
const isKeyDefined = keys === '' || keys === undefined;
if (isKeyDefined) {
return;
}
const isKeyArray = keys instanceof Array;
if (isKeyArray) {
keys.forEach(key => this._bindHotkeys(commandName, key));
return;
}
hotkeys.bind(keys, evt => {
this._commandsManager.runCommand(commandName, { evt });
});
}
/**
* unbinds one or more set of hotkey combinations for a given command
*
* @private
* @param {string} commandName - The name of the previously bound command
* @param {string[]} keys - One or more sets of previously bound keys
* @returns {undefined}
*/
_unbindHotkeys(commandName, keys) {
const isKeyDefined = keys !== '' && keys !== undefined;
if (!isKeyDefined) {
return;
}
const isKeyArray = keys instanceof Array;
if (isKeyArray) {
keys.forEach(key => this._unbindHotkeys(commandName, key));
return;
}
hotkeys.unbind(keys);
}
}
export default HotkeysManager;
// Commands Contexts:
// --> Name and Priority
// GLOBAL: 0
// VIEWER::CORNERSTONE: 1
// VIEWER::VTK: 1

View File

@ -0,0 +1,201 @@
import CommandsManager from './CommandsManager.js';
import HotkeysManager from './HotkeysManager.js';
import hotkeys from './hotkeys';
import log from './../log.js';
jest.mock('./CommandsManager.js');
jest.mock('./hotkeys');
jest.mock('./../log.js');
describe('HotkeysManager', () => {
let hotkeysManager, commandsManager;
beforeEach(() => {
commandsManager = new CommandsManager();
hotkeysManager = new HotkeysManager(commandsManager);
CommandsManager.mockClear();
hotkeys.mockClear();
log.warn.mockClear();
jest.clearAllMocks();
});
it('has expected properties', () => {
const allProperties = Object.keys(hotkeysManager);
const expectedProprties = [
'hotkeyDefinitions',
'hotkeyDefaults',
'isEnabled',
];
const containsAllExpectedProperties = expectedProprties.every(expected =>
allProperties.includes(expected)
);
expect(containsAllExpectedProperties).toBe(true);
});
it('logs a warning if instantiated without a commandsManager', () => {
new HotkeysManager();
expect(log.warn.mock.calls.length).toBe(1);
expect(log.warn.mock.calls[0][0]).toEqual(
'HotkeysManager instantiated without a commandsManager. Hotkeys will be unable to find and run commands.'
);
});
describe('disable()', () => {
beforeEach(() => hotkeys.pause.mockClear());
it('sets isEnabled property to false', () => {
hotkeysManager.disable();
expect(hotkeysManager.isEnabled).toBe(false);
});
it('calls hotkeys.pause()', () => {
hotkeysManager.disable();
expect(hotkeys.pause.mock.calls.length).toBe(1);
});
});
describe('enable()', () => {
beforeEach(() => hotkeys.unpause.mockClear());
it('sets isEnabled property to true', () => {
hotkeysManager.disable();
hotkeysManager.enable();
expect(hotkeysManager.isEnabled).toBe(true);
});
it('calls hotkeys.unpause()', () => {
hotkeysManager.enable();
expect(hotkeys.unpause.mock.calls.length).toBe(1);
});
});
describe('setHotkeys()', () => {
it('calls registerHotkeys for each hotkeyDefinition', () => {
const hotkeyDefinitions = [
{ commandName: 'dance', label: 'dance dance', keys: '+' },
{ commandName: 'celebrate', label: 'celebrate everything', keys: 'q' },
];
hotkeysManager.registerHotkeys = jest.fn();
hotkeysManager.setHotkeys(hotkeyDefinitions);
const numberOfCalls = hotkeysManager.registerHotkeys.mock.calls.length;
const firstCallArgs = hotkeysManager.registerHotkeys.mock.calls[0][0];
const secondCallArgs = hotkeysManager.registerHotkeys.mock.calls[1][0];
expect(numberOfCalls).toBe(2);
expect(firstCallArgs).toEqual(hotkeyDefinitions[0]);
expect(secondCallArgs).toEqual(hotkeyDefinitions[1]);
});
it('does not set this.hotkeyDefaults by default', () => {
const hotkeyDefinitions = [{ commandName: 'dance', keys: '+' }];
hotkeysManager.setHotkeys(hotkeyDefinitions);
expect(hotkeysManager.hotkeyDefaults).toEqual([]);
});
it('sets this.hotkeyDefaults when isDefaultDefinitions is true', () => {
const hotkeyDefinitions = [{ commandName: 'dance', keys: '+' }];
const isDefaultDefinitions = true;
hotkeysManager.setHotkeys(hotkeyDefinitions, isDefaultDefinitions);
expect(hotkeysManager.hotkeyDefaults).toEqual(hotkeyDefinitions);
});
});
describe('registerHotkeys()', () => {
it('logs a warning and returns undefined if a commandName is not provided', () => {
const definition = { commandName: undefined, keys: '+' };
const result = hotkeysManager.registerHotkeys(definition);
expect(result).toBe(undefined);
expect(log.warn.mock.calls.length).toBe(1);
});
it('updates hotkeyDefinitions property with registered keys', () => {
const definition = { commandName: 'dance', label: 'hello', keys: '+' };
const expectedHotkeyDefinition = { label: 'hello', keys: '+' };
hotkeysManager.registerHotkeys(definition);
const numOfHotkeyDefinitions = Object.keys(
hotkeysManager.hotkeyDefinitions
).length;
const hotkeyDefinitionForRegisteredCommand =
hotkeysManager.hotkeyDefinitions[definition.commandName];
expect(numOfHotkeyDefinitions).toBe(1);
expect(hotkeyDefinitionForRegisteredCommand).toEqual(
expectedHotkeyDefinition
);
});
it('calls hotkeys.bind for all keys in array', () => {
const definition = { commandName: 'dance', keys: ['h', 'e', 'l', 'o'] };
hotkeysManager.registerHotkeys(definition);
expect(hotkeys.bind.mock.calls.length).toBe(definition.keys.length);
definition.keys.forEach((key, i) =>
expect(hotkeys.bind.mock.calls[i][0]).toBe(key)
);
});
it('calls hotkeys.unbind if commandName was previously registered, for each previously registered set of keys', () => {
const firstDefinition = {
commandName: 'dance',
keys: ['h', 'e', 'l', 'o'],
};
const secondDefinition = { commandName: 'dance', keys: 'a' };
// First call
hotkeysManager.registerHotkeys(firstDefinition);
// Second call
hotkeysManager.registerHotkeys(secondDefinition);
expect(hotkeys.unbind.mock.calls.length).toBe(
firstDefinition.keys.length
);
firstDefinition.keys.forEach((key, i) =>
expect(hotkeys.unbind.mock.calls[i][0]).toBe(key)
);
});
});
describe('restoreDefaults()', () => {
it('calls setHotkeys with hotkey defaults', () => {
hotkeysManager.setHotkeys = jest.fn();
hotkeysManager.restoreDefaultBindings();
expect(hotkeysManager.setHotkeys.mock.calls[0][0]).toEqual(
hotkeysManager.hotkeyDefaults
);
});
});
describe('destroy()', () => {
it('clears default and definition properties', () => {
hotkeysManager.hotkeyDefaults = ['hotdog', 'jeremy', 'qasar'];
hotkeysManager.hotkeyDefinitions = {
hello: 'world',
};
hotkeysManager.destroy();
expect(hotkeysManager.hotkeyDefaults).toEqual([]);
expect(hotkeysManager.hotkeyDefinitions).toEqual({});
});
it('resets all hotkey bindings', () => {
hotkeysManager.destroy();
expect(hotkeys.reset.mock.calls.length).toEqual(1);
});
});
});

View File

@ -0,0 +1,68 @@
import guid from '../utils/guid.js';
import OHIFError from './OHIFError';
const OBJECT = 'object';
/**
* This class defines an ImageSet object which will be used across the viewer. This object represents
* a list of images that are associated by any arbitrary criteria being thus content agnostic. Besides the
* main attributes (images and uid) it allows additional attributes to be appended to it (currently
* indiscriminately, but this should be changed).
*/
class ImageSet {
constructor(images) {
if (Array.isArray(images) !== true) {
throw new OHIFError('ImageSet expects an array of images');
}
// @property "images"
Object.defineProperty(this, 'images', {
enumerable: false,
configurable: false,
writable: false,
value: images,
});
// @property "uid"
Object.defineProperty(this, 'uid', {
enumerable: false,
configurable: false,
writable: false,
value: guid(), // Unique ID of the instance
});
}
getUID() {
return this.uid;
}
setAttribute(attribute, value) {
this[attribute] = value;
}
getAttribute(attribute) {
return this[attribute];
}
setAttributes(attributes) {
if (typeof attributes === OBJECT && attributes !== null) {
const imageSet = this,
hasOwn = Object.prototype.hasOwnProperty;
for (let attribute in attributes) {
if (hasOwn.call(attributes, attribute)) {
imageSet[attribute] = attributes[attribute];
}
}
}
}
getImage(index) {
return this.images[index];
}
sortBy(sortingCallback) {
return this.images.sort(sortingCallback);
}
}
export default ImageSet;

View File

@ -0,0 +1,412 @@
import { parsingUtils } from '../lib/parsingUtils';
const FUNCTION = 'function';
class MetadataProvider {
constructor() {
// Define the main "metadataLookup" private property as an immutable property.
Object.defineProperty(this, 'metadataLookup', {
configurable: false,
enumerable: false,
writable: false,
value: new Map(),
});
// Local reference to provider function bound to current instance.
Object.defineProperty(this, '_provider', {
configurable: false,
enumerable: false,
writable: true,
value: null,
});
}
/**
* Cornerstone Metadata provider to store image meta data
* Data from instances, series, and studies are associated with
* imageIds to facilitate usage of this information by Cornerstone's Tools
*
* e.g. the imagePlane metadata object contains instance information about
* row/column pixel spacing, patient position, and patient orientation. It
* is used in CornerstoneTools to position reference lines and orientation markers.
*
* @param {String} imageId The Cornerstone ImageId
* @param {Object} data An object containing instance, series, and study metadata
*/
addMetadata(imageId, data) {
const instanceMetadata = data.instance;
const seriesMetadata = data.series;
const studyMetadata = data.study;
const numImages = data.numImages;
const metadata = {};
metadata.frameNumber = data.frameNumber;
metadata.study = {
accessionNumber: studyMetadata.accessionNumber,
patientId: studyMetadata.patientId,
studyInstanceUid: studyMetadata.studyInstanceUid,
studyDate: studyMetadata.studyDate,
studyTime: studyMetadata.studyTime,
studyDescription: studyMetadata.studyDescription,
institutionName: studyMetadata.institutionName,
patientHistory: studyMetadata.patientHistory,
};
metadata.series = {
seriesDescription: seriesMetadata.seriesDescription,
seriesNumber: seriesMetadata.seriesNumber,
seriesDate: seriesMetadata.seriesDate,
seriesTime: seriesMetadata.seriesTime,
modality: seriesMetadata.modality,
seriesInstanceUid: seriesMetadata.seriesInstanceUid,
numImages: numImages,
};
metadata.instance = instanceMetadata;
metadata.patient = {
name: studyMetadata.patientName,
id: studyMetadata.patientId,
birthDate: studyMetadata.patientBirthDate,
sex: studyMetadata.patientSex,
age: studyMetadata.patientAge,
};
// If there is sufficient information, populate
// the imagePlane object for easier use in the Viewer
metadata.imagePlane = this.getImagePlane(instanceMetadata);
// Add the metadata to the imageId lookup object
this.metadataLookup.set(imageId, metadata);
}
/**
* Return the metadata for the given imageId
* @param {String} imageId The Cornerstone ImageId
* @returns image metadata
*/
getMetadata(imageId) {
return this.metadataLookup.get(imageId);
}
/**
* Adds a set of metadata to the Cornerstone metadata provider given a specific
* imageId, type, and dataset
*
* @param imageId
* @param type (e.g. series, instance, tagDisplay)
* @param data
*/
addSpecificMetadata(imageId, type, data) {
const metadata = {};
metadata[type] = data;
const oldMetadata = this.metadataLookup.get(imageId);
this.metadataLookup.set(imageId, Object.assign(oldMetadata, metadata));
}
getFromImage(image, type, tag, attrName, defaultValue) {
let value;
if (image.data) {
value = this.getFromDataSet(image.data, type, tag);
} else {
value = image.instance[attrName];
}
return value === null ? defaultValue : value;
}
getFromDataSet(dataSet, type, tag) {
if (!dataSet) {
return;
}
const fn = dataSet[type];
if (!fn) {
return;
}
return fn.call(dataSet, tag);
}
getFrameIncrementPointer(image) {
const dataSet = image.data;
let frameInstancePointer = '';
if (parsingUtils.isValidDataSet(dataSet)) {
const frameInstancePointerNames = {
x00181063: 'frameTime',
x00181065: 'frameTimeVector',
};
// (0028,0009) = Frame Increment Pointer
const frameInstancePointerTag = parsingUtils.attributeTag(
dataSet,
'x00280009'
);
frameInstancePointer = frameInstancePointerNames[frameInstancePointerTag];
} else {
frameInstancePointer = image.instance.frameIncrementPointer;
}
return frameInstancePointer || '';
}
getFrameTimeVector(image) {
const dataSet = image.data;
if (parsingUtils.isValidDataSet(dataSet)) {
// Frame Increment Pointer points to Frame Time Vector (0018,1065) field
return parsingUtils.floatArray(dataSet, 'x00181065');
}
return image.instance.frameTimeVector;
}
getFrameTime(image) {
const dataSet = image.data;
if (parsingUtils.isValidDataSet(dataSet)) {
// Frame Increment Pointer points to Frame Time (0018,1063) field or is not defined (for addtional flexibility).
// Yet another value is possible for this field (5200,9230 for Multi-frame Functional Groups)
// but that case is currently not supported.
return dataSet.floatString('x00181063', -1);
}
return image.instance.frameTime;
}
/**
* Updates the related metadata for missing fields given a specified image
*
* @param image
*/
updateMetadata(image) {
const imageMetadata = this.metadataLookup.get(image.imageId);
if (!imageMetadata) {
return;
}
imageMetadata.patient.age =
imageMetadata.patient.age ||
this.getFromDataSet(image.data, 'string', 'x00101010');
imageMetadata.instance.rows = imageMetadata.instance.rows || image.rows;
imageMetadata.instance.columns =
imageMetadata.instance.columns || image.columns;
imageMetadata.instance.sopClassUid =
imageMetadata.instance.sopClassUid ||
this.getFromDataSet(image.data, 'string', 'x00080016');
imageMetadata.instance.sopInstanceUid =
imageMetadata.instance.sopInstanceUid ||
this.getFromDataSet(image.data, 'string', 'x00080018');
imageMetadata.instance.pixelSpacing =
imageMetadata.instance.pixelSpacing ||
this.getFromDataSet(image.data, 'string', 'x00280030');
imageMetadata.instance.frameOfReferenceUID =
imageMetadata.instance.frameOfReferenceUID ||
this.getFromDataSet(image.data, 'string', 'x00200052');
imageMetadata.instance.imageOrientationPatient =
imageMetadata.instance.imageOrientationPatient ||
this.getFromDataSet(image.data, 'string', 'x00200037');
imageMetadata.instance.imagePositionPatient =
imageMetadata.instance.imagePositionPatient ||
this.getFromDataSet(image.data, 'string', 'x00200032');
imageMetadata.instance.sliceThickness =
imageMetadata.instance.sliceThickness ||
this.getFromDataSet(image.data, 'string', 'x00180050');
imageMetadata.instance.sliceLocation =
imageMetadata.instance.sliceLocation ||
this.getFromDataSet(image.data, 'string', 'x00201041');
imageMetadata.instance.tablePosition =
imageMetadata.instance.tablePosition ||
this.getFromDataSet(image.data, 'string', 'x00189327');
imageMetadata.instance.spacingBetweenSlices =
imageMetadata.instance.spacingBetweenSlices ||
this.getFromDataSet(image.data, 'string', 'x00180088');
imageMetadata.instance.lossyImageCompression =
imageMetadata.instance.lossyImageCompression ||
this.getFromDataSet(image.data, 'string', 'x00282110');
imageMetadata.instance.lossyImageCompressionRatio =
imageMetadata.instance.lossyImageCompressionRatio ||
this.getFromDataSet(image.data, 'string', 'x00282112');
imageMetadata.instance.frameIncrementPointer =
imageMetadata.instance.frameIncrementPointer ||
this.getFromDataSet(image.data, 'string', 'x00280009');
imageMetadata.instance.frameTime =
imageMetadata.instance.frameTime ||
this.getFromDataSet(image.data, 'string', 'x00181063');
imageMetadata.instance.frameTimeVector =
imageMetadata.instance.frameTimeVector ||
this.getFromDataSet(image.data, 'string', 'x00181065');
if (
(image.data || image.instance) &&
!imageMetadata.instance.multiframeMetadata
) {
imageMetadata.instance.multiframeMetadata = this.getMultiframeModuleMetadata(
image
);
}
imageMetadata.imagePlane =
imageMetadata.imagePlane || this.getImagePlane(imageMetadata.instance);
}
/**
* Constructs and returns the imagePlane given the metadata instance
*
* @param metadataInstance The metadata instance (InstanceMetadata class) containing information to construct imagePlane
* @returns imagePlane The constructed imagePlane to be used in viewer easily
*/
getImagePlane(instance) {
if (
!instance.rows ||
!instance.columns ||
!instance.pixelSpacing ||
!instance.frameOfReferenceUID ||
!instance.imageOrientationPatient ||
!instance.imagePositionPatient
) {
return;
}
const imageOrientation = instance.imageOrientationPatient.split('\\');
const imagePosition = instance.imagePositionPatient.split('\\');
let columnPixelSpacing = 1.0;
let rowPixelSpacing = 1.0;
if (instance.pixelSpacing) {
const split = instance.pixelSpacing.split('\\');
rowPixelSpacing = parseFloat(split[0]);
columnPixelSpacing = parseFloat(split[1]);
}
return {
frameOfReferenceUID: instance.frameOfReferenceUID,
rows: instance.rows,
columns: instance.columns,
rowCosines: [
parseFloat(imageOrientation[0]),
parseFloat(imageOrientation[1]),
parseFloat(imageOrientation[2]),
],
columnCosines: [
parseFloat(imageOrientation[3]),
parseFloat(imageOrientation[4]),
parseFloat(imageOrientation[5]),
],
imagePositionPatient: [
parseFloat(imagePosition[0]),
parseFloat(imagePosition[1]),
parseFloat(imagePosition[2]),
],
rowPixelSpacing,
columnPixelSpacing,
};
}
/**
* This function extracts miltiframe information from a dicomParser.DataSet object.
*
* @param dataSet {Object} An instance of dicomParser.DataSet object where multiframe information can be found.
* @return {Object} An object containing multiframe image metadata (frameIncrementPointer, frameTime, frameTimeVector, etc).
*/
getMultiframeModuleMetadata(image) {
const imageInfo = {
isMultiframeImage: false,
frameIncrementPointer: null,
numberOfFrames: 0,
frameTime: 0,
frameTimeVector: null,
averageFrameRate: 0, // backwards compatibility only... it might be useless in the future
};
let frameTime;
const numberOfFrames = this.getFromImage(
image,
'intString',
'x00280008',
'numberOfFrames',
-1
);
if (numberOfFrames > 0) {
// set multi-frame image indicator
imageInfo.isMultiframeImage = true;
imageInfo.numberOfFrames = numberOfFrames;
// (0028,0009) = Frame Increment Pointer
const frameIncrementPointer = this.getFrameIncrementPointer(image);
if (frameIncrementPointer === 'frameTimeVector') {
// Frame Increment Pointer points to Frame Time Vector (0018,1065) field
const frameTimeVector = this.getFrameTimeVector(image);
if (frameTimeVector instanceof Array && frameTimeVector.length > 0) {
imageInfo.frameIncrementPointer = frameIncrementPointer;
imageInfo.frameTimeVector = frameTimeVector;
frameTime =
frameTimeVector.reduce((a, b) => a + b) / frameTimeVector.length;
imageInfo.averageFrameRate = 1000 / frameTime;
}
} else if (
frameIncrementPointer === 'frameTime' ||
frameIncrementPointer === ''
) {
frameTime = this.getFrameTime(image);
if (frameTime > 0) {
imageInfo.frameIncrementPointer = frameIncrementPointer;
imageInfo.frameTime = frameTime;
imageInfo.averageFrameRate = 1000 / frameTime;
}
}
}
return imageInfo;
}
/**
* Get a bound reference to the provider function.
*/
getProvider() {
let provider = this._provider;
if (typeof this._provider !== FUNCTION) {
provider = this.provider.bind(this);
this._provider = provider;
}
return provider;
}
/**
* Looks up metadata for Cornerstone Tools given a specified type and imageId
* A type may be, e.g. 'study', or 'patient', or 'imagePlaneModule'. These types
* are keys in the stored metadata objects.
*
* @param type
* @param imageId
* @returns {Object} Relevant metadata of the specified type
*/
provider(type, imageId) {
const imageMetadata = this.metadataLookup.get(imageId);
if (!imageMetadata) {
return;
}
if (imageMetadata.hasOwnProperty(type)) {
return imageMetadata[type];
}
}
}
export default MetadataProvider;

View File

@ -0,0 +1,14 @@
// @TODO: improve this object
/**
* Objects to be used to throw errors
*/
class OHIFError extends Error {
constructor(message) {
super();
this.message = message;
this.stack = new Error().stack;
this.name = this.constructor.name;
}
}
export default OHIFError;

View File

@ -0,0 +1,81 @@
import { studyMetadataManager, updateMetaDataManager } from '../utils';
import OHIFError from './OHIFError';
import { StudyMetadata } from './metadata/StudyMetadata';
import { StudyMetadataSource } from './StudyMetadataSource.js';
import { StudySummary } from './metadata/StudySummary';
import { retrieveStudyMetadata } from '../studies/retrieveStudyMetadata.js';
export class OHIFStudyMetadataSource extends StudyMetadataSource {
/**
* Get study metadata for a study with given study InstanceUID
* @param server
* @param {String} studyInstanceUID Study InstanceUID
* @return {Promise} A Promise object
*/
getByInstanceUID(server, studyInstanceUID) {
return retrieveStudyMetadata(server, studyInstanceUID);
}
/**
* Load study info (OHIF.viewer.Studies) and study metadata (OHIF.viewer.StudyMetadataList) for a given study.
* @param {StudySummary|StudyMetadata} study of StudySummary or StudyMetadata object.
*/
loadStudy(study) {
if (!(study instanceof StudyMetadata) && !(study instanceof StudySummary)) {
throw new OHIFError(
'OHIFStudyMetadataSource::loadStudy study is not an instance of StudySummary or StudyMetadata'
);
}
return new Promise((resolve, reject) => {
const studyInstanceUID = study.getStudyInstanceUID();
if (study instanceof StudyMetadata) {
const alreadyLoaded = OHIF.viewer.Studies.findBy({
studyInstanceUid: studyInstanceUID,
});
if (!alreadyLoaded) {
OHIFStudyMetadataSource._updateStudyCollections(study);
}
resolve(study);
return;
}
this.getByInstanceUID(studyInstanceUID)
.then(studyInfo => {
// Create study metadata object
const studyMetadata = new StudyMetadata(
studyInfo,
studyInfo.studyInstanceUid
);
// Get Study display sets
const displaySets = studyMetadata.createDisplaySets();
// Set studyMetadata display sets
studyMetadata.setDisplaySets(displaySets);
OHIFStudyMetadataSource._updateStudyCollections(studyMetadata);
resolve(studyMetadata);
})
.catch(reject);
});
}
// Static methods
static _updateStudyCollections(studyMetadata) {
const studyInfo = studyMetadata.getData();
// Set some studyInfo properties
studyInfo.selected = true;
studyInfo.displaySets = studyMetadata.getDisplaySets();
// Updates WADO-RS metaDataManager
updateMetaDataManager(studyInfo);
studyMetadataManager.add(studyMetadata);
}
}

View File

@ -0,0 +1,55 @@
import StudySummary from './StudySummary';
/**
* Constants
*/
const STRING = 'string';
const propertyReplacementMap = {
modalities: 'ModalitiesInStudy',
patientBirthdate: 'PatientBirthDate',
};
/**
* OHIF Viewers specialized version of StudySummary class
*/
export class OHIFStudySummary extends StudySummary {
// @Override
addTags(tagMap) {
const _hasOwn = Object.prototype.hasOwnProperty;
const _tagMap = Object.create(null);
for (let property in tagMap) {
if (_hasOwn.call(tagMap, property)) {
let standardProperty = OHIFStudySummary.getStandardPropertyName(
property
);
if (standardProperty) {
_tagMap[standardProperty] = tagMap[property];
}
}
}
super.addTags(_tagMap);
}
/**
* Turns a non-standard, OHIF specific, DICOM property name into a standard one.
* @param {string} property A string representing a non-conforming keyword.
* @returns {string|undefined} Returns a standard-conforming property name.
*/
static getStandardPropertyName(property) {
let standardProperty;
if (typeof property === STRING && property.charAt(0) !== '_') {
if (property in propertyReplacementMap) {
standardProperty = propertyReplacementMap[propertyReplacementMap];
} else {
standardProperty = property
.replace(/^sop/, 'SOP')
.replace(/Uid$/, 'UID')
.replace(/Id$/, 'ID');
standardProperty =
standardProperty.charAt(0).toUpperCase() + standardProperty.substr(1);
}
}
return standardProperty;
}
}

View File

@ -0,0 +1,167 @@
# Table of contents
In this document, some important objects are described. In the files there are comments that can help better undestand their methods and properties.
- [ResizeViewportManager object](#the-resize-viewport-manager-object)
- [ImageSet object](#the-image-set-object)
- [Layout Manager](#the-layout-manager-object)
- [Type Safe Collections](#the-type-safe-collections)
# The Resize Viewport Manager object
This object has multiple functions to manage window resize event. It relocates Dialogs, resizes viewport elements and scrollbars and some other UI components such as Study and Series Quick Switch, when available.
## Usage
It's only necessary to bind **handleResize** function to the window resize event as follows. The **ohif:viewerbase** package needs to be imported by the referring code as well.
```javascript
import { Viewerbase } from 'meteor/ohif:viewerbase';
const ResizeViewportManager = new Viewerbase.ResizeViewportManager();
window.addEventListener('resize', ResizeViewportManager.getResizeHandler());
```
An example os its usage can be found in **ohif-viewerbase/client/components/viewer/viewerMain/viewerMain.js**.
# The Image Set object
An object that represents a list of images that are associated by any arbitrary criteria being thus content agnostic. Besides the main attributes (**images** and **uid**) it allows additional attributes to be appended to it (currently indiscriminately, but this should be changed).
## Usage
ImageSet constructor requires an array of SOP instances like in the example below. It's necessary to import **ohif:viewerbase**.
```javascript
import { Viewerbase } from 'meteor/ohif:viewerbase';
const imageSet = new Viewerbase.ImageSet(sopInstances);
imageSet.setAttributes({
displaySetInstanceUid: imageSet.uid,
seriesInstanceUid: seriesData.seriesInstanceUid,
seriesNumber: seriesData.seriesNumber,
seriesDescription: seriesData.seriesDescription,
numImageFrames: instances.length,
frameRate: instance.getRawValue('x00181063'),
modality: seriesData.modality,
isMultiFrame: isMultiFrame(instance)
});
// Sort instances by InstanceNumber (0020,0013)
imageSet.sortBy((a, b) => {
return (parseInt(a.getRawValue('x00200013', 0)) || 0) - (parseInt(b.getRawValue('x00200013', 0)) || 0);
});
```
Each SOP instance in this example is an instance of **OHIFInstanceMetadata** object, which is a specialization of **InstanceMetadata**. To read more about the **Metadata API** click [here](metadata/).
# The Layout Manager object
Objects of this class are responsible for creating, organizing and maintaining (manage) viewport rendering. It creates a grid, positioning viewports accordingly to it's configuration keeping all viewports data (in **viewportData** property) for easy access from other components. It support many layout configurations and some of them were fully tested: 1x1, 1x2, 1x3, 2x1, 2x2, 2x3, 3x1, 3x2, 3x3. Other configurations may work as well.
Finally it provides some useful functions to move through viewports and zoom it.
## Usage
In order to use _LayoutManager_ the **ohif:viewerbase** package needs to be imported by the referring code and instantiated as follows. An example os its usage is in **ohif-viewerbase/client/components/viewer/viewerMain/viewerMain.js**.
```javascript
import { Viewerbase } from 'meteor/ohif:viewerbase';
// Get an array of studies object. This function needs to be implemented, it does not exist.
const studies = getArrayOfStudiesObjects();
const parentElement = document.getElementById('layoutManagerTarget');
const LayoutManager = new Viewerbase.LayoutManager(parentElement, studies);
```
The default configuration is 1x1, and to change it just set **layoutProps** and call **updateViewports** to update the layout as follows.
```javascript
import { Viewerbase } from 'meteor/ohif:viewerbase';
// Get an array of studies object. This function needs to be implemented, it does not exist.
const studies = getArrayOfStudiesObjects();
const parentElement = document.getElementById('layoutManagerTarget');
const LayoutManager = new LayoutManager(parentElement, studies);
// Set the layout proprerties to 2x2 layout
LayoutManager.layoutProps = {
rows: 2,
columns: 2
};
// It will render four viewports: two in each row.
LayoutManager.updateViewports();
```
The layoutManagerTarget element will have a new class **layout-2-2** (to allow further styling) and it's inner content will a new div#imageViewerViewports that has four inner elements like the following (some elements and attributes were removed for example purpose):
```html
<div class="viewportContainer active" style="height:50%; width:50%;">
<div class="removable">
<div class="imageViewerViewport">
<canvas></canvas>
</div>
<div class="imageViewerViewportOverlay"></div>
<div class="imageViewerLoadingIndicator"></div>
<div class="imageViewerErrorLoadingIndicator"></div>
<div class="viewportOrientationMarkers"></div>
</div>
</div>
```
Each of this _div.viewportContainer_ will have some classes to help CSS specific styling accordingly to the element's position in the grid: **top**, **middle** and **bottom**. This classes are added by **viewer/components/gridLayout/** component in ohif-viewerbase package.
# The Type Safe Collections
With the introduction of the new _Study Metadata API_ in which study metadata is represented by class hierarchies (using prototype-based inheritance), the usage of standard _Minimongo_ collections as a central client-side storage for this data became no longer an option. Standard _Mongo_ and _Minimongo_ collections internally _flatten_ data (in other words, data gets serialized) before storage hence no functions or prototype chains are preserved. In that scenario, when an object is restored (fetched), what is returned is actually a flattened copy of the original object with no functions or prototype (it's no longer an instance of it's original class). As an attempt to overcome this limitation a new type of collection was intruduced: the *TypeSafeCollection*.
The `TypeSafeCollection` is a simple list-like collection which tries to implement an API _similar_ but not compatible with _Mongo_'s API. It supports basic features like search by attribute map and ID, retrieval by index, sorting of result sets, insertion, removal and reactive operations but, unlike _Mongo_'s API, it (still) lacks support to advanced functionality like complex search criterea or flexible sorting options.
## Implementation
The `TypeSafeCollection` is implemented on top of the _JavaScript_ `Array` object. Each element inserted in the collection is appended to the end of its internal array as a _key-value pair (KVP)_ object where the _key_ is a unique randomly generated ID string and the _value_ is the element itself. Once the object has been successfully stored, the generated ID (its ID) is returned to the client code and can later be used to access that specific element. At this point, an important difference to the _Minimongo_ API can be highlighted: a _TypeSafeCollection_ instance will never make any changes to the stored element (e.g., no "\_id" property will ever be assigned to the original object). Another relevant feature that is supported by this design decision is that _not only objects_ can be stored in this collections, but literally _anything_.
Inside the codebase, the _value_ attribute of each _KVP_ entry in the collection is refered to as _the **payload** of the entry_ since it's what really matters to the user. Hence, this term will also be used here to refer to the _value that has been stored in the collection_. That being said, we can approach another important feature of these collections: A single _payload_ cannot be stored more than once in a given collection. When an attempt of inserting a _payload_ which is already present in the collection is detected, the insert operation will fail and `null` will be returned. In that regard, the collection behaves like `Set` object not permitting a payload to be stored more than once. Strict equality is used when comparing payloads, thus cloned objects are not considered the same. This feature adds an additional garantee that a given study/series/instance will not be listed more than once (it was designed as a replacement for central study collections which were always checked for duplicates).
Please refer to the codebase for the full `TypeSafeCollection` API.
## Usage
In order to use the `TypeSafeCollection` class, the **ohif:viewerbase** package needs to be imported by the referring code and instantiated as follows:
```javascript
import { Viewerbase } from 'meteor/ohif:viewerbase'; // i.e., Viewerbase.TypeSafeCollection
OR
import 'meteor/ohif:viewerbase'; // i.e., OHIF.viewerbase.TypeSafeCollection
// The later is preferred when the client code already makes use of the "OHIF" namespace making the second
// "import" a garantee that the ".viewerbase" namespace has been properly loaded.
```
A few usage examples:
```javascript
const Users = new OHIF.viewerbase.TypeSafeCollection();
[[ ... ]]
// Insert a User object...
let userId = Users.insert({
data: {
firstName: 'John',
lastName: 'Doe',
age: 45
},
getFullName() {
return `${this.data.firstName} ${this.data.lastName}`;
},
getAge() {
return this.data.age;
}
});
[[ ... ]]
let theUserWeJustStored = Users.findById(userId); // ;-)
[[ ... ]]
// Retrieve a single user with "Doe" as `lastName`...
let myUser = Users.findBy({ 'data.lastName': 'Doe' });
// Or all users with "Doe" as `lastName`, sorted by `firstName` in ascending
// order and using the `age` attribute to break ties in descending order...
let myUsers = Users.findAllBy({ 'data.lastName': 'Doe' }, {
sort: [ [ 'data.firstName', 'asc' ], [ 'data.age', 'desc' ] ]
});
```

View File

@ -0,0 +1,471 @@
import cornerstone from 'cornerstone-core';
import cornerstoneWADOImageLoader from 'cornerstone-wado-image-loader';
import {
clearStudyLoadingProgress,
setStudyLoadingProgress,
} from '../redux/actions';
import StackManager from '../utils/StackManager';
class BaseLoadingListener {
constructor(stack, options = {}) {
this.id = BaseLoadingListener.getNewId();
this.stack = stack;
this.startListening();
this.statsItemsLimit = options.statsItemsLimit || 2;
this.stats = {
items: [],
total: 0,
elapsedTime: 0,
speed: 0,
};
this._setProgressData = options._setProgressData;
this._clearProgressById = options._clearProgressById;
// Register the start point to make it possible to calculate
// bytes/s or frames/s when the first byte or frame is received
this._addStatsData(0);
// Update the progress before starting the download
// to make it possible to update the UI
this._updateProgress();
}
_addStatsData(value) {
const date = new Date();
const stats = this.stats;
const items = stats.items;
const newItem = {
value,
date,
};
items.push(newItem);
stats.total += newItem.value;
// Remove items until it gets below the limit
while (items.length > this.statsItemsLimit) {
const item = items.shift();
stats.total -= item.value;
}
// Update the elapsedTime (seconds) based on first and last
// elements and recalculate the speed (bytes/s or frames/s)
if (items.length > 1) {
const oldestItem = items[0];
stats.elapsedTime =
(newItem.date.getTime() - oldestItem.date.getTime()) / 1000;
stats.speed = (stats.total - oldestItem.value) / stats.elapsedTime;
}
}
_getProgressId() {
const displaySetInstanceUid = this.stack.displaySetInstanceUid;
return 'StackProgress:' + displaySetInstanceUid;
}
_clearProgress() {
const progressId = this._getProgressId();
this._clearProgressById(progressId);
}
startListening() {
throw new Error('`startListening` must be implemented by child classes');
}
stopListening() {
throw new Error('`stopListening` must be implemented by child classes');
}
destroy() {
this.stopListening();
this._clearProgress();
}
static getNewId() {
const timeSlice = new Date()
.getTime()
.toString()
.slice(-8);
const randomNumber = parseInt(Math.random() * 1000000000);
return timeSlice.toString() + randomNumber.toString();
}
}
class DICOMFileLoadingListener extends BaseLoadingListener {
constructor(stack, options) {
super(stack, options);
this._dataSetUrl = this._getDataSetUrl(stack);
this._lastLoaded = 0;
// Check how many instances has already been download (cached)
this._checkCachedData();
}
_checkCachedData() {
const dataSet = cornerstoneWADOImageLoader.wadouri.dataSetCacheManager.get(
this._dataSetUrl
);
if (dataSet) {
const dataSetLength = dataSet.byteArray.length;
this._updateProgress({
percentComplete: 100,
loaded: dataSetLength,
total: dataSetLength,
});
}
}
_getImageLoadProgressEventName() {
// TODO: Add this event as a constant in Cornerstone
return 'cornerstoneimageloadprogress.' + this.id;
}
startListening() {
const imageLoadProgressEventName = this._getImageLoadProgressEventName();
this.imageLoadProgressEventHandler = this._imageLoadProgressEventHandle.bind(
this
);
this.stopListening();
cornerstone.events.addEventListener(
imageLoadProgressEventName,
this.imageLoadProgressEventHandle
);
}
stopListening() {
const imageLoadProgressEventName = this._getImageLoadProgressEventName();
cornerstone.events.removeEventListener(
imageLoadProgressEventName,
this.imageLoadProgressEventHandle
);
}
_imageLoadProgressEventHandler = e => {
const eventData = e.detail;
const dataSetUrl = this._convertImageIdToDataSetUrl(eventData.imageId);
const bytesDiff = eventData.loaded - this._lastLoaded;
if (!this._dataSetUrl === dataSetUrl) {
return;
}
// Add the bytes downloaded to the stats
this._addStatsData(bytesDiff);
// Update the download progress
this._updateProgress(eventData);
// Cache the last eventData.loaded value
this._lastLoaded = eventData.loaded;
};
_updateProgress(eventData) {
const progressId = this._getProgressId();
eventData = eventData || {};
const progressData = {
multiFrame: false,
percentComplete: eventData.percentComplete,
bytesLoaded: eventData.loaded,
bytesTotal: eventData.total,
bytesPerSecond: this.stats.speed,
};
this._setProgressData(progressId, progressData);
}
_convertImageIdToDataSetUrl(imageId) {
// Remove the prefix ("dicomweb:" or "wadouri:"")
imageId = imageId.replace(/^(dicomweb:|wadouri:)/i, '');
// Remove "frame=999&" from the imageId
imageId = imageId.replace(/frame=\d+&?/i, '');
// Remove the last "&" like in "http://...?foo=1&bar=2&"
imageId = imageId.replace(/&$/, '');
return imageId;
}
_getDataSetUrl(stack) {
const imageId = stack.imageIds[0];
return this._convertImageIdToDataSetUrl(imageId);
}
}
class StackLoadingListener extends BaseLoadingListener {
constructor(stack, options = {}) {
options.statsItemsLimit = 20;
super(stack, options);
this.imageDataMap = this._convertImageIdsArrayToMap(stack.imageIds);
this.framesStatus = this._createArray(stack.imageIds.length, false);
this.loadedCount = 0;
// Check how many instances has already been download (cached)
this._checkCachedData();
}
_convertImageIdsArrayToMap(imageIds) {
const imageIdsMap = new Map();
for (let i = 0; i < imageIds.length; i++) {
imageIdsMap.set(imageIds[i], {
index: i,
loaded: false,
});
}
return imageIdsMap;
}
_createArray(length, defaultValue) {
// `new Array(length)` is an anti-pattern in javascript because its
// funny API. Otherwise I would go for `new Array(length).fill(false)`
const array = [];
for (let i = 0; i < length; i++) {
array[i] = defaultValue;
}
return array;
}
_checkCachedData() {
// const imageIds = this.stack.imageIds;
// TODO: No way to check status of Promise.
/*for(let i = 0; i < imageIds.length; i++) {
const imageId = imageIds[i];
const imagePromise = cornerstone.imageCache.getImageLoadObject(imageId).promise;
if (imagePromise && (imagePromise.state() === 'resolved')) {
this._updateFrameStatus(imageId, true);
}
}*/
}
_getImageLoadedEventName() {
return `${cornerstone.EVENTS.IMAGE_LOADED}.${this.id}`;
}
_getImageCachePromiseRemoveEventName() {
return `${cornerstone.EVENTS.IMAGE_CACHE_PROMISE_REMOVED}.${this.id}`;
}
_imageLoadedEventHandler(e) {
this._updateFrameStatus(e.detail.image.imageId, true);
}
_imageCachePromiseRemovedEventHandler(e) {
this._updateFrameStatus(e.detail.imageId, false);
}
startListening() {
const imageLoadedEventName = this._getImageLoadedEventName();
const imageCachePromiseRemovedEventName = this._getImageCachePromiseRemoveEventName();
this.imageLoadedEventHandler = this._imageLoadedEventHandler.bind(this);
this.imageCachePromiseRemovedEventHandler = this._imageCachePromiseRemovedEventHandler.bind(
this
);
this.stopListening();
cornerstone.events.addEventListener(
imageLoadedEventName,
this.imageLoadedEventHandler
);
cornerstone.events.addEventListener(
imageCachePromiseRemovedEventName,
this.imageCachePromiseRemovedEventHandler
);
}
stopListening() {
const imageLoadedEventName = this._getImageLoadedEventName();
const imageCachePromiseRemovedEventName = this._getImageCachePromiseRemoveEventName();
cornerstone.events.removeEventListener(
imageLoadedEventName,
this.imageLoadedEventHandler
);
cornerstone.events.removeEventListener(
imageCachePromiseRemovedEventName,
this.imageCachePromiseRemovedEventHandler
);
}
_updateFrameStatus(imageId, loaded) {
const imageData = this.imageDataMap.get(imageId);
if (!imageData || imageData.loaded === loaded) {
return;
}
// Add one more frame to the stats
if (loaded) {
this._addStatsData(1);
}
imageData.loaded = loaded;
this.framesStatus[imageData.index] = loaded;
this.loadedCount += loaded ? 1 : -1;
this._updateProgress();
}
_setProgressData(progressId, progressData) {
// TODO: This method (and _clearProgressById) need to access
// the Redux store and should therefore be provided from the
// application. I've added a workaround to pass this in through
// the 'options' variable on instantiation, but this is really ugly.
// We could consider making the StudyLoadingListener a higher-order
// component which would set this stuff itself.
throw new Error(
"The _setProgressData function must be provided in StudyLoadingListener's options"
);
}
_clearProgressById(progressId) {
throw new Error(
"The _clearProgressById function must be provided in StudyLoadingListener's options"
);
}
_updateProgress() {
const totalFramesCount = this.stack.imageIds.length;
const loadedFramesCount = this.loadedCount;
const loadingFramesCount = totalFramesCount - loadedFramesCount;
const percentComplete = Math.round(
(loadedFramesCount / totalFramesCount) * 100
);
const progressId = this._getProgressId();
const progressData = {
multiFrame: true,
totalFramesCount,
loadedFramesCount,
loadingFramesCount,
percentComplete,
framesPerSecond: this.stats.speed,
framesStatus: this.framesStatus,
};
this._setProgressData(progressId, progressData);
}
_logProgress() {
const totalFramesCount = this.stack.imageIds.length;
const displaySetInstanceUid = this.stack.displaySetInstanceUid;
let progressBar = '[';
for (let i = 0; i < totalFramesCount; i++) {
const ch = this.framesStatus[i] ? '|' : '.';
progressBar += `${ch}`;
}
progressBar += ']';
log.info(`${displaySetInstanceUid}: ${progressBar}`);
}
}
class StudyLoadingListener {
constructor(options) {
this.listeners = {};
this.options = options;
}
addStack(stack, stackMetaData) {
// TODO: Make this work for plugins
if (!stack) {
//console.log('Skipping adding stack to StudyLoadingListener');
return;
}
const displaySetInstanceUid = stack.displaySetInstanceUid;
if (!this.listeners[displaySetInstanceUid]) {
const listener = this._createListener(stack, stackMetaData);
if (listener) {
this.listeners[displaySetInstanceUid] = listener;
}
}
}
addStudy(study) {
study.displaySets.forEach(displaySet => {
const stack = StackManager.findOrCreateStack(study, displaySet);
// TODO: Make this work for plugins
if (!stack) {
console.warn('Skipping adding displaySet to StudyLoadingListener');
console.warn(displaySet);
return;
}
this.addStack(stack, {
isMultiFrame: displaySet.isMultiFrame,
});
});
}
addStudies(studies) {
if (!studies || !studies.length) {
return;
}
studies.forEach(study => this.addStudy(study));
}
clear() {
const displaySetInstanceUids = Object.keys(this.listeners);
const length = displaySetInstanceUids.length;
for (let i = 0; i < length; i++) {
const displaySetInstanceUid = displaySetInstanceUids[i];
const displaySet = this.listeners[displaySetInstanceUid];
displaySet.destroy();
}
this.listeners = {};
}
_createListener(stack, stackMetaData) {
const schema = this._getSchema(stack);
// A StackLoadingListener can be created if it's wadors or not a multiframe
// wadouri instance (single file) that means "N" files will have to be
// downloaded where "N" is the number of frames. DICOMFileLoadingListener
// is created only if it's a single DICOM file and there's no way to know
// how many frames has already been loaded (bytes/s instead of frames/s).
if (schema === 'wadors' || !stackMetaData.isMultiFrame) {
return new StackLoadingListener(stack, this.options);
} else {
return new DICOMFileLoadingListener(stack, this.options);
}
}
_getSchema(stack) {
const imageId = stack.imageIds[0];
const colonIndex = imageId.indexOf(':');
return imageId.substring(0, colonIndex);
}
// Singleton
static getInstance(options) {
if (!StudyLoadingListener._instance) {
StudyLoadingListener._instance = new StudyLoadingListener(options);
}
return StudyLoadingListener._instance;
}
}
export { StudyLoadingListener, StackLoadingListener, DICOMFileLoadingListener };

View File

@ -0,0 +1,32 @@
import OHIFError from './OHIFError';
/**
* Abstract class to fetch study metadata.
*/
export class StudyMetadataSource {
/**
* Get study metadata for a study with given study InstanceUID.
* @param {String} studyInstanceUID Study InstanceUID.
*/
getByInstanceUID(studyInstanceUID) {
/**
* Please override this method on a specialized class.
*/
throw new OHIFError(
'StudyMetadataSource::getByInstanceUID is not overriden. Please, override it in a specialized class. See OHIFStudyMetadataSource for example'
);
}
/**
* Load study info and study metadata for a given study into the viewer.
* @param {StudySummary|StudyMetadata} study of StudySummary or StudyMetadata object.
*/
loadStudy(study) {
/**
* Please override this method on a specialized class.
*/
throw new OHIFError(
'StudyMetadataSource::loadStudy is not overriden. Please, override it in a specialized class. See OHIFStudyMetadataSource for example'
);
}
}

View File

@ -0,0 +1,255 @@
import log from '../log.js';
import OHIFError from './OHIFError';
import cornerstone from 'cornerstone-core';
import cornerstoneTools from 'cornerstone-tools';
import getImageId from '../utils/getImageId.js';
export class StudyPrefetcher {
constructor(studies) {
this.studies = studies || [];
this.prefetchDisplaySetsTimeout = 300;
this.lastActiveViewportElement = null;
cornerstone.events.addEventListener(
'cornerstoneimagecachefull.StudyPrefetcher',
this.cacheFullHandler
);
}
destroy() {
this.stopPrefetching();
cornerstone.events.removeEventListener(
'cornerstoneimagecachefull.StudyPrefetcher',
this.cacheFullHandler
);
}
static getInstance() {
if (!StudyPrefetcher.instance) {
StudyPrefetcher.instance = new StudyPrefetcher([]);
}
return StudyPrefetcher.instance;
}
setStudies(studies) {
this.stopPrefetching();
this.studies = studies;
}
prefetch() {
if (!this.studies || !this.studies.length) {
return;
}
this.stopPrefetching();
this.prefetchDisplaySets();
}
stopPrefetching() {
cornerstoneTools.requestPoolManager.clearRequestStack('prefetch');
}
prefetchDisplaySetsAsync(timeout) {
timeout = timeout || this.prefetchDisplaySetsTimeout;
clearTimeout(this.prefetchDisplaySetsHandler);
this.prefetchDisplaySetsHandler = setTimeout(() => {
this.prefetchDisplaySets();
}, timeout);
}
prefetchDisplaySets() {
// TODO: Allow passing in config
let config = {
order: 'closest',
displaySetCount: 1,
};
const displaySetsToPrefetch = this.getDisplaySetsToPrefetch(config);
const imageIds = this.getImageIdsFromDisplaySets(displaySetsToPrefetch);
this.prefetchImageIds(imageIds);
}
prefetchImageIds(imageIds) {
const nonCachedImageIds = this.filterCachedImageIds(imageIds);
const requestPoolManager = cornerstoneTools.requestPoolManager;
const requestType = 'prefetch';
const preventCache = false;
const noop = () => {};
nonCachedImageIds.forEach(imageId => {
requestPoolManager.addRequest(
{},
imageId,
requestType,
preventCache,
noop,
noop
);
});
requestPoolManager.startGrabbing();
}
getStudy(image) {
const studyMetadata = cornerstone.metaData.get('study', image.imageId);
return OHIF.viewer.Studies.find(
study => study.studyInstanceUid === studyMetadata.studyInstanceUid
);
}
getSeries(study, image) {
const seriesMetadata = cornerstone.metaData.get('series', image.imageId);
const studyMetadata = OHIF.viewerbase.getStudyMetadata(study);
return studyMetadata.getSeriesByUID(seriesMetadata.seriesInstanceUid);
}
getInstance(series, image) {
const instanceMetadata = cornerstone.metaData.get(
'instance',
image.imageId
);
return series.getInstanceByUID(instanceMetadata.sopInstanceUid);
}
getActiveDisplaySet(displaySets, instance) {
return displaySets.find(displaySet => {
return displaySet.images.some(displaySetImage => {
return displaySetImage.sopInstanceUid === instance.sopInstanceUid;
});
});
}
getDisplaySetsToPrefetch(config) {
const image = this.getActiveViewportImage();
if (!image || !config || !config.displaySetCount) {
return [];
}
/*const study = this.getStudy(image);
const series = this.getSeries(study, image);
const instance = this.getInstance(series, image);*/
const displaySets = study.displaySets;
const activeDisplaySet = null; //this.getActiveDisplaySet(displaySets, instance);
const prefetchMethodMap = {
topdown: 'getFirstDisplaySets',
downward: 'getNextDisplaySets',
closest: 'getClosestDisplaySets',
};
const prefetchOrder = config.order;
const methodName = prefetchMethodMap[prefetchOrder];
const getDisplaySets = this[methodName];
if (!getDisplaySets) {
if (prefetchOrder) {
log.warn(`Invalid prefetch order configuration (${prefetchOrder})`);
}
return [];
}
return getDisplaySets.call(
this,
displaySets,
activeDisplaySet,
config.displaySetCount
);
}
getFirstDisplaySets(displaySets, activeDisplaySet, displaySetCount) {
const length = displaySets.length;
const selectedDisplaySets = [];
for (let i = 0; i < length && displaySetCount; i++) {
const displaySet = displaySets[i];
if (displaySet !== activeDisplaySet) {
selectedDisplaySets.push(displaySet);
displaySetCount--;
}
}
return selectedDisplaySets;
}
getNextDisplaySets(displaySets, activeDisplaySet, displaySetCount) {
const activeDisplaySetIndex = displaySets.indexOf(activeDisplaySet);
const begin = activeDisplaySetIndex + 1;
const end = Math.min(begin + displaySetCount, displaySets.length);
return displaySets.slice(begin, end);
}
getClosestDisplaySets(displaySets, activeDisplaySet, displaySetCount) {
const activeDisplaySetIndex = displaySets.indexOf(activeDisplaySet);
const length = displaySets.length;
const selectedDisplaySets = [];
let left = activeDisplaySetIndex - 1;
let right = activeDisplaySetIndex + 1;
while ((left >= 0 || right < length) && displaySetCount) {
if (left >= 0) {
selectedDisplaySets.push(displaySets[left]);
displaySetCount--;
left--;
}
if (right < length && displaySetCount) {
selectedDisplaySets.push(displaySets[right]);
displaySetCount--;
right++;
}
}
return selectedDisplaySets;
}
getImageIdsFromDisplaySets(displaySets) {
let imageIds = [];
displaySets.forEach(displaySet => {
imageIds = imageIds.concat(this.getImageIdsFromDisplaySet(displaySet));
});
return imageIds;
}
getImageIdsFromDisplaySet(displaySet) {
const imageIds = [];
// TODO: This duplicates work done by the stack manager
displaySet.images.forEach(image => {
const numFrames = image.numFrames;
if (numFrames > 1) {
for (let i = 0; i < numFrames; i++) {
let imageId = getImageId(image, i);
imageIds.push(imageId);
}
} else {
let imageId = getImageId(image);
imageIds.push(imageId);
}
});
return imageIds;
}
filterCachedImageIds(imageIds) {
return imageIds.filter(imageId => !this.isImageCached(imageId));
}
isImageCached(imageId) {
const image = cornerstone.imageCache.imageCache[imageId];
return image && image.sizeInBytes;
}
cacheFullHandler = () => {
log.warn('Cache full');
this.stopPrefetching();
};
}

View File

@ -0,0 +1,508 @@
import guid from '../utils/guid';
/**
* Constants
*/
const PROPERTY_SEPARATOR = '.';
const ORDER_ASC = 'asc';
const ORDER_DESC = 'desc';
const MIN_COUNT = 0x00000000;
const MAX_COUNT = 0x7fffffff;
/**
* Class Definition
*/
export class TypeSafeCollection {
constructor() {
this._operationCount = MIN_COUNT;
this._elementList = [];
this._handlers = Object.create(null);
}
/**
* Private Methods
*/
_invalidate() {
let count = this._operationCount;
this._operationCount = count < MAX_COUNT ? count + 1 : MIN_COUNT;
}
_elements(silent) {
silent === true || this._operationCount;
return this._elementList;
}
_elementWithPayload(payload, silent) {
return this._elements(silent).find(item => item.payload === payload);
}
_elementWithId(id, silent) {
return this._elements(silent).find(item => item.id === id);
}
_trigger(event, data) {
let handlers = this._handlers;
if (event in handlers) {
handlers = handlers[event];
if (!(handlers instanceof Array)) {
return;
}
for (let i = 0, limit = handlers.length; i < limit; ++i) {
let handler = handlers[i];
if (_isFunction(handler)) {
handler.call(null, data);
}
}
}
}
/**
* Public Methods
*/
onInsert(callback) {
if (_isFunction(callback)) {
let handlers = this._handlers.insert;
if (!(handlers instanceof Array)) {
handlers = [];
this._handlers.insert = handlers;
}
handlers.push(callback);
}
}
/**
* Update the payload associated with the given ID to be the new supplied payload.
* @param {string} id The ID of the entry that will be updated.
* @param {any} payload The element that will replace the previous payload.
* @returns {boolean} Returns true if the given ID is present in the collection, false otherwise.
*/
updateById(id, payload) {
let result = false,
found = this._elementWithPayload(payload, true);
if (found) {
// nothing to do since the element is already in the collection...
if (found.id === id) {
// set result to true since the ids match...
result = true;
this._invalidate();
}
} else {
found = this._elementWithId(id, true);
if (found) {
found.payload = payload;
result = true;
this._invalidate();
}
}
return result;
}
/**
* Signal that the given element has been changed by notifying reactive data-source observers.
* This method is basically a means to invalidate the inernal reactive data-source.
* @param {any} payload The element that has been altered.
* @returns {boolean} Returns true if the element is present in the collection, false otherwise.
*/
update(payload) {
let result = false,
found = this._elementWithPayload(payload, true);
if (found) {
// nothing to do since the element is already in the collection...
result = true;
this._invalidate();
}
return result;
}
/**
* Insert an element in the collection. On success, the element ID (a unique string) is returned. On failure, returns null.
* A failure scenario only happens when the given payload is already present in the collection. Note that NO exceptions are thrown!
* @param {any} payload The element to be stored.
* @returns {string} The ID of the inserted element or null if the element already exists...
*/
insert(payload) {
let id = null,
found = this._elementWithPayload(payload, true);
if (!found) {
id = guid();
this._elements(true).push({ id, payload });
this._invalidate();
this._trigger('insert', { id, data: payload });
}
return id;
}
/**
* Remove all elements from the collection.
* @returns {void} No meaningful value is returned.
*/
removeAll() {
let all = this._elements(true),
length = all.length;
for (let i = length - 1; i >= 0; i--) {
let item = all[i];
delete item.id;
delete item.payload;
all[i] = null;
}
all.splice(0, length);
this._invalidate();
}
/**
* Remove elements from the collection that match the criteria given in the property map.
* @param {Object} propertyMap A property map that will be macthed against all collection elements.
* @returns {Array} A list with all removed elements.
*/
remove(propertyMap) {
let found = this.findAllEntriesBy(propertyMap),
foundCount = found.length,
removed = [];
if (foundCount > 0) {
const all = this._elements(true);
for (let i = foundCount - 1; i >= 0; i--) {
let item = found[i];
all.splice(item[2], 1);
removed.push(item[0]);
}
this._invalidate();
}
return removed;
}
/**
* Provides the ID of the given element inside the collection.
* @param {any} payload The element being searched for.
* @returns {string} The ID of the given element or undefined if the element is not present.
*/
getElementId(payload) {
let found = this._elementWithPayload(payload);
return found && found.id;
}
/**
* Provides the position of the given element in the internal list returning -1 if the element is not present.
* @param {any} payload The element being searched for.
* @returns {number} The position of the given element in the internal list. If the element is not present -1 is returned.
*/
findById(id) {
let found = this._elementWithId(id);
return found && found.payload;
}
/**
* Provides the position of the given element in the internal list returning -1 if the element is not present.
* @param {any} payload The element being searched for.
* @returns {number} The position of the given element in the internal list. If the element is not present -1 is returned.
*/
indexOfElement(payload) {
return this._elements().indexOf(this._elementWithPayload(payload, true));
}
/**
* Provides the position of the element associated with the given ID in the internal list returning -1 if the element is not present.
* @param {string} id The index of the element.
* @returns {number} The position of the element associated with the given ID in the internal list. If the element is not present -1 is returned.
*/
indexOfId(id) {
return this._elements().indexOf(this._elementWithId(id, true));
}
/**
* Provides a list-like approach to the collection returning an element by index.
* @param {number} index The index of the element.
* @returns {any} If out of bounds, undefined is returned. Otherwise the element in the given position is returned.
*/
getElementByIndex(index) {
let found = this._elements()[index >= 0 ? index : -1];
return found && found.payload;
}
/**
* Find an element by a criteria defined by the given callback function.
* Attention!!! The reactive source will not be notified if no valid callback is supplied...
* @param {function} callback A callback function which will define the search criteria. The callback
* function will be passed the collection element, its ID and its index in this very order. The callback
* shall return true when its criterea has been fulfilled.
* @returns {any} The matched element or undefined if not match was found.
*/
find(callback) {
let found;
if (_isFunction(callback)) {
found = this._elements().find((item, index) => {
return callback.call(this, item.payload, item.id, index);
});
}
return found && found.payload;
}
/**
* Find the first element that strictly matches the specified property map.
* @param {Object} propertyMap A property map that will be macthed against all collection elements.
* @param {Object} options A set of options. Currently only "options.sort" option is supported.
* @param {Object.SortingSpecifier} options.sort An optional sorting specifier. If a sorting specifier is supplied
* but is not valid, an exception will be thrown.
* @returns {Any} The matched element or undefined if not match was found.
*/
findBy(propertyMap, options) {
let found;
if (_isObject(options)) {
// if the "options" argument is provided and is a valid object,
// it must be applied to the dataset before search...
const all = this.all(options);
if (all.length > 0) {
if (_isObject(propertyMap)) {
found = all.find(item =>
_compareToPropertyMapStrict(propertyMap, item)
);
} else {
found = all[0]; // simply extract the first element...
}
}
} else if (_isObject(propertyMap)) {
found = this._elements().find(item =>
_compareToPropertyMapStrict(propertyMap, item.payload)
);
if (found) {
found = found.payload;
}
}
return found;
}
/**
* Find all elements that strictly match the specified property map.
* Attention!!! The reactive source will not be notified if no valid property map is supplied...
* @param {Object} propertyMap A property map that will be macthed against all collection elements.
* @returns {Array} An array of entries of all elements that match the given criteria. Each set in
* in the array has the following format: [ elementData, elementId, elementIndex ].
*/
findAllEntriesBy(propertyMap) {
const found = [];
if (_isObject(propertyMap)) {
this._elements().forEach((item, index) => {
if (_compareToPropertyMapStrict(propertyMap, item.payload)) {
// Match! Add it to the found list...
found.push([item.payload, item.id, index]);
}
});
}
return found;
}
/**
* Find all elements that match a specified property map.
* Attention!!! The reactive source will not be notified if no valid property map is supplied...
* @param {Object} propertyMap A property map that will be macthed against all collection elements.
* @param {Object} options A set of options. Currently only "options.sort" option is supported.
* @param {Object.SortingSpecifier} options.sort An optional sorting specifier. If a sorting specifier is supplied
* but is not valid, an exception will be thrown.
* @returns {Array} An array with all elements that match the given criteria and sorted in the specified sorting order.
*/
findAllBy(propertyMap, options) {
const found = this.findAllEntriesBy(propertyMap).map(item => item[0]); // Only payload is relevant...
if (_isObject(options)) {
if ('sort' in options) {
_sortListBy(found, options.sort);
}
}
return found;
}
/**
* Executes the supplied callback function for each element of the collection.
* Attention!!! The reactive source will not be notified if no valid property map is supplied...
* @param {function} callback The callback function to be executed. The callback is passed the element,
* its ID and its index in this very order.
* @returns {void} Nothing is returned.
*/
forEach(callback) {
if (_isFunction(callback)) {
this._elements().forEach((item, index) => {
callback.call(this, item.payload, item.id, index);
});
}
}
/**
* Count the number of elements currently in the collection.
* @returns {number} The current number of elements in the collection.
*/
count() {
return this._elements().length;
}
/**
* Returns a list with all elements of the collection optionally sorted by a sorting specifier criteria.
* @param {Object} options A set of options. Currently only "options.sort" option is supported.
* @param {Object.SortingSpecifier} options.sort An optional sorting specifier. If a sorting specifier is supplied
* but is not valid, an exception will be thrown.
* @returns {Array} An array with all elements stored in the collection.
*/
all(options) {
let list = this._elements().map(item => item.payload);
if (_isObject(options)) {
if ('sort' in options) {
_sortListBy(list, options.sort);
}
}
return list;
}
}
/**
* Utility Functions
*/
/**
* Test if supplied argument is a valid object for current class purposes.
* Atention! The underscore version of this function should not be used for performance reasons.
*/
function _isObject(subject) {
return (
subject instanceof Object ||
(typeof subject === 'object' && subject !== null)
);
}
/**
* Test if supplied argument is a valid string for current class purposes.
* Atention! The underscore version of this function should not be used for performance reasons.
*/
function _isString(subject) {
return typeof subject === 'string';
}
/**
* Test if supplied argument is a valid function for current class purposes.
* Atention! The underscore version of this function should not be used for performance reasons.
*/
function _isFunction(subject) {
return typeof subject === 'function';
}
/**
* Shortcut for Object's prototype "hasOwnProperty" method.
*/
const _hasOwnProperty = Object.prototype.hasOwnProperty;
/**
* Retrieve an object's property value by name. Composite property names (e.g., 'address.country.name') are accepted.
* @param {Object} targetObject The object we want read the property from...
* @param {String} propertyName The property to be read (e.g., 'address.street.name' or 'address.street.number'
* to read object.address.street.name or object.address.street.number, respectively);
* @returns {Any} Returns whatever the property holds or undefined if the property cannot be read or reached.
*/
function _getPropertyValue(targetObject, propertyName) {
let propertyValue; // undefined (the default return value)
if (_isObject(targetObject) && _isString(propertyName)) {
const fragments = propertyName.split(PROPERTY_SEPARATOR);
const fragmentCount = fragments.length;
if (fragmentCount > 0) {
const firstFragment = fragments[0];
const remainingFragments =
fragmentCount > 1 ? fragments.slice(1).join(PROPERTY_SEPARATOR) : null;
propertyValue = targetObject[firstFragment];
if (remainingFragments !== null) {
propertyValue = _getPropertyValue(propertyValue, remainingFragments);
}
}
}
return propertyValue;
}
/**
* Compare a property map with a target object using strict comparison.
* @param {Object} propertyMap The property map whose properties will be used for comparison. Composite
* property names (e.g., 'address.country.name') will be tested against the "resolved" properties from the target object.
* @param {Object} targetObject The target object whose properties will be tested.
* @returns {boolean} Returns true if the properties match, false otherwise.
*/
function _compareToPropertyMapStrict(propertyMap, targetObject) {
let result = false;
// "for in" loops do not thown exceptions for invalid data types...
for (let propertyName in propertyMap) {
if (_hasOwnProperty.call(propertyMap, propertyName)) {
if (
propertyMap[propertyName] !==
_getPropertyValue(targetObject, propertyName)
) {
result = false;
break;
} else if (result !== true) {
result = true;
}
}
}
return result;
}
/**
* Checks if a sorting specifier is valid.
* A valid sorting specifier consists of an array of arrays being each subarray a pair
* in the format ["property name", "sorting order"].
* The following exemple can be used to sort studies by "date"" and use "time" to break ties in descending order.
* [ [ 'study.date', 'desc' ], [ 'study.time', 'desc' ] ]
* @param {Array} specifiers The sorting specifier to be tested.
* @returns {boolean} Returns true if the specifiers are valid, false otherwise.
*/
function _isValidSortingSpecifier(specifiers) {
let result = true;
if (specifiers instanceof Array && specifiers.length > 0) {
for (let i = specifiers.length - 1; i >= 0; i--) {
const item = specifiers[i];
if (item instanceof Array) {
const property = item[0];
const order = item[1];
if (
_isString(property) &&
(order === ORDER_ASC || order === ORDER_DESC)
) {
continue;
}
}
result = false;
break;
}
}
return result;
}
/**
* Sorts an array based on sorting specifier options.
* @param {Array} list The that needs to be sorted.
* @param {Array} specifiers An array of specifiers. Please read isValidSortingSpecifier method definition for further details.
* @returns {void} No value is returned. The array is sorted in place.
*/
function _sortListBy(list, specifiers) {
if (list instanceof Array && _isValidSortingSpecifier(specifiers)) {
const specifierCount = specifiers.length;
list.sort(function _sortListByCallback(a, b) {
// callback name for stack traces...
let index = 0;
while (index < specifierCount) {
const specifier = specifiers[index];
const property = specifier[0];
const order = specifier[1] === ORDER_DESC ? -1 : 1;
const aValue = _getPropertyValue(a, property);
const bValue = _getPropertyValue(b, property);
// @TODO: should we check for the types being compared, like:
// ~~ if (typeof aValue !== typeof bValue) continue;
// Not sure because dates, for example, can be correctly compared to numbers...
if (aValue < bValue) {
return order * -1;
}
if (aValue > bValue) {
return order * 1;
}
if (++index >= specifierCount) {
return 0;
}
}
});
} else {
throw new Error('Invalid Arguments');
}
}

View File

@ -0,0 +1,17 @@
// Only imported in environment w/ `window`
// So we need to mock these for tests
import Mousetrap from 'mousetrap';
import pausePlugin from 'mousetrap/plugins/pause/mousetrap-pause.js';
import recordPlugin from 'mousetrap/plugins/record/mousetrap-record.js';
// import pausePlugin from './pausePlugin.js';
// import recordPlugin from './recordPlugin.js';
// // // TODO: May need to bind these so Mousetrap = this in plugins;
// pausePlugin(Mousetrap);
// recordPlugin(Mousetrap);
// console.log(Mousetrap);
// console.log(Object.keys(Mousetrap));
export default Mousetrap;

View File

@ -0,0 +1,32 @@
/**
* adds a pause and unpause method to Mousetrap
* this allows you to enable or disable keyboard shortcuts
* without having to reset Mousetrap and rebind everything
*
* https://github.com/ccampbell/mousetrap/blob/master/plugins/pause/mousetrap-pause.js
*/
export default function(Mousetrap) {
var _originalStopCallback = Mousetrap.prototype.stopCallback;
Mousetrap.prototype.stopCallback = function(e, element, combo) {
var self = this;
if (self.paused) {
return true;
}
return _originalStopCallback.call(self, e, element, combo);
};
Mousetrap.prototype.pause = function() {
var self = this;
self.paused = true;
};
Mousetrap.prototype.unpause = function() {
var self = this;
self.paused = false;
};
Mousetrap.init();
}

View File

@ -0,0 +1,200 @@
/**
* This extension allows you to record a sequence using Mousetrap.
* {@link https://craig.is/killing/mice}
*
* @author Dan Tao <daniel.tao@gmail.com>
*/
export default function(Mousetrap) {
/**
* the sequence currently being recorded
*
* @type {Array}
*/
var _recordedSequence = [],
/**
* a callback to invoke after recording a sequence
*
* @type {Function|null}
*/
_recordedSequenceCallback = null,
/**
* a list of all of the keys currently held down
*
* @type {Array}
*/
_currentRecordedKeys = [],
/**
* temporary state where we remember if we've already captured a
* character key in the current combo
*
* @type {boolean}
*/
_recordedCharacterKey = false,
/**
* a handle for the timer of the current recording
*
* @type {null|number}
*/
_recordTimer = null,
/**
* the original handleKey method to override when Mousetrap.record() is
* called
*
* @type {Function}
*/
_origHandleKey = Mousetrap.prototype.handleKey;
/**
* handles a character key event
*
* @param {string} character
* @param {Array} modifiers
* @param {Event} e
* @returns void
*/
function _handleKey(character, modifiers, e) {
var self = this;
if (!self.recording) {
_origHandleKey.apply(self, arguments);
return;
}
// remember this character if we're currently recording a sequence
if (e.type == 'keydown') {
if (character.length === 1 && _recordedCharacterKey) {
_recordCurrentCombo();
}
for (i = 0; i < modifiers.length; ++i) {
_recordKey(modifiers[i]);
}
_recordKey(character);
// once a key is released, all keys that were held down at the time
// count as a keypress
} else if (e.type == 'keyup' && _currentRecordedKeys.length > 0) {
_recordCurrentCombo();
}
}
/**
* marks a character key as held down while recording a sequence
*
* @param {string} key
* @returns void
*/
function _recordKey(key) {
var i;
// one-off implementation of Array.indexOf, since IE6-9 don't support it
for (i = 0; i < _currentRecordedKeys.length; ++i) {
if (_currentRecordedKeys[i] === key) {
return;
}
}
_currentRecordedKeys.push(key);
if (key.length === 1) {
_recordedCharacterKey = true;
}
}
/**
* marks whatever key combination that's been recorded so far as finished
* and gets ready for the next combo
*
* @returns void
*/
function _recordCurrentCombo() {
_recordedSequence.push(_currentRecordedKeys);
_currentRecordedKeys = [];
_recordedCharacterKey = false;
_restartRecordTimer();
}
/**
* ensures each combo in a sequence is in a predictable order and formats
* key combos to be '+'-delimited
*
* modifies the sequence in-place
*
* @param {Array} sequence
* @returns void
*/
function _normalizeSequence(sequence) {
var i;
for (i = 0; i < sequence.length; ++i) {
sequence[i].sort(function(x, y) {
// modifier keys always come first, in alphabetical order
if (x.length > 1 && y.length === 1) {
return -1;
} else if (x.length === 1 && y.length > 1) {
return 1;
}
// character keys come next (list should contain no duplicates,
// so no need for equality check)
return x > y ? 1 : -1;
});
sequence[i] = sequence[i].join('+');
}
}
/**
* finishes the current recording, passes the recorded sequence to the stored
* callback, and sets Mousetrap.handleKey back to its original function
*
* @returns void
*/
function _finishRecording() {
if (_recordedSequenceCallback) {
_normalizeSequence(_recordedSequence);
_recordedSequenceCallback(_recordedSequence);
}
// reset all recorded state
_recordedSequence = [];
_recordedSequenceCallback = null;
_currentRecordedKeys = [];
}
/**
* called to set a 1 second timeout on the current recording
*
* this is so after each key press in the sequence the recording will wait for
* 1 more second before executing the callback
*
* @returns void
*/
function _restartRecordTimer() {
clearTimeout(_recordTimer);
_recordTimer = setTimeout(_finishRecording, 1000);
}
/**
* records the next sequence and passes it to a callback once it's
* completed
*
* @param {Function} callback
* @returns void
*/
Mousetrap.prototype.record = function(callback) {
var self = this;
self.recording = true;
_recordedSequenceCallback = function() {
self.recording = false;
callback.apply(self, arguments);
};
};
Mousetrap.prototype.handleKey = function() {
var self = this;
_handleKey.apply(self, arguments);
};
Mousetrap.init();
}

View File

@ -0,0 +1,61 @@
import {
InstanceMetadata,
SeriesMetadata,
StudyMetadata,
StudySummary,
} from './metadata';
import CommandsManager from './CommandsManager.js';
import { DICOMFileLoadingListener } from './StudyLoadingListener';
import HotkeysManager from './HotkeysManager.js';
import ImageSet from './ImageSet';
import MetadataProvider from './MetadataProvider.js';
import OHIFError from './OHIFError.js';
import { OHIFStudyMetadataSource } from './OHIFStudyMetadataSource';
import { StackLoadingListener } from './StudyLoadingListener';
import { StudyLoadingListener } from './StudyLoadingListener';
import { StudyMetadataSource } from './StudyMetadataSource';
import { StudyPrefetcher } from './StudyPrefetcher';
import { TypeSafeCollection } from './TypeSafeCollection';
//import { StudySummary } from './metadata/StudySummary';
export {
OHIFStudyMetadataSource,
MetadataProvider,
CommandsManager,
HotkeysManager,
ImageSet,
StudyPrefetcher,
//StudyLoadingListener,
StackLoadingListener,
DICOMFileLoadingListener,
StudyMetadata,
SeriesMetadata,
InstanceMetadata,
StudySummary,
TypeSafeCollection,
OHIFError,
StudyMetadataSource,
};
const classes = {
OHIFStudyMetadataSource,
MetadataProvider,
CommandsManager,
HotkeysManager,
ImageSet,
StudyPrefetcher,
StudyLoadingListener,
StackLoadingListener,
DICOMFileLoadingListener,
StudyMetadata,
SeriesMetadata,
InstanceMetadata,
StudySummary,
TypeSafeCollection,
OHIFError,
StudyMetadataSource,
};
export default classes;

View File

@ -0,0 +1,225 @@
import { Metadata } from './Metadata';
import OHIFError from '../OHIFError.js';
/**
* ATTENTION! This class should never depend on StudyMetadata or SeriesMetadata classes as this could
* possibly cause circular dependency issues.
*/
const UNDEFINED = 'undefined';
const STRING = 'string';
const STUDY_INSTANCE_UID = 'x0020000d';
const SERIES_INSTANCE_UID = 'x0020000e';
export class InstanceMetadata extends Metadata {
constructor(data, uid) {
super(data, uid);
// Initialize Private Properties
Object.defineProperties(this, {
_sopInstanceUID: {
configurable: true, // configurable so that it can be redefined in sub-classes...
enumerable: false,
writable: true,
value: null,
},
_imageId: {
configurable: true, // configurable so that it can be redefined in sub-classes...
enumerable: false,
writable: true,
value: null,
},
});
// Initialize Public Properties
this._definePublicProperties();
}
/**
* Private Methods
*/
/**
* Define Public Properties
* This method should only be called during initialization (inside the class constructor)
*/
_definePublicProperties() {
/**
* Property: this.sopInstanceUID
* Same as this.getSOPInstanceUID()
* It's specially useful in contexts where a method call is not suitable like in search criteria. For example:
* sopInstanceCollection.findBy({
* sopInstanceUID: '1.2.3.4.5.6.77777.8888888.99999999999.0'
* });
*/
Object.defineProperty(this, 'sopInstanceUID', {
configurable: false,
enumerable: false,
get: function() {
return this.getSOPInstanceUID();
},
});
}
/**
* Public Methods
*/
/**
* Returns the StudyInstanceUID of the current instance. This method is basically a shorthand the full "getTagValue" method call.
*/
getStudyInstanceUID() {
return this.getTagValue(STUDY_INSTANCE_UID, null);
}
/**
* Returns the SeriesInstanceUID of the current instance. This method is basically a shorthand the full "getTagValue" method call.
*/
getSeriesInstanceUID() {
return this.getTagValue(SERIES_INSTANCE_UID, null);
}
/**
* Returns the SOPInstanceUID of the current instance.
*/
getSOPInstanceUID() {
return this._sopInstanceUID;
}
// @TODO: Improve this... (E.g.: blob data)
getStringValue(tagOrProperty, index, defaultValue) {
let value = this.getTagValue(tagOrProperty, defaultValue);
if (typeof value !== STRING && typeof value !== UNDEFINED) {
value = value.toString();
}
return InstanceMetadata.getIndexedValue(value, index, defaultValue);
}
// @TODO: Improve this... (E.g.: blob data)
getFloatValue(tagOrProperty, index, defaultValue) {
let value = this.getTagValue(tagOrProperty, defaultValue);
value = InstanceMetadata.getIndexedValue(value, index, defaultValue);
if (value instanceof Array) {
value.forEach((val, idx) => {
value[idx] = parseFloat(val);
});
return value;
}
return typeof value === STRING ? parseFloat(value) : value;
}
// @TODO: Improve this... (E.g.: blob data)
getIntValue(tagOrProperty, index, defaultValue) {
let value = this.getTagValue(tagOrProperty, defaultValue);
value = InstanceMetadata.getIndexedValue(value, index, defaultValue);
if (value instanceof Array) {
value.forEach((val, idx) => {
value[idx] = parseFloat(val);
});
return value;
}
return typeof value === STRING ? parseInt(value) : value;
}
/**
* @deprecated Please use getTagValue instead.
*/
getRawValue(tagOrProperty, defaultValue) {
return this.getTagValue(tagOrProperty, defaultValue);
}
/**
* This function should be overriden by specialized classes in order to allow client libraries or viewers to take advantage of the Study Metadata API.
*/
getTagValue(tagOrProperty, defaultValue) {
/**
* Please override this method on a specialized class.
*/
throw new OHIFError(
'InstanceMetadata::getTagValue is not overriden. Please, override it in a specialized class. See OHIFInstanceMetadata for example'
);
}
/**
* Compares the current instance with another one.
* @param {InstanceMetadata} instance An instance of the InstanceMetadata class.
* @returns {boolean} Returns true if both instances refer to the same instance.
*/
equals(instance) {
const self = this;
return (
instance === self ||
(instance instanceof InstanceMetadata &&
instance.getSOPInstanceUID() === self.getSOPInstanceUID())
);
}
/**
* Check if the tagOrProperty exists
* @param {String} tagOrProperty tag or property be checked
* @return {Boolean} True if the tag or property exists or false if doesn't
*/
tagExists(tagOrProperty) {
/**
* Please override this method
*/
throw new OHIFError(
'InstanceMetadata::tagExists is not overriden. Please, override it in a specialized class. See OHIFInstanceMetadata for example'
);
}
/**
* Get custom image id of a sop instance
* @return {Any} sop instance image id
*/
getImageId(frame) {
/**
* Please override this method
*/
throw new OHIFError(
'InstanceMetadata::getImageId is not overriden. Please, override it in a specialized class. See OHIFInstanceMetadata for example'
);
}
/**
* Static Methods
*/
/**
* Get an value based that can be index based. This function is called by all getters. See above functions.
* - If value is a String and has indexes:
* - If undefined index: returns an array of the split values.
* - If defined index:
* - If invalid: returns defaultValue
* - If valid: returns the indexed value
* - If value is not a String, returns default value.
*/
static getIndexedValue(value, index, defaultValue) {
let result = defaultValue;
if (typeof value === STRING) {
const hasIndexValues = value.indexOf('\\') !== -1;
result = value;
if (hasIndexValues) {
const splitValues = value.split('\\');
if (Metadata.isValidIndex(index)) {
const indexedValue = splitValues[index];
result = typeof indexedValue !== STRING ? defaultValue : indexedValue;
} else {
result = splitValues;
}
}
}
return result;
}
}

View File

@ -0,0 +1,127 @@
/**
* Constants
*/
const STRING = 'string';
const NUMBER = 'number';
const FUNCTION = 'function';
const OBJECT = 'object';
/**
* Class Definition
*/
export class Metadata {
/**
* Constructor and Instance Methods
*/
constructor(data, uid) {
// Define the main "_data" private property as an immutable property.
// IMPORTANT: This property can only be set during instance construction.
Object.defineProperty(this, '_data', {
configurable: false,
enumerable: false,
writable: false,
value: data,
});
// Define the main "_uid" private property as an immutable property.
// IMPORTANT: This property can only be set during instance construction.
Object.defineProperty(this, '_uid', {
configurable: false,
enumerable: false,
writable: false,
value: uid,
});
// Define "_custom" properties as an immutable property.
// IMPORTANT: This property can only be set during instance construction.
Object.defineProperty(this, '_custom', {
configurable: false,
enumerable: false,
writable: false,
value: Object.create(null),
});
}
getData() {
return this._data;
}
getDataProperty(propertyName) {
let propertyValue;
const _data = this._data;
if (
_data instanceof Object ||
(typeof _data === OBJECT && _data !== null)
) {
propertyValue = _data[propertyName];
}
return propertyValue;
}
/**
* Get unique object ID
*/
getObjectID() {
return this._uid;
}
/**
* Set custom attribute value
* @param {String} attribute Custom attribute name
* @param {Any} value Custom attribute value
*/
setCustomAttribute(attribute, value) {
this._custom[attribute] = value;
}
/**
* Get custom attribute value
* @param {String} attribute Custom attribute name
* @return {Any} Custom attribute value
*/
getCustomAttribute(attribute) {
return this._custom[attribute];
}
/**
* Check if a custom attribute exists
* @param {String} attribute Custom attribute name
* @return {Boolean} True if custom attribute exists or false if not
*/
customAttributeExists(attribute) {
return attribute in this._custom;
}
/**
* Set custom attributes in batch mode.
* @param {Object} attributeMap An object whose own properties will be used as custom attributes.
*/
setCustomAttributes(attributeMap) {
const _hasOwn = Object.prototype.hasOwnProperty;
const _custom = this._custom;
for (let attribute in attributeMap) {
if (_hasOwn.call(attributeMap, attribute)) {
_custom[attribute] = attributeMap[attribute];
}
}
}
/**
* Static Methods
*/
static isValidUID(uid) {
return typeof uid === STRING && uid.length > 0;
}
static isValidIndex(index) {
return typeof index === NUMBER && index >= 0 && (index | 0) === index;
}
static isValidCallback(callback) {
return typeof callback === FUNCTION;
}
}

View File

@ -0,0 +1,124 @@
import { InstanceMetadata } from './InstanceMetadata';
import { DICOMTagDescriptions } from '../../utils/DICOMTagDescriptions.js';
import getImageId from '../../utils/getImageId.js';
export class OHIFInstanceMetadata extends InstanceMetadata {
/**
* @param {Object} Instance object.
*/
constructor(data, series, study, uid) {
super(data, uid);
this.init(series, study);
}
init(series, study) {
const instance = this.getData();
// Initialize Private Properties
Object.defineProperties(this, {
_sopInstanceUID: {
configurable: false,
enumerable: false,
writable: false,
value: instance.sopInstanceUid,
},
_study: {
configurable: false,
enumerable: false,
writable: false,
value: study,
},
_series: {
configurable: false,
enumerable: false,
writable: false,
value: series,
},
_instance: {
configurable: false,
enumerable: false,
writable: false,
value: instance,
},
_cache: {
configurable: false,
enumerable: false,
writable: false,
value: Object.create(null),
},
});
}
// Override
getTagValue(tagOrProperty, defaultValue, bypassCache) {
// check if this property has been cached...
if (tagOrProperty in this._cache && bypassCache !== true) {
return this._cache[tagOrProperty];
}
const propertyName = OHIFInstanceMetadata.getPropertyName(tagOrProperty);
// Search property value in the whole study metadata chain...
let rawValue;
if (propertyName in this._instance) {
rawValue = this._instance[propertyName];
} else if (propertyName in this._series) {
rawValue = this._series[propertyName];
} else if (propertyName in this._study) {
rawValue = this._study[propertyName];
}
if (rawValue !== void 0) {
// if rawValue value is not undefined, cache result...
this._cache[tagOrProperty] = rawValue;
return rawValue;
}
return defaultValue;
}
// Override
tagExists(tagOrProperty) {
const propertyName = OHIFInstanceMetadata.getPropertyName(tagOrProperty);
return (
propertyName in this._instance ||
propertyName in this._series ||
propertyName in this._study
);
}
// Override
getImageId(frame, thumbnail) {
// If _imageID is not cached, create it
if (this._imageId === null) {
this._imageId = getImageId(this.getData(), frame, thumbnail);
}
return this._imageId;
}
/**
* Static methods
*/
// @TODO: The current mapping of standard DICOM property names to local property names is not optimal.
// The inconsistency in property naming makes this function increasingly complex.
// A possible solution to improve this would be adapt retriveMetadata names to use DICOM standard names as in dicomTagDescriptions.js
static getPropertyName(tagOrProperty) {
let propertyName;
const tagInfo = DICOMTagDescriptions.find(tagOrProperty);
if (tagInfo !== void 0) {
// This function tries to translate standard DICOM property names into local naming convention.
propertyName = tagInfo.keyword
.replace(/^SOP/, 'sop')
.replace(/UID$/, 'Uid')
.replace(/ID$/, 'Id');
propertyName =
propertyName.charAt(0).toLowerCase() + propertyName.substr(1);
}
return propertyName;
}
}

View File

@ -0,0 +1,29 @@
import { SeriesMetadata } from './SeriesMetadata';
import { OHIFInstanceMetadata } from './OHIFInstanceMetadata';
export class OHIFSeriesMetadata extends SeriesMetadata {
/**
* @param {Object} Series object.
*/
constructor(data, study, uid) {
super(data, uid);
this.init(study);
}
init(study) {
const series = this.getData();
// define "_seriesInstanceUID" protected property...
Object.defineProperty(this, '_seriesInstanceUID', {
configurable: false,
enumerable: false,
writable: false,
value: series.seriesInstanceUid,
});
// populate internal list of instances...
series.instances.forEach(instance => {
this.addInstance(new OHIFInstanceMetadata(instance, series, study));
});
}
}

View File

@ -0,0 +1,29 @@
import { StudyMetadata } from './StudyMetadata';
import { OHIFSeriesMetadata } from './OHIFSeriesMetadata';
export class OHIFStudyMetadata extends StudyMetadata {
/**
* @param {Object} Study object.
*/
constructor(data, uid) {
super(data, uid);
this.init();
}
init() {
const study = this.getData();
// define "_studyInstanceUID" protected property
Object.defineProperty(this, '_studyInstanceUID', {
configurable: false,
enumerable: false,
writable: false,
value: study.studyInstanceUid,
});
// populate internal list of series
study.seriesList.forEach(series => {
this.addSeries(new OHIFSeriesMetadata(series, study));
});
}
}

View File

@ -0,0 +1,145 @@
# Study Metadata Module
This module defines the API/Data-Model by which OHIF Viewerbase package and
possibly distinct viewer implementations can access studies metadata. This
module does not attempt to define any means of _loading_ study metadata from any
data end-point but only how the data that has been previously loaded into the
application context will be accessed by any of the routines or algorithm
implementations that need the data.
## Intro
For various reasons like sorting, grouping or simply rendering study
information, OHIF Viewerbase package and applications depending on it usually
have the need to access study metadata. Before the current initiative there was
no uniform way of achieving that since each implementation provides study
metadata on its own specific ways. The application and the package itself needed
to have a deep knowledge of the data structures provided by the data endpoint to
perform any of the operations mentioned above, meaning that any data access code
needed to be adapted or rewritten.
The intent of the current module is to provide a fairly consistent and flexible
API/Data-Model by which OHIF Viewerbase package (and different viewer
implementations that depend on it) can manipulate DICOM matadata retrieved from
distinct data end points (e.g., a proprietary back end servers) in uniform ways
with minor to no modifications needed.
## Implementation
The current API implementation defines three classes of objects:
`StudyMetadata`, `SeriesMetadata` and `InstanceMetadata`. Inside OHIF Viewerbase
package, every access to Study, Series or SOP Instance metadata is achieved by
the interface exposed by these three classes. By inheriting from them and
overriding or extending their methods, different applications with different
data models can adapt even the most peculiar data structures to the uniform
interface defined by those classes. Together these classes define a flexible and
extensible data manipulation layer leaving routines and algorithms that depend
on that data untouched.
## Design Decisions & "_Protected_" Members
In order to provide for good programming practices, attributes and methods meant
to be used exclusively by the classes themselves (for internal purposes only)
were written with an initial '\_' character, being thus treated as "_protected_"
members. The idea behind this practice was never to hide them from the
programmers (what makes debugging tasks painful) but only advise for something
that's not part of the official public API and thus should not be relied on.
Usage of "protected" members makes the code less readable and prone to
compatibility issues.
As an example, the initial implementation of the `StudyMetadata` class defined
the attribute `_studyInstanceUID` and the method `getStudyInstanceUID`. This
implies that whenever the _StudyInstanceUID_ of a given study needs to be
retrieved the `getStudyInstanceUID` method should be called instead of directly
accessing the attribute `_studyInstanceUID` (which might not even be populated
since `getStudyInstanceUID` can be possiblity overriden by a subclass to satisfy
specific implementation needs, leaving the attribute `_studyInstanceUID`
unused).
Ex:
```javascript
let studyUID = myStudy.getStudyInstanceUID(); // GOOD! :-)
[ ... ]
let otherStudyUID = anotherStudy._studyInstanceUID; // BAD... :-(
```
Another important topic is the preference of _methods_ over _attributes_ on the
public API. This design decision was made to ensure extensibility and
flexibility (methods are extensible while standalone attributes are not, and can
be adapted through overrides, for example to support even the most peculiar
data models) even though the overhead a few additional function calls may incur.
## Abstract Classes
Some classes defined in this module are "_abstract_" classes (even though
JavaScript does not _officially_ support such programming facility). They are
_abstract_ in the sense that a few methods (very important ones, by the way)
were left "_blank_" (unimplemented, or more precisely implemented as empty NOP
functions) in order to be implemented by specialized subclasses. Methods
believed to be more generic were implemented in an attempt to satify most
implementation needs but nothing prevents a subclass from overriding them as
well (again, flexibility and extensibility are design goals). Most implemented
methods rely on the implementation of an unimplemented method. For example, the
method `getStringValue` from `InstanceMetadata` class, which has indeed been
implemented and is meant to retrieve a metadata value as a string, internally
calls the `getRawValue` method which _was NOT implemented_ and is meant to query
the internal data structures for the requested metadata value and return it _as
is_. Used in that way, an application would not benefit much from the already
implemented methods. On the other hand, by simply overriding the `getRawValue`
method on a specialized class to deal with the intrinsics of its internal data
structures, this very application would now benefit from all already implemented
methods.
The following code snippet tries to illustrate the idea:
```javascript
// -- InstanceMetadata.js
class InstanceMetadata {
[ ... ]
getRawValue(tagOrProperty, defaultValue) {
// Please implement this method in a specialized subclass...
}
[ ... ]
getStringValue(tagOrProperty, index, defaultValue) {
let rawValue = this.getRawValue(tagOrProperty, '');
// parse the returned value into a string...
[ ... ]
return stringValue;
}
[ ... ]
}
// -- MyFancyAppInstanceMetadata.js
class MyFancyAppInstanceMetadata extends InstanceMetadata {
// Overriding this method will make all methods implemented in the super class
// that rely on it to be immediately available...
getRawValue(tagOrProperty, defaultValue) {
let rawValue;
// retrieve raw value from internal data structures...
[ ... ]
return rawValue;
}
}
// -- main.js
[ ... ]
let sopInstaceMetadata = new MyFancyAppInstanceMetadata(myInternalData);
if (sopInstaceMetadata instanceof MyFancyAppInstanceMetadata) { // true
// this code will be executed...
}
if (sopInstaceMetadata instanceof InstanceMetadata) { // also true
// this code will also be executed...
}
// The following will also work since the internal "getRawValue" call inside
// "getStringValue" method will now be satisfied... (thanks to the override)
let patientName = sopInstaceMetadata.getStringValue('PatientName', '');
[ ... ]
```
_Copyright &copy; 2016 nucleushealth&trade;. All rights reserved_

View File

@ -0,0 +1,192 @@
import { Metadata } from './Metadata';
import { InstanceMetadata } from './InstanceMetadata';
export class SeriesMetadata extends Metadata {
constructor(data, uid) {
super(data, uid);
// Initialize Private Properties
Object.defineProperties(this, {
_seriesInstanceUID: {
configurable: true, // configurable so that it can be redefined in sub-classes...
enumerable: false,
writable: true,
value: null,
},
_instances: {
configurable: false,
enumerable: false,
writable: false,
value: [],
},
_firstInstance: {
configurable: false,
enumerable: false,
writable: true,
value: null,
},
});
// Initialize Public Properties
this._definePublicProperties();
}
/**
* Private Methods
*/
/**
* Define Public Properties
* This method should only be called during initialization (inside the class constructor)
*/
_definePublicProperties() {
/**
* Property: this.seriesInstanceUID
* Same as this.getSeriesInstanceUID()
* It's specially useful in contexts where a method call is not suitable like in search criteria. For example:
* seriesCollection.findBy({
* seriesInstanceUID: '1.2.3.4.5.6.77777.8888888.99999999999.0'
* });
*/
Object.defineProperty(this, 'seriesInstanceUID', {
configurable: false,
enumerable: false,
get: function() {
return this.getSeriesInstanceUID();
},
});
}
/**
* Public Methods
*/
/**
* Returns the SeriesInstanceUID of the current series.
*/
getSeriesInstanceUID() {
return this._seriesInstanceUID;
}
/**
* Append an instance to the current series.
* @param {InstanceMetadata} instance The instance to be added to the current series.
* @returns {boolean} Returns true on success, false otherwise.
*/
addInstance(instance) {
let result = false;
if (
instance instanceof InstanceMetadata &&
this.getInstanceByUID(instance.getSOPInstanceUID()) === void 0
) {
this._instances.push(instance);
result = true;
}
return result;
}
/**
* Get the first instance of the current series retaining a consistent result across multiple calls.
* @return {InstanceMetadata} An instance of the InstanceMetadata class or null if it does not exist.
*/
getFirstInstance() {
let instance = this._firstInstance;
if (!(instance instanceof InstanceMetadata)) {
instance = null;
const found = this.getInstanceByIndex(0);
if (found instanceof InstanceMetadata) {
this._firstInstance = found;
instance = found;
}
}
return instance;
}
/**
* Find an instance by index.
* @param {number} index An integer representing a list index.
* @returns {InstanceMetadata} Returns a InstanceMetadata instance when found or undefined otherwise.
*/
getInstanceByIndex(index) {
let found; // undefined by default...
if (Metadata.isValidIndex(index)) {
found = this._instances[index];
}
return found;
}
/**
* Find an instance by SOPInstanceUID.
* @param {string} uid An UID string.
* @returns {InstanceMetadata} Returns a InstanceMetadata instance when found or undefined otherwise.
*/
getInstanceByUID(uid) {
let found; // undefined by default...
if (Metadata.isValidUID(uid)) {
found = this._instances.find(instance => {
return instance.getSOPInstanceUID() === uid;
});
}
return found;
}
/**
* Retrieve the number of instances within the current series.
* @returns {number} The number of instances in the current series.
*/
getInstanceCount() {
return this._instances.length;
}
/**
* Invokes the supplied callback for each instance in the current series passing
* two arguments: instance (an InstanceMetadata instance) and index (the integer
* index of the instance within the current series)
* @param {function} callback The callback function which will be invoked for each instance in the series.
* @returns {undefined} Nothing is returned.
*/
forEachInstance(callback) {
if (Metadata.isValidCallback(callback)) {
this._instances.forEach((instance, index) => {
callback.call(null, instance, index);
});
}
}
/**
* Find the index of an instance inside the series.
* @param {InstanceMetadata} instance An instance of the SeriesMetadata class.
* @returns {number} The index of the instance inside the series or -1 if not found.
*/
indexOfInstance(instance) {
return this._instances.indexOf(instance);
}
/**
* Search the associated instances using the supplied callback as criteria. The callback is passed
* two arguments: instance (a InstanceMetadata instance) and index (the integer
* index of the instance within its series)
* @param {function} callback The callback function which will be invoked for each instance.
* @returns {InstanceMetadata|undefined} If an instance is found based on callback criteria it
* returns a InstanceMetadata. "undefined" is returned otherwise
*/
findInstance(callback) {
if (Metadata.isValidCallback(callback)) {
return this._instances.find((instance, index) => {
return callback.call(null, instance, index);
});
}
}
/**
* Compares the current series with another one.
* @param {SeriesMetadata} series An instance of the SeriesMetadata class.
* @returns {boolean} Returns true if both instances refer to the same series.
*/
equals(series) {
const self = this;
return (
series === self ||
(series instanceof SeriesMetadata &&
series.getSeriesInstanceUID() === self.getSeriesInstanceUID())
);
}
}

View File

@ -0,0 +1,651 @@
// - createStacks
import DICOMWeb from './../../DICOMWeb';
import ImageSet from './../ImageSet';
import { InstanceMetadata } from './InstanceMetadata';
import { Metadata } from './Metadata';
import OHIFError from '../OHIFError';
import { SeriesMetadata } from './SeriesMetadata';
// - createStacks
import { api } from 'dicomweb-client';
// - createStacks
import { isImage } from './../../utils/isImage';
export class StudyMetadata extends Metadata {
constructor(data, uid) {
super(data, uid);
// Initialize Private Properties
Object.defineProperties(this, {
_studyInstanceUID: {
configurable: true, // configurable so that it can be redefined in sub-classes...
enumerable: false,
writable: true,
value: null,
},
_series: {
configurable: false,
enumerable: false,
writable: false,
value: [],
},
_displaySets: {
configurable: false,
enumerable: false,
writable: false,
value: [],
},
_firstSeries: {
configurable: false,
enumerable: false,
writable: true,
value: null,
},
_firstInstance: {
configurable: false,
enumerable: false,
writable: true,
value: null,
},
});
// Initialize Public Properties
this._definePublicProperties();
}
/**
* Private Methods
*/
/**
* Define Public Properties
* This method should only be called during initialization (inside the class constructor)
*/
_definePublicProperties() {
/**
* Property: this.studyInstanceUID
* Same as this.getStudyInstanceUID()
* It's specially useful in contexts where a method call is not suitable like in search criteria. For example:
* studyCollection.findBy({
* studyInstanceUID: '1.2.3.4.5.6.77777.8888888.99999999999.0'
* });
*/
Object.defineProperty(this, 'studyInstanceUID', {
configurable: false,
enumerable: false,
get: function() {
return this.getStudyInstanceUID();
},
});
}
/**
* Public Methods
*/
/**
* Getter for displaySets
* @return {Array} Array of display set object
*/
getDisplaySets() {
return this._displaySets.slice();
}
/**
* Creates a set of series to be placed in the Study Metadata
* The series that appear in the Study Metadata must represent
* imaging modalities.
*
* Furthermore, for drag/drop functionality,
* it is easiest if the stack objects also contain information about
* which study they are linked to.
*
* @param {StudyMetadata} study The study instance metadata to be used
* @returns {Array} An array of series to be placed in the Study Metadata
*/
createDisplaySets(sopClassHandlerModules) {
const study = this;
const displaySets = [];
const anyDisplaySets = study.getSeriesCount();
const anySopClassHandlerModules =
sopClassHandlerModules && sopClassHandlerModules.length > 0;
if (!anyDisplaySets) {
return displaySets;
}
// Loop through the series (SeriesMetadata)
this.forEachSeries(series => {
const anyInstances = series.getInstanceCount() > 0;
if (!anyInstances) {
return;
}
const sopClassUids = getSopClassUids(series);
if (anySopClassHandlerModules) {
const displaySet = _getDisplaySetFromSopClassModule(
sopClassHandlerModules,
series,
study,
sopClassUids
);
if (displaySet) {
displaySets.push(displaySet);
return;
}
}
// WE NEED A BETTER WAY TO NOTE THAT THIS IS THE DEFAULT BEHAVIOR FOR LOADING
// A DISPLAY SET IF THERE IS NO MATCHING SOP CLASS PLUGIN
// Search through the instances (InstanceMetadata object) of this series
// Split Multi-frame instances and Single-image modalities
// into their own specific display sets. Place the rest of each
// series into another display set.
const stackableInstances = [];
series.forEachInstance(instance => {
// All imaging modalities must have a valid value for sopClassUid (x00080016) or rows (x00280010)
if (
!isImage(instance.getRawValue('x00080016')) &&
!instance.getRawValue('x00280010')
) {
return;
}
let displaySet;
if (isMultiFrame(instance)) {
displaySet = makeDisplaySet(series, [instance]);
displaySet.setAttributes({
sopClassUids,
isClip: true,
seriesInstanceUid: series.getSeriesInstanceUID(),
studyInstanceUid: study.getStudyInstanceUID(), // Include the study instance Uid for drag/drop purposes
numImageFrames: instance.getRawValue('x00280008'), // Override the default value of instances.length
instanceNumber: instance.getRawValue('x00200013'), // Include the instance number
acquisitionDatetime: instance.getRawValue('x0008002a'), // Include the acquisition datetime
});
displaySets.push(displaySet);
} else if (isSingleImageModality(instance.modality)) {
displaySet = makeDisplaySet(series, [instance]);
displaySet.setAttributes({
sopClassUids,
studyInstanceUid: study.getStudyInstanceUID(), // Include the study instance Uid
seriesInstanceUid: series.getSeriesInstanceUID(),
instanceNumber: instance.getRawValue('x00200013'), // Include the instance number
acquisitionDatetime: instance.getRawValue('x0008002a'), // Include the acquisition datetime
});
displaySets.push(displaySet);
} else {
stackableInstances.push(instance);
}
});
if (stackableInstances.length) {
const displaySet = makeDisplaySet(series, stackableInstances);
displaySet.setAttribute(
'studyInstanceUid',
study.getStudyInstanceUID()
);
displaySet.setAttributes({
sopClassUids,
});
displaySets.push(displaySet);
}
});
// TODO
displaySets.sort(_sortBySeriesNumber);
return displaySets;
}
/**
* Set display sets
* @param {Array} displaySets Array of display sets (ImageSet[])
*/
setDisplaySets(displaySets) {
displaySets.forEach(displaySet => this.addDisplaySet(displaySet));
}
/**
* Add a single display set to the list
* @param {Object} displaySet Display set object
* @returns {boolean} True on success, false on failure.
*/
addDisplaySet(displaySet) {
if (displaySet instanceof ImageSet) {
this._displaySets.push(displaySet);
return true;
}
return false;
}
/**
* Invokes the supplied callback for each display set in the current study passing
* two arguments: display set (a ImageSet instance) and index (the integer
* index of the display set within the current study)
* @param {function} callback The callback function which will be invoked for each display set instance.
* @returns {undefined} Nothing is returned.
*/
forEachDisplaySet(callback) {
if (Metadata.isValidCallback(callback)) {
this._displaySets.forEach((displaySet, index) => {
callback.call(null, displaySet, index);
});
}
}
/**
* Search the associated display sets using the supplied callback as criteria. The callback is passed
* two arguments: display set (an ImageSet instance) and index (the integer
* index of the display set within the current study)
* @param {function} callback The callback function which will be invoked for each display set instance.
* @returns {undefined} Nothing is returned.
*/
findDisplaySet(callback) {
if (Metadata.isValidCallback(callback)) {
return this._displaySets.find((displaySet, index) => {
return callback.call(null, displaySet, index);
});
}
}
/**
* Retrieve the number of display sets within the current study.
* @returns {number} The number of display sets in the current study.
*/
getDisplaySetCount() {
return this._displaySets.length;
}
/**
* Returns the StudyInstanceUID of the current study.
*/
getStudyInstanceUID() {
return this._studyInstanceUID;
}
/**
* Getter for series
* @return {Array} Array of SeriesMetadata object
*/
getSeries() {
return this._series.slice();
}
/**
* Append a series to the current study.
* @param {SeriesMetadata} series The series to be added to the current study.
* @returns {boolean} Returns true on success, false otherwise.
*/
addSeries(series) {
let result = false;
if (
series instanceof SeriesMetadata &&
this.getSeriesByUID(series.getSeriesInstanceUID()) === void 0
) {
this._series.push(series);
result = true;
}
return result;
}
/**
* Find a series by index.
* @param {number} index An integer representing a list index.
* @returns {SeriesMetadata} Returns a SeriesMetadata instance when found or undefined otherwise.
*/
getSeriesByIndex(index) {
let found; // undefined by default...
if (Metadata.isValidIndex(index)) {
found = this._series[index];
}
return found;
}
/**
* Find a series by SeriesInstanceUID.
* @param {string} uid An UID string.
* @returns {SeriesMetadata} Returns a SeriesMetadata instance when found or undefined otherwise.
*/
getSeriesByUID(uid) {
let found; // undefined by default...
if (Metadata.isValidUID(uid)) {
found = this._series.find(series => {
return series.getSeriesInstanceUID() === uid;
});
}
return found;
}
/**
* Retrieve the number of series within the current study.
* @returns {number} The number of series in the current study.
*/
getSeriesCount() {
return this._series.length;
}
/**
* Retrieve the number of instances within the current study.
* @returns {number} The number of instances in the current study.
*/
getInstanceCount() {
return this._series.reduce((sum, series) => {
return sum + series.getInstanceCount();
}, 0);
}
/**
* Invokes the supplied callback for each series in the current study passing
* two arguments: series (a SeriesMetadata instance) and index (the integer
* index of the series within the current study)
* @param {function} callback The callback function which will be invoked for each series instance.
* @returns {undefined} Nothing is returned.
*/
forEachSeries(callback) {
if (Metadata.isValidCallback(callback)) {
this._series.forEach((series, index) => {
callback.call(null, series, index);
});
}
}
/**
* Find the index of a series inside the study.
* @param {SeriesMetadata} series An instance of the SeriesMetadata class.
* @returns {number} The index of the series inside the study or -1 if not found.
*/
indexOfSeries(series) {
return this._series.indexOf(series);
}
/**
* It sorts the series based on display sets order. Each series must be an instance
* of SeriesMetadata and each display sets must be an instance of ImageSet.
* Useful example of usage:
* Study data provided by backend does not sort series at all and client-side
* needs series sorted by the same criteria used for sorting display sets.
*/
sortSeriesByDisplaySets() {
// Object for mapping display sets' index by seriesInstanceUid
const displaySetsMapping = {};
// Loop through each display set to create the mapping
this.forEachDisplaySet((displaySet, index) => {
if (!(displaySet instanceof ImageSet)) {
throw new OHIFError(
`StudyMetadata::sortSeriesByDisplaySets display set at index ${index} is not an instance of ImageSet`
);
}
// In case of multiframe studies, just get the first index occurence
if (displaySetsMapping[displaySet.seriesInstanceUid] === void 0) {
displaySetsMapping[displaySet.seriesInstanceUid] = index;
}
});
// Clone of actual series
const actualSeries = this.getSeries();
actualSeries.forEach((series, index) => {
if (!(series instanceof SeriesMetadata)) {
throw new OHIFError(
`StudyMetadata::sortSeriesByDisplaySets series at index ${index} is not an instance of SeriesMetadata`
);
}
// Get the new series index
const seriesIndex = displaySetsMapping[series.getSeriesInstanceUID()];
// Update the series object with the new series position
this._series[seriesIndex] = series;
});
}
/**
* Compares the current study instance with another one.
* @param {StudyMetadata} study An instance of the StudyMetadata class.
* @returns {boolean} Returns true if both instances refer to the same study.
*/
equals(study) {
const self = this;
return (
study === self ||
(study instanceof StudyMetadata &&
study.getStudyInstanceUID() === self.getStudyInstanceUID())
);
}
/**
* Get the first series of the current study retaining a consistent result across multiple calls.
* @return {SeriesMetadata} An instance of the SeriesMetadata class or null if it does not exist.
*/
getFirstSeries() {
let series = this._firstSeries;
if (!(series instanceof SeriesMetadata)) {
series = null;
const found = this.getSeriesByIndex(0);
if (found instanceof SeriesMetadata) {
this._firstSeries = found;
series = found;
}
}
return series;
}
/**
* Get the first instance of the current study retaining a consistent result across multiple calls.
* @return {InstanceMetadata} An instance of the InstanceMetadata class or null if it does not exist.
*/
getFirstInstance() {
let instance = this._firstInstance;
if (!(instance instanceof InstanceMetadata)) {
instance = null;
const firstSeries = this.getFirstSeries();
if (firstSeries instanceof SeriesMetadata) {
const found = firstSeries.getFirstInstance();
if (found instanceof InstanceMetadata) {
this._firstInstance = found;
instance = found;
}
}
}
return instance;
}
/**
* Search the associated series to find an specific instance using the supplied callback as criteria.
* The callback is passed two arguments: instance (a InstanceMetadata instance) and index (the integer
* index of the instance within the current series)
* @param {function} callback The callback function which will be invoked for each instance instance.
* @returns {Object} Result object containing series (SeriesMetadata) and instance (InstanceMetadata)
* objects or an empty object if not found.
*/
findSeriesAndInstanceByInstance(callback) {
let result;
if (Metadata.isValidCallback(callback)) {
let instance;
const series = this._series.find(series => {
instance = series.findInstance(callback);
return instance instanceof InstanceMetadata;
});
// No series found
if (series instanceof SeriesMetadata) {
result = {
series,
instance,
};
}
}
return result || {};
}
/**
* Find series by instance using the supplied callback as criteria. The callback is passed
* two arguments: instance (a InstanceMetadata instance) and index (the integer index of
* the instance within its series)
* @param {function} callback The callback function which will be invoked for each instance.
* @returns {SeriesMetadata|undefined} If a series is found based on callback criteria it
* returns a SeriesMetadata. "undefined" is returned otherwise
*/
findSeriesByInstance(callback) {
const result = this.findSeriesAndInstanceByInstance(callback);
return result.series;
}
/**
* Find an instance using the supplied callback as criteria. The callback is passed
* two arguments: instance (a InstanceMetadata instance) and index (the integer index of
* the instance within its series)
* @param {function} callback The callback function which will be invoked for each instance.
* @returns {InstanceMetadata|undefined} If an instance is found based on callback criteria it
* returns a InstanceMetadata. "undefined" is returned otherwise
*/
findInstance(callback) {
const result = this.findSeriesAndInstanceByInstance(callback);
return result.instance;
}
}
/**
*
* @typedef StudyMetadata
* @property {function} getSeriesCount - returns the number of series in the study
* @property {function} forEachSeries - function that invokes callback with each series and index
* @property {function} getStudyInstanceUID - returns the study's instance UID
*
*/
/**
* @typedef SeriesMetadata
* @property {function} getSeriesInstanceUID - returns the series's instance UID
* @property {function} getData - ???
* @property {function} forEachInstance - ???
*/
const dwc = api.DICOMwebClient;
const isMultiFrame = instance => {
// NumberOfFrames (0028,0008)
return instance.getRawValue('x00280008') > 1;
};
const makeDisplaySet = (series, instances) => {
const instance = instances[0];
const imageSet = new ImageSet(instances);
const seriesData = series.getData();
// set appropriate attributes to image set...
imageSet.setAttributes({
displaySetInstanceUid: imageSet.uid, // create a local alias for the imageSet UID
seriesDate: seriesData.seriesDate,
seriesTime: seriesData.seriesTime,
seriesInstanceUid: series.getSeriesInstanceUID(),
seriesNumber: instance.getRawValue('x00200011'),
seriesDescription: instance.getRawValue('x0008103e'),
numImageFrames: instances.length,
frameRate: instance.getRawValue('x00181063'),
modality: instance.getRawValue('x00080060'),
isMultiFrame: isMultiFrame(instance),
});
// Sort the images in this series if needed
const shallSort = true; //!OHIF.utils.ObjectPath.get(Meteor, 'settings.public.ui.sortSeriesByIncomingOrder');
if (shallSort) {
imageSet.sortBy((a, b) => {
// Sort by InstanceNumber (0020,0013)
return (
(parseInt(a.getRawValue('x00200013', 0)) || 0) -
(parseInt(b.getRawValue('x00200013', 0)) || 0)
);
});
}
// Include the first image instance number (after sorted)
imageSet.setAttribute(
'instanceNumber',
imageSet.getImage(0).getRawValue('x00200013')
);
return imageSet;
};
const isSingleImageModality = modality => {
return modality === 'CR' || modality === 'MG' || modality === 'DX';
};
function getSopClassUids(series) {
const uniqueSopClassUidsInSeries = new Set();
series.forEachInstance(instance => {
const instanceSopClassUid = instance.getRawValue('x00080016');
uniqueSopClassUidsInSeries.add(instanceSopClassUid);
});
const sopClassUids = Array.from(uniqueSopClassUidsInSeries);
return sopClassUids;
}
/**
* @private
* @param {SeriesMetadata} series
* @param {StudyMetadata} study
* @param {string[]} sopClassUids
*/
function _getDisplaySetFromSopClassModule(
sopClassHandlerExtensions, // TODO: Update Usage
series,
study,
sopClassUids
) {
// TODO: For now only use the plugins if all instances have the same sopClassUid
if (sopClassUids.length !== 1) {
console.warn(
'getDisplaySetFromSopClassPlugin: More than one SOPClassUid in the same series is not yet supported.'
);
return;
}
const sopClassUid = sopClassUids[0];
const sopClassHandlerModules = sopClassHandlerExtensions.map(extension => {
return extension.module;
});
const handlersForSopClassUid = sopClassHandlerModules.filter(module => {
return module.sopClassUids.includes(sopClassUid);
});
// TODO: Sort by something, so we can determine which plugin to use
if (!handlersForSopClassUid || !handlersForSopClassUid.length) {
return;
}
const plugin = handlersForSopClassUid[0];
const headers = DICOMWeb.getAuthorizationHeader();
const dicomWebClient = new dwc({
url: study.getData().wadoRoot,
headers,
});
return plugin.getDisplaySetFromSeries(series, study, dicomWebClient, headers);
}
/**
*
* @param {*} a - DisplaySet
* @param {*} b - DisplaySet
*/
function _sortBySeriesNumber(a, b) {
const seriesNumberAIsGreaterOrUndefined =
a.seriesNumber > b.seriesNumber || (!a.seriesNumber && b.seriesNumber);
return seriesNumberAIsGreaterOrUndefined ? 1 : -1;
}

View File

@ -0,0 +1,73 @@
import { Metadata } from './Metadata';
import { DICOMTagDescriptions } from '../../utils/DICOMTagDescriptions';
/**
* Constants
*/
const STUDY_INSTANCE_UID = 'x0020000d';
/**
* Class Definition
*/
export class StudySummary extends Metadata {
constructor(tagMap, attributeMap, uid) {
// Call the superclass constructor passing an plain object with no prototype to be used as the main "_data" attribute.
const _data = Object.create(null);
super(_data, uid);
// Initialize internal tag map if first argument is given.
if (tagMap !== void 0) {
this.addTags(tagMap);
}
// Initialize internal property map if second argument is given.
if (attributeMap !== void 0) {
this.setCustomAttributes(attributeMap);
}
}
getStudyInstanceUID() {
// This method should return null if StudyInstanceUID is not available to keep compatibility StudyMetadata API
return this.getTagValue(STUDY_INSTANCE_UID) || null;
}
/**
* Append tags to internal tag map.
* @param {Object} tagMap An object whose own properties will be used as tag values and appended to internal tag map.
*/
addTags(tagMap) {
const _hasOwn = Object.prototype.hasOwnProperty;
const _data = this._data;
for (let tag in tagMap) {
if (_hasOwn.call(tagMap, tag)) {
const description = DICOMTagDescriptions.find(tag);
// When a description is available, use its tag as internal key...
if (description) {
_data[description.tag] = tagMap[tag];
} else {
_data[tag] = tagMap[tag];
}
}
}
}
tagExists(tagName) {
const _data = this._data;
const description = DICOMTagDescriptions.find(tagName);
if (description) {
return description.tag in _data;
}
return tagName in _data;
}
getTagValue(tagName) {
const _data = this._data;
const description = DICOMTagDescriptions.find(tagName);
if (description) {
return _data[description.tag];
}
return _data[tagName];
}
}

View File

@ -0,0 +1,48 @@
export class WadoRsMetaDataBuilder {
constructor() {
this.tags = {};
}
addTag(tag, value, multi) {
this.tags[tag] = {
tag,
value,
multi,
};
return this;
}
toJSON() {
const json = {};
const keys = Object.keys(this.tags);
keys.forEach(key => {
if (!this.tags.hasOwnProperty(key)) {
return;
}
const tag = this.tags[key];
const multi = !!tag.multi;
let value = tag.value;
if (value == null || (value.length === 1 && value[0] == null)) {
return;
}
if (typeof value === 'string' && multi) {
value = value.split('\\');
}
if (!Array.isArray(value)) {
value = [value];
}
json[key] = {
Value: value,
};
});
return json;
}
}

View File

@ -0,0 +1,35 @@
import { InstanceMetadata } from './InstanceMetadata';
import { Metadata } from './Metadata';
import { OHIFInstanceMetadata } from './OHIFInstanceMetadata';
import { OHIFSeriesMetadata } from './OHIFSeriesMetadata';
import { OHIFStudyMetadata } from './OHIFStudyMetadata';
import { SeriesMetadata } from './SeriesMetadata';
import { StudyMetadata } from './StudyMetadata';
import { StudySummary } from './StudySummary';
import { WadoRsMetaDataBuilder } from './WadoRsMetaDataBuilder';
const metadata = {
Metadata,
StudySummary,
WadoRsMetaDataBuilder,
StudyMetadata,
SeriesMetadata,
InstanceMetadata,
OHIFStudyMetadata,
OHIFSeriesMetadata,
OHIFInstanceMetadata,
};
export {
Metadata,
StudySummary,
WadoRsMetaDataBuilder,
StudyMetadata,
SeriesMetadata,
InstanceMetadata,
OHIFStudyMetadata,
OHIFSeriesMetadata,
OHIFInstanceMetadata,
};
export default metadata;

View File

@ -0,0 +1,458 @@
var dialogPolyfill = (function() {
var supportCustomEvent = window.CustomEvent;
if (!supportCustomEvent || typeof supportCustomEvent == 'object') {
supportCustomEvent = function CustomEvent(event, x) {
x = x || {};
var ev = document.createEvent('CustomEvent');
ev.initCustomEvent(event, !!x.bubbles, !!x.cancelable, x.detail || null);
return ev;
};
supportCustomEvent.prototype = window.Event.prototype;
}
/**
* Finds the nearest <dialog> from the passed element.
*
* @param {Element} el to search from
* @param {HTMLDialogElement} dialog found
*/
function findNearestDialog(el) {
while (el) {
if (el.nodeName == 'DIALOG') {
return el;
}
el = el.parentElement;
}
return null;
}
var dialogPolyfill = {};
dialogPolyfill.reposition = function(element) {
var scrollTop =
document.body.scrollTop || document.documentElement.scrollTop;
var topValue = scrollTop + (window.innerHeight - element.offsetHeight) / 2;
element.style.top = Math.max(0, topValue) + 'px';
element.dialogPolyfillInfo.isTopOverridden = true;
};
dialogPolyfill.inNodeList = function(nodeList, node) {
for (var i = 0; i < nodeList.length; ++i) {
if (nodeList[i] == node) return true;
}
return false;
};
dialogPolyfill.isInlinePositionSetByStylesheet = function(element) {
for (var i = 0; i < document.styleSheets.length; ++i) {
var styleSheet = document.styleSheets[i];
var cssRules = null;
// Some browsers throw on cssRules.
try {
cssRules = styleSheet.cssRules;
} catch (e) {}
if (!cssRules) continue;
for (var j = 0; j < cssRules.length; ++j) {
var rule = cssRules[j];
var selectedNodes = null;
// Ignore errors on invalid selector texts.
try {
selectedNodes = document.querySelectorAll(rule.selectorText);
} catch (e) {}
if (
!selectedNodes ||
!dialogPolyfill.inNodeList(selectedNodes, element)
)
continue;
var cssTop = rule.style.getPropertyValue('top');
var cssBottom = rule.style.getPropertyValue('bottom');
if ((cssTop && cssTop != 'auto') || (cssBottom && cssBottom != 'auto'))
return true;
}
}
return false;
};
dialogPolyfill.needsCentering = function(dialog) {
var computedStyle = window.getComputedStyle(dialog);
if (computedStyle.position != 'absolute') {
return false;
}
// We must determine whether the top/bottom specified value is non-auto. In
// WebKit/Blink, checking computedStyle.top == 'auto' is sufficient, but
// Firefox returns the used value. So we do this crazy thing instead: check
// the inline style and then go through CSS rules.
if (
(dialog.style.top != 'auto' && dialog.style.top != '') ||
(dialog.style.bottom != 'auto' && dialog.style.bottom != '')
)
return false;
return !dialogPolyfill.isInlinePositionSetByStylesheet(dialog);
};
dialogPolyfill.showDialog = function(isModal) {
if (this.open) {
throw 'InvalidStateError: showDialog called on open dialog';
}
this.open = true; // TODO: should be a getter mapped to attribute
this.setAttribute('open', 'open');
if (isModal) {
// Find element with `autofocus` attribute or first form control
var first_form_ctrl = null;
var autofocus = null;
var findElementToFocus = function(root) {
if (!root.children) {
return;
}
for (var i = 0; i < root.children.length; i++) {
var elem = root.children[i];
if (
first_form_ctrl === null &&
!elem.disabled &&
(elem.nodeName == 'BUTTON' ||
elem.nodeName == 'INPUT' ||
elem.nodeName == 'KEYGEN' ||
elem.nodeName == 'SELECT' ||
elem.nodeName == 'TEXTAREA')
) {
first_form_ctrl = elem;
}
if (elem.autofocus) {
autofocus = elem;
return;
}
findElementToFocus(elem);
if (autofocus !== null) return;
}
};
findElementToFocus(this);
if (autofocus !== null) {
autofocus.focus();
} else if (first_form_ctrl !== null) {
first_form_ctrl.focus();
}
}
if (dialogPolyfill.needsCentering(this)) dialogPolyfill.reposition(this);
if (isModal) {
this.dialogPolyfillInfo.modal = true;
dialogPolyfill.dm.pushDialog(this);
}
// IE sometimes complains when calling .focus() that it
// "Can't move focus to the control because it is invisible, not enabled, or of a type that does not accept the focus."
try {
if (autofocus !== null) {
autofocus.focus();
} else if (first_form_ctrl !== null) {
first_form_ctrl.focus();
}
} catch (e) {}
this.style.zoom = 1;
};
dialogPolyfill.close = function(retval) {
if (!this.open && !window.HTMLDialogElement) {
// Native implementations will set .open to false, so ignore this error.
throw 'InvalidStateError: close called on closed dialog';
}
this.open = false;
this.removeAttribute('open');
// Leave returnValue untouched in case it was set directly on the element
if (typeof retval != 'undefined') {
this.returnValue = retval;
}
// This won't match the native <dialog> exactly because if the user sets top
// on a centered polyfill dialog, that top gets thrown away when the dialog is
// closed. Not sure it's possible to polyfill this perfectly.
if (this.dialogPolyfillInfo.isTopOverridden) {
this.style.top = 'auto';
}
if (this.dialogPolyfillInfo.modal) {
dialogPolyfill.dm.removeDialog(this);
}
// Triggering "close" event for any attached listeners on the <dialog>
var event;
if (document.createEvent) {
event = document.createEvent('HTMLEvents');
event.initEvent('close', true, true);
} else {
event = new Event('close');
}
this.dispatchEvent(event);
return this.returnValue;
};
dialogPolyfill.registerDialog = function(element) {
if (element.show) {
// console.warn("This browser already supports <dialog>, the polyfill " +
// "may not work correctly.");
}
element.show = dialogPolyfill.showDialog.bind(element, false);
element.showModal = dialogPolyfill.showDialog.bind(element, true);
element.close = dialogPolyfill.close.bind(element);
element.dialogPolyfillInfo = {};
element.open = false;
};
// The overlay is used to simulate how a modal dialog blocks the document. The
// blocking dialog is positioned on top of the overlay, and the rest of the
// dialogs on the pending dialog stack are positioned below it. In the actual
// implementation, the modal dialog stacking is controlled by the top layer,
// where z-index has no effect.
var TOP_LAYER_ZINDEX = 100000;
var MAX_PENDING_DIALOGS = 100000;
dialogPolyfill.DialogManager = function() {
this.pendingDialogStack = [];
this.overlay = document.createElement('div');
this.overlay.style.width = '100%';
this.overlay.style.height = '100%';
this.overlay.style.position = 'fixed';
this.overlay.style.left = '0px';
this.overlay.style.top = '0px';
this.overlay.style.backgroundColor = 'rgba(0,0,0,0.0)';
this.focusPageLast = this.createFocusable();
this.overlay.appendChild(this.focusPageLast);
this.overlay.addEventListener('click', function(e) {
var redirectedEvent = document.createEvent('MouseEvents');
redirectedEvent.initMouseEvent(
e.type,
e.bubbles,
e.cancelable,
window,
e.detail,
e.screenX,
e.screenY,
e.clientX,
e.clientY,
e.ctrlKey,
e.altKey,
e.shiftKey,
e.metaKey,
e.button,
e.relatedTarget
);
document.body.dispatchEvent(redirectedEvent);
});
// TODO: Only install when any dialogs are open.
document.addEventListener(
'submit',
function(ev) {
var method = ev.target.getAttribute('method');
method = method ? method.toLowerCase() : '';
if (method != 'dialog') {
return;
}
ev.preventDefault();
var dialog = findNearestDialog(ev.target);
if (!dialog) {
return;
}
// FIXME: The original event doesn't contain the INPUT element used to
// submit the form (if any). Look in some possible places.
var returnValue;
var cands = [document.activeElement, ev.explicitOriginalTarget];
cands.some(function(cand) {
if (cand && cand.nodeName == 'INPUT' && cand.form == ev.target) {
returnValue = cand.value;
return true;
}
});
dialog.close(returnValue);
},
true
);
};
dialogPolyfill.DialogManager.prototype.createFocusable = function(tabIndex) {
var span = document.createElement('span');
span.tabIndex = tabIndex || 0;
span.style.opacity = 0;
span.style.position = 'static';
return span;
};
dialogPolyfill.DialogManager.prototype.blockDocument = function() {
if (!document.body.contains(this.overlay)) {
document.body.appendChild(this.overlay);
// On Safari/Mac (and possibly other browsers), the documentElement is
// not focusable. This is required for modal dialogs as it is the first
// element to be hit by a tab event, and further tabs are redirected to
// the most visible dialog.
if (this.needsDocumentElementFocus === undefined) {
document.documentElement.focus();
this.needsDocumentElementFocus =
document.activeElement != document.documentElement;
}
if (this.needsDocumentElementFocus) {
document.documentElement.tabIndex = 1;
}
}
};
dialogPolyfill.DialogManager.prototype.unblockDocument = function() {
document.body.removeChild(this.overlay);
if (this.needsDocumentElementFocus) {
// TODO: Restore the previous tabIndex, rather than clearing it.
document.documentElement.tabIndex = '';
}
};
dialogPolyfill.DialogManager.prototype.updateStacking = function() {
if (this.pendingDialogStack.length == 0) {
this.unblockDocument();
return;
}
this.blockDocument();
var zIndex = TOP_LAYER_ZINDEX;
for (var i = 0; i < this.pendingDialogStack.length; i++) {
if (i == this.pendingDialogStack.length - 1)
this.overlay.style.zIndex = zIndex++;
var dialog = this.pendingDialogStack[i];
dialog.dialogPolyfillInfo.backdrop.style.zIndex = zIndex++;
dialog.style.zIndex = zIndex++;
}
};
dialogPolyfill.DialogManager.prototype.handleKey = function(event) {
var dialogCount = this.pendingDialogStack.length;
if (dialogCount == 0) {
return;
}
var dialog = this.pendingDialogStack[dialogCount - 1];
var pfi = dialog.dialogPolyfillInfo;
switch (event.keyCode) {
case 9 /* tab */:
var activeElement = document.activeElement;
var forward = !event.shiftKey;
if (forward) {
// Tab forward, so look for document or fake last focus element.
if (
activeElement == document.documentElement ||
activeElement == document.body ||
activeElement == pfi.backdrop
) {
pfi.focusFirst.focus();
} else if (activeElement == pfi.focusLast) {
// TODO: Instead of wrapping to focusFirst, escape to browser chrome.
pfi.focusFirst.focus();
}
} else {
// Tab backwards, so look for fake first focus element.
if (activeElement == pfi.focusFirst) {
// TODO: Instead of wrapping to focusLast, escape to browser chrome.
pfi.focusLast.focus();
} else if (activeElement == this.focusPageLast) {
// The focus element is at the end of the page (e.g., shift-tab from
// the window chrome): move current focus to the last element in the
// dialog instead.
pfi.focusLast.focus();
}
}
break;
case 27 /* esc */:
event.preventDefault();
event.stopPropagation();
var cancelEvent = new supportCustomEvent('cancel', {
bubbles: false,
cancelable: true,
});
if (dialog.dispatchEvent(cancelEvent)) {
dialog.close();
}
break;
}
};
dialogPolyfill.DialogManager.prototype.pushDialog = function(dialog) {
if (this.pendingDialogStack.length >= MAX_PENDING_DIALOGS) {
throw 'Too many modal dialogs';
}
var backdrop = document.createElement('div');
backdrop.className = 'backdrop';
var clickEventListener = function(e) {
var redirectedEvent = document.createEvent('MouseEvents');
redirectedEvent.initMouseEvent(
e.type,
e.bubbles,
e.cancelable,
window,
e.detail,
e.screenX,
e.screenY,
e.clientX,
e.clientY,
e.ctrlKey,
e.altKey,
e.shiftKey,
e.metaKey,
e.button,
e.relatedTarget
);
dialog.dispatchEvent(redirectedEvent);
};
backdrop.addEventListener('click', clickEventListener);
dialog.parentNode.insertBefore(backdrop, dialog.nextSibling);
dialog.dialogPolyfillInfo.backdrop = backdrop;
dialog.dialogPolyfillInfo.clickEventListener = clickEventListener;
this.pendingDialogStack.push(dialog);
this.updateStacking();
dialog.dialogPolyfillInfo.focusFirst = this.createFocusable();
dialog.dialogPolyfillInfo.focusLast = this.createFocusable();
dialog.appendChild(dialog.dialogPolyfillInfo.focusLast);
dialog.insertBefore(
dialog.dialogPolyfillInfo.focusFirst,
dialog.firstChild
);
};
dialogPolyfill.DialogManager.prototype.removeDialog = function(dialog) {
var index = this.pendingDialogStack.indexOf(dialog);
if (index == -1) {
return;
}
this.pendingDialogStack.splice(index, 1);
var backdrop = dialog.dialogPolyfillInfo.backdrop;
var clickEventListener = dialog.dialogPolyfillInfo.clickEventListener;
backdrop.removeEventListener('click', clickEventListener);
backdrop.parentNode.removeChild(backdrop);
dialog.dialogPolyfillInfo.backdrop = null;
dialog.dialogPolyfillInfo.clickEventListener = null;
this.updateStacking();
dialog.removeChild(dialog.dialogPolyfillInfo.focusFirst);
dialog.removeChild(dialog.dialogPolyfillInfo.focusLast);
dialog.dialogPolyfillInfo.focusFirst = null;
dialog.dialogPolyfillInfo.focusLast = null;
};
dialogPolyfill.dm = new dialogPolyfill.DialogManager();
document.addEventListener(
'keydown',
dialogPolyfill.dm.handleKey.bind(dialogPolyfill.dm)
);
return dialogPolyfill;
})();

View File

@ -0,0 +1,34 @@
dialog
position: absolute
left: 0
right: 0
width: -moz-fit-content
width: -webkit-fit-content
width: fit-content
height: -moz-fit-content
height: -webkit-fit-content
height: fit-content
margin: auto
border: solid
padding: 1em
background: white
color: black
display: none
dialog[open]
display: block
dialog + .backdrop
position: fixed
top: 0
right: 0
bottom: 0
left: 0
background: rgba(0,0,0,0.1)
/* for small devices, modal dialogs go full-screen */
@media screen and (max-width: 540px)
dialog[_polyfill_modal]
top: 0
width: auto
margin: 1em

View File

@ -0,0 +1 @@
import './styleProperty.js';

View File

@ -0,0 +1,66 @@
/*
* https://github.com/swederik/dragula/blob/ccc15d75186f5168e7abadbe3077cf12dab09f8b/styleProperty.js
*/
(function() {
'use strict';
const browserProps = {};
function eachVendor(prop, fn) {
const prefixes = ['Webkit', 'Moz', 'ms', 'O'];
fn(prop);
for (let i = 0; i < prefixes.length; i++) {
fn(prefixes[i] + prop.charAt(0).toUpperCase() + prop.slice(1));
}
}
function check(property, testValue) {
const sandbox = document.createElement('iframe');
const element = document.createElement('p');
document.body.appendChild(sandbox);
sandbox.contentDocument.body.appendChild(element);
const support = set(element, property, testValue);
// We have to do this because remove() is not supported by IE11 and below
sandbox.parentElement.removeChild(sandbox);
return support;
}
function checkComputed(el, prop) {
const computed = window.getComputedStyle(el).getPropertyValue(prop);
return computed !== void 0 && computed.length > 0 && computed !== 'none';
}
function set(el, prop, value) {
let match = false;
if (browserProps[prop] === void 0) {
eachVendor(prop, function(vendorProp) {
if (el.style[vendorProp] !== void 0 && match === false) {
el.style[vendorProp] = value;
if (checkComputed(el, vendorProp)) {
match = true;
browserProps[prop] = vendorProp;
}
}
});
} else {
el.style[browserProps[prop]] = value;
return true;
}
return match;
}
const styleProperty = {
check,
set,
};
OHIF.ui.styleProperty = styleProperty;
})();
const { styleProperty } = OHIF.ui;
export { styleProperty };

View File

@ -0,0 +1,150 @@
/*!
* transition-to-from-auto 0.5.2
* https://github.com/75lb/transition-to-from-auto
* Copyright 2015 Lloyd Brookes <75pound@gmail.com>
*/
/**
@module
@alias transition
*/
(function(window, document) {
'use strict';
var getComputedStyle = window.getComputedStyle;
var isTransition = 'data-ttfaInTransition';
var elements = [];
var data = [];
// Transition detecting
var transitionProp = false;
var transitionEnd = false;
var testStyle = document.createElement('a').style;
var testProp;
if (testStyle[(testProp = 'webkitTransition')] !== undefined) {
transitionProp = testProp;
transitionEnd = testProp + 'End';
}
if (testStyle[(testProp = 'transition')] !== undefined) {
transitionProp = testProp;
transitionEnd = testProp + 'end';
}
function process(options, data) {
var el = options.element;
var val = options.val;
var prop = options.prop;
var style = el.style;
var startVal;
var autoVal;
if (!transitionProp) {
return (style[prop] = val);
}
if (el.hasAttribute(isTransition)) {
el.removeEventListener(transitionEnd, data.l);
} else {
style[transitionProp] = 'none';
startVal = getComputedStyle(el)[prop];
style[prop] = 'auto';
autoVal = getComputedStyle(el)[prop];
// Interrupt
if (startVal === val || (val === 'auto' && startVal === autoVal)) {
return;
}
data.auto = autoVal;
el.setAttribute(isTransition, 1);
// Transition
style[prop] = startVal;
el.offsetWidth;
style[transitionProp] = options.style;
}
style[prop] = val === 'auto' ? data.auto : val;
data.l = function(e) {
if (e.propertyName === prop) {
el.removeAttribute(isTransition);
el.removeEventListener(transitionEnd, data.l);
if (val === 'auto') {
/* avoid transition flashes in Safari */
style[transitionProp] = 'none';
style[prop] = val;
}
}
};
el.addEventListener(transitionEnd, data.l);
}
/**
@param options {Object}
@param options.element {string | element} - The DOM element or selector to transition
@param options.val {string} - The value you want to transition to
@param [options.prop] {string} - The CSS property to transition, defaults to `"height"`
@param [options.style] {string} - The desired value for the `transition` CSS property (e.g. `"height 1s"`). If specified, this value is added inline and will override your CSS. Leave this value blank if you already have it defined in your stylesheet.
@alias module:transition-to-from-auto
*/
function transition(options) {
var element = options.element;
var datum;
var index;
if (typeof element === 'string') {
element = document.querySelector(element);
}
element = options.element = element instanceof Node ? element : false;
options.prop = options.prop || 'height';
options.style = options.style || '';
if (element) {
index = elements.indexOf(element);
if (~index) {
datum = data[index];
} else {
datum = {};
elements.push(element);
data.push(datum);
}
process(options, datum);
}
}
/**
The name of the vendor-specific transition CSS property
@type {string}
@example
el.style[transition.prop + 'Duration'] = '1s';
*/
transition.prop = transitionProp;
/**
* The name of the [transition end event](https://developer.mozilla.org/en-US/docs/Web/Events/transitionend) in the current browser (typically `"transitionend"` or `"webkitTransitionEnd"`)
* @type {string}
* @example
* el.addEventListener(transition.end, function(){
* // the transition ended..
* });
*/
transition.end = transitionEnd;
if (typeof module === 'object' && module.exports) {
module.exports = transition;
} else if (typeof define === 'function' && define.amd) {
define(function() {
return transition;
});
} else {
window.transition = transition;
}
})(window, document);

View File

@ -0,0 +1,15 @@
import MetadataProvider from './classes/MetadataProvider';
import {
getBoundingBox,
pixelToPage,
repositionTextBox,
} from './lib/cornerstone.js';
const cornerstone = {
MetadataProvider,
getBoundingBox,
pixelToPage,
repositionTextBox,
};
export default cornerstone;

View File

@ -0,0 +1,176 @@
import MODULE_TYPES from './MODULE_TYPES.js';
import log from './../log.js';
export default class ExtensionManager {
constructor({ commandsManager }) {
this.modules = {};
this.registeredExtensionIds = [];
this.moduleTypeNames = Object.values(MODULE_TYPES);
//
this._commandsManager = commandsManager;
this.moduleTypeNames.forEach(moduleType => {
this.modules[moduleType] = [];
});
}
/**
* An array of extensions, or an array of arrays that contains extension
* configuration pairs.
*
* @param {Object[]} extensions - Array of extensions
*/
registerExtensions(extensions) {
extensions.forEach(extension => {
const hasConfiguration = Array.isArray(extension);
if (hasConfiguration) {
const [ohifExtension, configuration] = extensions;
this.registerExtension(ohifExtension, configuration);
} else {
this.registerExtension(extension);
}
});
}
/**
*
* TODO: Id Management: SopClassHandlers currently refer to viewport module by id; setting the extension id as viewport module id is a workaround for now
* @param {Object} extension
* @param {Object} configuration
*/
registerExtension(extension, configuration = {}) {
if (!extension) {
log.warn(
'Attempting to register a null/undefined extension. Exiting early.'
);
return;
}
let extensionId = extension.id;
if (!extensionId) {
extensionId = Math.random()
.toString(36)
.substr(2, 5);
log.warn(`Extension ID not set. Using random string ID: ${extensionId}`);
}
if (this.registeredExtensionIds.includes(extensionId)) {
log.warn(
`Extension ID ${extensionId} has already been registered. Exiting before duplicating modules.`
);
return;
}
// preRegistrationHook
if (extension.preRegistration) {
extension.preRegistration(configuration);
}
// Register Modules
this.moduleTypeNames.forEach(moduleType => {
const extensionModule = this._getExtensionModule(
moduleType,
extension,
extensionId
);
if (extensionModule) {
this._initSpecialModuleTypes(moduleType, extensionModule);
this.modules[moduleType].push({
extensionId,
module: extensionModule,
});
}
});
// Track extension registration
this.registeredExtensionIds.push(extensionId);
}
/**
* @private
* @param {string} moduleType
* @param {Object} extension
* @param {string} extensionId - Used for logging warnings
*/
_getExtensionModule(moduleType, extension, extensionId) {
const getModuleFnName = 'get' + _capitalizeFirstCharacter(moduleType);
const getModuleFn = extension[getModuleFnName];
if (!getModuleFn) {
return;
}
try {
const extensionModule = getModuleFn();
if (!extensionModule) {
log.warn(
`Null or undefined returned when registering the ${getModuleFnName} module for the ${extensionId} extension`
);
}
return extensionModule;
} catch (ex) {
log.error(
`Exception thrown while trying to call ${getModuleFnName} for the ${extensionId} extension`
);
}
}
_initSpecialModuleTypes(moduleType, extensionModule) {
switch (moduleType) {
case 'commandsModule': {
const { definitions, defaultContext } = extensionModule;
if (!definitions || Object.keys(definitions).length === 0) {
log.warn('Commands Module contains no command definitions');
return;
}
this._initCommandsModule(definitions, defaultContext);
break;
}
default:
// code block
}
}
/**
*
* @private
* @param {Object[]} commandDefinitions
*/
_initCommandsModule(commandDefinitions, defaultContext = 'VIEWER') {
if (!this._commandsManager.getContext(defaultContext)) {
this._commandsManager.createContext(defaultContext);
}
Object.keys(commandDefinitions).forEach(commandName => {
const commandDefinition = commandDefinitions[commandName];
const commandHasContextThatDoesNotExist =
commandDefinition.context &&
!this._commandsManager.getContext(commandDefinition.context);
if (commandHasContextThatDoesNotExist) {
this._commandsManager.createContext(commandDefinition.context);
}
this._commandsManager.registerCommand(
commandDefinition.context || defaultContext,
commandName,
commandDefinition
);
});
}
}
/**
* @private
* @param {string} lower
*/
function _capitalizeFirstCharacter(lower) {
return lower.charAt(0).toUpperCase() + lower.substr(1);
}

View File

@ -0,0 +1,182 @@
import { Exception } from 'handlebars';
import ExtensionManager from './ExtensionManager.js';
import MODULE_TYPES from './MODULE_TYPES.js';
import log from './../log.js';
jest.mock('./../log.js');
describe('ExtensionManager.js', () => {
let extensionManager, commandsManager;
beforeEach(() => {
commandsManager = {
createContext: jest.fn(),
getContext: jest.fn(),
registerCommand: jest.fn(),
};
extensionManager = new ExtensionManager({ commandsManager });
log.warn.mockClear();
jest.clearAllMocks();
});
it('creates a module namespace for each module type', () => {
const moduleKeys = Object.keys(extensionManager.modules);
const moduleTypeValues = Object.values(MODULE_TYPES);
expect(moduleKeys.sort()).toEqual(moduleTypeValues.sort());
});
describe('registerExtensions()', () => {
it('calls registerExtension() for each extension', () => {
extensionManager.registerExtension = jest.fn();
// SUT
const fakeExtensions = [{ one: '1' }, { two: '2' }, { three: '3 ' }];
extensionManager.registerExtensions(fakeExtensions);
// Assert
expect(extensionManager.registerExtension.mock.calls.length).toBe(3);
});
});
describe('registerExtension()', () => {
it('logs a warning if the extension is null or undefined', () => {
const undefinedExtension = undefined;
const nullExtension = null;
extensionManager.registerExtension(undefinedExtension);
extensionManager.registerExtension(nullExtension);
expect(log.warn.mock.calls.length).toBe(2);
});
it('logs a warning if the extension does not have an id', () => {
const extensionWithoutId = {};
extensionManager.registerExtension(extensionWithoutId);
expect(log.warn.mock.calls.length).toBe(1);
});
it('tracks which extensions have been registered', () => {
const extension = {
id: 'hello-world',
};
extensionManager.registerExtension(extension);
expect(extensionManager.registeredExtensionIds).toContain(extension.id);
});
it('logs a warning if the extension has an id that has already been registered', () => {
const extension = { id: 'hello-world' };
extensionManager.registerExtension(extension);
// SUT
extensionManager.registerExtension(extension);
expect(log.warn.mock.calls.length).toBe(1);
});
it('logs a warning if a defined module returns null or undefined', () => {
const extensionWithBadModule = {
id: 'hello-world',
getViewportModule: () => {
return null;
},
};
extensionManager.registerExtension(extensionWithBadModule);
expect(log.warn.mock.calls.length).toBe(1);
expect(log.warn.mock.calls[0][0]).toContain(
'Null or undefined returned when registering'
);
});
it('logs an error if an exception is thrown while retrieving a module', () => {
const extensionWithBadModule = {
id: 'hello-world',
getViewportModule: () => {
throw new Exception('Hello World');
},
};
extensionManager.registerExtension(extensionWithBadModule);
expect(log.error.mock.calls.length).toBe(1);
expect(log.error.mock.calls[0][0]).toContain(
'Exception thrown while trying to call'
);
});
it('successfully registers a module for each module type', () => {
const extension = {
id: 'hello-world',
getViewportModule: () => {
return {};
},
getSopClassHandlerModule: () => {
return {};
},
getPanelModule: () => {
return {};
},
getToolbarModule: () => {
return {};
},
getCommandsModule: () => {
return {};
},
};
extensionManager.registerExtension(extension);
// Registers 1 module per module type
Object.keys(extensionManager.modules).forEach(moduleType => {
const modulesForType = extensionManager.modules[moduleType];
expect(modulesForType.length).toBe(1);
});
});
it('calls commandsManager.registerCommand for each commandsModule command definition', () => {
const extension = {
id: 'hello-world',
getCommandsModule: () => {
return {
definitions: {
exampleDefinition: {
commandFn: () => {},
storeContexts: [],
options: {},
},
},
};
},
};
// SUT
extensionManager.registerExtension(extension);
expect(commandsManager.registerCommand.mock.calls.length).toBe(1);
});
it('logs a warning if the commandsModule contains no command definitions', () => {
const extension = {
id: 'hello-world',
getCommandsModule: () => {
return {};
},
};
// SUT
extensionManager.registerExtension(extension);
expect(log.warn.mock.calls.length).toBe(1);
expect(log.warn.mock.calls[0][0]).toContain(
'Commands Module contains no command definitions'
);
});
});
});

View File

@ -0,0 +1,7 @@
export default {
COMMANDS: 'commandsModule',
PANEL: 'panelModule',
SOP_CLASS_HANDLER: 'sopClassHandlerModule',
TOOLBAR: 'toolbarModule',
VIEWPORT: 'viewportModule',
};

View File

@ -0,0 +1,9 @@
import ExtensionManager from './ExtensionManager';
import MODULE_TYPES from './MODULE_TYPES.js';
export default {
ExtensionManager,
MODULE_TYPES,
};
export { ExtensionManager, MODULE_TYPES };

View File

@ -0,0 +1,120 @@
import OHIFError from '../classes/OHIFError.js';
import metadata from '../classes/metadata/';
import { validate } from './lib/validate.js';
import { CustomAttributeRetrievalCallbacks } from './customAttributes';
/**
* Import Constants
*/
const { StudySummary, InstanceMetadata } = metadata;
/**
* Match a Metadata instance against rules using Validate.js for validation.
* @param {StudySummary|InstanceMetadata} metadataInstance Metadata instance object
* @param {Array} rules Array of MatchingRules instances (StudyMatchingRule|SeriesMatchingRule|ImageMatchingRule) for the match
* @return {Object} Matching Object with score and details (which rule passed or failed)
*/
const match = (metadataInstance, rules) => {
// Make sure the supplied data is valid.
if (
!(
metadataInstance instanceof StudySummary ||
metadataInstance instanceof InstanceMetadata
)
) {
throw new OHIFError(
'HPMatcher::match metadataInstance must be an instance of StudySummary or InstanceMetadata'
);
}
const options = {
format: 'grouped',
};
const details = {
passed: [],
failed: [],
};
let requiredFailed = false;
let score = 0;
rules.forEach(rule => {
const attribute = rule.attribute;
// Do not use the custom attribute from the metadataInstance since it is subject to change
if (CustomAttributeRetrievalCallbacks.hasOwnProperty(attribute)) {
const customAttribute = CustomAttributeRetrievalCallbacks[attribute];
metadataInstance.setCustomAttribute(
attribute,
customAttribute.callback(metadataInstance)
);
}
// Format the constraint as required by Validate.js
const testConstraint = {
[attribute]: rule.constraint,
};
// Create a single attribute object to be validated, since metadataInstance is an
// instance of Metadata (StudyMetadata, SeriesMetadata or InstanceMetadata)
const attributeValue = metadataInstance.customAttributeExists(attribute)
? metadataInstance.getCustomAttribute(attribute)
: metadataInstance.getTagValue(attribute);
const attributeMap = {
[attribute]: attributeValue,
};
// Use Validate.js to evaluate the constraints on the specified metadataInstance
let errorMessages;
try {
errorMessages = validate(attributeMap, testConstraint, [options]);
} catch (e) {
errorMessages = ['Something went wrong during validation.', e];
}
if (!errorMessages) {
// If no errorMessages were returned, then validation passed.
// Add the rule's weight to the total score
score += parseInt(rule.weight, 10);
// Log that this rule passed in the matching details object
details.passed.push({
rule,
});
} else {
// If errorMessages were present, then validation failed
// If the rule that failed validation was Required, then
// mark that a required Rule has failed
if (rule.required) {
requiredFailed = true;
}
// Log that this rule failed in the matching details object
// and include any error messages
details.failed.push({
rule,
errorMessages,
});
}
});
// If a required Rule has failed Validation, set the matching score to zero
if (requiredFailed) {
score = 0;
}
return {
score,
details,
requiredFailed,
};
};
const HPMatcher = {
match,
};
export { HPMatcher };

View File

@ -0,0 +1,824 @@
import OHIFError from '../classes/OHIFError.js';
import metadata from '../classes/metadata/';
import { StudyMetadataSource } from '../classes/StudyMetadataSource.js';
import { isImage } from '../utils/isImage.js';
import { HPMatcher } from './HPMatcher.js';
import { sortByScore } from './lib/sortByScore';
import log from '../log.js';
import sortBy from '../utils/sortBy.js';
import { CustomViewportSettings } from './customViewportSettings';
import Protocol from './classes/Protocol';
import { ProtocolStore } from './protocolStore/classes';
/**
* Import Constants
*/
const { StudyMetadata, InstanceMetadata, StudySummary } = metadata;
// Useful constants
const ABSTRACT_PRIOR_VALUE = 'abstractPriorValue';
export default class ProtocolEngine {
matchedProtocols = new Map();
matchedProtocolScores = {};
/**
* Constructor
* @param {ProtocolStore} protocolStore Protocol Store used to keep track of all hanging protocols
* @param {Array} studies Array of study metadata
* @param {Map} priorStudies Map of prior studies
* @param {Object} studyMetadataSource Instance of StudyMetadataSource (ohif-viewerbase) Object to get study metadata
* @param {Object} options
*/
constructor(
protocolStore,
studies,
priorStudies,
studyMetadataSource,
options = {}
) {
// -----------
// Type Validations
if (!(studyMetadataSource instanceof StudyMetadataSource)) {
throw new OHIFError(
'ProtocolEngine::constructor studyMetadataSource is not an instance of StudyMetadataSource'
);
}
if (
!(studies instanceof Array) &&
!studies.every(study => study instanceof StudyMetadata)
) {
throw new OHIFError(
"ProtocolEngine::constructor studies is not an array or it's items are not instances of StudyMetadata"
);
}
// --------------
// Initialization
this.protocolStore = protocolStore;
this.studies = studies;
this.priorStudies = priorStudies instanceof Map ? priorStudies : new Map();
this.studyMetadataSource = studyMetadataSource;
this.options = options;
// Put protocol engine in a known state
this.reset();
// Create an array for new stage ids to be stored
// while editing a stage
this.newStageIds = [];
}
/**
* Resets the ProtocolEngine to the best match
*/
reset() {
const protocol = this.getBestProtocolMatch();
this.setHangingProtocol(protocol);
}
/**
* Retrieves the current Stage from the current Protocol and stage index
*
* @returns {*} The Stage model for the currently displayed Stage
*/
getCurrentStageModel() {
return this.protocol.stages[this.stage];
}
/**
* Finds the best protocols from Protocol Store, matching each protocol matching rules
* with the given study. The best protocol are orded by score and returned in an array
* @param {Object} study StudyMetadata instance object
* @return {Array} Array of match objects or an empty array if no match was found
* Each match object has the score of the matching and the matched
* protocol
*/
findMatchByStudy(study) {
log.trace('ProtocolEngine::findMatchByStudy');
const matched = [];
const studyInstance = study.getFirstInstance();
// Set custom attribute for study metadata
const numberOfAvailablePriors = this.getNumberOfAvailablePriors(
study.getObjectID()
);
this.protocolStore.getProtocol().forEach(protocol => {
// Clone the protocol's protocolMatchingRules array
// We clone it so that we don't accidentally add the
// numberOfPriorsReferenced rule to the Protocol itself.
let rules = protocol.protocolMatchingRules.slice();
if (!rules) {
return;
}
// Check if the study has the minimun number of priors used by the protocol.
const numberOfPriorsReferenced = protocol.getNumberOfPriorsReferenced();
if (numberOfPriorsReferenced > numberOfAvailablePriors) {
return;
}
// Run the matcher and get matching details
const matchedDetails = HPMatcher.match(studyInstance, rules);
const score = matchedDetails.score;
// The protocol matched some rule, add it to the matched list
if (score > 0) {
matched.push({
score,
protocol,
});
}
});
// If no matches were found, select the default protocol
if (!matched.length) {
const defaultProtocol = this.protocolStore.getProtocol('defaultProtocol');
return [
{
score: 1,
protocol: defaultProtocol,
},
];
}
// Sort the matched list by score
sortByScore(matched);
log.trace('ProtocolEngine::findMatchByStudy matched', matched);
return matched;
}
_clearMatchedProtocols() {
this.matchedProtocols.clear();
this.matchedProtocolScores = {};
}
/**
* Populates the MatchedProtocols Collection by running the matching procedure
*/
updateProtocolMatches() {
log.trace('ProtocolEngine::updateProtocolMatches');
// Clear all data currently in matchedProtocols
this._clearMatchedProtocols();
// For each study, find the matching protocols
this.studies.forEach(study => {
const matched = this.findMatchByStudy(study);
// For each matched protocol, check if it is already in MatchedProtocols
matched.forEach(matchedDetail => {
const protocol = matchedDetail.protocol;
if (!protocol) {
return;
}
// If it is not already in the MatchedProtocols Collection, insert it with its score
if (!this.matchedProtocols.has(protocol.id)) {
log.trace(
'ProtocolEngine::updateProtocolMatches inserting protocol match',
matchedDetail
);
this.matchedProtocols.set(protocol.id, protocol);
this.matchedProtocolScores[protocol.id] = matchedDetail.score;
}
});
});
}
_largestKeyByValue(obj) {
return Object.keys(obj).reduce((a, b) => (obj[a] > obj[b] ? a : b));
}
_getHighestScoringProtocol() {
if (!Object.keys(this.matchedProtocolScores).length) {
return this.protocolStore.getProtocol('defaultProtocol');
}
const highestScoringProtocolId = this._largestKeyByValue(
this.matchedProtocolScores
);
return this.matchedProtocols.get(highestScoringProtocolId);
}
/**
* Return the best matched Protocol to the current study or set of studies
* @returns {*}
*/
getBestProtocolMatch() {
// Run the matching to populate matchedProtocols Set and Map
this.updateProtocolMatches();
// Retrieve the highest scoring Protocol
const bestMatch = this._getHighestScoringProtocol();
log.trace('ProtocolEngine::getBestProtocolMatch bestMatch', bestMatch);
return bestMatch;
}
/**
* Get the number of prior studies supplied in the priorStudies map property.
*
* @param {String} studyObjectID The study object ID of the study whose priors are needed
* @returns {number} The number of available prior studies with the same PatientID
*/
getNumberOfAvailablePriors(studyObjectID) {
return this.getAvailableStudyPriors(studyObjectID).length;
}
/**
* Get the array of prior studies from a specific study.
*
* @param {String} studyObjectID The study object ID of the study whose priors are needed
* @returns {Array} The array of available priors or an empty array
*/
getAvailableStudyPriors(studyObjectID) {
const priors = this.priorStudies.get(studyObjectID);
return priors instanceof Array ? priors : [];
}
// Match images given a list of Studies and a Viewport's image matching reqs
matchImages(viewport, viewportIndex) {
log.trace('ProtocolEngine::matchImages');
const {
studyMatchingRules,
seriesMatchingRules,
imageMatchingRules: instanceMatchingRules,
} = viewport;
const matchingScores = [];
const currentStudy = this.studies[0]; // @TODO: Should this be: this.studies[this.currentStudy] ???
const firstInstance = currentStudy.getFirstInstance();
let highestStudyMatchingScore = 0;
let highestSeriesMatchingScore = 0;
// Set custom attribute for study metadata and it's first instance
currentStudy.setCustomAttribute(ABSTRACT_PRIOR_VALUE, 0);
if (firstInstance instanceof InstanceMetadata) {
firstInstance.setCustomAttribute(ABSTRACT_PRIOR_VALUE, 0);
}
// Only used if study matching rules has abstract prior values defined...
let priorStudies;
studyMatchingRules.forEach(rule => {
if (rule.attribute === ABSTRACT_PRIOR_VALUE) {
const validatorType = Object.keys(rule.constraint)[0];
const validator = Object.keys(rule.constraint[validatorType])[0];
let abstractPriorValue = rule.constraint[validatorType][validator];
abstractPriorValue = parseInt(abstractPriorValue, 10);
// TODO: Restrict or clarify validators for abstractPriorValue?
// No need to call it more than once...
if (!priorStudies) {
priorStudies = this.getAvailableStudyPriors(
currentStudy.getObjectID()
);
}
// TODO: Revisit this later: What about two studies with the same
// study date?
let priorStudy;
if (abstractPriorValue === -1) {
priorStudy = priorStudies[priorStudies.length - 1];
} else {
const studyIndex = Math.max(abstractPriorValue - 1, 0);
priorStudy = priorStudies[studyIndex];
}
// Invalid data
if (
!(priorStudy instanceof StudyMetadata) &&
!(priorStudy instanceof StudySummary)
) {
return;
}
const priorStudyObjectID = priorStudy.getObjectID();
// Check if study metadata is already in studies list
if (
this.studies.find(study => study.getObjectID() === priorStudyObjectID)
) {
return;
}
// Get study metadata if necessary and load study in the viewer (each viewer should provide it's own load study method)
this.studyMetadataSource.loadStudy(priorStudy).then(
studyMetadata => {
// Set the custom attribute abstractPriorValue for the study metadata
studyMetadata.setCustomAttribute(
ABSTRACT_PRIOR_VALUE,
abstractPriorValue
);
// Also add custom attribute
const firstInstance = studyMetadata.getFirstInstance();
if (firstInstance instanceof InstanceMetadata) {
firstInstance.setCustomAttribute(
ABSTRACT_PRIOR_VALUE,
abstractPriorValue
);
}
// Insert the new study metadata
this.studies.push(studyMetadata);
// Update the viewport to refresh layout manager with new study
this.updateViewports(viewportIndex);
},
error => {
log.warn(error);
throw new OHIFError(
`ProtocolEngine::matchImages could not get study metadata for the Study with the following ObjectID: ${priorStudyObjectID}`
);
}
);
}
// TODO: Add relative Date / time
});
this.studies.forEach(study => {
const studyMatchDetails = HPMatcher.match(
study.getFirstInstance(),
studyMatchingRules
);
// Prevent bestMatch from being updated if the matchDetails' required attribute check has failed
if (
studyMatchDetails.requiredFailed === true ||
studyMatchDetails.score < highestStudyMatchingScore
) {
return;
}
highestStudyMatchingScore = studyMatchDetails.score;
study.forEachSeries(series => {
const seriesMatchDetails = HPMatcher.match(
series.getFirstInstance(),
seriesMatchingRules
);
// Prevent bestMatch from being updated if the matchDetails' required attribute check has failed
if (
seriesMatchDetails.requiredFailed === true ||
seriesMatchDetails.score < highestSeriesMatchingScore
) {
return;
}
highestSeriesMatchingScore = seriesMatchDetails.score;
series.forEachInstance((instance, index) => {
// This tests to make sure there is actually image data in this instance
// TODO: Change this when we add PDF and MPEG support
// See https://ohiforg.atlassian.net/browse/LT-227
// sopClassUid = x00080016
// rows = x00280010
if (
!isImage(instance.getTagValue('x00080016')) &&
!instance.getTagValue('x00280010')
) {
return;
}
const instanceMatchDetails = HPMatcher.match(
instance,
instanceMatchingRules
);
// Prevent bestMatch from being updated if the matchDetails' required attribute check has failed
if (instanceMatchDetails.requiredFailed === true) {
return;
}
const matchDetails = {
passed: [],
failed: [],
};
matchDetails.passed = matchDetails.passed.concat(
instanceMatchDetails.details.passed
);
matchDetails.passed = matchDetails.passed.concat(
seriesMatchDetails.details.passed
);
matchDetails.passed = matchDetails.passed.concat(
studyMatchDetails.details.passed
);
matchDetails.failed = matchDetails.failed.concat(
instanceMatchDetails.details.failed
);
matchDetails.failed = matchDetails.failed.concat(
seriesMatchDetails.details.failed
);
matchDetails.failed = matchDetails.failed.concat(
studyMatchDetails.details.failed
);
const totalMatchScore =
instanceMatchDetails.score +
seriesMatchDetails.score +
studyMatchDetails.score;
const currentSOPInstanceUID = instance.getSOPInstanceUID();
const imageDetails = {
studyInstanceUid: study.getStudyInstanceUID(),
seriesInstanceUid: series.getSeriesInstanceUID(),
sopInstanceUid: currentSOPInstanceUID,
currentImageIdIndex: index,
matchingScore: totalMatchScore,
matchDetails: matchDetails,
sortingInfo: {
score: totalMatchScore,
study:
instance.getTagValue('x00080020') +
instance.getTagValue('x00080030'), // StudyDate = x00080020 StudyTime = x00080030
series: parseInt(instance.getTagValue('x00200011')), // TODO: change for seriesDateTime SeriesNumber = x00200011
instance: parseInt(instance.getTagValue('x00200013')), // TODO: change for acquisitionTime InstanceNumber = x00200013
},
};
// Find the displaySet
const displaySet = study.findDisplaySet(displaySet =>
displaySet.images.find(
image => image.getSOPInstanceUID() === currentSOPInstanceUID
)
);
// If the instance was found, set the displaySet ID
if (displaySet) {
imageDetails.displaySetInstanceUid = displaySet.getUID();
imageDetails.imageId = instance.getImageId();
}
matchingScores.push(imageDetails);
});
});
});
// Sort the matchingScores
const sortingFunction = sortBy(
{
name: 'score',
reverse: true,
},
{
name: 'study',
reverse: true,
},
{
name: 'instance',
},
{
name: 'series',
}
);
matchingScores.sort((a, b) =>
sortingFunction(a.sortingInfo, b.sortingInfo)
);
const bestMatch = matchingScores[0];
log.trace('ProtocolEngine::matchImages bestMatch', bestMatch);
return {
bestMatch,
matchingScores,
};
}
/**
* Sets the current layout
*
* @param rows
* @param columns
*/
setLayout(rows, columns) {
if (rows < 1 && columns < 1) {
log.error(`Invalid layout ${rows} x ${columns}`);
return;
}
if (typeof this.options.setLayout !== 'function') {
log.error('Hanging Protocol Engine setLayout callback is not defined');
return;
}
let viewports = [];
const numViewports = rows * columns;
for (let i = 0; i < numViewports; i++) {
viewports.push({
height: `${100 / rows}%`,
width: `${100 / columns}%`,
});
}
this.options.setLayout({ viewports });
}
/**
* Rerenders viewports that are part of the current layout manager
* using the matching rules internal to each viewport.
*
* If this function is provided the index of a viewport, only the specified viewport
* is rerendered.
*
* @param viewportIndex
*/
updateViewports(viewportIndex) {
log.trace(
`ProtocolEngine::updateViewports viewportIndex: ${viewportIndex}`
);
// Make sure we have an active protocol with a non-empty array of display sets
if (!this.getNumProtocolStages()) {
return;
}
// Retrieve the current stage
const stageModel = this.getCurrentStageModel();
// If the current stage does not fulfill the requirements to be displayed,
// stop here.
if (
!stageModel ||
!stageModel.viewportStructure ||
!stageModel.viewports ||
!stageModel.viewports.length
) {
return;
}
// Retrieve the layoutTemplate associated with the current display set's viewport structure
// If no such template name exists, stop here.
const layoutTemplateName = stageModel.viewportStructure.getLayoutTemplateName();
if (!layoutTemplateName) {
return;
}
// Retrieve the properties associated with the current display set's viewport structure template
// If no such layout properties exist, stop here.
const layoutProps = stageModel.viewportStructure.properties;
if (!layoutProps) {
return;
}
// Create an empty array to store the output viewportData
const viewportData = [];
// Empty the matchDetails associated with the ProtocolEngine.
// This will be used to store the pass/fail details and score
// for each of the viewport matching procedures
this.matchDetails = [];
// Loop through each viewport
stageModel.viewports.forEach((viewport, viewportIndex) => {
const details = this.matchImages(viewport, viewportIndex);
this.matchDetails[viewportIndex] = details;
// Convert any YES/NO values into true/false for Cornerstone
const cornerstoneViewportParams = {};
// Cache viewportSettings keys
const viewportSettingsKeys = Object.keys(viewport.viewportSettings);
viewportSettingsKeys.forEach(key => {
let value = viewport.viewportSettings[key];
if (value === 'YES') {
value = true;
} else if (value === 'NO') {
value = false;
}
cornerstoneViewportParams[key] = value;
});
// imageViewerViewports occasionally needs relevant layout data in order to set
// the element style of the viewport in question
const currentViewportData = {
viewportIndex,
viewport: cornerstoneViewportParams,
...layoutProps,
};
const customSettings = [];
viewportSettingsKeys.forEach(id => {
const setting = CustomViewportSettings[id];
if (!setting) {
return;
}
customSettings.push({
id: id,
value: viewport.viewportSettings[id],
});
});
currentViewportData.renderedCallback = element => {
//console.log('renderedCallback for ' + element.id);
customSettings.forEach(customSetting => {
log.trace(
`ProtocolEngine::currentViewportData.renderedCallback Applying custom setting: ${
customSetting.id
}`
);
log.trace(
`ProtocolEngine::currentViewportData.renderedCallback with value: ${
customSetting.value
}`
);
const setting = CustomViewportSettings[customSetting.id];
setting.callback(element, customSetting.value);
});
};
let currentMatch = details.bestMatch;
let currentPosition = 1;
const scoresLength = details.matchingScores.length;
while (
currentPosition < scoresLength &&
viewportData.find(a => a.imageId === currentMatch.imageId)
) {
currentMatch = details.matchingScores[currentPosition];
currentPosition++;
}
if (currentMatch && currentMatch.imageId) {
currentViewportData.studyInstanceUid = currentMatch.studyInstanceUid;
currentViewportData.seriesInstanceUid = currentMatch.seriesInstanceUid;
currentViewportData.sopInstanceUid = currentMatch.sopInstanceUid;
currentViewportData.currentImageIdIndex =
currentMatch.currentImageIdIndex;
currentViewportData.displaySetInstanceUid =
currentMatch.displaySetInstanceUid;
currentViewportData.imageId = currentMatch.imageId;
}
// @TODO Why should we throw an exception when a best match is not found? This was aborting the whole process.
// if (!currentViewportData.displaySetInstanceUid) {
// throw new OHIFError('ProtocolEngine::updateViewports No matching display set found?');
// }
viewportData.push(currentViewportData);
});
this.setLayout(layoutProps.rows, layoutProps.columns);
if (typeof this.options.setViewportSpecificData !== 'function') {
log.error(
'Hanging Protocol Engine setViewportSpecificData callback is not defined'
);
return;
}
// If viewportIndex is defined, then update only that viewport
if (viewportIndex !== undefined && viewportData[viewportIndex]) {
this.options.setViewportSpecificData(
viewportIndex,
viewportData[viewportIndex]
);
return;
}
// Update all viewports
viewportData.forEach(viewportSpecificData => {
this.options.setViewportSpecificData(
viewportSpecificData.viewportIndex,
viewportSpecificData
);
});
}
/**
* Sets the current Hanging Protocol to the specified Protocol
* An optional argument can also be used to prevent the updating of the Viewports
*
* @param newProtocol
* @param updateViewports
*/
setHangingProtocol(newProtocol, updateViewports = true) {
log.trace('ProtocolEngine::setHangingProtocol newProtocol', newProtocol);
log.trace(
`ProtocolEngine::setHangingProtocol updateViewports = ${updateViewports}`
);
// Reset the array of newStageIds
this.newStageIds = [];
if (Protocol.prototype.isPrototypeOf(newProtocol)) {
this.protocol = newProtocol;
} else {
this.protocol = new Protocol();
this.protocol.fromObject(newProtocol);
}
this.stage = 0;
// Update viewports by default
if (updateViewports) {
this.updateViewports();
}
}
/**
* Check if the next stage is available
* @return {Boolean} True if next stage is available or false otherwise
*/
isNextStageAvailable() {
const numberOfStages = this.getNumProtocolStages();
return this.stage + 1 < numberOfStages;
}
/**
* Check if the previous stage is available
* @return {Boolean} True if previous stage is available or false otherwise
*/
isPreviousStageAvailable() {
return this.stage - 1 >= 0;
}
/**
* Changes the current stage to a new stage index in the display set sequence.
* It checks if the next stage exists.
*
* @param {Integer} stageAction An integer value specifying wheater next (1) or previous (-1) stage
* @return {Boolean} True if new stage has set or false, otherwise
*/
setCurrentProtocolStage(stageAction) {
// Check if previous or next stage is available
if (stageAction === -1 && !this.isPreviousStageAvailable()) {
return false;
} else if (stageAction === 1 && !this.isNextStageAvailable()) {
return false;
}
// Sets the new stage
this.stage += stageAction;
// Log the new stage
log.trace(`ProtocolEngine::setCurrentProtocolStage stage = ${this.stage}`);
// Since stage has changed, we need to update the viewports
// and redo matchings
this.updateViewports();
// Everything went well
return true;
}
/**
* Retrieves the number of Stages in the current Protocol or
* undefined if no protocol or stages are set
*/
getNumProtocolStages() {
if (
!this.protocol ||
!this.protocol.stages ||
!this.protocol.stages.length
) {
return;
}
return this.protocol.stages.length;
}
/**
* Switches to the next protocol stage in the display set sequence
*/
nextProtocolStage() {
log.trace('ProtocolEngine::nextProtocolStage');
if (!this.setCurrentProtocolStage(1)) {
log.trace('ProtocolEngine::nextProtocolStage failed');
}
}
/**
* Switches to the previous protocol stage in the display set sequence
*/
previousProtocolStage() {
log.trace('ProtocolEngine::previousProtocolStage');
if (!this.setCurrentProtocolStage(-1)) {
log.trace('ProtocolEngine::previousProtocolStage failed');
}
}
}

View File

@ -0,0 +1,244 @@
import { ProtocolMatchingRule } from './rules';
import { removeFromArray } from '../lib/removeFromArray';
import Stage from './Stage';
import guid from '../../utils/guid';
import user from '../../user';
/**
* This class represents a Hanging Protocol at the highest level
*
* @type {Protocol}
*/
export default class Protocol {
/**
* The Constructor for the Class to create a Protocol with the bare
* minimum information
*
* @param name The desired name for the Protocol
*/
constructor(name) {
// Create a new UUID for this Protocol
this.id = guid();
// Store a value which determines whether or not a Protocol is locked
// This is probably temporary, since we will eventually have role / user
// checks for editing. For now we just need it to prevent changes to the
// default protocols.
this.locked = false;
// Boolean value to indicate if the protocol has updated priors information
// it's set in "updateNumberOfPriorsReferenced" function
this.hasUpdatedPriorsInformation = false;
// Apply the desired name
this.name = name;
// Set the created and modified dates to Now
this.createdDate = new Date();
this.modifiedDate = new Date();
// If we are logged in while creating this Protocol,
// store this information as well
if (user.userLoggedIn && user.userLoggedIn()) {
this.createdBy = user.getUserId();
this.modifiedBy = user.getUserId();
}
// Create two empty Sets specifying which roles
// have read and write access to this Protocol
this.availableTo = new Set();
this.editableBy = new Set();
// Define empty arrays for the Protocol matching rules
// and Stages
this.protocolMatchingRules = [];
this.stages = [];
// Define auxiliary values for priors
this.numberOfPriorsReferenced = -1;
}
getNumberOfPriorsReferenced(skipCache = false) {
let numberOfPriorsReferenced =
skipCache !== true ? this.numberOfPriorsReferenced : -1;
// Check if information is cached already
if (numberOfPriorsReferenced > -1) {
return numberOfPriorsReferenced;
}
numberOfPriorsReferenced = 0;
// Search each study matching rule for prior rules
// Each stage can have many viewports that can have
// multiple study matching rules.
this.stages.forEach(stage => {
if (!stage.viewports) {
return;
}
stage.viewports.forEach(viewport => {
if (!viewport.studyMatchingRules) {
return;
}
viewport.studyMatchingRules.forEach(rule => {
// If the current rule is not a priors rule, it will return -1 then numberOfPriorsReferenced will continue to be 0
const priorsReferenced = rule.getNumberOfPriorsReferenced();
if (priorsReferenced > numberOfPriorsReferenced) {
numberOfPriorsReferenced = priorsReferenced;
}
});
});
});
this.numberOfPriorsReferenced = numberOfPriorsReferenced;
return numberOfPriorsReferenced;
}
updateNumberOfPriorsReferenced() {
this.getNumberOfPriorsReferenced(true);
}
/**
* Method to update the modifiedDate when the Protocol
* has been changed
*/
protocolWasModified() {
// If we are logged in while modifying this Protocol,
// store this information as well
if (user.userLoggedIn && user.userLoggedIn()) {
this.modifiedBy = user.getUserId();
}
// Protocol has been modified, so mark priors information
// as "outdated"
this.hasUpdatedPriorsInformation = false;
// Update number of priors referenced info
this.updateNumberOfPriorsReferenced();
// Update the modifiedDate with the current Date/Time
this.modifiedDate = new Date();
}
/**
* Occasionally the Protocol class needs to be instantiated from a JavaScript Object
* containing the Protocol data. This function fills in a Protocol with the Object
* data.
*
* @param input A Protocol as a JavaScript Object, e.g. retrieved from JSON
*/
fromObject(input) {
// Check if the input already has an ID
// If so, keep it. It not, create a new UUID
this.id = input.id || guid();
// Assign the input name to the Protocol
this.name = input.name;
// Retrieve locked status, use !! to make it truthy
// so that undefined values will be set to false
this.locked = !!input.locked;
// TODO: Check how to regenerate Set from Object
//this.availableTo = new Set(input.availableTo);
//this.editableBy = new Set(input.editableBy);
// If the input contains Protocol matching rules
if (input.protocolMatchingRules) {
input.protocolMatchingRules.forEach(ruleObject => {
// Create new Rules from the stored data
var rule = new ProtocolMatchingRule();
rule.fromObject(ruleObject);
// Add them to the Protocol
this.protocolMatchingRules.push(rule);
});
}
// If the input contains data for various Stages in the
// display set sequence
if (input.stages) {
input.stages.forEach(stageObject => {
// Create Stages from the stored data
var stage = new Stage();
stage.fromObject(stageObject);
// Add them to the Protocol
this.stages.push(stage);
});
}
}
/**
* Creates a clone of the current Protocol with a new name
*
* @param name
* @returns {Protocol|*}
*/
createClone(name) {
// Create a new JavaScript independent of the current Protocol
var currentProtocol = Object.assign({}, this);
// Create a new Protocol to return
var clonedProtocol = new Protocol();
// Apply the desired properties
currentProtocol.id = clonedProtocol.id;
clonedProtocol.fromObject(currentProtocol);
// If we have specified a name, assign it
if (name) {
clonedProtocol.name = name;
}
// Unlock the clone
clonedProtocol.locked = false;
// Return the cloned Protocol
return clonedProtocol;
}
/**
* Adds a Stage to this Protocol's display set sequence
*
* @param stage
*/
addStage(stage) {
this.stages.push(stage);
// Update the modifiedDate and User that last
// modified this Protocol
this.protocolWasModified();
}
/**
* Adds a Rule to this Protocol's array of matching rules
*
* @param rule
*/
addProtocolMatchingRule(rule) {
this.protocolMatchingRules.push(rule);
// Update the modifiedDate and User that last
// modified this Protocol
this.protocolWasModified();
}
/**
* Removes a Rule from this Protocol's array of matching rules
*
* @param rule
*/
removeProtocolMatchingRule(rule) {
var wasRemoved = removeFromArray(this.protocolMatchingRules, rule);
// Update the modifiedDate and User that last
// modified this Protocol
if (wasRemoved) {
this.protocolWasModified();
}
}
}

View File

@ -0,0 +1,174 @@
import { comparators } from '../lib/comparators';
import guid from '../../utils/guid';
const EQUALS_REGEXP = /^equals$/;
/**
* This Class represents a Rule to be evaluated given a set of attributes
* Rules have:
* - An attribute (e.g. 'seriesDescription')
* - A constraint Object, in the form required by Validate.js:
*
* rule.constraint = {
* contains: {
* value: 'T-1'
* }
* };
*
* Note: In this example we use the 'contains' Validator, which is a custom Validator defined in Viewerbase
*
* - A value for whether or not they are Required to be matched (default: False)
* - A value for their relative weighting during Protocol or Image matching (default: 1)
*/
export default class Rule {
/**
* The Constructor for the Class to create a Rule with the bare
* minimum information
*
* @param name The desired name for the Rule
*/
constructor(attribute, constraint, required, weight) {
// Create a new UUID for this Rule
this.id = guid();
// Set the Rule's weight (defaults to 1)
this.weight = weight || 1;
// If an attribute is specified, assign it
if (attribute) {
this.attribute = attribute;
}
// If a constraint is specified, assign it
if (constraint) {
this.constraint = constraint;
}
// If a value for 'required' is specified, assign it
if (required === undefined) {
// If no value was specified, default to False
this.required = false;
} else {
this.required = required;
}
// Cache for constraint info object
this._constraintInfo = void 0;
// Cache for validator and value object
this._validatorAndValue = void 0;
}
/**
* Occasionally the Rule class needs to be instantiated from a JavaScript Object.
* This function fills in a Protocol with the Object data.
*
* @param input A Rule as a JavaScript Object, e.g. retrieved from JSON
*/
fromObject(input) {
// Check if the input already has an ID
// If so, keep it. It not, create a new UUID
this.id = input.id || guid();
// Assign the specified input data to the Rule
this.required = input.required;
this.weight = input.weight;
this.attribute = input.attribute;
this.constraint = input.constraint;
}
/**
* Get the constraint info object for the current constraint
* @return {Object\undefined} Constraint object or undefined if current constraint
* is not valid or not found in comparators list
*/
getConstraintInfo() {
let constraintInfo = this._constraintInfo;
// Check if info is cached already
if (constraintInfo !== void 0) {
return constraintInfo;
}
const ruleConstraint = Object.keys(this.constraint)[0];
if (ruleConstraint !== void 0) {
constraintInfo = comparators.find(
comparator => ruleConstraint === comparator.id
);
}
// Cache this information for later use
this._constraintInfo = constraintInfo;
return constraintInfo;
}
/**
* Check if current rule is related to priors
* @return {Boolean} True if a rule is related to priors or false otherwise
*/
isRuleForPrior() {
// @TODO: Should we check this too? this.attribute === 'relativeTime'
return this.attribute === 'abstractPriorValue';
}
/**
* If the current rule is a rule for priors, returns the number of referenced priors. Otherwise, returns -1.
* @return {Number} The number of referenced priors or -1 if not applicable. Returns zero if the actual value could not be determined.
*/
getNumberOfPriorsReferenced() {
if (!this.isRuleForPrior()) {
return -1;
}
// Get rule's validator and value
const ruleValidatorAndValue = this.getConstraintValidatorAndValue();
const { value, validator } = ruleValidatorAndValue;
const intValue = parseInt(value, 10) || 0; // avoid possible NaN
// "Equal to" validators
if (EQUALS_REGEXP.test(validator)) {
// In this case, -1 (the oldest prior) indicates that at least one study is used
return intValue < 0 ? 1 : intValue;
}
// Default cases return value
return 0;
}
/**
* Get the constraint validator and value
* @return {Object|undefined} Returns an object containing the validator and it's value or undefined
*/
getConstraintValidatorAndValue() {
let validatorAndValue = this._validatorAndValue;
// Check if validator and value are cached already
if (validatorAndValue !== void 0) {
return validatorAndValue;
}
// Get the constraint info object
const constraintInfo = this.getConstraintInfo();
// Constraint info object exists and is valid
if (constraintInfo !== void 0) {
const validator = constraintInfo.validator;
const currentValidator = this.constraint[validator];
if (currentValidator) {
const constraintValidator = constraintInfo.validatorOption;
const constraintValue = currentValidator[constraintValidator];
validatorAndValue = {
value: constraintValue,
validator: constraintInfo.id,
};
this._validatorAndValue = validatorAndValue;
}
}
return validatorAndValue;
}
}

View File

@ -0,0 +1,85 @@
import ViewportStructure from './ViewportStructure';
import Viewport from './Viewport';
import guid from '../../utils/guid';
/**
* A Stage is one step in the Display Set Sequence for a Hanging Protocol
*
* Stages are defined as a ViewportStructure and an array of Viewports
*
* @type {Stage}
*/
export default class Stage {
constructor(ViewportStructure, name) {
// Create a new UUID for this Stage
this.id = guid();
// Assign the name and ViewportStructure provided
this.name = name;
this.viewportStructure = ViewportStructure;
// Create an empty array for the Viewports
this.viewports = [];
// Set the created date to Now
this.createdDate = new Date();
}
/**
* Creates a clone of the current Stage with a new name
*
* @param name
* @returns {Stage|*}
*/
createClone(name) {
// Create a new JavaScript independent of the current Protocol
var currentStage = Object.assign({}, this);
// Create a new Stage to return
var clonedStage = new Stage();
// Assign the desired properties
currentStage.id = clonedStage.id;
clonedStage.fromObject(currentStage);
// If we have specified a name, assign it
if (name) {
clonedStage.name = name;
}
// Return the cloned Stage
return clonedStage;
}
/**
* Occasionally the Stage class needs to be instantiated from a JavaScript Object.
* This function fills in a Protocol with the Object data.
*
* @param input A Stage as a JavaScript Object, e.g. retrieved from JSON
*/
fromObject(input) {
// Check if the input already has an ID
// If so, keep it. It not, create a new UUID
this.id = input.id || guid();
// Assign the input name to the Stage
this.name = input.name;
// If a ViewportStructure is present in the input, add it from the
// input data
this.viewportStructure = new ViewportStructure();
this.viewportStructure.fromObject(input.viewportStructure);
// If any viewports are present in the input object
if (input.viewports) {
input.viewports.forEach(viewportObject => {
// Create a new Viewport with their data
var viewport = new Viewport();
viewport.fromObject(viewportObject);
// Add it to the viewports array
this.viewports.push(viewport);
});
}
}
}

View File

@ -0,0 +1,85 @@
import {
StudyMatchingRule,
SeriesMatchingRule,
ImageMatchingRule,
} from './rules';
import { removeFromArray } from '../lib/removeFromArray';
/**
* This Class defines a Viewport in the Hanging Protocol Stage. A Viewport contains
* arrays of Rules that are matched in the ProtocolEngine in order to determine which
* images should be hung.
*
* @type {Viewport}
*/
export default class Viewport {
constructor() {
this.viewportSettings = {};
this.imageMatchingRules = [];
this.seriesMatchingRules = [];
this.studyMatchingRules = [];
}
/**
* Occasionally the Viewport class needs to be instantiated from a JavaScript Object.
* This function fills in a Viewport with the Object data.
*
* @param input The Viewport as a JavaScript Object, e.g. retrieved from JSON
*/
fromObject(input) {
// If ImageMatchingRules exist, create them from the Object data
// and add them to the Viewport's imageMatchingRules array
if (input.imageMatchingRules) {
input.imageMatchingRules.forEach(ruleObject => {
var rule = new ImageMatchingRule();
rule.fromObject(ruleObject);
this.imageMatchingRules.push(rule);
});
}
// If SeriesMatchingRules exist, create them from the Object data
// and add them to the Viewport's seriesMatchingRules array
if (input.seriesMatchingRules) {
input.seriesMatchingRules.forEach(ruleObject => {
var rule = new SeriesMatchingRule();
rule.fromObject(ruleObject);
this.seriesMatchingRules.push(rule);
});
}
// If StudyMatchingRules exist, create them from the Object data
// and add them to the Viewport's studyMatchingRules array
if (input.studyMatchingRules) {
input.studyMatchingRules.forEach(ruleObject => {
var rule = new StudyMatchingRule();
rule.fromObject(ruleObject);
this.studyMatchingRules.push(rule);
});
}
// If ViewportSettings exist, add them to the current protocol
if (input.viewportSettings) {
this.viewportSettings = input.viewportSettings;
}
}
/**
* Finds and removes a rule from whichever array it exists in.
* It is not required to specify if it exists in studyMatchingRules,
* seriesMatchingRules, or imageMatchingRules
*
* @param rule
*/
removeRule(rule) {
var array;
if (rule instanceof StudyMatchingRule) {
array = this.studyMatchingRules;
} else if (rule instanceof SeriesMatchingRule) {
array = this.seriesMatchingRules;
} else if (rule instanceof ImageMatchingRule) {
array = this.imageMatchingRules;
}
removeFromArray(array, rule);
}
}

View File

@ -0,0 +1,53 @@
/**
* The ViewportStructure class represents the layout and layout properties that
* Viewports are displayed in. ViewportStructure has a type, which corresponds to
* a layout template, and a set of properties, which depend on the type.
*
* @type {ViewportStructure}
*/
export default class ViewportStructure {
constructor(type, properties) {
this.type = type;
this.properties = properties;
}
/**
* Occasionally the ViewportStructure class needs to be instantiated from a JavaScript Object.
* This function fills in a ViewportStructure with the Object data.
*
* @param input The ViewportStructure as a JavaScript Object, e.g. retrieved from JSON
*/
fromObject(input) {
this.type = input.type;
this.properties = input.properties;
}
/**
* Retrieve the layout template name based on the layout type
*
* @returns {string}
*/
getLayoutTemplateName() {
// Viewport structure can be updated later when we build more complex display layouts
switch (this.type) {
case 'grid':
return 'gridLayout';
}
}
/**
* Retrieve the number of Viewports required for this layout
* given the layout type and properties
*
* @returns {string}
*/
getNumViewports() {
// Viewport structure can be updated later when we build more complex display layouts
switch (this.type) {
case 'grid':
// For the typical grid layout, we only need to multiply rows by columns to
// obtain the number of viewports
return this.properties.rows * this.properties.columns;
}
}
}

View File

@ -0,0 +1,23 @@
import Protocol from './Protocol.js';
import Rule from './Rule.js';
import Stage from './Stage.js';
import Viewport from './Viewport.js';
import ViewportStructure from './ViewportStructure.js';
import {
ProtocolMatchingRule,
StudyMatchingRule,
SeriesMatchingRule,
ImageMatchingRule,
} from './rules.js';
export {
Protocol,
Rule,
Stage,
Viewport,
ViewportStructure,
ProtocolMatchingRule,
StudyMatchingRule,
SeriesMatchingRule,
ImageMatchingRule,
};

View File

@ -0,0 +1,40 @@
import Rule from './Rule';
/**
* The ProtocolMatchingRule Class extends the Rule Class.
*
* At present it does not add any new methods or attributes
* @type {ProtocolMatchingRule}
*/
class ProtocolMatchingRule extends Rule {}
/**
* The StudyMatchingRule Class extends the Rule Class.
*
* At present it does not add any new methods or attributes
* @type {StudyMatchingRule}
*/
class StudyMatchingRule extends Rule {}
/**
* The SeriesMatchingRule Class extends the Rule Class.
*
* At present it does not add any new methods or attributes
* @type {SeriesMatchingRule}
*/
class SeriesMatchingRule extends Rule {}
/**
* The ImageMatchingRule class extends the Rule Class.
*
* At present it does not add any new methods or attributes
* @type {ImageMatchingRule}
*/
class ImageMatchingRule extends Rule {}
export {
ProtocolMatchingRule,
StudyMatchingRule,
SeriesMatchingRule,
ImageMatchingRule,
};

View File

@ -0,0 +1,30 @@
// Define an empty object to store callbacks that are used to retrieve custom attributes
// The simplest example for a custom attribute is the Timepoint type (i.e. baseline or follow-up)
// used in the LesionTracker application.
//
// Timepoint type can be obtained given a studyId, and this is done through a custom callback.
// Developers can define attributes (i.e. attributeId = timepointType) with a name ('Timepoint Type')
// and a callback function that is used to calculate them.
//
// The input to the callback, which is called during viewport-image matching rule evaluation
// is the set of attributes that contains the specified attribute. In our example, timepointType is
// linked to the study attributes, and so the inputs to the callback is an object containing
// the study attributes.
const CustomAttributeRetrievalCallbacks = {};
/**
* Adds a custom attribute to be used in the HangingProtocol UI and matching rules, including a
* callback that will be used to calculate the attribute value.
*
* @param attributeId The ID used to refer to the attribute (e.g. 'timepointType')
* @param attributeName The name of the attribute to be displayed (e.g. 'Timepoint Type')
* @param callback The function used to calculate the attribute value from the other attributes at its level (e.g. study/series/image)
*/
function addCustomAttribute(attributeId, attributeName, callback) {
CustomAttributeRetrievalCallbacks[attributeId] = {
name: attributeName,
callback: callback,
};
}
export { CustomAttributeRetrievalCallbacks, addCustomAttribute };

View File

@ -0,0 +1,22 @@
// Define an empty object to store callbacks that are used to apply custom viewport settings
// after a viewport is rendered.
const CustomViewportSettings = {};
/**
* Adds a custom setting that can be chosen in the HangingProtocol UI and applied to a Viewport
*
* @param settingId The ID used to refer to the setting (e.g. 'displayCADMarkers')
* @param settingName The name of the setting to be displayed (e.g. 'Display CAD Markers')
* @param options
* @param callback A function to be run after a viewport is rendered with a series
*/
function addCustomViewportSetting(settingId, settingName, options, callback) {
CustomViewportSettings[settingId] = {
id: settingId,
text: settingName,
options: options,
callback: callback,
};
}
export { CustomViewportSettings, addCustomViewportSetting };

View File

@ -0,0 +1,133 @@
export const attributeDefaults = {
abstractPriorValue: 0,
};
export const displaySettings = {
invert: {
id: 'invert',
text: 'Show Grayscale Inverted',
defaultValue: 'NO',
options: ['YES', 'NO'],
},
};
// @TODO Fix abstractPriorValue comparison
export const studyAttributes = [
{
id: 'x00100020',
text: '(x00100020) Patient ID',
},
{
id: 'x0020000d',
text: '(x0020000d) Study Instance UID',
},
{
id: 'x00080020',
text: '(x00080020) Study Date',
},
{
id: 'x00080030',
text: '(x00080030) Study Time',
},
{
id: 'x00081030',
text: '(x00081030) Study Description',
},
{
id: 'abstractPriorValue',
text: 'Abstract Prior Value',
},
];
export const protocolAttributes = [
{
id: 'x00100020',
text: '(x00100020) Patient ID',
},
{
id: 'x0020000d',
text: '(x0020000d) Study Instance UID',
},
{
id: 'x00080020',
text: '(x00080020) Study Date',
},
{
id: 'x00080030',
text: '(x00080030) Study Time',
},
{
id: 'x00081030',
text: '(x00081030) Study Description',
},
{
id: 'anatomicRegion',
text: 'Anatomic Region',
},
];
export const seriesAttributes = [
{
id: 'x0020000e',
text: '(x0020000e) Series Instance UID',
},
{
id: 'x00080060',
text: '(x00080060) Modality',
},
{
id: 'x00200011',
text: '(x00200011) Series Number',
},
{
id: 'x0008103e',
text: '(x0008103e) Series Description',
},
{
id: 'numImages',
text: 'Number of Images',
},
];
export const instanceAttributes = [
{
id: 'x00080016',
text: '(x00080016) SOP Class UID',
},
{
id: 'x00080018',
text: '(x00080018) SOP Instance UID',
},
{
id: 'x00185101',
text: '(x00185101) View Position',
},
{
id: 'x00200013',
text: '(x00200013) Instance Number',
},
{
id: 'x00080008',
text: '(x00080008) Image Type',
},
{
id: 'x00181063',
text: '(x00181063) Frame Time',
},
{
id: 'x00200060',
text: '(x00200060) Laterality',
},
{
id: 'x00541330',
text: '(x00541330) Image Index',
},
{
id: 'x00280004',
text: '(x00280004) Photometric Interpretation',
},
{
id: 'x00180050',
text: '(x00180050) Slice Thickness',
},
];

View File

@ -0,0 +1,14 @@
import ProtocolEngine from './ProtocolEngine.js';
import { ProtocolStore, ProtocolStrategy } from './protocolStore';
import { addCustomAttribute } from './customAttributes';
import { addCustomViewportSetting } from './customViewportSettings';
const hangingProtocols = {
ProtocolEngine,
ProtocolStore,
ProtocolStrategy,
addCustomAttribute,
addCustomViewportSetting,
};
export default hangingProtocols;

View File

@ -0,0 +1,98 @@
const comparators = [
{
id: 'equals',
name: '= (Equals)',
validator: 'equals',
validatorOption: 'value',
description: 'The attribute must equal this value.',
},
{
id: 'doesNotEqual',
name: '!= (Does not equal)',
validator: 'doesNotEqual',
validatorOption: 'value',
description: 'The attribute must not equal this value.',
},
{
id: 'contains',
name: 'Contains',
validator: 'contains',
validatorOption: 'value',
description: 'The attribute must contain this value.',
},
{
id: 'doesNotContain',
name: 'Does not contain',
validator: 'doesNotContain',
validatorOption: 'value',
description: 'The attribute must not contain this value.',
},
{
id: 'startsWith',
name: 'Starts with',
validator: 'startsWith',
validatorOption: 'value',
description: 'The attribute must start with this value.',
},
{
id: 'endsWith',
name: 'Ends with',
validator: 'endsWith',
validatorOption: 'value',
description: 'The attribute must end with this value.',
},
{
id: 'onlyInteger',
name: 'Only Integers',
validator: 'numericality',
validatorOption: 'onlyInteger',
description: "Real numbers won't be allowed.",
},
{
id: 'greaterThan',
name: '> (Greater than)',
validator: 'numericality',
validatorOption: 'greaterThan',
description: 'The attribute has to be greater than this value.',
},
{
id: 'greaterThanOrEqualTo',
name: '>= (Greater than or equal to)',
validator: 'numericality',
validatorOption: 'greaterThanOrEqualTo',
description: 'The attribute has to be at least this value.',
},
{
id: 'lessThanOrEqualTo',
name: '<= (Less than or equal to)',
validator: 'numericality',
validatorOption: 'lessThanOrEqualTo',
description: 'The attribute can be this value at the most.',
},
{
id: 'lessThan',
name: '< (Less than)',
validator: 'numericality',
validatorOption: 'lessThan',
description: 'The attribute has to be less than this value.',
},
{
id: 'odd',
name: 'Odd',
validator: 'numericality',
validatorOption: 'odd',
description: 'The attribute has to be odd.',
},
{
id: 'even',
name: 'Even',
validator: 'numericality',
validatorOption: 'even',
description: 'The attribute has to be even.',
},
];
// Immutable object
Object.freeze(comparators);
export { comparators };

View File

@ -0,0 +1,71 @@
const attributeCache = Object.create(null);
const REGEXP = /^\([x0-9a-f]+\)/;
const humanize = text => {
let humanized = text.replace(/([A-Z])/g, ' $1'); // insert a space before all caps
humanized = humanized.replace(/^./, str => {
// uppercase the first character
return str.toUpperCase();
});
return humanized;
};
/**
* Get the text of an attribute for a given attribute
* @param {String} attributeId The attribute ID
* @param {Array} attributes Array of attributes objects with id and text properties
* @return {String} If found return the attribute text or an empty string otherwise
*/
const getAttributeText = (attributeId, attributes) => {
// If the attribute is already in the cache, return it
if (attributeId in attributeCache) {
return attributeCache[attributeId];
}
// Find the attribute with given attributeId
const attribute = attributes.find(attribute => attribute.id === attributeId);
let attributeText;
// If attribute was found get its text and save it on the cache
if (attribute) {
attributeText = attribute.text.replace(REGEXP, '');
attributeCache[attributeId] = attributeText;
}
return attributeText || '';
};
function displayConstraint(attributeId, constraint, attributes) {
if (!constraint || !attributeId) {
return;
}
const validatorType = Object.keys(constraint)[0];
if (!validatorType) {
return;
}
const validator = Object.keys(constraint[validatorType])[0];
if (!validator) {
return;
}
const value = constraint[validatorType][validator];
if (value === void 0) {
return;
}
let comparator = validator;
if (validator === 'value') {
comparator = validatorType;
}
const attributeText = getAttributeText(attributeId, attributes);
const constraintText =
attributeText + ' ' + humanize(comparator).toLowerCase() + ' ' + value;
return constraintText;
}

View File

@ -0,0 +1,32 @@
/**
* Removes the first instance of an element from an array, if an equal value exists
*
* @param array
* @param input
*
* @returns {boolean} Whether or not the element was found and removed
*/
const removeFromArray = (array, input) => {
// If the array is empty, stop here
if (!array || !array.length) {
return false;
}
array.forEach((value, index) => {
// TODO: Double check whether or not this deep equality check is necessary
//if (_.isEqual(value, input)) {
if (value === input) {
indexToRemove = index;
return false;
}
});
if (indexToRemove === void 0) {
return false;
}
array.splice(indexToRemove, 1);
return true;
};
export { removeFromArray };

View File

@ -0,0 +1,8 @@
// Sorts an array by score
const sortByScore = arr => {
arr.sort((a, b) => {
return b.score - a.score;
});
};
export { sortByScore };

View File

@ -0,0 +1,39 @@
import validate from 'validate.js';
validate.validators.equals = function(value, options, key, attributes) {
if (options && value !== options.value) {
return key + 'must equal ' + options.value;
}
};
validate.validators.doesNotEqual = function(value, options, key) {
if (options && value === options.value) {
return key + 'cannot equal ' + options.value;
}
};
validate.validators.contains = function(value, options, key) {
if (options && value.indexOf && value.indexOf(options.value) === -1) {
return key + 'must contain ' + options.value;
}
};
validate.validators.doesNotContain = function(value, options, key) {
if (options && value.indexOf && value.indexOf(options.value) !== -1) {
return key + 'cannot contain ' + options.value;
}
};
validate.validators.startsWith = function(value, options, key) {
if (options && value.startsWith && !value.startsWith(options.value)) {
return key + 'must start with ' + options.value;
}
};
validate.validators.endsWith = function(value, options, key) {
if (options && value.endsWith && !value.endsWith(options.value)) {
return key + 'must end with ' + options.value;
}
};
export { validate };

View File

@ -0,0 +1,97 @@
import Protocol from '../../classes/Protocol';
// The ProtocolStore class allows persisting hanging protocols using different strategies.
// For example, one strategy stores hanging protocols in the application server while
// another strategy stores them in a remote machine, but only one strategy can be used at a time.
export default class ProtocolStore {
constructor(strategy) {
this.strategy = strategy;
}
/**
* Get a Protocol instance or array of Protocol instances for the given protocol object or array
* @param {Object|array} protocolObject Protocol plain object or array of Protocol plain objects
* @return {Protocol|array} Protocol instance or array of Protocol intances for the given protocol object or array
*/
static getProtocolInstance(protocolObject) {
let result = protocolObject;
// If result is an array of protocols objects
if (result instanceof Array) {
result.forEach((protocol, index) => {
// Check if protocol is an instance of Protocol
if (!(protocol instanceof Protocol)) {
const protocolInstance = new Protocol();
protocolInstance.fromObject(protocol);
result[index] = protocolInstance;
}
});
} else if (result !== void 0 && !(result instanceof Protocol)) {
// Check if result exists and is not an instance of Protocol
const protocolInstance = new Protocol();
protocolInstance.fromObject(result);
result = protocolInstance;
}
return result;
}
/**
* Registers a function to be called when the protocol store is ready to persist hanging protocols
*
* NOTE: Strategies should implement this function
*
* @param callback The function to be called as a callback
*/
onReady(callback) {
this.strategy.onReady(callback);
}
/**
* Gets the hanging protocol by protocolId if defined, otherwise all stored hanging protocols
*
* NOTE: Strategies should implement this function
*
* @param protocolId The protocol ID used to find the hanging protocol
* @returns {object|array} The hanging protocol by protocolId or array of the stored hanging protocols
*/
getProtocol(protocolId) {
let result = this.strategy.getProtocol(protocolId);
return ProtocolStore.getProtocolInstance(result);
}
/**
* Stores the hanging protocol
*
* NOTE: Strategies should implement this function
*
* @param protocol The hanging protocol to be stored
*/
addProtocol(protocol) {
this.strategy.addProtocol(protocol);
}
/**
* Updates the hanging protocol by protocolId
*
* NOTE: Strategies should implement this function
*
* @param protocolId The protocol ID used to find the hanging protocol to update
* @param protocol The updated hanging protocol
*/
updateProtocol(protocolId, protocol) {
this.strategy.updateProtocol(protocolId, protocol);
}
/**
* Removes the hanging protocol
*
* NOTE: Strategies should implement this function
*
* @param protocolId The protocol ID used to remove the hanging protocol
*/
removeProtocol(protocolId) {
this.strategy.removeProtocol(protocolId);
}
}

View File

@ -0,0 +1,77 @@
import log from '../../../log';
import defaultProtocol from '../defaultProtocol';
export default class ProtocolStrategy {
constructor() {
this.hangingProtocols = new Map();
this.defaultsAdded = false;
}
/**
* Registers a function to be called when the hangingProtocols collection is subscribed
* The callback is called only one time when the subscription is ready
*
* @param callback The function to be called as a callback
*/
onReady(callback) {
if (!this.defaultsAdded) {
log.info('Inserting the default hanging protocol...');
this.addProtocol(defaultProtocol);
this.defaultsAdded = true;
}
callback();
}
/**
* Gets the hanging protocol by protocolId if defined, otherwise all stored hanging protocols
*
* @param protocolId The protocol ID used to find the hanging protocol
* @returns {object|array} The hanging protocol by protocolId or array of the stored hanging protocols
*/
getProtocol(protocolId) {
// Return the hanging protocol by protocolId if defined
if (protocolId) {
return this.hangingProtocols.get(protocolId);
}
// Otherwise, return all protocols
return Array.from(this.hangingProtocols.values());
}
/**
* Stores the hanging protocol
*
* @param protocol The hanging protocol to be stored
*/
addProtocol(protocol) {
this.hangingProtocols.set(protocol.id, protocol);
}
/**
* Updates the hanging protocol by protocolId
*
* @param protocolId The protocol ID used to find the hanging protocol to update
* @param protocol The updated hanging protocol
*/
updateProtocol(protocolId, protocol) {
if (!this.hangingProtocols.has(protocolId)) {
return;
}
this.hangingProtocols.set(protocolId, protocol);
}
/**
* Removes the hanging protocol
*
* @param protocolId The protocol ID used to remove the hanging protocol
*/
removeProtocol(protocolId) {
if (!this.hangingProtocols.has(protocolId)) {
return;
}
this.hangingProtocols.delete(protocolId);
}
}

View File

@ -0,0 +1,4 @@
import ProtocolStore from './ProtocolStore';
import ProtocolStrategy from './ProtocolStrategy';
export { ProtocolStore, ProtocolStrategy };

View File

@ -0,0 +1,27 @@
import Protocol from '../classes/Protocol';
import ViewportStructure from '../classes/ViewportStructure';
import Viewport from '../classes/Viewport';
import Stage from '../classes/Stage';
function getDefaultProtocol() {
const protocol = new Protocol('Default');
protocol.id = 'defaultProtocol';
protocol.locked = true;
const oneByOne = new ViewportStructure('grid', {
rows: 1,
columns: 1,
});
const viewport = new Viewport();
const first = new Stage(oneByOne, 'oneByOne');
first.viewports.push(viewport);
protocol.stages.push(first);
return protocol;
}
const defaultProtocol = getDefaultProtocol();
export default defaultProtocol;

View File

@ -0,0 +1,5 @@
import { ProtocolStore, ProtocolStrategy } from './classes';
import defaultProtocol from './defaultProtocol';
import testProtocols from './testProtocols';
export { ProtocolStore, ProtocolStrategy, defaultProtocol, testProtocols };

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,9 @@
//import Dropdown from './ui/dropdown/class.js';
/*
* Defines the base OHIF header object
*/
//const dropdown = new OHIF.ui.Dropdown();
const header = {};
export default header;

9
packages/_core/src/ie.js Normal file
View File

@ -0,0 +1,9 @@
import writeScript from './lib/writeScript';
// Check if browser is IE and add the polyfill scripts
if (navigator && /MSIE \d|Trident.*rv:/.test(navigator.userAgent)) {
window.onload = () => {
// Fix SVG+USE issues by calling the SVG polyfill
writeScript('svgxuse.min.js');
};
}

View File

@ -0,0 +1,73 @@
import './lib';
import { ExtensionManager, MODULE_TYPES } from './extensions';
import classes, { CommandsManager, HotkeysManager } from './classes/';
import DICOMWeb from './DICOMWeb';
import cornerstone from './cornerstone.js';
import hangingProtocols from './hanging-protocols';
import header from './header.js';
import log from './log.js';
import measurements from './measurements';
import metadata from './classes/metadata/';
import object from './object.js';
import redux from './redux/';
import string from './string.js';
//import './schema.js';
import studies from './studies/';
import ui from './ui';
import user from './user.js';
import utils from './utils/';
const OHIF = {
MODULE_TYPES,
//
CommandsManager,
ExtensionManager,
HotkeysManager,
//
utils,
studies,
redux,
classes,
metadata,
header,
cornerstone,
string,
ui,
user,
object,
log,
DICOMWeb,
viewer: {},
measurements,
hangingProtocols,
};
export {
MODULE_TYPES,
//
CommandsManager,
ExtensionManager,
HotkeysManager,
//
utils,
studies,
redux,
classes,
metadata,
header,
cornerstone,
string,
ui,
user,
object,
log,
DICOMWeb,
measurements,
hangingProtocols,
};
export { OHIF };
export default OHIF;

View File

@ -0,0 +1,35 @@
import * as OHIF from './index.js';
describe('Top level exports', () => {
test('have not changed', () => {
const expectedExports = [
'MODULE_TYPES',
//
'CommandsManager',
'ExtensionManager',
'HotkeysManager',
//
'utils',
'studies',
'redux',
'classes',
'metadata',
'header',
'cornerstone',
'default', //
'string',
'ui',
'user',
'object',
'log',
'DICOMWeb',
'OHIF', //
'measurements',
'hangingProtocols',
].sort();
const exports = Object.keys(OHIF).sort();
expect(exports).toEqual(expectedExports);
});
});

View File

@ -0,0 +1,327 @@
import cornerstone from 'cornerstone-core';
import cornerstoneTools from 'cornerstone-tools';
function getBoundingBox(context, textLines, x, y, options) {
if (Object.prototype.toString.call(textLines) !== '[object Array]') {
textLines = [textLines];
}
const padding = 5;
const font = cornerstoneTools.textStyle.getFont();
const fontSize = cornerstoneTools.textStyle.getFontSize();
context.save();
context.font = font;
context.textBaseline = 'top';
// Find the longest text width in the array of text data
let maxWidth = 0;
textLines.forEach(text => {
// Get the text width in the current font
const width = context.measureText(text).width;
// Find the maximum with for all the text rows;
maxWidth = Math.max(maxWidth, width);
});
// Calculate the bounding box for this text box
const boundingBox = {
width: maxWidth + padding * 2,
height: padding + textLines.length * (fontSize + padding),
};
if (options && options.centering && options.centering.x === true) {
x -= boundingBox.width / 2;
}
if (options && options.centering && options.centering.y === true) {
y -= boundingBox.height / 2;
}
boundingBox.left = x;
boundingBox.top = y;
context.restore();
// Return the bounding box so it can be used for pointNearHandle
return boundingBox;
}
function pixelToPage(element, position) {
const enabledElement = cornerstone.getEnabledElement(element);
const result = {
x: 0,
y: 0,
};
// Stop here if the cornerstone element is not enabled or position is not an object
if (!enabledElement || typeof position !== 'object') {
return result;
}
const canvas = enabledElement.canvas;
const canvasOffset = $(canvas).offset();
result.x += canvasOffset.left;
result.y += canvasOffset.top;
const canvasPosition = cornerstone.pixelToCanvas(element, position);
result.x += canvasPosition.x;
result.y += canvasPosition.y;
return result;
}
function repositionTextBox(eventData, measurementData, config) {
// Stop here if it's not a measurement creating
if (!measurementData.isCreating) {
return;
}
const element = eventData.element;
const enabledElement = cornerstone.getEnabledElement(element);
const image = enabledElement.image;
const allowedBorders = OHIF.uiSettings.autoPositionMeasurementsTextCallOuts;
const allow = {
T: !allowedBorders || allowedBorders.includes('T'),
R: !allowedBorders || allowedBorders.includes('R'),
B: !allowedBorders || allowedBorders.includes('B'),
L: !allowedBorders || allowedBorders.includes('L'),
};
const getAvailableBlankAreas = (enabledElement, labelWidth, labelHeight) => {
const { element, canvas, image } = enabledElement;
const topLeft = cornerstone.pixelToCanvas(element, {
x: 0,
y: 0,
});
const bottomRight = cornerstone.pixelToCanvas(element, {
x: image.width,
y: image.height,
});
const $canvas = $(canvas);
const canvasWidth = $canvas.outerWidth();
const canvasHeight = $canvas.outerHeight();
const result = {};
result['x-1'] = allow.L && topLeft.x > labelWidth;
result['y-1'] = allow.T && topLeft.y > labelHeight;
result.x1 = allow.R && canvasWidth - bottomRight.x > labelWidth;
result.y1 = allow.B && canvasHeight - bottomRight.y > labelHeight;
return result;
};
const getRenderingInformation = (limits, tool) => {
const mid = {};
mid.x = limits.x / 2;
mid.y = limits.y / 2;
const directions = {};
directions.x = tool.x < mid.x ? -1 : 1;
directions.y = tool.y < mid.y ? -1 : 1;
const diffX = directions.x < 0 ? tool.x : limits.x - tool.x;
const diffY = directions.y < 0 ? tool.y : limits.y - tool.y;
let cornerAxis = diffY < diffX ? 'y' : 'x';
const map = {
'x-1': 'L',
'y-1': 'T',
x1: 'R',
y1: 'B',
};
let current = 0;
while (current < 4 && !allow[map[cornerAxis + directions[cornerAxis]]]) {
// Invert the direction for the next iteration
directions[cornerAxis] *= -1;
// Invert the tempCornerAxis
cornerAxis = cornerAxis === 'x' ? 'y' : 'x';
current++;
}
return {
directions,
cornerAxis,
};
};
const calculateAxisCenter = (axis, start, end) => {
const a = start[axis];
const b = end[axis];
const lowest = Math.min(a, b);
const highest = Math.max(a, b);
return lowest + (highest - lowest) / 2;
};
const getTextBoxSizeInPixels = (element, bounds) => {
const topLeft = cornerstone.pageToPixel(element, 0, 0);
const bottomRight = cornerstone.pageToPixel(element, bounds.x, bounds.y);
return {
x: bottomRight.x - topLeft.x,
y: bottomRight.y - topLeft.y,
};
};
function getTextBoxOffset(config, cornerAxis, toolAxis, boxSize) {
config = config || {};
const centering = config.centering || {};
const centerX = !!centering.x;
const centerY = !!centering.y;
const halfBoxSizeX = boxSize.x / 2;
const halfBoxSizeY = boxSize.y / 2;
const offset = {
x: [],
y: [],
};
if (cornerAxis === 'x') {
const offsetY = centerY ? 0 : halfBoxSizeY;
offset.x[-1] = centerX ? halfBoxSizeX : 0;
offset.x[1] = centerX ? -halfBoxSizeX : -boxSize.x;
offset.y[-1] = offsetY;
offset.y[1] = offsetY;
} else {
const offsetX = centerX ? 0 : halfBoxSizeX;
offset.x[-1] = offsetX;
offset.x[1] = offsetX;
offset.y[-1] = centerY ? halfBoxSizeY : 0;
offset.y[1] = centerY ? -halfBoxSizeY : -boxSize.y;
}
return offset;
}
const handles = measurementData.handles;
const textBox = handles.textBox;
const $canvas = $(enabledElement.canvas);
const canvasWidth = $canvas.outerWidth();
const canvasHeight = $canvas.outerHeight();
const offset = $canvas.offset();
const canvasDimensions = {
x: canvasWidth,
y: canvasHeight,
};
const bounds = {};
bounds.x = textBox.boundingBox.width;
bounds.y = textBox.boundingBox.height;
const getHandlePosition = key => {
const { x, y } = handles[key];
return { x, y };
};
const start = getHandlePosition('start');
const end = getHandlePosition('end');
const tool = {};
tool.x = calculateAxisCenter('x', start, end);
tool.y = calculateAxisCenter('y', start, end);
let limits = {};
limits.x = image.width;
limits.y = image.height;
let { directions, cornerAxis } = getRenderingInformation(limits, tool);
const availableAreas = getAvailableBlankAreas(
enabledElement,
bounds.x,
bounds.y
);
const tempDirections = Object.assign({}, directions);
let tempCornerAxis = cornerAxis;
let foundPlace = false;
let current = 0;
while (current < 4) {
if (availableAreas[tempCornerAxis + tempDirections[tempCornerAxis]]) {
foundPlace = true;
break;
}
// Invert the direction for the next iteration
tempDirections[tempCornerAxis] *= -1;
// Invert the tempCornerAxis
tempCornerAxis = tempCornerAxis === 'x' ? 'y' : 'x';
current++;
}
let cornerAxisPosition;
if (foundPlace) {
directions = Object.assign({}, directions, tempDirections);
cornerAxis = tempCornerAxis;
cornerAxisPosition = directions[cornerAxis] < 0 ? 0 : limits[cornerAxis];
} else {
limits = Object.assign({}, limits, canvasDimensions);
const toolPositionOnCanvas = cornerstone.pixelToCanvas(element, tool);
const renderingInformation = getRenderingInformation(
limits,
toolPositionOnCanvas
);
directions = renderingInformation.directions;
cornerAxis = renderingInformation.cornerAxis;
const position = {
x: directions.x < 0 ? offset.left : offset.left + canvasWidth,
y: directions.y < 0 ? offset.top : offset.top + canvasHeight,
};
const pixelPosition = cornerstone.pageToPixel(
element,
position.x,
position.y
);
cornerAxisPosition = pixelPosition[cornerAxis];
}
const toolAxis = cornerAxis === 'x' ? 'y' : 'x';
const boxSize = getTextBoxSizeInPixels(element, bounds);
textBox[cornerAxis] = cornerAxisPosition;
textBox[toolAxis] = tool[toolAxis];
// Adjust the text box position reducing its size from the corner axis
const textBoxOffset = getTextBoxOffset(config, cornerAxis, toolAxis, boxSize);
textBox[cornerAxis] += textBoxOffset[cornerAxis][directions[cornerAxis]];
// Preventing the text box from partially going outside the canvas area
const topLeft = cornerstone.pixelToCanvas(element, textBox);
const bottomRight = {
x: topLeft.x + bounds.x,
y: topLeft.y + bounds.y,
};
const canvasBorders = {
x0: offset.left,
y0: offset.top,
x1: offset.left + canvasWidth,
y1: offset.top + canvasHeight,
};
if (topLeft[toolAxis] < 0) {
const x = canvasBorders.x0;
const y = canvasBorders.y0;
const pixelPosition = cornerstone.pageToPixel(element, x, y);
textBox[toolAxis] = pixelPosition[toolAxis];
} else if (bottomRight[toolAxis] > canvasDimensions[toolAxis]) {
const x = canvasBorders.x1 - bounds.x;
const y = canvasBorders.y1 - bounds.y;
const pixelPosition = cornerstone.pageToPixel(element, x, y);
textBox[toolAxis] = pixelPosition[toolAxis];
}
}
export { getBoundingBox, pixelToPage, repositionTextBox };

View File

@ -0,0 +1,2 @@
import './cornerstone.js';
import './parsingUtils.js';

Some files were not shown because too many files have changed in this diff Show More