sadpandajoe commented on code in PR #42910: URL: https://github.com/apache/superset/pull/42910#discussion_r4299753258
########## superset-frontend/src/features/themes/ThemeColorPickers.tsx: ########## @@ -0,0 +1,175 @@ +/** + * 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 { useMemo } from 'react'; +import { t } from '@apache-superset/core/translation'; +import { styled } from '@apache-superset/core/theme'; +import { Typography } from '@superset-ui/core/components/Typography'; +import ColorPickerControl from 'src/explore/components/controls/ColorPickerControl'; +import type { ColorPickerValue } from 'src/explore/components/controls/ColorPickerControl'; + +/** + * Curated antd theme SEED tokens (plus a handful of the most load-bearing + * MapToken/AliasToken derivatives) surfaced as individual color pickers, so + * the common case -- "change the brand color" -- doesn't require pasting a + * hand-edited JSON blob. This intentionally does not attempt to cover the + * full antd token surface (100+ tokens): anything not listed here is still + * fully editable via the JSON textarea below, which remains the source of + * truth. Names are taken directly from antd's own `SeedToken` / + * `MapToken` types -- see `antd/es/theme/interface/{seeds,maps/colors}.d.ts` + * -- never invented. + */ +export const CURATED_COLOR_TOKENS = [ + { key: 'colorPrimary', label: () => t('Primary') }, + { key: 'colorSuccess', label: () => t('Success') }, + { key: 'colorWarning', label: () => t('Warning') }, + { key: 'colorError', label: () => t('Error') }, + { key: 'colorInfo', label: () => t('Info') }, + { key: 'colorLink', label: () => t('Link') }, + { key: 'colorText', label: () => t('Text') }, + { key: 'colorTextSecondary', label: () => t('Secondary text') }, + { key: 'colorBgBase', label: () => t('Base background') }, + { key: 'colorBgContainer', label: () => t('Container background') }, + { key: 'colorBorder', label: () => t('Border') }, +] as const; + +export type CuratedColorToken = (typeof CURATED_COLOR_TOKENS)[number]['key']; + +interface ParsedThemeJson { + token?: Record<string, unknown>; + [key: string]: unknown; +} + +const isPlainObject = (value: unknown): value is Record<string, unknown> => + typeof value === 'object' && value !== null && !Array.isArray(value); + +/** Attempts to parse `jsonData` as a theme config object; returns `null` + * (never throws) when the JSON is empty, mid-edit, or otherwise invalid -- + * matching the JSON-parse error handling already used elsewhere in + * ThemeModal (`formatJsonData`, `isValidJson`). A `token` that parses but + * isn't itself a plain object (a string, array, or number) also counts as + * invalid here, since `patchThemeJsonToken` below spreads it -- and + * spreading a string or array silently rewrites it into numeric-keyed + * junk rather than the token map callers expect. */ +export const tryParseThemeJson = ( + jsonData: string | undefined, +): ParsedThemeJson | null => { + if (!jsonData?.trim()) return null; + try { + const parsed = JSON.parse(jsonData); + if (!isPlainObject(parsed)) return null; + if ( + 'token' in parsed && + parsed.token !== undefined && + !isPlainObject(parsed.token) + ) { + return null; + } + return parsed; + } catch { + return null; + } +}; + +/** Patches a single curated token into `jsonData`'s `token` object, + * preserving every other key (including tokens this UI doesn't curate) and + * re-serializing with the same 2-space indent used throughout this modal. */ +export const patchThemeJsonToken = ( + jsonData: string, + key: CuratedColorToken, + value: string, +): string => { + const parsed = tryParseThemeJson(jsonData) ?? {}; + const next = { + ...parsed, + token: { + ...parsed.token, + [key]: value, + }, + }; + return JSON.stringify(next, null, 2); +}; + +const TokenGrid = styled.div` + display: grid; + grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); + gap: ${({ theme }) => theme.sizeUnit * 3}px; + margin-bottom: ${({ theme }) => theme.sizeUnit * 4}px; +`; + +const TokenRow = styled.div` + display: flex; + align-items: center; + justify-content: space-between; + gap: ${({ theme }) => theme.sizeUnit * 2}px; +`; + +interface ThemeColorPickersProps { + jsonData: string; + onChange: (nextJsonData: string) => void; + disabled?: boolean; +} + +export default function ThemeColorPickers({ + jsonData, + onChange, + disabled = false, +}: ThemeColorPickersProps) { + const parsed = useMemo(() => tryParseThemeJson(jsonData), [jsonData]); + const isValid = parsed !== null; + const tokenValues = parsed?.token ?? {}; + + const handleTokenChange = + (key: CuratedColorToken) => (color: ColorPickerValue) => { + if (typeof color !== 'string' || !isValid || disabled) return; + onChange(patchThemeJsonToken(jsonData, key, color)); + }; + + return ( + <div data-test="theme-color-pickers"> + {!isValid && ( + <Typography.Text + type="secondary" + data-test="theme-color-pickers-invalid-json-notice" + > + {t( + 'Fix the JSON errors below to edit colors here; your changes ' + + 'sync automatically once the JSON is valid again.', + )} + </Typography.Text> + )} + <TokenGrid> + {CURATED_COLOR_TOKENS.map(({ key, label }) => { + const tokenValue = tokenValues[key]; + return ( + <TokenRow key={key} data-test={`theme-color-picker-${key}`}> + <Typography.Text>{label()}</Typography.Text> + <ColorPickerControl + ariaLabel={label()} + value={typeof tokenValue === 'string' ? tokenValue : undefined} Review Comment: A theme whose JSON has `{"token":{"colorPrimary":"Red"}}` is valid CSS red (`#ff0000`), but `ColorPickerControl` treats the string `Red` as the Green/Red comparison preset even without `resolveThemeTokens`, so this picker shows `#96000033`. Nudging the opacity then writes that wrong color back into the theme. Should this caller normalize literal color strings, or turn off the preset lookup for theme tokens? ########## superset-frontend/src/explore/components/controls/IntervalColorsControl/index.tsx: ########## @@ -0,0 +1,103 @@ +/** + * 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 } 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); + const legacyColors = resolveLegacyColors( + bounds, + legacyIntervalColorIndices, + colorScheme, + ); + const schemeColors = + getCategoricalSchemeRegistry().get(colorScheme)?.colors ?? []; + + // 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; Review Comment: The partial-explicit case isn't covered at the editor boundary: with `intervals="20,60"`, `value={['#ff0000']}` and legacy indices `"3,1"`, the second row should show the scheme's positional color rather than the legacy one. The only precedence test passes a full two-entry array, so reverting `hasExplicitColors` would still pass while editing row 1 silently persists the wrong color for row 2. Could you add a test that renders this partial value and asserts the second swatch and the `onChange` array after editing the first row? ########## superset/mcp_service/chart/chart_utils.py: ########## @@ -4228,6 +4238,9 @@ def merge_update_form_data( # noqa: C901 | FORM_DATA_UPDATE_PRESERVE_KEYS["presentation"] | FORM_DATA_UPDATE_PRESERVE_KEYS["time"] ) - _get_known_fields(BulletChartConfig) +# Explore-authored Bullet controls the typed config does not model. They are +# preserved on update but excluded from the typed validation copy. +_BULLET_UNMODELED_NATIVE_KEYS = frozenset({"range_colors"}) Review Comment: The new `range_colors` exemption that keeps a saved Bullet chart's colors out of the typed validation copy has no regression test. If someone drops it from this set, an MCP `update_chart` that only changes the metric on a Bullet saved with `range_colors: ["#ff0000", "#00ff00"]` (or `[]`) starts rejecting the merged state as an unknown field, and nothing in `test_bullet_chart.py` would fail. Could you add a test that merges such an update and asserts `validate_merged_bullet_form_data` succeeds with the colors unchanged? -- 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]
