@vitessce/neuroglancer 3.5.12 → 3.6.1

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vitessce/neuroglancer",
3
- "version": "3.5.12",
3
+ "version": "3.6.1",
4
4
  "author": "Gehlenborg Lab",
5
5
  "homepage": "http://vitessce.io",
6
6
  "repository": {
@@ -17,17 +17,22 @@
17
17
  ],
18
18
  "dependencies": {
19
19
  "@janelia-flyem/react-neuroglancer": "^2.5.0",
20
- "@material-ui/core": "~4.12.3",
21
- "@vitessce/neuroglancer-workers": "3.5.12",
22
- "@vitessce/constants-internal": "3.5.12",
23
- "@vitessce/vit-s": "3.5.12"
20
+ "lodash-es": "^4.17.21",
21
+ "@vitessce/neuroglancer-workers": "3.6.1",
22
+ "@vitessce/styles": "3.6.1",
23
+ "@vitessce/constants-internal": "3.6.1",
24
+ "@vitessce/vit-s": "3.6.1",
25
+ "@vitessce/sets-utils": "3.6.1",
26
+ "@vitessce/utils": "3.6.1",
27
+ "@vitessce/tooltip": "3.6.1"
24
28
  },
25
29
  "devDependencies": {
26
- "@testing-library/jest-dom": "^5.16.4",
27
- "@testing-library/react": "^13.3.0",
30
+ "@testing-library/jest-dom": "^6.6.3",
31
+ "@testing-library/react": "^16.3.0",
28
32
  "react": "^18.0.0",
29
- "vite": "^4.3.0",
30
- "vitest": "^0.32.2"
33
+ "react-dom": "^18.0.0",
34
+ "vite": "^6.3.5",
35
+ "vitest": "^3.1.4"
31
36
  },
