aminghadersohi commented on code in PR #42910:
URL: https://github.com/apache/superset/pull/42910#discussion_r4376003190


##########
superset-frontend/plugins/plugin-chart-echarts/src/BigNumber/BigNumberPeriodOverPeriod/controlPanel.ts:
##########
@@ -35,6 +36,30 @@ import {
   metricNameFontSizeWithVisibility,
 } from '../sharedControls';
 
+// Shared base for the `increase_color` / `decrease_color` pickers so the
+// presets, token resolution, output format and visibility rule can't drift
+// apart. No static default: charts saved before these controls existed only
+// have `comparison_color_scheme` ('Green' | 'Red', where 'Red' reverses
+// increase/decrease colors). Leaving each control's value undefined lets
+// `resolveComparisonColorKeys` (see BigNumberPeriodOverPeriod/utils.ts)
+// resolve the correct color from that legacy scheme at render time. A
+// hardcoded default here would win over the legacy fallback via
+// `applyDefaultFormData` and silently repaint old dashboards.
+const comparisonColorControlConfig: CustomControlItem['config'] = {

Review Comment:
   With no `increase_color`/`decrease_color` saved (any new chart), both 
pickers read 'Transparent' while PopKPI paints the theme success/error colors, 
so the editor never shows what the chart draws.



##########
superset-frontend/src/explore/components/controls/IntervalColorsControl/index.tsx:
##########
@@ -0,0 +1,135 @@
+/**
+ * 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 ?? [];
+  // Legacy indices past the static palette resolve only against the
+  // renderer's render-time palette, so the editor cannot show (or safely
+  // persist) the colors the chart renders. Stay read-only until explicit
+  // colors exist, so a row edit never rewrites an untouched band.
+  const legacyUnresolved =
+    !hasExplicitColors &&
+    legacyIndexCount > 0 &&
+    legacyColors.length > 0 &&
+    legacyColors.every(color => color === '');
+  const editable = boundsComplete && !legacyUnresolved;

Review Comment:
   When an in-use legacy index is past the static palette, every row is 
disabled with no explanation and the legacy field is hidden, so these bands 
can't be recolored except by switching scheme, while the help text still says 
colors follow the scheme until one is edited.



##########
superset-frontend/src/explore/components/controls/IntervalColorsControl/legacyColors.ts:
##########
@@ -0,0 +1,89 @@
+/**
+ * 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 {
+  getCategoricalSchemeRegistry,
+  validateNumber,
+} from '@superset-ui/core';
+
+export const parseIntervalBounds = (intervals?: string): number[] =>
+  (intervals ?? '')
+    .split(',')
+    .map(part => part.trim())
+    .filter(part => part !== '')
+    .map(Number)
+    .filter(bound => Number.isFinite(bound));
+
+/**
+ * Resolves the legacy `interval_color_indices` control (comma-separated,
+ * 1-indexed positions into the chosen categorical color scheme) into real
+ * hex colors, one per interval band (`boundCount` entries). Shared by the
+ * control panel (display-only fallback while a legacy chart is being edited)
+ * and by `handleDeprecatedControls` (which, on request, migrates the value
+ * into `interval_colors`).
+ */
+export const resolveLegacyIntervalColors = (
+  boundCount: number,
+  legacyIntervalColorIndices: string | undefined,
+  colorScheme: string | undefined,
+): string[] => {
+  // Non-strict lookup mirrors the Gauge renderer: an unregistered scheme
+  // falls back to the registry's default scheme.
+  const schemeColors =
+    getCategoricalSchemeRegistry().get(colorScheme)?.colors ?? [];
+  // Parse with the exact same semantics `getIntervalBoundsAndColors` in
+  // Gauge/transformProps.ts uses for this same legacy fallback (via
+  // `parseNumbersList`, not reimported here to avoid pulling the whole
+  // `@superset-ui/plugin-chart-echarts` package -- and every chart plugin it
+  // eagerly registers -- into `explore/store.ts`'s import graph): one
+  // unparseable (or blank) token discards every legacy index for the whole
+  // list, rather than resolving the other tokens independently. A more
+  // lenient parser here would let this one-time migration (and this
+  // display-only preview) disagree with how an untouched legacy chart has
+  // always rendered -- see #42910 review thread on this file.
+  let indices: number[];
+  try {
+    indices = (legacyIntervalColorIndices ?? '').split(',').map(part => {
+      if (validateNumber(part)) throw new Error('All values must be numeric');
+      return Number(part);
+    });
+  } catch {
+    indices = [];
+  }
+  // An index past the static palette can only be resolved against the
+  // renderer's render-time palette (which grows under USE_ANALOGOUS_COLORS),
+  // so wrapping it modulo the static scheme would show -- and, once a row is
+  // edited, persist -- a different color than the chart renders. Leave every
+  // band unresolved so such charts keep rendering through the renderer's own
+  // legacy path.
+  if (indices.some(index => index > schemeColors.length)) {

Review Comment:
   Only the first `boundCount` legacy indices are rendered, but every one is 
checked here: indices `2,3,7` on a 3-color scheme with bounds `20,60` lock both 
rows and show positional colors, not the rendered `#ff7f0e`/`#2ca02c`.
   
   ```suggestion
     if (indices.slice(0, boundCount).some(index => index > 
schemeColors.length)) {
   ```



-- 
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]

Reply via email to