Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.
[feat] introduction of deck.gl effects (#2372)
Igor Dykhtaa3521948eb25
diff --git a/examples/demo-app/src/factories/map-control.js b/examples/demo-app/src/factories/map-control.jsindex 6326d5f90..96f39e9a2 100644--- a/examples/demo-app/src/factories/map-control.js+++ b/examples/demo-app/src/factories/map-control.js@@ -20,25 +20,73 @@import React from 'react';import styled from 'styled-components';-import {MapControlFactory, withState} from '@kepler.gl/components';+import {+ withState,+ MapControlFactory,+ EffectControlFactory,+ EffectManagerFactory+} from '@kepler.gl/components';import {SampleMapPanel} from '../components/map-control/map-control';-CustomMapControlFactory.deps = MapControlFactory.deps;-function CustomMapControlFactory(...deps) {+const StyledMapControlPanel = styled.div`+ position: relative;+`;++const StyledMapControlContextPanel = styled.div`+ max-height: 100%;+ overflow: hidden;++ display: flex;+ flex-direction: column;+ justify-content: space-between;+ pointer-events: none !important; /* prevent padding from blocking input */+ & > * {+ /* all children should allow input */+ pointer-events: all;+ }+`;++const StyledMapControlOverlay = styled.div`+ position: absolute;+ display: flex;+ top: ${props => props.top}px;+ right: 0;+ z-index: 1;+ pointer-events: none !important; /* prevent padding from blocking input */+ & > * {+ /* all children should allow input */+ pointer-events: all;+ }++ margin-top: ${props => props.theme.rightPanelMarginTop}px;+ margin-right: ${props => props.theme.rightPanelMarginRight}px;+ ${props => (props.fullHeight ? 'height' : 'max-height')}: calc(100% - ${props =>+ props.theme.rightPanelMarginTop + props.theme.bottomWidgetPaddingBottom}px);+`;++CustomMapControlFactory.deps = [+ EffectControlFactory,+ EffectManagerFactory,+ ...MapControlFactory.deps+];+function CustomMapControlFactory(EffectControl, EffectManager, ...deps) {const MapControl = MapControlFactory(...deps);- const StyledMapControlOverlay = styled.div`- position: absolute;- top: ${props => props.top}px;- right: 0;- z-index: 1;- `;-- const CustomMapControl = props => (- <StyledMapControlOverlay top={props.top}>- {!props.isExport && props.currentSample ? <SampleMapPanel {...props} /> : null}- <MapControl {...props} top={0} />- </StyledMapControlOverlay>- );+ const actionComponents = [...(MapControl.defaultProps?.actionComponents ?? []), EffectControl];++ const CustomMapControl = props => {+ const showEffects = props.mapControls?.effect?.active;+ return (+ <StyledMapControlOverlay top={props.top}>+ <StyledMapControlPanel>+ {!props.isExport && props.currentSample ? <SampleMapPanel {...props} /> : null}+ <MapControl {...props} top={0} actionComponents={actionComponents} />+ </StyledMapControlPanel>+ <StyledMapControlContextPanel>+ {showEffects ? <EffectManager /> : null}+ </StyledMapControlContextPanel>+ </StyledMapControlOverlay>+ );+ };return withState([], state => ({...state.demo.app}))(CustomMapControl);}diff --git a/examples/webpack.config.local.js b/examples/webpack.config.local.jsindex 8c737f39d..5920de2a7 100644--- a/examples/webpack.config.local.js+++ b/examples/webpack.config.local.js@@ -57,7 +57,9 @@ function makeLocalDevConfig(env, EXAMPLE_DIR = LIB_DIR, externals = {}) {'react-dom': `${NODE_MODULES_DIR}/react-dom`,'react-redux': `${NODE_MODULES_DIR}/react-redux/lib`,'styled-components': `${NODE_MODULES_DIR}/styled-components`,- 'react-intl': `${NODE_MODULES_DIR}/react-intl`+ 'react-intl': `${NODE_MODULES_DIR}/react-intl`,+ // Suppress useles warnings from react-date-picker's dep+ 'tiny-warning': `${SRC_DIR}/utils/src/noop.ts`};// Combine flagsdiff --git a/package.json b/package.jsonindex d6893acae..ab9972da8 100644--- a/package.json+++ b/package.json@@ -29,6 +29,7 @@"./src/processors","./src/tasks","./src/actions",+ "./src/effects","./src/reducers","./src/components"],@@ -96,6 +97,7 @@"components.js","constants.js","layers.js",+ "effects.js","middleware.js","processors.js","reducers.js",diff --git a/src/actions/src/action-types.ts b/src/actions/src/action-types.tsindex 05278648d..71db454a8 100644--- a/src/actions/src/action-types.ts+++ b/src/actions/src/action-types.ts@@ -117,6 +117,10 @@ export const ActionTypes = {NEXT_FILE_BATCH: `${ACTION_PREFIX}NEXT_FILE_BATCH`,PROCESS_FILE_CONTENT: `${ACTION_PREFIX}PROCESS_FILE_CONTENT`,UPDATE_TABLE_COLOR: `${ACTION_PREFIX}UPDATE_TABLE_COLOR`,+ ADD_EFFECT: `${ACTION_PREFIX}ADD_EFFECT`,+ REORDER_EFFECT: `${ACTION_PREFIX}REORDER_EFFECT`,+ REMOVE_EFFECT: `${ACTION_PREFIX}REMOVE_EFFECT`,+ UPDATE_EFFECT: `${ACTION_PREFIX}UPDATE_EFFECT`,// mapStateUPDATE_MAP: `${ACTION_PREFIX}UPDATE_MAP`,diff --git a/src/actions/src/vis-state-actions.ts b/src/actions/src/vis-state-actions.tsindex c830d1d74..d9e7d7b23 100644--- a/src/actions/src/vis-state-actions.ts+++ b/src/actions/src/vis-state-actions.ts@@ -36,7 +36,9 @@ import {InteractionConfig,Filter,ParsedConfig,- ParsedLayer+ ParsedLayer,+ EffectConfig,+ EffectParamsPartial} from '@kepler.gl/types';// TODO - import LoaderObject type from @loaders.gl/core when supported// TODO - import LoadOptions type from @loaders.gl/core when supported@@ -521,6 +523,89 @@ export function duplicateLayer(};}+export type AddEffectUpdaterAction = {+ config: EffectParamsPartial;+};++/**+ * Add a new effect+ * @memberof visStateActions+ * @param config - new effect config+ * @returns action+ * @public+ */+export function addEffect(+ config: EffectParamsPartial+): Merge<AddEffectUpdaterAction, {type: typeof ActionTypes.ADD_EFFECT}> {+ return {+ type: ActionTypes.ADD_EFFECT,+ config+ };+}++export type ReorderEffectUpdaterAction = {+ order: string[];+};++/**+ * Reorder effects+ * @memberof visStateActions+ * @param order an array of effect ids+ * @returns action+ * @public+ */+export function reorderEffect(+ order: string[]+): Merge<ReorderEffectUpdaterAction, {type: typeof ActionTypes.REORDER_EFFECT}> {+ return {+ type: ActionTypes.REORDER_EFFECT,+ order+ };+}++export type RemoveEffectUpdaterAction = {+ id: string;+};++/**+ * Remove an effect+ * @memberof visStateActions+ * @param id idx of the effect to be removed+ * @returns action+ * @public+ */+export function removeEffect(+ id: string+): Merge<RemoveEffectUpdaterAction, {type: typeof ActionTypes.REMOVE_EFFECT}> {+ return {+ type: ActionTypes.REMOVE_EFFECT,+ id+ };+}++export type UpdateEffectUpdaterAction = {+ id: string;+ props: Partial<EffectConfig>;+};++/**+ * Update an effect+ * @memberof visStateActions+ * @param props idx of the effect to be updated with specified props+ * @returns action+ * @public+ */+export function updateEffect(+ id: string,+ props: Partial<EffectConfig>+): Merge<UpdateEffectUpdaterAction, {type: typeof ActionTypes.UPDATE_EFFECT}> {+ return {+ type: ActionTypes.UPDATE_EFFECT,+ id,+ props+ };+}+export type RemoveDatasetUpdaterAction = {dataId: string;};diff --git a/src/components/package.json b/src/components/package.jsonindex e02098e66..7f450bea7 100644--- a/src/components/package.json+++ b/src/components/package.json@@ -40,6 +40,7 @@"@kepler.gl/cloud-providers": "3.0.0-alpha.0","@kepler.gl/constants": "3.0.0-alpha.0","@kepler.gl/layers": "3.0.0-alpha.0",+ "@kepler.gl/effects": "3.0.0-alpha.0","@kepler.gl/localization": "3.0.0-alpha.0","@kepler.gl/processors": "3.0.0-alpha.0","@kepler.gl/reducers": "3.0.0-alpha.0",@@ -104,6 +105,7 @@"react": "^18.2.0","react-color": "^2.17.3","react-copy-to-clipboard": "^5.0.2",+ "react-date-picker": "^10.2.0","react-dom": "^18.2.0","react-intl": "^6.3.0","react-json-pretty": "^2.2.0",@@ -114,6 +116,7 @@"react-onclickoutside": "^6.7.1","react-redux": "^8.0.5","react-sortable-hoc": "^1.8.3",+ "react-time-picker": "^6.2.0","react-tooltip": "^4.2.17","react-virtualized": "^9.22.4","react-vis": "1.11.7",diff --git a/src/components/src/common/styled-components.tsx b/src/components/src/common/styled-components.tsxindex ae1efae02..b72518839 100644--- a/src/components/src/common/styled-components.tsx+++ b/src/components/src/common/styled-components.tsx@@ -19,6 +19,8 @@// THE SOFTWARE.import styled from 'styled-components';+import DatePicker from 'react-date-picker';+import TimePicker from 'react-time-picker';import ReactTooltip from 'react-tooltip';import {media} from '@kepler.gl/styles';import classnames from 'classnames';@@ -779,3 +781,307 @@ export const CheckMark = styled.span.attrs({height: 6.22px;}`;++export const StyledTimePicker = styled(TimePicker)`+ .react-time-picker {+ display: inline-flex;+ position: relative;+ font-family: ${props => props.theme.fontFamily};+ font-size: ${props => props.theme.inputFontSize};+ background-color: ${props => props.theme.inputBgd};+ color: ${props => props.theme.textColor};+ }+ .react-time-picker,+ .react-time-picker *,+ .react-time-picker *:before,+ .react-time-picker *:after {+ -moz-box-sizing: border-box;+ -webkit-box-sizing: border-box;+ box-sizing: border-box;+ }+ .react-time-picker__wrapper {+ display: flex;+ flex-grow: 1;+ flex-shrink: 0;+ background-color: ${props => props.theme.inputBgd};+ border: thin solid ${props => props.theme.inputBgd};+ border-radius: 2px;+ }+ .react-time-picker__wrapper:hover {+ background-color: ${props => props.theme.inputBgdHover};+ }+ .react-time-picker__inputGroup {+ min-width: calc((4px * 3) + 0.54em * 6 + 0.217em * 2);+ flex-grow: 1;+ padding: 4px 10px;+ box-sizing: content-box;+ }+ .react-time-picker__inputGroup__divider {+ padding: 1px 0;+ white-space: pre;+ }+ .react-time-picker__inputGroup__divider,+ .react-time-picker__inputGroup__leadingZero {+ display: inline-block;+ color: ${props => props.theme.textColor};+ font-family: ${props => props.theme.fontFamily};+ font-size: ${props => props.theme.inputFontSize};+ }+ .react-time-picker__inputGroup__input {+ min-width: 0.54em;+ height: 100%;+ position: relative;+ padding: 0 1px;+ border: 0;+ background: transparent;+ color: ${props => props.theme.textColor};+ font-family: ${props => props.theme.fontFamily};+ font-size: ${props => props.theme.inputFontSize};+ box-sizing: content-box;+ -webkit-appearance: textfield;+ -moz-appearance: textfield;+ appearance: textfield;+ }+ .react-time-picker__inputGroup__input:focus {+ outline: none;+ }+ .react-time-picker__inputGroup__input::-webkit-outer-spin-button,+ .react-time-picker__inputGroup__input::-webkit-inner-spin-button {+ -webkit-appearance: none;+ -moz-appearance: none;+ appearance: none;+ margin: 0;+ }+ .react-time-picker__inputGroup__input--hasLeadingZero {+ margin-left: -0.54em;+ padding-left: calc(1px + 0.54em);+ }+ .react-time-picker__inputGroup__amPm {+ font: inherit;+ -webkit-appearance: menulist;+ -moz-appearance: menulist;+ appearance: menulist;+ font-size: ${props => props.theme.inputFontSize};+ }+ .react-time-picker__button {+ border: 0;+ background-color: ${props => props.theme.inputBgd};+ padding: 4px 6px;+ }+ .react-time-picker__button:enabled {+ cursor: pointer;+ }+ .react-time-picker__button svg {+ display: inherit;+ }+ .react-time-picker__clock--closed,+ .react-time-picker__clear-button {+ display: none;+ }+`;++export const StyledDatePicker = styled(DatePicker)`+ .react-date-picker {+ display: inline-flex;+ position: relative;+ font-family: ${props => props.theme.fontFamily};+ font-size: ${props => props.theme.inputFontSize};+ }+ .react-date-picker,+ .react-date-picker *,+ .react-date-picker *:before,+ .react-date-picker *:after {+ -moz-box-sizing: border-box;+ -webkit-box-sizing: border-box;+ box-sizing: border-box;+ }+ .react-date-picker--disabled {+ background-color: #f0f0f0;+ color: #6d6d6d;+ }+ .react-date-picker__wrapper {+ display: flex;+ flex-grow: 1;+ flex-shrink: 0;+ border: thin solid ${props => props.theme.inputBgd};+ border-radius: 2px;+ }+ .react-date-picker__inputGroup {+ min-width: calc((4px * 3) + 0.54em * 8 + 0.217em * 2);+ flex-grow: 1;+ padding: 4px 10px;+ box-sizing: content-box;+ background-color: ${props => props.theme.inputBgd};+ }++ .react-date-picker__inputGroup:hover {+ background-color: ${props => props.theme.inputBgdHover};+ }+ .react-date-picker__inputGroup__divider {+ padding: 1px 0;+ white-space: pre;+ color: ${props => props.theme.textColor};+ }+ .react-date-picker__inputGroup__divider,+ .react-date-picker__inputGroup__leadingZero {+ display: inline-block;+ }+ .react-date-picker__inputGroup__input {+ min-width: 0.54em;+ height: 100%;+ position: relative;+ padding: 0 1px;+ border: 0;+ background: none;+ color: ${props => props.theme.textColor};+ font: inherit;+ font-size: ${props => props.theme.inputFontSize};+ box-sizing: content-box;+ -webkit-appearance: textfield;+ -moz-appearance: textfield;+ appearance: textfield;+ }+ .react-date-picker__inputGroup__input:focus {+ outline: none;+ }+ .react-date-picker__inputGroup__input::-webkit-outer-spin-button,+ .react-date-picker__inputGroup__input::-webkit-inner-spin-button {+ -webkit-appearance: none;+ -moz-appearance: none;+ appearance: none;+ margin: 0;+ }+ .react-date-picker__inputGroup__input:invalid {+ background: ${props => props.theme.inputBgd};+ }+ .react-date-picker__inputGroup__input--hasLeadingZero {+ margin-left: -0.54em;+ padding-left: calc(1px + 0.54em);+ }+ .react-date-picker__calendar {+ width: 257px;+ max-width: 100vw;+ z-index: 11;+ inset: auto !important;+ color: ${props => props.theme.textColor};+ }+ .react-date-picker__calendar--closed {+ display: none;+ }+ .react-date-picker__calendar .react-calendar {+ border-width: thin;+ }+ .react-date-picker__button {+ display: none;+ }+ .react-calendar {+ width: 257px;+ max-width: 100%;+ color: ${props => props.theme.textColor};+ background: ${props => props.theme.inputBgdHover};+ border: 1px solid ${props => props.theme.textColor};+ border-radius: 2px;+ font-family: ${props => props.theme.fontFamily};+ line-height: 1.125em;+ }+ .react-calendar,+ .react-calendar *,+ .react-calendar *:before,+ .react-calendar *:after {+ -moz-box-sizing: border-box;+ -webkit-box-sizing: border-box;+ box-sizing: border-box;+ }+ .react-calendar button {+ margin: 0;+ border: 0;+ outline: none;+ }+ .react-calendar buttom:enabled {+ color: ${props => props.theme.primaryBtnActColor};+ }+ .react-calendar button:enabled:hover {+ cursor: pointer;+ }+ .react-calendar__navigation {+ display: flex;+ height: 25px;+ margin-bottom: 1em;+ }+ .react-calendar__navigation button {+ min-width: 25px;+ background: none;+ }+ .react-calendar__navigation button:enabled:hover,+ .react-calendar__navigation button:enabled:focus {+ background-color: ${props => props.theme.inputBgdActive};+ }+ .react-calendar__month-view__weekdays {+ text-align: center;+ text-transform: uppercase;+ font-weight: bold;+ }+ .react-calendar__month-view__weekdays__weekday {+ padding: 0.5em;+ font-size: ${props => props.theme.inputFontSize};+ }+ .react-calendar__month-view__weekNumbers .react-calendar__tile {+ display: flex;+ align-items: center;+ justify-content: center;+ font-weight: bold;+ }+ .react-calendar__month-view__days__day--weekend {+ color: ${props => props.theme.textColor};+ }+ .react-calendar__month-view__days__day--neighboringMonth {+ color: ${props => props.theme.textColor};+ opacity: 0.4;+ }+ .react-calendar__navigation__label__labelText,+ .react-calendar__navigation__arrow {+ color: ${props => props.theme.textColor};+ }+ .react-calendar__year-view .react-calendar__tile,+ .react-calendar__decade-view .react-calendar__tile,+ .react-calendar__century-view .react-calendar__tile {+ padding: 2em 0.5em;+ }+ .react-calendar__tile {+ color: ${props => props.theme.textColor};+ max-width: 100%;+ padding: 6px 4px;+ background: none;+ text-align: center;+ font-size: ${props => props.theme.inputFontSize};+ }+ .react-calendar__tile:enabled:hover,+ .react-calendar__tile:enabled:focus {+ background-color: ${props => props.theme.primaryBtnBgd};+ color: ${props => props.theme.primaryBtnActColor};+ }+ .react-calendar__tile--now:enabled:hover,+ .react-calendar__tile--now:enabled:focus {+ background: ${props => props.theme.primaryBtnBgd};+ color: ${props => props.theme.primaryBtnActColor};+ }+ .react-calendar__tile--hasActive {+ background: ${props => props.theme.primaryBtnActBgd};+ }+ .react-calendar__tile--hasActive:enabled:hover,+ .react-calendar__tile--hasActive:enabled:focus {+ background: ${props => props.theme.primaryBtnActBgd};+ color: ${props => props.theme.primaryBtnActColor};+ }+ .react-calendar__tile--active {+ background: ${props => props.theme.primaryBtnActBgd};+ color: ${props => props.theme.primaryBtnActColor};+ }+ .react-calendar__tile--active:enabled:hover,+ .react-calendar__tile--active:enabled:focus {+ background: ${props => props.theme.primaryBtnActBgd};+ }+ .calendar__navigation__label__labelText {+ сolor: ${props => props.theme.textColor};+ }+`;diff --git a/src/components/src/dnd-context.tsx b/src/components/src/dnd-context.tsxindex 6ba7e7c4b..9230aa280 100644--- a/src/components/src/dnd-context.tsx+++ b/src/components/src/dnd-context.tsx@@ -7,15 +7,25 @@ import {DND_MODIFIERS,DROPPABLE_MAP_CONTAINER_TYPE,SORTABLE_LAYER_TYPE,- SORTABLE_SIDE_PANEL_TYPE+ SORTABLE_SIDE_PANEL_TYPE,+ SORTABLE_EFFECT_TYPE,+ SORTABLE_EFFECT_PANEL_TYPE} from '@kepler.gl/constants';-import {layerConfigChange, reorderLayer, toggleLayerForMap} from '@kepler.gl/actions';+import {+ layerConfigChange,+ reorderLayer,+ toggleLayerForMap,+ updateEffect,+ reorderEffect+} from '@kepler.gl/actions';import LayerPanelHeaderFactory from './side-panel/layer-panel/layer-panel-header';import {withState} from './injector';import {visStateLens} from '@kepler.gl/reducers';import {reorderLayerOrder} from '@kepler.gl/reducers';import {VisState} from '@kepler.gl/schemas';import {Layer} from '@kepler.gl/layers';+import {Effect} from '@kepler.gl/types';+import {reorderEffectOrder} from '@kepler.gl/utils';export type DndContextProps = PropsWithChildren<{visState: VisState;@@ -64,24 +74,28 @@ function DndContextFactory(};const DndContext = ({children, visState}: DndContextProps) => {- const {datasets, layerOrder, layers, splitMaps} = visState;+ const {datasets, layerOrder, layers, effects, effectOrder, splitMaps} = visState;const [activeLayer, setActiveLayer]: [Layer | undefined,(l: Layer | undefined) => void] = useState();- const dispatch = useDispatch();+ const [activeEffect, setActiveEffect]: [+ Effect | undefined,+ (l: Effect | undefined) => void+ ] = useState();+ const dispatch = useDispatch();const isSplit = useMemo(() => splitMaps?.length > 1, [splitMaps]);const dndModifiers = useMemo(() => (isSplit ? DND_EMPTY_MODIFIERS : DND_MODIFIERS), [isSplit]);- const onDragStart = useCallback(++ const onLayerDragStart = useCallback(event => {const {active} = event;const newActiveLayer = layers.find(layer => layer.id === active.id);if (newActiveLayer) {setActiveLayer(newActiveLayer);-if (newActiveLayer?.config.isConfigActive) {dispatch(layerConfigChange(newActiveLayer, {isConfigActive: false}));}@@ -90,12 +104,34 @@ function DndContextFactory([dispatch, layers]);- const onDragEnd = useCallback(+ const onEffectDragStart = useCallback(+ event => {+ const {active} = event;+ const newActiveEffect = effects.find(effect => effect.id === active.id);+ if (newActiveEffect) {+ setActiveEffect(newActiveEffect);+ if (newActiveEffect.config.isConfigActive) {+ dispatch(updateEffect(newActiveEffect.id, {isConfigActive: false}));+ }+ }+ },+ [dispatch, effects]+ );++ const onDragStart = useCallback(+ event => {+ onLayerDragStart(event);+ onEffectDragStart(event);+ },+ [onLayerDragStart, onEffectDragStart]+ );++ const onLayerDragEnd = useCallback(event => {const {active, over} = event;const {id: activeLayerId} = active;- const overType = over.data.current?.type;+ const overType = over?.data.current?.type;if (!overType) {setActiveLayer(undefined);@@ -131,6 +167,49 @@ function DndContextFactory([dispatch, layerOrder]);+ const onEffectDragEnd = useCallback(+ event => {+ const {active, over} = event;++ const {id: activeEffectId} = active;+ const overType = over?.data.current?.type;++ if (!overType) {+ setActiveEffect(undefined);+ return;+ }++ switch (overType) {+ // swaping effects+ case SORTABLE_EFFECT_TYPE:+ dispatch(reorderEffect(reorderEffectOrder(effectOrder, activeEffectId, over.id)));+ break;+ // moving effects within side panel+ case SORTABLE_EFFECT_PANEL_TYPE:+ // move effect to the end of the list+ dispatch(+ reorderEffect(+ reorderEffectOrder(effectOrder, activeEffectId, effectOrder[effectOrder.length - 1])+ )+ );+ break;+ default:+ break;+ }++ setActiveEffect(undefined);+ },+ [dispatch, effectOrder]+ );++ const onDragEnd = useCallback(+ event => {+ if (activeLayer) onLayerDragEnd(event);+ if (activeEffect) onEffectDragEnd(event);+ },+ [activeLayer, activeEffect, onLayerDragEnd, onEffectDragEnd]+ );+return (<DndKitContext onDragStart={onDragStart} onDragEnd={onDragEnd} modifiers={dndModifiers}>{children}diff --git a/src/components/src/effects/effect-configurator.tsx b/src/components/src/effects/effect-configurator.tsxnew file mode 100644index 000000000..6d525e9fe--- /dev/null+++ b/src/components/src/effects/effect-configurator.tsx@@ -0,0 +1,256 @@+import React, {useCallback, useMemo} from 'react';+import styled from 'styled-components';++import {LIGHT_AND_SHADOW_EFFECT} from '@kepler.gl/constants';+import {isNumber} from '@kepler.gl/utils';+import {Effect, EffectConfig} from '@kepler.gl/types';++import {PanelLabel} from '../common/styled-components';+import RangeSliderFactory from '../common/range-slider';+import ColorSelectorFactory from '../side-panel/layer-panel/color-selector';+import EffectTimeConfiguratorFactory from './effect-time-configurator';++export type EffectConfiguratorProps = {+ effect: Effect;+ updateEffectConfig: (+ e: Event | null | undefined,+ id: string,+ config: Partial<EffectConfig>+ ) => void;+};++const StyledEffectConfigurator = styled.div.attrs({+ className: 'effect-panel__config'+})`+ position: relative;+ margin-top: ${props => props.theme.effectConfiguratorMargin};+ padding: ${props => props.theme.effectConfiguratorPadding};+`;++export const PanelLabelWrapper = styled.div.attrs({+ className: 'side-panel-panel__label-wrapper'+})`+ display: flex;+ align-items: self-start;++ .side-panel-panel__label {+ margin-top: 2px;+ margin-bottom: 0px;+ }+`;++export const StyledColorSelectorWrapper = styled.div`+ margin-right: 5px;+ margin-left: 5px;+ margin-bottom: 6px;+ margin-top: 2px;+`;++const COMMON_SLIDER_PROPS = {+ showInput: true,+ isRanged: false,+ step: 0.001,+ label: 'value'+};++EffectConfiguratorFactory.deps = [+ RangeSliderFactory,+ ColorSelectorFactory,+ EffectTimeConfiguratorFactory+];++export default function EffectConfiguratorFactory(+ RangeSlider: ReturnType<typeof RangeSliderFactory>,+ ColorSelector: ReturnType<typeof ColorSelectorFactory>,+ EffectTimeConfigurator: ReturnType<typeof EffectTimeConfiguratorFactory>+): React.FC<EffectConfiguratorProps> {+ const EffectConfigurator = ({effect, updateEffectConfig}: EffectConfiguratorProps) => {+ const renderShadowEffectConfigurator = useCallback(() => {+ const {config} = effect;++ const sliderProps = useMemo(() => {+ const propNames = ['shadowIntensity', 'ambientLightIntensity', 'sunLightIntensity'];+ return propNames.map(propName => {+ return {+ value1: effect.config.params[propName],+ range: [0, 1],+ value0: 0,+ onChange: (value: number[], e?: Event) => {+ updateEffectConfig(e, effect.id, {params: {[propName]: value[1]}});+ }+ };+ });+ }, [effect, config.params, updateEffectConfig]);++ const onDateTimeChange = useCallback(+ value => {+ updateEffectConfig(null, effect.id, {params: {timestamp: value}});+ },+ [effect, updateEffectConfig]+ );++ const onUseCurrentTimeChange = useCallback(+ value => {+ updateEffectConfig(null, effect.id, {+ params: {useCurrentTime: value}+ });+ },+ [effect, updateEffectConfig]+ );++ const colorPickerProps = useMemo(() => {+ const propNames = ['ambientLightColor', 'sunLightColor'];+ return propNames.map(propName => {+ return {+ colorSets: [+ {+ selectedColor: config.params[propName],+ setColor: v => updateEffectConfig(null, effect.id, {params: {[propName]: v}})+ }+ ]+ };+ });+ }, [effect, config.params, updateEffectConfig]);++ return (+ <StyledEffectConfigurator key={effect.id}>+ <PanelLabelWrapper>+ <PanelLabel>{'Date & Time'}</PanelLabel>+ </PanelLabelWrapper>+ <EffectTimeConfigurator+ timestamp={config.params.timestamp}+ onDateTimeChange={onDateTimeChange}+ useCurrentTime={config.params.useCurrentTime}+ onUseCurrentTimeChange={onUseCurrentTimeChange}+ />+ <PanelLabelWrapper>+ <PanelLabel>{'Shadow intensity'}</PanelLabel>+ </PanelLabelWrapper>+ <RangeSlider {...COMMON_SLIDER_PROPS} {...sliderProps[0]} />+ <PanelLabelWrapper>+ <PanelLabel>{'Ambient light intensity'}</PanelLabel>+ </PanelLabelWrapper>+ <RangeSlider {...COMMON_SLIDER_PROPS} {...sliderProps[1]} />+ <PanelLabelWrapper>+ <PanelLabel>{'Ambient light color'}</PanelLabel>+ </PanelLabelWrapper>+ <StyledColorSelectorWrapper>+ <ColorSelector {...colorPickerProps[0]} />+ </StyledColorSelectorWrapper>+ <PanelLabelWrapper>+ <PanelLabel>{'Sun light intensity'}</PanelLabel>+ </PanelLabelWrapper>+ <RangeSlider {...COMMON_SLIDER_PROPS} {...sliderProps[2]} />+ <PanelLabelWrapper>+ <PanelLabel>{'Sun light color'}</PanelLabel>+ </PanelLabelWrapper>+ <StyledColorSelectorWrapper>+ <ColorSelector {...colorPickerProps[1]} />+ </StyledColorSelectorWrapper>+ </StyledEffectConfigurator>+ );+ }, [effect, updateEffectConfig]);++ const renderPostProcessingEffectConfigurator = useCallback(() => {+ const {config} = effect;+ const uniforms = effect.deckEffect?.module.uniforms || {};+ const propNames = Object.keys(uniforms);++ const slidersForProps = useMemo(() => {+ return propNames.map(propName => {+ const uniform = uniforms[propName];+ if (!uniform || uniform.private) {+ return null;+ }++ const sliders: {+ value0: number;+ value1: number;+ range: [number, number];+ onChange: (value: number[], e?: Event) => void;+ }[] = [];+ const prevValue = config.params[propName];++ // the uniform is [0, 1] array+ if (uniform.length === 2) {+ sliders.push({+ value1: prevValue[0] || 0,+ range: [0, 1],+ value0: 0,+ onChange: (newValue, e) => {+ updateEffectConfig(e, effect.id, {+ params: {[propName]: [newValue[1], prevValue[1]]}+ });+ }+ });++ sliders.push({+ value1: prevValue[1] || 0,+ range: [0, 1],+ value0: 0,+ onChange: (newValue, e) => {+ updateEffectConfig(e, effect.id, {+ params: {[propName]: [prevValue[0], newValue[1]]}+ });+ }+ });+ }+ // the uniform plain number without any desc+ else if (isNumber(uniform)) {+ sliders.push({+ value1: prevValue || 0,+ range: [0, 500],+ value0: 0,+ onChange: (newValue, e) => {+ updateEffectConfig(e, effect.id, {params: {[propName]: newValue[1]}});+ }+ });+ }+ // the uniform description is {value: 0, min: 0, max: 1, ...}+ else if (isNumber(uniform.value)) {+ sliders.push({+ value1: prevValue || 0,+ range: [uniform.min ?? uniform.softMin ?? 0, uniform.max ?? uniform.softMax ?? 1],+ value0: uniform.min ?? uniform.softMin ?? 0,+ onChange: (newValue, e) => {+ updateEffectConfig(e, effect.id, {params: {[propName]: newValue[1]}});+ }+ });+ } else {+ return null;+ }++ return sliders;+ });+ }, [propNames, effect, effect.config.params, updateEffectConfig]);++ return (+ <StyledEffectConfigurator key={effect.id}>+ {propNames.map((propName, uniformIndex) => {+ const slidersForProp = slidersForProps[uniformIndex];+ if (!slidersForProp) {+ return null;+ }++ return (+ <div key={`${effect.id}-${uniformIndex}`}>+ <PanelLabelWrapper>+ <PanelLabel>{propName}</PanelLabel>+ </PanelLabelWrapper>+ {slidersForProp.map((sliderProp, sliderIndex) => {+ return <RangeSlider key={sliderIndex} {...COMMON_SLIDER_PROPS} {...sliderProp} />;+ })}+ </div>+ );+ })}+ </StyledEffectConfigurator>+ );+ }, [effect, updateEffectConfig]);++ const {config} = effect;+ if (config.type === LIGHT_AND_SHADOW_EFFECT.type) return renderShadowEffectConfigurator();+ return renderPostProcessingEffectConfigurator();+ };++ return EffectConfigurator;+}diff --git a/src/components/src/effects/effect-list.tsx b/src/components/src/effects/effect-list.tsxnew file mode 100644index 000000000..c49f88b8f--- /dev/null+++ b/src/components/src/effects/effect-list.tsx@@ -0,0 +1,144 @@+import React, {useMemo} from 'react';+import styled from 'styled-components';+import classnames from 'classnames';+import {CSS} from '@dnd-kit/utilities';+import {useSortable, SortableContext, verticalListSortingStrategy} from '@dnd-kit/sortable';++import {dataTestIds, SORTABLE_EFFECT_TYPE, SORTABLE_EFFECT_PANEL_TYPE} from '@kepler.gl/constants';+import {findById} from '@kepler.gl/utils';+import {VisStateActions} from '@kepler.gl/actions';+import {Effect} from '@kepler.gl/types';++import EffectPanelFactory from './effect-panel';++export type EffectListProps = {+ effects: Effect[];+ effectOrder: string[];+ visStateActions: typeof VisStateActions;+ isSortable: boolean;+};++const Container = styled.div`+ display: flex;+ flex-direction: column;+`;++type SortableStyledItemProps = {transition?: string; transform?: string};+const SortableStyledItem = styled.div<SortableStyledItemProps>`+ z-index: ${props => props.theme.dropdownWrapperZ + 1};+ transition: ${props => props.transition};+ transform: ${props => props.transform};+ &.sorting {+ opacity: 0.3;+ pointer-events: none;+ }+ &.sorting-effects .effect-panel__header {+ background-color: ${props => props.theme.panelBackgroundHover};+ font-family: ${props => props.theme.fontFamily};+ font-weight: ${props => props.theme.fontWeight};+ font-size: ${props => props.theme.fontSize};+ line-height: ${props => props.theme.lineHeight};+ *,+ *:before,+ *:after {+ box-sizing: border-box;+ }+ .effect__drag-handle {+ opacity: 1;+ color: ${props => props.theme.textColorHl};+ }+ }+`;++EffectListFactory.deps = [EffectPanelFactory];++function EffectListFactory(+ EffectPanel: ReturnType<typeof EffectPanelFactory>+): React.FC<EffectListProps> {+ const SortableItem = ({effect, idx, panelProps, disabled}) => {+ const {attributes, listeners, setNodeRef, isDragging, transform, transition} = useSortable({+ id: effect.id,+ data: {+ type: SORTABLE_EFFECT_TYPE,+ parent: SORTABLE_EFFECT_PANEL_TYPE+ },+ disabled+ });++ return (+ <SortableStyledItem+ ref={setNodeRef}+ className={classnames(+ {[dataTestIds.sortableEffectItem]: !disabled},+ {[dataTestIds.staticEffectItem]: disabled},+ {sorting: isDragging}+ )}+ data-testid={disabled ? dataTestIds.staticEffectItem : dataTestIds.sortableEffectItem}+ transform={CSS.Transform.toString(transform)}+ transition={transition || ''}+ {...attributes}+ >+ <EffectPanel+ {...panelProps}+ key={effect.id}+ idx={idx}+ effect={effect}+ listeners={listeners}+ isDraggable={!disabled}+ />+ </SortableStyledItem>+ );+ };++ const EffectList = (props: EffectListProps) => {+ const {effects, effectOrder, visStateActions} = props;++ const effectsToShow = useMemo(() => {+ return effectOrder.reduce((acc, effectId) => {+ const effect = findById(effectId)(effects.filter(Boolean));+ if (!effect) {+ return acc;+ }+ return [...acc, effect];+ }, [] as Effect[]);+ }, [effects, effectOrder]);++ const sidePanelDndItems = useMemo(() => {+ return effectsToShow.map(({id}) => id);+ }, [effectsToShow]);++ const panelProps = useMemo(+ () => ({+ effects,+ effectOrder,+ removeEffect: visStateActions.removeEffect,+ updateEffect: visStateActions.updateEffect+ }),+ [effects, effectOrder, visStateActions]+ );++ return (+ <Container>+ <SortableContext+ id={SORTABLE_EFFECT_PANEL_TYPE}+ items={sidePanelDndItems}+ strategy={verticalListSortingStrategy}+ disabled={false}+ >+ {effectsToShow.map(effect => (+ <SortableItem+ key={effect.id}+ effect={effect}+ idx={effects.findIndex(l => l?.id === effect.id)}+ panelProps={panelProps}+ disabled={false}+ />+ ))}+ </SortableContext>+ </Container>+ );+ };+ return EffectList;+}++export default EffectListFactory;diff --git a/src/components/src/effects/effect-manager.tsx b/src/components/src/effects/effect-manager.tsxnew file mode 100644index 000000000..98ef04da5--- /dev/null+++ b/src/components/src/effects/effect-manager.tsx@@ -0,0 +1,125 @@+import React, {useMemo} from 'react';+import styled from 'styled-components';+import {IntlShape} from 'react-intl';+import {injectIntl} from 'react-intl';++import {addEffect, updateEffect, removeEffect, reorderEffect} from '@kepler.gl/actions';+import {LIGHT_AND_SHADOW_EFFECT, EFFECT_DESCS} from '@kepler.gl/constants';+import {VisStateActions} from '@kepler.gl/actions';+import {Effect} from '@kepler.gl/types';++import {withState} from '../injector';+import SidePanelTitleFactory from './side-panel-title';+import EffectListFactory from './effect-list';+import EffectTypeSelectorFactory from './effect-type-selector';++export type EffectManagerState = {+ visStateActions: typeof VisStateActions;+ effects: Effect[];+ effectOrder: string[];+ children: React.ReactNode;+};+export type EffectManagerWithIntlProp = {intl: IntlShape};++const StyledEffectPanelContainer = styled.div`+ display: flex;+ flex-direction: column;+ pointer-events: none !important; /* prevent padding from blocking input */+ flex-grow: 1;+ justify-content: space-between;+ overflow: hidden;++ & > * {+ /* all children should allow input */+ pointer-events: all;+ }+`;++// top right position absolute+const StyledEffectPanel = styled.div`+ top: 0;+ background-color: ${props => props.theme.sidePanelBg};+ display: flex;+ flex-direction: column;+ flex-grow: 1;+ overflow: hidden;+`;++const StyledEffectPanelHeader = styled.div`+ padding: ${({theme}) =>+ `${theme.effectPanelPaddingTop}px ${theme.effectPanelPaddingSide}px 4px ${theme.effectPanelPaddingSide}px}`};+ border-bottom: 1px solid ${props => props.theme.borderColor};+ min-width: ${({theme}) => theme.effectPanelWidth}px;+`;++const StyledEffectPanelContent = styled.div`+ ${props => props.theme.sidePanelScrollBar};+ padding: 10px 0;+ overflow: overlay;+ display: flex;+ flex-direction: column;+`;++EffectManagerFactory.deps = [EffectListFactory, SidePanelTitleFactory, EffectTypeSelectorFactory];++function EffectManagerFactory(+ EffectList: ReturnType<typeof EffectListFactory>,+ SidePanelTitle: ReturnType<typeof SidePanelTitleFactory>,+ EffectTypeSelector: ReturnType<typeof EffectTypeSelectorFactory>+): React.FC<EffectManagerWithIntlProp> {+ const EffectManager = (props: EffectManagerWithIntlProp & EffectManagerState) => {+ const {intl, visStateActions, effects, effectOrder, children} = props;++ // Prevent shadow effect from being added multiple times+ const effectOptions = useMemo(() => {+ const hasShadow = effects.some(effect => {+ return effect.config.type === LIGHT_AND_SHADOW_EFFECT.type;+ });++ return hasShadow+ ? EFFECT_DESCS.filter(desc => desc.type !== LIGHT_AND_SHADOW_EFFECT.type)+ : EFFECT_DESCS;+ }, [effects]);++ return (+ <StyledEffectPanelContainer className="effect-manager">+ <StyledEffectPanel>+ <StyledEffectPanelHeader>+ <SidePanelTitle+ className="effect-manager-title"+ title={intl.formatMessage({id: 'effectManager.effect'})}+ >+ <EffectTypeSelector options={effectOptions} onSelect={visStateActions.addEffect} />+ </SidePanelTitle>+ </StyledEffectPanelHeader>++ <StyledEffectPanelContent>+ <EffectList+ effects={effects}+ effectOrder={effectOrder}+ visStateActions={visStateActions}+ isSortable={true}+ />+ </StyledEffectPanelContent>+ </StyledEffectPanel>+ {children}+ </StyledEffectPanelContainer>+ );+ };++ return withState(+ [],+ state => {+ const visState = state.demo.keplerGl.map.visState;+ return {+ effects: visState.effects,+ effectOrder: visState.effectOrder+ };+ },+ {+ visStateActions: {addEffect, updateEffect, removeEffect, reorderEffect}+ }+ )(injectIntl(EffectManager)) as React.FC<{}>;+}++export default EffectManagerFactory;diff --git a/src/components/src/effects/effect-panel-header.tsx b/src/components/src/effects/effect-panel-header.tsxnew file mode 100644index 000000000..68577ef64--- /dev/null+++ b/src/components/src/effects/effect-panel-header.tsx@@ -0,0 +1,217 @@+import React from 'react';+import classnames from 'classnames';+import styled from 'styled-components';++import PanelHeaderActionFactory from '../side-panel/panel-header-action';+import {ArrowDown, EyeSeen, EyeUnseen, Trash, VertDots, BaseProps} from '../common/icons';+import {StyledPanelHeader} from '../common/styled-components';++export type EffectPanelHeaderProps = {+ label: string;+ listeners: any;+ effectId: string;+ isEnabled: boolean;+ isConfigActive: boolean;+ showSortHandle?: boolean;+ isDragNDropEnabled: boolean;+ onToggleEnabled: () => void;+ onRemoveEffect: () => void;+ onToggleEnableConfig: () => void;+ actionIcons?: {+ remove: React.ComponentType<Partial<BaseProps>>;+ visible: React.ComponentType<Partial<BaseProps>>;+ hidden: React.ComponentType<Partial<BaseProps>>;+ enableConfig: React.ComponentType<Partial<BaseProps>>;+ };+};++export const defaultProps = {+ isDragNDropEnabled: true+};++const defaultActionIcons = {+ remove: Trash,+ visible: EyeSeen,+ hidden: EyeUnseen,+ enableConfig: ArrowDown+};++const StyledEffectPanelHeader = styled(StyledPanelHeader)`+ height: ${props => props.theme.effectPanelHeaderHeight}px;+ position: relative;+ align-items: stretch;++ .effect__drag-handle__placeholder {+ height: 20px;+ padding: 10px;+ }++ :hover {+ cursor: pointer;+ background-color: ${props => props.theme.panelBackgroundHover};+ .effect__drag-handle {+ opacity: 1;+ }+ }++ border-left: 3px solid ${props => props.theme.panelBackgroundHover};+`;++const HeaderActionSection = styled.div`+ display: flex;+ position: absolute;+ height: 100%;+ align-items: stretch;+ right: 10px;+ :hover {+ .effect-panel__header__actions__hidden {+ opacity: 1;+ background-color: ${props => props.theme.panelBackgroundHover};+ }+ }+`;++// Hiden actions only show up on hover+type StyledPanelHeaderHiddenActionsProps = {isConfigActive: boolean};+const StyledPanelHeaderHiddenActions = styled.div.attrs({+ className: 'effect-panel__header__actions__hidden'+})<StyledPanelHeaderHiddenActionsProps>`+ opacity: 0;+ display: flex;+ align-items: center;+ transition: opacity 0.4s ease, background-color 0.4s ease;+ background-color: ${props =>+ props.isConfigActive ? props.theme.panelBackgroundHover : props.theme.panelBackground};++ :hover {+ opacity: 1;+ }+`;++const StyledDragHandle = styled.div`+ display: flex;+ align-items: center;+ opacity: 0;+ z-index: 1000;+ :hover {+ cursor: move;+ opacity: 1;+ color: ${props => props.theme.textColorHl};+ }+`;++const DragHandle = ({className, listeners, children}) => (+ <StyledDragHandle className={className} {...listeners}>+ {children}+ </StyledDragHandle>+);++EffectPanelHeaderActionSectionFactory.deps = [PanelHeaderActionFactory];++export function EffectPanelHeaderActionSectionFactory(+ PanelHeaderAction: ReturnType<typeof PanelHeaderActionFactory>+): React.FC<EffectPanelHeaderProps> {+ const EffectPanelHeaderActionSection = (props: EffectPanelHeaderProps) => {+ const {+ effectId,+ isEnabled,+ isConfigActive,+ onToggleEnabled,+ onRemoveEffect,+ onToggleEnableConfig,+ actionIcons = defaultActionIcons+ } = props;++ return (+ <HeaderActionSection className="effect-panel__header__actions">+ <StyledPanelHeaderHiddenActions isConfigActive={isConfigActive}>+ <PanelHeaderAction+ className="effect__remove-effect"+ testId="remove-effect-action"+ id={effectId}+ tooltip={'tooltip.removeEffect'}+ onClick={onRemoveEffect}+ tooltipType="error"+ IconComponent={actionIcons.remove}+ />+ </StyledPanelHeaderHiddenActions>+ <PanelHeaderAction+ className="effect__visibility-toggle"+ id={effectId}+ tooltip={isEnabled ? 'tooltip.disableEffect' : 'tooltip.enabledEffect'}+ onClick={onToggleEnabled}+ IconComponent={isEnabled ? actionIcons.visible : actionIcons.hidden}+ />+ <PanelHeaderAction+ className={classnames('effect__enable-config ', {+ 'is-open': isConfigActive+ })}+ id={effectId}+ tooltip={'tooltip.effectSettings'}+ onClick={onToggleEnableConfig}+ IconComponent={actionIcons.enableConfig}+ />+ </HeaderActionSection>+ );+ };++ return EffectPanelHeaderActionSection;+}++const StyledEffectTitleSection = styled.div`+ margin-left: 4px;+ flex-grow: 1;+ align-items: center;+ display: flex;+ color: ${props => props.theme.textColor};+`;++const IconPlaceholder = styled.div`+ width: 20px;+ height: 20px;+`;++EffectPanelHeaderFactory.deps = [EffectPanelHeaderActionSectionFactory];++function EffectPanelHeaderFactory(+ EffectPanelHeaderActionSection: ReturnType<typeof EffectPanelHeaderActionSectionFactory>+): React.FC<EffectPanelHeaderProps> {+ const EffectPanelHeader = (props: EffectPanelHeaderProps) => {+ const {+ isConfigActive,+ isDragNDropEnabled,+ label,+ onToggleEnableConfig,+ listeners,+ showSortHandle = true+ } = props;++ return (+ <StyledEffectPanelHeader+ className={classnames('effect-panel__header', {+ 'sort--handle': !isConfigActive+ })}+ active={isConfigActive}+ onClick={onToggleEnableConfig}+ >+ {isDragNDropEnabled ? (+ <DragHandle className="effect__drag-handle" listeners={listeners}>+ {showSortHandle ? <VertDots height="20px" /> : <IconPlaceholder />}+ </DragHandle>+ ) : (+ <div className="effect__drag-handle__placeholder" />+ )}++ <StyledEffectTitleSection>{label}</StyledEffectTitleSection>++ <EffectPanelHeaderActionSection {...props} />+ </StyledEffectPanelHeader>+ );+ };++ EffectPanelHeader.defaultProps = defaultProps;++ return EffectPanelHeader;+}++export default EffectPanelHeaderFactory;diff --git a/src/components/src/effects/effect-panel.tsx b/src/components/src/effects/effect-panel.tsxnew file mode 100644index 000000000..653a00601--- /dev/null+++ b/src/components/src/effects/effect-panel.tsx@@ -0,0 +1,119 @@+import React, {Component, ComponentType} from 'react';+import styled from 'styled-components';+import PropTypes from 'prop-types';++import {dataTestIds, LIGHT_AND_SHADOW_EFFECT} from '@kepler.gl/constants';+import {removeEffect, updateEffect} from '@kepler.gl/actions';+import {Effect, EffectConfig} from '@kepler.gl/types';++import EffectPanelHeaderFactory from './effect-panel-header';+import EffectConfiguratorFactory from './effect-configurator';++export type EffectPanelProps = {+ className: string;+ effect: Effect;+ isDraggable: boolean;+ listeners: any;+ removeEffect: typeof removeEffect;+ updateEffect: typeof updateEffect;++ style?: React.CSSProperties;+ onMouseDown: React.MouseEventHandler<HTMLDivElement>;+ onTouchStart: React.TouchEventHandler<HTMLDivElement>;+};++export type PanelWrapperProps = {+ active: boolean;+};++const PanelWrapper = styled.div<PanelWrapperProps>`+ font-size: 12px;+ border-radius: 1px;+ margin-bottom: 8px;+ z-index: 1000;+ &.dragging {+ cursor: move;+ }+ margin: 3px 25px;+`;++EffectPanelFactory.deps = [EffectPanelHeaderFactory, EffectConfiguratorFactory];++function EffectPanelFactory(+ EffectPanelHeader: ReturnType<typeof EffectPanelHeaderFactory>,+ EffectConfigurator: ReturnType<typeof EffectConfiguratorFactory>+): ComponentType<EffectPanelProps> {+ class EffectPanel extends Component<EffectPanelProps> {+ static propTypes = {+ effect: PropTypes.object.isRequired,+ removeEffect: PropTypes.func.isRequired,+ updateEffect: PropTypes.func.isRequired,+ isDraggable: PropTypes.bool+ };++ _toggleEnabled = (e?: Event) => {+ e?.stopPropagation();+ this.props.updateEffect(this.props.effect.id, {+ isEnabled: !this.props.effect.config.isEnabled+ });+ };++ _toggleConfigActive = (e?: Event) => {+ e?.stopPropagation();+ this.props.updateEffect(this.props.effect.id, {+ isConfigActive: !this.props.effect.config.isConfigActive+ });+ };++ _removeEffect = (e?: Event) => {+ e?.stopPropagation();+ this.props.removeEffect(this.props.effect.id);+ };++ _updateEffectConfig = (e, id, props) => {+ e?.stopPropagation();+ this.props.updateEffect(id, props);+ };++ render() {+ const {effect, isDraggable, listeners} = this.props;+ const {config = {} as EffectConfig} = effect;++ return (+ <PanelWrapper+ active={false}+ className={`effect-panel ${this.props.className}`}+ data-testid={dataTestIds.effectPanel}+ style={this.props.style}+ onMouseDown={this.props.onMouseDown}+ onTouchStart={this.props.onTouchStart}+ >+ <EffectPanelHeader+ isConfigActive={config.isConfigActive}+ effectId={effect.id}+ label={config.name}+ isEnabled={config.isEnabled}+ onToggleEnabled={this._toggleEnabled}+ onRemoveEffect={this._removeEffect}+ onToggleEnableConfig={this._toggleConfigActive}+ isDragNDropEnabled={isDraggable}+ listeners={listeners}+ showSortHandle={effect.type !== LIGHT_AND_SHADOW_EFFECT.type}+ />+ {config.isConfigActive && (+ <EffectConfigurator+ key={`effect-configurator-${effect.id}`}+ effect={effect}+ updateEffectConfig={this._updateEffectConfig}+ />+ )}+ </PanelWrapper>+ );+ }+ }++ // @ts-expect-error fix The types of 'propTypes.isDraggable[nominalTypeHack]' are incompatible between these types.+ return EffectPanel;+}++export default EffectPanelFactory;diff --git a/src/components/src/effects/effect-time-configurator.tsx b/src/components/src/effects/effect-time-configurator.tsxnew file mode 100644index 000000000..ccdec1f34--- /dev/null+++ b/src/components/src/effects/effect-time-configurator.tsx@@ -0,0 +1,191 @@+import React, {useCallback, useMemo} from 'react';+import styled from 'styled-components';++import {FormattedMessage} from '@kepler.gl/localization';+import {clamp} from '@kepler.gl/utils';++import {StyledTimePicker, StyledDatePicker, Tooltip} from '../common/styled-components';+import RangeSliderFactory from '../common/range-slider';+import Checkbox from '../common/checkbox';+import Button from '../common/data-table/button';+import {Pin} from '../common/icons';++const DAY_SLIDER_RANGE = 1000 * 60 * 60 * 24;++export type EffectTimeConfiguratorProps = {+ timestamp: string;+ onDateTimeChange: (time: number) => void;+ useCurrentTime: boolean;+ onUseCurrentTimeChange: (value: boolean) => void;+};++type StyledWrapperProps = {disabled?: boolean};+const StyledWrapper = styled.div<StyledWrapperProps>`+ display: flex;+ justify-content: space-between;+ align-items: center;+ padding-left: 5px;+ padding-right: 5px;+ margin-bottom: 9px;+ opacity: ${props => (props.disabled ? 0.3 : 1)};+ ${props => (props.disabled ? 'pointer-events: none;' : '')}+`;++type SliderWrapperProps = {disabled?: boolean};+const SliderWrapper = styled.div<SliderWrapperProps>`+ margin-top: 13px;+ margin-right: 8px;+ margin-bottom: 17px;++ opacity: ${props => (props.disabled ? 0.3 : 1)};+ ${props => (props.disabled ? 'pointer-events: none;' : '')}+`;++const StyledButton = styled(Button)`+ color: ${props => props.theme.textColor};+ background-color: ${props => props.theme.inputBgd};+ height: 31px;+ padding: 5px;+ border-radius: 2px;+ :hover {+ background-color: ${props => props.theme.inputBgdHover};+ }+`;++const StyledRadio = styled(Checkbox)`+ .kg-checkbox__label {+ font-family: ${props => props.theme.fontFamily};+ font-size: ${props => props.theme.inputFontSize};+ }+ .kg-checkbox__label:before {+ background-color: ${props => props.theme.inputBgdHover};+ }+`;++const StyledLabelWrapper = styled.div`+ color: ${props => props.theme.textColor};+ margin-right: 10px;+`;++const StyledEffectTimeConfigurator = styled.div`+ border-left: 3px solid ${props => props.theme.panelBorderColor};+ margin-bottom: 8px;+ margin-top: 3px;+ margin-left: 3px;+`;++EffectTimeConfiguratorFactory.deps = [RangeSliderFactory];++export default function EffectTimeConfiguratorFactory(+ RangeSlider: ReturnType<typeof RangeSliderFactory>+): React.FC<EffectTimeConfiguratorProps> {+ const EffectTimeConfigurator = ({+ timestamp,+ useCurrentTime,+ onDateTimeChange,+ onUseCurrentTimeChange+ }: EffectTimeConfiguratorProps) => {+ const [selectedDate, selectedTimeString] = useMemo(() => {+ const date = new Date(timestamp);++ const h = date.getHours();+ const m = date.getMinutes();+ const timeString = `${h < 10 ? `0${h}` : `${h}`}:${m < 10 ? `0${m}` : `${m}`}`;++ return [date, timeString];+ }, [timestamp]);++ const timeSliderValue = useMemo(() => {+ const base = new Date(timestamp).setHours(0, 0, 0).valueOf();+ return clamp([0, 1], (parseInt(timestamp) - base) / DAY_SLIDER_RANGE);+ }, [timestamp, selectedDate]);++ const timeSliderProps = useMemo(() => {+ return {+ label: 'value',+ value1: timeSliderValue,+ step: 0.001,+ range: [0, 1],+ value0: 0,+ onChange: value => {+ const start = new Date(timestamp).setHours(0, 0, 0).valueOf();+ onDateTimeChange(Math.floor(start + DAY_SLIDER_RANGE * clamp([0, 0.9999], value[1])));+ },+ showInput: false,+ isRanged: false+ };+ }, [timeSliderValue, timestamp, onDateTimeChange]);++ const setDate = useCallback(+ newDate => {+ onDateTimeChange(Math.floor(newDate.valueOf() + DAY_SLIDER_RANGE * timeSliderValue));+ },+ [timeSliderValue, onDateTimeChange]+ );++ const setTime = useCallback(+ time => {+ const conf = time.split(':');+ const start = new Date(timestamp).setHours(conf[0], conf[1]).valueOf();+ onDateTimeChange(start);+ },+ [timestamp, onDateTimeChange]+ );++ const setCurrentDateTime = useCallback(() => {+ onDateTimeChange(new Date().valueOf());+ }, [onDateTimeChange]);++ return (+ <StyledEffectTimeConfigurator>+ <StyledWrapper>+ <StyledRadio+ type="radio"+ checked={!useCurrentTime}+ id={`effect-time-toggle-use-pick`}+ label={'Pick date/time'}+ onChange={() => {+ onUseCurrentTimeChange(false);+ }}+ />+ </StyledWrapper>+ <StyledWrapper disabled={useCurrentTime}>+ <StyledButton onClick={setCurrentDateTime} data-for="pick-time-button" data-tip>+ <Pin height="15px" />+ <Tooltip id="pick-time-button" effect="solid" place="top" delayShow={500}>+ <FormattedMessage id={'Pick current time'} />+ </Tooltip>+ </StyledButton>+ <StyledDatePicker value={selectedDate} onChange={setDate} />+ <StyledTimePicker+ value={selectedTimeString}+ onChange={setTime}+ disableClock={true}+ format={'hh:mm a'}+ />+ <StyledLabelWrapper>+ <FormattedMessage id={'UTC'} />+ </StyledLabelWrapper>+ </StyledWrapper>++ <SliderWrapper disabled={useCurrentTime}>+ <RangeSlider {...timeSliderProps} />+ </SliderWrapper>++ <StyledWrapper>+ <StyledRadio+ type="radio"+ checked={useCurrentTime}+ id={`effect-time-toggle-use-current`}+ label={'Current time'}+ onChange={() => {+ onUseCurrentTimeChange(true);+ }}+ />+ </StyledWrapper>+ </StyledEffectTimeConfigurator>+ );+ };++ return EffectTimeConfigurator;+}diff --git a/src/components/src/effects/effect-type-selector.tsx b/src/components/src/effects/effect-type-selector.tsxnew file mode 100644index 000000000..42e026776--- /dev/null+++ b/src/components/src/effects/effect-type-selector.tsx@@ -0,0 +1,91 @@+import React, {useRef, useCallback} from 'react';+import styled from 'styled-components';++import {FormattedMessage} from '@kepler.gl/localization';+import {addEffect} from '@kepler.gl/actions';++import {Button} from '../common/styled-components';+import {Add} from '../common/icons';+import TippyTooltip from '../common/tippy-tooltip';++export type EffectTypeSelectorProps = {+ options: {type: string; name: string}[];+ onSelect: typeof addEffect;+};++const StyledTippyTooltipContentContainer = styled.div`+ background-color: ${props => props.theme.panelBackgroundHover};+ display: flex;+ flex-direction: column;+ align-items: start;+ margin: -7px -18px; /* compensate for kepler tippy parent padding */+ border-radius: 2px;+ .button {+ width: 100%;+ justify-content: start;+ color: ${props => props.theme.WHITE};+ }+`;++/** @type [number, number] */+const TIPPY_DURATION: [number, number] = [300, 0];+/** @type [number, number] */+const TIPPY_OFFSET: [number, number] = [0, 4];++function EffectTypeSelectorFactory(): React.FC<EffectTypeSelectorProps> {+ const EffectTypeSelector = ({onSelect, options}: EffectTypeSelectorProps) => {+ /** @type any */+ const tippyInstance = useRef(null);++ const render = useCallback(+ () => (+ <StyledTippyTooltipContentContainer>+ {options.map((effectDesc, idx) => {+ return (+ <Button+ key={`${effectDesc.type}-${idx}`}+ onClick={() => {+ onSelect({config: {type: effectDesc.type}});+ // @ts-expect-error type current+ tippyInstance.current?.hide();+ }}+ secondary+ >+ {effectDesc.name}+ </Button>+ );+ })}+ </StyledTippyTooltipContentContainer>+ ),+ [options, tippyInstance, tippyInstance.current, onSelect]+ );++ return (+ <TippyTooltip+ placement="bottom-start"+ offset={TIPPY_OFFSET}+ duration={TIPPY_DURATION}+ trigger="click"+ interactive={true}+ arrow={false}+ hideOnClick={true}+ onTrigger={instance => {+ // @ts-expect-error type current+ tippyInstance.current = instance;+ }}+ zIndex={999} // defaults to 9999; keep it below modals (1000)+ render={render}+ >+ <div>+ <Button className="add-effect-button" secondary>+ <Add height="12px" />+ <FormattedMessage id={'effectManager.addEffect'} />+ </Button>+ </div>+ </TippyTooltip>+ );+ };+ return EffectTypeSelector;+}++export default EffectTypeSelectorFactory;diff --git a/src/components/src/effects/side-panel-title.tsx b/src/components/src/effects/side-panel-title.tsxnew file mode 100644index 000000000..23155750a--- /dev/null+++ b/src/components/src/effects/side-panel-title.tsx@@ -0,0 +1,43 @@+import React, {PropsWithChildren} from 'react';+import styled from 'styled-components';++export type PanelTitleProps = PropsWithChildren<{+ title: string;+ className?: string;+}>;++type StyledSidePanelTitleProps = {className: string};+const StyledSidePanelTitle = styled.div.attrs<StyledSidePanelTitleProps>({+ className: 'panel-title'+})`+ color: ${props => props.theme.titleTextColor};+ font-size: ${props => props.theme.sidePanelTitleFontsize};+ line-height: ${props => props.theme.sidePanelTitleLineHeight};+ font-weight: 400;+ letter-spacing: 1.25px;+`;++const PanelHeaderRow = styled.div.attrs({+ className: 'side-panel-header-row'+})`+ display: flex;+ justify-content: space-between;+ align-items: center;+ margin-top: 0px;+ margin-bottom: 8px;+`;++const SidePanelTitleFactory = (): React.FC<PanelTitleProps> => {+ const SidePanelTitle = ({title, className, children}: PanelTitleProps) => (+ <PanelHeaderRow>+ <StyledSidePanelTitle className={className || 'side-panel-title'}>+ {title}+ </StyledSidePanelTitle>+ {children}+ </PanelHeaderRow>+ );++ return SidePanelTitle;+};++export default SidePanelTitleFactory;diff --git a/src/components/src/index.ts b/src/components/src/index.tsindex b2584e51e..8d577e98d 100644--- a/src/components/src/index.ts+++ b/src/components/src/index.ts@@ -222,6 +222,7 @@ export {default as AppLogo} from './common/logo';export {default as Switch} from './common/switch';export {default as Checkbox} from './common/checkbox';export {default as ColorLegend, LegendRow} from './common/color-legend';+export {default as EffectControlFactory} from './map/effects/effect-control';export {default as LoadingSpinner} from './common/loading-spinner';export {default as LoadingDialog} from './modals/loading-dialog';export {MapViewStateContext, MapViewStateContextProvider} from './map-view-state-context';@@ -259,6 +260,8 @@ export {} from './side-panel/layer-panel/layer-panel-header';export {default as FilterPanelHeaderFactory} from './side-panel/filter-panel/filter-panel-header';+export {default as EffectManagerFactory} from './effects/effect-manager';+export {default as HowToButton} from './side-panel/layer-panel/how-to-button';// eslint-disable-next-line prettier/prettierexport type {diff --git a/src/components/src/map-container.tsx b/src/components/src/map-container.tsxindex 97c29f165..2ebc5af3c 100644--- a/src/components/src/map-container.tsx+++ b/src/components/src/map-container.tsx@@ -63,7 +63,8 @@ import {onViewPortChange,getViewportFromMapState,normalizeEvent,- rgbToHex+ rgbToHex,+ computeDeckEffects} from '@kepler.gl/utils';import {breakPointValues} from '@kepler.gl/styles';@@ -539,6 +540,11 @@ export default function MapContainerFactory(}}+ _isOKToRenderEffects() {+ // TODO a hack to prevent effect preRender without valid generated viewports+ return Boolean(this._deck?.viewManager?._viewports?.length);+ }+_onBeforeRender = ({gl}) => {setLayerBlending(gl, this.props.visState.layerBlending);};@@ -785,6 +791,8 @@ export default function MapContainerFactory(};}+ const effects = this._isOKToRenderEffects() ? computeDeckEffects({visState, mapState}) : [];+const views = deckGlProps?.views? deckGlProps?.views(): new MapView({legacyMeterSizes: true});@@ -793,7 +801,8 @@ export default function MapContainerFactory(...deckGlProps,pickingRadius: DEFAULT_PICKING_RADIUS,views,- layers: deckGlLayers+ layers: deckGlLayers,+ effects};if (typeof deckRenderCallbacks?.onDeckRender === 'function') {diff --git a/src/components/src/map/effects/effect-control.tsx b/src/components/src/map/effects/effect-control.tsxnew file mode 100644index 000000000..460dcd204--- /dev/null+++ b/src/components/src/map/effects/effect-control.tsx@@ -0,0 +1,66 @@+import React, {useCallback, ComponentType} from 'react';++import {MapControls} from '@kepler.gl/types';++import {EyeSeen} from '../../common/icons';+import {MapControlButton} from '../../common/styled-components';+import MapControlTooltipFactory from '../map-control-tooltip';++interface EffectControlIcons {+ eyeSeen: ComponentType<any>;+}++export type EffectControlProps = {+ mapControls: MapControls;+ onToggleMapControl: (control: string) => void;+ actionIcons: EffectControlIcons;+};++EffectControlFactory.deps = [MapControlTooltipFactory];++export default function EffectControlFactory(+ MapControlTooltip: ReturnType<typeof MapControlTooltipFactory>+): React.FC<EffectControlProps> {+ const defaultActionIcons = {+ eyeSeen: EyeSeen+ };++ const EffectControl = ({+ mapControls,+ onToggleMapControl,+ actionIcons = defaultActionIcons+ }: EffectControlProps) => {+ const onClick = useCallback(+ event => {+ event.preventDefault();+ onToggleMapControl('effect');+ },+ [onToggleMapControl]+ );++ // TODO uncomment once effect related issues are fixed+ const showControl = false; // mapControls?.effect?.show;+ if (!showControl) {+ return null;+ }++ const active = mapControls?.effect?.active;+ return (+ <MapControlTooltip+ id="show-effect"+ message={active ? 'tooltip.hideEffectPanel' : 'tooltip.showEffectPanel'}+ >+ <MapControlButton+ className="map-control-button toggle-effect"+ onClick={onClick}+ active={active}+ >+ <actionIcons.eyeSeen height="22px" />+ </MapControlButton>+ </MapControlTooltip>+ );+ };++ EffectControl.displayName = 'EffectControl';+ return React.memo(EffectControl);+}diff --git a/src/constants/src/default-settings.ts b/src/constants/src/default-settings.tsindex 6cb3456cb..b1b25d2fc 100644--- a/src/constants/src/default-settings.ts+++ b/src/constants/src/default-settings.ts@@ -1117,7 +1117,8 @@ export const MAP_CONTROLS = keyMirror({toggle3d: null,splitMap: null,mapDraw: null,- mapLocale: null+ mapLocale: null,+ effect: null});/**@@ -1142,5 +1143,95 @@ export const dataTestIds: Record<string, string> = {staticLayerItem: 'static-layer-item',layerTitleEditor: 'layer__title__editor',removeLayerAction: 'remove-layer-action',- layerPanel: 'layer-panel'+ layerPanel: 'layer-panel',+ sortableEffectItem: 'sortable-effect-item',+ staticEffectItem: 'static-effect-item'};++// Effects++export const DEFAULT_EFFECT_TYPE = 'ink';++export const DEFAULT_LIGHT_COLOR: [number, number, number] = [255, 255, 255];+export const DEFAULT_LIGHT_INTENSITY = 1;+export const DEFAULT_SHADOW_INTENSITY = 0.5;+export const DEFAULT_SHADOW_COLOR: [number, number, number] = [0, 0, 0];+export const LIGHT_AND_SHADOW_EFFECT = {type: 'lightAndShadow', name: 'Light & Shadow'};+export const DEFAULT_LIGHT_AND_SHADOW_PROPS = {+ timestamp: Date.now(),+ useCurrentTime: false,+ shadowIntensity: DEFAULT_SHADOW_INTENSITY,+ shadowColor: [...DEFAULT_SHADOW_COLOR] as [number, number, number],+ sunLightColor: [...DEFAULT_LIGHT_COLOR] as [number, number, number],+ sunLightIntensity: DEFAULT_LIGHT_INTENSITY,+ ambientLightColor: [...DEFAULT_LIGHT_COLOR] as [number, number, number],+ ambientLightIntensity: DEFAULT_LIGHT_INTENSITY+};++export const POSTPROCESSING_EFFECTS: {[key: string]: {type: string; name: string}} = {+ ink: {+ type: 'ink',+ name: 'Ink'+ },+ brightnessContrast: {+ type: 'brightnessContrast',+ name: 'Brightness & Contrast'+ },+ hueSaturation: {+ type: 'hueSaturation',+ name: 'Hue & Saturation'+ },+ vibrance: {+ type: 'vibrance',+ name: 'Vibrance'+ },+ sepia: {+ type: 'sepia',+ name: 'Sepia'+ },+ dotScreen: {+ type: 'dotScreen',+ name: 'Dot Screen'+ },+ colorHalftone: {+ type: 'colorHalftone',+ name: 'Color Halftone'+ },+ noise: {+ type: 'noise',+ name: 'Noise'+ },+ triangleBlur: {+ type: 'triangleBlur',+ name: 'Blur (Triangle)'+ },+ zoomBlur: {+ type: 'zoomBlur',+ name: 'Blur (Zoom)'+ },+ tiltShift: {+ type: 'tiltShift',+ name: 'Blur (Tilt Shift)'+ },+ edgeWork: {+ type: 'edgeWork',+ name: 'Edge work'+ },+ vignette: {+ type: 'vignette',+ name: 'Vignette'+ },+ magnify: {+ type: 'magnify',+ name: 'Magnify'+ },+ hexagonalPixelate: {+ type: 'hexagonalPixelate',+ name: 'Hexagonal Pixelate'+ }+};++export const EFFECT_DESCS: {type: string; name: string}[] = [+ LIGHT_AND_SHADOW_EFFECT,+ ...Object.keys(POSTPROCESSING_EFFECTS).map(keyName => POSTPROCESSING_EFFECTS[keyName])+];diff --git a/src/constants/src/dnd-layer-items.ts b/src/constants/src/dnd-layer-items.tsindex d9347cd4c..bcfb5f840 100644--- a/src/constants/src/dnd-layer-items.ts+++ b/src/constants/src/dnd-layer-items.ts@@ -6,3 +6,6 @@ export const DND_EMPTY_MODIFIERS: Modifiers = [];export const SORTABLE_SIDE_PANEL_TYPE = 'root';export const DROPPABLE_MAP_CONTAINER_TYPE = 'map';export const SORTABLE_LAYER_TYPE = 'layer';++export const SORTABLE_EFFECT_PANEL_TYPE = 'root';+export const SORTABLE_EFFECT_TYPE = 'effect';diff --git a/src/effects/babel.config.js b/src/effects/babel.config.jsnew file mode 100644index 000000000..5edef63d4--- /dev/null+++ b/src/effects/babel.config.js@@ -0,0 +1,66 @@+// 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.++const KeplerPackage = require('./package');++const PRESETS = ['@babel/preset-env', '@babel/preset-react', '@babel/preset-typescript'];+const PLUGINS = [+ ['@babel/plugin-transform-typescript', {isTSX: true, allowDeclareFields: true}],+ '@babel/plugin-transform-modules-commonjs',+ '@babel/plugin-proposal-class-properties',+ '@babel/plugin-proposal-export-namespace-from',+ '@babel/plugin-proposal-optional-chaining',+ [+ '@babel/transform-runtime',+ {+ regenerator: true+ }+ ],+ [+ 'search-and-replace',+ {+ rules: [+ {+ search: '__PACKAGE_VERSION__',+ replace: KeplerPackage.version+ }+ ]+ }+ ]+];+const ENV = {+ test: {+ plugins: ['istanbul']+ },+ debug: {+ sourceMaps: 'inline',+ retainLines: true+ }+};++module.exports = function babel(api) {+ api.cache(true);++ return {+ presets: PRESETS,+ plugins: PLUGINS,+ env: ENV+ };+};diff --git a/src/effects/package.json b/src/effects/package.jsonnew file mode 100644index 000000000..02d98a709--- /dev/null+++ b/src/effects/package.json@@ -0,0 +1,55 @@+{+ "name": "@kepler.gl/effects",+ "author": "Shan He <[email protected]>",+ "version": "3.0.0-alpha.0",+ "description": "kepler.gl viaual effects",+ "license": "MIT",+ "main": "dist/index.js",+ "types": "dist/index.d.ts",+ "keywords": [+ "babel",+ "es6",+ "react",+ "webgl",+ "visualization",+ "deck.gl"+ ],+ "repository": {+ "type": "git",+ "url": "https://github.com/keplergl/kepler.gl.git"+ },+ "scripts": {+ "build": "rm -fr dist && babel src --out-dir dist --source-maps inline --extensions '.ts,.tsx,.js,.jsx' --ignore '**/*.d.ts'",+ "build:umd": "webpack --config ./webpack/umd.js --progress --env.prod",+ "build:types": "tsc --project ./tsconfig.production.json",+ "prepublish": "uber-licence && yarn build && yarn build:types",+ "stab": "mkdir -p dist && touch dist/index.js"+ },+ "files": [+ "dist",+ "umd"+ ],+ "dependencies": {+ "suncalc": "^1.9.0",+ "@deck.gl/core": "^8.9.12",+ "@luma.gl/shadertools": "^8.5.19",+ "@kepler.gl/utils": "3.0.0-alpha.0",+ "@kepler.gl/constants": "3.0.0-alpha.0",+ "@kepler.gl/types": "3.0.0-alpha.0"+ },+ "nyc": {+ "sourceMap": false,+ "instrument": false+ },+ "engines": {+ "node": ">=14.21.1"+ },+ "maintainers": [+ "Shan He <[email protected]>",+ "Giuseppe Macri <[email protected]>"+ ],+ "volta": {+ "node": "14.21.1",+ "yarn": "1.22.17"+ }+}diff --git a/src/effects/src/effect.ts b/src/effects/src/effect.tsnew file mode 100644index 000000000..3b80ccaeb--- /dev/null+++ b/src/effects/src/effect.ts@@ -0,0 +1,231 @@+import {+ PostProcessEffect,+ LightingEffect,+ AmbientLight,+ _SunLight as SunLight+} from '@deck.gl/core';+import {+ brightnessContrast,+ ink,+ triangleBlur,+ hueSaturation,+ vibrance,+ colorHalftone,+ dotScreen,+ edgeWork,+ noise,+ sepia,+ tiltShift,+ vignette,+ zoomBlur,+ magnify,+ hexagonalPixelate+} from '@luma.gl/shadertools';++import {generateHashId} from '@kepler.gl/utils';+import {+ LIGHT_AND_SHADOW_EFFECT,+ POSTPROCESSING_EFFECTS,+ EFFECT_DESCS,+ DEFAULT_LIGHT_AND_SHADOW_PROPS,+ DEFAULT_EFFECT_TYPE+} from '@kepler.gl/constants';+import {Effect as EffectInterface, EffectConfig, EffectParamsPartial} from '@kepler.gl/types';++const LIGHT_AND_SHADOW_EFFECT_DESC: {+ type: string;+ name: string;+ class: null;+} = {+ ...LIGHT_AND_SHADOW_EFFECT,+ class: null+};++const POSTPROCESSING_EFFECTS_DESCS = [+ {+ ...POSTPROCESSING_EFFECTS.ink,+ class: ink+ },+ {+ ...POSTPROCESSING_EFFECTS.brightnessContrast,+ class: brightnessContrast+ },+ {+ ...POSTPROCESSING_EFFECTS.hueSaturation,+ class: hueSaturation+ },+ {+ ...POSTPROCESSING_EFFECTS.vibrance,+ class: vibrance+ },+ {+ ...POSTPROCESSING_EFFECTS.sepia,+ class: sepia+ },+ {+ ...POSTPROCESSING_EFFECTS.dotScreen,+ class: dotScreen+ },+ {+ ...POSTPROCESSING_EFFECTS.colorHalftone,+ class: colorHalftone+ },+ {+ ...POSTPROCESSING_EFFECTS.noise,+ class: noise+ },+ {+ ...POSTPROCESSING_EFFECTS.triangleBlur,+ class: triangleBlur+ },+ {+ ...POSTPROCESSING_EFFECTS.zoomBlur,+ class: zoomBlur+ },+ {+ ...POSTPROCESSING_EFFECTS.tiltShift,+ class: tiltShift+ },+ {+ ...POSTPROCESSING_EFFECTS.edgeWork,+ class: edgeWork+ },+ {+ ...POSTPROCESSING_EFFECTS.vignette,+ class: vignette+ },+ {+ ...POSTPROCESSING_EFFECTS.magnify,+ class: magnify+ },+ {+ ...POSTPROCESSING_EFFECTS.hexagonalPixelate,+ class: hexagonalPixelate+ }+];++export function createDeckEffectFromConfig(params: Partial<EffectParamsPartial>): EffectInterface {+ return new Effect(params);+}++export class Effect implements EffectInterface {+ id: string;+ config: EffectConfig;+ deckEffect: PostProcessEffect | LightingEffect | null;++ constructor(props: EffectParamsPartial = {}) {+ this.id = props.id || `e_${generateHashId(6)}`;+ this.config = this.getDefaultEffectConfig(props.config);+ this.deckEffect = null;++ // TODO move to a separate class+ // Special case for shadow effect+ if (this.config.type === LIGHT_AND_SHADOW_EFFECT_DESC.type) {+ this._initializeLightAndShadowEffect();+ } else {+ this._initializePostProcessingEffect();+ }+ }++ _initializePostProcessingEffect() {+ // All other effects are PostProcessEffects+ const effectDesc = POSTPROCESSING_EFFECTS_DESCS.find(desc => desc.type === this.config.type);+ if (effectDesc) {+ this.deckEffect = new PostProcessEffect(effectDesc.class, this.config.params);++ // @ts-expect-error+ const uniforms = this.deckEffect?.module?.uniforms;+ if (uniforms) {+ // get default params+ const keys = Object.keys(uniforms);+ const defaultParams = {};+ keys.forEach(key => {+ defaultParams[key] = uniforms[key].value ?? uniforms[key];+ });+ this.config.params = {...defaultParams, ...this.config.params};+ }+ }+ }++ _initializeLightAndShadowEffect() {+ this.config.params = {...DEFAULT_LIGHT_AND_SHADOW_PROPS, ...this.config.params};++ const ambientLight = new AmbientLight({+ color: this.config.params.ambientLightColor,+ intensity: this.config.params.ambientLightIntensity+ });++ const sunLight = new SunLight({+ timestamp: this.config.params.timestamp,+ color: this.config.params.sunLightColor,+ intensity: this.config.params.sunLightIntensity,+ _shadow: true+ });++ this.deckEffect = new LightingEffect({+ ambientLight,+ sunLight+ });+ if (this.deckEffect) {+ // @ts-expect-error+ this.deckEffect.shadowColor[3] = this.config.params.shadowIntensity;+ }+ }++ getDefaultEffectConfig(config: Partial<EffectConfig> = {}) {+ const type = config.type || DEFAULT_EFFECT_TYPE;+ return {+ type,+ name: config.name || EFFECT_DESCS.find(desc => desc.type === type)?.name || 'Effect',+ isEnabled: config.isEnabled ?? true,+ isConfigActive: config.isConfigActive ?? true,+ params: {...(config.params || {})}+ };+ }++ updateConfig(config: Partial<EffectConfig>) {+ this.config = {+ ...this.config,+ ...config,+ params: {...this.config.params, ...(config.params || {})}+ };++ // any uniform updated?+ if (config.params) {+ const {params} = this.config;++ if (this.config.type === LIGHT_AND_SHADOW_EFFECT_DESC.type) {+ const effect = this.deckEffect as LightingEffect;+ if (effect) {+ // @ts-expect-error not typed+ effect.shadowColor[3] = params.shadowIntensity;+ // @ts-expect-error not typed+ effect.ambientLight.intensity = params.ambientLightIntensity;+ // @ts-expect-error not typed+ effect.ambientLight.color = params.ambientLightColor.slice();++ // @ts-expect-error not typed+ const sunLight = effect.directionalLights[0];+ if (sunLight) {+ sunLight.intensity = params.sunLightIntensity;+ sunLight.color = params.sunLightColor.slice();+ sunLight.timestamp = params.timestamp;+ }+ }+ } else {+ // @ts-expect-error not typed+ this.deckEffect?.setProps(params);+ }+ }+ }++ isValidToSave() {+ return Boolean(this.config.type && this.id && this.deckEffect);+ }++ get type() {+ return this.config.type;+ }+}++export default Effect;diff --git a/src/effects/src/index.ts b/src/effects/src/index.tsnew file mode 100644index 000000000..2f9fb1725--- /dev/null+++ b/src/effects/src/index.ts@@ -0,0 +1 @@+export {Effect, createDeckEffectFromConfig} from './effect';diff --git a/src/effects/tsconfig.production.json b/src/effects/tsconfig.production.jsonnew file mode 100644index 000000000..3c6aa0a93--- /dev/null+++ b/src/effects/tsconfig.production.json@@ -0,0 +1,31 @@+{+ "compilerOptions": {+ "target": "es2020",+ "allowJs": false,+ "checkJs": false,+ "jsx": "react",+ "module": "esnext",+ "moduleResolution": "node",+ "declaration": true,+ "emitDeclarationOnly": true,+ "noImplicitAny": false,+ "noImplicitReturns": true,+ "noImplicitThis": true,+ "noUnusedLocals": true,+ "outDir": "dist",+ "sourceMap": true,+ "strictNullChecks": true,+ "suppressImplicitAnyIndexErrors": false,+ "esModuleInterop": true,+ "allowSyntheticDefaultImports": true,+ "skipLibCheck": true,+ "strict": true,+ "resolveJsonModule": true,+ "isolatedModules": true,+ "baseUrl": "./src",+ "paths": {+ "*": ["*"]+ }+ },+ "include": ["src"]+}diff --git a/src/effects/webpack/umd.js b/src/effects/webpack/umd.jsnew file mode 100644index 000000000..d03af28a4--- /dev/null+++ b/src/effects/webpack/umd.js@@ -0,0 +1,120 @@+// 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.++const resolve = require('path').resolve;+const join = require('path').join;++// Import package.json to read version+const KeplerPackage = require('../package');++const SRC_DIR = resolve(__dirname, '../src');+const OUTPUT_DIR = resolve(__dirname, '../umd');++const LIBRARY_BUNDLE_CONFIG = env => ({+ entry: {+ KeplerGl: join(SRC_DIR, 'index.ts')+ },++ // Silence warnings about big bundles+ stats: {+ warnings: false+ },++ output: {+ // Generate the bundle in dist folder+ path: OUTPUT_DIR,+ filename: 'keplergl.min.js',+ globalObject: 'this',+ library: '[name]',+ libraryTarget: 'umd'+ },++ // let's put everything in+ externals: {+ react: {+ root: 'React',+ commonjs2: 'react',+ commonjs: 'react',+ amd: 'react',+ umd: 'react'+ },+ 'react-dom': {+ root: 'ReactDOM',+ commonjs2: 'react-dom',+ commonjs: 'react-dom',+ amd: 'react-dom',+ umd: 'react-dom'+ },+ redux: {+ root: 'Redux',+ commonjs2: 'redux',+ commonjs: 'redux',+ amd: 'redux',+ umd: 'redux'+ },+ 'react-redux': {+ root: 'ReactRedux',+ commonjs2: 'react-redux',+ commonjs: 'react-redux',+ amd: 'react-redux',+ umd: 'react-redux'+ },+ 'styled-components': {+ commonjs: 'styled-components',+ commonjs2: 'styled-components',+ amd: 'styled-components',+ root: 'styled'+ }+ },+ resolve: {+ extensions: ['.tsx', '.ts', '.js'],+ modules: ['node_modules', SRC_DIR]+ },+ module: {+ rules: [+ {+ test: /\.(js|ts|tsx)$/,+ loader: 'babel-loader',+ include: [SRC_DIR],+ options: {+ plugins: [+ [+ 'search-and-replace',+ {+ rules: [+ {+ search: '__PACKAGE_VERSION__',+ replace: KeplerPackage.version+ }+ ]+ }+ ]+ ]+ }+ }+ ]+ },++ node: {+ fs: 'empty'+ }+});++module.exports = env => LIBRARY_BUNDLE_CONFIG(env);diff --git a/src/localization/src/translations/en.ts b/src/localization/src/translations/en.tsindex 83b868a72..160080310 100644--- a/src/localization/src/translations/en.ts+++ b/src/localization/src/translations/en.ts@@ -186,6 +186,10 @@ export default {'3dBuildingColor': '3D Building Color',backgroundColor: 'Background Color'},+ effectManager: {+ effect: 'Effects',+ addEffect: 'Add effect'+ },layerConfiguration: {defaultDescription: 'Calculate {property} based on selected field',howTo: 'How to'@@ -232,7 +236,12 @@ export default {play: 'play',pause: 'pause',reset: 'reset',- export: 'export'+ export: 'export',+ showEffectPanel: 'Show effect panel',+ hideEffectPanel: 'Hide effect panel',+ removeEffect: 'Remove effect',+ disableEffect: 'Disable effect',+ effectSettings: 'Effect settings'},toolbar: {exportImage: 'Export Image',diff --git a/src/reducers/package.json b/src/reducers/package.jsonindex 2c6428f96..b50a08bc2 100644--- a/src/reducers/package.json+++ b/src/reducers/package.json@@ -35,6 +35,7 @@"@kepler.gl/constants": "3.0.0-alpha.0","@kepler.gl/deckgl-layers": "3.0.0-alpha.0","@kepler.gl/layers": "3.0.0-alpha.0",+ "@kepler.gl/effects": "3.0.0-alpha.0","@kepler.gl/localization": "3.0.0-alpha.0","@kepler.gl/processors": "3.0.0-alpha.0","@kepler.gl/schemas": "3.0.0-alpha.0",diff --git a/src/reducers/src/vis-state-merger.ts b/src/reducers/src/vis-state-merger.tsindex 3ee810edd..802377b16 100644--- a/src/reducers/src/vis-state-merger.ts+++ b/src/reducers/src/vis-state-merger.ts@@ -26,11 +26,13 @@ import {getInitialMapLayersForSplitMap,applyFiltersToDatasets,validateFiltersUpdateDatasets,- findById+ findById,+ mergeEffectParams} from '@kepler.gl/utils';import {getLayerOrderFromLayers} from '@kepler.gl/reducers';import {LayerColumns, LayerColumn, Layer} from '@kepler.gl/layers';+import {createDeckEffectFromConfig} from '@kepler.gl/effects';import {LAYER_BLENDINGS, OVERLAY_BLENDINGS} from '@kepler.gl/constants';import {CURRENT_VERSION, VisState, VisStateMergers, KeplerGLSchemaClass} from '@kepler.gl/schemas';@@ -41,7 +43,8 @@ import {TooltipInfo,SavedEditor,ParsedConfig,- Filter+ Filter,+ Effect as EffectType} from '@kepler.gl/types';import {KeplerTable, Datasets, assignGpuChannels, resetFilterGpuMode} from '@kepler.gl/table';@@ -448,6 +451,38 @@ export function mergeSplitMaps<S extends VisState>(};}+/**+ * Merge effects with saved config+ */+export function mergeEffects<S extends VisState>(+ state: S,+ effects: NonNullable<ParsedConfig['visState']>['effects'],+ fromConfig?: boolean+): S {+ const newEffects = [+ ...state.effects,+ ...(effects || [])+ .map(effect =>+ fromConfig+ ? // collapse all panels when loading effects++ createDeckEffectFromConfig(+ // @ts-expect-error+ mergeEffectParams(effect, {config: {isConfigActive: false}})+ )+ : (effect as EffectType)+ )+ .filter(effect => {+ return Boolean(effect && effect.isValidToSave());+ })+ ];+ return {+ ...state,+ effects: newEffects,+ effectOrder: newEffects.map(effect => effect.id)+ };+}+/*** Merge interactionConfig.tooltip with saved config,* validate fieldsToShow@@ -875,6 +910,10 @@ export const VIS_STATE_MERGERS: VisStateMergers<any> = [preserveOrder: 'preserveFilterOrder',replaceParentDatasetIds: replaceFilterDatasetIds},+ {+ merge: mergeEffects,+ prop: 'effects'+ },{merge: mergeInteractions,prop: 'interactionConfig',diff --git a/src/reducers/src/vis-state-updaters.ts b/src/reducers/src/vis-state-updaters.tsindex 1f1141444..cb769770b 100644--- a/src/reducers/src/vis-state-updaters.ts+++ b/src/reducers/src/vis-state-updaters.ts@@ -126,6 +126,8 @@ import {import {findFieldsToShow} from './interaction-utils';import {hasPropsToMerge, getPropValueToMerger} from './merger-handler';import {mergeDatasetsByOrder} from './vis-state-merger';+import {fixEffectOrder} from '@kepler.gl/utils';+import {createDeckEffectFromConfig} from '@kepler.gl/effects';// react-palm// disable capture exception for react-palm call to withTask@@ -251,6 +253,10 @@ export const INITIAL_VIS_STATE: VisState = {datasets: {},editingDataset: undefined,+ // effects+ effects: [],+ effectOrder: [],+interactionConfig: defaultInteractionConfig,interactionToBeMerged: {},@@ -1427,6 +1433,92 @@ export const duplicateLayerUpdater = (return updateAnimationDomain(nextState);};+/**+ * Add a new effect+ * @memberof visStateUpdaters+ * @public+ */+export const addEffectUpdater = (+ state: VisState,+ action: VisStateActions.AddEffectUpdaterAction+): VisState => {+ const newEffect = createDeckEffectFromConfig(action.config);++ // collapse configurators for other effects+ state.effects.forEach(effect => effect.updateConfig({isConfigActive: false}));++ const effects = [...state.effects, newEffect];+ const effectOrder = fixEffectOrder(effects, [newEffect.id, ...state.effectOrder]);++ return {+ ...state,+ effects,+ effectOrder+ };+};++/**+ * remove effect+ * @memberof visStateUpdaters+ * @public+ */+export const removeEffectUpdater = (+ state: VisState,+ {id}: VisStateActions.RemoveEffectUpdaterAction+): VisState => {+ const idx = state.effects.findIndex(l => l.id === id);+ if (idx < 0 || idx >= state.effects.length) {+ Console.warn(`can not remove effect with invalid id ${id}`);+ return state;+ }++ const {effects, effectOrder} = state;+ const effectToRemove = effects[idx];+ return {+ ...state,+ // @ts-expect-error fixed in ts+ effects: filterOutById(effectToRemove.id)(effects),+ effectOrder: effectOrder.filter(effectId => effectId !== effectToRemove.id)+ };+};++/**+ * Reorder effect+ * @memberof visStateUpdaters+ * @public+ */+export const reorderEffectUpdater = (+ state: VisState,+ {order}: VisStateActions.ReorderEffectUpdaterAction+): VisState => ({+ ...state,+ effectOrder: fixEffectOrder(state.effects, [...order])+});++/**+ * Update effect+ * @memberof visStateUpdaters+ * @public+ */+export const updateEffectUpdater = (+ state: VisState,+ {id, props}: VisStateActions.UpdateEffectUpdaterAction+): VisState => {+ const idx = state.effects.findIndex(l => l.id === id);+ if (idx < 0 || idx >= state.effects.length) {+ Console.warn(`can not update effect with invalid id ${id}`);+ return state;+ }++ const newEffects = [...state.effects];+ newEffects[idx].updateConfig(props);++ return {+ ...state,+ effects: newEffects+ };+};+/*** Remove a dataset and all layers, filters, tooltip configs that based on it* @memberof visStateUpdatersdiff --git a/src/reducers/src/vis-state.ts b/src/reducers/src/vis-state.tsindex 1d48cd17f..f7633c027 100644--- a/src/reducers/src/vis-state.ts+++ b/src/reducers/src/vis-state.ts@@ -152,7 +152,16 @@ const actionHandler = {[ActionTypes.PROCESS_FILE_CONTENT]: visStateUpdaters.processFileContentUpdater,- [ActionTypes.SET_LAYER_ANIMATION_TIME_CONFIG]: visStateUpdaters.setLayerAnimationTimeConfigUpdater+ [ActionTypes.SET_LAYER_ANIMATION_TIME_CONFIG]:+ visStateUpdaters.setLayerAnimationTimeConfigUpdater,++ [ActionTypes.ADD_EFFECT]: visStateUpdaters.addEffectUpdater,++ [ActionTypes.REORDER_EFFECT]: visStateUpdaters.reorderEffectUpdater,++ [ActionTypes.REMOVE_EFFECT]: visStateUpdaters.removeEffectUpdater,++ [ActionTypes.UPDATE_EFFECT]: visStateUpdaters.updateEffectUpdater};// construct vis-state reducerdiff --git a/src/schemas/src/vis-state-schema.ts b/src/schemas/src/vis-state-schema.tsindex b6c0a8edc..93dafbd24 100644--- a/src/schemas/src/vis-state-schema.ts+++ b/src/schemas/src/vis-state-schema.ts@@ -43,7 +43,8 @@ import {MinSavedLayer,SavedVisState,SplitMap,- ValueOf+ ValueOf,+ Effect} from '@kepler.gl/types';import {Datasets} from '@kepler.gl/table';import {Layer, LayerClassesType} from '@kepler.gl/layers';@@ -69,6 +70,8 @@ export interface VisState {layerData: any[];layerToBeMerged: any[];layerOrder: string[];+ effects: Effect[];+ effectOrder: string[];filters: Filter[];filterToBeMerged: any[];datasets: Datasets;@@ -782,6 +785,46 @@ export class SplitMapsSchema extends Schema {}}+export const effectPropsV1 = {+ id: null,+ config: new Schema({+ version: VERSIONS.v1,+ key: 'config',+ properties: {+ type: null,+ isEnabled: null,+ params: null+ }+ })+};+export class EffectsSchema extends Schema {+ key = 'effects';++ save(effects, parents) {+ const [visState] = parents.slice(-1);++ return {+ [this.key]: visState.effectOrder.reduce((saved, effectId) => {+ // save effects according to their rendering order+ /**+ * @type {Effect | undefined}+ */+ const effect = findById(effectId)(effects as Effect[]);+ if (effect?.isValidToSave()) {+ saved.push(this.savePropertiesOrApplySchema(effect).effects);+ }+ return saved;+ }, [])+ };+ }++ load(effects) {+ return {+ [this.key]: effects.map(effect => this.loadPropertiesOrApplySchema(effect, effects).effects)+ };+ }+}+export const filterPropsV1 = {...filterPropsV0,plotType: null,@@ -830,6 +873,10 @@ export const propertiesV1 = {version: VERSIONS.v1,properties: layerPropsV1}),+ effects: new EffectsSchema({+ version: VERSIONS.v1,+ properties: effectPropsV1+ }),interactionConfig: new InteractionSchemaV1({version: VERSIONS.v1,properties: interactionPropsV1diff --git a/src/styles/src/base.ts b/src/styles/src/base.tsindex 7ffc0fa9e..685f2d7c1 100644--- a/src/styles/src/base.ts+++ b/src/styles/src/base.ts@@ -472,6 +472,10 @@ export const breakPoints = {desk: 768};+// effectConfigurator+export const effectConfiguratorMargin = '6px';+export const effectConfiguratorPadding = '8px 0px 8px 5px';+// theme is passed to kepler.gl when it's mounted,// it is used by styled-components to pass along to// all child components@@ -1541,10 +1545,22 @@ export const theme = {layerConfiguratorMargin,layerConfiguratorPadding,+ // effectConfigurator+ effectConfiguratorMargin,+ effectConfiguratorPadding,+// Styled tokenfieldTokenRightMargin,fieldTokenHeight,- fieldTokenWidth+ fieldTokenWidth,++ // Effects+ effectPanelWidth: 345,+ effectPanelHeight: 180,+ effectPanelPaddingSide: 16,+ effectPanelPaddingTop: 16,+ rightPanelMarginTop: 12,+ rightPanelMarginRight: 12};export const themeLT = {diff --git a/src/types/effects.d.ts b/src/types/effects.d.tsnew file mode 100644index 000000000..eaa2851e2--- /dev/null+++ b/src/types/effects.d.ts@@ -0,0 +1,29 @@+export type EffectConfig = {+ type: string;+ name: string;+ isEnabled: boolean;+ isConfigActive: boolean;+ // effect specific params for a deck.gl effect (uniforms)+ params: {[key: string]: any};+};++export type EffectParams = {+ id: string;+ config: EffectConfig;+};++export type EffectParamsPartial = {+ id?: string;+ config?: Partial<EffectConfig>+};++export interface Effect {+ id: string;+ config: EffectConfig;+ deckEffect: any;++ getDefaultEffectConfig(config: Partial<EffectConfig>): EffectConfig;+ updateConfig(config: Partial<EffectConfig>): void;+ isValidToSave(): boolean;+ get type(): string;+}diff --git a/src/types/index.d.ts b/src/types/index.d.tsindex 7d1716dce..ecf48f208 100644--- a/src/types/index.d.ts+++ b/src/types/index.d.ts@@ -4,3 +4,4 @@ export * from './actions';export * from './schemas';export * from './types';export * from './components';+export * from './effects';diff --git a/src/types/reducers.d.ts b/src/types/reducers.d.tsindex f69690473..e8ec96e39 100644--- a/src/types/reducers.d.ts+++ b/src/types/reducers.d.ts@@ -366,6 +366,7 @@ export type MapControls = {splitMap?: MapControlItem;mapDraw?: MapControlItem;mapLocale?: MapControlItem;+ effect?: MapControlItem;};export type LoadFiles = {diff --git a/src/types/schemas.d.ts b/src/types/schemas.d.tsindex 827ecc050..0066e397c 100644--- a/src/types/schemas.d.ts+++ b/src/types/schemas.d.ts@@ -11,6 +11,8 @@ import {import {LayerTextLabel} from './layers';+import {EffectConfig} from './effects';+export type SavedFilter = {dataId: Filter['dataId'];id: Filter['id'];@@ -78,6 +80,11 @@ export type MinSavedLayer = {};export type ParsedLayer = SavedLayer | MinSavedLayer;+export type ParsedEffect = {+ id: string;+ config: EffectConfig;+};+export type SavedAnimationConfig = {currentTime: AnimationConfig['currentTime'];speed: AnimationConfig['speed'];@@ -113,6 +120,7 @@ export type MinSavedVisStateV1 = {export type ParsedVisState = {layers?: ParsedLayer[];+ effects?: ParsedEffect[];filters?: ParsedFilter[];interactionConfig?: Partial<SavedInteractionConfig>;layerBlending?: string;diff --git a/src/utils/src/effect-utils.ts b/src/utils/src/effect-utils.tsnew file mode 100644index 000000000..007b22817--- /dev/null+++ b/src/utils/src/effect-utils.ts@@ -0,0 +1,89 @@+import {arrayMove} from '@dnd-kit/sortable';+import SunCalc from 'suncalc';++import {PostProcessEffect} from '@deck.gl/core/typed';++import {LIGHT_AND_SHADOW_EFFECT} from '@kepler.gl/constants';+import {findById} from './utils';+import {VisState} from '@kepler.gl/schemas';+import {MapState, EffectParams, Effect} from '@kepler.gl/types';++export function computeDeckEffects({+ visState,+ mapState+}: {+ visState: VisState;+ mapState: MapState;+}): PostProcessEffect[] {+ let effects = visState.effectOrder+ .map(effectId => {+ return findById(effectId)(visState.effects);+ })+ .filter(effect => Boolean(effect && effect.config.isEnabled && effect.deckEffect)) as Effect[];++ const lightShadowEffect = effects.find(effect => effect.type === LIGHT_AND_SHADOW_EFFECT.type);+ if (lightShadowEffect) {+ const {timestamp} = lightShadowEffect.config.params;+ if (!isDaytime(mapState.latitude, mapState.longitude, timestamp)) {+ // TODO: interpolate for dusk/dawn+ // TODO: Should we avoid mutating the effect? (didn't work when tried defensive copying)+ lightShadowEffect.deckEffect.shadowColor[3] = 0;+ }+ }+ return effects.map(effect => effect.deckEffect);+}++export function mergeEffectParams(+ params: Partial<EffectParams>,+ extraParams: Partial<EffectParams>+): Partial<EffectParams> {+ const p1 = params || {};+ const p2 = extraParams || {};+ return {+ ...p1,+ ...p2,+ // @ts-expect-error+ config: {+ ...(p1.config || {}),+ ...(p2.config || {})+ }+ };+}++/**+ * Always keep light & shadow effect at the top+ */+export const fixEffectOrder = (effects: Effect[], effectOrder: string[]): string[] => {+ const lightShadowEffect = effects.find(effect => effect.type === LIGHT_AND_SHADOW_EFFECT.type);+ if (lightShadowEffect) {+ const ind = effectOrder.indexOf(lightShadowEffect.id);+ if (ind > 0) {+ effectOrder.splice(ind, 1);+ effectOrder.unshift(lightShadowEffect.id);+ }+ }+ return effectOrder;+};++export function reorderEffectOrder(+ effectOrder: string[],+ originEffectId: string,+ destinationEffectId: string+): string[] {+ const activeIndex = effectOrder.indexOf(originEffectId);+ const overIndex = effectOrder.indexOf(destinationEffectId);+ return arrayMove(effectOrder, activeIndex, overIndex);+}++/**+ * Check if the current time is daytime at the given location+ * @param {number} lat Latitude+ * @param {number} lon Longitude+ * @param {number} timestamp Milliseconds since the Unix Epoch+ * @returns boolean+ */+function isDaytime(lat, lon, timestamp) {+ const date = new Date(timestamp);+ const {sunrise, sunset} = SunCalc.getTimes(date, lat, lon);+ return date >= sunrise && date <= sunset;+}diff --git a/src/utils/src/index.ts b/src/utils/src/index.tsindex 6c84db3b5..10e32be99 100644--- a/src/utils/src/index.ts+++ b/src/utils/src/index.ts@@ -97,6 +97,8 @@ export * from './utils';export * from './split-map-utils';export {snapToMarks} from './plot';+export {computeDeckEffects, fixEffectOrder, mergeEffectParams, reorderEffectOrder} from './effect-utils';+// Mapboxexport {transformRequest, isStyleUsingMapboxTiles} from './map-style-utils/mapbox-utils';diff --git a/src/utils/src/noop.ts b/src/utils/src/noop.tsnew file mode 100644index 000000000..ca6a74471--- /dev/null+++ b/src/utils/src/noop.ts@@ -0,0 +1 @@+export default function noop() {}diff --git a/test/node/reducers/vis-state-test.js b/test/node/reducers/vis-state-test.jsindex d24725ca6..f0385e1c0 100644--- a/test/node/reducers/vis-state-test.js+++ b/test/node/reducers/vis-state-test.js@@ -2880,6 +2880,8 @@ test('#visStateReducer -> REMOVE_DATASET w filter and layer', t => {datasets: {[testGeoJsonDataId]: oldState.datasets[testGeoJsonDataId]},+ effects: [],+ effectOrder: [],interactionConfig: {tooltip: {@@ -3127,6 +3129,8 @@ test('#visStateReducer -> SPLIT_MAP: REMOVE_DATASET', t => {[testCsvDataId]: oldState.datasets[testCsvDataId]},filters: [],+ effects: [],+ effectOrder: [],interactionConfig: {tooltip: {id: 'tooltip',diff --git a/test/node/schemas/vis-state-schema-test.js b/test/node/schemas/vis-state-schema-test.jsindex fa553c23e..9cc8889bd 100644--- a/test/node/schemas/vis-state-schema-test.js+++ b/test/node/schemas/vis-state-schema-test.js@@ -44,6 +44,7 @@ import {VisStateActions} from '@kepler.gl/actions';const expectedVisStateEntries = ['filters','layers',+ 'effects','interactionConfig','layerBlending','overlayBlending',diff --git a/yarn.lock b/yarn.lockindex abfba1566..f52df80b0 100644--- a/yarn.lock+++ b/yarn.lock@@ -2379,7 +2379,7 @@"@probe.gl/log" "^3.5.0""@types/offscreencanvas" "^2019.7.0"-"@luma.gl/[email protected]", "@luma.gl/shadertools@^8.5.21":+"@luma.gl/[email protected]", "@luma.gl/shadertools@^8.5.19", "@luma.gl/shadertools@^8.5.21":version "8.5.19"resolved "https://registry.yarnpkg.com/@luma.gl/shadertools/-/shadertools-8.5.19.tgz#719a9612092ec0bed8a236e4f4f5592f07da7412"integrity sha512-Jn/gCAagMA9Rl4/AtKrdghRwWT8dCO2XBGI+WE5HPZPP2anTzN7DgDxUwKf+vEH8fFNOsr+jLdUXubIrRU3vTw==@@ -4271,6 +4271,11 @@"@webassemblyjs/wast-parser" "1.9.0""@xtuc/long" "4.2.2"+"@wojtekmaj/date-utils@^1.1.3", "@wojtekmaj/date-utils@^1.5.0":+ version "1.5.0"+ resolved "https://registry.yarnpkg.com/@wojtekmaj/date-utils/-/date-utils-1.5.0.tgz#6e8e5be857f3b66d0a99876e4c2295f1009a7560"+ integrity sha512-0mq88lCND6QiffnSDWp+TbOxzJSwy2V/3XN+HwWZ7S2n19QAgR5dy5hRVhlECXvQIq2r+VcblBu+S9V+yMcxXw==+"@xmldom/xmldom@^0.7.13":version "0.7.13"resolved "https://registry.yarnpkg.com/@xmldom/xmldom/-/xmldom-0.7.13.tgz#ff34942667a4e19a9f4a0996a76814daac364cf3"@@ -5965,6 +5970,11 @@ clsx@^1.0.4:resolved "https://registry.yarnpkg.com/clsx/-/clsx-1.1.1.tgz#98b3134f9abbdf23b2663491ace13c5c03a73188"integrity sha512-6/bPho624p3S2pMyvP5kKBPXnI3ufHLObBFCfgx+LkeR5lg2XYy2hqZqUf45ypD8COn2bhgGJSUE+l5dhNBieA==+clsx@^2.0.0:+ version "2.0.0"+ resolved "https://registry.yarnpkg.com/clsx/-/clsx-2.0.0.tgz#12658f3fd98fafe62075595a5c30e43d18f3d00b"+ integrity sha512-rQ1+kcj+ttHG0MKVGBUXwayCCF1oh39BF5COIpRzuCEv8Mwjv0XucrI2ExNTOn9IlLifGClWQcU9BrZORvtw6Q==+co@^4.6.0:version "4.6.0"resolved "https://registry.yarnpkg.com/co/-/co-4.6.0.tgz#6ea6bdf3d853ae54ccb8e47bfa0bf3f9031fb184"@@ -7007,6 +7017,11 @@ detab@^2.0.0:dependencies:repeat-string "^1.5.4"+detect-element-overflow@^1.4.0:+ version "1.4.1"+ resolved "https://registry.yarnpkg.com/detect-element-overflow/-/detect-element-overflow-1.4.1.tgz#fc2ff7eb04c03090b289abe45a447b2c78b983b6"+ integrity sha512-6a1wXl5+KbnXhO5FWgKq+omp8km42QLWgd1UYj99SS6o/aYBuTPU/ByI9dLgPYi9aes5TAg62IRoRKpqrDb0PQ==+detect-file@^1.0.0:version "1.0.0"resolved "https://registry.yarnpkg.com/detect-file/-/detect-file-1.0.0.tgz#f0d66d03672a825cb1b73bdb3fe62310c8e552b7"@@ -8966,6 +8981,14 @@ get-symbol-description@^1.0.0:call-bind "^1.0.2"get-intrinsic "^1.1.1"+get-user-locale@^2.2.1:+ version "2.3.0"+ resolved "https://registry.yarnpkg.com/get-user-locale/-/get-user-locale-2.3.0.tgz#7656315a963a824048883f7dab4d7dc74773d1e0"+ integrity sha512-I3rQvAUwu2nauRD9YyQBSXVFJZixNouwA+eZld51Sn4Pn0N1qFbgcgOi/nPigJPQlNY519mT95fiSPRgflQiTA==+ dependencies:+ "@types/lodash.memoize" "^4.1.7"+ lodash.memoize "^4.1.1"+get-value@^2.0.3, get-value@^2.0.6:version "2.0.6"resolved "https://registry.yarnpkg.com/get-value/-/get-value-2.0.6.tgz#dc15ca1c672387ca76bd37ac0a395ba2042a2c28"@@ -11604,7 +11627,7 @@ lodash.isplainobject@^4.0.6:resolved "https://registry.yarnpkg.com/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz#7c526a52d89b45c45cc690b88163be0497f550cb"integrity sha1-fFJqUtibRcRcxpC4gWO+BJf1UMs=[email protected], lodash.memoize@^4.1.2:[email protected], lodash.memoize@^4.1.1, lodash.memoize@^4.1.2:version "4.1.2"resolved "https://registry.yarnpkg.com/lodash.memoize/-/lodash.memoize-4.1.2.tgz#bcc6c49a42a2840ed997f323eada5ecd182e0bfe"integrity sha1-vMbEmkKihA7Zl/Mj6tpezRguC/4=@@ -11740,6 +11763,11 @@ make-dir@^3.0.0, make-dir@^3.0.2, make-dir@^3.1.0:dependencies:semver "^6.0.0"+make-event-props@^1.6.0:+ version "1.6.1"+ resolved "https://registry.yarnpkg.com/make-event-props/-/make-event-props-1.6.1.tgz#1d587017c3f1f3b42719b775af93d5253656ccdd"+ integrity sha512-JhvWq/iz1BvlmnPvLJjXv+xnMPJZuychrDC68V+yCGQJn5chcA8rLGKo5EP1XwIKVrigSXKLmbeXAGkf36wdCQ==+version "1.0.12"resolved "https://registry.yarnpkg.com/makeerror/-/makeerror-1.0.12.tgz#3e5dd2079a82e812e983cc6610c4a2cb0eaa801a"@@ -14082,6 +14110,27 @@ [email protected]:resolved "https://registry.yarnpkg.com/re-emitter/-/re-emitter-1.1.3.tgz#fa9e319ffdeeeb35b27296ef0f3d374dac2f52a7"integrity sha1-+p4xn/3u6zWycpbvDz03TawvUqc=+react-calendar@^4.6.0:+ version "4.6.0"+ resolved "https://registry.yarnpkg.com/react-calendar/-/react-calendar-4.6.0.tgz#2410895ba5f257f931815ffa74af06ff7a56d2e3"+ integrity sha512-GJ6ZipKMQmlK666t+0hgmecu6WHydEnMWJjKdEkUxW6F471hiM5DkbWXkfr8wlAg9tc9feNCBhXw3SqsPOm01A==+ dependencies:+ "@wojtekmaj/date-utils" "^1.1.3"+ clsx "^2.0.0"+ get-user-locale "^2.2.1"+ prop-types "^15.6.0"+ tiny-warning "^1.0.0"++react-clock@^4.5.0:+ version "4.5.0"+ resolved "https://registry.yarnpkg.com/react-clock/-/react-clock-4.5.0.tgz#fa4b9c6066c87177f8a5196d8ca30c9fa62fd68d"+ integrity sha512-0LnNG1NbEOOl0M4v3Ul1D/4U1898S3JIc5GMunR6PGMv+ntGqOV/flV9MbIIXoFu8TEgS6xC/RVHZWCmaKJXhA==+ dependencies:+ "@wojtekmaj/date-utils" "^1.5.0"+ clsx "^2.0.0"+ get-user-locale "^2.2.1"+ prop-types "^15.6.0"+react-color@^2.17.3:version "2.19.3"resolved "https://registry.yarnpkg.com/react-color/-/react-color-2.19.3.tgz#ec6c6b4568312a3c6a18420ab0472e146aa5683d"@@ -14103,6 +14152,20 @@ react-copy-to-clipboard@^5.0.2:copy-to-clipboard "^3"prop-types "^15.5.8"+react-date-picker@^10.2.0:+ version "10.5.1"+ resolved "https://registry.yarnpkg.com/react-date-picker/-/react-date-picker-10.5.1.tgz#20fb38937ffe3a55fb5519b63b493c5265571ccc"+ integrity sha512-Ipsq0NorPqXRuZQsqWhdd86RlSbZbnhpiH0aEMzJo6Rs2YA7eALZKB5lrl9stSjpDriDJH0dyh2kdWQmkBhNFg==+ dependencies:+ "@wojtekmaj/date-utils" "^1.1.3"+ clsx "^2.0.0"+ get-user-locale "^2.2.1"+ make-event-props "^1.6.0"+ prop-types "^15.6.0"+ react-calendar "^4.6.0"+ react-fit "^1.7.0"+ update-input-width "^1.4.0"+react-dom@^16.4.2:version "16.14.0"resolved "https://registry.yarnpkg.com/react-dom/-/react-dom-16.14.0.tgz#7ad838ec29a777fb3c75c3a190f661cf92ab8b89"@@ -14121,6 +14184,15 @@ react-dom@^18.2.0:loose-envify "^1.1.0"scheduler "^0.23.0"+react-fit@^1.7.0:+ version "1.7.0"+ resolved "https://registry.yarnpkg.com/react-fit/-/react-fit-1.7.0.tgz#0d0c5614cff691028357f748efc7a6e853e3c654"+ integrity sha512-mp1zCayzmCXrTYoSZjBGaN/VkYZ+QwMXm52Jh33au+bgrLoC7sn2XND1TOh2VZ/vqZ2MgpPjGcygCQ+7p514cQ==+ dependencies:+ detect-element-overflow "^1.4.0"+ prop-types "^15.6.0"+ tiny-warning "^1.0.0"+react-hot-loader@^4.13.0:version "4.13.0"resolved "https://registry.yarnpkg.com/react-hot-loader/-/react-hot-loader-4.13.0.tgz#c27e9408581c2a678f5316e69c061b226dc6a202"@@ -14330,6 +14402,20 @@ react-test-renderer@^18.2.0:react-shallow-renderer "^16.15.0"scheduler "^0.23.0"+react-time-picker@^6.2.0:+ version "6.5.1"+ resolved "https://registry.yarnpkg.com/react-time-picker/-/react-time-picker-6.5.1.tgz#f231fba6b10a7562a0c066bd5cd3353ed191b306"+ integrity sha512-8CLWWMNrx19GpHD3JQ5u5Cyqu3TmdFe+w5NQgInK9B3Vz6BkmqZC3fUQ8bQ4KbsjR21aqK1N6lEcJM2ARTQKkw==+ dependencies:+ "@wojtekmaj/date-utils" "^1.1.3"+ clsx "^2.0.0"+ get-user-locale "^2.2.1"+ make-event-props "^1.6.0"+ prop-types "^15.6.0"+ react-clock "^4.5.0"+ react-fit "^1.7.0"+ update-input-width "^1.4.0"+react-tooltip@^4.2.17:version "4.2.17"resolved "https://registry.yarnpkg.com/react-tooltip/-/react-tooltip-4.2.17.tgz#4884ce253ab298ee395950b24b752282efa8ac5d"@@ -16374,6 +16460,11 @@ sugarss@^2.0.0:dependencies:postcss "^7.0.2"+suncalc@^1.9.0:+ version "1.9.0"+ resolved "https://registry.yarnpkg.com/suncalc/-/suncalc-1.9.0.tgz#26212353fae61edb287c2d558fc4932ecf0e1532"+ integrity sha512-vMJ8Byp1uIPoj+wb9c1AdK4jpkSKVAywgHX0lqY7zt6+EWRRC3Z+0Ucfjy/0yxTVO1hwwchZe4uoFNqrIC24+A==+supercluster@^7.1.0:version "7.1.2"resolved "https://registry.yarnpkg.com/supercluster/-/supercluster-7.1.2.tgz#cf02a60283a0118212024f3bf02e4e63bb148e2c"@@ -16667,6 +16758,11 @@ tiny-lr@^1.1.0:object-assign "^4.1.0"qs "^6.4.0"+tiny-warning@^1.0.0:+ version "1.0.3"+ resolved "https://registry.yarnpkg.com/tiny-warning/-/tiny-warning-1.0.3.tgz#94a30db453df4c643d0fd566060d60a875d84754"+ integrity sha512-lBN9zLN/oAf68o3zNXYrdCt1kP8WsiGW8Oo2ka41b2IM5JL/S1CTyX1rW0mb/zSuJun0ZUrDxx4sqvYS2FWzPA==+tinycolor2@^1.4.1:version "1.4.2"resolved "https://registry.yarnpkg.com/tinycolor2/-/tinycolor2-1.4.2.tgz#3f6a4d1071ad07676d7fa472e1fac40a719d8803"@@ -17320,6 +17416,11 @@ update-browserslist-db@^1.0.9:escalade "^3.1.1"picocolors "^1.0.0"+update-input-width@^1.4.0:+ version "1.4.1"+ resolved "https://registry.yarnpkg.com/update-input-width/-/update-input-width-1.4.1.tgz#94636ef786da0a33581091c57d3a3c66d9fdcbd2"+ integrity sha512-/FDlfTvxlEQ9+/duf5PoC1q0uYQd/nE4w7K7rVAAoW/QKKa4bdhccuPaWtfkrWEy2r08rzX6wlmCHeGL+vgJOw==+update-notifier@^1.0.3:version "1.0.3"resolved "https://registry.yarnpkg.com/update-notifier/-/update-notifier-1.0.3.tgz#8f92c515482bd6831b7c93013e70f87552c7cf5a"