Giter Site home page Giter Site logo

cornerstonejs / react-cornerstone-viewport Goto Github PK

View Code? Open in Web Editor NEW
96.0 21.0 76.0 2.42 MB

Cornerstone medical image viewport component for React

Home Page: https://react.cornerstonejs.org/

License: MIT License

HTML 4.88% JavaScript 86.03% CSS 9.08%
nci-itcr javascript cornerstone dicom medical-imaging react

react-cornerstone-viewport's Introduction

react-cornerstone-viewport

Cornerstone medical image viewport component for React

NPM

Documentation and Examples: https://react.cornerstonejs.org/

Install

## NPM
npm install --save react-cornerstone-viewport

## Yarn
yarn add react-cornerstone-viewport

Usage

import React, { Component } from 'react'

import CornerstoneViewport from 'react-cornerstone-viewport'

class Example extends Component {
  render () {
    return (
      <CornerstoneViewport />
    )
  }
}

License

MIT © OHIF

react-cornerstone-viewport's People

Contributors

a-harris avatar alex979 avatar amrita-syn avatar arthur-miller avatar biharck avatar burnpiro avatar ckedar avatar dannyrb avatar dbousamra avatar dlwire avatar evren217 avatar galelis avatar horner avatar igoroctaviano avatar ivan-aksamentov avatar jamesapetts avatar joao-f-medeiros avatar mathisguilhin avatar nisalup avatar rish-hub avatar sedghi avatar swederik avatar todd-dembrey avatar xxlee0927 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-cornerstone-viewport's Issues

Not able to load DICOM P10 link

Hi,