32
37
  "scripts": {
33
38
  "bundle": "pnpm exec vite build -c ../../../scripts/vite.config.js",
@@ -1,49 +1,172 @@
1
- import React, { useCallback, useMemo, Suspense } from 'react';
1
+ /* eslint-disable react-refresh/only-export-components */
2
+ import React, { PureComponent, Suspense } from 'react';
2
3
  import { ChunkWorker } from '@vitessce/neuroglancer-workers';
3
- import { useStyles, globalNeuroglancerCss } from './styles.js';
4
+ import { isEqualWith, pick } from 'lodash-es';
5
+ import { NeuroglancerGlobalStyles } from './styles.js';
4
6
 
5
- // We lazy load the Neuroglancer component,
6
- // because the non-dynamic import causes problems for Vitest,
7
- // as the package appears contain be a mix of CommonJS and ESM syntax.
8
7
  const LazyReactNeuroglancer = React.lazy(async () => {
9
8
  const ReactNeuroglancer = await import('@janelia-flyem/react-neuroglancer');
10
9
  return ReactNeuroglancer;
11
10
  });
12
11
 
13
- // Reference: https://github.com/developit/jsdom-worker/issues/14#issuecomment-1268070123
14
12
  function createWorker() {
15
13
  return new ChunkWorker();
16
14
  }
17
15
 
18
- export function Neuroglancer(props) {
19
- const {
20
- viewerState,
21
- onViewerStateChanged,
22
- } = props;
23
- const classes = useStyles();
24
- const bundleRoot = useMemo(() => createWorker(), []);
25
-
26
- const handleStateChanged = useCallback((newState) => {
27
- if (JSON.stringify(newState) !== JSON.stringify(viewerState)) {
28
- if (onViewerStateChanged) {
29
- onViewerStateChanged(newState);
16
+ /**
17
+ * Is this a valid viewerState object?
18
+ * @param {object} viewerState
19
+ * @returns {boolean}
20
+ */
21
+ function isValidState(viewerState) {
22
+ const { projectionScale, projectionOrientation, position, dimensions } = viewerState || {};
23
+ return (
24
+ dimensions !== undefined
25
+ && typeof projectionScale === 'number'
26
+ && Array.isArray(projectionOrientation)
27
+ && projectionOrientation.length === 4
28
+ && Array.isArray(position)
29
+ && position.length === 3
30
+ );
31
+ }
32
+
33
+ // TODO: Do we want to use the same epsilon value
34
+ // for every viewstate property being compared?
35
+ const EPSILON = 1e-7;
36
+ const VIEWSTATE_KEYS = ['projectionScale', 'projectionOrientation', 'position'];
37
+
38
+ // Custom numeric comparison function
39
+ // for isEqualWith, to be able to set a custom epsilon.
40
+ function customizer(a, b) {
41
+ if (typeof a === 'number' && typeof b === 'number') {
42
+ // Returns true if the values are equivalent, else false.
43
+ return Math.abs(a - b) > EPSILON;
44
+ }
45
+ // Return undefined to fallback to the default
46
+ // comparison function.
47
+ return undefined;
48
+ }
49
+
50
+ /**
51
+ * Returns true if the two states are equal, or false if not.
52
+ * @param {object} prevState Previous viewer state.
53
+ * @param {object} nextState Next viewer state.
54
+ * @returns
55
+ */
56
+ function compareViewerState(prevState, nextState) {
57
+ if (isValidState(nextState)) {
58
+ // Subset the viewerState objects to only the keys
59
+ // that we want to use for comparison.
60
+ const prevSubset = pick(prevState, VIEWSTATE_KEYS);
61
+ const nextSubset = pick(nextState, VIEWSTATE_KEYS);
62
+ return isEqualWith(prevSubset, nextSubset, customizer);
63
+ }
64
+ return true;
65
+ }
66
+
67
+ export class Neuroglancer extends PureComponent {
68
+ constructor(props) {
69
+ super(props);
70
+
71
+ this.bundleRoot = createWorker();
72
+
73
+ this.viewerState = props.viewerState;
74
+ this.justReceivedExternalUpdate = false;
75
+
76
+ this.prevElement = null;
77
+ this.prevClickHandler = null;
78
+ this.prevMouseStateChanged = null;
79
+ this.prevHoverHandler = null;
80
+
81
+ this.onViewerStateChanged = this.onViewerStateChanged.bind(this);
82
+ this.onRef = this.onRef.bind(this);
83
+ }
84
+
85
+ onRef(viewerRef) {
86
+ // Here, we have access to the viewerRef.viewer object,
87
+ // which we can use to add/remove event handlers.
88
+ const {
89
+ onSegmentClick,
90
+ onSelectHoveredCoords,
91
+ } = this.props;
92
+
93
+ if (viewerRef) {
94
+ // Mount
95
+ const { viewer } = viewerRef;
96
+ this.prevElement = viewer.element;
97
+ this.prevMouseStateChanged = viewer.mouseState.changed;
98
+ this.prevClickHandler = (event) => {
99
+ if (event.button === 0) {
100
+ setTimeout(() => {
101
+ const { pickedValue } = viewer.mouseState;
102
+ if (pickedValue && pickedValue?.low) {
103
+ onSegmentClick(pickedValue?.low);
104
+ }
105
+ }, 100);
106
+ }
107
+ };
108
+ viewer.element.addEventListener('mousedown', this.prevClickHandler);
109
+
110
+ this.prevHoverHandler = () => {
111
+ if (viewer.mouseState.pickedValue !== undefined) {
112
+ const pickedSegment = viewer.mouseState.pickedValue;
113
+ onSelectHoveredCoords(pickedSegment?.low);
114
+ }
115
+ };
116
+
117
+ viewer.mouseState.changed.add(this.prevHoverHandler);
118
+ } else {
119
+ // Unmount (viewerRef is null)
120
+ if (this.prevElement && this.prevClickHandler) {
121
+ this.prevElement.removeEventListener('mousedown', this.prevClickHandler);
122
+ }
123
+ if (this.prevMouseStateChanged && this.prevHoverHandler) {
124
+ this.prevMouseStateChanged.remove(this.prevHoverHandler);
30
125
  }
31
126
  }
32
- }, [onViewerStateChanged, viewerState]);
127
+ }
33
128
 
34
- return (
35
- <>
36
- <style>{globalNeuroglancerCss}</style>
37
- <div className={classes.neuroglancerWrapper}>
38
- <Suspense fallback={<div>Loading...</div>}>
39
- <LazyReactNeuroglancer
40
- brainMapsClientId="NOT_A_VALID_ID"
41
- viewerState={viewerState}
42
- onViewerStateChanged={handleStateChanged}
43
- bundleRoot={bundleRoot}
44
- />
45
- </Suspense>
46
- </div>
47
- </>
48
- );
129
+ onViewerStateChanged(nextState) {
130
+ const { setViewerState } = this.props;
131
+ const { viewerState: prevState } = this;
132
+
133
+ if (!this.justReceivedExternalUpdate && !compareViewerState(prevState, nextState)) {
134
+ this.viewerState = nextState;
135
+ this.justReceivedExternalUpdate = false;
136
+ setViewerState(nextState);
137
+ }
138
+ }
139
+
140
+ UNSAFE_componentWillUpdate(prevProps) {
141
+ if (!compareViewerState(this.viewerState, prevProps.viewerState)) {
142
+ this.viewerState = prevProps.viewerState;
143
+ this.justReceivedExternalUpdate = true;
144
+ setTimeout(() => {
145
+ this.justReceivedExternalUpdate = false;
146
+ }, 100);
147
+ }
148
+ }
149
+
150
+ render() {
151
+ const {
152
+ classes,
153
+ } = this.props;
154
+
155
+ return (
156
+ <>
157
+ <NeuroglancerGlobalStyles classes={classes} />
158
+ <div className={classes.neuroglancerWrapper}>
159
+ <Suspense fallback={<div>Loading...</div>}>
160
+ <LazyReactNeuroglancer
161
+ brainMapsClientId="NOT_A_VALID_ID"
162
+ viewerState={this.viewerState}
163
+ onViewerStateChanged={this.onViewerStateChanged}
164
+ bundleRoot={this.bundleRoot}
165
+ ref={this.onRef}
166
+ />
167
+ </Suspense>
168
+ </div>
169
+ </>
170
+ );
171
+ }
49
172
  }
@@ -1,22 +1,211 @@
1
-
1
+ /* eslint-disable no-unused-vars */
2
+ import React, { useCallback, useMemo } from 'react';
2
3
  import {
3
4
  TitleInfo,
5
+ useCoordination,
6
+ useObsSetsData,
7
+ useLoaders,
8
+ useObsEmbeddingData,
4
9
  } from '@vitessce/vit-s';
5
-
6
- import { ViewHelpMapping } from '@vitessce/constants-internal';
10
+ import {
11
+ ViewHelpMapping,
12
+ ViewType,
13
+ COMPONENT_COORDINATION_TYPES,
14
+ } from '@vitessce/constants-internal';
15
+ import { mergeObsSets, getCellColors, setObsSelection } from '@vitessce/sets-utils';
7
16
  import { Neuroglancer } from './Neuroglancer.js';
17
+ import { useStyles } from './styles.js';
18
+
19
+ const NEUROGLANCER_ZOOM_BASIS = 16;
20
+
21
+ function mapVitessceToNeuroglancer(zoom) {
22
+ return NEUROGLANCER_ZOOM_BASIS * (2 ** -zoom);
23
+ }
24
+
25
+ function mapNeuroglancerToVitessce(projectionScale) {
26
+ return -Math.log2(projectionScale / NEUROGLANCER_ZOOM_BASIS);
27
+ }
28
+
29
+ function quaternionToEuler([x, y, z, w]) {
30
+ // X-axis rotation (Roll)
31
+ const thetaX = Math.atan2(2 * (w * x + y * z), 1 - 2 * (x * x + y * y));
32
+
33
+ // Y-axis rotation (Pitch)
34
+ const sinp = 2 * (w * y - z * x);
35
+ const thetaY = Math.abs(sinp) >= 1 ? Math.sign(sinp) * (Math.PI / 2) : Math.asin(sinp);
36
+
37
+ // Convert to degrees as Vitessce expects degrees?
38
+ return [thetaX * (180 / Math.PI), thetaY * (180 / Math.PI)];
39
+ }
40
+
41
+
42
+ function eulerToQuaternion(thetaX, thetaY) {
43
+ // Convert Euler angles (X, Y rotations) to quaternion
44
+ const halfThetaX = thetaX / 2;
45
+ const halfThetaY = thetaY / 2;
46
+
47
+ const sinX = Math.sin(halfThetaX);
48
+ const cosX = Math.cos(halfThetaX);
49
+ const sinY = Math.sin(halfThetaY);
50
+ const cosY = Math.cos(halfThetaY);
51
+
52
+ return [
53
+ sinX * cosY,
54
+ cosX * sinY,
55
+ sinX * sinY,
56
+ cosX * cosY,
57
+ ];
58
+ }
59
+
60
+ function normalizeQuaternion(q) {
61
+ const length = Math.sqrt((q[0] ** 2) + (q[1] ** 2) + (q[2] ** 2) + (q[3] ** 2));
62
+ return q.map(value => value / length);
63
+ }
8
64
 
9
65
  export function NeuroglancerSubscriber(props) {
10
66
  const {
67
+ coordinationScopes,
11
68
  closeButtonVisible,
12
69
  downloadButtonVisible,
13
70
  removeGridComponent,
14
71
  theme,
15
72
  title = 'Neuroglancer',
16
- viewerState: viewerStateInitial = null,
17
73
  helpText = ViewHelpMapping.NEUROGLANCER,
74
+ viewerState: initialViewerState,
18
75
  } = props;
19
76
 
77
+ const [{
78
+ dataset,
79
+ obsType,
80
+ spatialZoom,
81
+ spatialTargetX,
82
+ spatialTargetY,
83
+ spatialRotationX,
84
+ spatialRotationY,
85
+ // spatialRotationZ,
86
+ // spatialRotationOrbit,
87
+ // spatialOrbitAxis,
88
+ embeddingType: mapping,
89
+ obsSetSelection: cellSetSelection,
90
+ additionalObsSets: additionalCellSets,
91
+ obsSetColor: cellSetColor,
92
+ }, {
93
+ setAdditionalObsSets: setAdditionalCellSets,
94
+ setObsSetColor: setCellSetColor,
95
+ setObsColorEncoding: setCellColorEncoding,
96
+ setObsSetSelection: setCellSetSelection,
97
+ setObsHighlight: setCellHighlight,
98
+ setSpatialTargetX: setTargetX,
99
+ setSpatialTargetY: setTargetY,
100
+ setSpatialRotationX: setRotationX,
101
+ setSpatialRotationY: setRotationY,
102
+ // setSpatialRotationZ: setRotationZ,
103
+ // setSpatialRotationOrbit: setRotationOrbit,
104
+
105
+ setSpatialZoom: setZoom,
106
+ }] = useCoordination(COMPONENT_COORDINATION_TYPES[ViewType.NEUROGLANCER], coordinationScopes);
107
+
108
+ const { classes } = useStyles();
109
+ const loaders = useLoaders();
110
+
111
+ const [{ obsSets: cellSets }] = useObsSetsData(
112
+ loaders, dataset, false,
113
+ { setObsSetSelection: setCellSetSelection, setObsSetColor: setCellSetColor },
114
+ { cellSetSelection, obsSetColor: cellSetColor },
115
+ { obsType },
116
+ );
117
+
118
+ const [{ obsIndex }] = useObsEmbeddingData(
119
+ loaders, dataset, true, {}, {},
120
+ { obsType, embeddingType: mapping },
121
+ );
122
+
123
+ const handleStateUpdate = useCallback((newState) => {
124
+ const { projectionScale, projectionOrientation, position } = newState;
125
+ setZoom(mapNeuroglancerToVitessce(projectionScale));
126
+ const vitessceEularMapping = quaternionToEuler(projectionOrientation);
127
+
128
+ // TODO: support z rotation on SpatialView?
129
+ setRotationX(vitessceEularMapping[0]);
130
+ setRotationY(vitessceEularMapping[1]);
131
+
132
+ // Note: To pan in Neuroglancer, use shift+leftKey+drag
133
+ setTargetX(position[0]);
134
+ setTargetY(position[1]);
135
+ }, [setZoom, setTargetX, setTargetY, setRotationX, setRotationY]);
136
+
137
+ const onSegmentClick = useCallback((value) => {
138
+ if (value) {
139
+ const selectedCellIds = [String(value)];
140
+ setObsSelection(
141
+ selectedCellIds, additionalCellSets, cellSetColor,
142
+ setCellSetSelection, setAdditionalCellSets, setCellSetColor,
143
+ setCellColorEncoding,
144
+ 'Selection ',
145
+ `: based on selected segments ${value}`,
146
+ );
147
+ }
148
+ }, [additionalCellSets, cellSetColor, setAdditionalCellSets,
149
+ setCellColorEncoding, setCellSetColor, setCellSetSelection,
150
+ ]);
151
+
152
+ const mergedCellSets = useMemo(() => mergeObsSets(
153
+ cellSets, additionalCellSets,
154
+ ), [cellSets, additionalCellSets]);
155
+
156
+ const cellColors = useMemo(() => getCellColors({
157
+ cellSets: mergedCellSets,
158
+ cellSetSelection,
159
+ cellSetColor,
160
+ obsIndex,
161
+ theme,
162
+ }), [mergedCellSets, theme,
163
+ cellSetColor, cellSetSelection, obsIndex]);
164
+
165
+ const rgbToHex = useCallback(rgb => (typeof rgb === 'string' ? rgb
166
+ : `#${rgb.map(c => c.toString(16).padStart(2, '0')).join('')}`), []);
167
+
168
+ const cellColorMapping = useMemo(() => {
169
+ const colorCellMapping = {};
170
+ cellColors.forEach((color, cell) => {
171
+ colorCellMapping[cell] = rgbToHex(color);
172
+ });
173
+ return colorCellMapping;
174
+ }, [cellColors, rgbToHex]);
175
+
176
+ const derivedViewerState = useMemo(() => ({
177
+ ...initialViewerState,
178
+ layers: initialViewerState.layers.map((layer, index) => (index === 0
179
+ ? {
180
+ ...layer,
181
+ segments: Object.keys(cellColorMapping).map(String),
182
+ segmentColors: cellColorMapping,
183
+ }
184
+ : layer)),
185
+ }), [cellColorMapping, initialViewerState]);
186
+
187
+ const derivedViewerState2 = useMemo(() => {
188
+ if (typeof spatialZoom === 'number' && typeof spatialTargetX === 'number') {
189
+ const projectionScale = mapVitessceToNeuroglancer(spatialZoom);
190
+ const position = [spatialTargetX, spatialTargetY, derivedViewerState.position[2]];
191
+ const projectionOrientation = normalizeQuaternion(
192
+ eulerToQuaternion(spatialRotationX, spatialRotationY),
193
+ );
194
+ return {
195
+ ...derivedViewerState,
196
+ projectionScale,
197
+ position,
198
+ projectionOrientation,
199
+ };
200
+ }
201
+ return derivedViewerState;
202
+ }, [derivedViewerState, spatialZoom, spatialTargetX,
203
+ spatialTargetY, spatialRotationX, spatialRotationY]);
204
+
205
+ const onSegmentHighlight = useCallback((obsId) => {
206
+ setCellHighlight(String(obsId));
207
+ }, [obsIndex, setCellHighlight]);
208
+
20
209
  return (
21
210
  <TitleInfo
22
211
  title={title}
@@ -27,9 +216,15 @@ export function NeuroglancerSubscriber(props) {
27
216
  downloadButtonVisible={downloadButtonVisible}
28
217
  removeGridComponent={removeGridComponent}
29
218
  isReady
219
+ withPadding={false}
30
220
  >
31
- {viewerStateInitial && <Neuroglancer viewerState={viewerStateInitial} />}
221
+ <Neuroglancer
222
+ classes={classes}
223
+ onSegmentClick={onSegmentClick}
224
+ onSelectHoveredCoords={onSegmentHighlight}
225
+ viewerState={derivedViewerState2}
226
+ setViewerState={handleStateUpdate}
227
+ />
32
228
  </TitleInfo>
33
-
34
229
  );
35
230
  }