-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
vis-state-updaters.ts
2959 lines (2642 loc) · 78.9 KB
/
vis-state-updaters.ts
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
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2023 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import {console as Console} from 'global/window';
import {disableStackCapturing, withTask} from 'react-palm/tasks';
import cloneDeep from 'lodash.clonedeep';
import uniq from 'lodash.uniq';
import get from 'lodash.get';
import xor from 'lodash.xor';
import pick from 'lodash.pick';
import isEqual from 'lodash.isequal';
import copy from 'copy-to-clipboard';
import deepmerge from 'deepmerge';
// Tasks
import {LOAD_FILE_TASK, UNWRAP_TASK, PROCESS_FILE_DATA, DELAY_TASK} from '@kepler.gl/tasks';
// Actions
import {
applyLayerConfig,
layerConfigChange,
layerTypeChange,
layerVisConfigChange,
layerVisualChannelConfigChange,
loadFilesErr,
loadFilesSuccess,
loadFileStepSuccess,
loadNextFile,
nextFileBatch,
ReceiveMapConfigPayload,
VisStateActions,
MapStateActions,
processFileContent,
ActionTypes
} from '@kepler.gl/actions';
// Utils
import {
set,
toArray,
arrayInsert,
generateHashId,
isPlainObject,
isObject,
addNewLayersToSplitMap,
computeSplitMapLayers,
removeLayerFromSplitMaps,
isRgbColor,
parseFieldValue,
applyFilterFieldName,
applyFiltersToDatasets,
featureToFilterValue,
filterDatasetCPU,
FILTER_UPDATER_PROPS,
generatePolygonFilter,
getDefaultFilter,
getFilterIdInFeature,
getTimeWidgetTitleFormatter,
isInRange,
LIMITED_FILTER_EFFECT_PROPS,
updateFilterDataId,
getFilterPlot,
getDefaultFilterPlotType
} from '@kepler.gl/utils';
// Mergers
import {
VIS_STATE_MERGERS,
validateLayerWithData,
createLayerFromConfig,
serializeLayer,
serializeVisState,
parseLayerConfig
} from './vis-state-merger';
import {mergeStateFromMergers, isValidMerger} from './merger-handler';
import {Layer, LayerClasses, LAYER_ID_LENGTH} from '@kepler.gl/layers';
import {
EDITOR_MODES,
SORT_ORDER,
FILTER_TYPES,
FILTER_VIEW_TYPES,
MAX_DEFAULT_TOOLTIPS,
DEFAULT_TEXT_LABEL,
COMPARE_TYPES
} from '@kepler.gl/constants';
import {
pick_,
merge_,
swap_,
apply_,
compose_,
removeElementAtIndex,
filterOutById
} from './composer-helpers';
import KeplerGLSchema, {VisState, Merger, PostMergerPayload} from '@kepler.gl/schemas';
import {Filter, InteractionConfig, AnimationConfig, Editor, Field} from '@kepler.gl/types';
import {Loader} from '@loaders.gl/loader-utils';
import {calculateLayerData, findDefaultLayer, getLayerOrderFromLayers} from './layer-utils';
import {
copyTableAndUpdate,
Datasets,
pinTableColumns,
sortDatasetByColumn,
assignGpuChannel,
setFilterGpuMode,
createNewDataEntry
} from '@kepler.gl/table';
import {findFieldsToShow} from './interaction-utils';
import {hasPropsToMerge, getPropValueToMerger} from './merger-handler';
import {mergeDatasetsByOrder} from './vis-state-merger';
// react-palm
// disable capture exception for react-palm call to withTask
disableStackCapturing();
/**
* Updaters for `visState` reducer. Can be used in your root reducer to directly modify kepler.gl's state.
* Read more about [Using updaters](../advanced-usage/using-updaters.md)
*
* @public
* @example
*
* import keplerGlReducer, {visStateUpdaters} from 'kepler.gl/reducers';
* // Root Reducer
* const reducers = combineReducers({
* keplerGl: keplerGlReducer,
* app: appReducer
* });
*
* const composedReducer = (state, action) => {
* switch (action.type) {
* case 'CLICK_BUTTON':
* return {
* ...state,
* keplerGl: {
* ...state.keplerGl,
* foo: {
* ...state.keplerGl.foo,
* visState: visStateUpdaters.enlargeFilterUpdater(
* state.keplerGl.foo.visState,
* {idx: 0}
* )
* }
* }
* };
* }
* return reducers(state, action);
* };
*
* export default composedReducer;
*/
/* eslint-disable no-unused-vars */
// @ts-ignore
const visStateUpdaters = null;
/* eslint-enable no-unused-vars */
export const defaultInteractionConfig: InteractionConfig = {
tooltip: {
id: 'tooltip',
label: 'interactions.tooltip',
enabled: true,
config: {
fieldsToShow: {},
compareMode: false,
compareType: COMPARE_TYPES.ABSOLUTE
}
},
geocoder: {
id: 'geocoder',
label: 'interactions.geocoder',
enabled: false,
position: null
},
brush: {
id: 'brush',
label: 'interactions.brush',
enabled: false,
config: {
// size is in km
size: 0.5
}
},
coordinate: {
id: 'coordinate',
label: 'interactions.coordinate',
enabled: false,
position: null
}
};
export const DEFAULT_ANIMATION_CONFIG: AnimationConfig = {
domain: null,
currentTime: null,
speed: 1,
isAnimating: false,
timeFormat: null,
timezone: null,
defaultTimeFormat: null,
hideControl: false,
duration: null
};
export const DEFAULT_EDITOR: Editor = {
mode: EDITOR_MODES.DRAW_POLYGON,
features: [],
selectedFeature: null,
visible: true
};
/**
* Default initial `visState`
* @memberof visStateUpdaters
* @constant
* @public
*/
export const INITIAL_VIS_STATE: VisState = {
// map info
mapInfo: {
title: '',
description: ''
},
// layers
layers: [],
layerData: [],
layerToBeMerged: [],
layerOrder: [],
// filters
filters: [],
filterToBeMerged: [],
// a collection of multiple dataset
datasets: {},
editingDataset: undefined,
interactionConfig: defaultInteractionConfig,
interactionToBeMerged: {},
layerBlending: 'normal',
overlayBlending: 'normal',
hoverInfo: undefined,
clicked: undefined,
mousePos: {},
maxDefaultTooltips: MAX_DEFAULT_TOOLTIPS,
// this is used when user split maps
splitMaps: [
// this will contain a list of objects to
// describe the state of layer availability and visibility for each map
// [
// {
// layers: {layer_id: true | false}
// }
// ]
],
splitMapsToBeMerged: [],
isMergingDatasets: {},
// defaults layer classes
layerClasses: LayerClasses,
// default animation
// time in unix timestamp (milliseconds) (the number of seconds since the Unix Epoch)
animationConfig: DEFAULT_ANIMATION_CONFIG,
editor: DEFAULT_EDITOR,
fileLoading: false,
fileLoadingProgress: {},
loaders: [],
loadOptions: {},
// visStateMergers
mergers: VIS_STATE_MERGERS,
// kepler schemas
schema: KeplerGLSchema
};
type UpdateStateWithLayerAndDataType = {
layers: Layer[];
layerData: any[];
};
/**
* Update state with updated layer and layerData
*
*/
export function updateStateWithLayerAndData<S extends UpdateStateWithLayerAndDataType>(
state: S,
{layerData, layer, idx}: {layerData?: any; layer: Layer; idx: number}
): S {
return {
...state,
layers: state.layers.map((lyr, i) => (i === idx ? layer : lyr)),
layerData: layerData
? state.layerData.map((d, i) => (i === idx ? layerData : d))
: state.layerData
};
}
export function updateStateOnLayerVisibilityChange<S extends VisState>(state: S, layer: Layer): S {
let newState = state;
if (state.splitMaps.length) {
newState = {
...state,
splitMaps: layer.config.isVisible
? addNewLayersToSplitMap(state.splitMaps, layer)
: removeLayerFromSplitMaps(state.splitMaps, layer)
};
}
if (layer.config.animation.enabled) {
newState = updateAnimationDomain(state);
}
return newState;
}
/**
* Compares two objects (or arrays) and returns a new object with only the
* properties that have changed between the two objects.
*/
function pickChangedProps<T>(prev: T, next: T): Partial<T> {
const changedProps: Partial<T> = {};
const pickPropsOf = obj => {
Object.keys(obj).forEach(key => {
if (!changedProps.hasOwnProperty(key) && !isEqual(prev[key], next[key])) {
changedProps[key] = next[key];
}
});
};
pickPropsOf(prev);
pickPropsOf(next);
return changedProps;
}
const VISUAL_CHANNEL_PROP_TYPES = ['field', 'scale', 'domain', 'aggregation'];
/**
* Apply layer config
* @memberof visStateUpdaters
* @returns nextState
*/
// eslint-disable-next-line complexity, max-statements
export function applyLayerConfigUpdater(
state: VisState,
action: VisStateActions.ApplyLayerConfigUpdaterAction
): VisState {
const {oldLayerId, newLayerConfig, layerIndex} = action;
const newParsedLayer =
// will move visualChannels to the config prop
parseLayerConfig(state.schema, newLayerConfig);
const oldLayer = state.layers.find(l => l.id === oldLayerId);
if (!oldLayer || !newParsedLayer) {
return state;
}
if (layerIndex !== null && layerIndex !== undefined && state.layers[layerIndex] !== oldLayer) {
// layerIndex is provided, but it doesn't match the oldLayer
return state;
}
const dataset = state.datasets[newParsedLayer.config.dataId];
if (!dataset) {
return state;
}
// Make sure the layer is valid and convert it to Layer
const newLayer = validateLayerWithData(dataset, newParsedLayer, state.layerClasses);
if (!newLayer) {
return state;
}
let nextState = state;
if (newLayer.type && newLayer.type !== oldLayer.type) {
const oldLayerIndex = state.layers.findIndex(l => l.id === oldLayerId);
if (oldLayerIndex >= 0) {
nextState = layerTypeChangeUpdater(nextState, layerTypeChange(oldLayer, newLayer.type));
// layerTypeChangeUpdater changes the id of the layer, so we need to obtain the new id
// but first make sure that the layer was not removed
if (nextState.layers.length === state.layers.length) {
const newLayerId = nextState.layers[oldLayerIndex].id;
nextState = applyLayerConfigUpdater(
nextState,
applyLayerConfig(newLayerId, {...newLayerConfig, id: newLayerId})
);
}
}
return nextState;
}
// serializeLayer() might return null if the old layer is not valid,
// we should still apply the changes in that case
const serializedOldLayer = serializeLayer(oldLayer, state.schema) ?? {config: {}};
const serializedNewLayer = serializeLayer(newLayer, state.schema);
if (!serializedNewLayer) {
return state;
}
if (!isEqual(serializedOldLayer, serializedNewLayer)) {
const changed = pickChangedProps(serializedOldLayer.config, serializedNewLayer.config);
if ('visConfig' in changed) {
if (changed.visConfig) {
nextState = layerVisConfigChangeUpdater(
nextState,
layerVisConfigChange(oldLayer, changed.visConfig)
);
}
delete changed.visConfig;
}
Object.keys(oldLayer.visualChannels).forEach(channelName => {
const channel = oldLayer.visualChannels[channelName];
const channelPropNames = VISUAL_CHANNEL_PROP_TYPES.map(prop => channel[prop]);
if (channelPropNames.some(prop => prop in changed)) {
nextState = layerVisualChannelChangeUpdater(
nextState,
layerVisualChannelConfigChange(
oldLayer,
pick(newLayer.config, channelPropNames),
channelName
)
);
for (const prop of channelPropNames) {
delete changed[prop];
}
}
});
if (Object.keys(changed).length > 0) {
nextState = layerConfigChangeUpdater(
nextState,
layerConfigChange(oldLayer, pick(newLayer.config, Object.keys(changed)))
);
}
}
return nextState;
}
/**
* Update layer base config: dataId, label, column, isVisible
* @memberof visStateUpdaters
* @returns nextState
*/
// eslint-disable-next-line complexity
export function layerConfigChangeUpdater(
state: VisState,
action: VisStateActions.LayerConfigChangeUpdaterAction
): VisState {
const {oldLayer} = action;
const idx = state.layers.findIndex(l => l.id === oldLayer.id);
const props = Object.keys(action.newConfig);
if (
typeof action.newConfig.dataId === 'string' &&
action.newConfig.dataId !== oldLayer.config.dataId
) {
const {dataId, ...restConfig} = action.newConfig;
const stateWithDataId = layerDataIdChangeUpdater(state, {
oldLayer,
newConfig: {dataId}
});
const nextLayer = stateWithDataId.layers.find(l => l.id === oldLayer.id);
return nextLayer && Object.keys(restConfig).length
? layerConfigChangeUpdater(stateWithDataId, {oldLayer: nextLayer, newConfig: restConfig})
: stateWithDataId;
}
let newLayer = oldLayer.updateLayerConfig(action.newConfig);
let layerData;
if (newLayer.shouldCalculateLayerData(props)) {
const oldLayerData = state.layerData[idx];
const updateLayerDataResult = calculateLayerData(newLayer, state, oldLayerData);
newLayer = updateLayerDataResult.layer;
layerData = updateLayerDataResult.layerData;
}
let newState = state;
if ('isVisible' in action.newConfig) {
newState = updateStateOnLayerVisibilityChange(state, newLayer);
}
return updateStateWithLayerAndData(newState, {
layer: newLayer,
layerData,
idx
});
}
/**
* Updates isValid flag of a layer.
* Updates isVisible based on the value of isValid.
* Triggers update of data for the layer in order to get errors again during next update iteration.
* @memberof visStateUpdaters
* @returns nextState
*/
export function layerSetIsValidUpdater(
state: VisState,
action: VisStateActions.LayerSetIsValidUpdaterAction
): VisState {
const {oldLayer, isValid} = action;
const idx = state.layers.findIndex(l => l.id === oldLayer.id);
const layerToUpdate = state.layers[idx];
if (layerToUpdate) {
let newLayer;
let newData = null;
if (isValid) {
// Trigger data update in order to show errors again if present.
const {layer, layerData} = calculateLayerData(layerToUpdate, state, undefined);
newLayer = layer;
newData = layerData;
} else {
newLayer = layerToUpdate.updateLayerConfig({
isVisible: false
});
newLayer.isValid = false;
}
return updateStateWithLayerAndData(state, {idx, layer: newLayer, layerData: newData});
}
return state;
}
function addOrRemoveTextLabels(newFields, textLabel, defaultTextLabel = DEFAULT_TEXT_LABEL) {
let newTextLabel = textLabel.slice();
const currentFields = textLabel.map(tl => tl.field && tl.field.name).filter(d => d);
const addFields = newFields.filter(f => !currentFields.includes(f.name));
const deleteFields = currentFields.filter(f => !newFields.find(fd => fd.name === f));
// delete
newTextLabel = newTextLabel.filter(tl => tl.field && !deleteFields.includes(tl.field.name));
newTextLabel = !newTextLabel.length ? [defaultTextLabel] : newTextLabel;
// add
newTextLabel = [
...newTextLabel.filter(tl => tl.field),
...addFields.map(af => ({
...defaultTextLabel,
field: af
}))
];
return newTextLabel;
}
function updateTextLabelPropAndValue(idx, prop, value, textLabel) {
if (!textLabel[idx].hasOwnProperty(prop)) {
return textLabel;
}
let newTextLabel = textLabel.slice();
if (prop === 'field' && value === null && textLabel.length > 1) {
// remove label when field value is set to null
newTextLabel.splice(idx, 1);
} else if (prop) {
newTextLabel = textLabel.map((tl, i) => (i === idx ? {...tl, [prop]: value} : tl));
}
return newTextLabel;
}
/**
* Update layer base config: dataId, label, column, isVisible
* @memberof visStateUpdaters
* @returns nextState
*/
export function layerTextLabelChangeUpdater(
state: VisState,
action: VisStateActions.LayerTextLabelChangeUpdaterAction
): VisState {
const {oldLayer, idx, prop, value} = action;
const {textLabel} = oldLayer.config;
// when adding a new empty text label,
// rely on the layer's default config, or use the constant DEFAULT_TEXT_LABEL
const defaultTextLabel =
oldLayer.getDefaultLayerConfig({dataId: ''})?.textLabel?.[0] ?? DEFAULT_TEXT_LABEL;
let newTextLabel = textLabel.slice();
if (!textLabel[idx] && idx === textLabel.length) {
// if idx is set to length, add empty text label
newTextLabel = [...textLabel, defaultTextLabel];
}
if (idx === 'all' && prop === 'fields') {
newTextLabel = addOrRemoveTextLabels(value, textLabel, defaultTextLabel);
} else {
newTextLabel = updateTextLabelPropAndValue(idx, prop, value, newTextLabel);
}
// update text label prop and value
return layerConfigChangeUpdater(state, {
oldLayer,
newConfig: {textLabel: newTextLabel}
});
}
function validateExistingLayerWithData(dataset, layerClasses, layer, schema) {
const loadedLayer = serializeLayer(layer, schema);
return loadedLayer
? validateLayerWithData(dataset, loadedLayer, layerClasses, {
allowEmptyColumn: true
})
: null;
}
/**
* Update layer config dataId
* @memberof visStateUpdaters
* @returns nextState
*/
export function layerDataIdChangeUpdater(
state: VisState,
action: {
oldLayer: Layer;
newConfig: {
dataId: string;
};
}
): VisState {
const {oldLayer, newConfig} = action;
const {dataId} = newConfig;
if (!oldLayer || !state.datasets[dataId]) {
return state;
}
const idx = state.layers.findIndex(l => l.id === oldLayer.id);
let newLayer = oldLayer.updateLayerConfig({dataId});
// this may happen when a layer is new (type: null and no columns) but it's not ready to be saved
if (newLayer.isValidToSave()) {
const validated = validateExistingLayerWithData(
state.datasets[dataId],
state.layerClasses,
newLayer,
state.schema
);
// if cant validate it with data create a new one
if (!validated) {
// @ts-expect-error TODO: checking oldLayer.type !== null
newLayer = new state.layerClasses[oldLayer.type]({dataId, id: oldLayer.id});
} else {
newLayer = validated;
}
}
newLayer = newLayer.updateLayerConfig({
isVisible: oldLayer.config.isVisible,
isConfigActive: true
});
newLayer.updateLayerDomain(state.datasets);
const {layerData, layer} = calculateLayerData(newLayer, state, undefined);
return updateStateWithLayerAndData(state, {layerData, layer, idx});
}
export function setInitialLayerConfig(layer, datasets, layerClasses): Layer {
let newLayer = layer;
if (!Object.keys(datasets).length) {
// no data is loaded
return layer;
}
if (!layer.config.dataId) {
// set layer dataId
newLayer = layer.updateLayerConfig({dataId: Object.keys(datasets)[0]});
}
const dataset = datasets[newLayer.config.dataId];
if (!dataset) {
return layer;
}
// find defaut layer props
const result =
typeof layerClasses[newLayer.type].findDefaultLayerProps === 'function'
? layerClasses[newLayer.type].findDefaultLayerProps(dataset, [])
: {props: []};
// an array of possible props, use 1st one
const props = Array.isArray(result) ? result : result.props || [];
if (props.length) {
newLayer = new layerClasses[layer.type]({
...props[0],
label: newLayer.config.label,
dataId: newLayer.config.dataId,
isVisible: true,
isConfigActive: newLayer.config.isConfigActive
});
return typeof newLayer.setInitialLayerConfig === 'function'
? newLayer.setInitialLayerConfig(dataset)
: newLayer;
}
return newLayer;
}
/**
* Update layer type. Previews layer config will be copied if applicable.
* @memberof visStateUpdaters
* @public
*/
export function layerTypeChangeUpdater(
state: VisState,
action: VisStateActions.LayerTypeChangeUpdaterAction
): VisState {
const {oldLayer, newType} = action;
if (!oldLayer) {
return state;
}
const oldId = oldLayer.id;
const idx = state.layers.findIndex(l => l.id === oldId);
if (!state.layerClasses[newType]) {
Console.error(`${newType} is not a valid layer type`);
return state;
}
let newLayer = new state.layerClasses[newType]({
// keep old layer lable and isConfigActive
label: oldLayer.config.label,
isConfigActive: oldLayer.config.isConfigActive,
dataId: oldLayer.config.dataId
});
if (!oldLayer.type) {
// if setting layer type on an empty layer
newLayer = setInitialLayerConfig(newLayer, state.datasets, state.layerClasses);
} else {
// get a mint layer, with new id and type
// because deck.gl uses id to match between new and old layer.
// If type has changed but id is the same, it will break
newLayer.assignConfigToLayer(oldLayer.config, oldLayer.visConfigSettings);
newLayer.updateLayerDomain(state.datasets);
}
const {clicked, hoverInfo} = state;
let newState = {
...state,
clicked: oldLayer.isLayerHovered(clicked) ? undefined : clicked,
hoverInfo: oldLayer.isLayerHovered(hoverInfo) ? undefined : hoverInfo
};
const {layerData, layer} = calculateLayerData(newLayer, newState);
newState = updateStateWithLayerAndData(newState, {layerData, layer, idx});
if (layer.config.animation.enabled || oldLayer.config.animation.enabled) {
newState = updateAnimationDomain(newState);
}
// update splitMap layer id
if (state.splitMaps.length) {
newState = {
...newState,
splitMaps: newState.splitMaps.map(settings => {
const {[oldId]: oldLayerMap, ...otherLayers} = settings.layers;
return oldId in settings.layers
? {
...settings,
layers: {
...otherLayers,
[layer.id]: oldLayerMap
}
}
: settings;
})
};
}
// update layerOrder with new id
newState = {
...newState,
layerOrder: newState.layerOrder.map(layerId =>
layerId === oldLayer.id ? newLayer.id : layerId
)
};
return newState;
}
/**
* Update layer visual channel
* @memberof visStateUpdaters
* @returns {Object} nextState
* @public
*/
export function layerVisualChannelChangeUpdater(
state: VisState,
action: VisStateActions.LayerVisualChannelConfigChangeUpdaterAction
): VisState {
const {oldLayer, newConfig, channel} = action;
if (!oldLayer.config.dataId) {
return state;
}
const dataset = state.datasets[oldLayer.config.dataId];
const idx = state.layers.findIndex(l => l.id === oldLayer.id);
const newLayer = oldLayer.updateLayerConfig(newConfig);
newLayer.updateLayerVisualChannel(dataset, channel);
const oldLayerData = state.layerData[idx];
const {layerData, layer} = calculateLayerData(newLayer, state, oldLayerData);
return updateStateWithLayerAndData(state, {layerData, layer, idx});
}
/**
* Update layer `visConfig`
* @memberof visStateUpdaters
* @public
*/
export function layerVisConfigChangeUpdater(
state: VisState,
action: VisStateActions.LayerVisConfigChangeUpdaterAction
): VisState {
const {oldLayer} = action;
const idx = state.layers.findIndex(l => l.id === oldLayer.id);
const props = Object.keys(action.newVisConfig);
const newVisConfig = {
...oldLayer.config.visConfig,
...action.newVisConfig
};
const newLayer = oldLayer.updateLayerConfig({visConfig: newVisConfig});
if (newLayer.shouldCalculateLayerData(props)) {
const oldLayerData = state.layerData[idx];
const {layerData, layer} = calculateLayerData(newLayer, state, oldLayerData);
return updateStateWithLayerAndData(state, {layerData, layer, idx});
}
return updateStateWithLayerAndData(state, {layer: newLayer, idx});
}
/**
* Update filter property
* @memberof visStateUpdaters
* @public
*/
export function setFilterAnimationTimeUpdater(
state: VisState,
action: VisStateActions.SetFilterAnimationTimeUpdaterAction
): VisState {
return setFilterUpdater(state, action);
}
/**
* Update filter animation window
* @memberof visStateUpdaters
* @public
*/
export function setFilterAnimationWindowUpdater(
state: VisState,
{id, animationWindow}: VisStateActions.SetFilterAnimationWindowUpdaterAction
): VisState {
return {
...state,
filters: state.filters.map(f =>
f.id === id
? {
...f,
animationWindow
}
: f
)
};
}
/**
* Update filter property
* @memberof visStateUpdaters
* @public
*/
export function setFilterUpdater(
state: VisState,
action: VisStateActions.SetFilterUpdaterAction
): VisState {
const {idx, prop, value, valueIndex = 0} = action;
const oldFilter = state.filters[idx];
if (!oldFilter) {
Console.error(`filters.${idx} is undefined`);
return state;
}
let newFilter = set([prop], value, oldFilter);
let newState = state;
const {dataId} = newFilter;
// Ensuring backward compatibility
let datasetIds = toArray(dataId);
switch (prop) {
// TODO: Next PR for UI if we update dataId, we need to consider two cases:
// 1. dataId is empty: create a default filter
// 2. Add a new dataset id
case FILTER_UPDATER_PROPS.dataId:
// if trying to update filter dataId. create an empty new filter
newFilter = updateFilterDataId(dataId);
break;
case FILTER_UPDATER_PROPS.name:
// we are supporting the current functionality
// TODO: Next PR for UI filter name will only update filter name but it won't have side effects
// we are gonna use pair of datasets and fieldIdx to update the filter
const datasetId = newFilter.dataId[valueIndex];
const {filter: updatedFilter, dataset: newDataset} = applyFilterFieldName(
newFilter,
state.datasets[datasetId],
value,
valueIndex,
{mergeDomain: false}
);
if (!updatedFilter) {
return state;
}
newFilter = updatedFilter;
if (newFilter.gpu) {
newFilter = setFilterGpuMode(newFilter, state.filters);
newFilter = assignGpuChannel(newFilter, state.filters);
}
newState = set(['datasets', datasetId], newDataset, state);
// only filter the current dataset
break;
case FILTER_UPDATER_PROPS.layerId:
// We need to update only datasetId/s if we have added/removed layers
// - check for layerId changes (XOR works because of string values)
// if no differences between layerIds, don't do any filtering
// @ts-ignore
const layerIdDifference = xor(newFilter.layerId, oldFilter.layerId);
const layerDataIds = uniq<string>(
layerIdDifference
.map(lid =>
get(
state.layers.find(l => l.id === lid),
['config', 'dataId']
)
)
.filter(d => d) as string[]
);
// only filter datasetsIds
datasetIds = layerDataIds;
// Update newFilter dataIds
const newDataIds = uniq<string>(
newFilter.layerId
?.map(lid =>
get(
state.layers.find(l => l.id === lid),
['config', 'dataId']
)
)
.filter(d => d) as string[]
);
newFilter = {
...newFilter,
dataId: newDataIds
};
break;
default:
break;
}
const enlargedFilter = state.filters.find(f => f.view === FILTER_VIEW_TYPES.enlarged);
if (enlargedFilter && enlargedFilter.id !== newFilter.id) {
// there should be only one enlarged filter