Copilot commented on code in PR #37712:
URL: https://github.com/apache/superset/pull/37712#discussion_r2775458882


##########
superset-frontend/packages/superset-ui-chart-controls/test/shared-controls/xAxisSortControl.test.ts:
##########
@@ -0,0 +1,100 @@
+/**
+ * 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 { ControlPanelState } from '../../src/types';
+import { xAxisSortControl } from '../../src/shared-controls/customControls';
+
+const createState = (
+  overrides: Partial<ControlPanelState>,
+): ControlPanelState =>
+  ({
+    slice: { slice_id: 1 },
+    form_data: {},
+    datasource: {
+      column_formats: {},
+      verbose_map: {},
+    },
+    controls: {},
+    common: {},
+    metadata: {},
+    ...overrides,
+  }) as ControlPanelState;
+
+const createControlState = (value: unknown = undefined) => ({ value }) as any;
+
+test('xAxisSortControl includes axis and metric options when there is no 
dimension', () => {
+  const state = createState({
+    controls: {
+      x_axis: { value: 'ds', type: 'Select' },
+      groupby: { value: [], type: 'Select' },
+      metrics: { value: ['metric_1'], type: 'Select' },
+      timeseries_limit_metric: { value: 'sort_metric', type: 'Select' },
+      datasource: {
+        datasource: {
+          columns: [],
+          metrics: [],
+        },
+        type: 'Select',
+      },
+    },
+  });
+
+  const { options } = xAxisSortControl.config.mapStateToProps!(
+    state,
+    createControlState(),
+  ) as { options: { value: string }[] };
+
+  const values = options.map(opt => opt.value);
+
+  expect(values).toContain('ds');
+  expect(values).toContain('metric_1');
+});
+
+test('xAxisSortControl keeps axis and metric options when a dimension is set', 
() => {
+  const state = createState({
+    controls: {
+      x_axis: { value: 'ds', type: 'Select' },
+      groupby: { value: ['dim'], type: 'Select' },
+      metrics: { value: ['metric_1'], type: 'Select' },
+      timeseries_limit_metric: { value: 'sort_metric', type: 'Select' },
+      datasource: {
+        datasource: {
+          columns: [],
+          metrics: [],
+        },
+        type: 'Select',
+      },
+    },
+  });
+
+  const { options } = xAxisSortControl.config.mapStateToProps!(
+    state,
+    createControlState(),
+  ) as { options: { value: string }[] };
+
+  const values = options.map(opt => opt.value);
+
+  // Axis and metric choices should still be present
+  expect(values).toContain('ds');
+  expect(values).toContain('metric_1');
+
+  // And multi-series sort choices should also be available

Review Comment:
   This test asserts that axis/metric labels (e.g. `ds`, `metric_1`) remain 
valid sort option values when `groupby` is set. However, in multi-series mode 
the ECharts Timeseries/Bar code path treats the sort value as a 
`SortSeriesType` enum (`name`/`sum`/etc), so allowing arbitrary metric labels 
can lead to unsupported values. Consider adjusting the implementation (and then 
the test) to verify only supported values are exposed, or add coverage for the 
value-encoding/mapping used to make metric-based sorting actually work with 
dimensions.



##########
superset-frontend/packages/superset-ui-chart-controls/src/shared-controls/customControls.tsx:
##########
@@ -146,37 +146,44 @@ export const xAxisSortControl = {
       const columns = [controls?.x_axis?.value as QueryFormColumn].filter(
         Boolean,
       );
-      const isSingleSortAvailable =
-        ensureIsArray(controls?.groupby?.value).length === 0;
-      const isMultiSortAvailable =
-        !!ensureIsArray(controls?.groupby?.value).length ||
+      const hasGroupBy = ensureIsArray(controls?.groupby?.value).length > 0;
+      const hasMultipleMetrics =
         ensureIsArray(controls?.metrics?.value).length > 1;
+      const isMultiSortAvailable = hasGroupBy || hasMultipleMetrics;
       const metrics = [
         ...ensureIsArray(controls?.metrics?.value as QueryFormMetric),
         controls?.timeseries_limit_metric?.value as QueryFormMetric,
       ].filter(Boolean);
       const metricLabels = [...new Set(metrics.map(getMetricLabel))];
-      const options = [
-        ...(isSingleSortAvailable
-          ? [
-              ...columns.map(column => {
-                const value = getColumnLabel(column);
-                return { value, label: dataset?.verbose_map?.[value] || value 
};
-              }),
-              ...metricLabels.map(value => ({
-                value,
-                label: dataset?.verbose_map?.[value] || value,
-              })),
-            ]
-          : []),
-        ...(isMultiSortAvailable
-          ? SORT_SERIES_CHOICES.map(choice => ({
-              value: choice[0],
-              label: choice[1],
-            }))
-          : []),
+
+      // Base axis sort options: always include the explicit axis column and 
metrics,
+      // regardless of whether a dimension (groupby) is present. This keeps the
+      // "X-Axis Sort By" dropdown consistent when toggling dimensions.
+      const axisSortOptions = [
+        ...columns.map(column => {

Review Comment:
   `axisSortOptions` are now included even when `groupby` is set 
(multi-series). In the ECharts Timeseries/Bar pipeline, `xAxisSort` is 
interpreted as a `SortSeriesType` (name/sum/min/max/avg) for multi-series 
sorting; exposing arbitrary axis/metric labels here can yield unsupported 
values and result in incorrect/no sorting. Either keep multi-series options 
limited to `SORT_SERIES_CHOICES`, or add an explicit encoding/mapping (and 
update the consumer) so column/metric-based sorting is actually supported with 
dimensions.



##########
superset-frontend/packages/superset-ui-chart-controls/src/shared-controls/customControls.tsx:
##########
@@ -146,37 +146,44 @@ export const xAxisSortControl = {
       const columns = [controls?.x_axis?.value as QueryFormColumn].filter(
         Boolean,
       );
-      const isSingleSortAvailable =
-        ensureIsArray(controls?.groupby?.value).length === 0;
-      const isMultiSortAvailable =
-        !!ensureIsArray(controls?.groupby?.value).length ||
+      const hasGroupBy = ensureIsArray(controls?.groupby?.value).length > 0;
+      const hasMultipleMetrics =
         ensureIsArray(controls?.metrics?.value).length > 1;
+      const isMultiSortAvailable = hasGroupBy || hasMultipleMetrics;
       const metrics = [
         ...ensureIsArray(controls?.metrics?.value as QueryFormMetric),
         controls?.timeseries_limit_metric?.value as QueryFormMetric,
       ].filter(Boolean);
       const metricLabels = [...new Set(metrics.map(getMetricLabel))];
-      const options = [
-        ...(isSingleSortAvailable
-          ? [
-              ...columns.map(column => {
-                const value = getColumnLabel(column);
-                return { value, label: dataset?.verbose_map?.[value] || value 
};
-              }),
-              ...metricLabels.map(value => ({
-                value,
-                label: dataset?.verbose_map?.[value] || value,
-              })),
-            ]
-          : []),
-        ...(isMultiSortAvailable
-          ? SORT_SERIES_CHOICES.map(choice => ({
-              value: choice[0],
-              label: choice[1],
-            }))
-          : []),
+
+      // Base axis sort options: always include the explicit axis column and 
metrics,
+      // regardless of whether a dimension (groupby) is present. This keeps the
+      // "X-Axis Sort By" dropdown consistent when toggling dimensions.
+      const axisSortOptions = [
+        ...columns.map(column => {
+          const value = getColumnLabel(column);
+          return {
+            value,
+            label: dataset?.verbose_map?.[value as string] ?? value,
+          };
+        }),
+        ...metricLabels.map(value => ({
+          value,
+          label: dataset?.verbose_map?.[value as string] ?? value,
+        })),
       ];
 
+      // When there are multiple series (via groupby or multiple metrics),
+      // also expose the series-based sort options.
+      const multiSeriesOptions = isMultiSortAvailable
+        ? SORT_SERIES_CHOICES.map(([value, label]: [string, string]) => ({
+            value,
+            label,
+          }))
+        : [];
+
+      const options = [...axisSortOptions, ...multiSeriesOptions];

Review Comment:
   `options` concatenates `axisSortOptions` with `multiSeriesOptions` without 
de-duping by `value`. Since `SORT_SERIES_CHOICES` uses values like 
`name`/`sum`/`min`/`max`/`avg`, it’s easy for a real column/metric label to 
collide (e.g. an x-axis column named `name`), producing duplicate option values 
with different labels and ambiguous selections. Consider de-duplicating by 
`value` or namespacing values to keep them unique.
   ```suggestion
         // Combine axis and multi-series options, de-duplicating by `value`.
         // Axis/metric-based options take precedence over generic series 
options
         // when there is a collision.
         const optionMap = new Map<string, { value: string; label: string }>();
         axisSortOptions.forEach(option => {
           optionMap.set(option.value, option);
         });
         multiSeriesOptions.forEach(option => {
           if (!optionMap.has(option.value)) {
             optionMap.set(option.value, option);
           }
         });
         const options = Array.from(optionMap.values());
   ```



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