wip, very broken as I moved stuff to ohif-core
This commit is contained in:
parent
7b66dec163
commit
d541c23117
@ -26,12 +26,10 @@ standard-minifier-js@2.4.0
|
||||
shell-server@0.4.0
|
||||
|
||||
# OHIF Packages
|
||||
ohif:core
|
||||
ohif:cornerstone
|
||||
ohif:viewerbase
|
||||
ohif:study-list
|
||||
ohif:hanging-protocols
|
||||
ohif:measurement-table
|
||||
|
||||
fortawesome:fontawesome
|
||||
aldeed:simple-schema # Third party package to deal with schemas
|
||||
|
||||
@ -63,11 +63,8 @@ mongo-id@1.0.7
|
||||
natestrauser:select2@4.0.3
|
||||
npm-mongo@3.1.2-beta181.7
|
||||
observe-sequence@1.0.16
|
||||
ohif:core@0.0.1
|
||||
ohif:cornerstone@0.0.1
|
||||
ohif:hanging-protocols@0.0.1
|
||||
ohif:measurement-table@0.0.1
|
||||
ohif:measurements@0.0.1
|
||||
ohif:study-list@0.0.1
|
||||
ohif:themes@0.0.1
|
||||
ohif:themes-common@0.0.1
|
||||
|
||||
@ -1,4 +0,0 @@
|
||||
body
|
||||
background-color: black
|
||||
height: 100%
|
||||
width: 100%
|
||||
@ -1,4 +1,16 @@
|
||||
html,
|
||||
body,
|
||||
#root {
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
background-color: black;
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
body {
|
||||
box-sizing: border-box;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
@ -1,7 +1,7 @@
|
||||
import React, { Component } from 'react';
|
||||
import { withRouter } from 'react-router';
|
||||
import { Route, Switch } from 'react-router-dom';
|
||||
import { OHIF } from 'meteor/ohif:core';
|
||||
import { OHIF } from 'ohif-core';
|
||||
import ViewerRouting from "./ViewerRouting.js";
|
||||
import IHEInvokeImageDisplay from './IHEInvokeImageDisplay.js';
|
||||
import './App.css';
|
||||
@ -20,6 +20,11 @@ function setContext(context) {
|
||||
|
||||
class App extends Component {
|
||||
componentDidMount() {
|
||||
// Temporary until the rest of the UI is in React
|
||||
window.router = {
|
||||
history: this.props.history
|
||||
};
|
||||
|
||||
this.unlisten = this.props.history.listen((location, action) => {
|
||||
setContext(window.location.pathname);
|
||||
});
|
||||
|
||||
@ -1,7 +1,46 @@
|
||||
import React, {Component} from "react";
|
||||
import PropTypes from "prop-types";
|
||||
import Viewer from "./viewer/viewer.js";
|
||||
import { OHIF } from 'meteor/ohif:core';
|
||||
import { OHIF } from 'ohif-core';
|
||||
|
||||
function createDisplaySets(studies) {
|
||||
// Define the OHIF.viewer.data global object
|
||||
OHIF.viewer.data = OHIF.viewer.data || {};
|
||||
|
||||
// @TypeSafeStudies
|
||||
// Clears OHIF.viewer.Studies collection
|
||||
OHIF.viewer.Studies.removeAll();
|
||||
|
||||
// @TypeSafeStudies
|
||||
// Clears OHIF.viewer.StudyMetadataList collection
|
||||
OHIF.viewer.StudyMetadataList.removeAll();
|
||||
|
||||
OHIF.viewer.data.studyInstanceUids = [];
|
||||
|
||||
const updatedStudies = studies.map(study => {
|
||||
const studyMetadata = new OHIF.metadata.OHIFStudyMetadata(study, study.studyInstanceUid);
|
||||
let displaySets = study.displaySets;
|
||||
|
||||
if (!study.displaySets) {
|
||||
displaySets = OHIF.viewerbase.sortingManager.getDisplaySets(studyMetadata);
|
||||
study.displaySets = displaySets;
|
||||
}
|
||||
|
||||
studyMetadata.setDisplaySets(displaySets);
|
||||
|
||||
study.selected = true;
|
||||
OHIF.viewer.Studies.insert(study);
|
||||
OHIF.viewer.StudyMetadataList.insert(studyMetadata);
|
||||
OHIF.viewer.data.studyInstanceUids.push(study.studyInstanceUid);
|
||||
|
||||
// Updates WADO-RS metaDataManager
|
||||
OHIF.viewerbase.updateMetaDataManager(study);
|
||||
|
||||
return study;
|
||||
});
|
||||
|
||||
return updatedStudies;
|
||||
}
|
||||
|
||||
class ViewerFromStudyData extends Component {
|
||||
constructor(props) {
|
||||
@ -25,8 +64,11 @@ class ViewerFromStudyData extends Component {
|
||||
// Render the viewer when the data is ready
|
||||
promise.then(({ studies, viewerData }) => {
|
||||
OHIF.viewer.data = viewerData;
|
||||
|
||||
const updatedStudies = createDisplaySets(studies);
|
||||
|
||||
this.setState({
|
||||
studies,
|
||||
studies: updatedStudies,
|
||||
});
|
||||
}).catch(error => {
|
||||
this.setState({
|
||||
@ -50,7 +92,7 @@ class ViewerFromStudyData extends Component {
|
||||
}
|
||||
|
||||
ViewerFromStudyData.propTypes = {
|
||||
studyInstanceUids: PropTypes.array,
|
||||
studyInstanceUids: PropTypes.array.isRequired,
|
||||
seriesInstanceUids: PropTypes.array
|
||||
};
|
||||
|
||||
|
||||
@ -20,4 +20,13 @@ function ViewerRouting({ match }) {
|
||||
);
|
||||
}
|
||||
|
||||
ViewerRouting.propTypes = {
|
||||
match: PropTypes.shape({
|
||||
params: PropTypes.shape({
|
||||
studyInstanceUids: PropTypes.string.isRequired,
|
||||
seriesInstanceUids: PropTypes.string
|
||||
})
|
||||
})
|
||||
};
|
||||
|
||||
export default ViewerRouting;
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
import React, { Component } from 'react';
|
||||
import PropTypes from 'prop-types';
|
||||
import { OHIF } from 'meteor/ohif:core';
|
||||
import { OHIF } from 'ohif-core';
|
||||
import { Viewerbase } from 'meteor/ohif:viewerbase';
|
||||
import { StudyBrowser } from 'react-viewerbase';
|
||||
|
||||
|
||||
@ -4,9 +4,9 @@ import { BrowserRouter } from 'react-router-dom';
|
||||
import { Provider } from 'react-redux';
|
||||
import { createStore } from 'redux';
|
||||
import App from './App.js';
|
||||
import { OHIF } from 'meteor/ohif:core';
|
||||
import { OHIF } from 'ohif-core';
|
||||
|
||||
const store = createStore(OHIF.viewerbase.redux.combinedReducer);
|
||||
const store = createStore(OHIF.redux.combinedReducer);
|
||||
|
||||
// TODO[react] Use a provider when the whole tree is React
|
||||
window.store = store;
|
||||
|
||||
@ -1,8 +1,7 @@
|
||||
import { Meteor } from 'meteor/meteor';
|
||||
import { Template } from 'meteor/templating';
|
||||
import { Session } from 'meteor/session';
|
||||
import { ReactiveVar } from 'meteor/reactive-var';
|
||||
import { OHIF } from 'meteor/ohif:core';
|
||||
import { OHIF } from 'ohif-core';
|
||||
|
||||
import Viewer from '../viewer/viewer.js';
|
||||
|
||||
@ -61,18 +60,8 @@ Template.ohifViewer.onCreated(() => {
|
||||
});
|
||||
|
||||
Template.ohifViewer.events({
|
||||
'click .js-toggle-studyList'(event, instance) {
|
||||
'click .js-toggle-studyList'(event) {
|
||||
event.preventDefault();
|
||||
const isViewer = Session.get('ViewerOpened');
|
||||
|
||||
/*if (isViewer) {
|
||||
Router.go('studylist');
|
||||
} else {
|
||||
const { studyInstanceUids } = OHIF.viewer.data;
|
||||
if (studyInstanceUids) {
|
||||
Router.go('viewerStudies', { studyInstanceUids });
|
||||
}
|
||||
}*/
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
import { Template } from 'meteor/templating';
|
||||
import $ from 'jquery';
|
||||
|
||||
import { OHIF } from 'meteor/ohif:core';
|
||||
import { OHIF } from 'ohif-core';
|
||||
import 'meteor/ohif:viewerbase';
|
||||
|
||||
function isThereSeries(studies) {
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
import React, { Component } from "react";
|
||||
import PropTypes from "prop-types";
|
||||
|
||||
import { OHIF } from 'meteor/ohif:core';
|
||||
import { OHIF } from 'ohif-core';
|
||||
import { MeasurementTable } from 'meteor/ohif:measurement-table';
|
||||
|
||||
import { CineDialog } from 'react-viewerbase';
|
||||
@ -79,51 +79,17 @@ class Viewer extends Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
|
||||
// Define the OHIF.viewer.data global object
|
||||
OHIF.viewer.data = OHIF.viewer.data || {};
|
||||
|
||||
// @TypeSafeStudies
|
||||
// Clears OHIF.viewer.Studies collection
|
||||
OHIF.viewer.Studies.removeAll();
|
||||
|
||||
// @TypeSafeStudies
|
||||
// Clears OHIF.viewer.StudyMetadataList collection
|
||||
OHIF.viewer.StudyMetadataList.removeAll();
|
||||
|
||||
OHIF.viewer.data.studyInstanceUids = [];
|
||||
|
||||
const studies = this.props.studies;
|
||||
studies.forEach(study => {
|
||||
const studyMetadata = new OHIF.metadata.StudyMetadata(study, study.studyInstanceUid);
|
||||
let displaySets = study.displaySets;
|
||||
|
||||
if (!study.displaySets) {
|
||||
displaySets = OHIF.viewerbase.sortingManager.getDisplaySets(studyMetadata);
|
||||
study.displaySets = displaySets;
|
||||
}
|
||||
|
||||
studyMetadata.setDisplaySets(displaySets);
|
||||
|
||||
study.selected = true;
|
||||
OHIF.viewer.Studies.insert(study);
|
||||
OHIF.viewer.StudyMetadataList.insert(studyMetadata);
|
||||
OHIF.viewer.data.studyInstanceUids.push(study.studyInstanceUid);
|
||||
|
||||
// Updates WADO-RS metaDataManager
|
||||
OHIF.viewerbase.updateMetaDataManager(study);
|
||||
});
|
||||
|
||||
this.state = {
|
||||
leftSidebar: 'studies',
|
||||
rightSidebar: 'measurements',
|
||||
studies
|
||||
studies: this.props.studies
|
||||
};
|
||||
}
|
||||
|
||||
render() {
|
||||
return (<>
|
||||
<div className='viewerDialogs'>
|
||||
<CineDialog/>
|
||||
{/*<CineDialog/>*/}
|
||||
</div>
|
||||
<div id="viewer" className='Viewer'>
|
||||
{/*<ToolbarSection/>*/}
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
import { Meteor } from 'meteor/meteor';
|
||||
import { OHIF } from 'meteor/ohif:core';
|
||||
import { OHIF } from 'ohif-core';
|
||||
import { cornerstoneWADOImageLoader } from 'meteor/ohif:cornerstone';
|
||||
import sha from './sha.js';
|
||||
import version from './version.js';
|
||||
|
||||
@ -1,52 +0,0 @@
|
||||
import { Meteor } from "meteor/meteor";
|
||||
//import { Router } from 'meteor/clinical:router';
|
||||
import { OHIF } from 'meteor/ohif:core';
|
||||
|
||||
/*Router.configure({
|
||||
layoutTemplate: 'layout',
|
||||
});
|
||||
|
||||
|
||||
Router.onBeforeAction('loading');
|
||||
|
||||
Router.route('/', function() {
|
||||
Router.go('studylist', {}, { replaceState: true });
|
||||
}, { name: 'home' });
|
||||
|
||||
Router.route('/studylist', function() {
|
||||
this.render('ohifViewer', { data: { template: 'studylist' } });
|
||||
}, { name: 'studylist' });
|
||||
|
||||
Router.route('/viewer/:studyInstanceUids', function() {
|
||||
const studyInstanceUids = this.params.studyInstanceUids.split(';');
|
||||
OHIF.viewerbase.renderViewer(this, { studyInstanceUids }, 'ohifViewer');
|
||||
}, { name: 'viewerStudies' });
|
||||
|
||||
// OHIF #98 Show specific series of study
|
||||
Router.route('/study/:studyInstanceUid/series/:seriesInstanceUids', function () {
|
||||
const studyInstanceUid = this.params.studyInstanceUid;
|
||||
const seriesInstanceUids = this.params.seriesInstanceUids.split(';');
|
||||
OHIF.viewerbase.renderViewer(this, { studyInstanceUids: [studyInstanceUid], seriesInstanceUids }, 'ohifViewer');
|
||||
}, { name: 'viewerSeries' });
|
||||
|
||||
Router.route('/IHEInvokeImageDisplay', function() {
|
||||
const requestType = this.params.query.requestType;
|
||||
|
||||
if (requestType === "STUDY") {
|
||||
const studyInstanceUids = this.params.query.studyUID.split(';');
|
||||
|
||||
OHIF.viewerbase.renderViewer(this, {studyInstanceUids}, 'ohifViewer');
|
||||
} else if (requestType === "STUDYBASE64") {
|
||||
const uids = this.params.query.studyUID;
|
||||
const decodedData = window.atob(uids);
|
||||
const studyInstanceUids = decodedData.split(';');
|
||||
|
||||
OHIF.viewerbase.renderViewer(this, {studyInstanceUids}, 'ohifViewer');
|
||||
} else if (requestType === "PATIENT") {
|
||||
const patientUids = this.params.query.patientID.split(';');
|
||||
|
||||
Router.go('studylist', {}, {replaceState: true});
|
||||
} else {
|
||||
Router.go('studylist', {}, {replaceState: true});
|
||||
}
|
||||
});*/
|
||||
5
OHIFViewer/package-lock.json
generated
5
OHIFViewer/package-lock.json
generated
@ -4159,8 +4159,9 @@
|
||||
}
|
||||
},
|
||||
"react-viewerbase": {
|
||||
"version": "git://github.com/OHIF/react-viewerbase.git#af26417b7c1da75b713f70b38c9dc3ce29e5c359",
|
||||
"from": "git://github.com/OHIF/react-viewerbase.git",
|
||||
"version": "0.1.2",
|
||||
"resolved": "https://registry.npmjs.org/react-viewerbase/-/react-viewerbase-0.1.2.tgz",
|
||||
"integrity": "sha512-ibhnYNe6eVavzZGPN9s/gzRJ7cnkYz8nGMesjH6nigVDdkYgQTCnHzC1laJRFQBgeoNlsd9uKPyvOwjD9ftVuA==",
|
||||
"requires": {
|
||||
"classnames": "^2.2.6"
|
||||
}
|
||||
|
||||
@ -16,7 +16,7 @@
|
||||
"react-dom": "^16.6.3",
|
||||
"react-redux": "^6.0.0",
|
||||
"react-router-dom": "^4.3.1",
|
||||
"react-viewerbase": "git://github.com:OHIF/react-viewerbase.git",
|
||||
"react-viewerbase": "^0.1.2",
|
||||
"redux": "^4.0.1",
|
||||
"underscore": "1.9.1"
|
||||
},
|
||||
|
||||
@ -1,5 +0,0 @@
|
||||
import { OHIF } from 'meteor/ohif:core';
|
||||
|
||||
OHIF.servers = {
|
||||
collections: {}
|
||||
};
|
||||
@ -1,6 +0,0 @@
|
||||
import { OHIF } from 'meteor/ohif:core';
|
||||
import classes from './classes/';
|
||||
|
||||
OHIF.classes = classes;
|
||||
|
||||
export default classes;
|
||||
@ -1,113 +0,0 @@
|
||||
import { ReactiveVar } from 'meteor/reactive-var';
|
||||
import _ from 'underscore';
|
||||
import { OHIF } from 'meteor/ohif:core';
|
||||
|
||||
export class CommandsManager {
|
||||
constructor() {
|
||||
this.contexts = {};
|
||||
|
||||
// Enable reactivity by storing the last executed command
|
||||
this.last = new ReactiveVar('');
|
||||
}
|
||||
|
||||
getContext(contextName) {
|
||||
const context = this.contexts[contextName];
|
||||
if (!context) {
|
||||
return OHIF.log.warn(`No context found with name "${contextName}"`);
|
||||
}
|
||||
|
||||
return context;
|
||||
}
|
||||
|
||||
getCurrentContext() {
|
||||
const contextName = OHIF.context.get();
|
||||
if (!contextName) {
|
||||
return OHIF.log.warn('There is no selected context');
|
||||
}
|
||||
|
||||
return this.getContext(contextName);
|
||||
}
|
||||
|
||||
createContext(contextName) {
|
||||
if (!contextName) return;
|
||||
if (this.contexts[contextName]) {
|
||||
return this.clear(contextName);
|
||||
}
|
||||
|
||||
this.contexts[contextName] = {};
|
||||
}
|
||||
|
||||
set(contextName, definitions, extend=false) {
|
||||
if (typeof definitions !== 'object') return;
|
||||
const context = this.getContext(contextName);
|
||||
if (!context) return;
|
||||
|
||||
if (!extend) {
|
||||
this.clear(contextName);
|
||||
}
|
||||
|
||||
Object.keys(definitions).forEach(command => (context[command] = definitions[command]));
|
||||
}
|
||||
|
||||
register(contextName, command, definition) {
|
||||
if (typeof definition !== 'object') return;
|
||||
const context = this.getContext(contextName);
|
||||
if (!context) return;
|
||||
|
||||
context[command] = definition;
|
||||
}
|
||||
|
||||
setDisabledFunction(contextName, command, func) {
|
||||
if (!command || typeof func !== 'function') return;
|
||||
const context = this.getContext(contextName);
|
||||
if (!context) return;
|
||||
const definition = context[command];
|
||||
if (!definition) {
|
||||
return OHIF.log.warn(`Trying to set a disabled function to a command "${command}" that was not yet defined`);
|
||||
}
|
||||
|
||||
definition.disabled = func;
|
||||
}
|
||||
|
||||
clear(contextName) {
|
||||
if (!contextName) return;
|
||||
this.contexts[contextName] = {};
|
||||
}
|
||||
|
||||
getDefinition(command) {
|
||||
const context = this.getCurrentContext();
|
||||
if (!context) return;
|
||||
return context[command];
|
||||
}
|
||||
|
||||
isDisabled(command) {
|
||||
const definition = this.getDefinition(command);
|
||||
if (!definition) return false;
|
||||
const { disabled } = definition;
|
||||
if (_.isFunction(disabled) && disabled()) return true;
|
||||
if (!_.isFunction(disabled) && disabled) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
run(command) {
|
||||
const definition = this.getDefinition(command);
|
||||
if (!definition) {
|
||||
return OHIF.log.warn(`Command "${command}" not found in current context`);
|
||||
}
|
||||
|
||||
const { action, params } = definition;
|
||||
if (this.isDisabled(command)) return;
|
||||
if (typeof action !== 'function') {
|
||||
return OHIF.log.warn(`No action was defined for command "${command}"`);
|
||||
} else {
|
||||
const result = action(params);
|
||||
if (this.last.get() === command) {
|
||||
this.last.dep.changed();
|
||||
} else {
|
||||
this.last.set(command);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,65 +0,0 @@
|
||||
import { OHIF } from 'meteor/ohif:core';
|
||||
|
||||
export class HotkeysContext {
|
||||
constructor(name, definitions, enabled) {
|
||||
this.name = name;
|
||||
this.definitions = Object.assign({}, definitions);
|
||||
this.enabled = enabled;
|
||||
}
|
||||
|
||||
extend(definitions={}) {
|
||||
if (typeof definitions !== 'object') return;
|
||||
this.definitions = Object.assign({}, definitions);
|
||||
Object.keys(definitions).forEach(command => {
|
||||
const hotkey = definitions[command];
|
||||
this.unregister(command);
|
||||
if (hotkey) {
|
||||
this.register(command, hotkey);
|
||||
}
|
||||
|
||||
this.definitions[command] = hotkey;
|
||||
});
|
||||
}
|
||||
|
||||
register(command, hotkey) {
|
||||
if (!hotkey) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!command) {
|
||||
return OHIF.log.warn(`No command was defined for hotkey "${hotkey}"`);
|
||||
}
|
||||
|
||||
const bindingKey = `keydown.hotkey.${this.name}.${command}`;
|
||||
const bind = hotkey => $(document).bind(bindingKey, hotkey, event => {
|
||||
if (!this.enabled.get()) return;
|
||||
OHIF.commands.run(command);
|
||||
event.preventDefault();
|
||||
});
|
||||
|
||||
if (hotkey instanceof Array) {
|
||||
hotkey.forEach(hotkey => bind(hotkey));
|
||||
} else {
|
||||
bind(hotkey);
|
||||
}
|
||||
}
|
||||
|
||||
unregister(command) {
|
||||
const bindingKey = `keydown.hotkey.${this.name}.${command}`;
|
||||
if (this.definitions[command]) {
|
||||
$(document).unbind(bindingKey);
|
||||
delete this.definitions[command];
|
||||
}
|
||||
}
|
||||
|
||||
initialize() {
|
||||
Object.keys(this.definitions).forEach(command => {
|
||||
const hotkey = this.definitions[command];
|
||||
this.register(command, hotkey);
|
||||
});
|
||||
}
|
||||
|
||||
destroy() {
|
||||
$(document).unbind(`keydown.hotkey.${this.name}`);
|
||||
}
|
||||
}
|
||||
@ -1,159 +0,0 @@
|
||||
import { Meteor } from 'meteor/meteor';
|
||||
import { ReactiveVar } from 'meteor/reactive-var';
|
||||
import { Tracker } from 'meteor/tracker';
|
||||
import { Session } from 'meteor/session';
|
||||
import { OHIF } from 'meteor/ohif:core';
|
||||
import { HotkeysContext } from './HotkeysContext';
|
||||
|
||||
export class HotkeysManager {
|
||||
constructor() {
|
||||
this.contexts = {};
|
||||
this.defaults = {};
|
||||
this.currentContextName = null;
|
||||
this.enabled = new ReactiveVar(true);
|
||||
this.retrieveFunction = null;
|
||||
this.storeFunction = null;
|
||||
this.changeObserver = new Tracker.Dependency();
|
||||
|
||||
Tracker.autorun(() => {
|
||||
const contextName = OHIF.context.get();
|
||||
|
||||
// Avoind falling in MongoDB collections reactivity
|
||||
Tracker.nonreactive(() => this.switchToContext(contextName));
|
||||
});
|
||||
}
|
||||
|
||||
setRetrieveFunction(retrieveFunction) {
|
||||
this.retrieveFunction = retrieveFunction;
|
||||
}
|
||||
|
||||
setStoreFunction(storeFunction) {
|
||||
this.storeFunction = storeFunction;
|
||||
}
|
||||
|
||||
store(contextName, definitions) {
|
||||
const storageKey = `hotkeysDefinitions.${contextName}`;
|
||||
return new Promise((resolve, reject) => {
|
||||
if (this.storeFunction) {
|
||||
this.storeFunction.call(this, storageKey, definitions).then(resolve).catch(reject);
|
||||
} else if (OHIF.user.userLoggedIn()) {
|
||||
OHIF.user.setData(storageKey, definitions).then(resolve).catch(reject);
|
||||
} else {
|
||||
const definitionsJSON = JSON.stringify(definitions);
|
||||
localStorage.setItem(storageKey, definitionsJSON);
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
retrieve(contextName) {
|
||||
const storageKey = `hotkeysDefinitions.${contextName}`;
|
||||
return new Promise((resolve, reject) => {
|
||||
if (this.retrieveFunction) {
|
||||
this.retrieveFunction(contextName).then(resolve).catch(reject);
|
||||
} else if (OHIF.user.userLoggedIn()) {
|
||||
try {
|
||||
resolve(OHIF.user.getData(storageKey));
|
||||
} catch(error) {
|
||||
reject(error);
|
||||
}
|
||||
} else {
|
||||
const definitionsJSON = localStorage.getItem(storageKey) || '';
|
||||
const definitions = JSON.parse(definitionsJSON) || undefined;
|
||||
resolve(definitions);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
disable() {
|
||||
this.enabled.set(false);
|
||||
}
|
||||
|
||||
enable() {
|
||||
this.enabled.set(true);
|
||||
}
|
||||
|
||||
getContext(contextName) {
|
||||
return this.contexts[contextName];
|
||||
}
|
||||
|
||||
getCurrentContext() {
|
||||
return this.getContext(this.currentContextName);
|
||||
}
|
||||
|
||||
load(contextName) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const context = this.getContext(contextName);
|
||||
if (!context) return reject();
|
||||
this.retrieve(contextName).then(defs => {
|
||||
const definitions = defs || this.defaults[contextName];
|
||||
if (!definitions) {
|
||||
this.changeObserver.changed();
|
||||
return reject();
|
||||
}
|
||||
|
||||
context.destroy();
|
||||
context.definitions = definitions;
|
||||
context.initialize();
|
||||
this.changeObserver.changed();
|
||||
resolve(definitions);
|
||||
}).catch(reject);
|
||||
});
|
||||
}
|
||||
|
||||
set(contextName, contextDefinitions, isDefaultDefinitions=false) {
|
||||
const enabled = this.enabled;
|
||||
const context = new HotkeysContext(contextName, contextDefinitions, enabled);
|
||||
const currentContext = this.getCurrentContext();
|
||||
if (currentContext && currentContext.name === contextName) {
|
||||
currentContext.destroy();
|
||||
context.initialize();
|
||||
}
|
||||
|
||||
this.contexts[contextName] = context;
|
||||
if (isDefaultDefinitions) {
|
||||
this.defaults[contextName] = contextDefinitions;
|
||||
}
|
||||
}
|
||||
|
||||
register(contextName, command, hotkey) {
|
||||
if (!command || !hotkey) return;
|
||||
const context = this.getContext(contextName);
|
||||
if (!context) {
|
||||
this.set(contextName, {});
|
||||
}
|
||||
|
||||
context.register(command, hotkey);
|
||||
}
|
||||
|
||||
unsetContext(contextName) {
|
||||
if (contextName === this.currentContextName) {
|
||||
this.getCurrentContext().destroy();
|
||||
}
|
||||
|
||||
delete this.contexts[contextName];
|
||||
delete this.defaults[contextName];
|
||||
}
|
||||
|
||||
resetDefaults(contextName) {
|
||||
const context = this.getContext(contextName);
|
||||
const definitions = this.defaults[contextName];
|
||||
if (!context || !definitions) return;
|
||||
context.extend(definitions);
|
||||
return this.store(contextName, definitions);
|
||||
}
|
||||
|
||||
switchToContext(contextName) {
|
||||
const currentContext = this.getCurrentContext();
|
||||
if (currentContext) {
|
||||
currentContext.destroy();
|
||||
}
|
||||
|
||||
const newContext = this.contexts[contextName];
|
||||
if (!newContext) return;
|
||||
|
||||
this.currentContextName = contextName;
|
||||
newContext.initialize();
|
||||
this.load(contextName).catch(() => {});
|
||||
}
|
||||
}
|
||||
@ -1,69 +0,0 @@
|
||||
import { OHIF } from 'meteor/ohif:core';
|
||||
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).
|
||||
*/
|
||||
export 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: OHIF.utils.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);
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,354 +0,0 @@
|
||||
import { cornerstoneMath } from 'meteor/ohif:cornerstone';
|
||||
import { parsingUtils } from '../lib/parsingUtils';
|
||||
|
||||
const FUNCTION = 'function';
|
||||
|
||||
export 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:
|
||||
new cornerstoneMath.Vector3(parseFloat(imageOrientation[0]), parseFloat(imageOrientation[1]), parseFloat(imageOrientation[2])),
|
||||
columnCosines:
|
||||
new cornerstoneMath.Vector3(parseFloat(imageOrientation[3]), parseFloat(imageOrientation[4]), parseFloat(imageOrientation[5])),
|
||||
imagePositionPatient:
|
||||
new cornerstoneMath.Vector3(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 'imagePlane'. These types
|
||||
* are keys in the stored metadata objects.
|
||||
*
|
||||
* @param type
|
||||
* @param imageId
|
||||
* @returns {Object} Relevant metadata of the specified type
|
||||
*/
|
||||
provider(type, imageId) {
|
||||
// TODO: Cornerstone Tools use 'imagePlaneModule', but OHIF use 'imagePlane'. It must be consistent.
|
||||
if (type === 'imagePlaneModule') {
|
||||
type = 'imagePlane';
|
||||
}
|
||||
|
||||
const imageMetadata = this.metadataLookup.get(imageId);
|
||||
if (!imageMetadata) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (imageMetadata.hasOwnProperty(type)) {
|
||||
return imageMetadata[type];
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,14 +0,0 @@
|
||||
// @TODO: improve this object
|
||||
/**
|
||||
* Objects to be used to throw errors, specially
|
||||
* in Trackers functions (afterFlush, Flush).
|
||||
*/
|
||||
export class OHIFError extends Error {
|
||||
|
||||
constructor(message) {
|
||||
super();
|
||||
this.message = message;
|
||||
this.stack = (new Error()).stack;
|
||||
this.name = this.constructor.name;
|
||||
}
|
||||
}
|
||||
@ -1,74 +0,0 @@
|
||||
import { OHIF } from 'meteor/ohif:core';
|
||||
|
||||
// Important metadata classes
|
||||
const { OHIFError, metadata } = OHIF.viewerbase;
|
||||
const { StudySummary, StudyMetadata } = metadata;
|
||||
|
||||
export class OHIFStudyMetadataSource extends OHIF.viewerbase.StudyMetadataSource {
|
||||
|
||||
/**
|
||||
* Get study metadata for a study with given study InstanceUID
|
||||
* @param {String} studyInstanceUID Study InstanceUID
|
||||
* @return {Promise} A Promise object
|
||||
*/
|
||||
getByInstanceUID(studyInstanceUID) {
|
||||
return OHIF.studies.retrieveStudyMetadata(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 OHIF.metadata.StudyMetadata(studyInfo, studyInfo.studyInstanceUid);
|
||||
|
||||
// Get Study display sets
|
||||
const displaySets = OHIF.viewerbase.sortingManager.getDisplaySets(studyMetadata);
|
||||
|
||||
// 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();
|
||||
|
||||
// Insert new study info object in Studies TypeSafeCollection
|
||||
OHIF.viewer.Studies.insert(studyInfo);
|
||||
|
||||
// Insert new study metadata in StudyMetadataList TypeSafeCollection
|
||||
OHIF.viewer.StudyMetadataList.insert(studyMetadata);
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,52 +0,0 @@
|
||||
import { OHIF } from 'meteor/ohif:core';
|
||||
import 'meteor/ohif:viewerbase';
|
||||
|
||||
/**
|
||||
* Constants
|
||||
*/
|
||||
|
||||
const STRING = 'string';
|
||||
const propertyReplacementMap = {
|
||||
modalities: 'ModalitiesInStudy',
|
||||
patientBirthdate: 'PatientBirthDate'
|
||||
};
|
||||
|
||||
/**
|
||||
* OHIF Viewers specialized version of StudySummary class
|
||||
*/
|
||||
export class OHIFStudySummary extends OHIF.viewerbase.metadata.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;
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,167 +0,0 @@
|
||||
# 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 { OHIF } from 'meteor/ohif:core';
|
||||
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' ] ]
|
||||
});
|
||||
|
||||
```
|
||||
@ -1,151 +0,0 @@
|
||||
import { Session } from 'meteor/session';
|
||||
import $ from 'jquery';
|
||||
import { OHIF } from 'meteor/ohif:core';
|
||||
//import { getInstanceClassDefaultViewport } from '../instanceClassSpecificViewport';
|
||||
|
||||
// Manage resizing viewports triggered by window resize
|
||||
export class ResizeViewportManager {
|
||||
constructor() {
|
||||
this._resizeHandler = null;
|
||||
}
|
||||
|
||||
// Reposition Study Series Quick Switch based whether side bars are opened or not
|
||||
repositionStudySeriesQuickSwitch() {
|
||||
OHIF.log.info('ResizeViewportManager repositionStudySeriesQuickSwitch');
|
||||
|
||||
// Stop here if viewer is not displayed
|
||||
const isViewer = Session.get('ViewerOpened');
|
||||
if (!isViewer) return;
|
||||
|
||||
// Stop here if there is no one or only one viewport
|
||||
const nViewports = OHIF.viewerbase.layoutManager.viewportData.length;
|
||||
if (!nViewports || nViewports <= 1) return;
|
||||
|
||||
const $viewer = $('#viewer');
|
||||
const leftSidebar = $viewer.find('.sidebar-left.sidebar-open');
|
||||
const rightSidebar = $viewer.find('.sidebar-right.sidebar-open');
|
||||
|
||||
const $leftQuickSwitch = $('.quickSwitchWrapper.left');
|
||||
const $rightQuickSwitch = $('.quickSwitchWrapper.right');
|
||||
|
||||
const hasLeftSidebar = leftSidebar.length > 0;
|
||||
const hasRightSidebar = rightSidebar.length > 0;
|
||||
|
||||
$rightQuickSwitch.removeClass('left-sidebar-only');
|
||||
$leftQuickSwitch.removeClass('right-sidebar-only');
|
||||
|
||||
let leftOffset = 0;
|
||||
|
||||
if (hasLeftSidebar) {
|
||||
leftOffset = (leftSidebar.width() / $(window).width()) * 100;
|
||||
|
||||
if (!hasRightSidebar) {
|
||||
$rightQuickSwitch.addClass('left-sidebar-only');
|
||||
}
|
||||
}
|
||||
|
||||
if (hasRightSidebar && !hasLeftSidebar) {
|
||||
$leftQuickSwitch.addClass('right-sidebar-only');
|
||||
}
|
||||
|
||||
const leftPosition = (($('#imageViewerViewports').width() / nViewports) / $(window).width()) * 100 + leftOffset;
|
||||
const rightPosition = 100 - leftPosition;
|
||||
|
||||
$leftQuickSwitch.css('right', rightPosition + '%');
|
||||
$rightQuickSwitch.css('left', leftPosition + '%');
|
||||
}
|
||||
|
||||
// Relocate dialogs positions
|
||||
relocateDialogs(){
|
||||
OHIF.log.info('ResizeViewportManager relocateDialogs');
|
||||
|
||||
const $bottomRightDialogs = $('#annotationDialog, #textMarkerOptionsDialog');
|
||||
$bottomRightDialogs.css({
|
||||
top: '', // This removes the CSS property completely
|
||||
left: '',
|
||||
bottom: 0,
|
||||
right: 0
|
||||
});
|
||||
|
||||
const centerDialogs = $('.draggableDialog').not($bottomRightDialogs);
|
||||
|
||||
centerDialogs.css({
|
||||
top: 0,
|
||||
left: 0,
|
||||
bottom: 0,
|
||||
right: 0
|
||||
});
|
||||
}
|
||||
|
||||
// Resize viewport scrollbars
|
||||
resizeScrollbars(element) {
|
||||
OHIF.log.info('ResizeViewportManager resizeScrollbars');
|
||||
|
||||
const $currentOverlay = $(element).siblings('.imageViewerViewportOverlay');
|
||||
$currentOverlay.find('.scrollbar').trigger('rescale');
|
||||
}
|
||||
|
||||
// Resize a single viewport element
|
||||
resizeViewportElement(element, fitToWindow = true) {
|
||||
let enabledElement;
|
||||
try {
|
||||
enabledElement = cornerstone.getEnabledElement(element);
|
||||
} catch(error) {
|
||||
return;
|
||||
}
|
||||
|
||||
cornerstone.resize(element, fitToWindow);
|
||||
|
||||
/*if (enabledElement.fitToWindow === false) {
|
||||
const imageId = enabledElement.image.imageId;
|
||||
const instance = cornerstone.metaData.get('instance', imageId);
|
||||
const instanceClassViewport = getInstanceClassDefaultViewport(instance, enabledElement, imageId);
|
||||
cornerstone.setViewport(element, instanceClassViewport);
|
||||
}*/
|
||||
}
|
||||
|
||||
// Resize each viewport element
|
||||
resizeViewportElements() {
|
||||
this.relocateDialogs();
|
||||
|
||||
setTimeout(() => {
|
||||
this.repositionStudySeriesQuickSwitch();
|
||||
|
||||
const elements = $('.imageViewerViewport').not('.empty');
|
||||
elements.each((index, element) => {
|
||||
this.resizeViewportElement(element);
|
||||
this.resizeScrollbars(element);
|
||||
});
|
||||
}, 1);
|
||||
}
|
||||
|
||||
// Function to override resizeViewportElements function
|
||||
setResizeViewportElement(resizeViewportElements) {
|
||||
this.resizeViewportElements = resizeViewportElements;
|
||||
}
|
||||
|
||||
// Avoid doing DOM manipulation during the resize handler
|
||||
// because it is fired very often.
|
||||
// Resizing is therefore performed 100 ms after the resize event stops.
|
||||
handleResize() {
|
||||
clearTimeout(this.resizeTimer);
|
||||
this.resizeTimer = setTimeout(() => {
|
||||
OHIF.log.info('ResizeViewportManager resizeViewportElements');
|
||||
this.resizeViewportElements();
|
||||
}, 100);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a unique event handler function associated with a given instance using lazy assignment.
|
||||
* @return {function} Returns a unique copy of the event handler of this class.
|
||||
*/
|
||||
getResizeHandler() {
|
||||
let resizeHandler = this._resizeHandler;
|
||||
if (resizeHandler === null) {
|
||||
resizeHandler = this.handleResize.bind(this);
|
||||
this._resizeHandler = resizeHandler;
|
||||
}
|
||||
|
||||
return resizeHandler;
|
||||
}
|
||||
}
|
||||
@ -1,218 +0,0 @@
|
||||
import { Session } from 'meteor/session';
|
||||
import $ from 'jquery';
|
||||
import { OHIF } from 'meteor/ohif:core';
|
||||
import { cornerstone, cornerstoneTools } from 'meteor/ohif:cornerstone';
|
||||
import { toolManager } from '../toolManager';
|
||||
|
||||
export class StackImagePositionOffsetSynchronizer {
|
||||
constructor() {
|
||||
this.active = false;
|
||||
this.syncedViewports = [];
|
||||
this.synchronizer = new cornerstoneTools.Synchronizer('cornerstonenewimage', cornerstoneTools.stackImagePositionOffsetSynchronizer);
|
||||
}
|
||||
|
||||
static get ELEMENT_DISABLED_EVENT() {
|
||||
return 'cornerstoneelementdisabled.StackImagePositionOffsetSynchronizer';
|
||||
}
|
||||
|
||||
isActive() {
|
||||
return this.active;
|
||||
}
|
||||
|
||||
activate() {
|
||||
const viewports = this.getLinkableViewports();
|
||||
this.syncViewports(viewports);
|
||||
}
|
||||
|
||||
activateByViewportIndexes(viewportIndexes) {
|
||||
const viewports = this.getViewportByIndexes(viewportIndexes);
|
||||
this.syncViewports(viewports);
|
||||
}
|
||||
|
||||
deactivate() {
|
||||
if (!this.isActive()) {
|
||||
return;
|
||||
}
|
||||
|
||||
while (this.syncedViewports.length) {
|
||||
const viewport = this.syncedViewports[0];
|
||||
this.removeViewport(viewport);
|
||||
}
|
||||
|
||||
this.active = false;
|
||||
toolManager.deactivateCommandButton('linkStackScroll');
|
||||
}
|
||||
|
||||
update() {
|
||||
if (!this.isActive()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const activeViewportElement = this.getActiveViewportElement();
|
||||
|
||||
if (this.isViewportSynced(activeViewportElement)) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.deactivate();
|
||||
this.activate();
|
||||
}
|
||||
|
||||
syncViewports(viewports) {
|
||||
const viewportIndexes = [];
|
||||
|
||||
if (this.isActive() || (viewports.length <= 1)) {
|
||||
return;
|
||||
}
|
||||
|
||||
viewports.forEach((viewport, index) => {
|
||||
this.synchronizer.add(viewport.element);
|
||||
this.syncedViewports.push(viewport);
|
||||
viewportIndexes.push(viewport.index);
|
||||
if (!this.disabledListener) {
|
||||
this.disabledListener = this.elementDisabledHandler(this);
|
||||
}
|
||||
|
||||
viewport.element.addEventListener(StackImagePositionOffsetSynchronizer.ELEMENT_DISABLED_EVENT, this.disabledListener);
|
||||
});
|
||||
|
||||
this.active = true;
|
||||
toolManager.activateCommandButton('linkStackScroll');
|
||||
Session.set('StackImagePositionOffsetSynchronizerLinkedViewports', viewportIndexes);
|
||||
}
|
||||
|
||||
isViewportSynced(viewportElement) {
|
||||
return !!this.getViewportByElement(viewportElement);
|
||||
}
|
||||
|
||||
getActiveViewportElement() {
|
||||
const viewportIndex = window.store.getState().viewports.activeViewport || 0;
|
||||
return $('.imageViewerViewport').get(viewportIndex);
|
||||
}
|
||||
|
||||
removeViewport(viewport) {
|
||||
const index = this.syncedViewports.indexOf(viewport);
|
||||
|
||||
if (index === -1) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.syncedViewports.splice(index, 1);
|
||||
this.synchronizer.remove(viewport.element);
|
||||
this.removeLinkedViewportFromSession(viewport);
|
||||
viewport.element.removeEventListener(StackImagePositionOffsetSynchronizer.ELEMENT_DISABLED_EVENT, this.disabledListener);
|
||||
}
|
||||
|
||||
getViewportByElement(viewportElement) {
|
||||
const length = this.syncedViewports.length;
|
||||
|
||||
for (let i = 0; i < length; i++) {
|
||||
const viewport = this.syncedViewports[i];
|
||||
|
||||
if (viewport.element === viewportElement) {
|
||||
return viewport;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
removeViewportByElement(viewportElement) {
|
||||
let viewport = this.getViewportByElement(viewportElement);
|
||||
|
||||
if (viewport) {
|
||||
this.removeViewport(viewport);
|
||||
}
|
||||
}
|
||||
|
||||
removeLinkedViewportFromSession(viewport) {
|
||||
const linkedViewports = Session.get('StackImagePositionOffsetSynchronizerLinkedViewports');
|
||||
const index = linkedViewports.indexOf(viewport.index);
|
||||
|
||||
if (index !== -1) {
|
||||
linkedViewports.splice(index, 1);
|
||||
Session.set('StackImagePositionOffsetSynchronizerLinkedViewports', linkedViewports);
|
||||
}
|
||||
}
|
||||
|
||||
elementDisabledHandler(context) {
|
||||
return e => context.removeViewportByElement(e.detail.element);
|
||||
}
|
||||
|
||||
getViewportByIndexes(viewportIndexes) {
|
||||
const viewports = [];
|
||||
const $viewportElements = $('.imageViewerViewport');
|
||||
|
||||
viewportIndexes.forEach(index => {
|
||||
const element = $viewportElements.get(index);
|
||||
|
||||
if (!element) {
|
||||
return;
|
||||
}
|
||||
|
||||
viewports.push({
|
||||
index,
|
||||
element
|
||||
});
|
||||
});
|
||||
|
||||
return viewports;
|
||||
}
|
||||
|
||||
isViewportsLinkable(viewportElementA, viewportElementB) {
|
||||
const viewportAImageNormal = this.getViewportImageNormal(viewportElementA);
|
||||
const viewportBImageNormal = this.getViewportImageNormal(viewportElementB);
|
||||
|
||||
if (viewportAImageNormal && viewportBImageNormal) {
|
||||
const angleInRadians = viewportBImageNormal.angleTo(viewportAImageNormal);
|
||||
|
||||
// Pi / 12 radians = 15 degrees
|
||||
// If the angle between two vectors is Pi, it means they are just inverted
|
||||
return angleInRadians < Math.PI / 12 || angleInRadians === Math.PI;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
getLinkableViewports() {
|
||||
const activeViewportElement = this.getActiveViewportElement();
|
||||
const viewports = [];
|
||||
|
||||
$('.imageViewerViewport').each((index, viewportElement) => {
|
||||
if (this.isViewportsLinkable(activeViewportElement, viewportElement)) {
|
||||
viewports.push({
|
||||
index: index,
|
||||
element: viewportElement
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return viewports;
|
||||
}
|
||||
|
||||
getViewportImageNormal(element) {
|
||||
if (!element) {
|
||||
return;
|
||||
}
|
||||
|
||||
element = $(element).get(0);
|
||||
|
||||
try {
|
||||
const enabledElement = cornerstone.getEnabledElement(element);
|
||||
|
||||
if (!enabledElement.image) {
|
||||
return;
|
||||
}
|
||||
|
||||
const imageId = enabledElement.image.imageId;
|
||||
const imagePlane = cornerstone.metaData.get('imagePlane', imageId);
|
||||
|
||||
if (!imagePlane || !imagePlane.rowCosines || !imagePlane.columnCosines) {
|
||||
return;
|
||||
}
|
||||
|
||||
return imagePlane.rowCosines.clone().cross(imagePlane.columnCosines);
|
||||
} catch(error) {
|
||||
const errorMessage = error.message || error;
|
||||
OHIF.log.info(`StackImagePositionOffsetSynchronizer getViewportImageNormal: ${errorMessage}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,398 +0,0 @@
|
||||
import $ from 'jquery';
|
||||
import { Session } from 'meteor/session';
|
||||
import { OHIF } from 'meteor/ohif:core';
|
||||
import { cornerstone, cornerstoneWADOImageLoader } from 'meteor/ohif:cornerstone';
|
||||
|
||||
class BaseLoadingListener {
|
||||
constructor(stack, options) {
|
||||
options = options || {};
|
||||
|
||||
this.id = BaseLoadingListener.getNewId();
|
||||
this.stack = stack;
|
||||
this.startListening();
|
||||
this.statsItemsLimit = options.statsItemsLimit || 2;
|
||||
this.stats = {
|
||||
items: [],
|
||||
total: 0,
|
||||
elapsedTime: 0,
|
||||
speed: 0
|
||||
};
|
||||
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
|
||||
_getProgressSessionId() {
|
||||
const displaySetInstanceUid = this.stack.displaySetInstanceUid;
|
||||
return 'StackProgress:' + displaySetInstanceUid;
|
||||
}
|
||||
|
||||
_clearSession() {
|
||||
const progressSessionId = this._getProgressSessionId();
|
||||
Session.set(progressSessionId, undefined);
|
||||
delete Session.keys.progressSessionId;
|
||||
}
|
||||
|
||||
startListening() {
|
||||
throw new Error('`startListening` must be implemented by child clases');
|
||||
}
|
||||
|
||||
stopListening() {
|
||||
throw new Error('`stopListening` must be implemented by child clases');
|
||||
}
|
||||
|
||||
destroy() {
|
||||
this.stopListening();
|
||||
this._clearSession();
|
||||
}
|
||||
|
||||
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) {
|
||||
super(stack);
|
||||
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() {
|
||||
return 'cornerstoneimageloadprogress.' + this.id;
|
||||
}
|
||||
|
||||
startListening() {
|
||||
const imageLoadProgressEventName = this._getImageLoadProgressEventName();
|
||||
const imageLoadProgressEventHandle = this._imageLoadProgressEventHandle.bind(this);
|
||||
|
||||
this.stopListening();
|
||||
|
||||
cornerstone.events.addEventListener(imageLoadProgressEventName, imageLoadProgressEventHandle);
|
||||
}
|
||||
|
||||
stopListening() {
|
||||
const imageLoadProgressEventName = this._getImageLoadProgressEventName();
|
||||
cornerstone.events.removeEventListener(imageLoadProgressEventName);
|
||||
}
|
||||
|
||||
_imageLoadProgressEventHandle(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 progressSessionId = this._getProgressSessionId();
|
||||
eventData = eventData || {};
|
||||
|
||||
Session.set(progressSessionId, {
|
||||
multiFrame: false,
|
||||
percentComplete: eventData.percentComplete,
|
||||
bytesLoaded: eventData.loaded,
|
||||
bytesTotal: eventData.total,
|
||||
bytesPerSecond: this.stats.speed
|
||||
});
|
||||
}
|
||||
|
||||
_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) {
|
||||
super(stack, { statsItemsLimit: 20 });
|
||||
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 'cornerstoneimageloaded.' + this.id;
|
||||
}
|
||||
|
||||
_getImageCachePromiseRemoveEventName() {
|
||||
return 'cornerstoneimagecachepromiseremoved.' + this.id;
|
||||
}
|
||||
|
||||
startListening() {
|
||||
const imageLoadedEventName = this._getImageLoadedEventName();
|
||||
const imageCachePromiseRemovedEventName = this._getImageCachePromiseRemoveEventName();
|
||||
const imageLoadedEventHandle = this._imageLoadedEventHandle.bind(this);
|
||||
const imageCachePromiseRemovedEventHandle = this._imageCachePromiseRemovedEventHandle.bind(this);
|
||||
|
||||
this.stopListening();
|
||||
|
||||
cornerstone.events.addEventListener(imageLoadedEventName, imageLoadedEventHandle);
|
||||
cornerstone.events.addEventListener(imageCachePromiseRemovedEventName, imageCachePromiseRemovedEventHandle);
|
||||
}
|
||||
|
||||
stopListening() {
|
||||
const imageLoadedEventName = this._getImageLoadedEventName();
|
||||
const imageCachePromiseRemovedEventName = this._getImageCachePromiseRemoveEventName();
|
||||
|
||||
cornerstone.events.removeEventListener(imageLoadedEventName);
|
||||
cornerstone.events.removeEventListener(imageCachePromiseRemovedEventName);
|
||||
}
|
||||
|
||||
_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();
|
||||
}
|
||||
|
||||
_imageLoadedEventHandle(e) {
|
||||
this._updateFrameStatus(e.detail.image.imageId, true);
|
||||
}
|
||||
|
||||
_imageCachePromiseRemovedEventHandle(e) {
|
||||
this._updateFrameStatus(e.detail.imageId, false);
|
||||
}
|
||||
|
||||
_updateProgress() {
|
||||
const totalFramesCount = this.stack.imageIds.length;
|
||||
const loadedFramesCount = this.loadedCount;
|
||||
const loadingFramesCount = totalFramesCount - loadedFramesCount;
|
||||
const percentComplete = Math.round(loadedFramesCount / totalFramesCount * 100);
|
||||
const progressSessionId = this._getProgressSessionId();
|
||||
|
||||
Session.set(progressSessionId, {
|
||||
multiFrame: true,
|
||||
totalFramesCount,
|
||||
loadedFramesCount,
|
||||
loadingFramesCount,
|
||||
percentComplete,
|
||||
framesPerSecond: this.stats.speed,
|
||||
framesStatus: this.framesStatus
|
||||
});
|
||||
}
|
||||
|
||||
_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 += ']';
|
||||
OHIF.log.info(`${displaySetInstanceUid}: ${progressBar}`);
|
||||
}
|
||||
}
|
||||
|
||||
class StudyLoadingListener {
|
||||
constructor() {
|
||||
this.listeners = {};
|
||||
}
|
||||
|
||||
addStack(stack, stackMetaData) {
|
||||
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 = OHIF.viewerbase.stackManager.findOrCreateStack(study, displaySet);
|
||||
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);
|
||||
} else {
|
||||
return new DICOMFileLoadingListener(stack);
|
||||
}
|
||||
}
|
||||
|
||||
_getSchema(stack) {
|
||||
const imageId = stack.imageIds[0];
|
||||
const colonIndex = imageId.indexOf(':');
|
||||
return imageId.substring(0, colonIndex);
|
||||
}
|
||||
|
||||
// Singleton
|
||||
static getInstance() {
|
||||
if (!StudyLoadingListener._instance) {
|
||||
StudyLoadingListener._instance = new StudyLoadingListener();
|
||||
}
|
||||
|
||||
return StudyLoadingListener._instance;
|
||||
}
|
||||
}
|
||||
|
||||
export { StudyLoadingListener, StackLoadingListener, DICOMFileLoadingListener };
|
||||
@ -1,30 +0,0 @@
|
||||
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');
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,331 +0,0 @@
|
||||
import { Meteor } from 'meteor/meteor';
|
||||
import { Session } from 'meteor/session';
|
||||
import $ from 'jquery';
|
||||
import _ from 'underscore';
|
||||
import { OHIF } from 'meteor/ohif:core';
|
||||
import { OHIFError } from './OHIFError';
|
||||
//import { getImageId } from '../getImageId.js';
|
||||
|
||||
export class StudyPrefetcher {
|
||||
|
||||
constructor(studies) {
|
||||
this.studies = studies || [];
|
||||
this.prefetchDisplaySetsTimeout = 300;
|
||||
this.lastActiveViewportElement = null;
|
||||
this.cacheFullHandlerBound = _.bind(this.cacheFullHandler, this);
|
||||
|
||||
cornerstone.events.addEventListener('cornerstoneimagecachefull.StudyPrefetcher', this.cacheFullHandlerBound);
|
||||
}
|
||||
|
||||
destroy() {
|
||||
this.stopPrefetching();
|
||||
cornerstone.events.removeEventListener('cornerstoneimagecachefull.StudyPrefetcher', this.cacheFullHandlerBound);
|
||||
}
|
||||
|
||||
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.prefetchActiveViewport();
|
||||
this.prefetchDisplaySets();
|
||||
}
|
||||
|
||||
stopPrefetching() {
|
||||
this.disableViewportPrefetch();
|
||||
cornerstoneTools.requestPoolManager.clearRequestStack('prefetch');
|
||||
}
|
||||
|
||||
prefetchActiveViewport() {
|
||||
const activeViewportElement = OHIF.viewerbase.viewportUtils.getActiveViewportElement();
|
||||
this.enablePrefetchOnElement(activeViewportElement);
|
||||
this.attachActiveViewportListeners(activeViewportElement);
|
||||
}
|
||||
|
||||
disableViewportPrefetch() {
|
||||
$('.imageViewerViewport').each(function() {
|
||||
if (!$(this).find('canvas').length) {
|
||||
return;
|
||||
}
|
||||
|
||||
cornerstoneTools.stackPrefetch.disable(this);
|
||||
});
|
||||
}
|
||||
|
||||
hasStack(element) {
|
||||
const stack = cornerstoneTools.getToolState(element, 'stack');
|
||||
return stack && stack.data.length && (stack.data[0].imageIds.length > 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* This function enables stack prefetching for a specified element (viewport)
|
||||
* It first disables any prefetching currently occurring on any other viewports.
|
||||
*
|
||||
* @param element {node} DOM Node representing the viewport element
|
||||
*/
|
||||
enablePrefetchOnElement(element) {
|
||||
if (!$(element).find('canvas').length) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Make sure there is a stack to fetch
|
||||
if (this.hasStack(element)) {
|
||||
// Check if this is a clip or not
|
||||
const activeViewportIndex = window.store.getState().viewports.activeViewport;
|
||||
const displaySetInstanceUid = OHIF.viewer.data.loadedSeriesData[activeViewportIndex].displaySetInstanceUid;
|
||||
|
||||
const { StackManager } = OHIF.viewerbase;
|
||||
|
||||
const stack = StackManager.findStack(displaySetInstanceUid);
|
||||
|
||||
if (!stack) {
|
||||
throw new OHIFError(`Requested stack ${displaySetInstanceUid} was not created`);
|
||||
}
|
||||
|
||||
cornerstoneTools.stackPrefetch.enable(element);
|
||||
}
|
||||
}
|
||||
|
||||
attachActiveViewportListeners(activeViewportElement) {
|
||||
function newImageHandler() {
|
||||
// It needs to be called asynchronously because cornerstone does it at the same way.
|
||||
// All instance urls to be prefetched will be removed again if we add them before
|
||||
// Cornerstone callback (see stackPrefetch.onImageUpdated).
|
||||
StudyPrefetcher.prefetchDisplaySetsAsync();
|
||||
}
|
||||
|
||||
if (this.lastActiveViewportElement) {
|
||||
this.lastActiveViewportElement.removeEventListener('cornerstonenewimage.StudyPrefetcher', newImageHandler);
|
||||
}
|
||||
|
||||
activeViewportElement.removeEventListener('cornerstonenewimage.StudyPrefetcher', newImageHandler);
|
||||
|
||||
// Cornerstone will not attach an event listener if the element doesn't have a stack
|
||||
if (this.hasStack(activeViewportElement)) {
|
||||
activeViewportElement.addEventListener('cornerstonenewimage.StudyPrefetcher', newImageHandler);
|
||||
}
|
||||
|
||||
this.lastActiveViewportElement = activeViewportElement;
|
||||
}
|
||||
|
||||
prefetchDisplaySetsAsync(timeout) {
|
||||
timeout = timeout || this.prefetchDisplaySetsTimeout;
|
||||
|
||||
clearTimeout(this.prefetchDisplaySetsHandler);
|
||||
this.prefetchDisplaySetsHandler = setTimeout(() => {
|
||||
this.prefetchDisplaySets();
|
||||
}, timeout);
|
||||
}
|
||||
|
||||
prefetchDisplaySets() {
|
||||
let config;
|
||||
if (Meteor.settings &&
|
||||
Meteor.settings.public &&
|
||||
Meteor.settings.prefetch) {
|
||||
config = Meteor.settings.public.prefetch;
|
||||
} else {
|
||||
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();
|
||||
}
|
||||
|
||||
getActiveViewportImage() {
|
||||
const element = OHIF.viewerbase.viewportUtils.getActiveViewportElement();
|
||||
|
||||
if (!element) {
|
||||
return;
|
||||
}
|
||||
|
||||
const enabledElement = cornerstone.getEnabledElement(element);
|
||||
const image = enabledElement.image;
|
||||
|
||||
return image;
|
||||
}
|
||||
|
||||
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 _.find(displaySets, displaySet => {
|
||||
return _.some(displaySet.images, 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 = 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) {
|
||||
OHIF.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 = [];
|
||||
|
||||
/*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 _.filter(imageIds, imageId => {
|
||||
return !this.isImageCached(imageId);
|
||||
});
|
||||
}
|
||||
|
||||
isImageCached(imageId) {
|
||||
const image = cornerstone.imageCache.imageCache[imageId];
|
||||
return image && image.sizeInBytes;
|
||||
}
|
||||
|
||||
cacheFullHandler() {
|
||||
OHIF.log.warn('Cache full');
|
||||
this.stopPrefetching();
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,498 +0,0 @@
|
||||
import { OHIF } from 'meteor/ohif:core';
|
||||
import { ReactiveVar } from 'meteor/reactive-var';
|
||||
|
||||
/**
|
||||
* 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 = new ReactiveVar(MIN_COUNT);
|
||||
this._elementList = [];
|
||||
this._handlers = Object.create(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Private Methods
|
||||
*/
|
||||
|
||||
_invalidate() {
|
||||
let count = this._operationCount.get();
|
||||
this._operationCount.set(count < MAX_COUNT ? count + 1 : MIN_COUNT);
|
||||
}
|
||||
|
||||
_elements(silent) {
|
||||
(silent === true || this._operationCount.get());
|
||||
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 = OHIF.utils.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');
|
||||
}
|
||||
}
|
||||
@ -1,69 +0,0 @@
|
||||
import MetadataProvider from './MetadataProvider.js';
|
||||
import CommandsManager from './CommandsManager.js';
|
||||
import HotkeysContext from './HotkeysContext.js';
|
||||
import HotkeysManager from './HotkeysManager.js';
|
||||
import { ImageSet } from './ImageSet';
|
||||
import { StudyPrefetcher } from './StudyPrefetcher';
|
||||
import { ResizeViewportManager } from './ResizeViewportManager';
|
||||
import { StudyLoadingListener } from './StudyLoadingListener';
|
||||
import { StackLoadingListener } from './StudyLoadingListener';
|
||||
import { DICOMFileLoadingListener } from './StudyLoadingListener';
|
||||
import { StudyMetadata } from './metadata/StudyMetadata';
|
||||
import { SeriesMetadata } from './metadata/SeriesMetadata';
|
||||
import { InstanceMetadata } from './metadata/InstanceMetadata';
|
||||
//import { StudySummary } from './metadata/StudySummary';
|
||||
import { plugins } from './plugins/';
|
||||
import { TypeSafeCollection } from './TypeSafeCollection';
|
||||
import { OHIFError } from './OHIFError.js';
|
||||
//import { StackImagePositionOffsetSynchronizer } from './StackImagePositionOffsetSynchronizer';
|
||||
import { StudyMetadataSource } from './StudyMetadataSource';
|
||||
|
||||
export {
|
||||
MetadataProvider,
|
||||
CommandsManager,
|
||||
HotkeysContext,
|
||||
HotkeysManager,
|
||||
ImageSet,
|
||||
StudyPrefetcher,
|
||||
ResizeViewportManager,
|
||||
StudyLoadingListener,
|
||||
StackLoadingListener,
|
||||
DICOMFileLoadingListener,
|
||||
StudyMetadata,
|
||||
SeriesMetadata,
|
||||
InstanceMetadata,
|
||||
//StudySummary,
|
||||
TypeSafeCollection,
|
||||
OHIFError,
|
||||
//StackImagePositionOffsetSynchronizer,
|
||||
StudyMetadataSource
|
||||
};
|
||||
|
||||
const classes = {
|
||||
MetadataProvider,
|
||||
CommandsManager,
|
||||
HotkeysContext,
|
||||
HotkeysManager,
|
||||
ImageSet,
|
||||
StudyPrefetcher,
|
||||
ResizeViewportManager,
|
||||
StudyLoadingListener,
|
||||
StackLoadingListener,
|
||||
DICOMFileLoadingListener,
|
||||
StudyMetadata,
|
||||
SeriesMetadata,
|
||||
InstanceMetadata,
|
||||
//StudySummary,
|
||||
TypeSafeCollection,
|
||||
OHIFError,
|
||||
//StackImagePositionOffsetSynchronizer,
|
||||
StudyMetadataSource
|
||||
};
|
||||
|
||||
export default classes;
|
||||
|
||||
//Viewerbase.metadata = { StudyMetadata, SeriesMetadata, InstanceMetadata, StudySummary };
|
||||
//Viewerbase.plugins = plugins;
|
||||
|
||||
// TypeSafeCollection
|
||||
//Viewerbase.TypeSafeCollection = TypeSafeCollection;
|
||||
@ -1,227 +0,0 @@
|
||||
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 NUMBER = 'number';
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,127 +0,0 @@
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,117 +0,0 @@
|
||||
import { InstanceMetadata } from './InstanceMetadata';
|
||||
import { DICOMTagDescriptions } from '../../lib/DICOMTagDescriptions.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 = Viewerbase.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;
|
||||
}
|
||||
}
|
||||
@ -1,32 +0,0 @@
|
||||
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));
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -1,31 +0,0 @@
|
||||
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));
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,128 +0,0 @@
|
||||
# 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 usualy 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 exclusevily 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 © 2016 nucleushealth™. All rights reserved_
|
||||
@ -1,195 +0,0 @@
|
||||
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()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,396 +0,0 @@
|
||||
import { Metadata } from './Metadata';
|
||||
import { SeriesMetadata } from './SeriesMetadata';
|
||||
import { InstanceMetadata } from './InstanceMetadata';
|
||||
import { ImageSet } from '../ImageSet';
|
||||
import { OHIFError } from '../OHIFError';
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 (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.
|
||||
*/
|
||||
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;
|
||||
}
|
||||
}
|
||||
@ -1,78 +0,0 @@
|
||||
import { Metadata } from './Metadata';
|
||||
import { OHIFError } from '../OHIFError';
|
||||
import { DICOMTagDescriptions } from '../../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];
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,50 +0,0 @@
|
||||
import _ from 'underscore';
|
||||
|
||||
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 (!_.isArray(value)) {
|
||||
value = [value];
|
||||
}
|
||||
|
||||
json[key] = {
|
||||
Value: value
|
||||
};
|
||||
});
|
||||
|
||||
return json;
|
||||
}
|
||||
}
|
||||
@ -1,21 +0,0 @@
|
||||
import { StudyMetadata } from './StudyMetadata';
|
||||
import { SeriesMetadata } from './SeriesMetadata';
|
||||
import { InstanceMetadata } from './InstanceMetadata';
|
||||
import { OHIFStudyMetadata } from './OHIFStudyMetadata';
|
||||
import { OHIFSeriesMetadata } from './OHIFSeriesMetadata';
|
||||
import { OHIFInstanceMetadata } from './OHIFInstanceMetadata';
|
||||
import { Metadata } from './Metadata';
|
||||
import { WadoRsMetaDataBuilder } from './WadoRsMetaDataBuilder';
|
||||
|
||||
const metadata = {
|
||||
Metadata,
|
||||
WadoRsMetaDataBuilder,
|
||||
StudyMetadata,
|
||||
SeriesMetadata,
|
||||
InstanceMetadata,
|
||||
OHIFStudyMetadata,
|
||||
OHIFSeriesMetadata,
|
||||
OHIFInstanceMetadata
|
||||
}
|
||||
|
||||
export default metadata;
|
||||
@ -1,75 +0,0 @@
|
||||
export class OHIFPlugin {
|
||||
// TODO: this class is still under development and will
|
||||
// likely change in the near future
|
||||
constructor () {
|
||||
this.name = "Unnamed plugin";
|
||||
this.description = "No description available";
|
||||
}
|
||||
|
||||
// load an individual script URL
|
||||
static loadScript(scriptURL, type = "text/javascript") {
|
||||
return new Promise((resolve, reject) => {
|
||||
const head = document.getElementsByTagName("head")[0];
|
||||
const script = document.createElement("script");
|
||||
|
||||
script.onload = () => {
|
||||
head.removeChild(script);
|
||||
resolve();
|
||||
};
|
||||
|
||||
script.onerror = reject;
|
||||
|
||||
script.src = scriptURL;
|
||||
script.type = type;
|
||||
script.async = false;
|
||||
|
||||
head.appendChild(script);
|
||||
});
|
||||
}
|
||||
|
||||
// reload all the dependency scripts and also
|
||||
// the main plugin script url.
|
||||
static reloadPlugin(plugin) {
|
||||
if (plugin.scriptURLs && plugin.scriptURLs.length) {
|
||||
plugin.scriptURLs.forEach(scriptURL => {
|
||||
this.loadScript(scriptURL);
|
||||
});
|
||||
}
|
||||
|
||||
// TODO: Later we should probably merge script and module URLs
|
||||
if (plugin.moduleURLs && plugin.moduleURLs.length) {
|
||||
plugin.moduleURLs.forEach(moduleURLs => {
|
||||
this.loadScript(moduleURLs, "module");
|
||||
});
|
||||
}
|
||||
|
||||
if (plugin.styleURLs && plugin.styleURLs.length) {
|
||||
plugin.styleURLs.forEach(styleURLs => {
|
||||
this.loadScript(styleURLs, "text/css");
|
||||
});
|
||||
}
|
||||
|
||||
let scriptURL = plugin.url;
|
||||
|
||||
if (plugin.allowCaching === false) {
|
||||
scriptURL += "?" + performance.now();
|
||||
}
|
||||
|
||||
const type = plugin.module === true ? 'module' : 'text/javascript'
|
||||
|
||||
console.warn(`Calling loadScript for ${plugin.name}`);
|
||||
console.time(`loadScript ${plugin.name}`);
|
||||
this.loadScript(scriptURL, type).then((script) => {
|
||||
console.timeEnd(`loadScript ${plugin.name}`);
|
||||
const entryPointFunction = OHIF.plugins.entryPoints[plugin.name];
|
||||
|
||||
if (entryPointFunction) {
|
||||
entryPointFunction();
|
||||
} else {
|
||||
throw new Error(`No entry point found for ${plugin.name}`);
|
||||
}
|
||||
}, error => {
|
||||
throw new Error(error);
|
||||
});
|
||||
}
|
||||
}
|
||||
@ -1,170 +0,0 @@
|
||||
import { Session } from 'meteor/session';
|
||||
import { Tracker } from 'meteor/tracker';
|
||||
|
||||
import { OHIF } from 'meteor/ohif:core';
|
||||
|
||||
import { OHIFPlugin } from "./OHIFPlugin";
|
||||
|
||||
export class ViewportPlugin extends OHIFPlugin {
|
||||
constructor(name) {
|
||||
super();
|
||||
|
||||
this.name = name;
|
||||
this._destroyed = false;
|
||||
|
||||
this._setupListeners();
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve a Display Set for a specific viewport by viewport index,
|
||||
* if one is already displayed in the viewport.
|
||||
*
|
||||
* @static
|
||||
* @param {Number} viewportIndex
|
||||
* @return {undefined|ImageSet}
|
||||
*/
|
||||
static getDisplaySet(viewportIndex) {
|
||||
// TODO: Move layoutManager from viewerbase to viewer
|
||||
const { layoutManager } = OHIF.viewerbase;
|
||||
const viewportData = layoutManager.viewportData[viewportIndex];
|
||||
const { studyInstanceUid, displaySetInstanceUid } = viewportData;
|
||||
const studyMetadata = OHIF.viewer.StudyMetadataList.findBy({ studyInstanceUID: studyInstanceUid });
|
||||
|
||||
return studyMetadata.findDisplaySet(displaySet => {
|
||||
return displaySet.displaySetInstanceUid === displaySetInstanceUid;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Set up the viewport using the plugin.
|
||||
*
|
||||
* This should be implemented by the child class.
|
||||
*
|
||||
* @abstract
|
||||
*
|
||||
* @param {HTMLElement} div
|
||||
* @param {ImageSet} displaySet
|
||||
* @param {Object} viewportDetails
|
||||
*/
|
||||
setupViewport(div, displaySet, viewportDetails) {
|
||||
throw new Error('You must override this method!');
|
||||
}
|
||||
|
||||
/**
|
||||
* Switch a single viewport to use the current ViewportPlugin
|
||||
*
|
||||
* @param {Number} viewportIndex The viewport to switch to the current plugin type
|
||||
*/
|
||||
setViewportToPlugin(viewportIndex) {
|
||||
if (!this.name) {
|
||||
throw new Error('ViewportPlugin subclasses must have a name');
|
||||
}
|
||||
|
||||
const { layoutManager } = OHIF.viewerbase;
|
||||
const viewportData = layoutManager.viewportData[viewportIndex];
|
||||
if (viewportData.plugin === this.name) {
|
||||
OHIF.log.info(`setViewportToPlugin: Viewport ${viewportIndex} already set to plugin ${this.name}`);
|
||||
}
|
||||
|
||||
viewportData.plugin = this.name;
|
||||
|
||||
layoutManager.rerenderViewportWithNewDisplaySet(viewportIndex, viewportData);
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs 'setupViewport' for the ViewportPlugin on all viewports which should
|
||||
* be rendered by this plugin, but have not yet been initialized. Viewports
|
||||
* which already contain contents are skipped.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
_initEmptyPluginViewports() {
|
||||
if (!this.name) {
|
||||
throw new Error('ViewportPlugin subclasses must have a name');
|
||||
}
|
||||
|
||||
// Find all Viewport HTMLElements currently using this plugin
|
||||
const pluginDivs = Array.from(document.querySelectorAll(`.viewport-plugin-${this.name}`));
|
||||
|
||||
// If there are no Viewports using this plugin, stop here
|
||||
if (!pluginDivs.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
const emptyPluginDivs = pluginDivs.filter(div => {
|
||||
// Keep only divs owned by the plugin which have no contents
|
||||
return div.innerHTML.trim() === '';
|
||||
});
|
||||
|
||||
OHIF.log.info(`${this.name}: Initializing ${emptyPluginDivs.length} viewports`);
|
||||
|
||||
// Retrieve the list of all viewports, so we can figure out the viewport details
|
||||
const allViewports = Array.from(document.querySelectorAll('.viewportContainer'));
|
||||
|
||||
const { layoutManager } = OHIF.viewerbase;
|
||||
|
||||
emptyPluginDivs.forEach(div => {
|
||||
// Identify the Viewport index, and any display set that is currently
|
||||
// hung in the viewport
|
||||
const viewportIndex = allViewports.indexOf(div.parentNode);
|
||||
const viewportData = layoutManager.viewportData[viewportIndex];
|
||||
const displaySet = ViewportPlugin.getDisplaySet(viewportIndex);
|
||||
|
||||
// Use the plugin's setupViewport function to render the contents
|
||||
// of this viewport.
|
||||
this.setupViewport(div, viewportData, displaySet);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Listen for changes to the viewport layout which would necessitate a
|
||||
* rerendering of the viewports. When this happens, re-render all viewports
|
||||
* which are using this plugin.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
_setupListeners() {
|
||||
if (!this.name) {
|
||||
throw new Error('ViewportPlugin subclasses must have a name');
|
||||
}
|
||||
|
||||
console.warn(`_setupListeners: ${this.name}`);
|
||||
|
||||
// TODO: Stop using Meteor's reactivity here
|
||||
Tracker.autorun((computation) => {
|
||||
const random = Session.get('LayoutManagerUpdated');
|
||||
console.warn(`LayoutManagerUpdated: ${this.name}: ${random}`);
|
||||
|
||||
// Bail out if this is the first time the autorun
|
||||
// executes (i.e. when it is being defined).
|
||||
//
|
||||
// Note: This has to be checked after the dependency on the
|
||||
// Session variable above, or the reactive dependency will not
|
||||
// be established.
|
||||
if (computation.firstRun === true) {
|
||||
return;
|
||||
}
|
||||
|
||||
// In case we need to disable the use
|
||||
// of this plugin, we can also stop the
|
||||
// reactive computation by setting
|
||||
// this.destroyed to true.
|
||||
if (this._destroyed === true) {
|
||||
computation.stop();
|
||||
}
|
||||
|
||||
// Identify all viewports which should be
|
||||
// rendered by the ViewportPlugin, and render
|
||||
// them.
|
||||
this._initEmptyPluginViewports();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop listening for changes to the viewport layout in order to
|
||||
* automatically rerender viewports setup for use by this plugin.
|
||||
*/
|
||||
stopListeners() {
|
||||
this._destroyed = true;
|
||||
}
|
||||
}
|
||||
@ -1,18 +0,0 @@
|
||||
import { OHIF } from 'meteor/ohif:core';
|
||||
|
||||
import { OHIFPlugin } from './OHIFPlugin';
|
||||
import { ViewportPlugin } from './ViewportPlugin';
|
||||
|
||||
// Each plugin registers an entry point function to be called
|
||||
// when the loading is complete.
|
||||
|
||||
const plugins = {
|
||||
OHIFPlugin,
|
||||
ViewportPlugin,
|
||||
entryPoints: {}
|
||||
};
|
||||
|
||||
// TODO: When we reorganize the packages, we should figure out where to put this.
|
||||
OHIF.plugins = plugins;
|
||||
|
||||
export default plugins;
|
||||
@ -1,11 +0,0 @@
|
||||
import { Mongo } from 'meteor/mongo';
|
||||
import { OHIF } from 'meteor/ohif:core';
|
||||
|
||||
// CurrentServer is a single document collection to describe which of the Servers is being used
|
||||
const CurrentServer = new Mongo.Collection(null);
|
||||
CurrentServer._debugName = 'CurrentServer';
|
||||
OHIF.servers = OHIF.servers || {};
|
||||
OHIF.servers.collections = OHIF.servers.collections || {};
|
||||
OHIF.servers.collections.currentServer = CurrentServer;
|
||||
|
||||
export { CurrentServer };
|
||||
@ -1,4 +0,0 @@
|
||||
import { CurrentServer } from './currentServer.js';
|
||||
import { Servers } from './servers.js';
|
||||
|
||||
export { CurrentServer, Servers };
|
||||
@ -1,17 +0,0 @@
|
||||
import { Mongo } from 'meteor/mongo';
|
||||
import { OHIF } from 'meteor/ohif:core';
|
||||
// import { Servers as ServerSchema } from 'meteor/ohif:servers/both/schema/servers.js';
|
||||
|
||||
let collectionName = 'servers';
|
||||
if (Meteor.settings && Meteor.settings.public && Meteor.settings.public.clientOnly === true) {
|
||||
collectionName = null;
|
||||
}
|
||||
|
||||
// Servers describe the DICOM servers configurations
|
||||
const Servers = new Mongo.Collection(collectionName);
|
||||
// TODO: Make the Schema match what we are currently sticking into the Collection
|
||||
//Servers.attachSchema(ServerSchema);
|
||||
Servers._debugName = 'Servers';
|
||||
OHIF.servers.collections.servers = Servers;
|
||||
|
||||
export { Servers };
|
||||
@ -1,18 +0,0 @@
|
||||
import { ReactiveVar } from 'meteor/reactive-var';
|
||||
import { OHIF } from 'meteor/ohif:core';
|
||||
import { CommandsManager } from './classes/CommandsManager';
|
||||
|
||||
// Create context namespace using a ReactiveVar
|
||||
const context = new ReactiveVar(null);
|
||||
|
||||
// Append context namespace to OHIF namespace
|
||||
OHIF.context = context;
|
||||
|
||||
// Create commands namespace using a CommandsManager class instance
|
||||
const commands = new CommandsManager(context);
|
||||
|
||||
// Append commands namespace to OHIF namespace
|
||||
OHIF.commands = commands;
|
||||
|
||||
// Export relevant objects
|
||||
export { context, commands };
|
||||
@ -1,49 +0,0 @@
|
||||
import { OHIF } from 'meteor/ohif:core';
|
||||
|
||||
/*
|
||||
* Base component to template instances of all dynamic components
|
||||
*/
|
||||
class Component {
|
||||
|
||||
// Set up the component
|
||||
constructor(templateInstance) {
|
||||
// Store the component in the current view
|
||||
templateInstance.view._component = this;
|
||||
|
||||
// Create an object to register section's content
|
||||
templateInstance.sections = {};
|
||||
|
||||
// Store the template instance in the component
|
||||
this.templateInstance = templateInstance;
|
||||
|
||||
// Store the component's registered sub-components
|
||||
this.registeredItems = new Set();
|
||||
}
|
||||
|
||||
// Self register the component in its first parent component
|
||||
registerSelf() {
|
||||
const parent = OHIF.blaze.getParentComponent(this.templateInstance.view);
|
||||
if (parent) {
|
||||
// Store this component's parent in a property
|
||||
this.parent = parent;
|
||||
|
||||
// Add this component in its parent's registered items list
|
||||
parent.registeredItems.add(this);
|
||||
}
|
||||
}
|
||||
|
||||
// Self unregister the component in its first parent component
|
||||
unregisterSelf() {
|
||||
const parent = OHIF.blaze.getParentComponent(this.templateInstance.view);
|
||||
if (parent) {
|
||||
// Remove the parent property from this component
|
||||
delete this.parent;
|
||||
|
||||
// Remove this component from its parent's registered items list
|
||||
parent.registeredItems.delete(this);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
OHIF.Component = Component;
|
||||
@ -1,39 +0,0 @@
|
||||
// Core files
|
||||
import './component.js';
|
||||
import './mixin.js';
|
||||
import './template.js';
|
||||
|
||||
// Section
|
||||
import './section/section.html';
|
||||
import './section/section.js';
|
||||
|
||||
// Mixins
|
||||
import './mixins/action.js';
|
||||
import './mixins/button.js';
|
||||
import './mixins/checkbox.js';
|
||||
import './mixins/component.js';
|
||||
import './mixins/dropdown.js';
|
||||
import './mixins/form.js';
|
||||
import './mixins/formItem.js';
|
||||
import './mixins/group.js';
|
||||
import './mixins/groupRadio.js';
|
||||
import './mixins/input.js';
|
||||
import './mixins/link.js';
|
||||
import './mixins/popover.js';
|
||||
import './mixins/schemaData.js';
|
||||
import './mixins/select.js';
|
||||
import './mixins/select2.js';
|
||||
|
||||
// Templates
|
||||
import './templates/button.html';
|
||||
import './templates/custom.html';
|
||||
import './templates/div.html';
|
||||
import './templates/form.html';
|
||||
import './templates/input.html';
|
||||
import './templates/link.html';
|
||||
import './templates/select.html';
|
||||
import './templates/tr.html';
|
||||
|
||||
// wrappers
|
||||
import './wrappers/label.html';
|
||||
import './wrappers/labelContent.html';
|
||||
@ -1,138 +0,0 @@
|
||||
import { OHIF } from 'meteor/ohif:core';
|
||||
import _ from 'underscore';
|
||||
|
||||
// Create an object to store all the application mixins
|
||||
OHIF.mixins = {};
|
||||
|
||||
// Class to manage new mixins and its dependencies
|
||||
class Mixin {
|
||||
|
||||
// Create the mixin instance
|
||||
constructor({ dependencies, composition }) {
|
||||
// Store the mixin dependencies
|
||||
this.dependencies = dependencies || '';
|
||||
|
||||
// Store the mixin composition
|
||||
this.composition = composition;
|
||||
}
|
||||
|
||||
// Initialize the mixin applying all its composition functions
|
||||
init(template, data, applied, behaviors) {
|
||||
const dependenciesArray = this.dependencies.split(' ');
|
||||
_.each(dependenciesArray, dependency => {
|
||||
// Go to next dependency if the current dependency string is blank
|
||||
if (!dependency) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Get the dependent mixin to be initizalized
|
||||
const mixin = Mixin.getMixin(dependency);
|
||||
|
||||
// Throw an error if a cyclic dependency was found on this mixin
|
||||
if (mixin === this) {
|
||||
throw new Error(`Mixin ${dependency} has a cyclic dependency.`);
|
||||
}
|
||||
|
||||
// Initizalize the mixin dependencies recursively
|
||||
mixin.init(template, data, applied, behaviors);
|
||||
});
|
||||
|
||||
// Apply the mixin's composition behaviors to the template
|
||||
this.apply(template, data, applied, behaviors);
|
||||
}
|
||||
|
||||
// Add the mixin's composition behaviors to the template
|
||||
apply(template, data, applied, behaviors) {
|
||||
// Ignore if the mixin was already applied to the template
|
||||
if (_.contains(applied, this)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Store the mixin's composition
|
||||
const composition = this.composition;
|
||||
|
||||
// Iterate over each behavior
|
||||
_.each(behaviors, behavior => {
|
||||
// Execute something only after all the mixins are done
|
||||
let functionName = behavior;
|
||||
if (functionName === 'onMixins') {
|
||||
functionName = 'onRendered';
|
||||
}
|
||||
|
||||
if (behavior === 'onData' && composition[behavior]) {
|
||||
// If it's just data manipulation, call it immediately
|
||||
composition[behavior](data);
|
||||
} else if (composition[behavior]) {
|
||||
// Register the behavior in the template
|
||||
template[functionName](composition[behavior]);
|
||||
}
|
||||
});
|
||||
|
||||
// Set the current mixin's state as applied
|
||||
applied.push(this);
|
||||
}
|
||||
|
||||
// Initialize all data manipulation mixins
|
||||
static initData(data) {
|
||||
// Split the mixins by space
|
||||
const mixinsArray = data.mixins.split(' ');
|
||||
|
||||
// Control and ignore the mixins that have already been applied
|
||||
const appliedOnData = [];
|
||||
_.each(mixinsArray, mixinName => {
|
||||
// Ignore blank strings
|
||||
if (!mixinName) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Get the current mixin
|
||||
const mixin = Mixin.getMixin(mixinName);
|
||||
|
||||
// Initialize the data manipulation composition
|
||||
mixin.init(null, data, appliedOnData, ['onData']);
|
||||
});
|
||||
}
|
||||
|
||||
// Initialize all the template's mixins
|
||||
static initAll(template, data) {
|
||||
// Split the mixins by space
|
||||
const mixinsArray = data.mixins.split(' ');
|
||||
|
||||
// Control and ignore the mixins that have already been applied
|
||||
const appliedCommon = [];
|
||||
const appliedOnMixins = [];
|
||||
_.each(mixinsArray, mixinName => {
|
||||
// Ignore blank strings
|
||||
if (!mixinName) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Get the current mixin
|
||||
const mixin = Mixin.getMixin(mixinName);
|
||||
|
||||
// Initialize blaze default compositions
|
||||
mixin.init(template, data, appliedCommon, ['onCreated', 'onRendered', 'onDestroyed', 'events', 'helpers']);
|
||||
|
||||
// Execute some behaviors after all mixins are applied
|
||||
mixin.init(template, data, appliedOnMixins, ['onMixins']);
|
||||
});
|
||||
}
|
||||
|
||||
// Get a mixin by name
|
||||
static getMixin(mixinName) {
|
||||
// Get the mixin from mixins object
|
||||
const mixin = OHIF.mixins[mixinName];
|
||||
|
||||
// Throw an error if the mixin does not exists
|
||||
if (!mixin) {
|
||||
throw new Error(`Mixin ${mixinName} not found.`);
|
||||
}
|
||||
|
||||
// Return the found mixin
|
||||
return mixin;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Store the Mixin class inside the shared OHIF object
|
||||
OHIF.Mixin = Mixin;
|
||||
@ -1,72 +0,0 @@
|
||||
import { Template } from 'meteor/templating';
|
||||
import $ from 'jquery';
|
||||
import { OHIF } from 'meteor/ohif:core';
|
||||
|
||||
/*
|
||||
* action: controls an element that will trigger some form API's method
|
||||
*/
|
||||
OHIF.mixins.action = new OHIF.Mixin({
|
||||
dependencies: 'formItem',
|
||||
composition: {
|
||||
onRendered() {
|
||||
const instance = Template.instance();
|
||||
const component = instance.component;
|
||||
|
||||
// Add the form-action identification class
|
||||
component.$element.addClass('form-action');
|
||||
},
|
||||
|
||||
events: {
|
||||
'click .form-action'(event, instance) {
|
||||
event.preventDefault();
|
||||
const component = instance.component;
|
||||
|
||||
// Extract action, disabled state and params
|
||||
const { action } = instance.data;
|
||||
const params = instance.data.params ? instance.data.params : event;
|
||||
|
||||
// Set the focus back to the input that triggered the click with Enter key
|
||||
const $focused = $(':focus');
|
||||
const applyFocus = () => {
|
||||
if ($focused[0] && event.currentTarget !== $focused[0]) {
|
||||
setTimeout(() => $focused.focus());
|
||||
}
|
||||
};
|
||||
|
||||
// Stop here if the component is disabled
|
||||
if (component.$element.hasClass('disabled')) return;
|
||||
|
||||
// Get the current component's API
|
||||
const api = component.getApi();
|
||||
|
||||
if (typeof action === 'function') {
|
||||
// Call the action if it's a function
|
||||
component.actionResult = action.call(event.currentTarget, params, event);
|
||||
} else if (!api || !action || typeof api[action] !== 'function') {
|
||||
// Stop here if no API or action was defined
|
||||
return true;
|
||||
} else {
|
||||
// Call the defined action function
|
||||
component.actionResult = api[action].call(event.currentTarget, params, event);
|
||||
}
|
||||
|
||||
// Prepend a spinner into the action element content if it's a promise
|
||||
if (component.actionResult instanceof Promise) {
|
||||
const form = component.getForm();
|
||||
form.disable(true);
|
||||
const $spinner = $('<i class="fa fa-spin fa-circle-o-notch fa-fw m-r"></i>');
|
||||
component.$element.prepend($spinner);
|
||||
const finishAction = () => {
|
||||
$spinner.remove();
|
||||
form.disable(false);
|
||||
applyFocus();
|
||||
};
|
||||
|
||||
component.actionResult.then(finishAction).catch(finishAction);
|
||||
} else {
|
||||
applyFocus();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
@ -1,18 +0,0 @@
|
||||
import { OHIF } from 'meteor/ohif:core';
|
||||
import { Template } from 'meteor/templating';
|
||||
|
||||
/*
|
||||
* button: controls a button
|
||||
*/
|
||||
OHIF.mixins.button = new OHIF.Mixin({
|
||||
dependencies: 'formItem',
|
||||
composition: {
|
||||
onRendered() {
|
||||
const instance = Template.instance();
|
||||
const component = instance.component;
|
||||
|
||||
// Set the element to be controlled
|
||||
component.$element = instance.$('button').first();
|
||||
}
|
||||
}
|
||||
});
|
||||
@ -1,26 +0,0 @@
|
||||
import { OHIF } from 'meteor/ohif:core';
|
||||
import { Template } from 'meteor/templating';
|
||||
import _ from 'underscore';
|
||||
|
||||
/*
|
||||
* inputCheckbox: controls a checkbox input
|
||||
*/
|
||||
OHIF.mixins.checkbox = new OHIF.Mixin({
|
||||
dependencies: 'input',
|
||||
composition: {
|
||||
onCreated() {
|
||||
const instance = Template.instance();
|
||||
const component = instance.component;
|
||||
|
||||
// Get or set the checked state using jQuery's prop method
|
||||
component.value = value => {
|
||||
const isGet = _.isUndefined(value);
|
||||
if (isGet) {
|
||||
return component.parseData(component.$element.is(':checked'));
|
||||
}
|
||||
|
||||
component.$element.prop('checked', value).trigger('change');
|
||||
};
|
||||
}
|
||||
}
|
||||
});
|
||||
@ -1,10 +0,0 @@
|
||||
import { OHIF } from 'meteor/ohif:core';
|
||||
import { Template } from 'meteor/templating';
|
||||
|
||||
/*
|
||||
* component: base component structure
|
||||
*/
|
||||
OHIF.mixins.component = new OHIF.Mixin({
|
||||
composition: {
|
||||
}
|
||||
});
|
||||
@ -1,322 +0,0 @@
|
||||
import { Meteor } from 'meteor/meteor';
|
||||
import { Template } from 'meteor/templating';
|
||||
import { Blaze } from 'meteor/blaze';
|
||||
import { ReactiveVar } from 'meteor/reactive-var';
|
||||
import $ from 'jquery';
|
||||
import _ from 'underscore';
|
||||
import { OHIF } from 'meteor/ohif:core';
|
||||
|
||||
/*
|
||||
* dropdown: controls a dropdown
|
||||
*/
|
||||
OHIF.mixins.dropdown = new OHIF.Mixin({
|
||||
dependencies: 'form',
|
||||
composition: {
|
||||
onRendered() {
|
||||
const instance = Template.instance();
|
||||
const { event, centered, marginTop, $parentLi, reactiveClose } = instance.data.options;
|
||||
// Get the dropdown element to enable position manipulation
|
||||
const $dropdown = instance.$('.dropdown');
|
||||
const dropdown = $dropdown[0];
|
||||
const $dropdownMenu = $dropdown.children('.dropdown-menu');
|
||||
|
||||
// Get the timeout to dismiss the dropdown form
|
||||
let { dismissTimeout } = instance.data.options;
|
||||
if (_.isUndefined(dismissTimeout)) {
|
||||
dismissTimeout = 500;
|
||||
}
|
||||
|
||||
// Set a opening state to the component
|
||||
instance.opening = true;
|
||||
|
||||
// Destroy the Blaze created view (either created with template calls or with renderWithData)
|
||||
instance.destroyView = () => {
|
||||
const destroyHandle = () => {
|
||||
if (typeof instance.data.destroyView === 'function') {
|
||||
instance.data.destroyView();
|
||||
} else {
|
||||
Blaze.remove(instance.view);
|
||||
}
|
||||
};
|
||||
|
||||
const timeout = setTimeout(destroyHandle, dismissTimeout);
|
||||
$dropdownMenu.one('transitionend', () => {
|
||||
destroyHandle();
|
||||
clearTimeout(timeout);
|
||||
});
|
||||
$dropdown.removeClass('open');
|
||||
};
|
||||
|
||||
// Destroy the view when the promise is fullfilled
|
||||
instance.data.promise.then(instance.destroyView, instance.destroyView);
|
||||
|
||||
// Close submenu if exists
|
||||
instance.closeSubmenu = focusSelf => {
|
||||
if (instance.reactiveClose) {
|
||||
if (focusSelf) {
|
||||
$(instance.lastSubmenu).focus();
|
||||
}
|
||||
|
||||
instance.reactiveClose.set(true);
|
||||
delete instance.reactiveClose;
|
||||
delete instance.lastSubmenu;
|
||||
}
|
||||
};
|
||||
|
||||
// Close the dropdown resolving or rejecting the promise
|
||||
instance.close = (isResolve, result) => {
|
||||
const method = instance.data[isResolve ? 'promiseResolve' : 'promiseReject'];
|
||||
const param = result instanceof Promise ? null : result;
|
||||
method(param);
|
||||
instance.closeSubmenu(false);
|
||||
instance.closed = true;
|
||||
};
|
||||
|
||||
// Close the dropdown if the reactiveClose suffered changes
|
||||
if (reactiveClose) {
|
||||
instance.autorun(() => {
|
||||
const isClosed = reactiveClose.get();
|
||||
if (!isClosed) return;
|
||||
instance.close(false);
|
||||
});
|
||||
}
|
||||
|
||||
// Stop here and destroy the view if no items was given
|
||||
if (!instance.data.items.length) {
|
||||
return instance.close(false);
|
||||
}
|
||||
|
||||
dropdown.oncontextmenu = () => false;
|
||||
|
||||
const cssBefore = {};
|
||||
if (event) {
|
||||
cssBefore.position = 'fixed';
|
||||
$dropdownMenu.bounded();
|
||||
}
|
||||
|
||||
if (marginTop) {
|
||||
cssBefore['margin-top'] = marginTop;
|
||||
}
|
||||
|
||||
$dropdownMenu.css(cssBefore);
|
||||
|
||||
// Postpone visibility change to allow CSS transitions
|
||||
Meteor.defer(() => {
|
||||
// Show the dropdown and focus the first option
|
||||
$dropdown.addClass('open').find('a:first').focus();
|
||||
|
||||
// Add a handler to change the opening state
|
||||
$dropdownMenu.one('transitionend', event => {
|
||||
instance.opening = false;
|
||||
});
|
||||
|
||||
// Change the dropdown position if mouse event was given
|
||||
if (event) {
|
||||
const originalEventTouches = event.originalEvent && event.originalEvent.touches;
|
||||
const position = {
|
||||
left: 0,
|
||||
top: 0
|
||||
};
|
||||
|
||||
if (originalEventTouches && originalEventTouches.length > 0) {
|
||||
position.left = originalEventTouches[0].pageX;
|
||||
position.top = originalEventTouches[0].pageY;
|
||||
} else {
|
||||
position.left = event.clientX;
|
||||
position.top = event.clientY;
|
||||
}
|
||||
|
||||
if (centered) {
|
||||
// Center the dropdown menu based on the event mouse position
|
||||
position.left -= $dropdownMenu.outerWidth() / 2;
|
||||
position.top -= $dropdownMenu.outerHeight() / 2;
|
||||
} else if ($parentLi) {
|
||||
// Change the dropdown menu position based on the parent menu item
|
||||
const $parentDm = $parentLi.closest('.dropdown-menu');
|
||||
const dmWidth = $dropdownMenu.outerWidth();
|
||||
const pdmWidth = $parentDm.outerWidth();
|
||||
const pdmOffset = $parentDm.offset();
|
||||
const pliOffset = OHIF.ui.getOffset($parentLi[0]);
|
||||
Object.assign(position, {
|
||||
left: pdmWidth + pdmOffset.left,
|
||||
top: pliOffset.top
|
||||
});
|
||||
|
||||
// Check if the element position is going beyond the window right boundary
|
||||
let rightToLeft = false;
|
||||
if (position.left < pdmOffset.left + pdmWidth || position.left > document.body.clientWidth - dmWidth) {
|
||||
position.left -= pdmWidth + $dropdownMenu.outerWidth();
|
||||
rightToLeft = true;
|
||||
}
|
||||
|
||||
const menuClass = rightToLeft ? 'origin-top-right' : 'origin-top-left';
|
||||
$dropdownMenu.addClass(menuClass);
|
||||
}
|
||||
|
||||
// Fix dropdown position if it is going outside the window boundaries
|
||||
$dropdownMenu.css(position).trigger('spatialChanged');
|
||||
|
||||
// Check if scrolling will be needed
|
||||
const isFixed = $dropdownMenu.css('position') === 'fixed';
|
||||
if (isFixed && $dropdownMenu.outerHeight() > window.innerHeight) {
|
||||
$dropdownMenu.css({
|
||||
'overflow-y': 'scroll',
|
||||
'max-height': window.innerHeight
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
events: {
|
||||
'click .form-action'(event, instance) {
|
||||
const $target = $(event.currentTarget);
|
||||
const isDisabled = $target.hasClass('disabled');
|
||||
|
||||
if (isDisabled) {
|
||||
instance.close(false);
|
||||
} else {
|
||||
const component = $target.data('component');
|
||||
instance.close(true, component.actionResult);
|
||||
}
|
||||
},
|
||||
|
||||
'mouseenter .form-action, openSubmenu .form-action'(event, instance) {
|
||||
// Postpone the submenu opening if it's still being animated
|
||||
if (instance.opening) {
|
||||
instance.$('.dropdown-menu').one('transitionend', event => {
|
||||
$(event.currentTarget).trigger('openSubmenu');
|
||||
});
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Stop here if dropdown is already closed or event was triggered in child elements
|
||||
if (instance.closed || event.target !== event.currentTarget) return;
|
||||
|
||||
// Close the submenu if a sibling element was hovered
|
||||
if (instance.lastSubmenu && instance.lastSubmenu !== event.currentTarget) {
|
||||
instance.closeSubmenu(!this.items);
|
||||
}
|
||||
|
||||
// Stop here if submenu is already opened for the current menu item
|
||||
if (!this.items || instance.lastSubmenu === event.currentTarget) return;
|
||||
|
||||
// Close the current opened submenu (if exists) in order to open another one
|
||||
instance.closeSubmenu(!this.items);
|
||||
|
||||
// Set the reactive closing elementcontroller and the last submenu element trigger
|
||||
const reactiveClose = new ReactiveVar(false);
|
||||
instance.reactiveClose = reactiveClose;
|
||||
instance.lastSubmenu = event.currentTarget;
|
||||
|
||||
// Get the triggering li element and render the submenu
|
||||
const $parentLi = $(event.currentTarget).closest('li');
|
||||
OHIF.ui.showDropdown(this.items, {
|
||||
event,
|
||||
reactiveClose: instance.reactiveClose,
|
||||
$parentLi,
|
||||
parentInstance: instance,
|
||||
dismissTimeout: instance.data.options && instance.data.options.dismissTimeout
|
||||
}).then(instance.data.promiseResolve).catch(() => {});
|
||||
},
|
||||
|
||||
'keydown .form-action'(event, instance) {
|
||||
event.stopPropagation();
|
||||
const key = event.which;
|
||||
const $target = $(event.currentTarget);
|
||||
|
||||
// Allow navigation using DOWN and UP arrow keys
|
||||
if (key === 38 || key === 40) {
|
||||
const $parentLi = $target.closest('li');
|
||||
const $liList = $parentLi.parent().children();
|
||||
const index = $parentLi.index();
|
||||
|
||||
let $newLi;
|
||||
if (key === 38) {
|
||||
// Control the UP key
|
||||
if (index === 0) {
|
||||
$newLi = $liList.eq($liList.length - 1);
|
||||
} else {
|
||||
$newLi = $parentLi.prev();
|
||||
}
|
||||
} else {
|
||||
// Control the DOWN key
|
||||
if (index === $liList.length - 1) {
|
||||
$newLi = $liList.eq(0);
|
||||
} else {
|
||||
$newLi = $parentLi.next();
|
||||
}
|
||||
}
|
||||
|
||||
// Focus the link inside the new li element
|
||||
event.preventDefault();
|
||||
$newLi.find('a:first').focus();
|
||||
return;
|
||||
}
|
||||
|
||||
// Close the submenu if LEFT, BACKSPACE or ESC key was pressed
|
||||
const { parentInstance } = instance.data.options;
|
||||
if (parentInstance && (key === 37 || key === 8 || key === 27)) {
|
||||
event.preventDefault();
|
||||
return parentInstance.closeSubmenu(true);
|
||||
}
|
||||
|
||||
// Close the dropdown if there's no submenu open and ESC key was pressed
|
||||
if (!parentInstance && key === 27) {
|
||||
return instance.close(false);
|
||||
}
|
||||
|
||||
// Stop here if it's not a submenu trigger
|
||||
if (!this.items) return;
|
||||
|
||||
// Open the submenu if RIGHT, ENTER or SPACE key was pressed
|
||||
if (key === 39 || key === 13 || key === 32) {
|
||||
$target.trigger('openSubmenu');
|
||||
event.preventDefault();
|
||||
}
|
||||
},
|
||||
|
||||
'mousedown .dropdown'(event) {
|
||||
// This is required to stop blur event which is fired before click event
|
||||
// when a dropdown item is clicked, otherwise click event is not fired
|
||||
event.stopPropagation();
|
||||
},
|
||||
|
||||
'blur .dropdown'(event, instance) {
|
||||
// Stop here if it's closed or if it's a submenu not being closed
|
||||
if (instance.closed) return;
|
||||
if (instance.reactiveClose && !instance.reactiveClose.get()) return;
|
||||
|
||||
// Postpone the execution to enable getting the focused element
|
||||
Meteor.defer(() => {
|
||||
const $focus = $(':focus');
|
||||
|
||||
// Iterate over all parent dropdowns and check if one of them has the focus
|
||||
let hasFocus = false;
|
||||
let currentInstance = instance;
|
||||
do {
|
||||
if ($.contains(currentInstance.$('.dropdown')[0], $focus[0])) {
|
||||
hasFocus = true;
|
||||
break;
|
||||
}
|
||||
|
||||
if (!currentInstance.data.options.parentInstance) {
|
||||
break;
|
||||
} else {
|
||||
currentInstance = currentInstance.data.options.parentInstance;
|
||||
|
||||
// Close the current instance's submenu as it has no focus
|
||||
currentInstance.closeSubmenu(false);
|
||||
}
|
||||
} while (currentInstance);
|
||||
|
||||
// Close all dropdown levels if it lost the focus
|
||||
if (!hasFocus) {
|
||||
currentInstance.close(false);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
@ -1,108 +0,0 @@
|
||||
import { OHIF } from 'meteor/ohif:core';
|
||||
import { Template } from 'meteor/templating';
|
||||
import { Tracker } from 'meteor/tracker';
|
||||
import { Spacebars } from 'meteor/spacebars';
|
||||
import _ from 'underscore';
|
||||
import $ from 'jquery';
|
||||
|
||||
/*
|
||||
* form: controls a form and its registered inputs
|
||||
*/
|
||||
OHIF.mixins.form = new OHIF.Mixin({
|
||||
dependencies: 'group',
|
||||
composition: {
|
||||
onCreated() {
|
||||
const instance = Template.instance();
|
||||
const component = instance.component;
|
||||
|
||||
// Set the form identifier flag
|
||||
component.isForm = true;
|
||||
|
||||
// Set the form validated flag
|
||||
component.isValidatedAlready = false;
|
||||
|
||||
component.validationObserver = new Tracker.Dependency();
|
||||
|
||||
// Reset the pathKey
|
||||
instance.data.pathKey = '';
|
||||
|
||||
// Debound the observer call to prevent tons of re-rendering
|
||||
component.validationRan = _.throttle(() => {
|
||||
// Enable reactivity by changing a Tracker.Dependency observer
|
||||
component.validationObserver.changed();
|
||||
}, 200);
|
||||
|
||||
// Change the validation function to focus the fields with error
|
||||
const validateSelf = component.validate;
|
||||
component.validate = () => {
|
||||
// Call the original validation function
|
||||
const validationResult = validateSelf();
|
||||
|
||||
// Change the form validated flag to true
|
||||
component.isValidatedAlready = true;
|
||||
|
||||
// Focus the first error field if some validation failed
|
||||
if (component.schema && component.schema._invalidKeys.length) {
|
||||
Tracker.afterFlush(() => instance.$('.state-error :input:first').focus());
|
||||
}
|
||||
|
||||
return validationResult;
|
||||
};
|
||||
},
|
||||
|
||||
onRendered() {
|
||||
const instance = Template.instance();
|
||||
const component = instance.component;
|
||||
|
||||
// Set the component main and style elements
|
||||
component.$style = component.$element = instance.$('form').first();
|
||||
|
||||
// Block page redirecting on submit
|
||||
component.$element[0].onsubmit = () => false;
|
||||
},
|
||||
|
||||
events: {
|
||||
'click .validation-error-container a'(event, instance) {
|
||||
// Get the target key
|
||||
const targetKey = $(event.currentTarget).attr('data-target');
|
||||
|
||||
// Focus the first input inside the element with error state
|
||||
instance.$(`.state-error[data-key="${targetKey}"]`).find(':input:first').focus();
|
||||
}
|
||||
},
|
||||
|
||||
helpers: {
|
||||
validationErrors() {
|
||||
const instance = Template.instance();
|
||||
const component = instance.component;
|
||||
|
||||
// Create a dependency on child components validation
|
||||
component.validationObserver.depend();
|
||||
|
||||
// Stop here if no schema was defined for the form
|
||||
if (!component.schema) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if there were some validation errors
|
||||
if (component.schema._invalidKeys.length) {
|
||||
const result = [];
|
||||
|
||||
// Iterate over each validation error and add to result
|
||||
component.schema._invalidKeys.forEach(item => {
|
||||
const label = component.schema._schema[item.name].label;
|
||||
let message = component.schema.keyErrorMessage(item.name);
|
||||
message = message.replace(label, `<strong>${label}</strong>`);
|
||||
result.push({
|
||||
key: item.name,
|
||||
message: Spacebars.SafeString(message)
|
||||
});
|
||||
});
|
||||
|
||||
// Return the resulting validation errors
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
@ -1,337 +0,0 @@
|
||||
import { OHIF } from 'meteor/ohif:core';
|
||||
import { Template } from 'meteor/templating';
|
||||
import { Tracker } from 'meteor/tracker';
|
||||
import { Meteor } from 'meteor/meteor';
|
||||
import _ from 'underscore';
|
||||
import $ from 'jquery';
|
||||
|
||||
/*
|
||||
* formItem: create a generic controller for form items
|
||||
* It may be used to manage all components that belong to forms
|
||||
*/
|
||||
OHIF.mixins.formItem = new OHIF.Mixin({
|
||||
dependencies: 'schemaData',
|
||||
composition: {
|
||||
|
||||
onCreated() {
|
||||
const instance = Template.instance();
|
||||
const component = instance.component;
|
||||
|
||||
// Create a observer to monitor changed values
|
||||
component.changeObserver = new Tracker.Dependency();
|
||||
|
||||
// Register the component in the parent component
|
||||
component.registerSelf();
|
||||
|
||||
// Declare the component elements that will be manipulated
|
||||
component.$element = $();
|
||||
component.$style = $();
|
||||
component.$wrapper = $();
|
||||
|
||||
// Get or set the component's value using jQuery's val method
|
||||
component.value = value => {
|
||||
const isGet = _.isUndefined(value);
|
||||
if (isGet) {
|
||||
return component.parseData(component.$element.val());
|
||||
}
|
||||
|
||||
// Deferring the `change` event because it was being triggered before
|
||||
// formItem.onMixins execution when a defaultValue was specified. In
|
||||
// this case $elem.data('component') code from the event handler was
|
||||
// returning `undefined` and breaking the app
|
||||
Meteor.defer(() => {
|
||||
component.$element.val(value).trigger('change');
|
||||
});
|
||||
};
|
||||
|
||||
// Disable or enable the component
|
||||
component.disable = isDisable => {
|
||||
component.$element.prop('disabled', !!isDisable);
|
||||
};
|
||||
|
||||
// Set or unset component's readonly property
|
||||
component.readonly = isReadonly => {
|
||||
component.$element.prop('readonly', !!isReadonly);
|
||||
};
|
||||
|
||||
// Show or hide the component
|
||||
component.show = isShow => {
|
||||
const method = isShow ? 'show' : 'hide';
|
||||
component.$wrapper[method]();
|
||||
};
|
||||
|
||||
// Check if the focus is inside this element
|
||||
component.hasFocus = () => {
|
||||
// Get the focused element
|
||||
const focused = $(':focus')[0];
|
||||
|
||||
// Check if the focused element is inside the component
|
||||
const contains = $.contains(component.$wrapper[0], focused);
|
||||
const isEqual = component.$wrapper[0] === focused;
|
||||
|
||||
// Return true if he component has the focus
|
||||
return contains || isEqual;
|
||||
};
|
||||
|
||||
// Add or remove a state from the component
|
||||
component.state = (state, flag) => {
|
||||
component.$wrapper.toggleClass(`state-${state}`, !!flag);
|
||||
};
|
||||
|
||||
// Set the component in error state and display the error message
|
||||
component.error = errorMessage => {
|
||||
// Set the component error state
|
||||
component.state('error', !!errorMessage);
|
||||
|
||||
// Set or remove the error message
|
||||
if (errorMessage) {
|
||||
component.$wrapper.attr('data-error', errorMessage);
|
||||
} else {
|
||||
component.$wrapper.removeAttr('data-error', errorMessage);
|
||||
}
|
||||
};
|
||||
|
||||
// Toggle the tooltip over the component
|
||||
component.toggleTooltip = (isShow, message) => {
|
||||
if (isShow && message) {
|
||||
const tooltipId = component.$wrapper.attr('aria-describedby');
|
||||
const $tooltip = $(document.getElementById(tooltipId));
|
||||
if ($tooltip.length) {
|
||||
// Change the message if the tooltip is already created
|
||||
$tooltip.find('.tooltip-inner').text(message);
|
||||
} else {
|
||||
// Destroy the tooltip if already created, creating it again
|
||||
component.$wrapper.tooltip('destroy').tooltip({
|
||||
trigger: 'manual',
|
||||
title: message
|
||||
}).tooltip('show');
|
||||
}
|
||||
} else {
|
||||
// Destroy the tooltip
|
||||
component.$wrapper.tooltip('destroy');
|
||||
}
|
||||
};
|
||||
|
||||
// Toggle a state message as a tooltip over the component
|
||||
component.toggleMessage = isShow => {
|
||||
// Check if the action is to hide
|
||||
if (!isShow) {
|
||||
Meteor.setTimeout(() => {
|
||||
// Check if the component has the focus
|
||||
if (component.hasFocus()) {
|
||||
// Prevent the tooltip from being hidden
|
||||
return;
|
||||
}
|
||||
|
||||
// Hide the tooltip
|
||||
component.toggleTooltip(false);
|
||||
}, 100);
|
||||
return;
|
||||
}
|
||||
|
||||
// Check for error state and message
|
||||
const errorMessage = component.$wrapper.attr('data-error');
|
||||
if (errorMessage) {
|
||||
// Show the tooltip with the error message
|
||||
component.toggleTooltip(true, errorMessage);
|
||||
}
|
||||
};
|
||||
|
||||
// Search for the parent form component
|
||||
component.getForm = () => {
|
||||
let currentComponent = component;
|
||||
while (currentComponent) {
|
||||
currentComponent = currentComponent.parent;
|
||||
if (currentComponent && currentComponent.isForm) {
|
||||
return currentComponent;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Get the current component API
|
||||
component.getApi = () => {
|
||||
const api = instance.data.api;
|
||||
|
||||
// Check if the API was not given
|
||||
if (!api) {
|
||||
// Stop here if the component is form and API was not given
|
||||
if (component.isForm) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Get the current component's form
|
||||
const form = component.getForm();
|
||||
|
||||
// Stop here if the component has no form
|
||||
if (!form) {
|
||||
return;
|
||||
}
|
||||
|
||||
return form.getApi();
|
||||
}
|
||||
|
||||
// Return the given API
|
||||
return api;
|
||||
};
|
||||
|
||||
// Check if the component value is valid in its form's schema
|
||||
component.validate = () => {
|
||||
// Get the component's form
|
||||
const form = component.getForm();
|
||||
|
||||
// Get the form's data schema
|
||||
const schema = form && form.schema;
|
||||
|
||||
// Get the current component's key
|
||||
const key = instance.data.pathKey;
|
||||
|
||||
// Return true if validation is not needed
|
||||
if (!key || !schema || !component.$wrapper.is(':visible')) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Create the data document for validation
|
||||
const document = OHIF.object.getNestedObject({
|
||||
[key]: component.value()
|
||||
});
|
||||
|
||||
// Get the validation result
|
||||
const validationResult = schema.validateOne(document, key);
|
||||
|
||||
// Notify the form that the validation ran
|
||||
form.validationRan();
|
||||
|
||||
// Check if the document validation failed
|
||||
if (!validationResult) {
|
||||
// Set the component in error state and display the message
|
||||
component.error(schema.keyErrorMessage(key));
|
||||
|
||||
// Return false for validation
|
||||
return false;
|
||||
}
|
||||
|
||||
// Remove the component error state and message
|
||||
component.error(false);
|
||||
|
||||
// Return true for validation
|
||||
return true;
|
||||
};
|
||||
|
||||
component.depend = () => {
|
||||
return component.changeObserver.depend();
|
||||
};
|
||||
|
||||
// Click the first submit (or first button if submit not found) button on closest form
|
||||
component.triggerFormMainButton = () => {
|
||||
const $form = component.$element.closest('form');
|
||||
let $formButton = $form.find('button[type=submit]:first');
|
||||
if (!$formButton.length) {
|
||||
$formButton = $form.find('button:first');
|
||||
}
|
||||
|
||||
$formButton.click();
|
||||
};
|
||||
|
||||
},
|
||||
|
||||
onRendered() {
|
||||
const instance = Template.instance();
|
||||
const component = instance.component;
|
||||
|
||||
// Set the element to be controlled
|
||||
component.$element = instance.$(':input').first();
|
||||
|
||||
// Set the most outer wrapper element
|
||||
component.$wrapper = instance.wrapper.$('*').first();
|
||||
|
||||
// Add the pathKey to the wrapper element
|
||||
component.$wrapper.attr('data-key', instance.data.pathKey);
|
||||
|
||||
// Get the component's form
|
||||
const form = component.getForm();
|
||||
|
||||
// Observer for changes and revalidate the component
|
||||
instance.autorun(computation => {
|
||||
component.changeObserver.depend();
|
||||
|
||||
// Stop here if it is the first run
|
||||
if (computation.firstRun) return;
|
||||
|
||||
// Revalidate the component if form is already validated
|
||||
if (form && form.isValidatedAlready) {
|
||||
component.validate();
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
onDestroyed() {
|
||||
const instance = Template.instance();
|
||||
const component = instance.component;
|
||||
|
||||
// Get the component's form for further use
|
||||
const form = component.getForm();
|
||||
|
||||
// Unregister the component in the parent component
|
||||
component.unregisterSelf();
|
||||
|
||||
// Remove the component tooltip, error state and message
|
||||
component.error(false);
|
||||
component.toggleTooltip(false);
|
||||
|
||||
// Revalidate the form to remove this component from validation results
|
||||
if (form && form.isValidatedAlready) {
|
||||
form.validate();
|
||||
}
|
||||
},
|
||||
|
||||
onMixins() {
|
||||
const instance = Template.instance();
|
||||
const component = instance.component;
|
||||
|
||||
// If no style element was defined, set it as the element itself
|
||||
if (!component.$style.length) {
|
||||
component.$style = component.$element;
|
||||
}
|
||||
|
||||
// Set the component in element and wrapper jQuery data
|
||||
component.$element.data('component', component);
|
||||
component.$wrapper.data('component', component);
|
||||
},
|
||||
|
||||
events: {
|
||||
|
||||
// Handle the change event for the component
|
||||
change(event, instance) {
|
||||
const component = instance.component;
|
||||
|
||||
// Prevent execution on upper components
|
||||
if (event.currentTarget === component.$element[0]) {
|
||||
// Enable reactivity by changing a Tracker.Dependency observer
|
||||
component.changeObserver.changed();
|
||||
}
|
||||
},
|
||||
|
||||
focus(event, instance) {
|
||||
const component = instance.component;
|
||||
const isGroupOrCustomFocus = component.isGroup || component.isCustomFocus;
|
||||
const isSameTarget = event.target === event.currentTarget;
|
||||
if (!isGroupOrCustomFocus && isSameTarget) {
|
||||
// Check for state messages and show it
|
||||
component.toggleMessage(true);
|
||||
}
|
||||
},
|
||||
|
||||
blur(event, instance) {
|
||||
const component = instance.component;
|
||||
const isGroupOrCustomFocus = component.isGroup || component.isCustomFocus;
|
||||
const isSameTarget = event.target === event.currentTarget;
|
||||
if (!isGroupOrCustomFocus && isSameTarget) {
|
||||
// Check for state messages and show it
|
||||
component.toggleMessage(false);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
});
|
||||
@ -1,169 +0,0 @@
|
||||
import { OHIF } from 'meteor/ohif:core';
|
||||
import { Template } from 'meteor/templating';
|
||||
import { ReactiveVar } from 'meteor/reactive-var';
|
||||
import _ from 'underscore';
|
||||
|
||||
/*
|
||||
* group: controls a group and its registered items
|
||||
*/
|
||||
OHIF.mixins.group = new OHIF.Mixin({
|
||||
dependencies: 'formItem',
|
||||
composition: {
|
||||
onCreated() {
|
||||
const instance = Template.instance();
|
||||
const component = instance.component;
|
||||
|
||||
// Set the group identifier flag
|
||||
component.isGroup = true;
|
||||
|
||||
// Run this computation every time the schema property is changed
|
||||
instance.autorun(() => {
|
||||
let schema = instance.data.schema;
|
||||
|
||||
// Check if the schema is reactive
|
||||
if (schema instanceof ReactiveVar) {
|
||||
// Register a dependency on schema property
|
||||
schema = schema.get();
|
||||
}
|
||||
|
||||
// Set the form's data schema
|
||||
component.schema = schema && schema.newContext();
|
||||
});
|
||||
|
||||
// Get or set the child components values
|
||||
component.value = value => {
|
||||
const isGet = _.isUndefined(value);
|
||||
const isArray = instance.data.arrayValues;
|
||||
|
||||
// Create the result data as array or object
|
||||
const result = isArray ? [] : {};
|
||||
|
||||
// Get the group current value and return it
|
||||
if (isGet) {
|
||||
// Iterate over each registered item and extract its value
|
||||
component.registeredItems.forEach(child => {
|
||||
// Check if it is an array or an object group
|
||||
if (isArray) {
|
||||
// Get the mixins array
|
||||
const mixins = child.templateInstance.data.mixins.split(' ');
|
||||
|
||||
// Prevent reading action components
|
||||
if (mixins.indexOf('action') > -1) return;
|
||||
|
||||
// Push the item value to the result array
|
||||
result.push(child.value());
|
||||
} else {
|
||||
// Get the item key
|
||||
const key = child.templateInstance.data.key;
|
||||
|
||||
//Check if a key is set for the item
|
||||
if (key) {
|
||||
// Add the item value to the result object
|
||||
result[key] = child.value();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Return the resulting data as array or object
|
||||
return result;
|
||||
}
|
||||
|
||||
// Get the group current value
|
||||
const groupValue = typeof value === 'object' ? value : result;
|
||||
|
||||
// Stop here if there is no value defined for this group
|
||||
if (!groupValue) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Iterate over each registered item and set its value
|
||||
let i = 0;
|
||||
component.registeredItems.forEach(child => {
|
||||
const mixins = child.templateInstance.data.mixins.split(' ');
|
||||
|
||||
// Prevent reading action components
|
||||
if (isArray && mixins.indexOf('action') > -1) return;
|
||||
|
||||
const key = isArray ? i : child.templateInstance.data.key;
|
||||
const childValue = _.isUndefined(groupValue[key]) ? null : groupValue[key];
|
||||
child.value(childValue);
|
||||
i++;
|
||||
});
|
||||
|
||||
// Trigger the change event after setting the new value
|
||||
component.$element.trigger('change');
|
||||
};
|
||||
|
||||
// Get a registered item in form by its key
|
||||
component.item = itemKey => {
|
||||
let found;
|
||||
|
||||
// Iterate over each registered form item
|
||||
component.registeredItems.forEach(child => {
|
||||
const key = child.templateInstance.data.key;
|
||||
|
||||
// Change the found item if current key is the same as given
|
||||
if (key === itemKey) {
|
||||
found = child;
|
||||
}
|
||||
});
|
||||
|
||||
// Return the found item or undefined if it was not found
|
||||
return found;
|
||||
};
|
||||
|
||||
// Check if the form data is valid in its schema
|
||||
const validateSelf = component.validate;
|
||||
component.validate = () => {
|
||||
// Assume validation result as true
|
||||
let result = true;
|
||||
|
||||
// Return true if there's no data schema defined
|
||||
if (component.isForm && !component.schema) {
|
||||
return result;
|
||||
}
|
||||
|
||||
// Reset the validation
|
||||
const schema = component.isForm ? component.schema : component.getForm().schema;
|
||||
schema.resetValidation();
|
||||
|
||||
// Validate the component itself if it has a key
|
||||
if (instance.data.pathKey && !validateSelf()) {
|
||||
result = false;
|
||||
}
|
||||
|
||||
// Iterate over each registered form item and validate it
|
||||
component.registeredItems.forEach(child => {
|
||||
const key = child.templateInstance.data.key;
|
||||
|
||||
// Change result to false if any form item is invalid
|
||||
if ((key || instance.data.arrayValues) && !child.validate()) {
|
||||
result = false;
|
||||
}
|
||||
});
|
||||
|
||||
// Return the validation result
|
||||
return result;
|
||||
};
|
||||
|
||||
// Disable or enable the component
|
||||
component.disable = isDisable => {
|
||||
component.registeredItems.forEach(child => child.disable(isDisable));
|
||||
};
|
||||
|
||||
// Set or unset component's readonly property
|
||||
component.readonly = isReadonly => {
|
||||
component.registeredItems.forEach(child => child.readonly(isReadonly));
|
||||
};
|
||||
|
||||
},
|
||||
|
||||
onRendered() {
|
||||
const instance = Template.instance();
|
||||
const component = instance.component;
|
||||
|
||||
// Set the element to be controlled
|
||||
component.$element = instance.$('.component-group').first();
|
||||
}
|
||||
}
|
||||
});
|
||||
@ -1,32 +0,0 @@
|
||||
import { OHIF } from 'meteor/ohif:core';
|
||||
import { Template } from 'meteor/templating';
|
||||
import _ from 'underscore';
|
||||
import $ from 'jquery';
|
||||
|
||||
/*
|
||||
* groupRadio: controls all the radio inputs inside the group
|
||||
*/
|
||||
OHIF.mixins.groupRadio = new OHIF.Mixin({
|
||||
dependencies: 'group',
|
||||
composition: {
|
||||
|
||||
onCreated() {
|
||||
const instance = Template.instance();
|
||||
const component = instance.component;
|
||||
|
||||
// Get the selected radio's value or select a radio based on value
|
||||
component.value = value => {
|
||||
const isGet = _.isUndefined(value);
|
||||
const elements = [];
|
||||
component.registeredItems.forEach(child => elements.push(child.$element[0]));
|
||||
const $elements = $(elements);
|
||||
if (isGet) {
|
||||
return component.parseData($elements.filter(':checked').val());
|
||||
}
|
||||
|
||||
$elements.filter(`[value='${value}']`).prop('checked', true).trigger('change');
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
});
|
||||
@ -1,18 +0,0 @@
|
||||
import { OHIF } from 'meteor/ohif:core';
|
||||
import { Template } from 'meteor/templating';
|
||||
|
||||
/*
|
||||
* input: controls a basic input
|
||||
*/
|
||||
OHIF.mixins.input = new OHIF.Mixin({
|
||||
dependencies: 'formItem',
|
||||
composition: {
|
||||
onRendered() {
|
||||
const instance = Template.instance();
|
||||
const component = instance.component;
|
||||
|
||||
// Set the element to be controlled
|
||||
component.$element = instance.$('input').first();
|
||||
}
|
||||
}
|
||||
});
|
||||
@ -1,26 +0,0 @@
|
||||
import { Template } from 'meteor/templating';
|
||||
import { OHIF } from 'meteor/ohif:core';
|
||||
|
||||
/*
|
||||
* link: controls a link
|
||||
*/
|
||||
OHIF.mixins.link = new OHIF.Mixin({
|
||||
dependencies: 'formItem',
|
||||
composition: {
|
||||
onRendered() {
|
||||
const instance = Template.instance();
|
||||
const component = instance.component;
|
||||
|
||||
// Set the element to be controlled
|
||||
component.$element = instance.$('a').first();
|
||||
},
|
||||
|
||||
events: {
|
||||
'click a'(event, instance) {
|
||||
if (instance.data.action) {
|
||||
event.preventDefault();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
@ -1,40 +0,0 @@
|
||||
import { Meteor } from 'meteor/meteor';
|
||||
import { Template } from 'meteor/templating';
|
||||
import $ from 'jquery';
|
||||
import { OHIF } from 'meteor/ohif:core';
|
||||
|
||||
/*
|
||||
* popover: controls a popover
|
||||
*/
|
||||
OHIF.mixins.popover = new OHIF.Mixin({
|
||||
dependencies: 'form',
|
||||
composition: {
|
||||
onRendered() {
|
||||
const instance = Template.instance();
|
||||
instance.$form = instance.$('form').first();
|
||||
instance.$form.find(':input:first').focus();
|
||||
},
|
||||
|
||||
events: {
|
||||
'blur form'(event, instance) {
|
||||
Meteor.defer(() => {
|
||||
const $focus = $(':focus');
|
||||
if (!$.contains(instance.$form[0], $focus[0])) {
|
||||
instance.data.promiseReject();
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
'click .btn-cancel'(event, instance) {
|
||||
event.stopPropagation();
|
||||
instance.data.promiseReject();
|
||||
},
|
||||
|
||||
'click .btn-confirm'(event, instance) {
|
||||
event.stopPropagation();
|
||||
const form = instance.$('form').data('component');
|
||||
instance.data.promiseResolve(form.value());
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
@ -1,189 +0,0 @@
|
||||
import { OHIF } from 'meteor/ohif:core';
|
||||
import { Blaze } from 'meteor/blaze';
|
||||
import { Template } from 'meteor/templating';
|
||||
import { ReactiveVar } from 'meteor/reactive-var';
|
||||
import { Tracker } from 'meteor/tracker';
|
||||
import _ from 'underscore';
|
||||
|
||||
// Helper function to get the component's current schema
|
||||
const getCurrentSchemaDefs = (parentComponent, key) => {
|
||||
// Get the parent component schema
|
||||
let schema = parentComponent && parentComponent.schema;
|
||||
let schemaComponentHolder = parentComponent;
|
||||
|
||||
// Try to get the form schema if it was not found
|
||||
if (parentComponent && !schema) {
|
||||
const form = parentComponent.getForm();
|
||||
schema = form && form.schema;
|
||||
schemaComponentHolder = form;
|
||||
}
|
||||
|
||||
// Stop here if there's no key or schema defined
|
||||
if (!key || !schema) {
|
||||
return { schemaComponentHolder };
|
||||
}
|
||||
|
||||
// Get the current schema data using component's key
|
||||
const currentSchema = _.clone(schema._schema[key]);
|
||||
|
||||
// Stop here if no schema was found for the given key
|
||||
if (!currentSchema) {
|
||||
return { schemaComponentHolder };
|
||||
}
|
||||
|
||||
// Merge the sub-schema properties if it's an array
|
||||
if (Array.isArray(currentSchema.type())) {
|
||||
_.extend(currentSchema, schema._schema[key + '.$']);
|
||||
}
|
||||
|
||||
// Return the component's schema definitions
|
||||
return {
|
||||
currentSchema,
|
||||
schemaComponentHolder
|
||||
};
|
||||
};
|
||||
|
||||
/*
|
||||
* schemaData: change the component data based on its form's schema data
|
||||
*/
|
||||
OHIF.mixins.schemaData = new OHIF.Mixin({
|
||||
dependencies: 'component',
|
||||
composition: {
|
||||
|
||||
onData() {
|
||||
// Get the current template data
|
||||
const data = Template.currentData();
|
||||
|
||||
// Get the parent component
|
||||
const parent = OHIF.blaze.getParentComponent(Blaze.currentView);
|
||||
|
||||
// Get he parent component key
|
||||
const parentKey = parent && parent.templateInstance.data.pathKey;
|
||||
|
||||
// Check if the parent is an array group
|
||||
const isParentArray = parent && parent.templateInstance.data.arrayValues;
|
||||
|
||||
// Set the path key for this component
|
||||
data.pathKey = data.key || (isParentArray ? '$' : '');
|
||||
if (data.pathKey && typeof parentKey === 'string') {
|
||||
const prefix = parentKey ? `${parentKey}.` : '';
|
||||
data.pathKey = `${prefix}${data.pathKey}`;
|
||||
}
|
||||
|
||||
// Get the current schema data using component's key
|
||||
const { currentSchema } = getCurrentSchemaDefs(parent, data.pathKey);
|
||||
|
||||
// Stop here if there's no schema data for current key
|
||||
if (!currentSchema) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Use schema's label if it was not defined
|
||||
if (!data.label) {
|
||||
data.label = new ReactiveVar(currentSchema.label);
|
||||
}
|
||||
|
||||
// Set the min value
|
||||
if (_.isUndefined(data.min) && currentSchema.min) {
|
||||
data.min = currentSchema.min;
|
||||
}
|
||||
|
||||
// Set the max value
|
||||
if (_.isUndefined(data.max) && currentSchema.max) {
|
||||
data.max = currentSchema.max;
|
||||
}
|
||||
|
||||
// Set the emptyOption data attribute if given on schema
|
||||
if (currentSchema.emptyOption) {
|
||||
data.emptyOption = currentSchema.emptyOption;
|
||||
}
|
||||
|
||||
// Fill the items if it's an array schema
|
||||
if (!data.items && Array.isArray(currentSchema.allowedValues)) {
|
||||
data.items = data.items instanceof ReactiveVar ? data.items : new ReactiveVar();
|
||||
|
||||
Tracker.autorun(() => {
|
||||
const schemaDefs = getCurrentSchemaDefs(parent, data.pathKey);
|
||||
|
||||
// Check if schema is reactive and add reactivity to this function if so
|
||||
const componentHolder = schemaDefs.schemaComponentHolder;
|
||||
if (componentHolder.templateInstance.data.schema instanceof ReactiveVar) {
|
||||
componentHolder.templateInstance.data.schema.dep.depend();
|
||||
}
|
||||
|
||||
// Get the values and labels arrays from schema
|
||||
const values = schemaDefs.currentSchema.allowedValues;
|
||||
const labels = schemaDefs.currentSchema.valuesLabels || [];
|
||||
|
||||
// Initialize the items array
|
||||
const items = [];
|
||||
|
||||
// Iterate the allowed values array
|
||||
for (let i = 0; i < values.length; i++) {
|
||||
// Push the current item to the items array
|
||||
items.push({
|
||||
value: values[i],
|
||||
label: labels[i] || values[i]
|
||||
});
|
||||
}
|
||||
|
||||
// Add the items to a reactive instance
|
||||
data.items.set(items);
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
onCreated() {
|
||||
const instance = Template.instance();
|
||||
const component = instance.component;
|
||||
|
||||
// Create a data parser according to current schema key
|
||||
component.parseData = value => {
|
||||
// Get the current schema data using component's key
|
||||
const { currentSchema } = getCurrentSchemaDefs(component.parent, instance.data.pathKey);
|
||||
const { dataType } = instance.data;
|
||||
|
||||
// Stop here if there's no schema data for current key or no dataType defined
|
||||
if (!currentSchema && !dataType) {
|
||||
return value;
|
||||
}
|
||||
|
||||
// Get the schema type
|
||||
const schemaType = currentSchema && currentSchema.type;
|
||||
|
||||
// Check if the type is Number
|
||||
if (schemaType === Number || dataType === 'Number') {
|
||||
return parseFloat(value);
|
||||
}
|
||||
|
||||
// Check if the type is Boolean
|
||||
if (schemaType === Boolean || dataType === 'Boolean') {
|
||||
return !!value;
|
||||
}
|
||||
|
||||
// Return the original value if none of the checks matched
|
||||
return value;
|
||||
};
|
||||
},
|
||||
|
||||
onMixins() {
|
||||
const instance = Template.instance();
|
||||
const component = instance.component;
|
||||
|
||||
// Get the current schema data using component's key
|
||||
const { currentSchema } = getCurrentSchemaDefs(component.parent, instance.data.pathKey);
|
||||
|
||||
// Stop here if there's no schema data for current key
|
||||
if (!currentSchema) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Fill the component with its default value after rendering
|
||||
if (!_.isUndefined(currentSchema.defaultValue)) {
|
||||
component.defaultValue = currentSchema.defaultValue;
|
||||
component.value(currentSchema.defaultValue);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
});
|
||||
@ -1,18 +0,0 @@
|
||||
import { OHIF } from 'meteor/ohif:core';
|
||||
import { Template } from 'meteor/templating';
|
||||
|
||||
/*
|
||||
* input: controls a basic select
|
||||
*/
|
||||
OHIF.mixins.select = new OHIF.Mixin({
|
||||
dependencies: 'formItem',
|
||||
composition: {
|
||||
onRendered() {
|
||||
const instance = Template.instance();
|
||||
const component = instance.component;
|
||||
|
||||
// Set the element to be controlled
|
||||
component.$element = instance.$('select').first();
|
||||
}
|
||||
}
|
||||
});
|
||||
@ -1,229 +0,0 @@
|
||||
import { Template } from 'meteor/templating';
|
||||
import { ReactiveVar } from 'meteor/reactive-var';
|
||||
import { Tracker } from 'meteor/tracker';
|
||||
import _ from 'underscore';
|
||||
import $ from 'jquery';
|
||||
import { OHIF } from 'meteor/ohif:core';
|
||||
|
||||
/*
|
||||
* input: controls a select2 component
|
||||
*/
|
||||
OHIF.mixins.select2 = new OHIF.Mixin({
|
||||
dependencies: 'select',
|
||||
composition: {
|
||||
onCreated() {
|
||||
const instance = Template.instance();
|
||||
const { component, data } = instance;
|
||||
|
||||
// Controls select2 initialization
|
||||
instance.isInitialized = false;
|
||||
|
||||
// Set the custom focus flag
|
||||
component.isCustomFocus = true;
|
||||
|
||||
const valueMethod = component.value;
|
||||
component.value = value => {
|
||||
if (_.isUndefined(value) && !instance.isInitialized) {
|
||||
if (!_.isUndefined(instance.data.value)) return instance.data.value;
|
||||
if (!_.isUndefined(component.defaultValue)) return component.defaultValue;
|
||||
return;
|
||||
}
|
||||
|
||||
return valueMethod(value);
|
||||
};
|
||||
|
||||
// Utility function to get the dropdown jQuery element
|
||||
instance.getDropdownContainerElement = () => {
|
||||
const $select2 = component.$element.nextAll('.select2:first');
|
||||
const containerId = $select2.find('.select2-selection').attr('aria-owns');
|
||||
return $(`#${containerId}`).closest('.select2-container');
|
||||
};
|
||||
|
||||
// Check if this select will include a placeholder
|
||||
const placeholder = data.options && data.options.placeholder;
|
||||
if (placeholder) {
|
||||
instance.autorun(() => {
|
||||
// Get the option items
|
||||
let items = data.items;
|
||||
|
||||
// Check if the items are reactive and get them if true
|
||||
const isReactive = items instanceof ReactiveVar;
|
||||
if (isReactive) {
|
||||
items = items.get();
|
||||
}
|
||||
|
||||
// Check if there is already an empty option on items list
|
||||
// Note: If this is a multi-select input. Do not add a placeholder
|
||||
const isMultiple = instance.data.options && instance.data.options.multiple;
|
||||
if (!_.findWhere(items, { value: '' }) && isMultiple === false) {
|
||||
// Clone the current items
|
||||
const newItems = _.clone(items) || [];
|
||||
newItems.unshift({
|
||||
label: placeholder,
|
||||
value: ''
|
||||
});
|
||||
|
||||
// Set the new items list including the empty option
|
||||
if (isReactive) {
|
||||
data.items.set(newItems);
|
||||
} else {
|
||||
data.items = newItems;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
onRendered() {
|
||||
const instance = Template.instance();
|
||||
const { component, data } = instance;
|
||||
|
||||
// Destroy and re-create the select2 instance
|
||||
instance.rebuildSelect2 = () => {
|
||||
// Destroy the select2 instance if exists and re-create it
|
||||
if (component.select2Instance) {
|
||||
component.select2Instance.destroy();
|
||||
}
|
||||
|
||||
// Clone the options and check if the select2 should be initialized inside a modal
|
||||
const options = _.clone(data.options);
|
||||
const $closestModal = component.$element.closest('.modal');
|
||||
if ($closestModal.length) {
|
||||
options.dropdownParent = $closestModal;
|
||||
}
|
||||
|
||||
// Apply the select2 to the component
|
||||
component.$element.select2(options);
|
||||
|
||||
// Store the select2 instance to allow its further destruction
|
||||
component.select2Instance = component.$element.data('select2');
|
||||
|
||||
// Get the focusable elements
|
||||
const elements = [];
|
||||
const $select2 = component.$element.nextAll('.select2:first');
|
||||
const $select2Selection = $select2.find('.select2-selection');
|
||||
elements.push(component.$element[0]);
|
||||
elements.push($select2Selection[0]);
|
||||
|
||||
// Attach focus and blur handlers to focusable elements
|
||||
$(elements).on('focus', event => {
|
||||
instance.isFocused = true;
|
||||
if (event.target === event.currentTarget) {
|
||||
// Show the state message on elements focus
|
||||
component.toggleMessage(true);
|
||||
}
|
||||
}).on('blur', event => {
|
||||
instance.isFocused = false;
|
||||
if (event.target === event.currentTarget) {
|
||||
// Hide the state message on elements blur
|
||||
component.toggleMessage(false);
|
||||
}
|
||||
});
|
||||
|
||||
// Redirect keydown events from input to the select2 selection handler
|
||||
component.$element.on('keydown ', event => {
|
||||
event.preventDefault();
|
||||
$select2.find('.select2-selection').trigger(event);
|
||||
});
|
||||
|
||||
// Keep focus on element if ESC was pressed
|
||||
$select2.on('keydown ', event => {
|
||||
if (event.which === 27) {
|
||||
instance.component.$element.focus();
|
||||
}
|
||||
});
|
||||
|
||||
// Handle dropdown opening when focusing the selection element
|
||||
$select2Selection.on('keydown ', event => {
|
||||
const skipKeys = new Set([8, 9, 12, 16, 17, 18, 20, 27, 46, 91, 93]);
|
||||
const functionKeysRegex = /F[0-9]([0-9])?$/;
|
||||
const isFunctionKey = functionKeysRegex.test(event.key);
|
||||
if (skipKeys.has(event.which) || isFunctionKey) {
|
||||
return;
|
||||
}
|
||||
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
|
||||
// Open the select2 dropdown
|
||||
instance.component.$element.select2('open');
|
||||
|
||||
// Check if the pressed key will produce a character
|
||||
const searchSelector = '.select2-search__field';
|
||||
const $search = component.select2Instance.$dropdown.find(searchSelector);
|
||||
const isChar = OHIF.ui.isCharacterKeyPress(event);
|
||||
const char = event.key;
|
||||
if ($search.length && isChar && char.length === 1) {
|
||||
// Event needs to be triggered twice to work properly with this plugin
|
||||
$search.val(char).trigger('input').trigger('input');
|
||||
}
|
||||
});
|
||||
|
||||
// Set select2 as initialized
|
||||
instance.isInitialized = true;
|
||||
};
|
||||
|
||||
instance.autorun(() => {
|
||||
// Run this computation every time the reactive items suffer any changes
|
||||
const isReactive = data.items instanceof ReactiveVar;
|
||||
if (isReactive) {
|
||||
data.items.dep.depend();
|
||||
}
|
||||
|
||||
if (isReactive) {
|
||||
// Keep the current value of the component
|
||||
const currentValue = component.value();
|
||||
const wasFocused = instance.isFocused;
|
||||
|
||||
Tracker.afterFlush(() => {
|
||||
component.$element.val(currentValue);
|
||||
instance.rebuildSelect2();
|
||||
|
||||
if (wasFocused) {
|
||||
component.$element.focus();
|
||||
}
|
||||
});
|
||||
} else {
|
||||
instance.rebuildSelect2();
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
events: {
|
||||
// Focus element when selecting a value
|
||||
'select2:select'(event, instance) {
|
||||
instance.component.$element.focus();
|
||||
},
|
||||
|
||||
// Focus the element when closing the dropdown container using ESC key
|
||||
'select2:open'(event, instance) {
|
||||
const { minimumResultsForSearch } = instance.data.options;
|
||||
if (minimumResultsForSearch === Infinity || minimumResultsForSearch === -1) return;
|
||||
const $container = instance.getDropdownContainerElement();
|
||||
|
||||
if (!instance.data.wrapText) {
|
||||
$container.addClass('select2-container-nowrap');
|
||||
}
|
||||
|
||||
const $searchInput = $container.find('.select2-search__field');
|
||||
$searchInput.on('keydown.focusOnFinish', event => {
|
||||
const keys = new Set([9, 13, 27]);
|
||||
if (keys.has(event.which)) {
|
||||
$searchInput.off('keydown.focusOnFinish');
|
||||
instance.component.$element.focus();
|
||||
}
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
onDestroyed() {
|
||||
const instance = Template.instance();
|
||||
const { component } = instance;
|
||||
|
||||
// Destroy the select2 instance to remove unwanted DOM elements
|
||||
if (component.select2Instance) {
|
||||
component.select2Instance.destroy();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
@ -1,3 +0,0 @@
|
||||
<template name="section">{{! TODO: use whitespace control when/if it's available (https://github.com/meteor/blaze/issues/88)
|
||||
}}{{>instance.renderFunction.get instance.sectionData.get}}{{!
|
||||
}}</template>
|
||||
@ -1,61 +0,0 @@
|
||||
import { Template } from 'meteor/templating';
|
||||
import { Tracker } from 'meteor/tracker';
|
||||
import { ReactiveVar } from 'meteor/reactive-var';
|
||||
import { OHIF } from 'meteor/ohif:core';
|
||||
|
||||
Template.section.onCreated(() => {
|
||||
const instance = Template.instance();
|
||||
|
||||
// Create the render function and section data as reactive objects
|
||||
instance.renderFunction = new ReactiveVar(null);
|
||||
instance.sectionData = new ReactiveVar(null);
|
||||
|
||||
// Get the section name
|
||||
const sectionName = instance.data;
|
||||
|
||||
// Stop here if no section name was defined
|
||||
if (!sectionName) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Get the content block
|
||||
const templateContentBlock = instance.view.templateContentBlock;
|
||||
|
||||
// Get the parent template view of this section block
|
||||
let currentView = OHIF.blaze.getParentTemplateView(instance.view);
|
||||
|
||||
// Check if it is defining or printing the section content
|
||||
if (templateContentBlock) {
|
||||
// Define a section map for template's view if none was yet set
|
||||
if (!currentView._sectionMap) {
|
||||
currentView._sectionMap = new Map();
|
||||
}
|
||||
|
||||
// Define the content
|
||||
currentView._sectionMap.set(sectionName, {
|
||||
data: Object.assign({}, currentView._templateInstance.data),
|
||||
renderFunction: templateContentBlock.renderFunction
|
||||
});
|
||||
} else {
|
||||
// Wait for re-rendering and print the section content
|
||||
Tracker.afterFlush(() => {
|
||||
// Get the defined section's content
|
||||
const section = OHIF.blaze.getSectionContent(currentView, sectionName);
|
||||
|
||||
// Stop here if the section content is not defined
|
||||
if (!section) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Set the section data on its respective reactive object
|
||||
instance.sectionData.set(section.data);
|
||||
|
||||
// Set the render function on its respective reactive object
|
||||
instance.renderFunction.set(new Template(section.renderFunction));
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
Template.registerHelper('hasSection', sectionName => {
|
||||
return !!OHIF.blaze.getSectionContent(Template.instance().view, sectionName);
|
||||
});
|
||||
@ -1,112 +0,0 @@
|
||||
import { Template } from 'meteor/templating';
|
||||
import { Blaze } from 'meteor/blaze';
|
||||
import _ from 'underscore';
|
||||
import { OHIF } from 'meteor/ohif:core';
|
||||
|
||||
// Create a new custom template for the base component
|
||||
Template.baseComponent = new Template('baseComponent', () => {});
|
||||
|
||||
// Inject some custom behaviors in the view's construction function
|
||||
Template.baseComponent.constructView = function(contentFunc, elseFunc) {
|
||||
// Get the data passed to the template
|
||||
const data = Template.currentData();
|
||||
|
||||
if (!data) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Check the base template. If it's not informed set as the custom base
|
||||
data.base || (data.base = 'baseCustom');
|
||||
|
||||
// Get the base template object
|
||||
const baseTemplate = Template[data.base];
|
||||
|
||||
// Throw an error if the base template does not exists
|
||||
if (!baseTemplate) {
|
||||
throw new Error(`Template ${data.base} not found.`);
|
||||
}
|
||||
|
||||
// Declare the template object and name it as base name + 'Component'
|
||||
const template = OHIF.blaze.cloneTemplate(baseTemplate, data.base + 'Component');
|
||||
|
||||
// Extract the render function from the base template
|
||||
template.renderFunction = baseTemplate.renderFunction;
|
||||
|
||||
// Init the data manipulation mixins
|
||||
OHIF.Mixin.initData(data);
|
||||
|
||||
// Create and fill a list of wrappers that will enclose the component
|
||||
const wrappers = [];
|
||||
if (data.wrappers) {
|
||||
const wrappersList = data.wrappers.split(' ');
|
||||
_.each(wrappersList, wrapper => wrapper && wrappers.push(wrapper));
|
||||
}
|
||||
|
||||
// Declare a variable to store the wrapper instances that will be rendered
|
||||
const wrapperInstances = [];
|
||||
|
||||
// Declare the content function to render the component
|
||||
let contentFunction = () => {
|
||||
// Create the most inner content function
|
||||
const innerContentFunction = () => {
|
||||
// Return the view instance
|
||||
return template.constructView(contentFunc, elseFunc);
|
||||
};
|
||||
|
||||
// Assign properties to all wrappers after template's creation
|
||||
template.onCreated(() => {
|
||||
const instance = Template.instance();
|
||||
|
||||
// create the base structure to aplly specific component mixins
|
||||
instance.component = new OHIF.Component(instance);
|
||||
|
||||
// Assign the template most outer wrapper
|
||||
instance.wrapper = wrapperInstances[0] || instance;
|
||||
|
||||
// Iterate over all wrappers and assign the component to them
|
||||
wrapperInstances.forEach(wrapperInstance => {
|
||||
wrapperInstance.component = instance.component;
|
||||
});
|
||||
});
|
||||
|
||||
// Apply the mixins to the component
|
||||
OHIF.Mixin.initAll(template, data);
|
||||
|
||||
// Return the recursive function for wrappers
|
||||
return Blaze.With(data, innerContentFunction);
|
||||
};
|
||||
|
||||
let wrapper;
|
||||
while (wrapper = wrappers.shift()) {
|
||||
// Get the wrapper template
|
||||
const wrapperTemplate = Template[wrapper];
|
||||
|
||||
// Throw an error if the wrapper template does not exists
|
||||
if (!wrapperTemplate) {
|
||||
throw new Error(`Template ${wrapper} not found.`);
|
||||
}
|
||||
|
||||
// Clone the wrapper template to avoid assigning duplicated handlers
|
||||
const currentTemplate = OHIF.blaze.cloneTemplate(wrapperTemplate);
|
||||
|
||||
// Store the child content function to render it inside the wrapper
|
||||
const childContentFunction = contentFunction;
|
||||
|
||||
// Create a function that will enable the recursion for wrappers
|
||||
const enclosingContentFunction = () => {
|
||||
// Add the current wrapper's instance to the wrapper instances list
|
||||
currentTemplate.onCreated(() => wrapperInstances.push(Template.instance()));
|
||||
|
||||
// Return the wrapper view instance with its child as content
|
||||
return currentTemplate.constructView(childContentFunction, elseFunc);
|
||||
};
|
||||
|
||||
// Replace the content function enclosing it recursively
|
||||
contentFunction = () => {
|
||||
return Blaze.With(data, enclosingContentFunction);
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
return contentFunction(contentFunc, elseFunc);
|
||||
};
|
||||
@ -1,12 +0,0 @@
|
||||
<template name="baseButton">
|
||||
<button
|
||||
id="{{this.id}}"
|
||||
class="{{this.class}}"
|
||||
disabled="{{#if this.disabled}}disabled{{/if}}"
|
||||
title="{{this.title}}"
|
||||
type="{{this.type}}"
|
||||
{{this.tagAttributes}}
|
||||
>
|
||||
{{>UI.contentBlock}}
|
||||
</button>
|
||||
</template>
|
||||
@ -1,3 +0,0 @@
|
||||
<template name="baseCustom">
|
||||
{{>UI.contentBlock}}
|
||||
</template>
|
||||
@ -1,9 +0,0 @@
|
||||
<template name="baseDiv">
|
||||
<div
|
||||
id="{{this.id}}"
|
||||
class="{{this.class}}"
|
||||
{{this.tagAttributes}}
|
||||
>
|
||||
{{>UI.contentBlock}}
|
||||
</div>
|
||||
</template>
|
||||
@ -1,23 +0,0 @@
|
||||
<template name="baseForm">
|
||||
<form
|
||||
id="{{this.id}}"
|
||||
class="{{this.class}}"
|
||||
name="{{this.name}}"
|
||||
action="{{this.action}}"
|
||||
method="{{this.method}}"
|
||||
autocomplete="{{this.autocomplete}}"
|
||||
enctype="{{this.enctype}}"
|
||||
novalidate="{{this.novalidate}}"
|
||||
target="{{this.target}}"
|
||||
{{this.tagAttributes}}
|
||||
>
|
||||
{{#if (and validationErrors (not this.hideValidationBox))}}
|
||||
<div class="validation-error-container alert alert-danger" role="alert">
|
||||
{{#each error in validationErrors}}
|
||||
<p><a href="#" class="text-danger" data-target="{{error.key}}">{{error.message}}</a></p>
|
||||
{{/each}}
|
||||
</div>
|
||||
{{/if}}
|
||||
{{>UI.contentBlock}}
|
||||
</form>
|
||||
</template>
|
||||
@ -1,17 +0,0 @@
|
||||
<template name="baseInput">
|
||||
<input
|
||||
type="{{choose this.type 'text'}}"
|
||||
id="{{this.id}}"
|
||||
class="{{this.class}}"
|
||||
name="{{this.name}}"
|
||||
value="{{reactive this.value}}"
|
||||
placeholder="{{this.placeholder}}"
|
||||
checked="{{#if this.checked}}checked{{/if}}"
|
||||
disabled="{{#if this.disabled}}disabled{{/if}}"
|
||||
min="{{this.min}}"
|
||||
max="{{this.max}}"
|
||||
maxlength="{{choose this.maxlength this.max}}"
|
||||
{{this.tagAttributes}}
|
||||
>
|
||||
{{>UI.contentBlock}}
|
||||
</template>
|
||||
@ -1,11 +0,0 @@
|
||||
<template name="baseLink">
|
||||
<a
|
||||
id="{{this.id}}"
|
||||
class="{{this.class}} {{#if this.disabled}}disabled{{/if}}"
|
||||
href="{{choose this.href '#'}}"
|
||||
title="{{this.title}}"
|
||||
{{this.tagAttributes}}
|
||||
>
|
||||
{{>UI.contentBlock}}
|
||||
</a>
|
||||
</template>
|
||||
@ -1,28 +0,0 @@
|
||||
<template name="baseSelect">
|
||||
<select
|
||||
id="{{this.id}}"
|
||||
class="{{this.class}}"
|
||||
name="{{this.name}}"
|
||||
multiple="{{#if this.multiple}}multiple{{/if}}"
|
||||
disabled="{{#if this.disabled}}disabled{{/if}}"
|
||||
{{this.tagAttributes}}
|
||||
>
|
||||
{{>UI.contentBlock}}
|
||||
{{>baseSelectOptions this.items}}
|
||||
</select>
|
||||
</template>
|
||||
|
||||
<template name="baseSelectOptions">
|
||||
{{#each item in (reactive this)}}
|
||||
{{#if item.items}}
|
||||
<optgroup label="{{item.label}}">
|
||||
{{>baseSelectOptions item.items}}
|
||||
</optgroup>
|
||||
{{else}}
|
||||
<option
|
||||
value="{{item.value}}"
|
||||
selected="{{#if eq item.value (reactive this.value)}}selected{{/if}}"
|
||||
>{{item.label}}</option>
|
||||
{{/if}}
|
||||
{{/each}}
|
||||
</template>
|
||||
@ -1,9 +0,0 @@
|
||||
<template name="baseTr">
|
||||
<tr
|
||||
id="{{this.id}}"
|
||||
class="{{this.class}}"
|
||||
{{this.tagAttributes}}
|
||||
>
|
||||
{{>UI.contentBlock}}
|
||||
</tr>
|
||||
</template>
|
||||
@ -1,15 +0,0 @@
|
||||
<template name="wrapperLabel">
|
||||
{{#unless this.labelAsDiv}}
|
||||
<label class="wrapperLabel {{this.labelClass}}" {{clone this.labelTagAttributes}}>
|
||||
{{#wrapperLabelContent (extend this labelAfter=true)}}
|
||||
{{>UI.contentBlock}}
|
||||
{{/wrapperLabelContent}}
|
||||
</label>
|
||||
{{else}}
|
||||
<div class="wrapperLabel {{this.labelClass}}" {{clone this.labelTagAttributes}}>
|
||||
{{#wrapperLabelContent}}
|
||||
{{>UI.contentBlock}}
|
||||
{{/wrapperLabelContent}}
|
||||
</div>
|
||||
{{/unless}}
|
||||
</template>
|
||||
@ -1,9 +0,0 @@
|
||||
<template name="wrapperLabelContent">
|
||||
{{#if this.labelAfter}}
|
||||
{{>UI.contentBlock}}
|
||||
{{/if}}
|
||||
<span class="wrapperText">{{>section 'labelBeforeText'}}{{reactive this.label}}{{>section 'labelAfterText'}}</span>
|
||||
{{#unless this.labelAfter}}
|
||||
{{>UI.contentBlock}}
|
||||
{{/unless}}
|
||||
</template>
|
||||
@ -1,14 +0,0 @@
|
||||
.modal
|
||||
.modal-header:empty, .modal-footer:empty
|
||||
display: none
|
||||
|
||||
.modal-blank
|
||||
|
||||
.modal-content
|
||||
border: 0
|
||||
|
||||
.modal-header, .modal-footer
|
||||
display: none
|
||||
|
||||
.modal-body
|
||||
padding: 0
|
||||
@ -1,7 +0,0 @@
|
||||
<template name="dialogConfirm">
|
||||
{{#dialogForm (extend this
|
||||
dialogClass='modal-sm'
|
||||
title=(choose this.title 'Confirmation')
|
||||
message=(valueIf UI.contentBlock '' (choose this.message 'Are you sure you want to perform this action?'))
|
||||
)}}{{>UI.contentBlock}}{{/dialogForm}}
|
||||
</template>
|
||||
@ -1,45 +0,0 @@
|
||||
<template name="dialogForm">
|
||||
<div id="{{this.id}}" class="modal fade {{this.class}}" tabindex="-1" role="dialog">
|
||||
<div class="modal-dialog {{this.dialogClass}}" role="document">
|
||||
{{#form class=(concat 'modal-content ' this.formClass) hideValidationBox=true
|
||||
api=(extend instance.api instance.data.api) schema=this.schema
|
||||
}}
|
||||
{{#if or this.title (hasSection 'dialogHeader')}}
|
||||
{{>dialogHeader this}}
|
||||
{{/if}}
|
||||
<div class="modal-body">
|
||||
<div class="messages">
|
||||
{{#each message in this.messages}}
|
||||
<div class="message">{{{message}}}</div>
|
||||
{{else}}
|
||||
{{#if isError}}
|
||||
{{>pageError (extend this error=this.details)}}
|
||||
{{else}}
|
||||
{{#let message=(choose this.bodyText this.reason this.message (valueIf UI.contentBlock '' 'An error has ocurred.' ))}}
|
||||
<div class="message">{{message}}</div>
|
||||
{{/let}}
|
||||
{{/if}}
|
||||
{{/each}}
|
||||
</div>
|
||||
{{>UI.contentBlock}}
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
{{>section 'dialogFooter'}}
|
||||
{{#unless this.hideCancel}}
|
||||
{{#button action='cancel'
|
||||
disabled=this.cancelDisabled
|
||||
class=(concat 'btn btn-cancel ' (choose this.cancelClass 'btn-secondary'))
|
||||
tagAttributes=(extend this.tagAttributes data-dismiss='modal')
|
||||
}}{{choose this.cancelLabel 'Cancel'}}{{/button}}
|
||||
{{/unless}}
|
||||
{{#unless this.hideConfirm}}
|
||||
{{#button action='confirm'
|
||||
disabled=this.confirmDisabled
|
||||
class=(concat 'btn btn-confirm ' (choose this.confirmClass 'btn-primary'))
|
||||
}}{{choose this.confirmLabel 'Confirm'}}{{/button}}
|
||||
{{/unless}}
|
||||
</div>
|
||||
{{/form}}
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@ -1,114 +0,0 @@
|
||||
import { Template } from 'meteor/templating';
|
||||
import _ from 'underscore';
|
||||
import { OHIF } from 'meteor/ohif:core';
|
||||
|
||||
Template.dialogForm.onCreated(() => {
|
||||
const instance = Template.instance();
|
||||
|
||||
const dismissModal = (promiseFunction, param) => {
|
||||
// Hide the modal, removing the backdrop
|
||||
instance.$('.modal').one('hidden.bs.modal', event => {
|
||||
// Resolve or reject the promise with the given parameter
|
||||
promiseFunction(param);
|
||||
}).modal('hide');
|
||||
};
|
||||
|
||||
instance.api = {
|
||||
|
||||
confirm() {
|
||||
// Check if the form has valid data
|
||||
const form = instance.$('form').data('component');
|
||||
if (!form.validate()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const formData = form.value();
|
||||
const dismiss = param => dismissModal(instance.data.promiseResolve, param);
|
||||
|
||||
if (_.isFunction(instance.data.confirmCallback)) {
|
||||
const result = instance.data.confirmCallback(formData);
|
||||
if (result instanceof Promise) {
|
||||
return result.then(dismiss);
|
||||
} else {
|
||||
return dismiss(result);
|
||||
}
|
||||
}
|
||||
|
||||
dismiss(formData);
|
||||
},
|
||||
|
||||
cancel() {
|
||||
const dismiss = param => dismissModal(instance.data.promiseReject, param);
|
||||
|
||||
if (_.isFunction(instance.data.cancelCallback)) {
|
||||
const result = instance.data.cancelCallback();
|
||||
if (result instanceof Promise) {
|
||||
return result.then(dismiss);
|
||||
} else {
|
||||
return dismiss(result);
|
||||
}
|
||||
}
|
||||
|
||||
dismiss();
|
||||
}
|
||||
|
||||
};
|
||||
});
|
||||
|
||||
Template.dialogForm.onRendered(() => {
|
||||
const instance = Template.instance();
|
||||
|
||||
// Allow options ovewrite
|
||||
const modalOptions = _.extend({
|
||||
backdrop: 'static',
|
||||
keyboard: false
|
||||
}, instance.data.modalOptions);
|
||||
|
||||
const $modal = instance.$('.modal');
|
||||
|
||||
// Create the bootstrap modal
|
||||
$modal.modal(modalOptions);
|
||||
|
||||
// Check if dialog will be repositioned
|
||||
let position = instance.data.position;
|
||||
const event = instance.data.event;
|
||||
if (!position && event && event.clientX) {
|
||||
position = {
|
||||
x: event.clientX,
|
||||
y: event.clientY
|
||||
};
|
||||
}
|
||||
|
||||
// Reposition dialog if position object was filled
|
||||
if (position) {
|
||||
OHIF.ui.repositionDialog($modal, position.x, position.y);
|
||||
}
|
||||
});
|
||||
|
||||
Template.dialogForm.events({
|
||||
keydown(event) {
|
||||
const instance = Template.instance(),
|
||||
keyCode = event.keyCode || event.which;
|
||||
|
||||
let handled = false;
|
||||
|
||||
if (keyCode === 27) {
|
||||
instance.$('.btn.btn-cancel').click();
|
||||
handled = true;
|
||||
} else if (keyCode === 13) {
|
||||
instance.$('.btn.btn-confirm').click();
|
||||
handled = true;
|
||||
}
|
||||
|
||||
if (handled) {
|
||||
event.stopPropagation();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Template.dialogForm.helpers({
|
||||
isError() {
|
||||
const data = Template.instance().data;
|
||||
return data instanceof Error || (data && data.error instanceof Error);
|
||||
}
|
||||
});
|
||||
@ -1,16 +0,0 @@
|
||||
<template name="dialogHeader">
|
||||
<div class="modal-header">
|
||||
{{>section 'dialogHeader'}}
|
||||
{{#if or this.title (hasSection 'dialogHeader')}}
|
||||
{{#button class='close' action='cancel'
|
||||
tagAttributes=(extend this.tagAttributes
|
||||
data-dismiss='modal' aria-label='Close'
|
||||
)
|
||||
}}<span aria-hidden="true">×</span>{{/button}}
|
||||
<h4 class="modal-title">
|
||||
{{#if this.titleIcon}}<i class="{{this.titleIcon}}"></i>{{/if}}
|
||||
<span>{{this.title}}</span>
|
||||
</h4>
|
||||
{{/if}}
|
||||
</div>
|
||||
</template>
|
||||
@ -1,19 +0,0 @@
|
||||
<template name="dialogInfo">
|
||||
{{#dialogSimple (extend this
|
||||
title=(choose this.title 'Error')
|
||||
)}}
|
||||
<div class="messages">
|
||||
{{#each message in this.messages}}
|
||||
<div class="message">{{{message}}}</div>
|
||||
{{else}}
|
||||
{{#if isError}}
|
||||
{{>pageError (extend this error=this.details)}}
|
||||
{{else}}
|
||||
{{#let message=(choose this.reason this.message 'An error has ocurred.')}}
|
||||
<div class="message">{{message}}</div>
|
||||
{{/let}}
|
||||
{{/if}}
|
||||
{{/each}}
|
||||
</div>
|
||||
{{/dialogSimple}}
|
||||
</template>
|
||||
@ -1,16 +0,0 @@
|
||||
import { Template } from 'meteor/templating';
|
||||
|
||||
Template.dialogInfo.onRendered(() => {
|
||||
const instance = Template.instance();
|
||||
|
||||
const $modal = instance.$('.modal');
|
||||
|
||||
$modal.one('hidden.bs.modal', () => instance.data.promiseResolve());
|
||||
});
|
||||
|
||||
Template.dialogInfo.helpers({
|
||||
isError() {
|
||||
const data = Template.instance().data;
|
||||
return data instanceof Error || (data && data.error instanceof Error);
|
||||
}
|
||||
});
|
||||
@ -1,7 +0,0 @@
|
||||
<template name="dialogLoading">
|
||||
<div id="{{this.id}}" class="modal fade {{this.class}}" tabindex="-1" role="dialog">
|
||||
<div class="loading-text noselect">
|
||||
{{choose this.text 'Loading...'}} <i class="fa fa-spin fa-circle-o-notch fa-fw"></i>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@ -1,14 +0,0 @@
|
||||
import { Template } from 'meteor/templating';
|
||||
|
||||
Template.dialogLoading.onRendered(() => {
|
||||
const instance = Template.instance();
|
||||
|
||||
const $modal = instance.$('.modal');
|
||||
|
||||
// Create the bootstrap modal
|
||||
$modal.modal({
|
||||
backdrop: 'static',
|
||||
keyboard: false,
|
||||
show: true
|
||||
});
|
||||
});
|
||||
@ -1,9 +0,0 @@
|
||||
@import "{ohif:viewerbase}/app"
|
||||
|
||||
.modal .loading-text
|
||||
theme('color', '$textSecondaryColor')
|
||||
font-size: 30px
|
||||
height: 100vh
|
||||
line-height: 100vh
|
||||
text-align: center
|
||||
text-shadow: 1px 1px 0 #000, -1px -1px 0 #000, -1px 1px 0 #000, 1px -1px 0 #000, -1px 0 0 #000, 0 -1px 0 #000, 1px 0 0 #000, 0 1px 0 #000
|
||||
@ -1,6 +0,0 @@
|
||||
<template name="dialogLogin">
|
||||
{{#dialogForm (extend this dialogClass='modal-sm' schema=(choose this.schema instance.schema))}}
|
||||
{{>inputText labelClass='form-group' key='username'}}
|
||||
{{>inputPassword labelClass='form-group' key='password'}}
|
||||
{{/dialogForm}}
|
||||
</template>
|
||||
@ -1,17 +0,0 @@
|
||||
import { Template } from 'meteor/templating';
|
||||
import { SimpleSchema } from 'meteor/aldeed:simple-schema';
|
||||
|
||||
Template.dialogLogin.onCreated(() => {
|
||||
const instance = Template.instance();
|
||||
|
||||
instance.schema = new SimpleSchema({
|
||||
username: {
|
||||
type: String,
|
||||
label: 'Username'
|
||||
},
|
||||
password: {
|
||||
type: String,
|
||||
label: 'Password'
|
||||
}
|
||||
});
|
||||
});
|
||||
@ -1,17 +0,0 @@
|
||||
<template name="dialogProgress">
|
||||
{{#dialogForm (extend this
|
||||
dialogClass='modal-sm modal-progress'
|
||||
title=(choose this.title 'Processing...')
|
||||
)}}
|
||||
<div class="status">
|
||||
<div class="progress-bar-container">
|
||||
<div class="progress-bar progress-bar-striped active" role="progressbar" style="width: {{progress}}%">
|
||||
<div class="percentage">{{formatNumberPrecision progress 0}}%</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="message">
|
||||
{{{message}}}
|
||||
</div>
|
||||
{{/dialogForm}}
|
||||
</template>
|
||||
@ -1,87 +0,0 @@
|
||||
import { Template } from 'meteor/templating';
|
||||
import { ReactiveVar } from 'meteor/reactive-var';
|
||||
import _ from 'underscore';
|
||||
|
||||
Template.dialogProgress.onCreated(() => {
|
||||
const instance = Template.instance();
|
||||
|
||||
instance.state = new ReactiveVar({
|
||||
processed: 0,
|
||||
total: instance.data.total,
|
||||
message: instance.data.message
|
||||
});
|
||||
});
|
||||
|
||||
Template.dialogProgress.onRendered(() => {
|
||||
const instance = Template.instance();
|
||||
const task = instance.data.task;
|
||||
|
||||
const progressDialog = {
|
||||
promise: instance.data.promise,
|
||||
|
||||
done: value => {
|
||||
// Hide the modal, removing the backdrop
|
||||
instance.$('.modal').on('hidden.bs.modal', event => {
|
||||
instance.data.promiseResolve(value);
|
||||
}).modal('hide');
|
||||
},
|
||||
|
||||
cancel: () => {
|
||||
// Hide the modal, removing the backdrop
|
||||
instance.$('.modal').on('hidden.bs.modal', event => {
|
||||
instance.data.promiseReject();
|
||||
}).modal('hide');
|
||||
},
|
||||
|
||||
update: _.throttle(processed => {
|
||||
const state = instance.state.get();
|
||||
state.processed = Math.max(0, processed);
|
||||
|
||||
instance.state.set(state);
|
||||
}, 100),
|
||||
|
||||
setTotal: _.throttle(total => {
|
||||
const state = instance.state.get();
|
||||
state.total = total;
|
||||
|
||||
instance.state.set(state);
|
||||
}, 100),
|
||||
|
||||
setMessage: _.throttle(message => {
|
||||
const state = instance.state.get();
|
||||
state.message = message;
|
||||
|
||||
instance.state.set(state);
|
||||
}, 100)
|
||||
};
|
||||
|
||||
task.run(progressDialog);
|
||||
});
|
||||
|
||||
Template.dialogProgress.helpers({
|
||||
progress() {
|
||||
const instance = Template.instance();
|
||||
const state = instance.state.get();
|
||||
|
||||
if (!state || !state.total) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return Math.min(1, state.processed / state.total) * 100;
|
||||
},
|
||||
|
||||
message() {
|
||||
const instance = Template.instance();
|
||||
const state = instance.state.get();
|
||||
|
||||
if (!state) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof state.message === 'function') {
|
||||
return state.message(state);
|
||||
}
|
||||
|
||||
return state.message;
|
||||
}
|
||||
});
|
||||
@ -1,14 +0,0 @@
|
||||
.modal-progress
|
||||
.status
|
||||
.progress-bar-container
|
||||
border: solid 1px #28405E
|
||||
overflow: auto;
|
||||
margin: 0 0 10px
|
||||
border-radius: 3px
|
||||
|
||||
.percentage
|
||||
margin: 0 5px
|
||||
|
||||
.btn-confirm
|
||||
display: none
|
||||
|
||||
@ -1,13 +0,0 @@
|
||||
<template name="dialogSimple">
|
||||
<div id="{{this.id}}" class="modal fade {{this.class}}" tabindex="-1" role="dialog">
|
||||
<div class="modal-dialog {{this.dialogClass}}" role="document">
|
||||
<div class="modal-content">
|
||||
{{>dialogHeader this}}
|
||||
<div class="modal-body">
|
||||
{{>UI.contentBlock}}
|
||||
</div>
|
||||
<div class="modal-footer">{{>section 'dialogFooter'}}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@ -1,61 +0,0 @@
|
||||
import { Meteor } from 'meteor/meteor';
|
||||
import { Template } from 'meteor/templating';
|
||||
import _ from 'underscore';
|
||||
import { OHIF } from 'meteor/ohif:core';
|
||||
|
||||
Template.dialogSimple.onCreated(() => {
|
||||
const instance = Template.instance();
|
||||
|
||||
instance.close = () => {
|
||||
instance.$('.modal').modal('hide');
|
||||
};
|
||||
|
||||
// Automatically close the modal if a timeout value was given
|
||||
if (instance.data.timeout) {
|
||||
Meteor.setTimeout(instance.close, instance.data.timeout);
|
||||
}
|
||||
});
|
||||
|
||||
Template.dialogSimple.onRendered(() => {
|
||||
const instance = Template.instance();
|
||||
|
||||
// Allow options ovewrite
|
||||
const modalOptions = _.extend({
|
||||
backdrop: 'static',
|
||||
keyboard: false
|
||||
}, instance.data.modalOptions);
|
||||
|
||||
const $modal = instance.$('.modal');
|
||||
|
||||
// Create the bootstrap modal
|
||||
$modal.modal(modalOptions);
|
||||
|
||||
// Resolve the promise as soon as the modal is closed
|
||||
$modal.one('hidden.bs.modal', () => instance.data.promiseResolve());
|
||||
|
||||
let position = instance.data.position;
|
||||
|
||||
const { event } = instance.data;
|
||||
if (!position && event && !_.isUndefined(event.clientX)) {
|
||||
position = {
|
||||
x: event.clientX,
|
||||
y: event.clientY
|
||||
};
|
||||
}
|
||||
|
||||
if (position) {
|
||||
OHIF.ui.repositionDialog($modal, position.x, position.y);
|
||||
}
|
||||
});
|
||||
|
||||
Template.dialogSimple.events({
|
||||
keydown(event) {
|
||||
const instance = Template.instance();
|
||||
const keyCode = event.keyCode || event.which;
|
||||
|
||||
if (keyCode === 27) {
|
||||
instance.close();
|
||||
event.stopPropagation();
|
||||
}
|
||||
}
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user