Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[chore] Add several vis state mergers combineConfigs and improve TS #2634

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions src/reducers/src/merger-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ function callFunctionGetTask(fn: () => any): [any, any] {
export function mergeStateFromMergers<State extends VisState>(
state: State,
initialState: State,
mergers: Merger<any>[],
mergers: Merger<State>[],
postMergerPayload: PostMergerPayload
): {
mergedState: State;
Expand Down Expand Up @@ -79,7 +79,7 @@ export function mergeStateFromMergers<State extends VisState>(

export function hasPropsToMerge<State extends object>(
state: State,
mergerProps: string | string[]
mergerProps?: string | string[]
): boolean {
return Array.isArray(mergerProps)
? Boolean(mergerProps.some(p => Object.prototype.hasOwnProperty.call(state, p)))
Expand All @@ -88,15 +88,15 @@ export function hasPropsToMerge<State extends object>(

export function getPropValueToMerger<State extends object>(
state: State,
mergerProps: string | string[],
mergerProps?: string | string[],
toMergeProps?: string | string[]
): Partial<State> | ValueOf<State> {
return Array.isArray(mergerProps)
return Array.isArray(mergerProps) && Array.isArray(toMergeProps)
? mergerProps.reduce((accu, p, i) => {
if (!toMergeProps) return accu;
return {...accu, [toMergeProps[i]]: state[p]};
}, {})
: state[mergerProps];
: state[mergerProps as string];
}

export function resetStateToMergeProps<State extends VisState>(
Expand Down
153 changes: 144 additions & 9 deletions src/reducers/src/vis-state-merger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,15 @@ import {
getInitialMapLayersForSplitMap,
applyFiltersToDatasets,
validateFiltersUpdateDatasets,
findById
findById,
aggregate,
notNullorUndefined
} from '@kepler.gl/utils';
import {getLayerOrderFromLayers} from '@kepler.gl/reducers';

import {LayerColumns, LayerColumn, Layer} from '@kepler.gl/layers';
import {createEffect} from '@kepler.gl/effects';
import {LAYER_BLENDINGS, OVERLAY_BLENDINGS} from '@kepler.gl/constants';
import {AGGREGATION_TYPES, LAYER_BLENDINGS, OVERLAY_BLENDINGS} from '@kepler.gl/constants';
import {CURRENT_VERSION, VisState, VisStateMergers, KeplerGLSchemaClass} from '@kepler.gl/schemas';

import {
Expand All @@ -28,7 +30,9 @@ import {
ParsedConfig,
Filter,
Effect as EffectType,
ParsedEffect
ParsedEffect,
NestedPartial,
SavedAnimationConfig
} from '@kepler.gl/types';
import {KeplerTable, Datasets, assignGpuChannels, resetFilterGpuMode} from '@kepler.gl/table';

Expand Down Expand Up @@ -305,7 +309,7 @@ export function mergeInteractions<S extends VisState>(
state: S,
interactionToBeMerged: Partial<SavedInteractionConfig> | undefined
): S {
const merged: Partial<SavedInteractionConfig> = {};
const merged: NestedPartial<SavedInteractionConfig> = {};
const unmerged: Partial<SavedInteractionConfig> = {};

if (interactionToBeMerged) {
Expand Down Expand Up @@ -370,6 +374,64 @@ export function mergeInteractions<S extends VisState>(
return nextState;
}

function combineInteractionConfigs(configs: SavedInteractionConfig[]): SavedInteractionConfig {
const combined = {...configs[0]};
// handle each property key of an `InteractionConfig`, e.g. tooltip, geocoder, brush, coordinate
// by combining values for each among all passed in configs

for (const key in combined) {
const toBeCombinedProps = configs.map(c => c[key]);

// all of these have an enabled boolean
combined[key] = {
// are any of the configs' enabled values true?
enabled: toBeCombinedProps.some(p => p?.enabled)
};

if (key === 'tooltip') {
// are any of the configs' compareMode values true?
combined[key].compareMode = toBeCombinedProps.some(p => p?.compareMode);

// return the compare type mode, it will be either absolute or relative
combined[key].compareType = getValueWithHighestOccurrence(
toBeCombinedProps.map(p => p.compareType)
);

// combine fieldsToShow among all dataset ids
combined[key].fieldsToShow = toBeCombinedProps
.map(p => p.fieldsToShow)
.reduce((acc, nextFieldsToShow) => {
for (const nextDataIdKey in nextFieldsToShow) {
const nextTooltipFields = nextFieldsToShow[nextDataIdKey];
if (!acc[nextDataIdKey]) {
// if the dataset id is not present in the accumulator
// then add it with its tooltip fields
acc[nextDataIdKey] = nextTooltipFields;
} else {
// otherwise the dataset id is already present in the accumulator
// so only add the next tooltip fields for this dataset's array if they are not already present,
// using the tooltipField.name property for uniqueness
nextTooltipFields.forEach(nextTF => {
if (!acc[nextDataIdKey].find(({name}) => nextTF.name === name)) {
acc[nextDataIdKey].push(nextTF);
}
});
}
}
return acc;
}, {});
}

if (key === 'brush') {
// keep the biggest brush size
combined[key].size =
aggregate(toBeCombinedProps, AGGREGATION_TYPES.maximum, p => p.size) ?? null;
}
}

return combined;
}

function savedUnmergedInteraction<S extends VisState>(
state: S,
unmerged: Partial<SavedInteractionConfig>
Expand Down Expand Up @@ -405,6 +467,7 @@ function replaceInteractionDatasetIds(interactionConfig, dataId: string, dataIdT
}
return null;
}

/**
* Merge splitMaps config with current visStete.
* 1. if current map is split, but splitMap DOESNOT contain maps
Expand Down Expand Up @@ -542,6 +605,15 @@ export function mergeLayerBlending<S extends VisState>(
return state;
}

/**
* Combines multiple layer blending configs into a single string
* by returning the one with the highest occurrence
*/
function combineLayerBlendingConfigs(configs: string[]): string | null {
// return the mode of the layer blending type
return getValueWithHighestOccurrence(configs);
}

/**
* Merge overlayBlending with saved
*/
Expand All @@ -559,6 +631,15 @@ export function mergeOverlayBlending<S extends VisState>(
return state;
}

/**
* Combines multiple overlay blending configs into a single string
* by returning the one with the highest occurrence
**/
function combineOverlayBlendingConfigs(configs: string[]): string | null {
// return the mode of the overlay blending type
return getValueWithHighestOccurrence(configs);
}

/**
* Merge animation config
*/
Expand All @@ -580,6 +661,14 @@ export function mergeAnimationConfig<S extends VisState>(
return state;
}

function combineAnimationConfigs(configs: SavedAnimationConfig[]): SavedAnimationConfig {
// get the smallest values of currentTime and speed among all configs
return {
currentTime: aggregate(configs, AGGREGATION_TYPES.minimum, c => c.currentTime) ?? null,
speed: aggregate(configs, AGGREGATION_TYPES.minimum, c => c.speed) ?? null
};
}

/**
* Validate saved layer columns with new data,
* update fieldIdx based on new fields
Expand Down Expand Up @@ -875,6 +964,24 @@ export function mergeEditor<S extends VisState>(state: S, savedEditor: SavedEdit
};
}

function combineEditorConfigs(configs: SavedEditor[]): SavedEditor {
return configs.reduce(
(acc, nextConfig) => {
return {
...acc,
features: [...acc.features, ...(nextConfig.features || [])]
};
},
{
// start with:
// - empty array for features accumulation
// - and are any of the configs' visible values true?
features: [],
visible: configs.some(c => c?.visible)
}
);
}

/**
* Validate saved layer config with new data,
* update fieldIdx based on new fields
Expand Down Expand Up @@ -902,6 +1009,29 @@ export function mergeDatasetsByOrder(state: VisState, newDataEntries: Datasets):
return merged;
}

/**
* Simliar purpose to aggregation utils `getMode` function,
* but returns the mode in the same value type without coercing to a string.
* It ignores `undefined` or `null` values, but returns `null` if no mode could be calculated.
*/
function getValueWithHighestOccurrence<T>(arr: T[]): T | null {
const tallys = new Map();
arr.forEach(value => {
if (notNullorUndefined(value)) {
if (!tallys.has(value)) {
tallys.set(value, 1);
} else {
tallys.set(value, tallys.get(value) + 1);
}
}
});
// return the value with the highest total occurrence count
if (tallys.size === 0) {
return null;
}
return [...tallys.entries()]?.reduce((acc, next) => (next[1] > acc[1] ? next : acc))[0];
}

export const VIS_STATE_MERGERS: VisStateMergers<any> = [
{
merge: mergeLayers,
Expand All @@ -925,11 +1055,16 @@ export const VIS_STATE_MERGERS: VisStateMergers<any> = [
prop: 'interactionConfig',
toMergeProp: 'interactionToBeMerged',
replaceParentDatasetIds: replaceInteractionDatasetIds,
saveUnmerged: savedUnmergedInteraction
saveUnmerged: savedUnmergedInteraction,
combineConfigs: combineInteractionConfigs
},
{merge: mergeLayerBlending, prop: 'layerBlending', combineConfigs: combineLayerBlendingConfigs},
{
merge: mergeOverlayBlending,
prop: 'overlayBlending',
combineConfigs: combineOverlayBlendingConfigs
},
{merge: mergeLayerBlending, prop: 'layerBlending'},
{merge: mergeOverlayBlending, prop: 'overlayBlending'},
{merge: mergeSplitMaps, prop: 'splitMaps', toMergeProp: 'splitMapsToBeMerged'},
{merge: mergeAnimationConfig, prop: 'animationConfig'},
{merge: mergeEditor, prop: 'editor'}
{merge: mergeAnimationConfig, prop: 'animationConfig', combineConfigs: combineAnimationConfigs},
{merge: mergeEditor, prop: 'editor', combineConfigs: combineEditorConfigs}
];
1 change: 1 addition & 0 deletions src/schemas/src/vis-state-schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ export type Merger<S extends object> = {
waitForLayerData?: boolean;
replaceParentDatasetIds?: ReplaceParentDatasetIdsFunc<ValueOf<S>>;
saveUnmerged?: (state: S, unmerged: any) => S;
combineConfigs?: (configs: S[]) => S;
getChildDatasetIds?: any;
};
export type VisStateMergers<S extends object> = Merger<S>[];
Expand Down
10 changes: 5 additions & 5 deletions src/types/schemas.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

import {RGBColor, Merge, RequireFrom} from './types';

import {Filter, TooltipInfo, AnimationConfig, SplitMap, Feature} from './reducers';
import {Filter, InteractionConfig, AnimationConfig, SplitMap, Feature} from './reducers';

import {LayerTextLabel} from './layers';

Expand All @@ -28,16 +28,16 @@ export type MinSavedFilter = RequireFrom<SavedFilter, 'dataId' | 'id' | 'name' |
export type ParsedFilter = SavedFilter | MinSavedFilter;

export type SavedInteractionConfig = {
tooltip: TooltipInfo['config'] & {
tooltip: InteractionConfig['tooltip']['config'] & {
enabled: boolean;
};
geocoder: TooltipInfo['geocoder'] & {
geocoder: {
enabled: boolean;
};
brush: TooltipInfo['brush'] & {
brush: InteractionConfig['brush']['config'] & {
enabled: boolean;
};
coordinate: TooltipInfo['coordinate'] & {
coordinate: {
enabled: boolean;
};
};
Expand Down
10 changes: 8 additions & 2 deletions src/utils/src/aggregate-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
// Copyright contributors to the kepler.gl project

import {deviation, min, max, mean, median, sum, variance} from 'd3-array';
import {AGGREGATION_TYPES} from '@kepler.gl/constants';
import {AGGREGATION_TYPES, AggregationTypes} from '@kepler.gl/constants';
import {ValueOf} from '@kepler.gl/types';
const identity = d => d;

export const getFrequency = data =>
data.reduce(
Expand All @@ -21,7 +23,11 @@
);
};

export function aggregate(data, technique) {
export function aggregate(
data: any[],
technique: ValueOf<AggregationTypes>,
accessor: (any: any) => any = identity

Check warning on line 29 in src/utils/src/aggregate-utils.ts

View workflow job for this annotation

GitHub Actions / build (18.x)

'accessor' is assigned a value but never used
): any {
switch (technique) {
case AGGREGATION_TYPES.average:
return mean(data);
Expand Down
Loading
Loading