@cornerstonejs/tools 0.56.2 → 0.56.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (352) hide show
  1. package/package.json +5 -4
  2. package/src/constants/COLOR_LUT.ts +262 -0
  3. package/src/constants/index.ts +3 -0
  4. package/src/cursors/ImageMouseCursor.ts +39 -0
  5. package/src/cursors/MouseCursor.ts +114 -0
  6. package/src/cursors/SVGCursorDescriptor.ts +462 -0
  7. package/src/cursors/SVGMouseCursor.ts +145 -0
  8. package/src/cursors/elementCursor.ts +69 -0
  9. package/src/cursors/index.ts +24 -0
  10. package/src/cursors/setCursorForElement.ts +33 -0
  11. package/src/drawingSvg/_getHash.ts +9 -0
  12. package/src/drawingSvg/_setAttributesIfNecessary.ts +13 -0
  13. package/src/drawingSvg/_setNewAttributesIfValid.ts +10 -0
  14. package/src/drawingSvg/clearByToolType.ts +26 -0
  15. package/src/drawingSvg/draw.ts +16 -0
  16. package/src/drawingSvg/drawArrow.ts +82 -0
  17. package/src/drawingSvg/drawCircle.ts +62 -0
  18. package/src/drawingSvg/drawEllipse.ts +71 -0
  19. package/src/drawingSvg/drawHandles.ts +87 -0
  20. package/src/drawingSvg/drawLine.ts +70 -0
  21. package/src/drawingSvg/drawLink.ts +76 -0
  22. package/src/drawingSvg/drawLinkedTextBox.ts +64 -0
  23. package/src/drawingSvg/drawPolyline.ts +80 -0
  24. package/src/drawingSvg/drawRect.ts +70 -0
  25. package/src/drawingSvg/drawTextBox.ts +213 -0
  26. package/src/drawingSvg/getSvgDrawingHelper.ts +98 -0
  27. package/src/drawingSvg/index.ts +23 -0
  28. package/src/enums/AnnotationStyleStates.ts +22 -0
  29. package/src/enums/Events.ts +242 -0
  30. package/src/enums/SegmentationRepresentations.ts +12 -0
  31. package/src/enums/ToolBindings.ts +37 -0
  32. package/src/enums/ToolModes.ts +31 -0
  33. package/src/enums/Touch.ts +8 -0
  34. package/src/enums/index.js +16 -0
  35. package/src/eventDispatchers/annotationModifiedEventDispatcher.ts +41 -0
  36. package/src/eventDispatchers/cameraModifiedEventDispatcher.ts +41 -0
  37. package/src/eventDispatchers/imageRenderedEventDispatcher.ts +37 -0
  38. package/src/eventDispatchers/imageSpacingCalibratedEventDispatcher.ts +50 -0
  39. package/src/eventDispatchers/index.js +15 -0
  40. package/src/eventDispatchers/keyboardEventHandlers/index.js +4 -0
  41. package/src/eventDispatchers/keyboardEventHandlers/keyDown.ts +29 -0
  42. package/src/eventDispatchers/keyboardEventHandlers/keyUp.ts +33 -0
  43. package/src/eventDispatchers/keyboardToolEventDispatcher.ts +28 -0
  44. package/src/eventDispatchers/mouseEventHandlers/index.js +19 -0
  45. package/src/eventDispatchers/mouseEventHandlers/mouseClick.ts +13 -0
  46. package/src/eventDispatchers/mouseEventHandlers/mouseDoubleClick.ts +13 -0
  47. package/src/eventDispatchers/mouseEventHandlers/mouseDown.ts +196 -0
  48. package/src/eventDispatchers/mouseEventHandlers/mouseDownActivate.ts +35 -0
  49. package/src/eventDispatchers/mouseEventHandlers/mouseDrag.ts +25 -0
  50. package/src/eventDispatchers/mouseEventHandlers/mouseMove.ts +70 -0
  51. package/src/eventDispatchers/mouseEventHandlers/mouseUp.ts +9 -0
  52. package/src/eventDispatchers/mouseEventHandlers/mouseWheel.ts +13 -0
  53. package/src/eventDispatchers/mouseToolEventDispatcher.ts +64 -0
  54. package/src/eventDispatchers/shared/customCallbackHandler.ts +73 -0
  55. package/src/eventDispatchers/shared/getActiveToolForKeyboardEvent.ts +58 -0
  56. package/src/eventDispatchers/shared/getActiveToolForMouseEvent.ts +61 -0
  57. package/src/eventDispatchers/shared/getActiveToolForTouchEvent.ts +64 -0
  58. package/src/eventDispatchers/shared/getMouseModifier.ts +30 -0
  59. package/src/eventDispatchers/shared/getToolsWithModesForMouseEvent.ts +56 -0
  60. package/src/eventDispatchers/shared/getToolsWithModesForTouchEvent.ts +54 -0
  61. package/src/eventDispatchers/touchEventHandlers/index.js +15 -0
  62. package/src/eventDispatchers/touchEventHandlers/touchDrag.ts +23 -0
  63. package/src/eventDispatchers/touchEventHandlers/touchEnd.ts +9 -0
  64. package/src/eventDispatchers/touchEventHandlers/touchPress.ts +13 -0
  65. package/src/eventDispatchers/touchEventHandlers/touchStart.ts +174 -0
  66. package/src/eventDispatchers/touchEventHandlers/touchStartActivate.ts +36 -0
  67. package/src/eventDispatchers/touchEventHandlers/touchTap.ts +9 -0
  68. package/src/eventDispatchers/touchToolEventDispatcher.ts +51 -0
  69. package/src/eventListeners/annotations/annotationModifiedListener.ts +22 -0
  70. package/src/eventListeners/annotations/annotationSelectionListener.ts +29 -0
  71. package/src/eventListeners/annotations/index.ts +4 -0
  72. package/src/eventListeners/index.ts +28 -0
  73. package/src/eventListeners/keyboard/index.ts +16 -0
  74. package/src/eventListeners/keyboard/keyDownListener.ts +99 -0
  75. package/src/eventListeners/mouse/getMouseEventPoints.ts +66 -0
  76. package/src/eventListeners/mouse/index.ts +55 -0
  77. package/src/eventListeners/mouse/mouseDoubleClickListener.ts +55 -0
  78. package/src/eventListeners/mouse/mouseDownListener.ts +519 -0
  79. package/src/eventListeners/mouse/mouseMoveListener.ts +33 -0
  80. package/src/eventListeners/segmentation/index.ts +11 -0
  81. package/src/eventListeners/segmentation/segmentationDataModifiedEventListener.ts +61 -0
  82. package/src/eventListeners/segmentation/segmentationModifiedEventListener.ts +32 -0
  83. package/src/eventListeners/segmentation/segmentationRepresentationModifiedEventListener.ts +15 -0
  84. package/src/eventListeners/segmentation/segmentationRepresentationRemovedEventListener.ts +16 -0
  85. package/src/eventListeners/touch/getTouchEventPoints.ts +75 -0
  86. package/src/eventListeners/touch/index.ts +37 -0
  87. package/src/eventListeners/touch/preventGhostClick.js +72 -0
  88. package/src/eventListeners/touch/touchStartListener.ts +499 -0
  89. package/src/eventListeners/wheel/index.ts +27 -0
  90. package/src/eventListeners/wheel/normalizeWheel.ts +69 -0
  91. package/src/eventListeners/wheel/wheelListener.ts +51 -0
  92. package/src/index.ts +133 -0
  93. package/src/init.ts +187 -0
  94. package/src/stateManagement/annotation/FrameOfReferenceSpecificAnnotationManager.ts +399 -0
  95. package/src/stateManagement/annotation/annotationLocking.ts +178 -0
  96. package/src/stateManagement/annotation/annotationSelection.ts +163 -0
  97. package/src/stateManagement/annotation/annotationState.ts +180 -0
  98. package/src/stateManagement/annotation/annotationVisibility.ts +156 -0
  99. package/src/stateManagement/annotation/config/ToolStyle.ts +265 -0
  100. package/src/stateManagement/annotation/config/getFont.ts +36 -0
  101. package/src/stateManagement/annotation/config/getState.ts +26 -0
  102. package/src/stateManagement/annotation/config/helpers.ts +55 -0
  103. package/src/stateManagement/annotation/config/index.ts +5 -0
  104. package/src/stateManagement/annotation/helpers/state.ts +83 -0
  105. package/src/stateManagement/annotation/index.ts +15 -0
  106. package/src/stateManagement/index.js +40 -0
  107. package/src/stateManagement/segmentation/SegmentationStateManager.ts +491 -0
  108. package/src/stateManagement/segmentation/activeSegmentation.ts +60 -0
  109. package/src/stateManagement/segmentation/addSegmentationRepresentations.ts +77 -0
  110. package/src/stateManagement/segmentation/addSegmentations.ts +27 -0
  111. package/src/stateManagement/segmentation/config/index.ts +29 -0
  112. package/src/stateManagement/segmentation/config/segmentationColor.ts +132 -0
  113. package/src/stateManagement/segmentation/config/segmentationConfig.ts +195 -0
  114. package/src/stateManagement/segmentation/config/segmentationVisibility.ts +171 -0
  115. package/src/stateManagement/segmentation/helpers/index.ts +3 -0
  116. package/src/stateManagement/segmentation/helpers/normalizeSegmentationInput.ts +35 -0
  117. package/src/stateManagement/segmentation/helpers/validateSegmentationInput.ts +41 -0
  118. package/src/stateManagement/segmentation/index.ts +22 -0
  119. package/src/stateManagement/segmentation/removeSegmentationsFromToolGroup.ts +85 -0
  120. package/src/stateManagement/segmentation/segmentIndex.ts +38 -0
  121. package/src/stateManagement/segmentation/segmentLocking.ts +72 -0
  122. package/src/stateManagement/segmentation/segmentationState.ts +429 -0
  123. package/src/stateManagement/segmentation/triggerSegmentationEvents.ts +157 -0
  124. package/src/store/SynchronizerManager/Synchronizer.ts +344 -0
  125. package/src/store/SynchronizerManager/createSynchronizer.ts +41 -0
  126. package/src/store/SynchronizerManager/destroy.ts +14 -0
  127. package/src/store/SynchronizerManager/destroySynchronizer.ts +25 -0
  128. package/src/store/SynchronizerManager/getAllSynchronizers.ts +12 -0
  129. package/src/store/SynchronizerManager/getSynchronizer.ts +13 -0
  130. package/src/store/SynchronizerManager/getSynchronizersForViewport.ts +44 -0
  131. package/src/store/SynchronizerManager/index.js +15 -0
  132. package/src/store/ToolGroupManager/ToolGroup.ts +679 -0
  133. package/src/store/ToolGroupManager/createToolGroup.ts +33 -0
  134. package/src/store/ToolGroupManager/destroy.ts +24 -0
  135. package/src/store/ToolGroupManager/destroyToolGroup.ts +26 -0
  136. package/src/store/ToolGroupManager/getAllToolGroups.ts +12 -0
  137. package/src/store/ToolGroupManager/getToolGroup.ts +14 -0
  138. package/src/store/ToolGroupManager/getToolGroupForViewport.ts +44 -0
  139. package/src/store/ToolGroupManager/getToolGroupsWithToolName.ts +33 -0
  140. package/src/store/ToolGroupManager/index.ts +17 -0
  141. package/src/store/addEnabledElement.ts +137 -0
  142. package/src/store/addTool.ts +56 -0
  143. package/src/store/cancelActiveManipulations.ts +30 -0
  144. package/src/store/filterMoveableAnnotationTools.ts +61 -0
  145. package/src/store/filterToolsWithAnnotationsForElement.ts +51 -0
  146. package/src/store/filterToolsWithMoveableHandles.ts +51 -0
  147. package/src/store/index.ts +29 -0
  148. package/src/store/removeEnabledElement.ts +132 -0
  149. package/src/store/state.ts +57 -0
  150. package/src/store/svgNodeCache.ts +7 -0
  151. package/src/synchronizers/callbacks/areViewportsCoplanar .ts +12 -0
  152. package/src/synchronizers/callbacks/cameraSyncCallback.ts +33 -0
  153. package/src/synchronizers/callbacks/stackImageSyncCallback.ts +157 -0
  154. package/src/synchronizers/callbacks/voiSyncCallback.ts +51 -0
  155. package/src/synchronizers/callbacks/zoomPanSyncCallback.ts +43 -0
  156. package/src/synchronizers/index.ts +11 -0
  157. package/src/synchronizers/synchronizers/createCameraPositionSynchronizer.ts +25 -0
  158. package/src/synchronizers/synchronizers/createStackImageSynchronizer.ts +25 -0
  159. package/src/synchronizers/synchronizers/createVOISynchronizer.ts +24 -0
  160. package/src/synchronizers/synchronizers/createZoomPanSynchronizer.ts +25 -0
  161. package/src/synchronizers/synchronizers/index.ts +11 -0
  162. package/src/tools/CrosshairsTool.ts +2693 -0
  163. package/src/tools/MIPJumpToClickTool.ts +99 -0
  164. package/src/tools/MagnifyTool.ts +319 -0
  165. package/src/tools/PanTool.ts +58 -0
  166. package/src/tools/PlanarRotateTool.ts +77 -0
  167. package/src/tools/ReferenceCursors.ts +466 -0
  168. package/src/tools/ReferenceLinesTool.ts +279 -0
  169. package/src/tools/ScaleOverlayTool.ts +685 -0
  170. package/src/tools/StackScrollTool.ts +97 -0
  171. package/src/tools/StackScrollToolMouseWheelTool.ts +58 -0
  172. package/src/tools/TrackballRotateTool.ts +141 -0
  173. package/src/tools/VolumeRotateMouseWheelTool.ts +86 -0
  174. package/src/tools/WindowLevelTool.ts +260 -0
  175. package/src/tools/ZoomTool.ts +293 -0
  176. package/src/tools/annotation/AngleTool.ts +835 -0
  177. package/src/tools/annotation/ArrowAnnotateTool.ts +820 -0
  178. package/src/tools/annotation/BidirectionalTool.ts +1350 -0
  179. package/src/tools/annotation/CircleROITool.ts +1070 -0
  180. package/src/tools/annotation/CobbAngleTool.ts +815 -0
  181. package/src/tools/annotation/DragProbeTool.ts +213 -0
  182. package/src/tools/annotation/EllipticalROITool.ts +1223 -0
  183. package/src/tools/annotation/LengthTool.ts +861 -0
  184. package/src/tools/annotation/PlanarFreehandROITool.ts +636 -0
  185. package/src/tools/annotation/ProbeTool.ts +681 -0
  186. package/src/tools/annotation/RectangleROITool.ts +1028 -0
  187. package/src/tools/annotation/planarFreehandROITool/closedContourEditLoop.ts +488 -0
  188. package/src/tools/annotation/planarFreehandROITool/drawLoop.ts +462 -0
  189. package/src/tools/annotation/planarFreehandROITool/editLoopCommon.ts +331 -0
  190. package/src/tools/annotation/planarFreehandROITool/findOpenUShapedContourVectorToPeak.ts +74 -0
  191. package/src/tools/annotation/planarFreehandROITool/openContourEditLoop.ts +612 -0
  192. package/src/tools/annotation/planarFreehandROITool/openContourEndEditLoop.ts +74 -0
  193. package/src/tools/annotation/planarFreehandROITool/renderMethods.ts +407 -0
  194. package/src/tools/base/AnnotationDisplayTool.ts +228 -0
  195. package/src/tools/base/AnnotationTool.ts +307 -0
  196. package/src/tools/base/BaseTool.ts +215 -0
  197. package/src/tools/base/index.ts +4 -0
  198. package/src/tools/displayTools/Contour/addContourToElement.ts +135 -0
  199. package/src/tools/displayTools/Contour/contourDisplay.ts +252 -0
  200. package/src/tools/displayTools/Contour/index.ts +3 -0
  201. package/src/tools/displayTools/Contour/removeContourFromElement.ts +35 -0
  202. package/src/tools/displayTools/Labelmap/addLabelmapToElement.ts +57 -0
  203. package/src/tools/displayTools/Labelmap/index.ts +4 -0
  204. package/src/tools/displayTools/Labelmap/labelmapConfig.ts +37 -0
  205. package/src/tools/displayTools/Labelmap/labelmapDisplay.ts +461 -0
  206. package/src/tools/displayTools/Labelmap/removeLabelmapFromElement.ts +27 -0
  207. package/src/tools/displayTools/Labelmap/validateRepresentationData.ts +30 -0
  208. package/src/tools/displayTools/SegmentationDisplayTool.ts +198 -0
  209. package/src/tools/index.ts +84 -0
  210. package/src/tools/segmentation/BrushTool.ts +474 -0
  211. package/src/tools/segmentation/CircleScissorsTool.ts +365 -0
  212. package/src/tools/segmentation/PaintFillTool.ts +370 -0
  213. package/src/tools/segmentation/RectangleROIStartEndThresholdTool.ts +471 -0
  214. package/src/tools/segmentation/RectangleROIThresholdTool.ts +281 -0
  215. package/src/tools/segmentation/RectangleScissorsTool.ts +382 -0
  216. package/src/tools/segmentation/SphereScissorsTool.ts +368 -0
  217. package/src/tools/segmentation/strategies/eraseCircle.ts +30 -0
  218. package/src/tools/segmentation/strategies/eraseRectangle.ts +81 -0
  219. package/src/tools/segmentation/strategies/eraseSphere.ts +27 -0
  220. package/src/tools/segmentation/strategies/fillCircle.ts +185 -0
  221. package/src/tools/segmentation/strategies/fillRectangle.ts +110 -0
  222. package/src/tools/segmentation/strategies/fillSphere.ts +88 -0
  223. package/src/tools/segmentation/strategies/index.ts +9 -0
  224. package/src/types/AnnotationGroupSelector.ts +7 -0
  225. package/src/types/AnnotationStyle.ts +42 -0
  226. package/src/types/AnnotationTypes.ts +109 -0
  227. package/src/types/BoundsIJK.ts +5 -0
  228. package/src/types/CINETypes.ts +32 -0
  229. package/src/types/ContourTypes.ts +26 -0
  230. package/src/types/CursorTypes.ts +12 -0
  231. package/src/types/EventTypes.ts +657 -0
  232. package/src/types/FloodFillTypes.ts +19 -0
  233. package/src/types/IAnnotationManager.ts +89 -0
  234. package/src/types/IDistance.ts +16 -0
  235. package/src/types/IPoints.ts +18 -0
  236. package/src/types/ISetToolModeOptions.ts +29 -0
  237. package/src/types/ISynchronizerEventHandler.ts +11 -0
  238. package/src/types/IToolClassReference.ts +5 -0
  239. package/src/types/IToolGroup.ts +72 -0
  240. package/src/types/ITouchPoints.ts +14 -0
  241. package/src/types/InteractionTypes.ts +6 -0
  242. package/src/types/InternalToolTypes.ts +19 -0
  243. package/src/types/JumpToSliceOptions.ts +7 -0
  244. package/src/types/LabelmapTypes.ts +41 -0
  245. package/src/types/PlanarBoundingBox.ts +8 -0
  246. package/src/types/SVGDrawingHelper.ts +10 -0
  247. package/src/types/ScrollOptions.ts +9 -0
  248. package/src/types/SegmentationStateTypes.ts +248 -0
  249. package/src/types/ToolHandle.ts +26 -0
  250. package/src/types/ToolProps.ts +16 -0
  251. package/src/types/ToolSpecificAnnotationTypes.ts +311 -0
  252. package/src/types/index.ts +115 -0
  253. package/src/utilities/boundingBox/extend2DBoundingBoxInViewAxis.ts +29 -0
  254. package/src/utilities/boundingBox/getBoundingBoxAroundShape.ts +57 -0
  255. package/src/utilities/boundingBox/index.ts +4 -0
  256. package/src/utilities/calibrateImageSpacing.ts +46 -0
  257. package/src/utilities/cine/events.ts +9 -0
  258. package/src/utilities/cine/index.ts +5 -0
  259. package/src/utilities/cine/playClip.ts +435 -0
  260. package/src/utilities/cine/state.ts +18 -0
  261. package/src/utilities/clip.js +30 -0
  262. package/src/utilities/debounce.js +217 -0
  263. package/src/utilities/drawing/getTextBoxCoordsCanvas.ts +45 -0
  264. package/src/utilities/drawing/index.ts +3 -0
  265. package/src/utilities/dynamicVolume/getDataInTime.ts +110 -0
  266. package/src/utilities/dynamicVolume/index.ts +2 -0
  267. package/src/utilities/getAnnotationNearPoint.ts +130 -0
  268. package/src/utilities/getModalityUnit.ts +11 -0
  269. package/src/utilities/getToolsWithModesForElement.ts +52 -0
  270. package/src/utilities/index.ts +68 -0
  271. package/src/utilities/isObject.js +29 -0
  272. package/src/utilities/math/angle/angleBetweenLines.ts +29 -0
  273. package/src/utilities/math/circle/_types.ts +6 -0
  274. package/src/utilities/math/circle/getCanvasCircleCorners.ts +23 -0
  275. package/src/utilities/math/circle/getCanvasCircleRadius.ts +16 -0
  276. package/src/utilities/math/circle/index.ts +4 -0
  277. package/src/utilities/math/ellipse/getCanvasEllipseCorners.ts +26 -0
  278. package/src/utilities/math/ellipse/index.ts +4 -0
  279. package/src/utilities/math/ellipse/pointInEllipse.ts +38 -0
  280. package/src/utilities/math/ellipse/pointInEllipsoidWithConstraint.ts +35 -0
  281. package/src/utilities/math/index.ts +8 -0
  282. package/src/utilities/math/line/distanceToPoint.ts +24 -0
  283. package/src/utilities/math/line/distanceToPointSquared.ts +44 -0
  284. package/src/utilities/math/line/index.ts +5 -0
  285. package/src/utilities/math/line/intersectLine.ts +92 -0
  286. package/src/utilities/math/midPoint.ts +24 -0
  287. package/src/utilities/math/point/distanceToPoint.ts +22 -0
  288. package/src/utilities/math/point/index.ts +3 -0
  289. package/src/utilities/math/polyline/addCanvasPointsToArray.ts +62 -0
  290. package/src/utilities/math/polyline/calculateAreaOfPoints.ts +23 -0
  291. package/src/utilities/math/polyline/getIntersectionWithPolyline.ts +182 -0
  292. package/src/utilities/math/polyline/getSubPixelSpacingAndXYDirections.ts +99 -0
  293. package/src/utilities/math/polyline/index.ts +19 -0
  294. package/src/utilities/math/polyline/planarFreehandROIInternalTypes.ts +36 -0
  295. package/src/utilities/math/polyline/pointCanProjectOnLine.ts +57 -0
  296. package/src/utilities/math/polyline/pointsAreWithinCloseContourProximity.ts +15 -0
  297. package/src/utilities/math/rectangle/distanceToPoint.ts +82 -0
  298. package/src/utilities/math/rectangle/index.ts +3 -0
  299. package/src/utilities/math/sphere/index.ts +3 -0
  300. package/src/utilities/math/sphere/pointInSphere.ts +31 -0
  301. package/src/utilities/math/vec2/findClosestPoint.ts +40 -0
  302. package/src/utilities/math/vec2/index.ts +4 -0
  303. package/src/utilities/math/vec2/liangBarksyClip.ts +84 -0
  304. package/src/utilities/orientation/getOrientationStringLPS.ts +52 -0
  305. package/src/utilities/orientation/index.ts +4 -0
  306. package/src/utilities/orientation/invertOrientationStringLPS.ts +21 -0
  307. package/src/utilities/planar/filterAnnotationsForDisplay.ts +68 -0
  308. package/src/utilities/planar/filterAnnotationsWithinSlice.ts +85 -0
  309. package/src/utilities/planar/getPointInLineOfSightWithCriteria.ts +104 -0
  310. package/src/utilities/planar/getWorldWidthAndHeightFromCorners.ts +51 -0
  311. package/src/utilities/planar/getWorldWidthAndHeightFromTwoPoints.ts +51 -0
  312. package/src/utilities/planar/index.ts +18 -0
  313. package/src/utilities/planarFreehandROITool/index.ts +7 -0
  314. package/src/utilities/planarFreehandROITool/interpolateAnnotation.ts +87 -0
  315. package/src/utilities/planarFreehandROITool/interpolatePoints.ts +214 -0
  316. package/src/utilities/planarFreehandROITool/interpolation/algorithms/bspline.ts +55 -0
  317. package/src/utilities/planarFreehandROITool/interpolation/interpolateSegmentPoints.ts +90 -0
  318. package/src/utilities/pointInShapeCallback.ts +138 -0
  319. package/src/utilities/pointInSurroundingSphereCallback.ts +188 -0
  320. package/src/utilities/rectangleROITool/getBoundsIJKFromRectangleAnnotations.ts +76 -0
  321. package/src/utilities/rectangleROITool/index.ts +3 -0
  322. package/src/utilities/scroll.ts +62 -0
  323. package/src/utilities/segmentation/brushSizeForToolGroup.ts +72 -0
  324. package/src/utilities/segmentation/brushThresholdForToolGroup.ts +65 -0
  325. package/src/utilities/segmentation/createLabelmapVolumeForViewport.ts +74 -0
  326. package/src/utilities/segmentation/createMergedLabelmapForIndex.ts +65 -0
  327. package/src/utilities/segmentation/floodFill.ts +194 -0
  328. package/src/utilities/segmentation/getDefaultRepresentationConfig.ts +20 -0
  329. package/src/utilities/segmentation/index.ts +33 -0
  330. package/src/utilities/segmentation/isValidRepresentationConfig.ts +22 -0
  331. package/src/utilities/segmentation/rectangleROIThresholdVolumeByRange.ts +91 -0
  332. package/src/utilities/segmentation/thresholdSegmentationByRange.ts +129 -0
  333. package/src/utilities/segmentation/thresholdVolumeByRange.ts +150 -0
  334. package/src/utilities/segmentation/triggerSegmentationRender.ts +206 -0
  335. package/src/utilities/segmentation/utilities.ts +116 -0
  336. package/src/utilities/stackPrefetch/index.ts +8 -0
  337. package/src/utilities/stackPrefetch/stackPrefetch.ts +405 -0
  338. package/src/utilities/stackPrefetch/state.ts +17 -0
  339. package/src/utilities/throttle.js +69 -0
  340. package/src/utilities/touch/index.ts +246 -0
  341. package/src/utilities/triggerAnnotationRender.ts +237 -0
  342. package/src/utilities/triggerAnnotationRenderForViewportIds.ts +18 -0
  343. package/src/utilities/viewport/index.ts +5 -0
  344. package/src/utilities/viewport/isViewportPreScaled.ts +24 -0
  345. package/src/utilities/viewport/jumpToSlice.ts +73 -0
  346. package/src/utilities/viewport/jumpToWorld.ts +58 -0
  347. package/src/utilities/viewportFilters/filterViewportsWithFrameOfReferenceUID.ts +28 -0
  348. package/src/utilities/viewportFilters/filterViewportsWithParallelNormals.ts +26 -0
  349. package/src/utilities/viewportFilters/filterViewportsWithSameOrientation.ts +15 -0
  350. package/src/utilities/viewportFilters/filterViewportsWithToolEnabled.ts +72 -0
  351. package/src/utilities/viewportFilters/getViewportIdsWithToolToRender.ts +45 -0
  352. package/src/utilities/viewportFilters/index.ts +11 -0
