sadpandajoe commented on code in PR #45680:
URL: https://github.com/apache/superset/pull/45680#discussion_r4405923519


##########
superset-frontend/plugins/plugin-chart-echarts/src/Waterfall/crossFilter.ts:
##########
@@ -0,0 +1,353 @@
+/**
+ * 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 {
+  BinaryQueryObjectFilterClause,
+  DataRecordValue,
+  getColumnLabel,
+  getTimeFormatter,
+  QueryFormColumn,
+  QueryObjectFilterClause,
+  TimeGranularity,
+} from '@superset-ui/core';
+import { GenericDataType } from '@apache-superset/core/common';
+import { NULL_STRING } from '../constants';
+import { formatSeriesName } from '../utils/series';
+import { getTemporalXAxisDrillByFilter } from '../utils/xAxisDrillByFilter';
+
+/** Matches `optionLabel` in `src/utils/common.ts`. */
+const EMPTY_STRING = '<empty string>';
+
+export type WaterfallCategory = {
+  /** The trailing total of a chart without a breakdown. Not a data category. 
*/
+  isGrandTotal: boolean;
+  /** Filter the X axis only. Period totals and charts without a breakdown. */
+  xOnly: boolean;
+  xColumn: QueryFormColumn;
+  xValue: DataRecordValue;
+  breakdownColumn?: QueryFormColumn;
+  breakdownValue?: DataRecordValue;
+};
+
+/**
+ * Selection-key part. `bigint` is wrapped so it does not share a key with the
+ * decimal string of the same digits (`42n` vs `'42'`). `JSON.stringify` cannot
+ * encode a bare `bigint`.
+ */
+function toKeyPart(
+  value: DataRecordValue,
+): string | number | boolean | null | { bigint: string } {
+  if (value == null) {
+    return null;
+  }
+  if (typeof value === 'bigint') {
+    return { bigint: value.toString() };
+  }
+  return value instanceof Date ? value.toISOString() : value;
+}
+
+/**
+ * `bigint` throws in `JSON.stringify`, and the data mask is serialized into
+ * dashboard state and the chart-data request.
+ */
+function toJsonSafeFilterValue(
+  value: Exclude<DataRecordValue, null>,
+): Exclude<DataRecordValue, null | bigint> {
+  return typeof value === 'bigint' ? value.toString() : value;
+}
+
+export function getWaterfallCrossFilterKey(
+  category: WaterfallCategory,
+): string | null {
+  if (category.isGrandTotal) {
+    return null;
+  }
+  const xPart = toKeyPart(category.xValue);
+  if (category.xOnly || !category.breakdownColumn) {
+    return JSON.stringify([xPart]);
+  }
+  return JSON.stringify([xPart, toKeyPart(category.breakdownValue ?? null)]);
+}
+
+export function getSelectedWaterfallKeys(selectedValues: unknown): string[] {
+  if (!selectedValues) {
+    return [];
+  }
+  if (Array.isArray(selectedValues)) {
+    return selectedValues.map(value => String(value));
+  }
+  if (typeof selectedValues === 'object') {
+    return Object.values(selectedValues as Record<string, unknown>).map(value 
=>
+      String(value),
+    );
+  }
+  return [];
+}
+
+export function isWaterfallBarDimmed(
+  category: WaterfallCategory,
+  selectedKeys: string[],
+): boolean {
+  if (selectedKeys.length === 0) {
+    return false;
+  }
+  if (category.isGrandTotal) {
+    return true;
+  }
+  const exactKey = getWaterfallCrossFilterKey(category);
+  if (exactKey && selectedKeys.includes(exactKey)) {
+    return false;
+  }
+  // An X-only selection (a period total) keeps every bar of that X value.
+  const xOnlyKey = JSON.stringify([toKeyPart(category.xValue)]);
+  return !selectedKeys.includes(xOnlyKey);
+}
+
+function formatDimensionValue(
+  col: QueryFormColumn,
+  value: DataRecordValue,
+  coltypeMapping?: Record<string, number>,
+  timeFormat?: string,
+): string {
+  if (value == null) {
+    return NULL_STRING;
+  }
+  if (value === '') {
+    return EMPTY_STRING;
+  }
+  return formatSeriesName(value, {
+    timeFormatter: getTimeFormatter(timeFormat),
+    coltype: coltypeMapping?.[getColumnLabel(col)] as
+      | GenericDataType
+      | undefined,
+  });
+}
+
+type FilterContext = {
+  coltypeMapping?: Record<string, number>;
+  timeFormat?: string;
+  timeGrain?: TimeGranularity;
+};
+
+type CategoryDimension = {
+  col: QueryFormColumn;
+  value: DataRecordValue;
+  /** The X axis is the column a time grain buckets. Breakdowns stay exact. */
+  bucket: boolean;
+};
+
+function isTemporalColumn(
+  col: QueryFormColumn,
+  coltypeMapping?: Record<string, number>,
+): boolean {
+  return coltypeMapping?.[getColumnLabel(col)] === GenericDataType.Temporal;
+}
+
+/**
+ * Range covering the clicked bucket. Absent when the column is not temporal,
+ * no grain is set, or the grain has no frontend bucket bounds.
+ */
+function temporalBucketFilter(
+  col: QueryFormColumn,
+  value: DataRecordValue,
+  formattedVal: string,
+  { coltypeMapping, timeGrain }: FilterContext,
+): BinaryQueryObjectFilterClause | undefined {
+  if (!timeGrain || !isTemporalColumn(col, coltypeMapping)) {
+    return undefined;
+  }
+  const filter = getTemporalXAxisDrillByFilter(

Review Comment:
   When the X axis is a temporal Custom SQL column (for example 
`CAST(order_date AS TIMESTAMP)`) with a month grain, `col` here is the ad-hoc 
column object from `transformProps`, so clicking a bar emits `TEMPORAL_RANGE` 
on that object. The SQLAlchemy filter handler only accepts `TEMPORAL_RANGE` 
when the column resolves to a dataset column (`col_obj`); ad-hoc columns leave 
it unset and fall through to `Invalid filter operation type: TEMPORAL_RANGE`, 
so the target charts would error instead of filtering. Should this fall back to 
the exact/grained clause for ad-hoc X columns, or is there a path that converts 
the ad-hoc column first?



##########
superset-frontend/plugins/plugin-chart-echarts/test/Waterfall/transformProps.test.ts:
##########
@@ -219,3 +222,65 @@ test('reclaims the left grid margin when the Y axis is 
hidden', () => {
   expect(hidden.left).toBeLessThan(shown.left);
   expect(hidden.bottom).toBe(shown.bottom);
 });
+
+test('renders an empty chart when the query result is missing', () => {
+  expect(() =>
+    transformProps(
+      new ChartProps({
+        formData: formData as unknown as SqlaFormData,
+        width: 800,
+        height: 600,
+        queriesData: [],
+        theme: supersetTheme,
+      }) as unknown as EchartsWaterfallChartProps,
+    ),
+  ).not.toThrow();
+});
+
+test('dims bars outside the selected period and uses a pointer cursor', () => {
+  const transformedProps = transformProps(
+    new ChartProps({
+      formData: formData as unknown as SqlaFormData,
+      width: 800,
+      height: 600,
+      queriesData: [{ data }],
+      filterState: { selectedValues: [JSON.stringify(['2019'])] },
+      emitCrossFilters: true,
+      theme: supersetTheme,
+    }) as unknown as EchartsWaterfallChartProps,
+  );
+  const series = transformedProps.echartOptions.series as BarSeriesOption[];
+  expect(series[0]?.cursor).toBe('pointer');
+  const increase = series[1]?.data as Array<{
+    value: number | string;
+    itemStyle?: { opacity?: number };
+  }>;
+  expect(transformedProps.categories[0]).toBeDefined();
+  expect(getWaterfallCrossFilterKey(transformedProps.categories[0]!)).toBe(
+    JSON.stringify(['2019']),
+  );
+  expect(increase[0]?.itemStyle?.opacity).toBeUndefined();
+  const decrease = series[2]?.data as Array<{
+    itemStyle?: { opacity?: number };
+  }>;
+  expect(decrease[1]?.itemStyle?.opacity).toBe(OpacityEnum.SemiTransparent);
+  const total = series[3]?.data as Array<{
+    itemStyle?: { opacity?: number };
+  }>;
+  expect(total[2]?.itemStyle?.opacity).toBe(OpacityEnum.SemiTransparent);
+});
+
+test('uses the default cursor when cross-filtering is off', () => {

Review Comment:
   The PR says bars outside the selection are dimmed even when cross-filtering 
is off, but every opacity assertion here runs with `emitCrossFilters: true`, 
and this disabled-mode test passes no selection and checks only the cursor. 
Gating `applyCrossFilterStyle` on `emitCrossFilters` would pass the whole suite 
while breaking testing step 7. Could you add a case with `emitCrossFilters: 
false` and `filterState.selectedValues: [JSON.stringify(['2019'])]` asserting 
the 2020 bar keeps `OpacityEnum.SemiTransparent` and the 2019 bar stays 
undefined?



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