/
LegendOld.js
610 lines (548 loc) · 19.6 KB
/
LegendOld.js
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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
import React from 'react';
import PropTypes from 'prop-types';
import { SortableContainer, SortableElement, SortableHandle, arrayMove } from 'react-sortable-hoc';
import isEqual from 'lodash/isEqual';
import throttle from 'lodash/throttle';
import sortBy from 'lodash/sortBy';
import { Router } from 'routes';
import moment from 'moment';
import InputRange from 'react-input-range';
// Redux
import { connect } from 'react-redux';
import { toggleModal } from 'redactions/modal';
import { toggleTooltip, setTooltipPosition } from 'redactions/tooltip';
import { setLayerGroupOpacity } from 'redactions/explore';
// Components
import LegendType from 'components/ui/LegendType';
import Icon from 'components/ui/Icon';
import LayerInfoModal from 'components/modal/LayerInfoModal';
import LayersTooltip from 'components/app/explore/LayersTooltip';
import SliderTooltip from 'components/app/explore/SliderTooltip';
import Button from 'components/ui/Button';
const TIMELINE_INTERVAL_TIMER = 3000;
const SortableItem = SortableElement(({ value }) => value);
const DragHandle = SortableHandle(() => (
<span className="handler">
<Icon name="icon-drag-dots" className="-small" />
</span>
));
const SortableList = SortableContainer(({ items }) => (
<ul className="legend-list">
{items.map((value, index) =>
<SortableItem key={value.key} index={index} value={value} />
)}
</ul>
));
class Legend extends React.PureComponent {
/**
* Return the position of a DOM element
* @static
* @param {HTMLElement} node
* @returns {{ x: number, y: number }}
*/
static getElementPosition(node) {
const clientRect = node.getBoundingClientRect();
return {
x: window.scrollX + clientRect.left + (clientRect.width / 2),
y: window.scrollY + clientRect.top + (clientRect.height / 2)
};
}
constructor(props) {
super(props);
this.state = {
open: props.expanded,
layersTooltipOpen: false,
layersTourTooltipOpen: false,
opacityTooltipOpen: false,
opacityOptions: {},
// Show a "tour" tooltip if the user adds a multi-layer
// layer group for the first time
hasShownLayersTourTooltip: false,
currentStepTimeline: null,
isTimelinePlaying: false
};
// List of the layers buttons
this.layersButtons = [];
// BINDINGS
this.onSortEnd = this.onSortEnd.bind(this);
this.onScrollLegend = throttle(this.onScrollLegend.bind(this), 30);
}
componentDidMount() {
// Show the layers tour tooltip
if (!this.state.hasShownLayersTourTooltip && this.state.open) {
this.showLayersTourTooltip();
}
}
componentWillReceiveProps(nextProps) {
if (nextProps.tooltipOpened === undefined && this.state.opacityTooltipOpen
&& this.state.opacityOptions.target) {
const layerGroup = nextProps.layerGroups
.find(lg => lg.dataset === this.state.opacityOptions.dataset);
if (layerGroup) {
this.onClickOpacity({ target: this.state.opacityOptions.target }, layerGroup);
}
}
}
componentDidUpdate(previousProps, previousState) {
const haveLayerGroupsChanged = !isEqual(this.props.layerGroups, previousProps.layerGroups);
// If the layers tooltip is opened and the layer groups changed in
// some way, then the height of the legend might change and we need
// to reposition the tooltip
if (this.state.layersTooltipOpen
&& this.activeLayersButton
&& haveLayerGroupsChanged) {
this.props.setTooltipPosition(Legend.getElementPosition(this.activeLayersButton));
}
// Show the layers tour tooltip
if ((haveLayerGroupsChanged || this.state.open !== previousState.open)
&& !this.state.hasShownLayersTourTooltip) {
if (this.state.open) this.showLayersTourTooltip();
}
}
/**
* Event handler executed when the user starts dragging
* a layer group
*/
onSortStart() {
// If the layers tour tooltip is opened, then we close it
if (this.state.layersTourTooltipOpen) {
this.closeLayersTourTooltip();
}
}
/**
* Event handler executed when the user drops the layer group
* they were dragging
* @param {any} { oldIndex, newIndex }
*/
onSortEnd({ oldIndex, newIndex }) {
const layers = [...this.props.layerGroups];
const datasets = arrayMove(layers, oldIndex, newIndex)
.map(l => l.dataset);
this.props.setLayerGroupsOrder(datasets);
}
/**
* Event handler executed when the user clicks the button
* to toggle the visibility of a layer
* @param {object} layer
*/
onToggleLayerGroupVisibility(layerGroup) {
this.props.toggleLayerGroupVisibility(layerGroup);
}
/**
* Event handler executed when the user clicks the button
* to remove a layer group from the map
* @param {LayerGroup} layerGroup
*/
onRemoveLayerGroup(layerGroup) {
this.setState({ currentStepTimeline: null, isTimelinePlaying: false });
this.props.removeLayerGroup(layerGroup);
}
/**
* Event handler executed when the user clicks the info
* button of a layer group
* @param {LayerGroup} layerGroup
*/
onLayerInfoModal(layerGroup) {
const activeLayer = layerGroup.layers.find(l => l.active);
this.props.toggleModal(true, {
children: LayerInfoModal,
childrenProps: {
data: activeLayer
}
});
}
/**
* Event handler executed when the user moves the opacity slider
* @param {Value} value
* @param {LayerGroup} layerGroup
*/
onChangeOpacity(value, layerGroup) {
const updateUrl = Router.route === '/app/Explore';
this.props.setLayerGroupOpacity(layerGroup.dataset, value, updateUrl);
}
/**
* Event handler executed when the user clicks the button
* to change the opacity of a layer
* @param {MouseEvent} e
* @param {LayerGroup} layerGroup
*/
onClickOpacity(e, layerGroup) { // eslint-disable-line class-methods-use-this
const opacity = layerGroup.layers.length && layerGroup.layers[0].opacity !== undefined ?
layerGroup.layers[0].opacity : 1;
// If the user is opening the tooltip to select a layer
// then the tour doesn't make any sense anymore
this.closeLayersTourTooltip();
// We save the button that was used to open the tooltip
// so we can compute its position later
this.opacityButton = e.target;
if (!this.state.opacityTooltipOpen) {
this.setState({
opacityTooltipOpen: true,
opacityOptions: { target: this.opacityButton, dataset: layerGroup.dataset },
layersTooltipOpen: false
});
}
this.props.toggleTooltip(true, {
follow: false,
position: Legend.getElementPosition(this.opacityButton),
children: SliderTooltip,
childrenProps: {
className: '',
options: {
min: 0, max: 1, step: 0.01, defaultValue: opacity
},
onChange: value => this.onChangeOpacity(value, layerGroup),
onClose: () => {
this.setState({ opacityTooltipOpen: false, opacityOptions: {} });
this.props.toggleTooltip(false);
}
}
});
}
/**
* Event handler executed when the user clicks the button
* to switch the layer for another one of the same dataset
* @param {MouseEvent} e
* @param {LayerGroup} layerGroup
*/
onClickLayers(e, layerGroup) {
this.setState({ layersTooltipOpen: true });
// If the user is opening the tooltip to select a layer
// then the tour doesn't make any sense anymore
this.closeLayersTourTooltip();
// We save the button that was used to open the tooltip
// so we can compute its position later
this.activeLayersButton = e.target;
this.props.toggleTooltip(true, {
follow: false,
position: Legend.getElementPosition(this.activeLayersButton),
children: LayersTooltip,
childrenProps: {
layerGroup,
onChangeLayer: this.props.setLayerGroupActiveLayer,
onClose: () => {
this.setState({ layersTooltipOpen: false });
this.props.toggleTooltip(false);
}
}
});
}
/**
* Event handler executed when the user scrolls in the legend
*/
onScrollLegend() {
// If the user scrolls in the legend, we close the tooltip
// to avoid having it pointing to anything that is not the
// layers button
if (!this.state.hasShownLayersTourTooltip && this.state.layersTourTooltipOpen) {
this.closeLayersTourTooltip();
}
// The same happens with the layers tooltip
if (this.state.layersTooltipOpen) {
this.props.toggleTooltip(false);
this.setState({ layersTooltipOpen: false });
}
}
onTimelineChange(currentValue = 0, datasetSpec) {
const currentLayer = datasetSpec.layers.find((l) => {
return moment(l.layerConfig.dateTime, 'YYYY-MM-DD').year() === parseInt(currentValue);
});
this.setState({ currentStepTimeline: currentValue });
this.props.setLayerGroupActiveLayer(datasetSpec.dataset, currentLayer.id); // datasetId, layerId
}
/**
* Return the action buttons associated to a
* layer group
* @param {LayerGroup} layerGroup
* @returns {HTMLElement}
*/
getItemsActions(layerGroup) {
const {
showLayersButton,
interactionDisabled,
readonly
} = this.props;
return (
<div className="item-actions">
{ layerGroup.layers.length > 1 && showLayersButton && (
<button
type="button"
className="layers"
onClick={e => this.onClickLayers(e, layerGroup)}
aria-label="Select other layer"
ref={(node) => { if (node) this.layersButtons.push(node); }}
>
<Icon name="icon-layers" />
</button>
) }
{ !interactionDisabled
&&
<button
type="button"
className={`opacity ${layerGroup.visible ? '' : '-disabled'}`}
onClick={e => this.onClickOpacity(e, layerGroup)}
disabled={!layerGroup.visible}
aria-label="Change opacity"
>
<Icon name="icon-opacity" />
</button>
}
{ !interactionDisabled
&& <button
type="button"
className="toggle"
onClick={() => this.onToggleLayerGroupVisibility(layerGroup)}
aria-label="Toggle the visibility"
>
<Icon name={layerGroup.visible ? 'icon-hide' : 'icon-show'} />
</button>
}
{ !interactionDisabled
&& <button type="button" className="info" onClick={() => this.onLayerInfoModal(layerGroup)} aria-label="More information">
<Icon name="icon-info" />
</button>
}
{ !readonly
&& !interactionDisabled
&& <button type="button" className="close" onClick={() => this.onRemoveLayerGroup(layerGroup)} aria-label="Remove">
<Icon name="icon-cross" />
</button>
}
</div>
);
}
setPlayTimeline(isPlaying, datasetSpec, firstLayer, lastLayer) {
if (this.timer) clearInterval(this.timer);
if (isPlaying) {
this.timer = setInterval(() => {
if (this.state.currentStepTimeline === lastLayer.layerConfig.order) {
clearInterval(this.timer);
return this.setState({ currentStepTimeline: null, isTimelinePlaying: false });
}
const currentValue = (this.state.currentStepTimeline || firstLayer.layerConfig.order);
const currentLayer = datasetSpec.layers.find(l => l.layerConfig.order === currentValue);
requestAnimationFrame(() => {
this.props.setLayerGroupActiveLayer(datasetSpec.dataset, currentLayer.id);
});
const sortedIimelineLayers = sortBy(datasetSpec.layers
.filter(l => l.layerConfig.timeline), l => l.layerConfig.order);
const index = sortedIimelineLayers.findIndex(e => e.layerConfig.order === currentValue);
const newCurrentStepTimeLine = sortedIimelineLayers[index + 1].layerConfig.order;
return this.setState({ currentStepTimeline: newCurrentStepTimeLine });
}, TIMELINE_INTERVAL_TIMER, true);
}
this.setState({ isTimelinePlaying: isPlaying });
}
/**
* Return the list of layers
* @returns {HTMLElement[]}
*/
getLegendItems() {
// We reset the buttons each time we render the legend again
this.layersButtons = [];
return this.props.layerGroups.map((layerGroup) => {
const datasetSpec = Object.assign({}, layerGroup);
const activeLayer = datasetSpec.layers.find(l => l.active);
const timelineLayers = datasetSpec.layers.filter(l => l.layerConfig.timeline);
// Legend with timeline
if (timelineLayers.length > 0) {
const sortedIimelineLayers = sortBy(timelineLayers, l => l.layerConfig.order);
const firstLayer = sortedIimelineLayers[0];
const lastLayer = sortedIimelineLayers[sortedIimelineLayers.length - 1];
const currentLayer = timelineLayers
.find(l => l.layerConfig.order ===
(this.state.currentStepTimeline || firstLayer.layerConfig.order));
return (
<li key={datasetSpec.dataset} className="c-legend-unit">
<div className="legend-info">
<header className="legend-item-header">
<h3 className={this.props.className.color}>
<span className="name">{currentLayer.name}</span>
</h3>
{this.getItemsActions(datasetSpec)}
</header>
<LegendType config={currentLayer.legendConfig} className={this.props.className} />
{/* Timeline */}
<div className="legend-timeline">
{ this.state.isTimelinePlaying &&
<button
type="button"
onClick={() => {
this.setPlayTimeline(false, datasetSpec, firstLayer, lastLayer);
}}
>
<Icon name="icon-stop2" className="-small" />
</button> }
{ !this.state.isTimelinePlaying &&
<button
type="button"
onClick={() => {
this.setPlayTimeline(true, datasetSpec, firstLayer, lastLayer);
}}
>
<Icon name="icon-play3" className="-small" />
</button> }
{ !!(datasetSpec.layers.length) &&
<InputRange
minValue={firstLayer.layerConfig.order}
maxValue={lastLayer.layerConfig.order}
formatLabel={(value) => {
const layerValue = timelineLayers.find(l => l.layerConfig.order === value);
return layerValue.layerConfig.timelineLabel;
}}
value={this.state.currentStepTimeline || firstLayer.layerConfig.order}
onChange={(value) => { this.onTimelineChange(value, datasetSpec); }}
/> }
</div>
</div>
<DragHandle />
</li>
);
}
// Legend without timeline
return (
<li key={layerGroup.dataset} className="c-legend-unit">
<div className="legend-info">
<header className="legend-item-header">
<h3 className={this.props.className.color}>
<span className="name">{activeLayer.name}</span>
</h3>
{this.getItemsActions(layerGroup)}
</header>
<LegendType config={activeLayer.legendConfig} className={this.props.className} />
</div>
<DragHandle />
</li>
);
});
}
/**
* Show the layers tour tooltip on the first layer group
* that has several layers
*/
showLayersTourTooltip() {
const multiLayerLayerGroupIndex = this.props.layerGroups.findIndex(l => l.layers.length > 1);
if (multiLayerLayerGroupIndex === -1) {
// If there's no multi-layer layer group and the tooltip
// is shown, we remove it
if (this.state.layersTourTooltipOpen) this.closeLayersTourTooltip();
return;
}
const button = this.layersButtons[multiLayerLayerGroupIndex];
if (!button) return;
this.setState({ layersTourTooltipOpen: true });
this.props.toggleTooltip(true, {
follow: false,
position: Legend.getElementPosition(this.layersButtons[multiLayerLayerGroupIndex]),
children: props => (
<div>
This dataset has {props.layersCount} layers
<div style={{ textAlign: 'center', marginTop: '5px' }}>
<Button
properties={{ className: '-tertiary' }}
onClick={() => this.closeLayersTourTooltip()}
>
Ok
</Button>
</div>
</div>
),
childrenProps: {
layersCount: this.props.layerGroups.find(l => l.layers.length > 1).layers.length
}
});
}
/**
* Hide the layers tour tooltip
*/
closeLayersTourTooltip() {
this.setState({
layersTourTooltipOpen: false,
hasShownLayersTourTooltip: true
});
this.props.toggleTooltip(false);
}
render() {
// We reset the list of button each time we render
// the component again
this.layersButtons = [];
return (
<div className="c-legend-map">
<div className={`open-legend ${this.state.open ? '-active' : ''}`} onScroll={this.onScrollLegend}>
<button type="button" className="toggle-legend" onClick={() => this.setState({ open: false })}>
<Icon name="icon-arrow-down" className="-small" />
</button>
<SortableList
items={this.getLegendItems()}
helperClass="c-legend-unit -sort"
onSortStart={() => this.onSortStart()}
onSortEnd={this.onSortEnd}
axis="y"
lockAxis="y"
lockToContainerEdges
lockOffset="50%"
useDragHandle
/>
</div>
<div className={`close-legend ${!this.state.open ? '-active' : ''}`}>
<h1 className="legend-title">
Legend
<button type="button" className="toggle-legend" onClick={() => this.setState({ open: true })}>
<Icon name="icon-arrow-up" className="-small" />
</button>
</h1>
</div>
</div>
);
}
}
Legend.propTypes = {
className: PropTypes.object,
// List of LayerGroup items
layerGroups: PropTypes.array,
// Layers can't be removed or hidden
readonly: PropTypes.bool,
// Layers can't be removed, hidden or toggled
// and the information button is hidden
interactionDisabled: PropTypes.bool,
// Whether by default the legend is expanded or not
expanded: PropTypes.bool,
// Tooltip open state
tooltipOpened: PropTypes.bool,
// Show layers button or not
showLayersButton: PropTypes.bool,
// Functions
// Callback to hide/show a layer group
toggleLayerGroupVisibility: PropTypes.func.isRequired,
// Callback to re-order the layer groups
setLayerGroupsOrder: PropTypes.func.isRequired,
// Callback to remove a layer group
removeLayerGroup: PropTypes.func,
// Callback to change which layer of the layer group is active
setLayerGroupActiveLayer: PropTypes.func.isRequired,
// Set layers opacity
setLayerGroupOpacity: PropTypes.func,
// Redux
// Toggle the modal
toggleModal: PropTypes.func.isRequired,
// Toggle the tooltip
toggleTooltip: PropTypes.func.isRequired,
// Set the position of the tooltip
setTooltipPosition: PropTypes.func.isRequired
};
Legend.defaultProps = {
readonly: false,
interactionDisabled: false,
expanded: true,
showLayersButton: true
};
const mapStateToProps = state => ({
tooltipOpened: state.tooltip.opened
});
const mapDispatchToProps = {
toggleModal,
toggleTooltip,
setTooltipPosition,
setLayerGroupOpacity
};
export default connect(mapStateToProps, mapDispatchToProps)(Legend);