Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.
fix(ui): prevent checkbox ID collisions across map instances (#3843)
Igor Dykhtac2ac0bc2e63d
diff --git a/src/components/src/common/checkbox.spec.tsx b/src/components/src/common/checkbox.spec.tsxnew file mode 100644index 000000000..77685c393--- /dev/null+++ b/src/components/src/common/checkbox.spec.tsx@@ -0,0 +1,53 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import React from 'react';+import {fireEvent, screen} from '@testing-library/react';++import {renderWithTheme} from 'test/helpers/component-jest-utils';++import Checkbox from './checkbox';++describe('Checkbox', () => {+ test('associates each label with its own input when ids repeat', () => {+ const onChangeFirst = jest.fn();+ const onChangeSecond = jest.fn();+ const {container} = renderWithTheme(+ <>+ <Checkbox id="layer-visible" label="First layer" onChange={onChangeFirst} />+ <Checkbox id="layer-visible" label="Second layer" onChange={onChangeSecond} />+ </>+ );++ const inputs = container.querySelectorAll('input');+ const labels = container.querySelectorAll('label');++ expect(inputs[0]).toHaveAttribute('id', 'layer-visible');+ expect(inputs[1]).toHaveAttribute('id', 'layer-visible');+ expect(labels[0]).not.toHaveAttribute('for');+ expect(labels[1]).not.toHaveAttribute('for');+ expect(labels[0]).toContainElement(inputs[0]);+ expect(labels[1]).toContainElement(inputs[1]);++ fireEvent.click(screen.getByText('Second layer'));++ expect(onChangeSecond).toHaveBeenCalledTimes(1);+ expect(onChangeFirst).not.toHaveBeenCalled();+ });++ test('keeps the caller-provided id for external labels', () => {+ const onChange = jest.fn();+ const {container} = renderWithTheme(+ <>+ <label htmlFor="legend-layer-visible">Layer visibility</label>+ <Checkbox id="legend-layer-visible" onChange={onChange} />+ </>+ );++ expect(container.querySelector('input')).toHaveAttribute('id', 'legend-layer-visible');++ fireEvent.click(screen.getByText('Layer visibility'));++ expect(onChange).toHaveBeenCalledTimes(1);+ });+});diff --git a/src/components/src/common/checkbox.tsx b/src/components/src/common/checkbox.tsxindex fc46af23a..4685a2954 100644--- a/src/components/src/common/checkbox.tsx+++ b/src/components/src/common/checkbox.tsx@@ -28,7 +28,17 @@ const StyledRadioInput = styled.label.withConfig({shouldForwardProp})<StyledSwitconst HiddenInput = styled.input.withConfig({shouldForwardProp})`position: absolute;+ width: 1px;+ height: 1px;+ margin: -1px;+ padding: 0;+ overflow: hidden;+ clip: rect(0, 0, 0, 0);+ clip-path: inset(50%);+ white-space: nowrap;+ border: 0;opacity: 0;+ pointer-events: none;`;interface StyledCheckboxProps {@@ -113,8 +123,7 @@ const Checkbox: FC<CheckboxProps> = ({const labelProps = {checked,disabled,- secondary,- htmlFor: id+ secondary};const LabelElement =@@ -130,8 +139,8 @@ const Checkbox: FC<CheckboxProps> = ({className={classnames('kg-checkbox', className)}disabled={disabled}>- <HiddenInput {...inputProps} /><LabelElement className="kg-checkbox__label" {...labelProps}>+ <HiddenInput {...inputProps} />{label}</LabelElement></StyledCheckbox>diff --git a/src/components/src/effects/effect-time-configurator.tsx b/src/components/src/effects/effect-time-configurator.tsxindex dd0be7be0..e55285021 100644--- a/src/components/src/effects/effect-time-configurator.tsx+++ b/src/components/src/effects/effect-time-configurator.tsx@@ -75,10 +75,8 @@ const StyledRadio = styled(Checkbox)`}.kg-checkbox__label:before {background: transparent;- border-color: ${props => props.theme.effectPanelTextSecondary2};- }- input:checked + .kg-checkbox__label:before {- border-color: ${props => props.theme.activeColor};+ border-color: ${props =>+ props.checked ? props.theme.activeColor : props.theme.effectPanelTextSecondary2};}.kg-checkbox__label:after {background-color: ${props => props.theme.activeColor};diff --git a/src/components/src/side-panel/interaction-panel/legend-config.tsx b/src/components/src/side-panel/interaction-panel/legend-config.tsxindex 69998c11a..cc784adad 100644--- a/src/components/src/side-panel/interaction-panel/legend-config.tsx+++ b/src/components/src/side-panel/interaction-panel/legend-config.tsx@@ -68,9 +68,9 @@ const LegendRow = styled.div.withConfig({shouldForwardProp})<{$depth: number; $dopacity: ${props => (props.$dimmed ? 0.45 : 1)};`;-const LegendLabel = styled.label.withConfig({shouldForwardProp})<{$group?: boolean}>`+const LegendLabel = styled.span.withConfig({shouldForwardProp})<{$group?: boolean}>`color: ${props => props.theme.textColor};- cursor: pointer;+ display: block;font-size: 12px;font-weight: ${props => (props.$group ? 500 : 400)};overflow: hidden;@@ -78,6 +78,36 @@ const LegendLabel = styled.label.withConfig({shouldForwardProp})<{$group?: boolewhite-space: nowrap;`;+const RightAlignedSwitch = styled(Switch)`+ margin-left: 0;+ width: 100%;++ .kg-checkbox__label {+ box-sizing: border-box;+ color: inherit;+ display: block;+ font-size: inherit;+ font-weight: inherit;+ line-height: inherit;+ width: 100%;+ padding-left: 0;+ padding-right: ${props => props.theme.switchWidth + 8}px;+ }++ .kg-checkbox__label:before {+ right: 0;+ left: auto;+ }++ .kg-checkbox__label:after {+ right: ${props =>+ props.checked+ ? props.theme.switchWidth / 2 - props.theme.switchBtnWidth+ : props.theme.switchWidth - (props.theme.switchHeight + props.theme.switchBtnWidth) / 2}px;+ left: auto;+ }+`;+const LegendOptionRow = styled.div`color: ${props => props.theme.labelColor};display: flex;@@ -154,12 +184,10 @@ const LegendEntries: React.FC<LegendEntriesProps> = ({title={dimmed ? hiddenByGroupTitle : undefined}data-testid={`interaction-legend-row-${group.id}`}>- <LegendLabel $group htmlFor={`legend-include-${group.id}`}>- {group.label}- </LegendLabel>- <Switch+ <RightAlignedSwitchchecked={included}id={`legend-include-${group.id}`}+ label={<LegendLabel $group>{group.label}</LegendLabel>}secondaryonChange={() => onToggleGroup(group)}/>@@ -188,12 +216,10 @@ const LegendEntries: React.FC<LegendEntriesProps> = ({title={dimmed ? hiddenByGroupTitle : undefined}data-testid={`interaction-legend-row-${layer.id}`}>- <LegendLabel htmlFor={`legend-include-${layer.id}`}>- {layer.config.label || layer.id}- </LegendLabel>- <Switch+ <RightAlignedSwitchchecked={included}id={`legend-include-${layer.id}`}+ label={<LegendLabel>{layer.config.label || layer.id}</LegendLabel>}secondaryonChange={() => onToggleLayer(layer)}/>@@ -317,12 +343,10 @@ function LegendConfigFactory(<FormattedMessage id="interactions.legendHint" /></LegendHint><LegendOptionRow className="interaction-legend__hide-invisible">- <label htmlFor="legend-hide-invisible">- <FormattedMessage id="interactions.legendHideInvisible" />- </label>- <Switch+ <RightAlignedSwitchchecked={hideInvisibleLayers}id="legend-hide-invisible"+ label={<FormattedMessage id="interactions.legendHideInvisible" />}secondaryonChange={onToggleHideInvisible}/>diff --git a/test/browser/components/side-panel/interaction-manager-test.js b/test/browser/components/side-panel/interaction-manager-test.jsindex 1c293bb53..49652c483 100644--- a/test/browser/components/side-panel/interaction-manager-test.js+++ b/test/browser/components/side-panel/interaction-manager-test.js@@ -1,12 +1,15 @@// SPDX-License-Identifier: MIT// Copyright contributors to the kepler.gl project-import React from 'react';+import React, {act} from 'react';import test from 'tape';import sinon from 'sinon';+import {mount} from 'enzyme';+import {ThemeProvider} from 'styled-components';import {InteractionManagerFactory, appInjector} from '@kepler.gl/components';import {defaultInteractionConfig, getZoomOpacityAnnotationTargetId} from '@kepler.gl/reducers';+import {theme} from '@kepler.gl/styles';import {initApplicationConfig} from '@kepler.gl/utils';import {IntlWrapper, mountWithTheme} from 'test/helpers/component-utils';@@ -150,31 +153,36 @@ test('Components -> InteractionManager legend section', t => {'layer-2'];- const wrapper = mountWithTheme(- <IntlWrapper>- <InteractionManager- interactionConfig={{- legend: {- id: 'legend',- label: 'interactions.legend',- enabled: true,- config: {hideInvisibleLayers: false}- }- }}- datasets={{}}- panelMetadata={panelMetadata}- layers={[excludedLayer, includedLayer]}- layerOrder={layerOrder}- mapLegendActive={true}- uiStateActions={{toggleMapControl}}- visStateActions={{- interactionConfigChange,- setColumnDisplayFormat: () => {},- layerConfigChange,- updateLayerGroup- }}- />- </IntlWrapper>+ const container = document.createElement('div');+ document.body.appendChild(container);+ const wrapper = mount(+ <ThemeProvider theme={theme}>+ <IntlWrapper>+ <InteractionManager+ interactionConfig={{+ legend: {+ id: 'legend',+ label: 'interactions.legend',+ enabled: true,+ config: {hideInvisibleLayers: false}+ }+ }}+ datasets={{}}+ panelMetadata={panelMetadata}+ layers={[excludedLayer, includedLayer]}+ layerOrder={layerOrder}+ mapLegendActive={true}+ uiStateActions={{toggleMapControl}}+ visStateActions={{+ interactionConfigChange,+ setColumnDisplayFormat: () => {},+ layerConfigChange,+ updateLayerGroup+ }}+ />+ </IntlWrapper>+ </ThemeProvider>,+ {attachTo: container});t.ok(wrapper.find('.interaction-legend').hostNodes().length >= 1, 'renders legend section');@@ -201,19 +209,37 @@ test('Components -> InteractionManager legend section', t => {t.ok(text.includes('New group'), 'lists an excluded group so it can be restored');t.ok(text.includes('Cities'), 'lists an included layer');- wrapper.find('input#legend-include-layer-1').at(0).simulate('change');+ act(() => {+ wrapper+ .find('[data-testid="interaction-legend-row-layer-1"] label.kg-checkbox__label')+ .at(0)+ .getDOMNode()+ .click();+ });t.equal(layerConfigChange.callCount, 1, 'toggling a layer updates layer config');t.equal(layerConfigChange.args[0][0].id, 'layer-1');t.deepEqual(layerConfigChange.args[0][1], {isIncludedInLegend: true});- wrapper.find('input#legend-include-group-1').at(0).simulate('change');+ act(() => {+ wrapper+ .find('[data-testid="interaction-legend-row-group-1"] label.kg-checkbox__label')+ .at(0)+ .getDOMNode()+ .click();+ });t.equal(updateLayerGroup.callCount, 1, 'toggling a group updates the group');t.deepEqual(updateLayerGroup.args[0][0], {id: 'group-1',options: {isIncludedInLegend: true}});- wrapper.find('input#legend-include-layer-2').at(0).simulate('change');+ act(() => {+ wrapper+ .find('[data-testid="interaction-legend-row-layer-2"] label.kg-checkbox__label')+ .at(0)+ .getDOMNode()+ .click();+ });t.deepEqual(layerConfigChange.args[1][1], {isIncludedInLegend: false});t.equal(@@ -221,7 +247,13 @@ test('Components -> InteractionManager legend section', t => {false,'hide hidden layers starts off');- wrapper.find('input#legend-hide-invisible').at(0).simulate('change');+ act(() => {+ wrapper+ .find('.interaction-legend__hide-invisible label.kg-checkbox__label')+ .at(0)+ .getDOMNode()+ .click();+ });t.equal(interactionConfigChange.callCount,1,@@ -245,6 +277,8 @@ test('Components -> InteractionManager legend section', t => {'disabling the feature keeps the settings section open');+ act(() => wrapper.unmount());+ container.remove();t.end();});