In this link (https://rawgit.com/cornerstonejs/cornerstoneWADOImageLoader/master/examples/wadouri/index.html), the cornerstone library successfully loads DICOM file from the link https://raw.githubusercontent.com/cornerstonejs/cornerstoneWADOImageLoader/master/testImages/CT2_J2KR

However, when I try to load the same link with react-cornerstone-viewport, it gives me an error with "Error Loading Image. An error has occurred" on the viewport without any details.

I have downloaded the DICOM file from the link and was able to load the file from OsiriX QuickLook (on MAC OS).

Is this a known issue? Or, do we have a work-around for this issue?

Thanks in advance

Enabled event listener mutates cornerstone events listener list

I'm getting errors when passing in onElementEnabled to the viewport. Because i changed the code to handle all events in #60 this bug has surfaced.

This is caused when iterating over the listener list in cornestone events. In my case the initial length of the listener is 3, but when the enabled event code fires it removes its listener and the list becomes length 2. So when i=3 stack[i] becomes undefined and we get:

Uncaught (in promise) TypeError: Cannot read property 'call' of undefined

Is there a reason for removing the listener at this point or could this be handled in the unmount like other events? Additionally should the changes from #60 exclude the events which the viewport exposes functions for or should it remain as is?

_handleOnElementEnabledEvent = () => {
const handler = evt => {
const elementThatWasEnabled = evt.detail.element;
if (elementThatWasEnabled === this.element) {
// Pass Event
this.props.onElementEnabled(evt);
// Stop Listening
cornerstone.events.removeEventListener(
cornerstone.EVENTS.ELEMENT_ENABLED,
handler
);
}
};
// Start Listening
if (this.props.onElementEnabled) {
cornerstone.events.addEventListener(
cornerstone.EVENTS.ELEMENT_ENABLED,
handler
);
}
};

question about package.json

I've noticed there's this line in example/package.json: "react-cornerstone-viewport": "link:..". I have an intuition that this tells it to look for the react-cornerstone-viewport in the upper parent folder. But I'm not entirely sure the mechanism to enable it. Does one have to do something in the parent folder to make react-cornerstone-viewport available?

In addition, I have several project folders containing components under development. I'd like to use this mechanism to make my dev component available. A clarification would be much appreciated.

stopClip should be called before cornerstone.disable

If you start a clip playing and then destroy the component you will end up with an infinite loop. The component is not cleaning up the clip properly. The disable() call should be done after the stopClip try/catch block (if it even needs to be a try/catch).

cornerstone.disable(element);
// Try to stop any currently playing clips
// Otherwise the interval will continuously throw errors
// TODO[cornerstoneTools]: Make this happen internally
try {
const enabledElement = cornerstone.getEnabledElement(element);
if (enabledElement) {
cornerstoneTools.stopClip(element);
}
} catch (error) {
//console.warn(error);
}
if (this.props.clearViewportSpecificData) {
this.props.clearViewportSpecificData();
}
}
componentDidUpdate(prevProps) {
// TODO: Add a real object shallow comparison here?
if (
this.state.displaySetInstanceUid !==

Is there a way to download images in the background?

Not sure where to ask this, so apologies if this is the wrong repo, or wrong place.

I am using react-cornerstone-viewport, and it's working really well.

One thing I want to do is download all the imageIds in a clip, regardless of whether the clip is playing.

Viewport resizes when stack is scrolled

Summary

In OHIF/Viewers, when we scroll to a new image in the same stack, the viewport is resized. The cornerstone-viewport thinks the layout has changed, so it calls debouncedResize();, which calls cornerstone.resize(element, forceFitToWindow: true).

Start point is here:

https://github.com/cornerstonejs/react-cornerstone-viewport/blob/master/src/CornerstoneViewport/CornerstoneViewport.js#L699-L701

Example GIF

MvCfvM5MAR

Created playing with our live demo at https://viewer.ohif.org

The Problem

The objects being compared are identical, but we're using !==, so they're now "different" objects in that they're not a reference to the same object. I'm not sure when this behavior started, as these specific lines haven't been touched in 6+ months. It's possible that they're triggered by a change in a different repository.

The Solution

Regardless, I think we can use a better qualifier to determine if we should force a resize. Likely either the number/position/size of viewports, and/or if we have been provided a new stack. These changes should probably also trigger the resize without a debounce applied.

Adding DicomTags to Overlay

Hi,

I am trying to add Gender and Birthday and hopefully otherpatientid to the overlay in the OHIF Viewer.

I added/changed

react-cornerstone-viewport-master\src\metadataProvider.js
if (type === 'patientModule') { return { patientName: getValue(metaData['00100010']), patientId: getValue(metaData['00100020']), patientSex: getValue(metaData['00100040']), patientBirthDate: getValue(metaData['00100030']), }; }

react-cornerstone-viewport-master\src\ViewportOverlay\ViewportOverlay.js

<div className="top-left overlay-element"> <div>{formatPN(patientName)} ({patientSex})</div> <div>{patientId}</div> <div>{patientBirthDate}</div> </div>

The Problem is that these values are not present in the metadata. The only thread that mentions this I could find is from 2016 and a lot has changed since then.

I looked into:
cornerstoneWADOImageLoader/src/imageLoader/wadors/metaData/
and
(OHIF)Viewers/platform/core/src/studies/services/wado/retrieveMetadata.js

but can't figure out where the metadata for the viewport is exactly added.
I hope some can point me in the right direction.
Thanks.

Re rendering with different stack doesn't work

I have a component defined:

import * as React from 'react';
import * as _ from 'lodash';
import * as Cornerstone from 'react-cornerstone-viewport';

export interface Stack {
  currentImageIdIndex: number;
  imageIds: string[];
}

export interface Props {
  stack: Stack;
  cornerstone: any;
  cornerstoneTools: any;
}

export default class CornerstoneViewport extends React.Component<Props> {
  constructor(props: Props) {
    super(props);
    console.log('Constructing CornerstoneViewport');
  }

  render() {
    console.log('Rerender with', this.props);
    return (
      <Cornerstone
        viewportData={{ stack: this.props.stack }}
        cornerstone={this.props.cornerstone}
        cornerstoneTools={this.props.cornerstoneTools}
      />
    );
  }
}

If I rerender this with a different stack passed in, it doesn't actually update the viewport. Is this related to #18 ? What should I do as a work around in the meantime?

annotations can be saved ?

i want to add annotations and save in some way that allow this annotations when viewer is reloaded, is this posible? maybe local storage

Dynamically change tools array in React

I wanted to change the tools array by adding/removing tools upon Click events. But the set of tools would not change after a render. Please let me know how to change the list of tools. <CornerstoneViewport tools={this.state.tools}>

Toggle dicom images through events

Hello, how can I use the click event to switch between different images
class DicomLoading extends Component {
render() {
const { dicomUrl='', className, style } = this.props;
console.log('DiconLoading ==> ', dicomUrl)
const dicomData = {
stack: {
currentImageIdIndex: 0,
imageIds:
[
'',
// 'dicomweb://localhost:3000/d1.DCM', //测试用dicom图片
]
}
}
dicomData.stack.imageIds[0] = dicomUrl
const dicomBox = ${styles.basicBox} ${className}
console.log('imageIds', dicomData.stack.imageIds)
return (




)
}
}
export default DicomLoading

Viewport continues to grow

I'm struggling to understand this issue. Any ideas or info would be much appreciated.

Here is a gif illustrating the behaviour. Notice what happens when I resize the window.

resize-image-viewer

Here is the component rendering the viewport:

<Flex height="100%" flexWrap="nowrap">
  <Box width="320px" p={3} className="sidebar-container">
    <ImageGrid instances={sortedInstances} onInstanceClick={onInstanceClick} />
  </Box>
  <Box flexGrow={1} p={3} className="viewer-container">
    <Flex flexDirection="column" height="100%">
      <Box px={2} py={2} backgroundColor="blue">
        Controls
      </Box>

      <Box px={2} py={2} backgroundColor="red" flex="1">
        <CornerstoneViewport
          key={instanceIndex}
          instance={instance}
          frameRate={frameRate}
          isPlaying={isPlaying}
        />
      </Box>
     
    </Flex>
  </Box>
</Flex>

I can post more info if needed. I think it's to do with https://github.com/cornerstonejs/react-cornerstone-viewport/blob/50e33ba0ae71ee7dfb20100c8424b4fcd78956f4/src/CornerstoneViewport/windowResizeHandler.js

Error fs

✖ ERROR ../node_modules/cornerstone-wado-image-loader/dist/cornerstoneWADOImageLoader.min.js
Module not found: Error: Can't resolve 'fs' in './node_modules/cornerstone-wado-image-loader/dist'
 @ ../node_modules/cornerstone-wado-image-loader/dist/cornerstoneWADOImageLoader.min.js 1:1536166-1536179 1:2419658-2419671
 @ ../node_modules/react-cornerstone-viewport/dist/index.es.js
 @ ./index.js
 @ ../node_modules/preact-cli/lib/lib/entry.js
 @ multi ../node_modules/preact-cli/lib/lib/entry webpack-dev-server/client webpack/hot/dev-server


import './style';
import { Component } from 'preact';
import CornerstoneViewport from 'react-cornerstone-viewport';

export default class App extends Component {
	state = {
		tools: [
		  // Mouse
		  {
				name: 'Wwwc',
				mode: 'active',
				modeOptions: { mouseButtonMask: 1 }
		  },
		  {
				name: 'Zoom',
				mode: 'active',
				modeOptions: { mouseButtonMask: 2 }
		  },
		  {
				name: 'Pan',
				mode: 'active',
				modeOptions: { mouseButtonMask: 4 }
		  },
		  // Scroll
		  { name: 'StackScrollMouseWheel', mode: 'active' },
		  // Touch
		  { name: 'PanMultiTouch', mode: 'active' },
		  { name: 'ZoomTouchPinch', mode: 'active' },
		  { name: 'StackScrollMultiTouch', mode: 'active' }
		],
		imageIds: [
		  'dicomweb://s3.amazonaws.com/lury/PTCTStudy/1.3.6.1.4.1.25403.52237031786.3872.20100510032220.11.dcm',
		  'dicomweb://s3.amazonaws.com/lury/PTCTStudy/1.3.6.1.4.1.25403.52237031786.3872.20100510032220.12.dcm'
		]
	  };
	render() {
		return (
			<div>
				<h1>Hello, World!</h1>
				<CornerstoneViewport
					tools={this.state.tools}
					imageIds={this.state.imageIds}
					style={{ minWidth: '100%', height: '512px', flex: '1' }}
				/>
			</div>
		);
	}
}

Question: About the examplegrid.js if we need to change the imageids for each grid...

Hi there,

I want to be able to change the imageIds for each grid dynamically. Am serving the dicom images and have been able to populate the this.state.imageIds for the second viewport but it is giving an error when I try to scroll and the error is shown as :

loadAndCacheImage: parameter imageId must not be undefined
Module.loadAndCacheImage
.../cornerstone/imageLoader.js:95
92 | */
93 | export function loadAndCacheImage (imageId, options) {
94 | if (imageId === undefined) {

95 | throw new Error('loadAndCacheImage: parameter imageId must not be undefined');
96 | }
97 |
98 | let imageLoadObject = getImageLoadObject(imageId);

(anonymous function)
.../src/ImageScrollbar/ImageScrollbar.js:43
40 |
41 | onChange = event => {
42 | const intValue = parseInt(event.target.value, 10);

43 | this.props.onInputCallback(intValue);
| ^ 44 | };
45 |
46 | onKeyDown = event => {

Would be grateful if you could point to any example or suggest changes.

thanks in advance.

Viewport in portal - cannot use tools

I have been trying to run the viewport inside a react portal in a new window. Use case being that while looking at the images, want to write up notes on the main app.
However, when I tried to put the component inside a portal, none of the clicks work anymore. Only scroll seems to register. I have tried react-new-window and react portal.

Maybe portals is not the best way to do this but I hope it is an issue that can be fixed.

Unable to add a custom tool to viewport

Hi,

I'm experimenting to create a custom tool and add it to the viewport. But it shows "Unable to add tool with name 'HelloWorldMouse'."

It's a very simple tool

`const BaseTool = cornerstoneTools.importInternal("base/BaseTool");

export default class HelloWorldMouseTool extends BaseTool {
constructor(name = "HelloWorldMouse") {
super({
name,
supportedInteractionTypes: ["mouse"],
mixins: [
"activeOrDisabledBinaryTool" // Mixin from cornerstoneTools source.
]
});
}
}`

I also added in the initCornerstone.js

cornerstoneTools.addTool(HelloWorldMouseTool);

And I added to the tools array

tools: [ // Mouse { name: "HelloWorldMouse", mode: "active", modeOptions: { mouseButtonMask: 1 } },

Is custom tool not supported in Viewport?

Thanks

Example is broken on 0.1.32

Uncaught TypeError: Cannot read property 'viewports' of undefined
    at layoutsEqual (index.umd.js:6444)
    at CornerstoneViewport.componentDidUpdate (index.umd.js:7097)
    at commitLifeCycles (react-dom.development.js:18130)
    at commitAllLifeCycles (react-dom.development.js:19674)
    at HTMLUnknownElement.callCallback (react-dom.development.js:147)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:196)
    at invokeGuardedCallback (react-dom.development.js:250)
    at commitRoot (react-dom.development.js:19898)
    at react-dom.development.js:21446
    at Object.unstable_runWithPriority (scheduler.development.js:255)
    at completeRoot (react-dom.development.js:21445)
    at performWorkOnRoot (react-dom.development.js:21368)
    at performWork (react-dom.development.js:21273)
    at performSyncWork (react-dom.development.js:21247)
    at requestWork (react-dom.development.js:21102)
    at scheduleWork (react-dom.development.js:20915)
    at Object.enqueueSetState (react-dom.development.js:11596)
    at CornerstoneViewport.push../node_modules/react/cjs/react.development.js.Component.setState (react.development.js:336)
    at EventTarget.<anonymous> (index.umd.js:6590)
    at EventTarget.dispatchEvent (cornerstone.js:4151)
    at triggerEvent (cornerstone.js:10926)
    at cornerstone.js:5184

0.1.31 works fine. I haven't looked into it further.

Download all images does not work

Hi,

I just update the version from 1.0.0 to 2.3.0 of react-cornestone-viewport. After that when I render the component all the stack in imageIds were download. Now it only dowloads the image when the cursor is on it, and that is unconfortable because everytime I move the image it has to dowload it if it do not have it yet. So, Is there any way in this new version to download all de stack of images?

I'm not sure if this is the correct repo for this question but any suggestions will be greatly appreciated!

Thank you!

Question: Can we get presentation state data from the cornerstone viewport object?

Hi there ,

Am looking to get hold of DICOM presentation state data any and display/enable on the dicom image after the element has been enabled.

I tested the overlaytest.dcm image in the my code and it was getting rendered, but was not able to get the presentation layer data with the canvas object. Maybe am missing something. Then realized that somebody in that issue has commented that cornerstone cannot access the presentation layer data if any.

Went through all these github links and not sure whether the feature of reading presentation state data is available in cornerstonetools now.

Also would be very obliged if you could please give the steps briefly of accessing the same using the react-cornerstone viewport

cornerstonejs/cornerstoneTools#780
https://gist.github.com/jdnarvaez/3368ac3e4f7f4eb14bc5f453f8a1ed1b
cornerstonejs/cornerstoneWADOImageLoader#239
OHIF/Viewers#954
cornerstonejs/cornerstoneTools#210
https://github.com/cornerstonejs/cornerstoneTools/blob/master/src/tools/annotation/LengthTool.js#L126-L129

Thanks very much in advance,
Sreevani

Question: How to enable 'Highlight', 'Elliptical ROI' and free text annotation in cornerstoneviewport and also save annotations

Hi there,

Is there an example on how we can enable the Rectangle ROI, Highlight and free hand text tools in cornerstoneviewport, by using the set active tool property? Am getting an error that cornerstoneviewport does not recognize these tools.

It would be very helpful if you can point to an example, the grid example has only the zoom, pan tools examples. Also please can you share example on how we can save these annotations and render the same.

Please refer https://shalkam.github.io/react-cornerstone-example/ for an example of the tools.
I tried to look into the OHIF github link, but was not able to get to the exact source code, if you could please point me, it would be very helpful.

thanks in advance,
Sreevani

Error loading viewport

Version(s):

using NPM packages:

When loading the viewport I am getting the following error:

cornerstoneTools.js:15244 Uncaught (in promise) TypeError: Cannot read property 'getEnabledElement' of undefined
    at _getUUIDFromElement (cornerstoneTools.js:15244)
    at Object.setStartLoadHandler (cornerstoneTools.js:15260)
    at CornerstoneViewport._setupLoadHandlers (index.umd.js:10583)
    at CornerstoneViewport._callee$ (index.umd.js:10092)
    at tryCatch (pdf.worker.js:1052)
    at Generator.invoke [as _invoke] (pdf.worker.js:1227)
    at Generator.prototype.<computed> [as next] (pdf.worker.js:1095)
    at asyncGeneratorStep (index.umd.js:908)
    at _next (index.umd.js:930)
    at index.umd.js:937
    at new Promise (<anonymous>)
  

This is even when I use only the viewport as in

<CornerstoneViewport/>

Question: Need to save the coordinates of length, elliptical roi, probe, rectangle roi etc into a database for now

Hi there,

There is a need in my application to be able to get the coordinates of the tools used to draw on the dicom image and save into a database for now.

So I tried the escapehatch example and got the cornerstoneelement. Then used the following code to get the coordinates in the ComponentDidUpdate() lifecycle method, but am always getting "undefined". Please can you help point out what I am missing...

const viewport = cornerstone.getViewport(this.state.cornerstoneElement);
console.log(viewport);
console.log("Rectangle ROI");
console.log(cornerstoneTools.getToolState(this.state.cornerstoneElement, "rectangleRoi"));

or

console.log(cornerstoneTools.getToolState(this.state.cornerstoneElement, this.state.activeTool));
regards,
Sreevani

Custom images downloader

Hi,

I want to use the react-cornerstone-viewport but I want to download the images by myself i.e. I want to download the images in other order. So, Is there a way for the component to not manage the images download?

Any suggestions will be greatly appreciated!

Question: Updating Angle annotation onto an image using toolstate not working...

Hi there,

Am using the following sample code snippet to figure out the right way to add the angle tool state onto an existing image, but the lifecycle of the component does not seem to end and the angle annotation is not getting rendered at all. Please can anyone point me to the right way or the right component life cycle to update the annotation. This will be a great help.

import React from 'react';
import dicomParser from 'dicom-parser';
import * as cornerstone from 'cornerstone-core';
import cornerstoneWADOImageLoader from 'cornerstone-wado-image-loader';
import cornerstoneMath from 'cornerstone-math';
import cornerstoneTools from 'cornerstone-tools';
import Hammer from 'hammerjs';
import CornerstoneViewport from 'react-cornerstone-viewport';

cornerstoneTools.external.cornerstone = cornerstone;
cornerstoneTools.external.Hammer = Hammer;
cornerstoneTools.external.cornerstoneMath = cornerstoneMath;

cornerstoneTools.init({
globalToolSyncEnabled: true
});
// Preferences
const fontFamily =
'Work Sans, Roboto, OpenSans, HelveticaNeue-Light, Helvetica Neue Light, Helvetica Neue, Helvetica, Arial, Lucida Grande, sans-serif';
cornerstoneTools.textStyle.setFont(16px ${fontFamily});
cornerstoneTools.toolStyle.setToolWidth(2);
cornerstoneTools.toolColors.setToolColor('rgb(255, 255, 0)');
cornerstoneTools.toolColors.setActiveColor('rgb(0, 255, 0)');

cornerstoneTools.store.state.touchProximity = 40;
const OverlayTool = cornerstoneTools.OverlayTool;
cornerstoneTools.addTool(OverlayTool);
cornerstoneTools.setToolEnabled("Overlay", {});

const toolStateManager = cornerstoneTools.globalImageIdSpecificToolStateManager;
// Image Loader
cornerstoneWADOImageLoader.external.cornerstone = cornerstone;
cornerstoneWADOImageLoader.external.dicomParser = dicomParser;
cornerstoneWADOImageLoader.webWorkerManager.initialize({
maxWebWorkers: navigator.hardwareConcurrency || 1,
startWebWorkersOnDemand: true,
taskConfiguration: {
decodeTask: {
initializeCodecsOnStartup: false,
usePDFJS: false,
strict: false,
},
},
});

// Debug
window.cornerstone = cornerstone;
window.cornerstoneTools = cornerstoneTools;

class ImageViewer extends React.Component{
state = {
cornerstoneElement: undefined,
loading:'initial'
};

render(){
  console.log("rendering imageviewer");
  console.log(this.state.cornerstoneElement);
  
  var testAngledata = '{"angle":{"data":[{"visible":true,"handles":{"start":{"x":92.40628941112809,"y":109.38908238107877,"highlight":true,"active":false},"end":{"x":112.40628941112809,"y":99.64666043201174,"highlight":true,"active":false,"active":false},"start2":{"x":92.40628941112809,"y":109.38908238107877,"highlight":true,"active":false},"end2":{"x":112.40628941112809,"y":119.38908238107877,"highlight":true,"active":false}}}]},"length":{"data":[{"visible":true,"handles":{"start":{"x":30.63388210486889,"y":77.14351868515968,"highlight":true,"active":false},"end":{"x":57.46755322260141,"y":154.21895700205096,"highlight":true,"active":false,"active":false}}}]}}';
 
  var testAngleDataString = JSON.stringify(testAngledata);
  console.log(testAngledata);
  
 
  if( this.state.loading === false)
  {
    const existingToolState = toolStateManager.saveToolState();
    console.log("existingToolState");
    console.log(existingToolState);
    var element = this.state.cornerstoneElement;
    
    var angleToolData = JSON.parse(testAngledata);
    console.log(angleToolData);
    
    cornerstoneTools.addToolState(element, 'Angle', angleToolData);
   
    cornerstone.updateImage(element,true);
      
      
  }

  return(
    
    <div style={{ display: 'flex', flexWrap: 'wrap' }}>
      <CornerstoneViewport
        tools={[
          {
            name: 'Wwwc',
            mode: 'enabled',
            modeOptions: { mouseButtonMask: 1 },
          },
          {
            name: 'Angle',
            mode: 'active',
            modeOptions: { mouseButtonMask: 1 }
          },
          // Scroll
          { name: 'StackScrollMouseWheel', mode: 'active' },
          
        ]}
        imageIds={[
          'dicomweb://s3.amazonaws.com/lury/PTCTStudy/1.3.6.1.4.1.25403.52237031786.3872.20100510032220.11.dcm',
          'dicomweb://s3.amazonaws.com/lury/PTCTStudy/1.3.6.1.4.1.25403.52237031786.3872.20100510032220.12.dcm',
        ]}
        onElementEnabled={elementEnabledEvt => {
          const cornerstoneElement = elementEnabledEvt.detail.element;

          // Save this for later
          this.setState({
            cornerstoneElement
          });
          

          // Wait for image to render, then invert it
          cornerstoneElement.addEventListener(
            'cornerstoneimagerendered',
            imageRenderedEvent => {
              const viewport = imageRenderedEvent.detail.viewport;
             
              cornerstone.setViewport(cornerstoneElement, viewport);
              this.setState({ loading: 'false' });
            }
          );
        }}
        style={{ minWidth: '100%', height: '512px', flex: '1' }}
      />
    </div>

  );
    
  
  
}

}

export default ImageViewer;

regards,
Sreevani

Error when formatting PatientsName

Version(s):

using NPM packages:
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]

I am hitting the following error when loading some arbitrary data:

TypeError: name.replace is not a function

in

formatPN from node_modules/react-cornerstone-viewport/dist/index.umd.js:2569

at

var commaBetweenFirstAndLast = name.replace('^', ', '); // Replace any remaining '^' characters with spaces

It appears that for some of my data, the name is an object (i.e. Object { Alphabetic: "C3L-00766" }. I can modify the src directly to resolve this issue, however being relatively new to cornerstone, I am not certain the best way to go about resolving this. I am using cornerstone-wado-image-loader as my image loader.

Thanks!

Events passed as props are not fired

For example, 'cornerstoneimagerendered' event is not fired when I pass it in eventListeners array. I suspect removing and adding external event listeners in componentDidUpdate causes the issue.

When Viewport property only defines stack, viewport does not update

When the passed Viewport data is only the stack, updates to the stack do not trigger an update. For example, switching from one series to a different one. A potential workaround until resolved is to set the displaySetInstanceUid with Math.random() when updating the stack.

Conditionally render ViewportOverlay w/ prop

Is there any method exposed to toggle display/hide property for the ViewportOverlay ?
I don't want to manipulate through the DOM using some classes unless some predefined method/api exists.
I tried finding about the same and couldn't get through any example demonstrating this simple behaviour.

Integrating Cornerstone.js with Next.js

Hi!

First of all: super cool library, thanks for all the effort put into this :)

I'm trying to incorporate this library into a Next.js app, but I'm going crazy with all this Server Side Rendering and Cornerstone.js rendering in the client.

Steps to Reproduce Error

  1. Create a Next app via npm init next-app.
  2. Install this library and all its peer dependencies. By the end of that I have this as my package.json file:
{
  "name": "test",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start"
  },
  "dependencies": {
    "next": "9.4.0",
    "react": "16.13.1",
    "react-cornerstone-viewport": "^2.3.8",
    "react-dom": "16.13.1"
  },
  "devDependencies": {
    "cornerstone-core": "^2.3.0",
    "cornerstone-math": "^0.1.8",
    "cornerstone-tools": "^4.15.0",
    "cornerstone-wado-image-loader": "^3.1.1",
    "dicom-parser": "^1.8.5",
    "hammerjs": "^2.0.8"
  }
}
  1. Add a minimal page to index.js:
import React from 'react'
import CornerstoneViewport from 'react-cornerstone-viewport'

export default function Home() {
  return (
    <CornerstoneViewport />
  )
}
  1. Try to run it and encounter the first error of the day: Module not found: Can't resolve 'fs' in 'cornerstone-wado-image-loader/dist'. Fixed this by modifying the webpack config, so create a next.config.js and add the following:
module.exports = {
  webpack(config, { isServer }) {
    if (!isServer) {
      config.node = {
        fs: 'empty'
      }
    }
    return config;
  }
}
  1. Try to run it again, encounter second error of the day: ReferenceError: window is not defined. I read about dynamic imports in Next.js, and they mention it is the way to include modules that are client-side only. So I modified index.js to this:
import React from 'react'
import dynamic from 'next/dynamic'

const CornerstoneViewport = dynamic(
  () => import('react-cornerstone-viewport'),
  { ssr: false }
)

export default function Home() {
  return (
    <CornerstoneViewport />
  )
}
  1. Try to run again, third error of the day: TypeError: Cannot read property 'getEnabledElement' of undefined. After researching closed issues on this project I came across a solution that mentioned you have to configure and init cornerstone with something like this:
import dicomParser from 'dicom-parser';
import cornerstone from 'cornerstone-core';
import cornerstoneWADOImageLoader from 'cornerstone-wado-image-loader';
import cornerstoneMath from 'cornerstone-math';
import cornerstoneTools from 'cornerstone-tools';
import Hammer from 'hammerjs';

export default function initCornerstone() {

  // Cornerstone Tools
  cornerstoneTools.external.cornerstone = cornerstone;
  cornerstoneTools.external.Hammer = Hammer;
  cornerstoneTools.external.cornerstoneMath = cornerstoneMath;
  cornerstoneTools.init();

  // Image Loader
  cornerstoneWADOImageLoader.external.cornerstone = cornerstone;
  cornerstoneWADOImageLoader.external.dicomParser = dicomParser;
  cornerstoneWADOImageLoader.webWorkerManager.initialize({
    maxWebWorkers: navigator.hardwareConcurrency || 1,
    startWebWorkersOnDemand: true,
    taskConfiguration: {
      decodeTask: {
        initializeCodecsOnStartup: false,
        usePDFJS: false,
        strict: false,
      },
    },
  });
}
  1. All the window not defined errors come creeping back up again.

Question

  1. I can't really import any cornerstone libraries in my repo. How can I call this function? Or initialize everything if I can't access cornerstone? Where should I call initCornerstone()?
    Doing something like this
const cornerstone = dynamic(
  () => import('cornerstone-core'),
  { ssr: false }
)

works with components, but not functions or objects... Been scratching my head for a while on this. Any help is appreciated.

Thanks!

Docs for 3rd party tools w/ `availableTools` prop

availableTools allows you to specify tools that should be "added" to the cornerstoneTools instance, with their default configuration.

Known Config

availableTools: [
    { name: 'Pan', mouseButtonMasks: [1, 4] },
    {
      name: 'Zoom',
        configuration: {
          minScale: 0.3,
          maxScale: 25,
          preventZoomOutsideImage: true
        },
        mouseButtonMasks: [1, 2]
     },
]

Undocumented Config

    {
        name: 'MyCustomTool',
        apiTool: MyCustomToolClass, // (optional)
        configuration: { ... },
        mouseButtonMasks: [...]
     },

Test cases for this setup would also be nice ^_^

Optimize eventListeners for react hook (functional component)

reproduce CodeSandbox:
https://codesandbox.io/s/react-cornerstone-viewport-evenlisteners-issue-i1hm6

The event handler would not rebind when related value change.
Currently I resolve this problem by add and remove eventListenr in useEffect.

const eventListeners = [...];

useEffect(() => {
    eventListeners.forEach(({ eventName, handler }) => {
      element.addEventListener(eventName, handler);
    });

    return () => {
      eventListeners.forEach(({ eventName, handler }) => {
        element.removeEventListener(eventName, handler);
      });
    };
  }, [realtedValue]);

Can't install react-cornerstone-viewport on react-app

Hi dudes, I'm new in react and its components, I'm trying to test viewport, from a react app that I've created.
First I've run create-react-app, then installed via npm react-cornerstone-viewport, cornerstone-core and those dependecies that appears in the examples, but when I want to import the components get an error:
error

and it seems that VSCode can't recognize those dependencies

Maybe I'm doing somewhat very bad, I dont know very well....
I'll thaks you any suggestion or help..

regards.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.