@@ -0,0 +1,435 @@
1
+ import { glMatrix, vec3 } from 'gl-matrix';
2
+ import {
3
+ utilities as csUtils,
4
+ getEnabledElement,
5
+ StackViewport,
6
+ VolumeViewport,
7
+ cache,
8
+ } from '@cornerstonejs/core';
9
+
10
+ import { Types } from '@cornerstonejs/core';
11
+ import CINE_EVENTS from './events';
12
+ import { addToolState, getToolState } from './state';
13
+ import { CINETypes } from '../../types';
14
+ import scroll from '../scroll';
15
+
16
+ const { triggerEvent } = csUtils;
17
+
18
+ const debounced = true;
19
+ const loop = true;
20
+ const dynamicVolumesPlayingMap = new Map();
21
+
22
+ /**
23
+ * Starts playing a clip or adjusts the frame rate of an already playing clip. framesPerSecond is
24
+ * optional and defaults to 30 if not specified. A negative framesPerSecond will play the clip in reverse.
25
+ * The element must be a stack of images
26
+ * @param element - HTML Element
27
+ * @param framesPerSecond - Number of frames per second
28
+ */
29
+ function playClip(
30
+ element: HTMLDivElement,
31
+ playClipOptions: CINETypes.PlayClipOptions
32
+ ): void {
33
+ let playClipTimeouts;
34
+ let playClipIsTimeVarying;
35
+
36
+ if (element === undefined) {
37
+ throw new Error('playClip: element must not be undefined');
38
+ }
39
+
40
+ const enabledElement = getEnabledElement(element);
41
+
42
+ if (!enabledElement) {
43
+ throw new Error(
44
+ 'playClip: element must be a valid Cornerstone enabled element'
45
+ );
46
+ }
47
+
48
+ // 4D Cine is enabled by default
49
+ playClipOptions.dynamicCineEnabled =
50
+ playClipOptions.dynamicCineEnabled ?? true;
51
+
52
+ const { viewport } = enabledElement;
53
+ const volume = _getVolumeFromViewport(viewport);
54
+ const playClipContext = _createCinePlayContext(viewport, playClipOptions);
55
+ let playClipData = getToolState(element);
56
+
57
+ const isDynamicCinePlaying =
58
+ playClipOptions.dynamicCineEnabled && volume?.isDynamicVolume();
59
+
60
+ // If user is trying to play CINE for a 4D volume it first needs
61
+ // to stop CINE that has may be playing for any other viewport.
62
+ if (isDynamicCinePlaying) {
63
+ _stopDynamicVolumeCine(element);
64
+ }
65
+
66
+ if (!playClipData) {
67
+ playClipData = {
68
+ intervalId: undefined,
69
+ framesPerSecond: 30,
70
+ lastFrameTimeStamp: undefined,
71
+ ignoreFrameTimeVector: false,
72
+ usingFrameTimeVector: false,
73
+ frameTimeVector: playClipOptions.frameTimeVector ?? undefined,
74
+ speed: playClipOptions.frameTimeVectorSpeedMultiplier ?? 1,
75
+ reverse: playClipOptions.reverse ?? false,
76
+ loop: playClipOptions.loop ?? true,
77
+ };
78
+ addToolState(element, playClipData);
79
+ } else {
80
+ // Make sure the specified clip is not running before any property update.
81
+ // If a 3D CINE was playing it passes isDynamicCinePlaying as FALSE to
82
+ // prevent stopping a 4D CINE in case it is playing on another viewport.
83
+ _stopClip(element, isDynamicCinePlaying);
84
+ }
85
+
86
+ playClipData.dynamicCineEnabled = playClipOptions.dynamicCineEnabled;
87
+
88
+ // If a framesPerSecond is specified and is valid, update the playClipData now
89
+ if (
90
+ playClipOptions.framesPerSecond < 0 ||
91
+ playClipOptions.framesPerSecond > 0
92
+ ) {
93
+ playClipData.framesPerSecond = Number(playClipOptions.framesPerSecond);
94
+ playClipData.reverse = playClipData.framesPerSecond < 0;
95
+ // If framesPerSecond is given, frameTimeVector will be ignored...
96
+ playClipData.ignoreFrameTimeVector = true;
97
+ }
98
+
99
+ // Determine if frame time vector should be used instead of a fixed frame rate...
100
+ if (
101
+ playClipData.ignoreFrameTimeVector !== true &&
102
+ playClipData.frameTimeVector &&
103
+ playClipData.frameTimeVector.length === playClipContext.numScrollSteps &&
104
+ playClipContext.frameTimeVectorEnabled
105
+ ) {
106
+ const { timeouts, isTimeVarying } = _getPlayClipTimeouts(
107
+ playClipData.frameTimeVector,
108
+ playClipData.speed
109
+ );
110
+
111
+ playClipTimeouts = timeouts;
112
+ playClipIsTimeVarying = isTimeVarying;
113
+ }
114
+
115
+ // This function encapsulates the frame rendering logic...
116
+ const playClipAction = () => {
117
+ const { numScrollSteps, currentStepIndex } = playClipContext;
118
+ let newStepIndex = currentStepIndex + (playClipData.reverse ? -1 : 1);
119
+ const newStepIndexOutOfRange =
120
+ newStepIndex < 0 || newStepIndex >= numScrollSteps;
121
+
122
+ if (!loop && newStepIndexOutOfRange) {
123
+ // If a 3D CINE was playing it passes isDynamicCinePlaying as FALSE to
124
+ // prevent stopping a 4D CINE in case it is playing on another viewport.
125
+ _stopClip(element, isDynamicCinePlaying);
126
+
127
+ const eventDetail = { element };
128
+
129
+ triggerEvent(element, CINE_EVENTS.CLIP_STOPPED, eventDetail);
130
+ return;
131
+ }
132
+
133
+ // Loop around if newStepIndex is out of range
134
+ if (newStepIndex >= numScrollSteps) {
135
+ newStepIndex = 0;
136
+ } else if (newStepIndex < 0) {
137
+ newStepIndex = numScrollSteps - 1;
138
+ }
139
+
140
+ const delta = newStepIndex - currentStepIndex;
141
+
142
+ if (delta) {
143
+ playClipContext.scroll(delta);
144
+ }
145
+ };
146
+
147
+ if (isDynamicCinePlaying) {
148
+ dynamicVolumesPlayingMap.set(volume.volumeId, element);
149
+ }
150
+
151
+ // If playClipTimeouts array is available, not empty and its elements are NOT uniform ...
152
+ // ... (at least one timeout is different from the others), use alternate setTimeout implementation
153
+ if (
154
+ playClipTimeouts &&
155
+ playClipTimeouts.length > 0 &&
156
+ playClipIsTimeVarying
157
+ ) {
158
+ playClipData.usingFrameTimeVector = true;
159
+ playClipData.intervalId = window.setTimeout(
160
+ function playClipTimeoutHandler() {
161
+ playClipData.intervalId = window.setTimeout(
162
+ playClipTimeoutHandler,
163
+ playClipTimeouts[playClipContext.currentStepIndex]
164
+ );
165
+ playClipAction();
166
+ },
167
+ 0
168
+ );
169
+ } else {
170
+ // ... otherwise user setInterval implementation which is much more efficient.
171
+ playClipData.usingFrameTimeVector = false;
172
+ playClipData.intervalId = window.setInterval(
173
+ playClipAction,
174
+ 1000 / Math.abs(playClipData.framesPerSecond)
175
+ );
176
+ }
177
+
178
+ const eventDetail = {
179
+ element,
180
+ };
181
+
182
+ triggerEvent(element, CINE_EVENTS.CLIP_STARTED, eventDetail);
183
+ }
184
+
185
+ /**
186
+ * Stops an already playing clip.
187
+ * @param element - HTML Element
188
+ */
189
+ function stopClip(element: HTMLDivElement): void {
190
+ _stopClip(element, true);
191
+ }
192
+
193
+ function _stopClip(element: HTMLDivElement, stopDynamicCine: boolean): void {
194
+ const enabledElement = getEnabledElement(element);
195
+ if (!enabledElement) return;
196
+ const { viewport } = enabledElement;
197
+ const cineToolData = getToolState(viewport.element);
198
+
199
+ if (cineToolData) {
200
+ _stopClipWithData(cineToolData);
201
+ }
202
+
203
+ if (stopDynamicCine) {
204
+ _stopDynamicVolumeCine(element);
205
+ }
206
+ }
207
+
208
+ /**
209
+ * [private] Stops any CINE playing for the dynamic volume loaded on this viewport
210
+ * @param element - HTML Element
211
+ */
212
+ function _stopDynamicVolumeCine(element) {
213
+ const { viewport } = getEnabledElement(element);
214
+ const volume = _getVolumeFromViewport(viewport);
215
+
216
+ // If the current viewport has a 4D volume loaded it may be playing
217
+ // if it is also loaded on another viewport and user has started CINE
218
+ // for that one. This guarantees the other viewport will also be stopped.
219
+ if (volume?.isDynamicVolume()) {
220
+ const dynamicCineElement = dynamicVolumesPlayingMap.get(volume.volumeId);
221
+
222
+ dynamicVolumesPlayingMap.delete(volume.volumeId);
223
+
224
+ if (dynamicCineElement && dynamicCineElement !== element) {
225
+ stopClip(<HTMLDivElement>dynamicCineElement);
226
+ }
227
+ }
228
+ }
229
+
230
+ /**
231
+ * [private] Turns a Frame Time Vector (0018,1065) array into a normalized array of timeouts. Each element
232
+ * ... of the resulting array represents the amount of time each frame will remain on the screen.
233
+ * @param vector - A Frame Time Vector (0018,1065) as specified in section C.7.6.5.1.2 of DICOM standard.
234
+ * @param speed - A speed factor which will be applied to each element of the resulting array.
235
+ * @returns An array with timeouts for each animation frame.
236
+ */
237
+ function _getPlayClipTimeouts(vector: number[], speed: number) {
238
+ let i;
239
+ let sample;
240
+ let delay;
241
+ let sum = 0;
242
+ const limit = vector.length;
243
+ const timeouts = [];
244
+
245
+ // Initialize time varying to false
246
+ let isTimeVarying = false;
247
+
248
+ if (typeof speed !== 'number' || speed <= 0) {
249
+ speed = 1;
250
+ }
251
+
252
+ // First element of a frame time vector must be discarded
253
+ for (i = 1; i < limit; i++) {
254
+ // eslint-disable-next-line no-bitwise
255
+ delay = (Number(vector[i]) / speed) | 0; // Integral part only
256
+ timeouts.push(delay);
257
+ if (i === 1) {
258
+ // Use first item as a sample for comparison
259
+ sample = delay;
260
+ } else if (delay !== sample) {
261
+ isTimeVarying = true;
262
+ }
263
+
264
+ sum += delay;
265
+ }
266
+
267
+ if (timeouts.length > 0) {
268
+ if (isTimeVarying) {
269
+ // If it's a time varying vector, make the last item an average...
270
+ // eslint-disable-next-line no-bitwise
271
+ delay = (sum / timeouts.length) | 0;
272
+ } else {
273
+ delay = timeouts[0];
274
+ }
275
+
276
+ timeouts.push(delay);
277
+ }
278
+
279
+ return { timeouts, isTimeVarying };
280
+ }
281
+
282
+ /**
283
+ * [private] Performs the heavy lifting of stopping an ongoing animation.
284
+ * @param element - HTML Element
285
+ * @param playClipData - The data from playClip that needs to be stopped.
286
+ */
287
+ function _stopClipWithData(playClipData) {
288
+ const id = playClipData.intervalId;
289
+
290
+ if (typeof id !== 'undefined') {
291
+ playClipData.intervalId = undefined;
292
+ if (playClipData.usingFrameTimeVector) {
293
+ clearTimeout(id);
294
+ } else {
295
+ clearInterval(id);
296
+ }
297
+ }
298
+ }
299
+
300
+ function _getVolumeFromViewport(viewport): Types.IImageVolume {
301
+ const actorEntry = viewport.getDefaultActor();
302
+
303
+ if (!actorEntry) {
304
+ console.warn('No actor found');
305
+ return;
306
+ }
307
+
308
+ const volumeId = actorEntry.uid;
309
+ return cache.getVolume(volumeId);
310
+ }
311
+
312
+ function _createStackViewportCinePlayContext(
313
+ viewport: StackViewport
314
+ ): CINETypes.CinePlayContext {
315
+ const imageIds = viewport.getImageIds();
316
+
317
+ return {
318
+ get numScrollSteps(): number {
319
+ return imageIds.length;
320
+ },
321
+ get currentStepIndex(): number {
322
+ return viewport.getTargetImageIdIndex();
323
+ },
324
+ get frameTimeVectorEnabled(): boolean {
325
+ // It is always in acquired orientation
326
+ return true;
327
+ },
328
+ scroll(delta: number): void {
329
+ scroll(viewport, { delta, debounceLoading: debounced });
330
+ },
331
+ };
332
+ }
333
+
334
+ function _createVolumeViewportCinePlayContext(
335
+ viewport: VolumeViewport,
336
+ volume: Types.IImageVolume
337
+ ): CINETypes.CinePlayContext {
338
+ const { volumeId } = volume;
339
+ const cachedScrollInfo = {
340
+ viewPlaneNormal: vec3.create(),
341
+ scrollInfo: null,
342
+ };
343
+
344
+ const getScrollInfo = () => {
345
+ const camera = viewport.getCamera();
346
+ const updateCache =
347
+ !cachedScrollInfo.scrollInfo ||
348
+ !vec3.equals(camera.viewPlaneNormal, cachedScrollInfo.viewPlaneNormal);
349
+
350
+ // Number of steps would change only after rotating the volume so it
351
+ // caches the result and recomputes only when necessary. Until it is
352
+ // rotated the current frame is updated locally
353
+ if (updateCache) {
354
+ const scrollInfo = csUtils.getVolumeViewportScrollInfo(
355
+ viewport,
356
+ volumeId
357
+ );
358
+
359
+ cachedScrollInfo.viewPlaneNormal = camera.viewPlaneNormal;
360
+ cachedScrollInfo.scrollInfo = scrollInfo;
361
+ }
362
+
363
+ return cachedScrollInfo.scrollInfo;
364
+ };
365
+
366
+ return {
367
+ get numScrollSteps(): number {
368
+ return getScrollInfo().numScrollSteps;
369
+ },
370
+ get currentStepIndex(): number {
371
+ return getScrollInfo().currentStepIndex;
372
+ },
373
+ get frameTimeVectorEnabled(): boolean {
374
+ const camera = viewport.getCamera();
375
+ const volumeViewPlaneNormal = volume.direction
376
+ .slice(6, 9)
377
+ .map((x) => -x) as Types.Point3;
378
+ const dot = vec3.dot(volumeViewPlaneNormal, camera.viewPlaneNormal);
379
+
380
+ // Check if the volume is in acquired orientation
381
+ // it may be flipped or rotated in plane
382
+ return glMatrix.equals(dot, 1);
383
+ },
384
+ scroll(delta: number): void {
385
+ getScrollInfo().currentStepIndex += delta;
386
+ scroll(viewport, { delta });
387
+ },
388
+ };
389
+ }
390
+
391
+ function _createDynamicVolumeViewportCinePlayContext(
392
+ volume: Types.IDynamicImageVolume
393
+ ): CINETypes.CinePlayContext {
394
+ return {
395
+ get numScrollSteps(): number {
396
+ return volume.numTimePoints;
397
+ },
398
+ get currentStepIndex(): number {
399
+ return volume.timePointIndex;
400
+ },
401
+ get frameTimeVectorEnabled(): boolean {
402
+ // Looping throught time does not uses frameTimeVector
403
+ return false;
404
+ },
405
+ scroll(delta: number): void {
406
+ // Updating this property (setter) makes it move to the desired time point
407
+ volume.timePointIndex += delta;
408
+ },
409
+ };
410
+ }
411
+
412
+ function _createCinePlayContext(
413
+ viewport,
414
+ playClipOptions: CINETypes.PlayClipOptions
415
+ ): CINETypes.CinePlayContext {
416
+ if (viewport instanceof StackViewport) {
417
+ return _createStackViewportCinePlayContext(viewport);
418
+ }
419
+
420
+ if (viewport instanceof VolumeViewport) {
421
+ const volume = _getVolumeFromViewport(viewport);
422
+
423
+ if (playClipOptions.dynamicCineEnabled && volume?.isDynamicVolume()) {
424
+ return _createDynamicVolumeViewportCinePlayContext(
425
+ <Types.IDynamicImageVolume>volume
426
+ );
427
+ }
428
+
429
+ return _createVolumeViewportCinePlayContext(viewport, volume);
430
+ }
431
+
432
+ throw new Error('Unknown viewport type');
433
+ }
434
+
435
+ export { playClip, stopClip };
@@ -0,0 +1,18 @@
1
+ import { getEnabledElement } from '@cornerstonejs/core';
2
+ import { CINETypes } from '../../types';
3
+
4
+ const state: Record<string, CINETypes.ToolData> = {};
5
+
6
+ function addToolState(element: HTMLDivElement, data: CINETypes.ToolData): void {
7
+ const enabledElement = getEnabledElement(element);
8
+ const { viewportId } = enabledElement;
9
+ state[viewportId] = data;
10
+ }
11
+
12
+ function getToolState(element: HTMLDivElement): CINETypes.ToolData | undefined {
13
+ const enabledElement = getEnabledElement(element);
14
+ const { viewportId } = enabledElement;
15
+ return state[viewportId];
16
+ }
17
+
18
+ export { addToolState, getToolState };
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Clips a value to an upper and lower bound.
3
+ * @export @public @method
4
+ * @name clip
5
+ *
6
+ * @param {number} val The value to clip.
7
+ * @param {number} low The lower bound.
8
+ * @param {number} high The upper bound.
9
+ * @returns {number} The clipped value.
10
+ */
11
+ export function clip(val, low, high) {
12
+ return Math.min(Math.max(low, val), high);
13
+ }
14
+
15
+ /**
16
+ * Clips a value within a box.
17
+ * @export @public @method
18
+ * @name clipToBox
19
+ *
20
+ * @param {Object} point The point to clip
21
+ * @param {Object} box The bounding box to clip to.
22
+ * @returns {Object} The clipped point.
23
+ */
24
+ export function clipToBox(point, box) {
25
+ // Clip an {x, y} point to a box of size {width, height}
26
+ point.x = clip(point.x, 0, box.width);
27
+ point.y = clip(point.y, 0, box.height);
28
+ }
29
+
30
+ export default clip;
@@ -0,0 +1,217 @@
1
+ import isObject from './isObject';
2
+
3
+ /**
4
+ * Creates a debounced function that delays invoking `func` until after `wait`
5
+ * milliseconds have elapsed since the last time the debounced function was
6
+ * invoked, or until the next browser frame is drawn. The debounced function
7
+ * comes with a `cancel` method to cancel delayed `func` invocations and a
8
+ * `flush` method to immediately invoke them. Provide `options` to indicate
9
+ * whether `func` should be invoked on the leading and/or trailing edge of the
10
+ * `wait` timeout. The `func` is invoked with the last arguments provided to the
11
+ * debounced function. Subsequent calls to the debounced function return the
12
+ * result of the last `func` invocation.
13
+ *
14
+ * **Note:** If `leading` and `trailing` options are `true`, `func` is
15
+ * invoked on the trailing edge of the timeout only if the debounced function
16
+ * is invoked more than once during the `wait` timeout.
17
+ *
18
+ * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
19
+ * until the next tick, similar to `setTimeout` with a timeout of `0`.
20
+ *
21
+ * If `wait` is omitted in an environment with `requestAnimationFrame`, `func`
22
+ * invocation will be deferred until the next frame is drawn (typically about
23
+ * 16ms).
24
+ *
25
+ * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
26
+ * for details over the differences between `debounce` and `throttle`.
27
+ *
28
+ * @param {Function} func The function to debounce.
29
+ * @param {number} [wait=0]
30
+ * The number of milliseconds to delay; if omitted, `requestAnimationFrame` is
31
+ * used (if available).
32
+ * @param {Object} [options={}] The options object.
33
+ * @param {boolean} [options.leading=false]
34
+ * Specify invoking on the leading edge of the timeout.
35
+ * @param {number} [options.maxWait]
36
+ * The maximum time `func` is allowed to be delayed before it's invoked.
37
+ * @param {boolean} [options.trailing=true]
38
+ * Specify invoking on the trailing edge of the timeout.
39
+ * @returns {Function} Returns the new debounced function.
40
+ * @example
41
+ *
42
+ * // Avoid costly calculations while the window size is in flux.
43
+ * jQuery(window).on('resize', debounce(calculateLayout, 150))
44
+ *
45
+ * // Invoke `sendMail` when clicked, debouncing subsequent calls.
46
+ * jQuery(element).on('click', debounce(sendMail, 300, {
47
+ * 'leading': true,
48
+ * 'trailing': false
49
+ * }))
50
+ *
51
+ * // Ensure `batchLog` is invoked once after 1 second of debounced calls.
52
+ * const debounced = debounce(batchLog, 250, { 'maxWait': 1000 })
53
+ * const source = new EventSource('/stream')
54
+ * jQuery(source).on('message', debounced)
55
+ *
56
+ * // Cancel the trailing debounced invocation.
57
+ * jQuery(window).on('popstate', debounced.cancel)
58
+ *
59
+ * // Check for pending invocations.
60
+ * const status = debounced.pending() ? "Pending..." : "Ready"
61
+ */
62
+ function debounce(func, wait, options) {
63
+ let lastArgs, lastThis, maxWait, result, timerId, lastCallTime;
64
+
65
+ let lastInvokeTime = 0;
66
+ let leading = false;
67
+ let maxing = false;
68
+ let trailing = true;
69
+
70
+ // Bypass `requestAnimationFrame` by explicitly setting `wait=0`.
71
+ const useRAF =
72
+ !wait && wait !== 0 && typeof window.requestAnimationFrame === 'function';
73
+
74
+ if (typeof func !== 'function') {
75
+ throw new TypeError('Expected a function');
76
+ }
77
+ wait = Number(wait) || 0;
78
+ if (isObject(options)) {
79
+ leading = Boolean(options.leading);
80
+ maxing = 'maxWait' in options;
81
+ maxWait = maxing ? Math.max(Number(options.maxWait) || 0, wait) : maxWait;
82
+ trailing = 'trailing' in options ? Boolean(options.trailing) : trailing;
83
+ }
84
+
85
+ function invokeFunc(time) {
86
+ const args = lastArgs;
87
+ const thisArg = lastThis;
88
+
89
+ lastArgs = lastThis = undefined;
90
+ lastInvokeTime = time;
91
+ result = func.apply(thisArg, args);
92
+
93
+ return result;
94
+ }
95
+
96
+ function startTimer(pendingFunc, wait) {
97
+ if (useRAF) {
98
+ return window.requestAnimationFrame(pendingFunc);
99
+ }
100
+
101
+ return setTimeout(pendingFunc, wait);
102
+ }
103
+
104
+ function cancelTimer(id) {
105
+ if (useRAF) {
106
+ return window.cancelAnimationFrame(id);
107
+ }
108
+ clearTimeout(id);
109
+ }
110
+
111
+ function leadingEdge(time) {
112
+ // Reset any `maxWait` timer.
113
+ lastInvokeTime = time;
114
+ // Start the timer for the trailing edge.
115
+ timerId = startTimer(timerExpired, wait);
116
+
117
+ // Invoke the leading edge.
118
+ return leading ? invokeFunc(time) : result;
119
+ }
120
+
121
+ function remainingWait(time) {
122
+ const timeSinceLastCall = time - lastCallTime;
123
+ const timeSinceLastInvoke = time - lastInvokeTime;
124
+ const timeWaiting = wait - timeSinceLastCall;
125
+
126
+ return maxing
127
+ ? Math.min(timeWaiting, maxWait - timeSinceLastInvoke)
128
+ : timeWaiting;
129
+ }
130
+
131
+ function shouldInvoke(time) {
132
+ const timeSinceLastCall = time - lastCallTime;
133
+ const timeSinceLastInvoke = time - lastInvokeTime;
134
+
135
+ // Either this is the first call, activity has stopped and we're at the
136
+ // trailing edge, the system time has gone backwards and we're treating
137
+ // it as the trailing edge, or we've hit the `maxWait` limit.
138
+ return (
139
+ lastCallTime === undefined ||
140
+ timeSinceLastCall >= wait ||
141
+ timeSinceLastCall < 0 ||
142
+ (maxing && timeSinceLastInvoke >= maxWait)
143
+ );
144
+ }
145
+
146
+ function timerExpired() {
147
+ const time = Date.now();
148
+
149
+ if (shouldInvoke(time)) {
150
+ return trailingEdge(time);
151
+ }
152
+ // Restart the timer.
153
+ timerId = startTimer(timerExpired, remainingWait(time));
154
+ }
155
+
156
+ function trailingEdge(time) {
157
+ timerId = undefined;
158
+
159
+ // Only invoke if we have `lastArgs` which means `func` has been
160
+ // debounced at least once.
161
+ if (trailing && lastArgs) {
162
+ return invokeFunc(time);
163
+ }
164
+ lastArgs = lastThis = undefined;
165
+
166
+ return result;
167
+ }
168
+
169
+ function cancel() {
170
+ if (timerId !== undefined) {
171
+ cancelTimer(timerId);
172
+ }
173
+ lastInvokeTime = 0;
174
+ lastArgs = lastCallTime = lastThis = timerId = undefined;
175
+ }
176
+
177
+ function flush() {
178
+ return timerId === undefined ? result : trailingEdge(Date.now());
179
+ }
180
+
181
+ function pending() {
182
+ return timerId !== undefined;
183
+ }
184
+
185
+ function debounced(...args) {
186
+ const time = Date.now();
187
+ const isInvoking = shouldInvoke(time);
188
+
189
+ lastArgs = args;
190
+ lastThis = this; // eslint-disable-line consistent-this
191
+ lastCallTime = time;
192
+
193
+ if (isInvoking) {
194
+ if (timerId === undefined) {
195
+ return leadingEdge(lastCallTime);
196
+ }
197
+ if (maxing) {
198
+ // Handle invocations in a tight loop.
199
+ timerId = startTimer(timerExpired, wait);
200
+
201
+ return invokeFunc(lastCallTime);
202
+ }
203
+ }
204
+ if (timerId === undefined) {
205
+ timerId = startTimer(timerExpired, wait);
206
+ }
207
+
208
+ return result;
209
+ }
210
+ debounced.cancel = cancel;
211
+ debounced.flush = flush;
212
+ debounced.pending = pending;
213
+
214
+ return debounced;
215
+ }
216
+
217
+ export default debounce;