bito-code-review[bot] commented on code in PR #42910:
URL: https://github.com/apache/superset/pull/42910#discussion_r4165186128
##########
superset-frontend/src/explore/store.ts:
##########
@@ -89,6 +104,45 @@ export function handleDeprecatedControls(formData:
FormData): void {
formData.matrixify_mode_columns = 'disabled';
}
}
+
+ // #42910: migrate the legacy BigNumberPeriodOverPeriod
+ // `comparison_color_scheme` ('Green' | 'Red', where 'Red' reverses
+ // increase/decrease colors) into the `increase_color` / `decrease_color`
+ // ColorPickerControls that replaced it. `comparison_color_scheme` is no
+ // longer a registered control, so `getFormDataFromControls` drops it the
+ // next time the chart is saved -- without this migration, that silently
+ // discards a reversed-color choice the first time an old chart is resaved.
+ if (
+ formData.viz_type === VizType.BigNumberPeriodOverPeriod &&
+ formData.comparison_color_scheme &&
+ formData.increase_color === undefined &&
+ formData.decrease_color === undefined
+ ) {
+ const legacyReversed = formData.comparison_color_scheme === 'Red';
+ formData.increase_color = legacyReversed ? 'Red' : 'Green';
+ formData.decrease_color = legacyReversed ? 'Green' : 'Red';
Review Comment:
<!-- Bito Reply -->
The suggestion to use `ColorSchemeEnum` is appropriate. It improves
maintainability by ensuring that the migration logic remains synchronized with
the render-time fallback, preventing potential discrepancies if the legacy
color scheme semantics are updated in the future.
**superset-frontend/src/explore/store.ts**
```
const legacyReversed = formData.comparison_color_scheme ===
ColorSchemeEnum.Red;
formData.increase_color = legacyReversed ? ColorSchemeEnum.Red :
ColorSchemeEnum.Green;
formData.decrease_color = legacyReversed ? ColorSchemeEnum.Green :
ColorSchemeEnum.Red;
```
##########
superset-frontend/src/explore/components/controls/BulletRangeColorsControl/index.tsx:
##########
@@ -0,0 +1,107 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { t } from '@apache-superset/core/translation';
+import { Button } from '@superset-ui/core/components';
+import {
+ tokenizeToNumericArray,
+ isRangesInputComplete,
+} from '@superset-ui/plugin-chart-echarts';
+import ControlHeader from '../../ControlHeader';
+import ColorPickerControl from '../ColorPickerControl';
+import type { ColorPickerValue } from '../ColorPickerControl';
+import {
+ RangeRow,
+ RangeLabel,
+ replaceColorAtIndex,
+} from '../shared/RangeColorRow';
+import { BulletRangeColorsControlProps } from './types';
+
+/**
+ * Per-range color editor for the Bullet chart. Row *count* is driven by the
+ * sibling `ranges` control (one row per parsed threshold) so range values
+ * keep a single source of truth; this control only owns colors, stored as
+ * an array of hex strings positionally matched to those thresholds. An
+ * empty string entry (or a missing entry past the end of the array) means
+ * "no custom color" -- `Bullet/transformProps.ts` falls back to the default
+ * theme-token band ramp for that range, so existing saved Bullet charts
+ * (which have no `range_colors` at all) render identically to before this
+ * control existed.
+ */
+export default function BulletRangeColorsControl({
+ value,
+ onChange,
+ ranges,
+ ...headerProps
+}: BulletRangeColorsControlProps) {
+ const rangeValues = tokenizeToNumericArray(ranges) ?? [];
+ // While `ranges` is mid-edit (e.g. "20,,60"), tokenizeToNumericArray's
+ // leniency silently compacts it to a shorter list, which would otherwise
+ // shift colors to the wrong positions. Block commits until it's complete
+ // again so no edit can be positionally misaligned once it is.
+ const rangesComplete = isRangesInputComplete(ranges);
+
+ const colorAt = (index: number): string => value?.[index] || '';
+
+ const handleColorChange = (index: number) => (color: ColorPickerValue) => {
+ if (typeof color !== 'string' || !rangesComplete) return;
+ onChange?.(replaceColorAtIndex(rangeValues.length, index, color, colorAt));
+ };
+
+ const handleReset = (index: number) => {
+ if (!rangesComplete) return;
+ onChange?.(replaceColorAtIndex(rangeValues.length, index, '', colorAt));
+ };
+
+ return (
+ <div>
+ <ControlHeader {...headerProps} />
+ {rangeValues.length === 0 ? (
+ <RangeLabel>
+ {t('Add ranges above to configure their colors here.')}
+ </RangeLabel>
+ ) : (
+ rangeValues.map((range, index) => (
+ // eslint-disable-next-line react/no-array-index-key
+ <RangeRow key={index}>
Review Comment:
<!-- Bito Reply -->
The update to use `t('Up to %s', range)` is appropriate. This change
correctly addresses the issue of fragmented i18n labels by allowing translators
to handle the full phrase, including the interpolated value, which improves
localization consistency.
**superset-frontend/src/explore/components/controls/BulletRangeColorsControl/index.tsx**
```
rangeValues.map((range, index) => (
// eslint-disable-next-line react/no-array-index-key
<RangeRow key={index}>
```
##########
superset-frontend/src/explore/components/controls/BulletRangeColorsControl/BulletRangeColorsControl.test.tsx:
##########
@@ -0,0 +1,144 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import {
+ render,
+ screen,
+ userEvent,
+ waitFor,
+} from 'spec/helpers/testing-library';
+import BulletRangeColorsControl from
'src/explore/components/controls/BulletRangeColorsControl';
+
+beforeEach(() => {
+ jest.clearAllMocks();
+});
+
+test('renders a hint and no rows when no ranges are configured', () => {
+ render(<BulletRangeColorsControl onChange={jest.fn()} />);
+
+ expect(
+ screen.getByText('Add ranges above to configure their colors here.'),
+ ).toBeInTheDocument();
+ expect(document.querySelectorAll('.ant-color-picker-trigger')).toHaveLength(
+ 0,
+ );
+});
+
+test('renders one color picker row per parsed range, unset by default', () => {
+ render(
+ <BulletRangeColorsControl onChange={jest.fn()} ranges="100,200,300" />,
+ );
+
+ expect(screen.getByText(/Up to 100/)).toBeInTheDocument();
+ expect(screen.getByText(/Up to 200/)).toBeInTheDocument();
+ expect(screen.getByText(/Up to 300/)).toBeInTheDocument();
+ expect(document.querySelectorAll('.ant-color-picker-trigger')).toHaveLength(
+ 3,
+ );
+ // no row has a custom color yet, so no "Use default" reset link shows
+ expect(screen.queryByText('Use default')).not.toBeInTheDocument();
+});
+
+test('shows a "Use default" reset link only for rows with a custom color', ()
=> {
+ render(
+ <BulletRangeColorsControl
+ onChange={jest.fn()}
+ ranges="100,200"
+ value={['#ff0000', '']}
+ />,
+ );
+
+ expect(screen.getAllByText('Use default')).toHaveLength(1);
+});
+
+test('calls onChange with the full color array when a row color is picked',
async () => {
+ const onChange = jest.fn();
+ render(
+ <BulletRangeColorsControl
+ onChange={onChange}
+ ranges="100,200"
+ value={['', '']}
+ />,
+ );
+
+ const triggers = document.querySelectorAll('.ant-color-picker-trigger');
+ expect(triggers).toHaveLength(2);
+
+ await userEvent.click(triggers[0]);
+ await waitFor(() => {
+ expect(document.querySelector('.ant-color-picker')).toBeInTheDocument();
+ });
+
+ const hexInput = document.querySelector<HTMLInputElement>(
+ '.ant-color-picker-input input',
+ );
+ expect(hexInput).toBeInTheDocument();
+ await userEvent.clear(hexInput!);
+ await userEvent.type(hexInput!, '00ff00{enter}');
+
+ await waitFor(() => {
+ expect(onChange).toHaveBeenCalled();
+ });
+ const lastCall = onChange.mock.calls[onChange.mock.calls.length - 1][0];
+ expect(lastCall[0].toLowerCase()).toBe('#00ff00');
+ expect(lastCall[1]).toBe('');
+});
+
+test('resets a single row back to "no custom color" without touching the
others', async () => {
+ const onChange = jest.fn();
+ render(
+ <BulletRangeColorsControl
+ onChange={onChange}
+ ranges="100,200"
+ value={['#ff0000', '#00ff00']}
+ />,
+ );
+
+ const resetButtons = screen.getAllByText('Use default');
+ expect(resetButtons).toHaveLength(2);
+ await userEvent.click(resetButtons[0]);
+
+ await waitFor(() => {
+ expect(onChange).toHaveBeenCalledWith(['', '#00ff00']);
+ });
+});
+
+test('disables editing and resets while ranges has a blank token between
numbers', () => {
+ const onChange = jest.fn();
+ render(
+ <BulletRangeColorsControl
+ onChange={onChange}
+ ranges="20,,60"
+ value={['#ff0000', '#00ff00', '#0000ff']}
+ />,
+ );
+
+ // The blank middle token means the list is still being edited; don't
+ // collapse row count or allow commits that would misalign colors once
+ // the blank is filled back in.
+ document.querySelectorAll('.ant-color-picker-trigger').forEach(trigger => {
+ expect(trigger).toHaveClass('ant-color-picker-trigger-disabled');
+ });
+ // AntD's Button always wraps its text child in an inner <span>, so
+ // querying by text here would match that span -- which `toBeDisabled`
+ // never recognizes (it only supports actual form-control elements).
+ // Query by role to get the real <button>, where `disabled` lives.
+ screen.getAllByRole('button', { name: 'Use default' }).forEach(button => {
+ expect(button).toBeDisabled();
+ });
+});
Review Comment:
<!-- Bito Reply -->
The added assertion correctly addresses the suggestion to ensure `onChange`
is not called when the UI is in a disabled state. This improves test coverage
by verifying that the component maintains its expected behavior under
restricted conditions.
**superset-frontend/src/explore/components/controls/BulletRangeColorsControl/BulletRangeColorsControl.test.tsx**
```
screen.getAllByRole('button', { name: 'Use default' }).forEach(button => {
expect(button).toBeDisabled();
});
expect(onChange).not.toHaveBeenCalled();
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]