Skip to content

Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.

chore: Convert class components to functional components (#3441)

Igor Dykhta80882a2caf98
diff --git a/src/components/src/effects/effect-panel.tsx b/src/components/src/effects/effect-panel.tsx
index 05fc9eacc..7abb70b8f 100644
--- a/src/components/src/effects/effect-panel.tsx
+++ b/src/components/src/effects/effect-panel.tsx
@@ -1,13 +1,12 @@
// SPDX-License-Identifier: MIT
// Copyright contributors to the kepler.gl project
-import React, {Component, ComponentType} from 'react';
+import React, {useCallback, ComponentType} from 'react';
import styled from 'styled-components';
import classnames from 'classnames';
-import PropTypes from 'prop-types';
import {dataTestIds, LIGHT_AND_SHADOW_EFFECT} from '@kepler.gl/constants';
-import {removeEffect, updateEffect} from '@kepler.gl/actions';
+import {ActionHandler, removeEffect, updateEffect} from '@kepler.gl/actions';
import {Effect} from '@kepler.gl/types';
import EffectPanelHeaderFactory from './effect-panel-header';
@@ -18,8 +17,8 @@ export type EffectPanelProps = {
effect: Effect;
isDraggable: boolean;
listeners: any;
- removeEffect: typeof removeEffect;
- updateEffect: typeof updateEffect;
+ removeEffect: ActionHandler<typeof removeEffect>;
+ updateEffect: ActionHandler<typeof updateEffect>;
style?: React.CSSProperties;
onMouseDown: React.MouseEventHandler<HTMLDivElement>;
@@ -46,79 +45,85 @@ 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 = (event?: Event) => {
- event?.stopPropagation();
- this.props.updateEffect(this.props.effect.id, {
- isEnabled: !this.props.effect.isEnabled
- });
- };
-
- _toggleConfigActive = (event?: Event) => {
- event?.stopPropagation();
- this.props.updateEffect(this.props.effect.id, {
- isConfigActive: !this.props.effect.isConfigActive
- });
- };
-
- _removeEffect = (event?: Event) => {
- event?.stopPropagation();
- this.props.removeEffect(this.props.effect.id);
- };
-
- _updateEffectConfig = (event, id, props) => {
- event?.stopPropagation();
- this.props.updateEffect(id, props);
- };
-
- render() {
- const {effect, isDraggable, listeners} = this.props;
- const {id, type, isConfigActive, isJsonEditorActive, isEnabled} = effect;
-
- const sortingAllowed = type !== LIGHT_AND_SHADOW_EFFECT.type;
-
- return (
- <PanelWrapper
- active={false}
- className={classnames('effect-panel', this.props.className)}
- data-testid={dataTestIds.effectPanel}
- style={this.props.style}
- onMouseDown={this.props.onMouseDown}
- onTouchStart={this.props.onTouchStart}
- >
- <EffectPanelHeader
- isConfigActive={isConfigActive}
- effectId={id}
- type={type}
- isEnabled={isEnabled}
- isJsonEditorActive={isJsonEditorActive}
- onToggleEnabled={this._toggleEnabled}
- onRemoveEffect={this._removeEffect}
- onToggleEnableConfig={this._toggleConfigActive}
- isDragNDropEnabled={isDraggable && sortingAllowed}
- listeners={listeners}
- showSortHandle={type !== LIGHT_AND_SHADOW_EFFECT.type}
+ const EffectPanel: React.FC<EffectPanelProps> = ({
+ className,
+ effect,
+ isDraggable,
+ listeners,
+ removeEffect: removeEffectAction,
+ updateEffect: updateEffectAction,
+ style,
+ onMouseDown,
+ onTouchStart
+ }) => {
+ const toggleEnabled = useCallback(
+ (event?: Event) => {
+ event?.stopPropagation();
+ updateEffectAction(effect.id, {isEnabled: !effect.isEnabled});
+ },
+ [updateEffectAction, effect.id, effect.isEnabled]
+ );
+
+ const toggleConfigActive = useCallback(
+ (event?: Event) => {
+ event?.stopPropagation();
+ updateEffectAction(effect.id, {isConfigActive: !effect.isConfigActive});
+ },
+ [updateEffectAction, effect.id, effect.isConfigActive]
+ );
+
+ const handleRemoveEffect = useCallback(
+ (event?: Event) => {
+ event?.stopPropagation();
+ removeEffectAction(effect.id);
+ },
+ [removeEffectAction, effect.id]
+ );
+
+ const handleUpdateEffectConfig = useCallback(
+ (event, id, props) => {
+ event?.stopPropagation();
+ updateEffectAction(id, props);
+ },
+ [updateEffectAction]
+ );
+
+ const {id, type, isConfigActive, isJsonEditorActive, isEnabled} = effect;
+ const sortingAllowed = type !== LIGHT_AND_SHADOW_EFFECT.type;
+
+ return (
+ <PanelWrapper
+ active={false}
+ className={classnames('effect-panel', className)}
+ data-testid={dataTestIds.effectPanel}
+ style={style}
+ onMouseDown={onMouseDown}
+ onTouchStart={onTouchStart}
+ >
+ <EffectPanelHeader
+ isConfigActive={isConfigActive}
+ effectId={id}
+ type={type}
+ isEnabled={isEnabled}
+ isJsonEditorActive={isJsonEditorActive}
+ onToggleEnabled={toggleEnabled}
+ onRemoveEffect={handleRemoveEffect}
+ onToggleEnableConfig={toggleConfigActive}
+ isDragNDropEnabled={isDraggable && sortingAllowed}
+ listeners={listeners}
+ showSortHandle={type !== LIGHT_AND_SHADOW_EFFECT.type}
+ />
+ {isConfigActive && (
+ <EffectConfigurator
+ key={`effect-configurator-${id}`}
+ effect={effect}
+ updateEffectConfig={handleUpdateEffectConfig}
/>
- {isConfigActive && (
- <EffectConfigurator
- key={`effect-configurator-${id}`}
- effect={effect}
- updateEffectConfig={this._updateEffectConfig}
- />
- )}
- </PanelWrapper>
- );
- }
- }
+ )}
+ </PanelWrapper>
+ );
+ };
- // @ts-expect-error fix The types of 'propTypes.isDraggable[nominalTypeHack]' are incompatible between these types.
return EffectPanel;
}
diff --git a/src/components/src/modals/add-map-style-modal.tsx b/src/components/src/modals/add-map-style-modal.tsx
index 08392be73..823139871 100644
--- a/src/components/src/modals/add-map-style-modal.tsx
+++ b/src/components/src/modals/add-map-style-modal.tsx
@@ -1,8 +1,7 @@
// SPDX-License-Identifier: MIT
// Copyright contributors to the kepler.gl project
-import React, {Component} from 'react';
-import {polyfill} from 'react-lifecycles-compat';
+import React, {useRef, useState, useEffect, useCallback} from 'react';
import classnames from 'classnames';
import styled from 'styled-components';
import {Map as MapboxLegacyMap, MapInstance, MapRef} from 'react-map-gl/mapbox-legacy';
@@ -112,222 +111,198 @@ interface AddMapStyleModalProps {
}
function AddMapStyleModalFactory() {
- class AddMapStyleModal extends Component<AddMapStyleModalProps> {
- state = {
- reRenderKey: 0,
- previousToken: null
- };
-
- static getDerivedStateFromProps(props, state) {
- if (
- props.inputStyle &&
- props.inputStyle.accessToken &&
- props.inputStyle.accessToken !== state.previousToken
- ) {
- // toke has changed
- // ReactMapGl doesn't re-create map when token has changed
- // here we force the map to update
-
- return {
- reRenderKey: state.reRenderKey + 1,
- previousToken: props.inputStyle.accessToken
- };
+ function AddMapStyleModal({
+ inputMapStyle: inputMapStyleAction,
+ inputStyle,
+ loadCustomMapStyle: loadCustomMapStyleAction,
+ mapboxApiAccessToken,
+ mapboxApiUrl,
+ transformRequest: customTransformRequest,
+ mapState,
+ intl
+ }: AddMapStyleModalProps) {
+ const [reRenderKey, setReRenderKey] = useState(0);
+ const [previousToken, setPreviousToken] = useState<string | null>(null);
+ const mapRef = useRef<MapInstance | null>(null);
+ const loadCustomMapStyleRef = useRef(loadCustomMapStyleAction);
+ loadCustomMapStyleRef.current = loadCustomMapStyleAction;
+
+ useEffect(() => {
+ if (inputStyle?.accessToken && inputStyle.accessToken !== previousToken) {
+ setReRenderKey(prev => prev + 1);
+ setPreviousToken(inputStyle.accessToken);
}
-
- return null;
- }
-
- _map: MapInstance | undefined | null;
-
- _setMapRef = (mapRef: MapRef | null) => {
- // Handle change of the basemap library
- if (this._map && mapRef) {
- const map = mapRef.getMap();
- if (map && this._map !== map) {
- this._map.off('style.load', nop);
- this._map.off('error', nop);
- this._map = null;
+ }, [inputStyle?.accessToken, previousToken]);
+
+ const setMapRefCallback = useCallback((mapRefInstance: MapRef | null) => {
+ if (mapRef.current && mapRefInstance) {
+ const map = mapRefInstance.getMap();
+ if (map && mapRef.current !== map) {
+ mapRef.current.off('style.load', nop);
+ mapRef.current.off('error', nop);
+ mapRef.current = null;
}
}
- const map = mapRef && mapRef.getMap();
- if (map && this._map !== map) {
- this._map = map;
+ const map = mapRefInstance && mapRefInstance.getMap();
+ if (map && mapRef.current !== map) {
+ mapRef.current = map;
map.on('style.load', () => {
const style = map.getStyle();
- this.loadMapStyleJson(style);
+ loadCustomMapStyleRef.current({style, error: false});
});
map.on('error', () => {
- this.loadMapStyleError();
+ loadCustomMapStyleRef.current({error: true});
});
}
+ }, []);
+
+ const baseMapLibraryName = getBaseMapLibrary(inputStyle);
+ const baseMapLibraryConfig = getApplicationConfig().baseMapLibraryConfig[baseMapLibraryName];
+
+ const mapboxApiAccessTokenToUse = inputStyle.accessToken || mapboxApiAccessToken;
+ const mapProps: Record<string, any> = {
+ ...mapState,
+ mapboxAccessToken: mapboxApiAccessTokenToUse,
+ preserveDrawingBuffer: true,
+ transformRequest:
+ customTransformRequest?.(mapboxApiAccessTokenToUse) ||
+ transformRequest(mapboxApiAccessTokenToUse)
};
- loadMapStyleJson = style => {
- this.props.loadCustomMapStyle({style, error: false});
- };
-
- loadMapStyleError = () => {
- this.props.loadCustomMapStyle({error: true});
- };
-
- render() {
- const {inputStyle, mapState, intl} = this.props;
-
- const baseMapLibraryName = getBaseMapLibrary(inputStyle);
- const baseMapLibraryConfig = getApplicationConfig().baseMapLibraryConfig[baseMapLibraryName];
-
- const mapboxApiAccessToken = inputStyle.accessToken || this.props.mapboxApiAccessToken;
- const mapProps: Record<string, any> = {
- ...mapState,
- // TODO baseApiUrl should be taken into account in transformRequest as we use dynamic mapLib import
- // baseApiUrl: mapboxApiUrl,
- mapboxAccessToken: mapboxApiAccessToken,
- preserveDrawingBuffer: true,
- transformRequest:
- this.props.transformRequest?.(mapboxApiAccessToken) ||
- transformRequest(mapboxApiAccessToken)
- };
-
- // Only pass mapLib for the mapbox-legacy adapter
- if (baseMapLibraryName === MAP_LIB_OPTIONS.MAPBOX) {
- mapProps.mapLib = baseMapLibraryConfig.getMapLib();
- }
-
- const ResolvedMapComponent =
- baseMapLibraryName === MAP_LIB_OPTIONS.MAPBOX ? MapboxLegacyMap : MaplibreMap;
-
- return (
- <div className="add-map-style-modal">
- <StyledModalContent>
- <StyledModalVerticalPanel>
- <StyledModalSection>
- <div className="modal-section-title">
- <FormattedMessage id={'modal.addStyle.pasteTitle'} />
- </div>
- <div className="modal-section-subtitle">
- {intl.formatMessage({id: 'modal.addStyle.pasteSubtitle0'})}
- <InlineLink
- target="_blank"
- href="https://www.mapbox.com/help/studio-manual-publish/#style-url"
- >
- {' '}
- {intl.formatMessage({id: 'modal.addStyle.pasteSubtitle2'})}
- </InlineLink>{' '}
- {intl.formatMessage({id: 'modal.addStyle.pasteSubtitle3'})}
- <InlineLink
- target="_blank"
- href="https://docs.mapbox.com/mapbox-gl-js/style-spec"
- >
- {' '}
- {intl.formatMessage({id: 'modal.addStyle.pasteSubtitle4'})}
- </InlineLink>
- </div>
- <InputLight
- type="text"
- value={inputStyle.url || ''}
- onChange={({target: {value}}) =>
- this.props.inputMapStyle({
- url: value,
- id: 'Custom Style',
- icon: `${getApplicationConfig().cdnUrl}/${NO_BASEMAP_ICON}`
- })
- }
- placeholder="e.g. https://basemaps.cartocdn.com/gl/positron-gl-style/style.json"
- />
- </StyledModalSection>
+ if (baseMapLibraryName === MAP_LIB_OPTIONS.MAPBOX) {
+ mapProps.mapLib = baseMapLibraryConfig.getMapLib();
+ }
- <StyledModalSection>
- <div className="modal-section-title">
- <FormattedMessage id={'modal.addStyle.publishTitle'} />
- </div>
- <div className="modal-section-subtitle">
- {intl.formatMessage({id: 'modal.addStyle.publishSubtitle1'})}
- <InlineLink target="_blank" href="https://www.mapbox.com/studio/styles/">
- {' '}
- mapbox
- </InlineLink>{' '}
- {intl.formatMessage({id: 'modal.addStyle.publishSubtitle2'})}
- <InlineLink
- target="_blank"
- href="https://www.mapbox.com/help/studio-manual-publish/"
- >
- {' '}
- {intl.formatMessage({id: 'modal.addStyle.publishSubtitle3'})}
- </InlineLink>{' '}
- {intl.formatMessage({id: 'modal.addStyle.publishSubtitle4'})}
- </div>
+ const ResolvedMapComponent =
+ baseMapLibraryName === MAP_LIB_OPTIONS.MAPBOX ? MapboxLegacyMap : MaplibreMap;
- <div className="modal-section-subtitle">
- {intl.formatMessage({id: 'modal.addStyle.publishSubtitle5'})}
- <InlineLink
- target="_blank"
- href="https://www.mapbox.com/help/how-access-tokens-work/"
- >
- {' '}
- {intl.formatMessage({id: 'modal.addStyle.publishSubtitle6'})}
- </InlineLink>{' '}
- {intl.formatMessage({id: 'modal.addStyle.publishSubtitle7'})}
- </div>
- <InputLight
- type="text"
- value={inputStyle.accessToken || ''}
- onChange={({target: {value}}) => this.props.inputMapStyle({accessToken: value})}
- placeholder={intl.formatMessage({id: 'modal.addStyle.exampleToken'})}
- />
- </StyledModalSection>
+ return (
+ <div className="add-map-style-modal">
+ <StyledModalContent>
+ <StyledModalVerticalPanel>
+ <StyledModalSection>
+ <div className="modal-section-title">
+ <FormattedMessage id={'modal.addStyle.pasteTitle'} />
+ </div>
+ <div className="modal-section-subtitle">
+ {intl.formatMessage({id: 'modal.addStyle.pasteSubtitle0'})}
+ <InlineLink
+ target="_blank"
+ href="https://www.mapbox.com/help/studio-manual-publish/#style-url"
+ >
+ {' '}
+ {intl.formatMessage({id: 'modal.addStyle.pasteSubtitle2'})}
+ </InlineLink>{' '}
+ {intl.formatMessage({id: 'modal.addStyle.pasteSubtitle3'})}
+ <InlineLink target="_blank" href="https://docs.mapbox.com/mapbox-gl-js/style-spec">
+ {' '}
+ {intl.formatMessage({id: 'modal.addStyle.pasteSubtitle4'})}
+ </InlineLink>
+ </div>
+ <InputLight
+ type="text"
+ value={inputStyle.url || ''}
+ onChange={({target: {value}}) =>
+ inputMapStyleAction({
+ url: value,
+ id: 'Custom Style',
+ icon: `${getApplicationConfig().cdnUrl}/${NO_BASEMAP_ICON}`
+ })
+ }
+ placeholder="e.g. https://basemaps.cartocdn.com/gl/positron-gl-style/style.json"
+ />
+ </StyledModalSection>
+
+ <StyledModalSection>
+ <div className="modal-section-title">
+ <FormattedMessage id={'modal.addStyle.publishTitle'} />
+ </div>
+ <div className="modal-section-subtitle">
+ {intl.formatMessage({id: 'modal.addStyle.publishSubtitle1'})}
+ <InlineLink target="_blank" href="https://www.mapbox.com/studio/styles/">
+ {' '}
+ mapbox
+ </InlineLink>{' '}
+ {intl.formatMessage({id: 'modal.addStyle.publishSubtitle2'})}
+ <InlineLink
+ target="_blank"
+ href="https://www.mapbox.com/help/studio-manual-publish/"
+ >
+ {' '}
+ {intl.formatMessage({id: 'modal.addStyle.publishSubtitle3'})}
+ </InlineLink>{' '}
+ {intl.formatMessage({id: 'modal.addStyle.publishSubtitle4'})}
+ </div>
- <StyledModalSection>
- <div className="modal-section-title">
- <FormattedMessage id={'modal.addStyle.namingTitle'} />
- </div>
- <InputLight
- type="text"
- value={inputStyle.label || ''}
- onChange={({target: {value}}) => this.props.inputMapStyle({label: value})}
- placeholder="Name your style"
- />
- </StyledModalSection>
- </StyledModalVerticalPanel>
- <PreviewMap>
- <div
- className={classnames('preview-title', {
- error: inputStyle.error
- })}
- >
- {inputStyle.error
- ? ErrorMsg.styleError
- : (inputStyle.style && inputStyle.style.name) || ''}
+ <div className="modal-section-subtitle">
+ {intl.formatMessage({id: 'modal.addStyle.publishSubtitle5'})}
+ <InlineLink
+ target="_blank"
+ href="https://www.mapbox.com/help/how-access-tokens-work/"
+ >
+ {' '}
+ {intl.formatMessage({id: 'modal.addStyle.publishSubtitle6'})}
+ </InlineLink>{' '}
+ {intl.formatMessage({id: 'modal.addStyle.publishSubtitle7'})}
</div>
- <StyledPreviewImage className="preview-image">
- {/** Note, we need the Map to render with errored params to get style.error messages */}
- {!inputStyle.isValid ? (
- <div className="preview-image-spinner" />
- ) : (
- <StyledMapContainer>
- <ResolvedMapComponent
- {...mapProps}
- ref={this._setMapRef as any}
- key={`${baseMapLibraryName}-${this.state.reRenderKey}-${inputStyle.url}-${mapboxApiAccessToken}`}
- style={{
- width: MapW,
- height: MapH
- }}
- mapStyle={inputStyle.url === null ? undefined : inputStyle.url}
- />
- </StyledMapContainer>
- )}
- </StyledPreviewImage>
- </PreviewMap>
- </StyledModalContent>
- </div>
- );
- }
+ <InputLight
+ type="text"
+ value={inputStyle.accessToken || ''}
+ onChange={({target: {value}}) => inputMapStyleAction({accessToken: value})}
+ placeholder={intl.formatMessage({id: 'modal.addStyle.exampleToken'})}
+ />
+ </StyledModalSection>
+
+ <StyledModalSection>
+ <div className="modal-section-title">
+ <FormattedMessage id={'modal.addStyle.namingTitle'} />
+ </div>
+ <InputLight
+ type="text"
+ value={inputStyle.label || ''}
+ onChange={({target: {value}}) => inputMapStyleAction({label: value})}
+ placeholder="Name your style"
+ />
+ </StyledModalSection>
+ </StyledModalVerticalPanel>
+ <PreviewMap>
+ <div
+ className={classnames('preview-title', {
+ error: inputStyle.error
+ })}
+ >
+ {inputStyle.error
+ ? ErrorMsg.styleError
+ : (inputStyle.style && inputStyle.style.name) || ''}
+ </div>
+ <StyledPreviewImage className="preview-image">
+ {!inputStyle.isValid ? (
+ <div className="preview-image-spinner" />
+ ) : (
+ <StyledMapContainer>
+ <ResolvedMapComponent
+ {...mapProps}
+ ref={setMapRefCallback as any}
+ key={`${baseMapLibraryName}-${reRenderKey}-${inputStyle.url}-${mapboxApiAccessTokenToUse}`}
+ style={{
+ width: MapW,
+ height: MapH
+ }}
+ mapStyle={inputStyle.url === null ? undefined : inputStyle.url}
+ />
+ </StyledMapContainer>
+ )}
+ </StyledPreviewImage>
+ </PreviewMap>
+ </StyledModalContent>
+ </div>
+ );
}
- return injectIntl(polyfill(AddMapStyleModal));
+ return injectIntl(AddMapStyleModal);
}
export default AddMapStyleModalFactory;
diff --git a/src/components/src/modals/data-table-modal.tsx b/src/components/src/modals/data-table-modal.tsx
index 51b81643c..9d599bbb1 100644
--- a/src/components/src/modals/data-table-modal.tsx
+++ b/src/components/src/modals/data-table-modal.tsx
@@ -1,11 +1,10 @@
// SPDX-License-Identifier: MIT
// Copyright contributors to the kepler.gl project
-import React from 'react';
+import React, {useState, useRef, useMemo, useCallback} from 'react';
import styled, {withTheme, IStyledComponent} from 'styled-components';
import DatasetLabel from '../common/dataset-label';
import DataTableFactory from '../common/data-table';
-import {createSelector} from 'reselect';
import {renderedSize} from '../common/data-table/cell-size';
import CanvasHack from '../common/data-table/canvas';
import KeplerTable, {Datasets} from '@kepler.gl/table';
@@ -144,50 +143,65 @@ function DataTableModalFactory(
DataTable: ReturnType<typeof DataTableFactory>,
DataTableConfig: ReturnType<typeof DataTableConfigFactory>
): React.ComponentType<Omit<DataTableModalProps, 'theme'>> {
- class DataTableModal extends React.Component<DataTableModalProps> {
- state = {
- showConfig: false
- };
-
- datasetCellSizeCache = {};
- dataId = ({dataId = ''}: DataTableModalProps) => dataId;
- datasets = (props: DataTableModalProps) => props.datasets;
- fields = ({datasets, dataId = ''}: DataTableModalProps) => (datasets[dataId] || {}).fields;
- columns = createSelector(this.fields, fields => fields.map(f => f.name));
- colMeta = createSelector([this.fields, this.datasets], fields =>
- fields.reduce(
- (acc, {name, displayName, type, filterProps, format, displayFormat}) => ({
- ...acc,
- [name]: {
- name: displayName || name,
- type,
- ...(format ? {format} : {}),
- ...(displayFormat ? {displayFormat} : {}),
- ...(filterProps?.columnStats ? {columnStats: filterProps.columnStats} : {})
- }
- }),
- {}
- )
+ const DataTableModal: React.FC<DataTableModalProps> = ({
+ theme,
+ dataId = '',
+ sortTableColumn,
+ pinTableColumn,
+ copyTableColumn: copyTableColumnProp,
+ datasets,
+ showDatasetTable,
+ showTab = true,
+ setColumnDisplayFormat: setColumnDisplayFormatProp,
+ uiStateActions,
+ uiState
+ }) => {
+ const [showConfig, setShowConfig] = useState(false);
+ const datasetCellSizeCache = useRef<Record<string, any>>({});
+
+ const fields = useMemo(
+ () => (datasets && dataId ? (datasets[dataId] || {}).fields : undefined),
+ [datasets, dataId]
);
- cellSizeCache = createSelector(this.dataId, this.datasets, (dataId, datasets) => {
- if (!datasets[dataId]) {
+ const columns = useMemo(() => fields?.map(f => f.name) || [], [fields]);
+
+ const colMeta = useMemo(
+ () =>
+ fields?.reduce(
+ (acc, {name, displayName, type, filterProps, format, displayFormat}) => ({
+ ...acc,
+ [name]: {
+ name: displayName || name,
+ type,
+ ...(format ? {format} : {}),
+ ...(displayFormat ? {displayFormat} : {}),
+ ...(filterProps?.columnStats ? {columnStats: filterProps.columnStats} : {})
+ }
+ }),
+ {}
+ ) || {},
+ [fields]
+ );
+
+ const cellSizeCache = useMemo(() => {
+ if (!datasets || !dataId || !datasets[dataId]) {
return {};
}
const {fields, dataContainer} = datasets[dataId];
let showCalculate: boolean | null = null;
- if (!this.datasetCellSizeCache[dataId]) {
+ if (!datasetCellSizeCache.current[dataId]) {
showCalculate = true;
} else if (
- this.datasetCellSizeCache[dataId].fields !== fields ||
- this.datasetCellSizeCache[dataId].dataContainer !== dataContainer
+ datasetCellSizeCache.current[dataId].fields !== fields ||
+ datasetCellSizeCache.current[dataId].dataContainer !== dataContainer
) {
showCalculate = true;
}
if (!showCalculate) {
- return this.datasetCellSizeCache[dataId].cellSizeCache;
+ return datasetCellSizeCache.current[dataId].cellSizeCache;
}
const cellSizeCache = fields.reduce(
@@ -200,113 +214,110 @@ function DataTableModalFactory(
},
colIdx,
type: field.type,
- fontSize: this.props.theme.cellFontSize,
- font: this.props.theme.fontFamily,
+ fontSize: theme.cellFontSize,
+ font: theme.fontFamily,
minCellSize: MIN_STATS_CELL_SIZE
})
}),
{}
);
- // save it to cache
- this.datasetCellSizeCache[dataId] = {
+
+ datasetCellSizeCache.current[dataId] = {
cellSizeCache,
fields,
dataContainer
};
return cellSizeCache;
- });
-
- copyTableColumn = (column: string) => {
- const {dataId = '', copyTableColumn} = this.props;
- copyTableColumn(dataId, column);
- };
-
- pinTableColumn = (column: string) => {
- const {dataId = '', pinTableColumn} = this.props;
- pinTableColumn(dataId, column);
- };
-
- sortTableColumn = (column: string, mode?: string) => {
- const {dataId = '', sortTableColumn} = this.props;
- sortTableColumn(dataId, column, mode);
- };
-
- setColumnDisplayFormat = formats => {
- const {dataId, setColumnDisplayFormat} = this.props;
- if (dataId) setColumnDisplayFormat(dataId, formats);
- };
-
- onOpenConfig = () => {
- this.setState({showConfig: true});
- };
-
- onCloseConfig = () => {
- this.setState({showConfig: false});
- };
-
- render() {
- const {datasets, dataId, showDatasetTable, showTab = true} = this.props;
- if (!datasets || !dataId) {
- return null;
- }
- const activeDataset = datasets[dataId];
- const columns = this.columns(this.props);
- const colMeta = this.colMeta(this.props);
- const cellSizeCache = this.cellSizeCache(this.props);
-
- return (
- <StyledModal className="dataset-modal" id="dataset-modal">
- <CanvasHack />
- <TableContainer>
- {showTab ? (
- <DatasetTabs
- activeDataset={activeDataset}
- datasets={datasets}
- showDatasetTable={showDatasetTable}
- />
- ) : null}
- <StyledConfigureButton className="display-config-button">
- <Gear onClick={this.onOpenConfig} />
- <Portaled
- right={240}
- top={20}
- isOpened={this.state.showConfig}
- onClose={this.onCloseConfig}
- >
- <DataTableConfig
- columns={columns}
- colMeta={colMeta}
- setColumnDisplayFormat={this.setColumnDisplayFormat}
- onClose={this.onCloseConfig}
- />
- </Portaled>
- </StyledConfigureButton>
- {datasets[dataId] ? (
- <DataTable
- key={dataId}
- dataId={dataId}
+ }, [dataId, datasets, theme]);
+
+ const handleCopyTableColumn = useCallback(
+ (column: string) => {
+ copyTableColumnProp(dataId, column);
+ },
+ [copyTableColumnProp, dataId]
+ );
+
+ const handlePinTableColumn = useCallback(
+ (column: string) => {
+ pinTableColumn(dataId, column);
+ },
+ [pinTableColumn, dataId]
+ );
+
+ const handleSortTableColumn = useCallback(
+ (column: string, mode?: string) => {
+ sortTableColumn(dataId, column, mode);
+ },
+ [sortTableColumn, dataId]
+ );
+
+ const handleSetColumnDisplayFormat = useCallback(
+ formats => {
+ if (dataId) setColumnDisplayFormatProp(dataId, formats);
+ },
+ [setColumnDisplayFormatProp, dataId]
+ );
+
+ const onOpenConfig = useCallback(() => {
+ setShowConfig(true);
+ }, []);
+
+ const onCloseConfig = useCallback(() => {
+ setShowConfig(false);
+ }, []);
+
+ if (!datasets || !dataId) {
+ return null;
+ }
+
+ const activeDataset = datasets[dataId];
+
+ return (
+ <StyledModal className="dataset-modal" id="dataset-modal">
+ <CanvasHack />
+ <TableContainer>
+ {showTab ? (
+ <DatasetTabs
+ activeDataset={activeDataset}
+ datasets={datasets}
+ showDatasetTable={showDatasetTable}
+ />
+ ) : null}
+ <StyledConfigureButton className="display-config-button">
+ <Gear onClick={onOpenConfig} />
+ <Portaled right={240} top={20} isOpened={showConfig} onClose={onCloseConfig}>
+ <DataTableConfig
columns={columns}
colMeta={colMeta}
- cellSizeCache={cellSizeCache}
- dataContainer={activeDataset.dataContainer}
- pinnedColumns={activeDataset.pinnedColumns}
- sortOrder={activeDataset.sortOrder}
- sortColumn={activeDataset.sortColumn || DEFAULT_SORT_COLUMN}
- copyTableColumn={this.copyTableColumn}
- pinTableColumn={this.pinTableColumn}
- sortTableColumn={this.sortTableColumn}
- setColumnDisplayFormat={this.setColumnDisplayFormat}
- hasStats={false}
+ setColumnDisplayFormat={handleSetColumnDisplayFormat}
+ onClose={onCloseConfig}
/>
- ) : null}
- </TableContainer>
- </StyledModal>
- );
- }
- }
+ </Portaled>
+ </StyledConfigureButton>
+ {datasets[dataId] ? (
+ <DataTable
+ key={dataId}
+ dataId={dataId}
+ columns={columns}
+ colMeta={colMeta}
+ cellSizeCache={cellSizeCache}
+ dataContainer={activeDataset.dataContainer}
+ pinnedColumns={activeDataset.pinnedColumns}
+ sortOrder={activeDataset.sortOrder}
+ sortColumn={activeDataset.sortColumn || DEFAULT_SORT_COLUMN}
+ copyTableColumn={handleCopyTableColumn}
+ pinTableColumn={handlePinTableColumn}
+ sortTableColumn={handleSortTableColumn}
+ setColumnDisplayFormat={handleSetColumnDisplayFormat}
+ hasStats={false}
+ />
+ ) : null}
+ </TableContainer>
+ </StyledModal>
+ );
+ };
- // @ts-expect-error figure out the proper way to type
- return withTheme(DataTableModal);
+ return withTheme(DataTableModal) as React.ComponentType<Omit<DataTableModalProps, 'theme'>>;
}
export default DataTableModalFactory;
diff --git a/src/components/src/modals/export-data-modal.tsx b/src/components/src/modals/export-data-modal.tsx
index e0ac181e6..d54b4f75f 100644
--- a/src/components/src/modals/export-data-modal.tsx
+++ b/src/components/src/modals/export-data-modal.tsx
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: MIT
// Copyright contributors to the kepler.gl project
-import React, {Component} from 'react';
+import React, {useEffect} from 'react';
import {injectIntl, IntlShape} from 'react-intl';
import {DatasetType, EXPORT_DATA_TYPE_OPTIONS} from '@kepler.gl/constants';
@@ -67,136 +67,135 @@ export interface ExportDataModalProps {
}
const ExportDataModalFactory = () => {
- class ExportDataModal extends Component<ExportDataModalProps> {
- componentDidMount() {
- const toCPUFilter = this.props.selectedDataset || Object.keys(this.props.datasets);
- this.props.applyCPUFilter(toCPUFilter);
- }
+ const ExportDataModal = ({
+ supportedDataTypes = EXPORT_DATA_TYPE_OPTIONS,
+ datasets,
+ selectedDataset,
+ dataType,
+ filtered,
+ onChangeExportDataType,
+ onChangeExportFiltered,
+ applyCPUFilter,
+ onChangeExportSelectedDataset,
+ intl
+ }: ExportDataModalProps) => {
+ useEffect(() => {
+ const toCPUFilter = selectedDataset || Object.keys(datasets);
+ applyCPUFilter(toCPUFilter);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
- _onSelectDataset: React.ChangeEventHandler<HTMLSelectElement> = ({target: {value}}) => {
- this.props.applyCPUFilter(value);
- this.props.onChangeExportSelectedDataset(value);
+ const onSelectDataset: React.ChangeEventHandler<HTMLSelectElement> = ({target: {value}}) => {
+ applyCPUFilter(value);
+ onChangeExportSelectedDataset(value);
};
- render() {
- const {
- supportedDataTypes = EXPORT_DATA_TYPE_OPTIONS,
- datasets,
- selectedDataset,
- dataType,
- filtered,
- onChangeExportDataType,
- onChangeExportFiltered,
- intl
- } = this.props;
-
- const exportAllDatasets = selectedDataset ? !datasets[selectedDataset] : true;
- const showTiledDatasetWarning = Object.keys(datasets).some(datasetId => {
- return (
- (datasets[datasetId].type === DatasetType.VECTOR_TILE ||
- datasets[datasetId].type === DatasetType.RASTER_TILE ||
- datasets[datasetId].type === DatasetType.WMS_TILE ||
- datasets[datasetId].type === DatasetType.TILE_3D) &&
- (selectedDataset === datasetId || exportAllDatasets)
- );
- });
-
+ const exportAllDatasets = selectedDataset ? !datasets[selectedDataset] : true;
+ const showTiledDatasetWarning = Object.keys(datasets).some(datasetId => {
return (
- <StyledModalContent className="export-data-modal">
- <div>
- <StyledExportSection>
- <div className="description">
- <div className="title">
- <FormattedMessage id={'modal.exportData.datasetTitle'} />
- </div>
- <div className="subtitle">
- <FormattedMessage id={'modal.exportData.datasetSubtitle'} />
- </div>
+ (datasets[datasetId].type === DatasetType.VECTOR_TILE ||
+ datasets[datasetId].type === DatasetType.RASTER_TILE ||
+ datasets[datasetId].type === DatasetType.WMS_TILE ||
+ datasets[datasetId].type === DatasetType.TILE_3D) &&
+ (selectedDataset === datasetId || exportAllDatasets)
+ );
+ });
+
+ return (
+ <StyledModalContent className="export-data-modal">
+ <div>
+ <StyledExportSection>
+ <div className="description">
+ <div className="title">
+ <FormattedMessage id={'modal.exportData.datasetTitle'} />
</div>
- <div className="selection">
- <select value={selectedDataset} onChange={this._onSelectDataset}>
- {[intl.formatMessage({id: 'modal.exportData.allDatasets'})]
- .concat(Object.keys(datasets))
- .map(d => (
- <option key={d} value={d}>
- {(datasets[d] && datasets[d].label) || d}
- </option>
- ))}
- </select>
+ <div className="subtitle">
+ <FormattedMessage id={'modal.exportData.datasetSubtitle'} />
</div>
- </StyledExportSection>
- <StyledExportSection>
- <div className="description">
- <div className="title">
- <FormattedMessage id={'modal.exportData.dataTypeTitle'} />
- </div>
- <div className="subtitle">
- <FormattedMessage id={'modal.exportData.dataTypeSubtitle'} />
- </div>
+ </div>
+ <div className="selection">
+ <select value={selectedDataset} onChange={onSelectDataset}>
+ {[intl.formatMessage({id: 'modal.exportData.allDatasets'})]
+ .concat(Object.keys(datasets))
+ .map(d => (
+ <option key={d} value={d}>
+ {(datasets[d] && datasets[d].label) || d}
+ </option>
+ ))}
+ </select>
+ </div>
+ </StyledExportSection>
+ <StyledExportSection>
+ <div className="description">
+ <div className="title">
+ <FormattedMessage id={'modal.exportData.dataTypeTitle'} />
</div>
- <div className="selection">
- {supportedDataTypes.map(op => (
- <StyledType
- key={op.id}
- selected={dataType === op.id}
- onClick={() => op.available && onChangeExportDataType(op.id)}
- >
- <FileType ext={op.label} height="80px" fontSize="11px" />
- {dataType === op.id && <CheckMark />}
- </StyledType>
- ))}
+ <div className="subtitle">
+ <FormattedMessage id={'modal.exportData.dataTypeSubtitle'} />
</div>
- </StyledExportSection>
- <StyledExportSection>
- <div className="description">
- <div className="title">
- <FormattedMessage id={'modal.exportData.dataTypeTitle'} />
- </div>
- <div className="subtitle">
- <FormattedMessage id={'modal.exportData.filterDataSubtitle'} />
- </div>
- </div>
- <div className="selection">
- <StyledFilteredOption
- className="unfiltered-option"
- selected={!filtered}
- onClick={() => onChangeExportFiltered(false)}
- >
- <div className="filter-option-title">
- <FormattedMessage id={'modal.exportData.unfilteredData'} />
- </div>
- <div className="filter-option-subtitle">
- {getDataRowCount(datasets, selectedDataset, false, intl)}
- </div>
- {!filtered && <CheckMark />}
- </StyledFilteredOption>
- <StyledFilteredOption
- className="filtered-option"
- selected={filtered}
- onClick={() => onChangeExportFiltered(true)}
+ </div>
+ <div className="selection">
+ {supportedDataTypes.map(op => (
+ <StyledType
+ key={op.id}
+ selected={dataType === op.id}
+ onClick={() => op.available && onChangeExportDataType(op.id)}
>
- <div className="filter-option-title">
- <FormattedMessage id={'modal.exportData.filteredData'} />
- </div>
- <div className="filter-option-subtitle">
- {getDataRowCount(datasets, selectedDataset, true, intl)}
- </div>
- {filtered && <CheckMark />}
- </StyledFilteredOption>
- </div>
- </StyledExportSection>
- {showTiledDatasetWarning ? (
+ <FileType ext={op.label} height="80px" fontSize="11px" />
+ {dataType === op.id && <CheckMark />}
+ </StyledType>
+ ))}
+ </div>
+ </StyledExportSection>
+ <StyledExportSection>
+ <div className="description">
<div className="title">
- <StyledWarning>
- <FormattedMessage id={'modal.exportData.tiledDatasetWarning'} />
- </StyledWarning>
+ <FormattedMessage id={'modal.exportData.dataTypeTitle'} />
</div>
- ) : null}
- </div>
- </StyledModalContent>
- );
- }
- }
+ <div className="subtitle">
+ <FormattedMessage id={'modal.exportData.filterDataSubtitle'} />
+ </div>
+ </div>
+ <div className="selection">
+ <StyledFilteredOption
+ className="unfiltered-option"
+ selected={!filtered}
+ onClick={() => onChangeExportFiltered(false)}
+ >
+ <div className="filter-option-title">
+ <FormattedMessage id={'modal.exportData.unfilteredData'} />
+ </div>
+ <div className="filter-option-subtitle">
+ {getDataRowCount(datasets, selectedDataset, false, intl)}
+ </div>
+ {!filtered && <CheckMark />}
+ </StyledFilteredOption>
+ <StyledFilteredOption
+ className="filtered-option"
+ selected={filtered}
+ onClick={() => onChangeExportFiltered(true)}
+ >
+ <div className="filter-option-title">
+ <FormattedMessage id={'modal.exportData.filteredData'} />
+ </div>
+ <div className="filter-option-subtitle">
+ {getDataRowCount(datasets, selectedDataset, true, intl)}
+ </div>
+ {filtered && <CheckMark />}
+ </StyledFilteredOption>
+ </div>
+ </StyledExportSection>
+ {showTiledDatasetWarning ? (
+ <div className="title">
+ <StyledWarning>
+ <FormattedMessage id={'modal.exportData.tiledDatasetWarning'} />
+ </StyledWarning>
+ </div>
+ ) : null}
+ </div>
+ </StyledModalContent>
+ );
+ };
return injectIntl(ExportDataModal);
};
diff --git a/src/components/src/notification-panel.tsx b/src/components/src/notification-panel.tsx
index 79b47c885..32004e863 100644
--- a/src/components/src/notification-panel.tsx
+++ b/src/components/src/notification-panel.tsx
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: MIT
// Copyright contributors to the kepler.gl project
-import React, {Component} from 'react';
+import React from 'react';
import styled from 'styled-components';
import NotificationItemFactory from './notification-panel/notification-item';
@@ -33,33 +33,26 @@ interface NotificationPanelProps {
export default function NotificationPanelFactory(
NotificationItem: ReturnType<typeof NotificationItemFactory>
-): React.ComponentClass<NotificationPanelProps> {
- class NotificationPanelUnmemoized extends Component<NotificationPanelProps> {
- static displayName = 'NotificationPanel';
+): React.FC<NotificationPanelProps> {
+ const NotificationPanel: React.FC<NotificationPanelProps> = ({
+ notifications,
+ removeNotification
+ }) => {
+ const globalNotifications = notifications.filter(
+ n => n.topic === DEFAULT_NOTIFICATION_TOPICS.global
+ );
+
+ return (
+ <NotificationPanelContent
+ className="notification-panel"
+ style={{display: globalNotifications.length ? 'block' : 'none'}}
+ >
+ {globalNotifications.map(n => (
+ <NotificationItem key={n.id} notification={n} removeNotification={removeNotification} />
+ ))}
+ </NotificationPanelContent>
+ );
+ };
- render() {
- const globalNotifications = this.props.notifications.filter(
- n => n.topic === DEFAULT_NOTIFICATION_TOPICS.global
- );
- return (
- <NotificationPanelContent
- className="notification-panel"
- style={{display: globalNotifications.length ? 'block' : 'none'}}
- >
- {globalNotifications.map(n => (
- <NotificationItem
- key={n.id}
- notification={n}
- removeNotification={this.props.removeNotification}
- />
- ))}
- </NotificationPanelContent>
- );
- }
- }
-
- const NotificationPanel = React.memo(
- NotificationPanelUnmemoized
- ) as unknown as typeof NotificationPanelUnmemoized;
return NotificationPanel;
}
diff --git a/src/components/src/notification-panel/notification-item.tsx b/src/components/src/notification-panel/notification-item.tsx
index 40e267b00..6fcb287b4 100644
--- a/src/components/src/notification-panel/notification-item.tsx
+++ b/src/components/src/notification-panel/notification-item.tsx
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: MIT
// Copyright contributors to the kepler.gl project
-import React, {Component} from 'react';
+import React, {useState, useEffect} from 'react';
import styled from 'styled-components';
import {Delete, Info, Warning, Checkmark} from '../common/icons';
import Markdown from 'markdown-to-jsx';
@@ -118,58 +118,56 @@ interface NotificationItemProps {
}
export default function NotificationItemFactory() {
- return class NotificationItem extends Component<NotificationItemProps> {
- state = {
- isExpanded: false
- };
-
- componentDidMount() {
- if (this.props.isExpanded) {
- this.setState({isExpanded: true});
+ return function NotificationItem({
+ notification,
+ removeNotification,
+ isExpanded: initialIsExpanded,
+ theme
+ }: NotificationItemProps) {
+ const [isExpanded, setIsExpanded] = useState(false);
+
+ useEffect(() => {
+ if (initialIsExpanded) {
+ setIsExpanded(true);
}
- }
-
- render() {
- const {notification, removeNotification} = this.props;
- const {isExpanded} = this.state;
-
- return (
- <NotificationItemContentBlock isExpanded={isExpanded} theme={this.props.theme}>
- {(notification.count || 0) > 1 ? (
- <NotificationCounter type={notification.type} theme={this.props.theme}>
- {notification.count}
- </NotificationCounter>
- ) : null}
- <NotificationItemContent
- className="notification-item"
- type={notification.type}
- isExpanded={isExpanded}
- onClick={() => this.setState({isExpanded: !isExpanded})}
- >
- <NotificationIcon className="notification-item--icon">
- {icons[notification.type]}
- </NotificationIcon>
- <NotificationMessage isExpanded={isExpanded} theme={this.props.theme}>
- <Markdown
- options={{
- overrides: {
- a: {
- component: LinkRenderer
- }
+ }, [initialIsExpanded]);
+
+ return (
+ <NotificationItemContentBlock isExpanded={isExpanded} theme={theme}>
+ {(notification.count || 0) > 1 ? (
+ <NotificationCounter type={notification.type} theme={theme}>
+ {notification.count}
+ </NotificationCounter>
+ ) : null}
+ <NotificationItemContent
+ className="notification-item"
+ type={notification.type}
+ isExpanded={isExpanded}
+ onClick={() => setIsExpanded(!isExpanded)}
+ >
+ <NotificationIcon className="notification-item--icon">
+ {icons[notification.type]}
+ </NotificationIcon>
+ <NotificationMessage isExpanded={isExpanded} theme={theme}>
+ <Markdown
+ options={{
+ overrides: {
+ a: {
+ component: LinkRenderer
}
- }}
- >
- {notification.message}
- </Markdown>
- </NotificationMessage>
- {typeof removeNotification === 'function' ? (
- <div className="notification-item--action">
- <DeleteIcon height="10px" onClick={() => removeNotification(notification.id)} />
- </div>
- ) : null}
- </NotificationItemContent>
- </NotificationItemContentBlock>
- );
- }
+ }
+ }}
+ >
+ {notification.message}
+ </Markdown>
+ </NotificationMessage>
+ {typeof removeNotification === 'function' ? (
+ <div className="notification-item--action">
+ <DeleteIcon height="10px" onClick={() => removeNotification(notification.id)} />
+ </div>
+ ) : null}
+ </NotificationItemContent>
+ </NotificationItemContentBlock>
+ );
};
}