sadpandajoe commented on code in PR #42910: URL: https://github.com/apache/superset/pull/42910#discussion_r4374082469
########## superset-frontend/src/explore/components/controls/IntervalColorsControl/IntervalColorsControl.test.tsx: ########## @@ -0,0 +1,384 @@ +/** + * 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 { + CategoricalScheme, + getCategoricalSchemeRegistry, +} from '@superset-ui/core'; +import IntervalColorsControl from 'src/explore/components/controls/IntervalColorsControl'; + +beforeAll(() => { + getCategoricalSchemeRegistry().registerValue( + 'testScheme', + new CategoricalScheme({ + id: 'testScheme', + colors: ['#1f77b4', '#ff7f0e', '#2ca02c'], + }), + ); +}); + +beforeEach(() => { + jest.clearAllMocks(); +}); + +test('renders a hint and no rows when no interval bounds are configured', () => { + render(<IntervalColorsControl onChange={jest.fn()} />); + + expect( + screen.getByText('Add interval bounds above to configure colors here.'), + ).toBeInTheDocument(); + expect(document.querySelectorAll('.ant-color-picker-trigger')).toHaveLength( + 0, + ); +}); + +test('renders one color picker row per parsed interval bound', () => { + render( + <IntervalColorsControl + onChange={jest.fn()} + intervals="20,60,100" + colorScheme="testScheme" + />, + ); + + expect(screen.getByText(/Up to 20/)).toBeInTheDocument(); + expect(screen.getByText(/Up to 60/)).toBeInTheDocument(); + expect(screen.getByText(/Up to 100/)).toBeInTheDocument(); + expect(document.querySelectorAll('.ant-color-picker-trigger')).toHaveLength( + 3, + ); +}); + +test('falls back to the categorical scheme when there is no explicit value or legacy data', () => { + render( + <IntervalColorsControl + onChange={jest.fn()} + intervals="20,60" + colorScheme="testScheme" + />, + ); + + expect(screen.getByText('#1F77B4')).toBeInTheDocument(); + expect(screen.getByText('#FF7F0E')).toBeInTheDocument(); +}); + +test('resolves legacy interval_color_indices against the color scheme for display', () => { + render( + <IntervalColorsControl + onChange={jest.fn()} + intervals="20,60" + legacyIntervalColorIndices="2,3" + colorScheme="testScheme" + />, + ); + + // 1-indexed: index 2 -> '#ff7f0e', index 3 -> '#2ca02c' + expect(screen.getByText('#FF7F0E')).toBeInTheDocument(); + expect(screen.getByText('#2CA02C')).toBeInTheDocument(); +}); + +test('disables editing while intervals has a blank token between numbers', async () => { + const onChange = jest.fn(); + render( + <IntervalColorsControl + onChange={onChange} + intervals="20,,60" + colorScheme="testScheme" + />, + ); + + // The blank middle token means the list is still being edited; don't + // allow commits that would misalign colors once the blank is filled in. + // Pin the row count first so the per-row assertions can't pass vacuously. + const triggers = document.querySelectorAll('.ant-color-picker-trigger'); + expect(triggers).toHaveLength(2); + triggers.forEach(trigger => { + expect(trigger).toHaveClass('ant-color-picker-trigger-disabled'); + }); + + // A change attempt on a disabled picker must neither open it nor commit. + await userEvent.click(triggers[0]); + expect( + document.querySelector('.ant-color-picker-presets-color'), + ).not.toBeInTheDocument(); + expect(onChange).not.toHaveBeenCalled(); +}); + +test('explicit value takes precedence over legacy indices', () => { + render( + <IntervalColorsControl + onChange={jest.fn()} + intervals="20,60" + value={['#ff0000', '#00ff00']} + legacyIntervalColorIndices="2,3" + colorScheme="testScheme" + />, + ); + + expect(screen.getByText('#FF0000')).toBeInTheDocument(); + expect(screen.getByText('#00FF00')).toBeInTheDocument(); +}); + +test('a non-positive legacy index falls back to the positional scheme color like the renderer', () => { + // The renderer computes `colors[(ind - 1) % n]`, which is `undefined` for + // index 0, so that band uses `colors[idx]`; it must not wrap to the last + // scheme color. + render( + <IntervalColorsControl + onChange={jest.fn()} + intervals="20,60" + legacyIntervalColorIndices="0,2" + colorScheme="testScheme" + />, + ); + + expect(screen.getByText('#1F77B4')).toBeInTheDocument(); + expect(screen.getByText('#FF7F0E')).toBeInTheDocument(); + expect(screen.queryByText('#2CA02C')).not.toBeInTheDocument(); +}); + +test('stays read-only when legacy indices cannot be resolved so untouched bands are never rewritten', async () => { + const onChange = jest.fn(); + render( + <IntervalColorsControl + onChange={onChange} + intervals="20,60" Review Comment: The read-only test omits `value`, but the Gauge control's default is `interval_colors: []` (`DEFAULT_FORM_DATA.intervalColors`). Dropping `value.length > 0` from `hasExplicitColors` would make `[]` count as explicit colors, re-enable editing for an unresolvable legacy chart, and every test here would still pass. Could this case also render with `value={[]}`, `intervals="20,60"` and `legacyIntervalColorIndices="10,3"`, then assert both triggers carry the disabled class and a click leaves `onChange` uncalled? ########## superset-frontend/src/explore/components/controls/IntervalColorsControl/index.tsx: ########## @@ -0,0 +1,125 @@ +/** + * 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 { getCategoricalSchemeRegistry } from '@superset-ui/core'; +import { + isRangesInputComplete, + hasTrailingBlankToken, +} from '@superset-ui/plugin-chart-echarts'; +import ControlHeader from '../../ControlHeader'; +import ColorPickerControl from '../ColorPickerControl'; +import type { ColorPickerValue } from '../ColorPickerControl'; +import { + RangeRow as IntervalRow, + RangeLabel as BoundLabel, + replaceColorAtIndex, +} from '../shared/RangeColorRow'; +import { IntervalColorsControlProps } from './types'; +import { + parseIntervalBounds as parseBounds, + resolveLegacyIntervalColors as resolveLegacyColors, +} from './legacyColors'; + +/** + * Per-interval color editor for the Gauge chart. Row *count* is driven by + * the sibling `intervals` control (one row per parsed upper bound) so bound + * values keep a single source of truth; this control only owns colors, + * stored as an array of hex strings positionally matched to those bounds. + */ +export default function IntervalColorsControl({ + value, + onChange, + intervals, + legacyIntervalColorIndices, + colorScheme, + ...headerProps +}: IntervalColorsControlProps) { + const bounds = parseBounds(intervals); + // `parseBounds` leniently drops blank tokens (e.g. mid-edit "20,,60"), + // which would otherwise shift colors to the wrong bound once the blank is + // filled back in -- same hazard `BulletRangeColorsControl` guards against. + const boundsComplete = isRangesInputComplete(intervals); + // Once `interval_colors` is populated the renderer ignores the legacy + // indices and falls back to the scheme's positional color for any missing + // entry, so the display must do the same to avoid persisting a different + // color into an untouched band. + const hasExplicitColors = Array.isArray(value) && value.length > 0; + // See the identical guard in `BulletRangeColorsControl`: while `intervals` + // ends in the one tolerated trailing blank (the last bound is being + // retyped), `bounds` is transiently one entry short. Writing a color at + // that moment must not truncate the array to that shorter length, or the + // color for the bound being retyped is permanently lost. For a legacy + // chart with no explicit colors yet, the legacy indices are the only + // record of how many bands there were, so they set that floor too; + // otherwise the first color edit in this window would persist a shorter + // explicit array, and the bound being retyped would come back with the + // positional scheme color instead of its legacy one. + const legacyIndexCount = legacyIntervalColorIndices?.trim() + ? legacyIntervalColorIndices.split(',').length + : 0; + const writeLength = hasTrailingBlankToken(intervals) + ? Math.max( + bounds.length, + value?.length ?? 0, + hasExplicitColors ? 0 : legacyIndexCount, + ) + : bounds.length; + const legacyColors = resolveLegacyColors( + writeLength, + legacyIntervalColorIndices, + colorScheme, + ); + const schemeColors = + getCategoricalSchemeRegistry().get(colorScheme)?.colors ?? []; + const colorAt = (index: number): string => + value?.[index] || + (hasExplicitColors ? '' : legacyColors[index]) || + schemeColors[index % (schemeColors.length || 1)] || Review Comment: Part of this still reproduces: the read-only guard only covers unresolved legacy indices, but the renderer also expands its palette under `USE_ANALOGOUS_COLORS` when there are more bands than colors, with no legacy indices at all. Example: a nine-color scheme with ten bounds and no `interval_colors` renders band 10 with an analogous color, while `colorAt(9)` shows static color 1; editing band 1 persists that wrapped color into band 10. The same happens when `interval_colors` holds fewer entries than the bounds. Could the editor stay read-only (or resolve against the render-time palette) whenever a band index is past the static scheme length and has no explicit color? -- 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]
