-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathdataviz.tsx
484 lines (452 loc) · 15.3 KB
/
dataviz.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
import React, { useState, useEffect, useRef } from 'react';
import { head, isNil, last, maxBy, minBy } from 'lodash';
import cx from 'classnames';
import { AdditionalDataItem } from 'common/IntervalsEditor/types';
import { preventDefault, getPositionFromMouseEvent } from './utils';
import {
cropForDatavizViewbox,
cropOperationPointsForDatavizViewbox,
getClosestOperationalPoint,
getHoveredItem,
} from './data';
import { ResizingScale, SimpleScale } from './Scales';
import IntervalItem from './IntervalItem';
import { IntervalItemBaseProps, LinearMetadataItem, OperationalPoint } from './types';
import './style.scss';
export interface LinearMetadataDatavizProps<T> extends IntervalItemBaseProps<T> {
/**
* Data to display on ranges below the main chart. The data must cover the whole path.
* Ex: display the catenary ranges to help the user selecting the correct power restrictions on path
*/
additionalData?: AdditionalDataItem[];
/**
* List of special points to display on the chart
*/
operationalPoints?: OperationalPoint[];
/**
* Part of the data which is visible
*/
viewBox: [number, number] | null;
/**
* Event when the user is dragging
*/
onDragX?: (gap: number, finalized: boolean) => void;
/**
* Event when mouse leaves data item
*/
onMouseLeave?: (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => void;
/**
* Event when the mouse move on a data item
*/
onMouseMove?: (
e: React.MouseEvent<HTMLDivElement, MouseEvent>,
item: LinearMetadataItem<T>,
index: number,
point: number // point on the linear metadata
) => void;
/**
* Event when the user is resizing an item
*/
onResize?: (index: number, gap: number, finalized: boolean) => void;
}
/**
* Component that displays a linear metadata of a line.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const LinearMetadataDataviz = <T extends { [key: string]: any }>({
additionalData,
creating = false,
data,
emptyValue = undefined,
field = 'value',
highlighted,
intervalType,
operationalPoints,
options = { resizingScale: false, fullHeightItem: false, showValues: false },
viewBox,
onClick,
onDoubleClick,
onMouseMove,
onMouseOver,
onMouseEnter,
onMouseLeave,
onWheel,
onDragX,
onResize,
onCreate,
}: LinearMetadataDatavizProps<T>) => {
// Html ref of the div wrapper
const wrapper = useRef<HTMLDivElement | null>(null);
// Need to compute the full length of the segment, to compute size in %
const [fullLength, setFullLength] = useState<number>(0);
// If the user is doing a drag'n'drop
const [draginStartAt, setDraginStartAt] = useState<number | null>(null);
// Store the data for the resizing:
const [resizing, setResizing] = useState<{
index: number | null;
startAt: number; // in px (on the screen)
startPosition: number; // in m
} | null>(null);
// min & max of the data value
const [min, setMin] = useState<number>(0);
const [max, setMax] = useState<number>(0);
// Computed data for the viz and the viewbox
const [data4viz, setData4viz] = useState<Array<LinearMetadataItem & { index: number }>>([]);
const [operationalPoints4viz, setOperationalPoints4viz] = useState<
Array<OperationalPoint & { positionInPx: number }>
>([]);
const [additionalData4viz, setAdditionalData4viz] = useState<AdditionalDataItem[]>([]);
const [hoverAtx, setHoverAtx] = useState<number | null>(null);
/**
* When data change (or the field)
* => we recompute the min/max
*/
useEffect(() => {
if (field) {
if (options.fullHeightItem) {
// we just need an arbitrary space for scaleY in that case
setMin(0);
setMax(1);
}
const dMin = minBy(data, field);
const dMax = maxBy(data, field);
setMin(dMin && dMin[field] < 0 ? dMin[field] : 0);
setMax(dMax && dMax[field] > 0 ? dMax[field] : 0);
} else {
setMin(0);
setMax(0);
}
}, [data, field]);
/**
* When data change
* => we recompute the data for the viz
* => we recompute the full length of the displayed data.
* => we recompute the additionalData4viz
* => we recompute the operationalPoints4viz
*/
useEffect(() => {
const nData = cropForDatavizViewbox(data, viewBox);
const nFullLength = (last(nData)?.end || 0) - (head(nData)?.begin || 0);
const croppedAdditionalData = cropForDatavizViewbox(
additionalData || [],
viewBox
) as LinearMetadataItem[] as AdditionalDataItem[];
const nOperationalPoints = cropOperationPointsForDatavizViewbox(
operationalPoints || [],
viewBox,
wrapper,
nFullLength
);
setData4viz(nData);
setFullLength(nFullLength);
setAdditionalData4viz(croppedAdditionalData);
setOperationalPoints4viz(nOperationalPoints);
}, [data, viewBox]);
/**
* When operationalPoints change
* => we recompute the operationalPoints4viz
*/
useEffect(() => {
if (fullLength > 0) {
const nOperationalPoints = cropOperationPointsForDatavizViewbox(
operationalPoints || [],
viewBox,
wrapper,
fullLength
);
setOperationalPoints4viz(nOperationalPoints);
}
}, [operationalPoints, fullLength]);
/**
* When the window is resized horizontally
* => we recompute the operationalPoints4viz
*/
useEffect(() => {
const debounceResize = () => {
let debounceTimeoutId;
clearTimeout(debounceTimeoutId);
debounceTimeoutId = setTimeout(() => {
const nOperationalPoints = cropOperationPointsForDatavizViewbox(
operationalPoints || [],
viewBox,
wrapper,
fullLength
);
setOperationalPoints4viz(nOperationalPoints);
}, 15);
};
window.addEventListener('resize', debounceResize);
return () => {
window.removeEventListener('resize', debounceResize);
};
}, [operationalPoints, viewBox, wrapper, fullLength]);
/**
* When additionalData change
* => we recompute the additionalData4viz
*/
useEffect(() => {
if (fullLength > 0 && additionalData && additionalData.length > 0) {
const croppedAdditionalData = cropForDatavizViewbox(
additionalData,
viewBox
) as LinearMetadataItem[] as AdditionalDataItem[];
setAdditionalData4viz(croppedAdditionalData);
}
}, [additionalData, fullLength]);
/**
* When the wrapper div change
* => we listen event on it to catch the wheel event and prevent the scroll
* => we listen for resize to compute its width (used in the drag'n'drop)
* NOTE: the prevent default directly on the event doesn't work, that's why we need
* to register it on the ref (@see https://github.com/facebook/react/issues/5845)
*/
useEffect(() => {
const element = wrapper.current;
if (element) element.addEventListener('wheel', preventDefault);
return () => {
if (element) element.removeEventListener('wheel', preventDefault);
};
}, [wrapper]);
/**
* When start to drag
* => register event on document for the mouseUp & mousemove
*/
useEffect(() => {
let fnUp: ((e: MouseEvent) => void) | undefined;
let fnMove: ((e: MouseEvent) => void) | undefined;
if (onDragX && draginStartAt && wrapper.current) {
const wrapperWidth = wrapper.current.offsetWidth;
// function for key up
fnUp = (e) => {
const delta = ((draginStartAt - e.clientX) / wrapperWidth) * fullLength;
onDragX(delta, true);
setDraginStartAt(null);
};
// function for move
fnMove = (e) => {
const delta = ((draginStartAt - e.clientX) / wrapperWidth) * fullLength;
onDragX(delta, false);
setDraginStartAt(e.clientX);
};
document.addEventListener('mouseup', fnUp, true);
document.addEventListener('mousemove', fnMove, true);
}
// cleanup
return () => {
if (fnUp && fnMove) {
document.removeEventListener('mouseup', fnUp, true);
document.removeEventListener('mousemove', fnMove, true);
}
};
}, [draginStartAt, onDragX, wrapper, fullLength]);
/**
* When resize starts
* => register event on document for the mouseUp
*/
useEffect(() => {
let fnUp: ((e: MouseEvent) => void) | undefined;
let fnMove: ((e: MouseEvent) => void) | undefined;
if (onResize && wrapper.current && resizing) {
const wrapperWidth = wrapper.current.offsetWidth;
const leftPadding = wrapper.current.getBoundingClientRect().x;
// function to compute delta (check for snapping to an operational point)
const computeDelta = (positionX: number) => {
const closestPoint = getClosestOperationalPoint(
positionX - leftPadding,
operationalPoints4viz
);
return closestPoint
? closestPoint.position - resizing.startPosition
: Math.round(((positionX - resizing.startAt) / wrapperWidth) * fullLength);
};
// function for key up
fnUp = (e) => {
const delta = computeDelta(e.clientX);
setResizing(null);
if (resizing.index !== null) onResize(resizing.index, delta, true);
};
// function for move
fnMove = (e) => {
const delta = computeDelta(e.clientX);
if (resizing.index !== null) onResize(resizing.index, delta, false);
};
document.addEventListener('mouseup', fnUp, true);
document.addEventListener('mousemove', fnMove, true);
}
// cleanup
return () => {
if (fnUp && fnMove) {
document.removeEventListener('mouseup', fnUp, true);
document.removeEventListener('mousemove', fnMove, true);
}
};
}, [resizing, onResize, wrapper, fullLength]);
return (
<div className={cx('linear-metadata-visualisation')}>
<div
className={cx(
'data',
viewBox !== null && draginStartAt && 'dragging',
resizing && 'resizing',
(viewBox === null || viewBox[0] === 0) && 'start-visible',
(viewBox === null || viewBox[1] === last(data)?.end) && 'end-visible'
)}
style={{ height: '30px' }}
>
{/* Display the operational points */}
{operationalPoints4viz.map((operationalPoint, index) => (
<div
key={`op-${operationalPoint.id || index}`}
className="operational-point"
style={{
position: 'absolute',
height: '50px',
left: `${operationalPoint.positionInPx}px`,
borderLeft: '2px dashed #a0a0a0',
}}
>
{operationalPoint.name && <p>{operationalPoint.name}</p>}
</div>
))}
</div>
<div
id="linear-metadata-dataviz-content"
ref={wrapper}
role="presentation"
onMouseLeave={(e) => {
setHoverAtx(null);
if (onMouseLeave) onMouseLeave(e);
}}
onMouseMove={(e) => {
const wrapperObject = wrapper.current;
// display vertical bar when hover element
setHoverAtx(e.clientX - (wrapperObject ? wrapperObject.getBoundingClientRect().x : 0));
if (!draginStartAt && onMouseMove && wrapperObject) {
const point = getPositionFromMouseEvent(e, fullLength, wrapperObject);
const result = getHoveredItem(data, e.clientX);
if (result) {
const { hoveredItem, hoveredItemIndex } = result;
onMouseMove(e, hoveredItem, hoveredItemIndex, point);
}
}
}}
className={cx(
'data',
highlighted.length > 0 && 'has-highlight',
viewBox !== null && draginStartAt && 'dragging',
resizing && 'resizing',
(viewBox === null || viewBox[0] === 0) && 'start-visible',
(viewBox === null || viewBox[1] === last(data)?.end) && 'end-visible'
)}
>
{/* Display the Y axis if there is one */}
{field && min !== max && !options.fullHeightItem && (
<SimpleScale className="scale-y" begin={min} end={max} />
)}
{!isNil(hoverAtx) && !draginStartAt && (
<div
className="hover-x"
style={{
borderLeft: '2px dotted',
height: '100%',
left: `${hoverAtx}px`,
pointerEvents: 'none',
position: 'absolute',
zIndex: 3,
}}
/>
)}
{/* Display the operational points */}
{operationalPoints4viz.map((operationalPoint) => (
<div
key={`op-${operationalPoint.id}`}
className="operational-point"
style={{
position: 'absolute',
height: '100%',
left: `${operationalPoint.positionInPx}px`,
borderLeft: '2px dashed #a0a0a0',
}}
/>
))}
{/* Create one div per item for the X axis */}
{data4viz.map((segment) => (
<IntervalItem
creating={creating}
data={data}
dragingStartAt={draginStartAt}
emptyValue={emptyValue}
field={field}
fullLength={fullLength}
highlighted={highlighted}
intervalType={intervalType}
key={`${segment.index}-${segment.begin}-${segment.end}-${fullLength}`}
min={min}
max={max}
onClick={onClick}
onCreate={onCreate}
onDoubleClick={onDoubleClick}
onMouseOver={onMouseOver}
onMouseEnter={onMouseEnter}
onWheel={onWheel}
options={options}
resizing={resizing}
segment={segment}
setDraginStartAt={setDraginStartAt}
setResizing={setResizing}
/>
))}
</div>
{/* Display the additionalData */}
{additionalData4viz.length > 0 && (
<>
<div
className={cx(
'spacer',
(viewBox === null || viewBox[0] === 0) && 'start-visible',
(viewBox === null || viewBox[1] === last(data)?.end) && 'end-visible'
)}
/>
<div
className={cx(
'additional-data',
(viewBox === null || viewBox[0] === 0) && 'start-visible',
(viewBox === null || viewBox[1] === last(data)?.end) && 'end-visible'
)}
>
{additionalData4viz.map((item, index) => (
<div
className="item"
key={`${item.begin}-${item.end}-${item.value}`}
style={{
width: `${((item.end - item.begin) / fullLength) * 100}%`,
}}
>
<div className={cx('value', item.value === '' && 'no-data')}>
<span>{item.value}</span>
</div>
{index !== additionalData4viz.length - 1 && <div className="resize" />}
</div>
))}
</div>
</>
)}
{/* Display the X axis */}
{options.resizingScale && wrapper.current ? (
<ResizingScale
begin={head(data4viz)?.begin || 0}
end={last(data4viz)?.end || 0}
wrapper={wrapper.current}
/>
) : (
<SimpleScale
className="scale-x"
begin={head(data4viz)?.begin || 0}
end={last(data4viz)?.end || 0}
min={head(data)?.begin || 0}
max={last(data)?.end || 0}
/>
)}
</div>
);
};