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


##########
superset-frontend/plugins/plugin-chart-echarts/src/BigNumber/BigNumberPeriodOverPeriod/PopKPI.tsx:
##########
@@ -195,15 +203,13 @@ export default function PopKPI(props: PopKPIProps) {
     let bgColor = defaultBackgroundColor;
     let txtColor = defaultTextColor;
     if (comparisonColorEnabled && percentDifferenceNumber !== 0) {
-      const useSuccess =
-        (percentDifferenceNumber > 0 &&
-          comparisonColorScheme === ColorSchemeEnum.Green) ||
-        (percentDifferenceNumber < 0 &&
-          comparisonColorScheme === ColorSchemeEnum.Red);
-
-      // Set background and text colors based on the conditions
-      bgColor = useSuccess ? theme.colorSuccessBg : theme.colorErrorBg;
-      txtColor = useSuccess ? theme.colorSuccessText : theme.colorErrorText;
+      const colorValue =
+        percentDifferenceNumber > 0
+          ? resolvedIncreaseColor
+          : resolvedDecreaseColor;

Review Comment:
   Good catch, hoisted a single `comparisonColorValue` that both the arrow and 
the pill read from now.



##########
superset-frontend/src/features/themes/ThemeColorPickers.tsx:
##########
@@ -0,0 +1,174 @@
+/**
+ * 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;

Review Comment:
   Fair point. Added a `disabled` prop to `ColorPickerControl` (straight 
pass-through to antd), and the theme pickers disable whenever the JSON is 
invalid or the editor is read-only, with tests for both.



##########
superset-frontend/plugins/plugin-chart-echarts/src/BigNumber/BigNumberPeriodOverPeriod/controlPanel.ts:
##########
@@ -100,21 +100,57 @@ const config: ControlPanelConfig = {
         ],
         [
           {
-            name: 'comparison_color_scheme',
+            name: 'increase_color',
             config: {
-              type: 'SelectControl',
-              label: t('color scheme for comparison'),
-              default: ColorSchemeEnum.Green,
+              type: 'ColorPickerControl',
+              label: t('Color for increase'),
+              // No static default: charts saved before this control existed
+              // only have `comparison_color_scheme` ('Green' | 'Red', where
+              // 'Red' reverses increase/decrease colors). Leaving this
+              // 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.
               renderTrigger: true,
-              choices: [
-                [ColorSchemeEnum.Green, 'Green for increase, red for 
decrease'],
-                [ColorSchemeEnum.Red, 'Red for increase, green for decrease'],
+              presets: [
+                {
+                  label: t('Semantic colors'),
+                  colors: [ColorSchemeEnum.Green, ColorSchemeEnum.Red],
+                },
               ],
+              resolveThemeTokens: true,
+              outputFormat: 'hex',
               visibility: ({ controls }) =>
                 controls?.comparison_color_enabled?.value === true,
               description: t(
-                'Adds color to the chart symbols based on the positive or ' +
-                  'negative change from the comparison value.',
+                'Color used for the arrow and symbols when the metric ' +
+                  'increased from the comparison value. Defaults to green.',
+              ),
+            },
+          },
+          {
+            name: 'decrease_color',
+            config: {
+              type: 'ColorPickerControl',
+              label: t('Color for decrease'),
+              // See the comment on `increase_color` above: no static
+              // default, so `resolveComparisonColorKeys` can apply the
+              // legacy `comparison_color_scheme` fallback for old charts.
+              renderTrigger: true,
+              presets: [
+                {
+                  label: t('Semantic colors'),
+                  colors: [ColorSchemeEnum.Green, ColorSchemeEnum.Red],
+                },
+              ],
+              resolveThemeTokens: true,
+              outputFormat: 'hex',
+              visibility: ({ controls }) =>
+                controls?.comparison_color_enabled?.value === true,
+              description: t(
+                'Color used for the arrow and symbols when the metric ' +
+                  'decreased from the comparison value. Defaults to red.',
               ),
             },
           },

Review Comment:
   Done, pulled the shared bits into a `comparisonColorControlConfig` that both 
controls spread, so only `label` and `description` differ now.



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