You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@superset.apache.org by "SBIN2010 (via GitHub)" <gi...@apache.org> on 2026/10/23 21:15:22 UTC

[PR] feat(plugin-chart-echarts): add cross-filtering to the Waterfall chart [superset]

SBIN2010 opened a new pull request, #45680:
URL: https://github.com/apache/superset/pull/45680

   <!---
   Please write the PR title following the conventions at https://www.conventionalcommits.org/en/v1.0.0/
   Example:
   fix(dashboard): load charts correctly
   -->
   
   ### SUMMARY
   <!--- Describe the change below, including rationale and design decisions -->
   
   The ECharts Waterfall chart can now drive dashboard cross-filters. Clicking a bar filters other charts on the same dataset. Clicking the same bar again clears the filter. Bars outside the selection are dimmed, and the pointer cursor appears only while cross-filtering is enabled.
   What a click filters depends on the bar:
   - A chart without a breakdown filters the X-axis column (`IN`).
   - A breakdown bar filters the X-axis column and the breakdown column.
   - A period total filters the X-axis column only, and every bar of that period stays highlighted.
   - The grand total at the end of a chart without a breakdown is not a category. Clicking it does not emit a filter and does not clear the current one. It dims while another bar is selected.
   An empty value is sent as `IS NULL`. An empty string stays an empty string and is shown on the chip as `<empty string>`. Numeric labels such as years are not abbreviated. `bigint` values are stringified so the data mask stays JSON-serializable. A temporal X value is formatted on the chip with the axis time format. The filter itself matches the raw cell value (`IN` for cross-filters, `==` for drill). A time grain does not expand that value into a `TEMPORAL_RANGE`.
   Right-click opens Drill to detail and Drill by. Drill by puts the breakdown in the series filters and the X-axis value in the X-axis filters. Both actions are registered because the chart has a metric. An empty query result renders an empty chart instead of failing.
   
   ### BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF
   <!--- Skip this if not applicable -->
   
   ### TESTING INSTRUCTIONS
   <!--- Required! What steps can be taken to manually verify the changes? -->
   1. Create a Waterfall chart and add it to a dashboard that has cross-filtering enabled, next to another chart on the same dataset. Leave Show total on.
   2. Click a period bar. The other chart should filter to that X value, the filter chip should show the raw category, and the other bars — including the grand total — should dim. The Waterfall itself should keep all of its bars.
   3. Click the same bar again. The filter and the dimming should clear.
   4. Click the grand total. Nothing should change.
   5. Add a breakdown and click one of its bars. The filter should include both the period and the breakdown value. Click that period's total bar. The filter should keep only the period, and every bar of that period should stay bright.
   6. Right-click a breakdown bar. Drill to detail should carry both columns. Drill by should offer the breakdown as the series filter and the period as the X-axis filter.
   7. Turn cross-filtering off for the dashboard. Clicks should no longer emit a filter, and the cursor should stay the default.
   8. Filter the Waterfall down to no rows. The chart should render empty instead of breaking.
   
   ### ADDITIONAL INFORMATION
   <!--- Check any relevant boxes with "x" -->
   <!--- HINT: Include "Fixes #nnn" if you are fixing an existing issue -->
   - [ ] Has associated issue:
   - [ ] Required feature flags:
   - [x] Changes UI
   - [ ] Includes DB Migration (follow approval process in [SIP-59](https://github.com/apache/superset/issues/13351))
     - [ ] Migration is atomic, supports rollback & is backwards-compatible
     - [ ] Confirm DB migration upgrade and downgrade tested
     - [ ] Runtime estimates and downtime expectations provided
   - [x] Introduces new feature or API
   - [ ] Removes existing feature or API
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(plugin-chart-echarts): add cross-filtering to the Waterfall chart [superset]

Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #45680:
URL: https://github.com/apache/superset/pull/45680#discussion_r4412335879


##########
superset-frontend/plugins/plugin-chart-echarts/src/Waterfall/crossFilter.ts:
##########
@@ -0,0 +1,392 @@
+/**
+ * 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,
+  isAdhocColumn,
+  isPhysicalColumn,
+  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;
+}
+
+/**
+ * Puts the grain on an adhoc column. The backend truncates that expression
+ * from the column itself and ignores `grain` once the SQL is compiled.
+ * `TEMPORAL_RANGE` is not an option: it requires a dataset column.
+ */
+function adhocBucketColumn(
+  col: QueryFormColumn,
+  timeGrain: TimeGranularity,
+): QueryFormColumn {
+  if (!isAdhocColumn(col)) {
+    return col;
+  }
+  return {
+    ...col,
+    columnType: 'BASE_AXIS',
+    timeGrain: col.timeGrain || timeGrain,
+  };
+}
+
+/**
+ * Range covering the clicked bucket. Absent when the column is not temporal,
+ * no grain is set, the grain has no frontend bucket bounds, or the column is
+ * an adhoc expression.
+ */
+function temporalBucketFilter(
+  col: QueryFormColumn,
+  value: DataRecordValue,
+  formattedVal: string,
+  { coltypeMapping, timeGrain }: FilterContext,
+): BinaryQueryObjectFilterClause | undefined {
+  if (
+    !timeGrain ||
+    !isPhysicalColumn(col) ||
+    !isTemporalColumn(col, coltypeMapping)
+  ) {
+    return undefined;
+  }
+  const filter = getTemporalXAxisDrillByFilter(
+    col,
+    value,
+    timeGrain,
+    formattedVal,
+  );
+  return filter?.op === 'TEMPORAL_RANGE' ? filter : undefined;
+}
+
+function dimensionFilter(
+  col: QueryFormColumn,
+  value: DataRecordValue,
+): QueryObjectFilterClause {
+  if (value == null) {
+    return { col, op: 'IS NULL' };
+  }
+  return { col, op: 'IN', val: [toJsonSafeFilterValue(value)] };
+}
+
+function drillFilter(
+  col: QueryFormColumn,
+  value: DataRecordValue,
+  formattedVal: string,
+  grain?: TimeGranularity,
+): QueryObjectFilterClause {
+  if (value == null) {
+    return { col, op: 'IS NULL', formattedVal };
+  }
+  return {
+    col,
+    op: '==',
+    val: toJsonSafeFilterValue(value),
+    formattedVal,
+    // Equality is applied to the truncated column, so a bucket start matches
+    // every row in the bucket. TEMPORAL_RANGE would be replaced by the query
+    // time range.
+    ...(grain ? { grain } : {}),
+  };
+}
+
+function categoryDimensions(category: WaterfallCategory): CategoryDimension[] {
+  const dimensions: CategoryDimension[] = [
+    { col: category.xColumn, value: category.xValue, bucket: true },
+  ];
+  if (!category.xOnly && category.breakdownColumn) {
+    dimensions.push({
+      col: category.breakdownColumn,
+      value: category.breakdownValue ?? null,
+      bucket: false,
+    });
+  }
+  return dimensions;
+}
+
+function categoryLabel(
+  category: WaterfallCategory,
+  coltypeMapping?: Record<string, number>,
+  timeFormat?: string,
+): string {
+  return categoryDimensions(category)
+    .map(({ col, value }) =>
+      formatDimensionValue(col, value, coltypeMapping, timeFormat),
+    )
+    .join(', ');
+}
+
+function crossFilterClause(
+  dimension: CategoryDimension,
+  context: FilterContext,
+): QueryObjectFilterClause {
+  const formattedVal = formatDimensionValue(
+    dimension.col,
+    dimension.value,
+    context.coltypeMapping,
+    context.timeFormat,
+  );
+  if (dimension.bucket) {
+    const range = temporalBucketFilter(
+      dimension.col,
+      dimension.value,
+      formattedVal,
+      context,
+    );
+    if (range) {
+      return range;
+    }
+    if (
+      !isPhysicalColumn(dimension.col) &&
+      dimension.value != null &&
+      context.timeGrain &&
+      isTemporalColumn(dimension.col, context.coltypeMapping)
+    ) {
+      return drillFilter(
+        adhocBucketColumn(dimension.col, context.timeGrain),
+        dimension.value,
+        formattedVal,
+        context.timeGrain,
+      );
+    }
+  }
+  return dimensionFilter(dimension.col, dimension.value);
+}
+
+function detailClause(
+  dimension: CategoryDimension,
+  context: FilterContext,
+): QueryObjectFilterClause {
+  const formattedVal = formatDimensionValue(
+    dimension.col,
+    dimension.value,
+    context.coltypeMapping,
+    context.timeFormat,
+  );
+  const grain =
+    dimension.bucket &&
+    dimension.value != null &&
+    context.timeGrain &&
+    isTemporalColumn(dimension.col, context.coltypeMapping)
+      ? context.timeGrain
+      : undefined;
+  return drillFilter(dimension.col, dimension.value, formattedVal, grain);

Review Comment:
   For a temporal Custom SQL X axis with a month grain, the cross-filter path above wraps the column with `adhocBucketColumn`, but Drill to detail here passes the original adhoc column with only a top-level `grain`. The backend only truncates by `grain` when it resolves a dataset column; for an adhoc expression the SQL is built from the expression as written, so `CAST(order_date AS TIMESTAMP) == Jan 1` misses an order dated Jan 15. Drill by has the same gap, since `simpleFilterToAdhoc` turns this into plain raw-expression equality and drops the grain. Should `detailClause` apply the same `adhocBucketColumn` treatment, and does Drill by need a grain-preserving conversion for adhoc X columns?



##########
superset-frontend/plugins/plugin-chart-echarts/src/Waterfall/crossFilter.ts:
##########
@@ -0,0 +1,392 @@
+/**
+ * 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,
+  isAdhocColumn,
+  isPhysicalColumn,
+  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;
+}
+
+/**
+ * Puts the grain on an adhoc column. The backend truncates that expression
+ * from the column itself and ignores `grain` once the SQL is compiled.
+ * `TEMPORAL_RANGE` is not an option: it requires a dataset column.
+ */
+function adhocBucketColumn(
+  col: QueryFormColumn,
+  timeGrain: TimeGranularity,
+): QueryFormColumn {
+  if (!isAdhocColumn(col)) {
+    return col;
+  }
+  return {
+    ...col,
+    columnType: 'BASE_AXIS',
+    timeGrain: col.timeGrain || timeGrain,
+  };
+}
+
+/**
+ * Range covering the clicked bucket. Absent when the column is not temporal,
+ * no grain is set, the grain has no frontend bucket bounds, or the column is
+ * an adhoc expression.
+ */
+function temporalBucketFilter(
+  col: QueryFormColumn,
+  value: DataRecordValue,
+  formattedVal: string,
+  { coltypeMapping, timeGrain }: FilterContext,
+): BinaryQueryObjectFilterClause | undefined {
+  if (
+    !timeGrain ||
+    !isPhysicalColumn(col) ||
+    !isTemporalColumn(col, coltypeMapping)
+  ) {
+    return undefined;
+  }
+  const filter = getTemporalXAxisDrillByFilter(
+    col,
+    value,
+    timeGrain,
+    formattedVal,
+  );
+  return filter?.op === 'TEMPORAL_RANGE' ? filter : undefined;
+}
+
+function dimensionFilter(
+  col: QueryFormColumn,
+  value: DataRecordValue,
+): QueryObjectFilterClause {
+  if (value == null) {
+    return { col, op: 'IS NULL' };
+  }
+  return { col, op: 'IN', val: [toJsonSafeFilterValue(value)] };
+}
+
+function drillFilter(
+  col: QueryFormColumn,
+  value: DataRecordValue,
+  formattedVal: string,
+  grain?: TimeGranularity,
+): QueryObjectFilterClause {
+  if (value == null) {
+    return { col, op: 'IS NULL', formattedVal };
+  }
+  return {
+    col,
+    op: '==',
+    val: toJsonSafeFilterValue(value),
+    formattedVal,
+    // Equality is applied to the truncated column, so a bucket start matches
+    // every row in the bucket. TEMPORAL_RANGE would be replaced by the query
+    // time range.
+    ...(grain ? { grain } : {}),
+  };
+}
+
+function categoryDimensions(category: WaterfallCategory): CategoryDimension[] {
+  const dimensions: CategoryDimension[] = [
+    { col: category.xColumn, value: category.xValue, bucket: true },
+  ];
+  if (!category.xOnly && category.breakdownColumn) {
+    dimensions.push({
+      col: category.breakdownColumn,
+      value: category.breakdownValue ?? null,
+      bucket: false,
+    });
+  }
+  return dimensions;
+}
+
+function categoryLabel(
+  category: WaterfallCategory,
+  coltypeMapping?: Record<string, number>,
+  timeFormat?: string,
+): string {
+  return categoryDimensions(category)
+    .map(({ col, value }) =>
+      formatDimensionValue(col, value, coltypeMapping, timeFormat),
+    )
+    .join(', ');
+}
+
+function crossFilterClause(
+  dimension: CategoryDimension,
+  context: FilterContext,
+): QueryObjectFilterClause {
+  const formattedVal = formatDimensionValue(
+    dimension.col,
+    dimension.value,
+    context.coltypeMapping,
+    context.timeFormat,
+  );
+  if (dimension.bucket) {
+    const range = temporalBucketFilter(
+      dimension.col,
+      dimension.value,
+      formattedVal,
+      context,
+    );
+    if (range) {
+      return range;
+    }
+    if (
+      !isPhysicalColumn(dimension.col) &&
+      dimension.value != null &&
+      context.timeGrain &&
+      isTemporalColumn(dimension.col, context.coltypeMapping)
+    ) {
+      return drillFilter(

Review Comment:
   The value forwarded here for an adhoc temporal column is whatever the chart data returned, which for a temporal series is normally epoch milliseconds, not an ISO string. `filter_values_handler` only converts an epoch to a timestamp literal when it has a native column type, and adhoc filters have no `col_obj`, so this becomes `<timestamp expr> = 1609459200000` and Postgres rejects the timestamp-versus-bigint comparison. The adhoc test in `crossFilter.test.ts` feeds an ISO string, so it would not catch this. Could you check what value a Custom SQL temporal X column actually yields, and cover that shape in the test?



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(plugin-chart-echarts): add cross-filtering to the Waterfall chart [superset]

Posted by "SBIN2010 (via GitHub)" <gi...@apache.org>.
SBIN2010 commented on code in PR #45680:
URL: https://github.com/apache/superset/pull/45680#discussion_r4414697161


##########
superset-frontend/plugins/plugin-chart-echarts/src/Waterfall/crossFilter.ts:
##########
@@ -0,0 +1,392 @@
+/**
+ * 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,
+  isAdhocColumn,
+  isPhysicalColumn,
+  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;
+}
+
+/**
+ * Puts the grain on an adhoc column. The backend truncates that expression
+ * from the column itself and ignores `grain` once the SQL is compiled.
+ * `TEMPORAL_RANGE` is not an option: it requires a dataset column.
+ */
+function adhocBucketColumn(
+  col: QueryFormColumn,
+  timeGrain: TimeGranularity,
+): QueryFormColumn {
+  if (!isAdhocColumn(col)) {
+    return col;
+  }
+  return {
+    ...col,
+    columnType: 'BASE_AXIS',
+    timeGrain: col.timeGrain || timeGrain,
+  };
+}
+
+/**
+ * Range covering the clicked bucket. Absent when the column is not temporal,
+ * no grain is set, the grain has no frontend bucket bounds, or the column is
+ * an adhoc expression.
+ */
+function temporalBucketFilter(
+  col: QueryFormColumn,
+  value: DataRecordValue,
+  formattedVal: string,
+  { coltypeMapping, timeGrain }: FilterContext,
+): BinaryQueryObjectFilterClause | undefined {
+  if (
+    !timeGrain ||
+    !isPhysicalColumn(col) ||
+    !isTemporalColumn(col, coltypeMapping)
+  ) {
+    return undefined;
+  }
+  const filter = getTemporalXAxisDrillByFilter(
+    col,
+    value,
+    timeGrain,
+    formattedVal,
+  );
+  return filter?.op === 'TEMPORAL_RANGE' ? filter : undefined;
+}
+
+function dimensionFilter(
+  col: QueryFormColumn,
+  value: DataRecordValue,
+): QueryObjectFilterClause {
+  if (value == null) {
+    return { col, op: 'IS NULL' };
+  }
+  return { col, op: 'IN', val: [toJsonSafeFilterValue(value)] };
+}
+
+function drillFilter(
+  col: QueryFormColumn,
+  value: DataRecordValue,
+  formattedVal: string,
+  grain?: TimeGranularity,
+): QueryObjectFilterClause {
+  if (value == null) {
+    return { col, op: 'IS NULL', formattedVal };
+  }
+  return {
+    col,
+    op: '==',
+    val: toJsonSafeFilterValue(value),
+    formattedVal,
+    // Equality is applied to the truncated column, so a bucket start matches
+    // every row in the bucket. TEMPORAL_RANGE would be replaced by the query
+    // time range.
+    ...(grain ? { grain } : {}),
+  };
+}
+
+function categoryDimensions(category: WaterfallCategory): CategoryDimension[] {
+  const dimensions: CategoryDimension[] = [
+    { col: category.xColumn, value: category.xValue, bucket: true },
+  ];
+  if (!category.xOnly && category.breakdownColumn) {
+    dimensions.push({
+      col: category.breakdownColumn,
+      value: category.breakdownValue ?? null,
+      bucket: false,
+    });
+  }
+  return dimensions;
+}
+
+function categoryLabel(
+  category: WaterfallCategory,
+  coltypeMapping?: Record<string, number>,
+  timeFormat?: string,
+): string {
+  return categoryDimensions(category)
+    .map(({ col, value }) =>
+      formatDimensionValue(col, value, coltypeMapping, timeFormat),
+    )
+    .join(', ');
+}
+
+function crossFilterClause(
+  dimension: CategoryDimension,
+  context: FilterContext,
+): QueryObjectFilterClause {
+  const formattedVal = formatDimensionValue(
+    dimension.col,
+    dimension.value,
+    context.coltypeMapping,
+    context.timeFormat,
+  );
+  if (dimension.bucket) {
+    const range = temporalBucketFilter(
+      dimension.col,
+      dimension.value,
+      formattedVal,
+      context,
+    );
+    if (range) {
+      return range;
+    }
+    if (
+      !isPhysicalColumn(dimension.col) &&
+      dimension.value != null &&
+      context.timeGrain &&
+      isTemporalColumn(dimension.col, context.coltypeMapping)
+    ) {
+      return drillFilter(
+        adhocBucketColumn(dimension.col, context.timeGrain),
+        dimension.value,
+        formattedVal,
+        context.timeGrain,
+      );
+    }
+  }
+  return dimensionFilter(dimension.col, dimension.value);
+}
+
+function detailClause(
+  dimension: CategoryDimension,
+  context: FilterContext,
+): QueryObjectFilterClause {
+  const formattedVal = formatDimensionValue(
+    dimension.col,
+    dimension.value,
+    context.coltypeMapping,
+    context.timeFormat,
+  );
+  const grain =
+    dimension.bucket &&
+    dimension.value != null &&
+    context.timeGrain &&
+    isTemporalColumn(dimension.col, context.coltypeMapping)
+      ? context.timeGrain
+      : undefined;
+  return drillFilter(dimension.col, dimension.value, formattedVal, grain);

Review Comment:
   Now, the "drill to detail" function applies the same `timeGrain` and a `columnType` of `'BASE_AXIS'` to a copy of the column. Furthermore, "drill by" no longer collapses such a filter into raw SQL; instead, the granularity is preserved and passed back into the query as `grain`.
   



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(plugin-chart-echarts): add cross-filtering to the Waterfall chart [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #45680:
URL: https://github.com/apache/superset/pull/45680#discussion_r4364354551


##########
superset-frontend/plugins/plugin-chart-echarts/src/Waterfall/crossFilter.ts:
##########
@@ -0,0 +1,238 @@
+/**
+ * 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 {
+  DataRecordValue,
+  getColumnLabel,
+  getTimeFormatter,
+  QueryFormColumn,
+  QueryObjectFilterClause,
+} from '@superset-ui/core';
+import { GenericDataType } from '@apache-superset/core/common';
+import { NULL_STRING } from '../constants';
+import { formatSeriesName } from '../utils/series';
+
+/** 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;
+};
+
+function toKeyPart(value: DataRecordValue): string | number | boolean | null {
+  if (value == null) {
+    return null;
+  }
+  if (typeof value === 'bigint') {
+    return value.toString();
+  }

Review Comment:
   **Suggestion:** `bigint` 42 and string '42' produce the same selection key, so clicking one selects or clears the other category when both occur.
   
   **Assessment:** 🟠 `Major` · 🔁 `Occurrence: Rarely` · 🏷️ `Logic error`
   
   [![Use CodeAnt Skill](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/use-codeant-skill-flat-v2.svg)](https://docs.codeant.ai/cli/resolve-pr-comments-skill) [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=2270c18eb422422db8df204850181096&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=2270c18eb422422db8df204850181096&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset-frontend/plugins/plugin-chart-echarts/src/Waterfall/crossFilter.ts
   **Line:** 48:50
   **Comment:**
   	*Logic Error: `bigint` 42 and string '42' produce the same selection key, so clicking one selects or clears the other category when both occur.
   
   Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
   Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
   ```
   </details>
   <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F45680&comment_hash=d624988d35fd304fffd1460a3634e54fd37cb6e6ec7f4a1387a8bb2edeb3ab0b&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F45680&comment_hash=d624988d35fd304fffd1460a3634e54fd37cb6e6ec7f4a1387a8bb2edeb3ab0b&reaction=dislike'>👎</a>



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(plugin-chart-echarts): add cross-filtering to the Waterfall chart [superset]

Posted by "EnxDev (via GitHub)" <gi...@apache.org>.
EnxDev commented on code in PR #45680:
URL: https://github.com/apache/superset/pull/45680#discussion_r4394430650


##########
superset-frontend/plugins/plugin-chart-echarts/src/Waterfall/transformProps.ts:
##########
@@ -373,9 +421,13 @@ export default function transformProps(
   axisLabel.formatter = xAxisFormatter;
   axisLabel.hideOverlap = false;
 
-  const seriesProps: Pick<BarSeriesOption, 'type' | 'stack' | 'emphasis'> = {
+  const seriesProps: Pick<
+    BarSeriesOption,
+    'type' | 'stack' | 'emphasis' | 'cursor'
+  > = {
     type: 'bar',
     stack: 'stack',
+    cursor: emitCrossFilters ? 'pointer' : 'default',

Review Comment:
   Nothing pins the `'default'` side of this. The only cursor assertion is `pointer` with cross-filtering on, so a change that always returns `pointer` would still pass.
   
   Worth one more assertion with `emitCrossFilters: false`, since step 7 of the testing instructions relies on it.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(plugin-chart-echarts): add cross-filtering to the Waterfall chart [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #45680:
URL: https://github.com/apache/superset/pull/45680#discussion_r4364586655


##########
superset-frontend/plugins/plugin-chart-echarts/src/Waterfall/crossFilter.ts:
##########
@@ -0,0 +1,238 @@
+/**
+ * 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 {
+  DataRecordValue,
+  getColumnLabel,
+  getTimeFormatter,
+  QueryFormColumn,
+  QueryObjectFilterClause,
+} from '@superset-ui/core';
+import { GenericDataType } from '@apache-superset/core/common';
+import { NULL_STRING } from '../constants';
+import { formatSeriesName } from '../utils/series';
+
+/** 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;
+};
+
+function toKeyPart(value: DataRecordValue): string | number | boolean | null {
+  if (value == null) {
+    return null;
+  }
+  if (typeof value === 'bigint') {
+    return value.toString();
+  }

Review Comment:
   ✅ **CodeAnt verified this suggestion was addressed in subsequent commits and marked this thread resolved** as of `0603540`.
   
   `toKeyPart` now wraps bigint values as `{ bigint: value.toString() }`, keeping them distinct from decimal strings when the selection key is serialized.
   
   <sub>If that's not right, unresolve this thread and CodeAnt will leave it open.</sub>
   
   <!-- codeant-auto-resolve-reply -->



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(plugin-chart-echarts): add cross-filtering to the Waterfall chart [superset]

Posted by "EnxDev (via GitHub) via notifications" <no...@superset.apache.org>.
EnxDev commented on code in PR #45680:
URL: https://github.com/apache/superset/pull/45680#discussion_r4431273528


##########
superset-frontend/src/explore/components/controls/FilterControl/AdhocFilter/index.ts:
##########
@@ -61,6 +61,32 @@ interface AdhocFilterInput {
   [key: string]: unknown;
 }
 
+function subjectForPill(
+  subject: AdhocFilterInput['subject'],
+): string | undefined {
+  if (!subject || typeof subject !== 'object' || subject.column_name) {
+    return undefined;
+  }
+  return typeof subject.label === 'string' ? subject.label : undefined;

Review Comment:
   The pill label is right, but opening it lands on the Simple tab with a blank column picker. `AdhocFilterEditPopoverSimpleTabContent` only resolves a string subject or one with `column_name`, so the Custom SQL bucket shows up as just `= 2021-01-01T00:00:00`.
   
   Value edits still go through, so a follow-up is fine. Could the picker fall back to the adhoc label the same way?



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(plugin-chart-echarts): add cross-filtering to the Waterfall chart [superset]

Posted by "SBIN2010 (via GitHub)" <gi...@apache.org>.
SBIN2010 commented on code in PR #45680:
URL: https://github.com/apache/superset/pull/45680#discussion_r4416303949


##########
superset-frontend/plugins/plugin-chart-echarts/src/Waterfall/EchartsWaterfall.tsx:
##########
@@ -16,21 +16,146 @@
  * specific language governing permissions and limitations
  * under the License.
  */
+import { useMemo } from 'react';
+import {
+  ContextMenuFilters,
+  getColumnLabel,
+  TimeGranularity,
+} from '@superset-ui/core';
 import Echart from '../components/Echart';
 import { WaterfallChartTransformedProps } from './types';
 import { EventHandlers } from '../types';
 import { useLegendEventHandlers } from '../utils/legendEventHandlers';
+import {
+  getSelectedWaterfallKeys,
+  getWaterfallCrossFilterDataMask,
+  getWaterfallDrillFilters,
+} from './crossFilter';
+
+const noop = () => {};
+
+type WaterfallBarEvent = {
+  dataIndex?: number;
+  event?: { stop: () => void; event: PointerEvent };
+};
 
 export default function EchartsWaterfall(
   props: WaterfallChartTransformedProps,
 ) {
-  const { height, width, echartOptions, refs, onLegendStateChanged, formData } =
-    props;
+  const {
+    categories,
+    coltypeMapping,
+    echartOptions,
+    emitCrossFilters,
+    filterState,
+    formData,
+    height,
+    onContextMenu,
+    onLegendStateChanged,
+    refs,
+    setDataMask = noop,
+    width,
+  } = props;
+  const { xAxisTimeFormat } = formData;
+  const timeGrain: TimeGranularity | undefined =
+    formData.extraFormData?.time_grain_sqla ?? formData.timeGrainSqla;
 
   // The waterfall legend has a fixed set of three entries, so it never
   // paginates and has no scroll position to preserve.
-  const eventHandlers: EventHandlers =
-    useLegendEventHandlers(onLegendStateChanged);
+  const legendEventHandlers = useLegendEventHandlers(onLegendStateChanged);
+
+  const crossFilterHandlers: EventHandlers = useMemo(() => {
+    const selectedKeys = getSelectedWaterfallKeys(filterState?.selectedValues);
+    const categoryAt = (event: WaterfallBarEvent) => {
+      if (event.dataIndex == null) {
+        return undefined;
+      }
+      const category = categories[event.dataIndex];
+      if (!category || category.isGrandTotal) {
+        return undefined;
+      }
+      return category;
+    };
+
+    return {
+      click: (event: WaterfallBarEvent) => {
+        if (!emitCrossFilters) {
+          return;
+        }
+        const category = categoryAt(event);
+        if (!category) {
+          return;
+        }
+        setDataMask(
+          getWaterfallCrossFilterDataMask({
+            category,
+            selectedKeys,
+            coltypeMapping,
+            timeFormat: xAxisTimeFormat,
+            timeGrain,
+          }).dataMask,
+        );
+      },
+      contextmenu: (event: WaterfallBarEvent) => {
+        if (!onContextMenu) {
+          return;
+        }
+        const category = categoryAt(event);
+        if (!category) {
+          return;
+        }
+        event.event?.stop();
+        const pointerEvent = event.event?.event;
+        if (!pointerEvent) {
+          return;
+        }
+        // IS NULL is unary. The menu types only binary operators, and both
+        // drill paths forward `op` unchanged.
+        const drillFilters = getWaterfallDrillFilters({
+          category,
+          coltypeMapping,
+          timeFormat: xAxisTimeFormat,
+          timeGrain,
+        }) as NonNullable<ContextMenuFilters['drillToDetail']>;
+        const xColumnLabel = getColumnLabel(category.xColumn);

Review Comment:
   `adhocBucketColumn` returns a copy of the column; the previous check—`filter.col === category.xColumn`—would have incorrectly routed a Custom SQL axis into the breakdown filters instead of the "Drill by" area. Existing tests only covered string-type columns, where both approaches yield the same result. A context menu call has been added for a temporary ad-hoc axis with monthly granularity: the filter now correctly remains in `xAxisFilters`, while the breakdown list remains empty.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(plugin-chart-echarts): add cross-filtering to the Waterfall chart [superset]

Posted by "sadpandajoe (via GitHub) via notifications" <no...@superset.apache.org>.
sadpandajoe commented on code in PR #45680:
URL: https://github.com/apache/superset/pull/45680#discussion_r4448953734


##########
superset-frontend/plugins/plugin-chart-echarts/src/Waterfall/EchartsWaterfall.tsx:
##########
@@ -16,21 +16,146 @@
  * specific language governing permissions and limitations
  * under the License.
  */
+import { useMemo } from 'react';
+import {
+  ContextMenuFilters,
+  getColumnLabel,
+  TimeGranularity,
+} from '@superset-ui/core';
 import Echart from '../components/Echart';
 import { WaterfallChartTransformedProps } from './types';
 import { EventHandlers } from '../types';
 import { useLegendEventHandlers } from '../utils/legendEventHandlers';
+import {
+  getSelectedWaterfallKeys,
+  getWaterfallCrossFilterDataMask,
+  getWaterfallDrillFilters,
+} from './crossFilter';
+
+const noop = () => {};
+
+type WaterfallBarEvent = {
+  dataIndex?: number;
+  event?: { stop: () => void; event: PointerEvent };
+};
 
 export default function EchartsWaterfall(
   props: WaterfallChartTransformedProps,
 ) {
-  const { height, width, echartOptions, refs, onLegendStateChanged, formData } =
-    props;
+  const {
+    categories,
+    coltypeMapping,
+    echartOptions,
+    emitCrossFilters,
+    filterState,
+    formData,
+    height,
+    onContextMenu,
+    onLegendStateChanged,
+    refs,
+    setDataMask = noop,
+    width,
+  } = props;
+  const { xAxisTimeFormat } = formData;
+  const timeGrain: TimeGranularity | undefined =
+    formData.extraFormData?.time_grain_sqla ?? formData.timeGrainSqla;
 
   // The waterfall legend has a fixed set of three entries, so it never
   // paginates and has no scroll position to preserve.
-  const eventHandlers: EventHandlers =
-    useLegendEventHandlers(onLegendStateChanged);
+  const legendEventHandlers = useLegendEventHandlers(onLegendStateChanged);
+
+  const crossFilterHandlers: EventHandlers = useMemo(() => {
+    const selectedKeys = getSelectedWaterfallKeys(filterState?.selectedValues);
+    const categoryAt = (event: WaterfallBarEvent) => {

Review Comment:
   `categoryAt` maps every series hit to a category by `dataIndex`, including the transparent `ASSIST_MARK` spacer series. Those spacers are drawn with a `transparent` fill but are still hit-testable and carry the pointer cursor, so with values `10` then `3` the second visible bar spans 10–13, and clicking the empty area under it (0–10) sets or clears that category's cross-filter; right-clicking it opens the drill menu. Should the handlers ignore events from the assist series (e.g. check `event.seriesName`) while still accepting the colored sign-crossing segments?



##########
superset-frontend/plugins/plugin-chart-echarts/test/Waterfall/EchartsWaterfall.test.tsx:
##########
@@ -0,0 +1,336 @@
+/**
+ * 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 { GenericDataType } from '@apache-superset/core/common';
+import { supersetTheme } from '@apache-superset/core/theme';
+import { ChartProps, SqlaFormData, TimeGranularity } from '@superset-ui/core';
+import { render } from '@testing-library/react';
+import EchartsWaterfall from '../../src/Waterfall/EchartsWaterfall';
+import transformProps from '../../src/Waterfall/transformProps';
+import { EchartsWaterfallChartProps } from '../../src/Waterfall/types';
+import Echart from '../../src/components/Echart';
+import { EventHandlers } from '../../src/types';
+
+jest.mock('../../src/components/Echart', () => ({
+  __esModule: true,
+  default: jest.fn(() => null),
+}));
+
+const mockedEchart = jest.mocked(Echart);
+
+const rows = [
+  { year: '2019', name: 'Sylvester', sum: 10 },
+  { year: '2019', name: 'Arnold', sum: 3 },
+  { year: '2020', name: 'Sylvester', sum: -10 },
+  { year: '2020', name: 'Arnold', sum: 5 },
+];
+
+const formData = {
+  colorScheme: 'bnbColors',
+  datasource: '3__table',
+  granularity_sqla: 'ds',
+  metric: 'sum',
+  x_axis: 'year',
+  groupby: 'name',
+  showTotal: true,
+};
+
+function renderChart(
+  overrides: Partial<ChartProps> & { emitCrossFilters?: boolean } = {},
+) {
+  const setDataMask = jest.fn();
+  const onContextMenu = jest.fn();
+  const chartProps = new ChartProps({
+    formData: formData as unknown as SqlaFormData,
+    width: 800,
+    height: 600,
+    queriesData: [{ data: rows }],
+    hooks: { setDataMask, onContextMenu },
+    theme: supersetTheme,
+    ...overrides,
+  });
+  const props = transformProps(
+    chartProps as unknown as EchartsWaterfallChartProps,
+  );
+  render(<EchartsWaterfall {...props} />);
+  const lastCall = mockedEchart.mock.calls[mockedEchart.mock.calls.length - 1];
+  const { eventHandlers } = lastCall[0] as { eventHandlers: EventHandlers };
+  return { eventHandlers, setDataMask, onContextMenu };
+}
+
+beforeEach(() => {
+  mockedEchart.mockClear();
+});
+
+function pointerEvent(dataIndex: number) {
+  return {
+    dataIndex,
+    event: {
+      stop: jest.fn(),
+      event: { clientX: 12, clientY: 24 } as PointerEvent,
+    },
+  };
+}
+
+test('clicking a breakdown bar filters the period and the breakdown', () => {
+  const { eventHandlers, setDataMask } = renderChart({
+    emitCrossFilters: true,
+  });
+  eventHandlers.click(pointerEvent(0));
+  expect(setDataMask).toHaveBeenCalledWith(
+    expect.objectContaining({
+      extraFormData: {
+        filters: [
+          { col: 'year', op: 'IN', val: ['2019'] },
+          { col: 'name', op: 'IN', val: ['Sylvester'] },
+        ],
+      },
+    }),
+  );
+});
+
+test('clicking a period total filters the period only', () => {
+  const { eventHandlers, setDataMask } = renderChart({
+    emitCrossFilters: true,
+  });
+  eventHandlers.click(pointerEvent(2));
+  expect(setDataMask).toHaveBeenCalledWith(
+    expect.objectContaining({
+      extraFormData: {
+        filters: [{ col: 'year', op: 'IN', val: ['2019'] }],
+      },
+    }),
+  );
+});
+
+test('clicking the same bar again clears the filter', () => {
+  const { eventHandlers, setDataMask } = renderChart({
+    emitCrossFilters: true,
+    filterState: { selectedValues: [JSON.stringify(['2019', 'Sylvester'])] },
+  });
+  eventHandlers.click(pointerEvent(0));
+  expect(setDataMask).toHaveBeenCalledWith(
+    expect.objectContaining({
+      extraFormData: { filters: [] },
+    }),
+  );
+});
+
+test('does not emit a filter when cross-filtering is disabled', () => {
+  const { eventHandlers, setDataMask } = renderChart({
+    emitCrossFilters: false,
+  });
+  eventHandlers.click(pointerEvent(0));
+  expect(setDataMask).not.toHaveBeenCalled();
+});
+
+test('clicking the grand total does not change the current filter', () => {
+  const { eventHandlers, setDataMask } = renderChart({
+    emitCrossFilters: true,
+    formData: { ...formData, groupby: undefined } as unknown as SqlaFormData,
+  });
+  eventHandlers.click(pointerEvent(2));
+  expect(setDataMask).not.toHaveBeenCalled();
+});
+
+const breakdownCrossFilter = {
+  dataMask: {
+    extraFormData: {
+      filters: [
+        { col: 'year', op: 'IN', val: ['2019'] },
+        { col: 'name', op: 'IN', val: ['Sylvester'] },
+      ],
+    },
+    filterState: {
+      label: '2019, Sylvester',
+      value: '2019, Sylvester',
+      selectedValues: [JSON.stringify(['2019', 'Sylvester'])],
+    },
+  },
+  isCurrentValueSelected: false,
+};
+
+test('a context menu carries the drill filters for the clicked bar', () => {

Review Comment:
   Every context-menu test here renders with `emitCrossFilters: true`, so nothing covers Drill to detail / Drill by when cross-filtering is off, which the PR says should still work. If the `contextmenu` handler were gated on `emitCrossFilters`, these tests would still pass. Could you add a case with `emitCrossFilters: false` that right-clicks a breakdown bar and asserts `onContextMenu` still receives the `drillToDetail` and `drillBy` filters while `setDataMask` is not called?



##########
superset-frontend/src/utils/simpleFilterToAdhoc.ts:
##########
@@ -75,16 +75,36 @@ export const simpleFilterToAdhoc = (
 
   let result: AdhocFilter;
   if (isAdhocColumn(filterClause.col)) {
-    result = {
-      expressionType: 'SQL',
-      clause,
-      sqlExpression: translateToSql({
-        expressionType: ExpressionTypes.Simple,
-        subject: `(${filterClause.col.sqlExpression})`,
+    // A grain on an adhoc expression has to stay on the column. Compiling it
+    // to raw SQL drops the grain, so the bucket is no longer truncated.
+    if (filterClause.grain) {
+      result = {
+        expressionType: 'SIMPLE',
+        clause,
         operator: filterClause.op,
+        operatorId: Object.entries(OPERATOR_ENUM_TO_OPERATOR_TYPE).find(
+          operatorEntry => operatorEntry[1].operation === filterClause.op,
+        )?.[0],
+        subject: {
+          ...filterClause.col,
+          columnType: 'BASE_AXIS',
+          timeGrain: filterClause.col.timeGrain || filterClause.grain,
+        },
+        timeGrain: filterClause.grain,
         comparator: 'val' in filterClause ? filterClause.val : undefined,
-      } as SimpleAdhocFilter),
-    };
+      } as unknown as SimpleAdhocFilter;
+    } else {
+      result = {
+        expressionType: 'SQL',
+        clause,
+        sqlExpression: translateToSql({

Review Comment:
   For a Custom SQL breakdown such as `COALESCE(name, '')`, Drill by on a bar whose value is `''` reaches this branch with `val: ''`. `translateToSql` goes through `getSimpleSQLExpression`, which formats comparators with `optionLabel`, so the empty string becomes the display marker `<empty string>` and (since `Number('')` is not NaN) it is left unquoted, giving `(COALESCE(name, '')) = <empty string>`. That is invalid SQL, so the drilled chart errors instead of showing the matching rows. Could this branch keep a structured filter, or serialize the real SQL literal for empty strings?



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(plugin-chart-echarts): add cross-filtering to the Waterfall chart [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on PR #45680:
URL: https://github.com/apache/superset/pull/45680#issuecomment-6375024582

   ## CodeAnt PR Risk: Medium Risk
   
   - The PR needs attention before merging.
   - In crossFilter.ts, bigint 42 and string "42" produce the same selection key, so mixed representations can select or clear the wrong category.
   
   **Assessed commit:** `5f785139e411`


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(plugin-chart-echarts): add cross-filtering to the Waterfall chart [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #45680:
URL: https://github.com/apache/superset/pull/45680#discussion_r4364479772


##########
superset-frontend/plugins/plugin-chart-echarts/src/Waterfall/crossFilter.ts:
##########
@@ -0,0 +1,238 @@
+/**
+ * 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 {
+  DataRecordValue,
+  getColumnLabel,
+  getTimeFormatter,
+  QueryFormColumn,
+  QueryObjectFilterClause,
+} from '@superset-ui/core';
+import { GenericDataType } from '@apache-superset/core/common';
+import { NULL_STRING } from '../constants';
+import { formatSeriesName } from '../utils/series';
+
+/** 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;
+};
+
+function toKeyPart(value: DataRecordValue): string | number | boolean | null {
+  if (value == null) {
+    return null;
+  }
+  if (typeof value === 'bigint') {
+    return value.toString();
+  }

Review Comment:
   ✅ **CodeAnt verified this suggestion was addressed in subsequent commits and marked this thread resolved** as of `39df3f9`.
   
   `toKeyPart` now wraps bigint values as `{ bigint: value.toString() }`, keeping them distinct from decimal strings when the selection key is serialized.
   
   <sub>If that's not right, unresolve this thread and CodeAnt will leave it open.</sub>
   
   <!-- codeant-auto-resolve-reply -->



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(plugin-chart-echarts): add cross-filtering to the Waterfall chart [superset]

Posted by "netlify[bot] (via GitHub)" <gi...@apache.org>.
netlify[bot] commented on PR #45680:
URL: https://github.com/apache/superset/pull/45680#issuecomment-6453033079

   ### <span aria-hidden="true">✅</span> Deploy Preview for *superset-docs-preview* ready!
   
   
   |  Name | Link |
   |:-:|------------------------|
   |<span aria-hidden="true">🔨</span> Latest commit | 3f2489029acf9149341191840977c5d048cfc6ce |
   |<span aria-hidden="true">🔍</span> Latest deploy log | https://app.netlify.com/projects/superset-docs-preview/deploys/6ae10b859edb630df83a2e13 |
   |<span aria-hidden="true">😎</span> Deploy Preview | [https://deploy-preview-45680--superset-docs-preview.netlify.app](https://deploy-preview-45680--superset-docs-preview.netlify.app) |
   |<span aria-hidden="true">📱</span> Preview on mobile | <details><summary> Toggle QR Code... </summary><br /><br />![QR Code](https://app.netlify.com/qr-code/eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1cmwiOiJodHRwczovL2RlcGxveS1wcmV2aWV3LTQ1NjgwLS1zdXBlcnNldC1kb2NzLXByZXZpZXcubmV0bGlmeS5hcHAifQ.7l1q6hTNxOxiip-EuKtwouPFcH3Om6ITFceGxm6rw60)<br /><br />_Use your smartphone camera to open QR code link._</details> |
   |<span aria-hidden="true">🤖</span> Make changes | [Run an agent on this branch](https://app.netlify.com/projects/superset-docs-preview/agent-runs#DcpBCoAgEEDRu8w6SJPEukGnkFHHEkzFhIjo7rn7fN4LpeazNFgBBjAVkz16e8I23tioeoxR25qvS_sQ-whp79JRifnZXLcSiTOj5oWckYI5rwROxAV8Pw) |
   ---
   <!-- [superset-docs-preview Preview](https://deploy-preview-45680--superset-docs-preview.netlify.app) -->
   _To edit notification comments on pull requests, go to your [Netlify project configuration](https://app.netlify.com/projects/superset-docs-preview/configuration/notifications#deploy-notifications)._


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(plugin-chart-echarts): add cross-filtering to the Waterfall chart [superset]

Posted by "SBIN2010 (via GitHub)" <gi...@apache.org>.
SBIN2010 commented on code in PR #45680:
URL: https://github.com/apache/superset/pull/45680#discussion_r4393927343


##########
superset-frontend/plugins/plugin-chart-echarts/src/Waterfall/crossFilter.ts:
##########
@@ -0,0 +1,245 @@
+/**
+ * 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 {
+  DataRecordValue,
+  getColumnLabel,
+  getTimeFormatter,
+  QueryFormColumn,
+  QueryObjectFilterClause,
+} from '@superset-ui/core';
+import { GenericDataType } from '@apache-superset/core/common';
+import { NULL_STRING } from '../constants';
+import { formatSeriesName } from '../utils/series';
+
+/** 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,
+  });
+}
+
+function dimensionFilter(
+  col: QueryFormColumn,
+  value: DataRecordValue,
+): QueryObjectFilterClause {
+  if (value == null) {
+    return { col, op: 'IS NULL' };
+  }
+  return { col, op: 'IN', val: [toJsonSafeFilterValue(value)] };

Review Comment:
   Agreed, that’s a great find. Now, clicking on the January column no longer compares the raw date against midnight on January 1st. If the axis is temporal and a "grain" (time granularity) is defined, the cross-filter sets a `TEMPORAL_RANGE` for the entire bucket and records it in `time_range`; otherwise, the backend replaces any such filter with the chart’s saved time range. A "grain" setting from a dashboard overrides the "grain" defined on the chart itself. For a standard column or an axis without a "grain" setting, the filter remains an exact `IN` match.
   
   "Drill to detail" continues to use `==`, but when a "grain" is present—much like in a timeseries—the comparison is performed against the truncated (binned) column value, and the `time_range` is not overwritten. "Drill by" on the X-axis applies a `TEMPORAL_RANGE` for the corresponding bucket, while a "breakdown" remains an exact value match.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(plugin-chart-echarts): add cross-filtering to the Waterfall chart [superset]

Posted by "SBIN2010 (via GitHub)" <gi...@apache.org>.
SBIN2010 commented on code in PR #45680:
URL: https://github.com/apache/superset/pull/45680#discussion_r4416296059


##########
superset-frontend/src/utils/simpleFilterToAdhoc.ts:
##########
@@ -75,16 +75,36 @@ export const simpleFilterToAdhoc = (
 
   let result: AdhocFilter;
   if (isAdhocColumn(filterClause.col)) {
-    result = {
-      expressionType: 'SQL',
-      clause,
-      sqlExpression: translateToSql({
-        expressionType: ExpressionTypes.Simple,
-        subject: `(${filterClause.col.sqlExpression})`,
+    // A grain on an adhoc expression has to stay on the column. Compiling it
+    // to raw SQL drops the grain, so the bucket is no longer truncated.
+    if (filterClause.grain) {
+      result = {
+        expressionType: 'SIMPLE',
+        clause,
         operator: filterClause.op,
+        operatorId: Object.entries(OPERATOR_ENUM_TO_OPERATOR_TYPE).find(
+          operatorEntry => operatorEntry[1].operation === filterClause.op,
+        )?.[0],
+        subject: {

Review Comment:
   The filter pill only read the `column_name` property from the object; consequently, after selecting "Drill by" → "Edit chart," the result was `[P1M] = '2021-01-01T00:00:00'`—lacking the column name. If `column_name` is missing, the label of the ad-hoc column is used instead. There is a specific test for this scenario, `getDefaultLabel`, which yields: `[P1M] order_date = '2021-01-01T00:00:00'`.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(plugin-chart-echarts): add cross-filtering to the Waterfall chart [superset]

Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #45680:
URL: https://github.com/apache/superset/pull/45680#discussion_r4392328709


##########
superset-frontend/plugins/plugin-chart-echarts/test/Waterfall/EchartsWaterfall.test.tsx:
##########
@@ -0,0 +1,186 @@
+/**
+ * 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 { supersetTheme } from '@apache-superset/core/theme';
+import { ChartProps, SqlaFormData } from '@superset-ui/core';
+import { render } from '@testing-library/react';
+import EchartsWaterfall from '../../src/Waterfall/EchartsWaterfall';
+import transformProps from '../../src/Waterfall/transformProps';
+import { EchartsWaterfallChartProps } from '../../src/Waterfall/types';
+import Echart from '../../src/components/Echart';
+import { EventHandlers } from '../../src/types';
+
+jest.mock('../../src/components/Echart', () => ({
+  __esModule: true,
+  default: jest.fn(() => null),
+}));
+
+const mockedEchart = jest.mocked(Echart);
+
+const rows = [
+  { year: '2019', name: 'Sylvester', sum: 10 },
+  { year: '2019', name: 'Arnold', sum: 3 },
+  { year: '2020', name: 'Sylvester', sum: -10 },
+  { year: '2020', name: 'Arnold', sum: 5 },
+];
+
+const formData = {
+  colorScheme: 'bnbColors',
+  datasource: '3__table',
+  granularity_sqla: 'ds',
+  metric: 'sum',
+  x_axis: 'year',
+  groupby: 'name',
+  showTotal: true,
+};
+
+function renderChart(
+  overrides: Partial<ChartProps> & { emitCrossFilters?: boolean } = {},
+) {
+  const setDataMask = jest.fn();
+  const onContextMenu = jest.fn();
+  const chartProps = new ChartProps({
+    formData: formData as unknown as SqlaFormData,
+    width: 800,
+    height: 600,
+    queriesData: [{ data: rows }],
+    hooks: { setDataMask, onContextMenu },
+    theme: supersetTheme,
+    ...overrides,
+  });
+  const props = transformProps(
+    chartProps as unknown as EchartsWaterfallChartProps,
+  );
+  render(<EchartsWaterfall {...props} />);
+  const lastCall = mockedEchart.mock.calls[mockedEchart.mock.calls.length - 1];
+  const { eventHandlers } = lastCall[0] as { eventHandlers: EventHandlers };
+  return { eventHandlers, setDataMask, onContextMenu };
+}
+
+beforeEach(() => {
+  mockedEchart.mockClear();
+});
+
+function pointerEvent(dataIndex: number) {
+  return {
+    dataIndex,
+    event: {
+      stop: jest.fn(),
+      event: { clientX: 12, clientY: 24 } as PointerEvent,
+    },
+  };
+}
+
+test('clicking a breakdown bar filters the period and the breakdown', () => {
+  const { eventHandlers, setDataMask } = renderChart({
+    emitCrossFilters: true,
+  });
+  eventHandlers.click(pointerEvent(0));
+  expect(setDataMask).toHaveBeenCalledWith(
+    expect.objectContaining({
+      extraFormData: {
+        filters: [
+          { col: 'year', op: 'IN', val: ['2019'] },
+          { col: 'name', op: 'IN', val: ['Sylvester'] },
+        ],
+      },
+    }),
+  );
+});
+
+test('clicking a period total filters the period only', () => {
+  const { eventHandlers, setDataMask } = renderChart({
+    emitCrossFilters: true,
+  });
+  eventHandlers.click(pointerEvent(2));
+  expect(setDataMask).toHaveBeenCalledWith(
+    expect.objectContaining({
+      extraFormData: {
+        filters: [{ col: 'year', op: 'IN', val: ['2019'] }],
+      },
+    }),
+  );
+});
+
+test('clicking the same bar again clears the filter', () => {
+  const { eventHandlers, setDataMask } = renderChart({
+    emitCrossFilters: true,
+    filterState: { selectedValues: [JSON.stringify(['2019', 'Sylvester'])] },
+  });
+  eventHandlers.click(pointerEvent(0));
+  expect(setDataMask).toHaveBeenCalledWith(
+    expect.objectContaining({
+      extraFormData: { filters: [] },
+    }),
+  );
+});
+
+test('does not emit a filter when cross-filtering is disabled', () => {
+  const { eventHandlers, setDataMask } = renderChart({
+    emitCrossFilters: false,
+  });
+  eventHandlers.click(pointerEvent(0));
+  expect(setDataMask).not.toHaveBeenCalled();
+});
+
+test('clicking the grand total does not change the current filter', () => {
+  const { eventHandlers, setDataMask } = renderChart({
+    emitCrossFilters: true,
+    formData: { ...formData, groupby: undefined } as unknown as SqlaFormData,
+  });
+  eventHandlers.click(pointerEvent(2));
+  expect(setDataMask).not.toHaveBeenCalled();
+});
+
+test('a context menu carries the drill filters for the clicked bar', () => {
+  const { eventHandlers, onContextMenu } = renderChart({
+    emitCrossFilters: true,
+  });
+  const event = pointerEvent(0);
+  eventHandlers.contextmenu(event);
+  expect(event.event.stop).toHaveBeenCalled();
+  expect(onContextMenu).toHaveBeenCalledWith(
+    12,
+    24,
+    expect.objectContaining({

Review Comment:
   `expect.objectContaining` here only pins `drillToDetail` and `drillBy`, so the `crossFilter` entry of the context-menu payload could be dropped or wrongly built (for example `isCurrentValueSelected` always false) and this test would still pass, which would break "filter" and "clear filter" from the right-click menu. Would asserting `crossFilter.dataMask` and `isCurrentValueSelected` for both an unselected and an already-selected bar cover it?



##########
superset-frontend/plugins/plugin-chart-echarts/src/Waterfall/crossFilter.ts:
##########
@@ -0,0 +1,245 @@
+/**
+ * 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 {
+  DataRecordValue,
+  getColumnLabel,
+  getTimeFormatter,
+  QueryFormColumn,
+  QueryObjectFilterClause,
+} from '@superset-ui/core';
+import { GenericDataType } from '@apache-superset/core/common';
+import { NULL_STRING } from '../constants';
+import { formatSeriesName } from '../utils/series';
+
+/** 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,
+  });
+}
+
+function dimensionFilter(
+  col: QueryFormColumn,
+  value: DataRecordValue,
+): QueryObjectFilterClause {
+  if (value == null) {
+    return { col, op: 'IS NULL' };
+  }
+  return { col, op: 'IN', val: [toJsonSafeFilterValue(value)] };

Review Comment:
   For a temporal X axis with a time grain, the bar's value is the bucket start (e.g. Jan 1 for a monthly grain), but this emits `col IN [<that timestamp>]`, and the drill path below emits `==`. Both compare against the raw, unbucketed column, so clicking the January bar of a chart over orders dated Jan 10 and Jan 20 returns no rows (or only rows exactly at midnight Jan 1) instead of the month. Timeseries handles this with a grain-aware `TEMPORAL_RANGE` filter; should temporal X columns do the same here for both cross-filter and drill?



##########
superset-frontend/plugins/plugin-chart-echarts/test/Waterfall/crossFilter.test.ts:
##########
@@ -0,0 +1,238 @@
+/**
+ * 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 { GenericDataType } from '@apache-superset/core/common';
+import { getTimeFormatter } from '@superset-ui/core';
+import {
+  getSelectedWaterfallKeys,
+  getWaterfallCrossFilterDataMask,
+  getWaterfallCrossFilterKey,
+  getWaterfallDrillFilters,
+  isWaterfallBarDimmed,
+  WaterfallCategory,
+} from '../../src/Waterfall/crossFilter';
+
+const yearBar: WaterfallCategory = {
+  isGrandTotal: false,
+  xOnly: true,
+  xColumn: 'year',
+  xValue: 2019,
+};
+
+const breakdownBar: WaterfallCategory = {
+  isGrandTotal: false,
+  xOnly: false,
+  xColumn: 'year',
+  xValue: 2019,
+  breakdownColumn: 'name',
+  breakdownValue: 'Sylvester',
+};
+
+const periodTotal: WaterfallCategory = {
+  isGrandTotal: false,
+  xOnly: true,
+  xColumn: 'year',
+  xValue: 2019,
+  breakdownColumn: 'name',
+};
+
+const grandTotal: WaterfallCategory = {
+  isGrandTotal: true,
+  xOnly: true,
+  xColumn: 'year',
+  xValue: null,
+};
+
+test('builds an X-only key and an X plus breakdown key', () => {
+  expect(getWaterfallCrossFilterKey(yearBar)).toBe(JSON.stringify([2019]));
+  expect(getWaterfallCrossFilterKey(breakdownBar)).toBe(
+    JSON.stringify([2019, 'Sylvester']),
+  );
+  expect(getWaterfallCrossFilterKey(grandTotal)).toBeNull();
+});
+
+test('filters the X column for a chart without a breakdown', () => {
+  const { dataMask } = getWaterfallCrossFilterDataMask({
+    category: yearBar,
+    selectedKeys: [],
+  });
+  expect(dataMask.extraFormData.filters).toEqual([
+    { col: 'year', op: 'IN', val: [2019] },
+  ]);
+  expect(dataMask.filterState.label).toBe('2019');
+  expect(dataMask.filterState.selectedValues).toEqual([JSON.stringify([2019])]);
+});
+
+test('filters both the X column and the breakdown', () => {
+  const { dataMask } = getWaterfallCrossFilterDataMask({
+    category: breakdownBar,
+    selectedKeys: [],
+  });
+  expect(dataMask.extraFormData.filters).toEqual([
+    { col: 'year', op: 'IN', val: [2019] },
+    { col: 'name', op: 'IN', val: ['Sylvester'] },
+  ]);
+  expect(dataMask.filterState.label).toBe('2019, Sylvester');
+});
+
+test('a period total filters the X column only', () => {
+  const { dataMask } = getWaterfallCrossFilterDataMask({
+    category: periodTotal,
+    selectedKeys: [],
+  });
+  expect(dataMask.extraFormData.filters).toEqual([
+    { col: 'year', op: 'IN', val: [2019] },
+  ]);
+});
+
+test('clicking the same bar again clears the filter', () => {
+  const key = getWaterfallCrossFilterKey(yearBar)!;
+  const { dataMask } = getWaterfallCrossFilterDataMask({
+    category: yearBar,
+    selectedKeys: [key],
+  });
+  expect(dataMask.extraFormData.filters).toEqual([]);
+  expect(dataMask.filterState.selectedValues).toBeNull();
+});
+
+test('a grand total produces no filter', () => {
+  const { dataMask } = getWaterfallCrossFilterDataMask({
+    category: grandTotal,
+    selectedKeys: [],
+  });
+  expect(dataMask.extraFormData.filters).toEqual([]);
+  expect(dataMask.filterState.selectedValues).toBeNull();
+});
+
+test('null and empty breakdown values stay distinct', () => {
+  const nullBar: WaterfallCategory = {
+    ...breakdownBar,
+    breakdownValue: null,
+  };
+  const emptyBar: WaterfallCategory = {
+    ...breakdownBar,
+    breakdownValue: '',
+  };
+  expect(
+    getWaterfallCrossFilterDataMask({
+      category: nullBar,
+      selectedKeys: [],
+    }).dataMask.extraFormData.filters,
+  ).toEqual([
+    { col: 'year', op: 'IN', val: [2019] },
+    { col: 'name', op: 'IS NULL' },
+  ]);
+  const emptyMask = getWaterfallCrossFilterDataMask({
+    category: emptyBar,
+    selectedKeys: [],
+  }).dataMask;
+  expect(emptyMask.extraFormData.filters).toEqual([
+    { col: 'year', op: 'IN', val: [2019] },
+    { col: 'name', op: 'IN', val: [''] },
+  ]);
+  expect(emptyMask.filterState.label).toBe('2019, <empty string>');
+});
+
+test('keeps a numeric category unabbreviated', () => {
+  const mask = getWaterfallCrossFilterDataMask({
+    category: { ...yearBar, xValue: 2024 },
+    selectedKeys: [],
+  }).dataMask;
+  expect(mask.filterState.label).toBe('2024');
+});
+
+test('a bigint category does not share a selection key with the same decimal string', () => {
+  const bigintBar: WaterfallCategory = { ...yearBar, xValue: BigInt(42) };
+  const stringBar: WaterfallCategory = { ...yearBar, xValue: '42' };
+  const bigintKey = getWaterfallCrossFilterKey(bigintBar);
+  const stringKey = getWaterfallCrossFilterKey(stringBar);
+
+  expect(bigintKey).not.toBe(stringKey);
+
+  const mask = getWaterfallCrossFilterDataMask({
+    category: bigintBar,
+    selectedKeys: [],
+  }).dataMask;
+  expect(mask.extraFormData.filters).toEqual([
+    { col: 'year', op: 'IN', val: ['42'] },
+  ]);
+  expect(mask.filterState.selectedValues).toEqual([bigintKey]);
+  expect(() => JSON.stringify(mask)).not.toThrow();
+
+  const stringMask = getWaterfallCrossFilterDataMask({
+    category: stringBar,
+    selectedKeys: bigintKey ? [bigintKey] : [],
+  }).dataMask;
+  expect(stringMask.extraFormData.filters).not.toEqual([]);
+  expect(isWaterfallBarDimmed(stringBar, bigintKey ? [bigintKey] : [])).toBe(
+    true,
+  );
+  expect(isWaterfallBarDimmed(bigintBar, bigintKey ? [bigintKey] : [])).toBe(
+    false,
+  );
+});
+
+test('formats a temporal X value with the axis time format', () => {
+  const epoch = Date.parse('2020-01-15T00:00:00.000Z');
+  const mask = getWaterfallCrossFilterDataMask({
+    category: {
+      ...yearBar,
+      xValue: epoch,
+    },
+    selectedKeys: [],
+    coltypeMapping: { year: GenericDataType.Temporal },
+    timeFormat: '%Y-%m-%d',
+  }).dataMask;
+  expect(mask.filterState.label).toBe(
+    getTimeFormatter('%Y-%m-%d')(new Date(epoch)),
+  );
+});
+
+test('reads selected keys from an array or an object', () => {
+  expect(getSelectedWaterfallKeys(['a'])).toEqual(['a']);
+  expect(getSelectedWaterfallKeys({ 0: 'a' })).toEqual(['a']);
+  expect(getSelectedWaterfallKeys(undefined)).toEqual([]);
+});
+
+test('an X-only selection keeps every bar of that period bright', () => {

Review Comment:
   The dimming tests only use an X-only selection (`[2019]`), so nothing pins the breakdown case: with `[2019, 'Sylvester']` selected, Sylvester should stay bright while the other 2019 breakdown bar and the period total dim. An implementation that keeps every bar sharing the selected X value bright would pass all of these assertions. Could a case selecting the breakdown key assert that?



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(plugin-chart-echarts): add cross-filtering to the Waterfall chart [superset]

Posted by "SBIN2010 (via GitHub)" <gi...@apache.org>.
SBIN2010 commented on code in PR #45680:
URL: https://github.com/apache/superset/pull/45680#discussion_r4405494867


##########
superset-frontend/plugins/plugin-chart-echarts/src/Waterfall/crossFilter.ts:
##########
@@ -0,0 +1,387 @@
+/**
+ * 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(
+    col,
+    value,
+    timeGrain,
+    formattedVal,
+  );
+  return filter?.op === 'TEMPORAL_RANGE' ? filter : undefined;
+}
+
+function dimensionFilter(
+  col: QueryFormColumn,
+  value: DataRecordValue,
+): QueryObjectFilterClause {
+  if (value == null) {
+    return { col, op: 'IS NULL' };
+  }
+  return { col, op: 'IN', val: [toJsonSafeFilterValue(value)] };
+}
+
+function drillFilter(
+  col: QueryFormColumn,
+  value: DataRecordValue,
+  formattedVal: string,
+  grain?: TimeGranularity,
+): QueryObjectFilterClause {
+  if (value == null) {
+    return { col, op: 'IS NULL', formattedVal };
+  }
+  return {
+    col,
+    op: '==',
+    val: toJsonSafeFilterValue(value),
+    formattedVal,
+    // Equality is applied to the truncated column, so a bucket start matches
+    // every row in the bucket. TEMPORAL_RANGE would be replaced by the query
+    // time range.
+    ...(grain ? { grain } : {}),
+  };
+}
+
+function categoryDimensions(category: WaterfallCategory): CategoryDimension[] {
+  const dimensions: CategoryDimension[] = [
+    { col: category.xColumn, value: category.xValue, bucket: true },
+  ];
+  if (!category.xOnly && category.breakdownColumn) {
+    dimensions.push({
+      col: category.breakdownColumn,
+      value: category.breakdownValue ?? null,
+      bucket: false,
+    });
+  }
+  return dimensions;
+}
+
+function categoryLabel(
+  category: WaterfallCategory,
+  coltypeMapping?: Record<string, number>,
+  timeFormat?: string,
+): string {
+  return categoryDimensions(category)
+    .map(({ col, value }) =>
+      formatDimensionValue(col, value, coltypeMapping, timeFormat),
+    )
+    .join(', ');
+}
+
+function crossFilterClause(
+  dimension: CategoryDimension,
+  context: FilterContext,
+): QueryObjectFilterClause {
+  const formattedVal = formatDimensionValue(
+    dimension.col,
+    dimension.value,
+    context.coltypeMapping,
+    context.timeFormat,
+  );
+  if (dimension.bucket) {
+    const range = temporalBucketFilter(
+      dimension.col,
+      dimension.value,
+      formattedVal,
+      context,
+    );
+    if (range) {
+      return range;
+    }
+  }
+  return dimensionFilter(dimension.col, dimension.value);
+}
+
+function detailClause(
+  dimension: CategoryDimension,
+  context: FilterContext,
+): QueryObjectFilterClause {
+  const formattedVal = formatDimensionValue(
+    dimension.col,
+    dimension.value,
+    context.coltypeMapping,
+    context.timeFormat,
+  );
+  const grain =
+    dimension.bucket &&
+    dimension.value != null &&
+    context.timeGrain &&
+    isTemporalColumn(dimension.col, context.coltypeMapping)
+      ? context.timeGrain
+      : undefined;
+  return drillFilter(dimension.col, dimension.value, formattedVal, grain);
+}
+
+export function getWaterfallCrossFilterDataMask({
+  category,
+  selectedKeys,
+  coltypeMapping,
+  timeFormat,
+  timeGrain,
+}: {
+  category: WaterfallCategory;
+  selectedKeys: string[];
+  coltypeMapping?: Record<string, number>;
+  timeFormat?: string;
+  timeGrain?: TimeGranularity;
+}) {
+  const key = getWaterfallCrossFilterKey(category);
+  const isCurrentValueSelected = Boolean(key && selectedKeys.includes(key));
+  const active = Boolean(key) && !isCurrentValueSelected;
+  const context: FilterContext = { coltypeMapping, timeFormat, timeGrain };
+  const label = active
+    ? categoryLabel(category, coltypeMapping, timeFormat)
+    : null;
+  const filters: QueryObjectFilterClause[] = active
+    ? categoryDimensions(category).map(dimension =>
+        crossFilterClause(dimension, context),
+      )
+    : [];
+  const temporalRange = filters.find(
+    (filter): filter is BinaryQueryObjectFilterClause =>
+      filter.op === 'TEMPORAL_RANGE',
+  );
+
+  return {
+    dataMask: {
+      extraFormData: {
+        filters,
+        // The backend copies the query time range onto every TEMPORAL_RANGE
+        // filter, so the clicked bucket has to be that time range too.
+        ...(temporalRange ? { time_range: String(temporalRange.val) } : {}),
+      },
+      filterState: {
+        label,
+        value: label,
+        selectedValues: active && key ? [key] : null,
+      },
+    },
+    isCurrentValueSelected,
+  };
+}
+
+export function getWaterfallDrillFilters({
+  category,
+  coltypeMapping,
+  timeFormat,
+  timeGrain,
+}: {
+  category: WaterfallCategory;
+  coltypeMapping?: Record<string, number>;
+  timeFormat?: string;
+  timeGrain?: TimeGranularity;
+}): QueryObjectFilterClause[] {
+  if (category.isGrandTotal) {
+    return [];
+  }
+  const context: FilterContext = { coltypeMapping, timeFormat, timeGrain };
+  return categoryDimensions(category).map(dimension =>
+    detailClause(dimension, context),
+  );
+}
+
+/**
+ * Drill by on the X axis. A known grain covers the bucket with TEMPORAL_RANGE,
+ * the same clause a time-axis chart uses. Grains without bucket bounds fall
+ * back to grained equality.
+ */
+export function getWaterfallDrillByXAxisFilter({
+  category,
+  coltypeMapping,
+  timeFormat,
+  timeGrain,
+}: {
+  category: WaterfallCategory;
+  coltypeMapping?: Record<string, number>;
+  timeFormat?: string;
+  timeGrain?: TimeGranularity;
+}): QueryObjectFilterClause | undefined {
+  if (category.isGrandTotal) {
+    return undefined;
+  }
+  const context: FilterContext = { coltypeMapping, timeFormat, timeGrain };
+  const [dimension] = categoryDimensions(category);
+  const formattedVal = formatDimensionValue(
+    dimension.col,
+    dimension.value,
+    coltypeMapping,
+    timeFormat,
+  );
+  return (
+    temporalBucketFilter(

Review Comment:
   When performing a drill-down along the X-axis, the system applies the same filter used for the initial drill-down—specifically, one that aligns with the granularity (bucket size) of the selected data point.
   
   The time range—whether saved or derived from the dashboard—is preserved within the modal window's query. The backend injects this into every `TEMPORAL_RANGE` parameter; consequently, a "January" bucket expands to cover the entire time range of the chart. The granularity-based comparison is applied to the already-filtered column, ensuring that the month remains consistent. 



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(plugin-chart-echarts): add cross-filtering to the Waterfall chart [superset]

Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(plugin-chart-echarts): add cross-filtering to the Waterfall chart [superset]

Posted by "SBIN2010 (via GitHub)" <gi...@apache.org>.
SBIN2010 commented on code in PR #45680:
URL: https://github.com/apache/superset/pull/45680#discussion_r4406298247


##########
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:
   Good catch. Now, for an axis with a Custom SQL column, the filter uses an equality operator based on the granularity (i.e., `==` and `grain`), while `timeGrain` is applied to a copy of the ad-hoc column with `columnType: 'BASE_AXIS'`. Otherwise, the expression wouldn't be truncated to the month, and the comparison would only capture the exact start of a bucket. In this case, `time_range` is not set. A standard dataset column, by contrast, continues to be filtered using a `TEMPORAL_RANGE` range.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(plugin-chart-echarts): add cross-filtering to the Waterfall chart [superset]

Posted by "SBIN2010 (via GitHub)" <gi...@apache.org>.
SBIN2010 commented on code in PR #45680:
URL: https://github.com/apache/superset/pull/45680#discussion_r4417760652


##########
superset-frontend/src/utils/simpleFilterToAdhoc.ts:
##########
@@ -75,16 +75,36 @@ export const simpleFilterToAdhoc = (
 
   let result: AdhocFilter;
   if (isAdhocColumn(filterClause.col)) {
-    result = {
-      expressionType: 'SQL',
-      clause,
-      sqlExpression: translateToSql({
-        expressionType: ExpressionTypes.Simple,
-        subject: `(${filterClause.col.sqlExpression})`,
+    // A grain on an adhoc expression has to stay on the column. Compiling it
+    // to raw SQL drops the grain, so the bucket is no longer truncated.
+    if (filterClause.grain) {
+      result = {
+        expressionType: 'SIMPLE',
+        clause,
         operator: filterClause.op,
+        operatorId: Object.entries(OPERATOR_ENUM_TO_OPERATOR_TYPE).find(
+          operatorEntry => operatorEntry[1].operation === filterClause.op,
+        )?.[0],
+        subject: {
+          ...filterClause.col,
+          columnType: 'BASE_AXIS',
+          timeGrain: filterClause.col.timeGrain || filterClause.grain,

Review Comment:
   Good catch. Now, if the value, operator, or subject changes, `duplicateWith` strips both the `timeGrain` and `columnType` from an ad-hoc column—not just the external `timeGrain`. After changing a value (e.g., from `2021-01-01` to `2021-01-15`), `convertFilter` sends the original column without any grain, which prevents the backend from attempting to compare a "month" grain against the 15th day of the month. Filters that remain unchanged retain their grain.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(plugin-chart-echarts): add cross-filtering to the Waterfall chart [superset]

Posted by "SBIN2010 (via GitHub)" <gi...@apache.org>.
SBIN2010 commented on code in PR #45680:
URL: https://github.com/apache/superset/pull/45680#discussion_r4393899862


##########
superset-frontend/plugins/plugin-chart-echarts/test/Waterfall/EchartsWaterfall.test.tsx:
##########
@@ -0,0 +1,186 @@
+/**
+ * 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 { supersetTheme } from '@apache-superset/core/theme';
+import { ChartProps, SqlaFormData } from '@superset-ui/core';
+import { render } from '@testing-library/react';
+import EchartsWaterfall from '../../src/Waterfall/EchartsWaterfall';
+import transformProps from '../../src/Waterfall/transformProps';
+import { EchartsWaterfallChartProps } from '../../src/Waterfall/types';
+import Echart from '../../src/components/Echart';
+import { EventHandlers } from '../../src/types';
+
+jest.mock('../../src/components/Echart', () => ({
+  __esModule: true,
+  default: jest.fn(() => null),
+}));
+
+const mockedEchart = jest.mocked(Echart);
+
+const rows = [
+  { year: '2019', name: 'Sylvester', sum: 10 },
+  { year: '2019', name: 'Arnold', sum: 3 },
+  { year: '2020', name: 'Sylvester', sum: -10 },
+  { year: '2020', name: 'Arnold', sum: 5 },
+];
+
+const formData = {
+  colorScheme: 'bnbColors',
+  datasource: '3__table',
+  granularity_sqla: 'ds',
+  metric: 'sum',
+  x_axis: 'year',
+  groupby: 'name',
+  showTotal: true,
+};
+
+function renderChart(
+  overrides: Partial<ChartProps> & { emitCrossFilters?: boolean } = {},
+) {
+  const setDataMask = jest.fn();
+  const onContextMenu = jest.fn();
+  const chartProps = new ChartProps({
+    formData: formData as unknown as SqlaFormData,
+    width: 800,
+    height: 600,
+    queriesData: [{ data: rows }],
+    hooks: { setDataMask, onContextMenu },
+    theme: supersetTheme,
+    ...overrides,
+  });
+  const props = transformProps(
+    chartProps as unknown as EchartsWaterfallChartProps,
+  );
+  render(<EchartsWaterfall {...props} />);
+  const lastCall = mockedEchart.mock.calls[mockedEchart.mock.calls.length - 1];
+  const { eventHandlers } = lastCall[0] as { eventHandlers: EventHandlers };
+  return { eventHandlers, setDataMask, onContextMenu };
+}
+
+beforeEach(() => {
+  mockedEchart.mockClear();
+});
+
+function pointerEvent(dataIndex: number) {
+  return {
+    dataIndex,
+    event: {
+      stop: jest.fn(),
+      event: { clientX: 12, clientY: 24 } as PointerEvent,
+    },
+  };
+}
+
+test('clicking a breakdown bar filters the period and the breakdown', () => {
+  const { eventHandlers, setDataMask } = renderChart({
+    emitCrossFilters: true,
+  });
+  eventHandlers.click(pointerEvent(0));
+  expect(setDataMask).toHaveBeenCalledWith(
+    expect.objectContaining({
+      extraFormData: {
+        filters: [
+          { col: 'year', op: 'IN', val: ['2019'] },
+          { col: 'name', op: 'IN', val: ['Sylvester'] },
+        ],
+      },
+    }),
+  );
+});
+
+test('clicking a period total filters the period only', () => {
+  const { eventHandlers, setDataMask } = renderChart({
+    emitCrossFilters: true,
+  });
+  eventHandlers.click(pointerEvent(2));
+  expect(setDataMask).toHaveBeenCalledWith(
+    expect.objectContaining({
+      extraFormData: {
+        filters: [{ col: 'year', op: 'IN', val: ['2019'] }],
+      },
+    }),
+  );
+});
+
+test('clicking the same bar again clears the filter', () => {
+  const { eventHandlers, setDataMask } = renderChart({
+    emitCrossFilters: true,
+    filterState: { selectedValues: [JSON.stringify(['2019', 'Sylvester'])] },
+  });
+  eventHandlers.click(pointerEvent(0));
+  expect(setDataMask).toHaveBeenCalledWith(
+    expect.objectContaining({
+      extraFormData: { filters: [] },
+    }),
+  );
+});
+
+test('does not emit a filter when cross-filtering is disabled', () => {
+  const { eventHandlers, setDataMask } = renderChart({
+    emitCrossFilters: false,
+  });
+  eventHandlers.click(pointerEvent(0));
+  expect(setDataMask).not.toHaveBeenCalled();
+});
+
+test('clicking the grand total does not change the current filter', () => {
+  const { eventHandlers, setDataMask } = renderChart({
+    emitCrossFilters: true,
+    formData: { ...formData, groupby: undefined } as unknown as SqlaFormData,
+  });
+  eventHandlers.click(pointerEvent(2));
+  expect(setDataMask).not.toHaveBeenCalled();
+});
+
+test('a context menu carries the drill filters for the clicked bar', () => {
+  const { eventHandlers, onContextMenu } = renderChart({
+    emitCrossFilters: true,
+  });
+  const event = pointerEvent(0);
+  eventHandlers.contextmenu(event);
+  expect(event.event.stop).toHaveBeenCalled();
+  expect(onContextMenu).toHaveBeenCalledWith(
+    12,
+    24,
+    expect.objectContaining({

Review Comment:
   Good catch; the test now checks `crossFilter.dataMask` and `isCurrentValueSelected` for both unselected columns and columns that are already selected—where a subsequent click removes the filter.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(plugin-chart-echarts): add cross-filtering to the Waterfall chart [superset]

Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #45680:
URL: https://github.com/apache/superset/pull/45680#discussion_r4396401966


##########
superset-frontend/plugins/plugin-chart-echarts/src/Waterfall/crossFilter.ts:
##########
@@ -0,0 +1,387 @@
+/**
+ * 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(
+    col,
+    value,
+    timeGrain,
+    formattedVal,
+  );
+  return filter?.op === 'TEMPORAL_RANGE' ? filter : undefined;
+}
+
+function dimensionFilter(
+  col: QueryFormColumn,
+  value: DataRecordValue,
+): QueryObjectFilterClause {
+  if (value == null) {
+    return { col, op: 'IS NULL' };
+  }
+  return { col, op: 'IN', val: [toJsonSafeFilterValue(value)] };
+}
+
+function drillFilter(
+  col: QueryFormColumn,
+  value: DataRecordValue,
+  formattedVal: string,
+  grain?: TimeGranularity,
+): QueryObjectFilterClause {
+  if (value == null) {
+    return { col, op: 'IS NULL', formattedVal };
+  }
+  return {
+    col,
+    op: '==',
+    val: toJsonSafeFilterValue(value),
+    formattedVal,
+    // Equality is applied to the truncated column, so a bucket start matches
+    // every row in the bucket. TEMPORAL_RANGE would be replaced by the query
+    // time range.
+    ...(grain ? { grain } : {}),
+  };
+}
+
+function categoryDimensions(category: WaterfallCategory): CategoryDimension[] {
+  const dimensions: CategoryDimension[] = [
+    { col: category.xColumn, value: category.xValue, bucket: true },
+  ];
+  if (!category.xOnly && category.breakdownColumn) {
+    dimensions.push({
+      col: category.breakdownColumn,
+      value: category.breakdownValue ?? null,
+      bucket: false,
+    });
+  }
+  return dimensions;
+}
+
+function categoryLabel(
+  category: WaterfallCategory,
+  coltypeMapping?: Record<string, number>,
+  timeFormat?: string,
+): string {
+  return categoryDimensions(category)
+    .map(({ col, value }) =>
+      formatDimensionValue(col, value, coltypeMapping, timeFormat),
+    )
+    .join(', ');
+}
+
+function crossFilterClause(
+  dimension: CategoryDimension,
+  context: FilterContext,
+): QueryObjectFilterClause {
+  const formattedVal = formatDimensionValue(
+    dimension.col,
+    dimension.value,
+    context.coltypeMapping,
+    context.timeFormat,
+  );
+  if (dimension.bucket) {
+    const range = temporalBucketFilter(
+      dimension.col,
+      dimension.value,
+      formattedVal,
+      context,
+    );
+    if (range) {
+      return range;
+    }
+  }
+  return dimensionFilter(dimension.col, dimension.value);
+}
+
+function detailClause(
+  dimension: CategoryDimension,
+  context: FilterContext,
+): QueryObjectFilterClause {
+  const formattedVal = formatDimensionValue(
+    dimension.col,
+    dimension.value,
+    context.coltypeMapping,
+    context.timeFormat,
+  );
+  const grain =
+    dimension.bucket &&
+    dimension.value != null &&
+    context.timeGrain &&
+    isTemporalColumn(dimension.col, context.coltypeMapping)
+      ? context.timeGrain
+      : undefined;
+  return drillFilter(dimension.col, dimension.value, formattedVal, grain);
+}
+
+export function getWaterfallCrossFilterDataMask({
+  category,
+  selectedKeys,
+  coltypeMapping,
+  timeFormat,
+  timeGrain,
+}: {
+  category: WaterfallCategory;
+  selectedKeys: string[];
+  coltypeMapping?: Record<string, number>;
+  timeFormat?: string;
+  timeGrain?: TimeGranularity;
+}) {
+  const key = getWaterfallCrossFilterKey(category);
+  const isCurrentValueSelected = Boolean(key && selectedKeys.includes(key));
+  const active = Boolean(key) && !isCurrentValueSelected;
+  const context: FilterContext = { coltypeMapping, timeFormat, timeGrain };
+  const label = active
+    ? categoryLabel(category, coltypeMapping, timeFormat)
+    : null;
+  const filters: QueryObjectFilterClause[] = active
+    ? categoryDimensions(category).map(dimension =>
+        crossFilterClause(dimension, context),
+      )
+    : [];
+  const temporalRange = filters.find(
+    (filter): filter is BinaryQueryObjectFilterClause =>
+      filter.op === 'TEMPORAL_RANGE',
+  );
+
+  return {
+    dataMask: {
+      extraFormData: {
+        filters,
+        // The backend copies the query time range onto every TEMPORAL_RANGE
+        // filter, so the clicked bucket has to be that time range too.
+        ...(temporalRange ? { time_range: String(temporalRange.val) } : {}),
+      },
+      filterState: {
+        label,
+        value: label,
+        selectedValues: active && key ? [key] : null,
+      },
+    },
+    isCurrentValueSelected,
+  };
+}
+
+export function getWaterfallDrillFilters({
+  category,
+  coltypeMapping,
+  timeFormat,
+  timeGrain,
+}: {
+  category: WaterfallCategory;
+  coltypeMapping?: Record<string, number>;
+  timeFormat?: string;
+  timeGrain?: TimeGranularity;
+}): QueryObjectFilterClause[] {
+  if (category.isGrandTotal) {
+    return [];
+  }
+  const context: FilterContext = { coltypeMapping, timeFormat, timeGrain };
+  return categoryDimensions(category).map(dimension =>
+    detailClause(dimension, context),
+  );
+}
+
+/**
+ * Drill by on the X axis. A known grain covers the bucket with TEMPORAL_RANGE,
+ * the same clause a time-axis chart uses. Grains without bucket bounds fall
+ * back to grained equality.
+ */
+export function getWaterfallDrillByXAxisFilter({
+  category,
+  coltypeMapping,
+  timeFormat,
+  timeGrain,
+}: {
+  category: WaterfallCategory;
+  coltypeMapping?: Record<string, number>;
+  timeFormat?: string;
+  timeGrain?: TimeGranularity;
+}): QueryObjectFilterClause | undefined {
+  if (category.isGrandTotal) {
+    return undefined;
+  }
+  const context: FilterContext = { coltypeMapping, timeFormat, timeGrain };
+  const [dimension] = categoryDimensions(category);
+  const formattedVal = formatDimensionValue(
+    dimension.col,
+    dimension.value,
+    coltypeMapping,
+    timeFormat,
+  );
+  return (
+    temporalBucketFilter(

Review Comment:
   When the chart has a saved or dashboard `time_range` (say `2021-01-01 : 2022-01-01` on a monthly Waterfall), the drill-by modal's query still carries that range, and the backend replaces every `TEMPORAL_RANGE` filter's value with the query time range. So the January bucket filter returned here is rewritten to the whole year and drilling by a column after clicking January includes every month. The cross-filter path avoids this by also setting `time_range`; should the drill-by path scope the clicked bucket the same way, or use the grained `==` clause that `drillToDetail` already uses for the X axis?



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(plugin-chart-echarts): add cross-filtering to the Waterfall chart [superset]

Posted by "SBIN2010 (via GitHub) via notifications" <no...@superset.apache.org>.
SBIN2010 commented on PR #45680:
URL: https://github.com/apache/superset/pull/45680#issuecomment-7170811188

   > Thanks @SBIN2010, the screenshots help a lot!
   > 
   > One thing on the newest commit... `_numeric_epoch_millis` in `helpers.py` kicks in for any numeric temporal column without a `python_date_format`, on every chart, not just this cross-filter. Are we sure those are always epoch ms? A column of epoch seconds would quietly filter out every row, where today it at least errors on Postgres. Setting the column's format to `epoch_ms` seems like it already covers this case, unless I'm missing something?
   
   Agreed. Guessing epoch milliseconds for every numeric temporal column without a format was too broad, and an epoch-seconds column would have silently dropped every row. _numeric_epoch_millis is removed. dttm_sql_literal emits an integer only when python_date_format is epoch_ms (or epoch_s / epoch_us). The example Gantt columns start_time and end_time now declare epoch_ms.


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(plugin-chart-echarts): add cross-filtering to the Waterfall chart [superset]

Posted by "SBIN2010 (via GitHub)" <gi...@apache.org>.
SBIN2010 commented on code in PR #45680:
URL: https://github.com/apache/superset/pull/45680#discussion_r4406275600


##########
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:
   Test Added – it passes `emitCrossFilters: false` and the selection `2019`. The `2019` column remains bright, while the `2020` column is set to an opacity of 0.3.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(plugin-chart-echarts): add cross-filtering to the Waterfall chart [superset]

Posted by "SBIN2010 (via GitHub)" <gi...@apache.org>.
SBIN2010 commented on code in PR #45680:
URL: https://github.com/apache/superset/pull/45680#discussion_r4414726129


##########
superset-frontend/plugins/plugin-chart-echarts/src/Waterfall/crossFilter.ts:
##########
@@ -0,0 +1,392 @@
+/**
+ * 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,
+  isAdhocColumn,
+  isPhysicalColumn,
+  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;
+}
+
+/**
+ * Puts the grain on an adhoc column. The backend truncates that expression
+ * from the column itself and ignores `grain` once the SQL is compiled.
+ * `TEMPORAL_RANGE` is not an option: it requires a dataset column.
+ */
+function adhocBucketColumn(
+  col: QueryFormColumn,
+  timeGrain: TimeGranularity,
+): QueryFormColumn {
+  if (!isAdhocColumn(col)) {
+    return col;
+  }
+  return {
+    ...col,
+    columnType: 'BASE_AXIS',
+    timeGrain: col.timeGrain || timeGrain,
+  };
+}
+
+/**
+ * Range covering the clicked bucket. Absent when the column is not temporal,
+ * no grain is set, the grain has no frontend bucket bounds, or the column is
+ * an adhoc expression.
+ */
+function temporalBucketFilter(
+  col: QueryFormColumn,
+  value: DataRecordValue,
+  formattedVal: string,
+  { coltypeMapping, timeGrain }: FilterContext,
+): BinaryQueryObjectFilterClause | undefined {
+  if (
+    !timeGrain ||
+    !isPhysicalColumn(col) ||
+    !isTemporalColumn(col, coltypeMapping)
+  ) {
+    return undefined;
+  }
+  const filter = getTemporalXAxisDrillByFilter(
+    col,
+    value,
+    timeGrain,
+    formattedVal,
+  );
+  return filter?.op === 'TEMPORAL_RANGE' ? filter : undefined;
+}
+
+function dimensionFilter(
+  col: QueryFormColumn,
+  value: DataRecordValue,
+): QueryObjectFilterClause {
+  if (value == null) {
+    return { col, op: 'IS NULL' };
+  }
+  return { col, op: 'IN', val: [toJsonSafeFilterValue(value)] };
+}
+
+function drillFilter(
+  col: QueryFormColumn,
+  value: DataRecordValue,
+  formattedVal: string,
+  grain?: TimeGranularity,
+): QueryObjectFilterClause {
+  if (value == null) {
+    return { col, op: 'IS NULL', formattedVal };
+  }
+  return {
+    col,
+    op: '==',
+    val: toJsonSafeFilterValue(value),
+    formattedVal,
+    // Equality is applied to the truncated column, so a bucket start matches
+    // every row in the bucket. TEMPORAL_RANGE would be replaced by the query
+    // time range.
+    ...(grain ? { grain } : {}),
+  };
+}
+
+function categoryDimensions(category: WaterfallCategory): CategoryDimension[] {
+  const dimensions: CategoryDimension[] = [
+    { col: category.xColumn, value: category.xValue, bucket: true },
+  ];
+  if (!category.xOnly && category.breakdownColumn) {
+    dimensions.push({
+      col: category.breakdownColumn,
+      value: category.breakdownValue ?? null,
+      bucket: false,
+    });
+  }
+  return dimensions;
+}
+
+function categoryLabel(
+  category: WaterfallCategory,
+  coltypeMapping?: Record<string, number>,
+  timeFormat?: string,
+): string {
+  return categoryDimensions(category)
+    .map(({ col, value }) =>
+      formatDimensionValue(col, value, coltypeMapping, timeFormat),
+    )
+    .join(', ');
+}
+
+function crossFilterClause(
+  dimension: CategoryDimension,
+  context: FilterContext,
+): QueryObjectFilterClause {
+  const formattedVal = formatDimensionValue(
+    dimension.col,
+    dimension.value,
+    context.coltypeMapping,
+    context.timeFormat,
+  );
+  if (dimension.bucket) {
+    const range = temporalBucketFilter(
+      dimension.col,
+      dimension.value,
+      formattedVal,
+      context,
+    );
+    if (range) {
+      return range;
+    }
+    if (
+      !isPhysicalColumn(dimension.col) &&
+      dimension.value != null &&
+      context.timeGrain &&
+      isTemporalColumn(dimension.col, context.coltypeMapping)
+    ) {
+      return drillFilter(

Review Comment:
   Corrected. This value now represents a "naive" date (without a time zone association): 2021-01-01T00:00:00.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(plugin-chart-echarts): add cross-filtering to the Waterfall chart [superset]

Posted by "SBIN2010 (via GitHub)" <gi...@apache.org>.
SBIN2010 commented on code in PR #45680:
URL: https://github.com/apache/superset/pull/45680#discussion_r4417760652


##########
superset-frontend/src/utils/simpleFilterToAdhoc.ts:
##########
@@ -75,16 +75,36 @@ export const simpleFilterToAdhoc = (
 
   let result: AdhocFilter;
   if (isAdhocColumn(filterClause.col)) {
-    result = {
-      expressionType: 'SQL',
-      clause,
-      sqlExpression: translateToSql({
-        expressionType: ExpressionTypes.Simple,
-        subject: `(${filterClause.col.sqlExpression})`,
+    // A grain on an adhoc expression has to stay on the column. Compiling it
+    // to raw SQL drops the grain, so the bucket is no longer truncated.
+    if (filterClause.grain) {
+      result = {
+        expressionType: 'SIMPLE',
+        clause,
         operator: filterClause.op,
+        operatorId: Object.entries(OPERATOR_ENUM_TO_OPERATOR_TYPE).find(
+          operatorEntry => operatorEntry[1].operation === filterClause.op,
+        )?.[0],
+        subject: {
+          ...filterClause.col,
+          columnType: 'BASE_AXIS',
+          timeGrain: filterClause.col.timeGrain || filterClause.grain,

Review Comment:
   Good catch—`getSimpleSQLExpression` no longer substitutes the `label`. It now uses `column_name` for dataset columns and `sqlExpression` for Custom SQL. The pill’s label still displays the `label` value, but only via `getDefaultLabel`. The SQL tab now shows `CAST(order_date AS TIMESTAMP) = '2021-01-01T00:00:00'` instead of the `bucket_date` alias.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(plugin-chart-echarts): add cross-filtering to the Waterfall chart [superset]

Posted by "SBIN2010 (via GitHub)" <gi...@apache.org>.
SBIN2010 commented on code in PR #45680:
URL: https://github.com/apache/superset/pull/45680#discussion_r4417804121


##########
superset-frontend/src/explore/exploreUtils/index.ts:
##########
@@ -466,10 +467,10 @@ export const getSimpleSQLExpression = (
   );
   const showComparator =
     disableInputOperatorValues.indexOf(operator ?? '') === -1;
-  // If returned value is an object after changing dataset
+  // A dataset column carries column_name. An adhoc column carries label.
   let expression: string =
     typeof subject === 'object'
-      ? (subject?.column_name ?? '')
+      ? (subject?.column_name ?? subject?.label ?? '')

Review Comment:
   Good catch—`getSimpleSQLExpression` no longer substitutes the `label`. It now uses `column_name` for dataset columns and `sqlExpression` for Custom SQL. The pill’s label still displays the `label` value, but only via `getDefaultLabel`. The SQL tab now shows `CAST(order_date AS TIMESTAMP) = '2021-01-01T00:00:00'` instead of the `bucket_date` alias.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(plugin-chart-echarts): add cross-filtering to the Waterfall chart [superset]

Posted by "SBIN2010 (via GitHub) via notifications" <no...@superset.apache.org>.
SBIN2010 commented on code in PR #45680:
URL: https://github.com/apache/superset/pull/45680#discussion_r4620420480


##########
superset-frontend/plugins/plugin-chart-echarts/src/Waterfall/EchartsWaterfall.tsx:
##########
@@ -16,21 +16,146 @@
  * specific language governing permissions and limitations
  * under the License.
  */
+import { useMemo } from 'react';
+import {
+  ContextMenuFilters,
+  getColumnLabel,
+  TimeGranularity,
+} from '@superset-ui/core';
 import Echart from '../components/Echart';
 import { WaterfallChartTransformedProps } from './types';
 import { EventHandlers } from '../types';
 import { useLegendEventHandlers } from '../utils/legendEventHandlers';
+import {
+  getSelectedWaterfallKeys,
+  getWaterfallCrossFilterDataMask,
+  getWaterfallDrillFilters,
+} from './crossFilter';
+
+const noop = () => {};
+
+type WaterfallBarEvent = {
+  dataIndex?: number;
+  event?: { stop: () => void; event: PointerEvent };
+};
 
 export default function EchartsWaterfall(
   props: WaterfallChartTransformedProps,
 ) {
-  const { height, width, echartOptions, refs, onLegendStateChanged, formData } =
-    props;
+  const {
+    categories,
+    coltypeMapping,
+    echartOptions,
+    emitCrossFilters,
+    filterState,
+    formData,
+    height,
+    onContextMenu,
+    onLegendStateChanged,
+    refs,
+    setDataMask = noop,
+    width,
+  } = props;
+  const { xAxisTimeFormat } = formData;
+  const timeGrain: TimeGranularity | undefined =
+    formData.extraFormData?.time_grain_sqla ?? formData.timeGrainSqla;
 
   // The waterfall legend has a fixed set of three entries, so it never
   // paginates and has no scroll position to preserve.
-  const eventHandlers: EventHandlers =
-    useLegendEventHandlers(onLegendStateChanged);
+  const legendEventHandlers = useLegendEventHandlers(onLegendStateChanged);
+
+  const crossFilterHandlers: EventHandlers = useMemo(() => {
+    const selectedKeys = getSelectedWaterfallKeys(filterState?.selectedValues);
+    const categoryAt = (event: WaterfallBarEvent) => {

Review Comment:
   fixed in [e47a335](https://github.com/apache/superset/pull/45680/commits/e47a335a03138c4ffbfdd9a57795bdf8efd75468)



##########
superset-frontend/src/utils/simpleFilterToAdhoc.ts:
##########
@@ -75,16 +75,36 @@ export const simpleFilterToAdhoc = (
 
   let result: AdhocFilter;
   if (isAdhocColumn(filterClause.col)) {
-    result = {
-      expressionType: 'SQL',
-      clause,
-      sqlExpression: translateToSql({
-        expressionType: ExpressionTypes.Simple,
-        subject: `(${filterClause.col.sqlExpression})`,
+    // A grain on an adhoc expression has to stay on the column. Compiling it
+    // to raw SQL drops the grain, so the bucket is no longer truncated.
+    if (filterClause.grain) {
+      result = {
+        expressionType: 'SIMPLE',
+        clause,
         operator: filterClause.op,
+        operatorId: Object.entries(OPERATOR_ENUM_TO_OPERATOR_TYPE).find(
+          operatorEntry => operatorEntry[1].operation === filterClause.op,
+        )?.[0],
+        subject: {
+          ...filterClause.col,
+          columnType: 'BASE_AXIS',
+          timeGrain: filterClause.col.timeGrain || filterClause.grain,
+        },
+        timeGrain: filterClause.grain,
         comparator: 'val' in filterClause ? filterClause.val : undefined,
-      } as SimpleAdhocFilter),
-    };
+      } as unknown as SimpleAdhocFilter;
+    } else {
+      result = {
+        expressionType: 'SQL',
+        clause,
+        sqlExpression: translateToSql({

Review Comment:
   fixed in [e47a335]



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(plugin-chart-echarts): add cross-filtering to the Waterfall chart [superset]

Posted by "SBIN2010 (via GitHub)" <gi...@apache.org>.
SBIN2010 commented on code in PR #45680:
URL: https://github.com/apache/superset/pull/45680#discussion_r4405478364


##########
superset-frontend/plugins/plugin-chart-echarts/src/Waterfall/transformProps.ts:
##########
@@ -373,9 +421,13 @@ export default function transformProps(
   axisLabel.formatter = xAxisFormatter;
   axisLabel.hideOverlap = false;
 
-  const seriesProps: Pick<BarSeriesOption, 'type' | 'stack' | 'emphasis'> = {
+  const seriesProps: Pick<
+    BarSeriesOption,
+    'type' | 'stack' | 'emphasis' | 'cursor'
+  > = {
     type: 'bar',
     stack: 'stack',
+    cursor: emitCrossFilters ? 'pointer' : 'default',

Review Comment:
   In the `transformProps` test, the cursor is set to `default` when the cross-filter is disabled; previously, only `pointer` was checked.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(plugin-chart-echarts): add cross-filtering to the Waterfall chart [superset]

Posted by "SBIN2010 (via GitHub)" <gi...@apache.org>.
SBIN2010 commented on code in PR #45680:
URL: https://github.com/apache/superset/pull/45680#discussion_r4393884685


##########
superset-frontend/plugins/plugin-chart-echarts/test/Waterfall/crossFilter.test.ts:
##########
@@ -0,0 +1,238 @@
+/**
+ * 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 { GenericDataType } from '@apache-superset/core/common';
+import { getTimeFormatter } from '@superset-ui/core';
+import {
+  getSelectedWaterfallKeys,
+  getWaterfallCrossFilterDataMask,
+  getWaterfallCrossFilterKey,
+  getWaterfallDrillFilters,
+  isWaterfallBarDimmed,
+  WaterfallCategory,
+} from '../../src/Waterfall/crossFilter';
+
+const yearBar: WaterfallCategory = {
+  isGrandTotal: false,
+  xOnly: true,
+  xColumn: 'year',
+  xValue: 2019,
+};
+
+const breakdownBar: WaterfallCategory = {
+  isGrandTotal: false,
+  xOnly: false,
+  xColumn: 'year',
+  xValue: 2019,
+  breakdownColumn: 'name',
+  breakdownValue: 'Sylvester',
+};
+
+const periodTotal: WaterfallCategory = {
+  isGrandTotal: false,
+  xOnly: true,
+  xColumn: 'year',
+  xValue: 2019,
+  breakdownColumn: 'name',
+};
+
+const grandTotal: WaterfallCategory = {
+  isGrandTotal: true,
+  xOnly: true,
+  xColumn: 'year',
+  xValue: null,
+};
+
+test('builds an X-only key and an X plus breakdown key', () => {
+  expect(getWaterfallCrossFilterKey(yearBar)).toBe(JSON.stringify([2019]));
+  expect(getWaterfallCrossFilterKey(breakdownBar)).toBe(
+    JSON.stringify([2019, 'Sylvester']),
+  );
+  expect(getWaterfallCrossFilterKey(grandTotal)).toBeNull();
+});
+
+test('filters the X column for a chart without a breakdown', () => {
+  const { dataMask } = getWaterfallCrossFilterDataMask({
+    category: yearBar,
+    selectedKeys: [],
+  });
+  expect(dataMask.extraFormData.filters).toEqual([
+    { col: 'year', op: 'IN', val: [2019] },
+  ]);
+  expect(dataMask.filterState.label).toBe('2019');
+  expect(dataMask.filterState.selectedValues).toEqual([JSON.stringify([2019])]);
+});
+
+test('filters both the X column and the breakdown', () => {
+  const { dataMask } = getWaterfallCrossFilterDataMask({
+    category: breakdownBar,
+    selectedKeys: [],
+  });
+  expect(dataMask.extraFormData.filters).toEqual([
+    { col: 'year', op: 'IN', val: [2019] },
+    { col: 'name', op: 'IN', val: ['Sylvester'] },
+  ]);
+  expect(dataMask.filterState.label).toBe('2019, Sylvester');
+});
+
+test('a period total filters the X column only', () => {
+  const { dataMask } = getWaterfallCrossFilterDataMask({
+    category: periodTotal,
+    selectedKeys: [],
+  });
+  expect(dataMask.extraFormData.filters).toEqual([
+    { col: 'year', op: 'IN', val: [2019] },
+  ]);
+});
+
+test('clicking the same bar again clears the filter', () => {
+  const key = getWaterfallCrossFilterKey(yearBar)!;
+  const { dataMask } = getWaterfallCrossFilterDataMask({
+    category: yearBar,
+    selectedKeys: [key],
+  });
+  expect(dataMask.extraFormData.filters).toEqual([]);
+  expect(dataMask.filterState.selectedValues).toBeNull();
+});
+
+test('a grand total produces no filter', () => {
+  const { dataMask } = getWaterfallCrossFilterDataMask({
+    category: grandTotal,
+    selectedKeys: [],
+  });
+  expect(dataMask.extraFormData.filters).toEqual([]);
+  expect(dataMask.filterState.selectedValues).toBeNull();
+});
+
+test('null and empty breakdown values stay distinct', () => {
+  const nullBar: WaterfallCategory = {
+    ...breakdownBar,
+    breakdownValue: null,
+  };
+  const emptyBar: WaterfallCategory = {
+    ...breakdownBar,
+    breakdownValue: '',
+  };
+  expect(
+    getWaterfallCrossFilterDataMask({
+      category: nullBar,
+      selectedKeys: [],
+    }).dataMask.extraFormData.filters,
+  ).toEqual([
+    { col: 'year', op: 'IN', val: [2019] },
+    { col: 'name', op: 'IS NULL' },
+  ]);
+  const emptyMask = getWaterfallCrossFilterDataMask({
+    category: emptyBar,
+    selectedKeys: [],
+  }).dataMask;
+  expect(emptyMask.extraFormData.filters).toEqual([
+    { col: 'year', op: 'IN', val: [2019] },
+    { col: 'name', op: 'IN', val: [''] },
+  ]);
+  expect(emptyMask.filterState.label).toBe('2019, <empty string>');
+});
+
+test('keeps a numeric category unabbreviated', () => {
+  const mask = getWaterfallCrossFilterDataMask({
+    category: { ...yearBar, xValue: 2024 },
+    selectedKeys: [],
+  }).dataMask;
+  expect(mask.filterState.label).toBe('2024');
+});
+
+test('a bigint category does not share a selection key with the same decimal string', () => {
+  const bigintBar: WaterfallCategory = { ...yearBar, xValue: BigInt(42) };
+  const stringBar: WaterfallCategory = { ...yearBar, xValue: '42' };
+  const bigintKey = getWaterfallCrossFilterKey(bigintBar);
+  const stringKey = getWaterfallCrossFilterKey(stringBar);
+
+  expect(bigintKey).not.toBe(stringKey);
+
+  const mask = getWaterfallCrossFilterDataMask({
+    category: bigintBar,
+    selectedKeys: [],
+  }).dataMask;
+  expect(mask.extraFormData.filters).toEqual([
+    { col: 'year', op: 'IN', val: ['42'] },
+  ]);
+  expect(mask.filterState.selectedValues).toEqual([bigintKey]);
+  expect(() => JSON.stringify(mask)).not.toThrow();
+
+  const stringMask = getWaterfallCrossFilterDataMask({
+    category: stringBar,
+    selectedKeys: bigintKey ? [bigintKey] : [],
+  }).dataMask;
+  expect(stringMask.extraFormData.filters).not.toEqual([]);
+  expect(isWaterfallBarDimmed(stringBar, bigintKey ? [bigintKey] : [])).toBe(
+    true,
+  );
+  expect(isWaterfallBarDimmed(bigintBar, bigintKey ? [bigintKey] : [])).toBe(
+    false,
+  );
+});
+
+test('formats a temporal X value with the axis time format', () => {
+  const epoch = Date.parse('2020-01-15T00:00:00.000Z');
+  const mask = getWaterfallCrossFilterDataMask({
+    category: {
+      ...yearBar,
+      xValue: epoch,
+    },
+    selectedKeys: [],
+    coltypeMapping: { year: GenericDataType.Temporal },
+    timeFormat: '%Y-%m-%d',
+  }).dataMask;
+  expect(mask.filterState.label).toBe(
+    getTimeFormatter('%Y-%m-%d')(new Date(epoch)),
+  );
+});
+
+test('reads selected keys from an array or an object', () => {
+  expect(getSelectedWaterfallKeys(['a'])).toEqual(['a']);
+  expect(getSelectedWaterfallKeys({ 0: 'a' })).toEqual(['a']);
+  expect(getSelectedWaterfallKeys(undefined)).toEqual([]);
+});
+
+test('an X-only selection keeps every bar of that period bright', () => {

Review Comment:
   A good find; now, when [2019, 'Sylvester'] is selected, only 'Sylvester' stands out. By comparison, the related metrics for the same period—as well as the overall figure for that period—look rather lackluster.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(plugin-chart-echarts): add cross-filtering to the Waterfall chart [superset]

Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #45680:
URL: https://github.com/apache/superset/pull/45680#discussion_r4417290596


##########
superset-frontend/src/utils/simpleFilterToAdhoc.ts:
##########
@@ -75,16 +75,36 @@ export const simpleFilterToAdhoc = (
 
   let result: AdhocFilter;
   if (isAdhocColumn(filterClause.col)) {
-    result = {
-      expressionType: 'SQL',
-      clause,
-      sqlExpression: translateToSql({
-        expressionType: ExpressionTypes.Simple,
-        subject: `(${filterClause.col.sqlExpression})`,
+    // A grain on an adhoc expression has to stay on the column. Compiling it
+    // to raw SQL drops the grain, so the bucket is no longer truncated.
+    if (filterClause.grain) {
+      result = {
+        expressionType: 'SIMPLE',
+        clause,
         operator: filterClause.op,
+        operatorId: Object.entries(OPERATOR_ENUM_TO_OPERATOR_TYPE).find(
+          operatorEntry => operatorEntry[1].operation === filterClause.op,
+        )?.[0],
+        subject: {
+          ...filterClause.col,
+          columnType: 'BASE_AXIS',
+          timeGrain: filterClause.col.timeGrain || filterClause.grain,

Review Comment:
   The grain is also stored on `subject` here, but `AdhocFilter.duplicateWith()` only clears the outer `timeGrain` when the comparator or operator changes. After Drill by on a monthly Custom SQL axis and Edit chart, changing the filter from `== 2021-01-01T00:00:00` to `== 2021-01-15T00:00:00` drops the grain from the pill while `convertFilter` still sends `col: subject` with `timeGrain: P1M` and `BASE_AXIS`, so the backend compares the month-truncated expression to Jan 15 and returns no rows. Should an edit that clears the filter's grain also strip `timeGrain`/`columnType` from the subject, with a test that goes conversion, edit, then `convertFilter`?



##########
superset-frontend/src/explore/exploreUtils/index.ts:
##########
@@ -466,10 +467,10 @@ export const getSimpleSQLExpression = (
   );
   const showComparator =
     disableInputOperatorValues.indexOf(operator ?? '') === -1;
-  // If returned value is an object after changing dataset
+  // A dataset column carries column_name. An adhoc column carries label.
   let expression: string =
     typeof subject === 'object'
-      ? (subject?.column_name ?? '')
+      ? (subject?.column_name ?? subject?.label ?? '')

Review Comment:
   `getSimpleSQLExpression` also feeds `translateToSql`, which builds the Custom SQL text when a filter is switched to the SQL tab. With a Custom SQL X axis such as `CAST(order_date AS TIMESTAMP)` labeled `bucket_date`, falling back to `label` turns the editor text into `bucket_date = '2021-01-01T00:00:00'`, and saving it fails because `bucket_date` is an alias, not a dataset column. Should the label fallback apply only to the pill display, with the SQL path using the subject's `sqlExpression`?



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(plugin-chart-echarts): add cross-filtering to the Waterfall chart [superset]

Posted by "EnxDev (via GitHub)" <gi...@apache.org>.
EnxDev commented on code in PR #45680:
URL: https://github.com/apache/superset/pull/45680#discussion_r4415423588


##########
superset-frontend/src/utils/simpleFilterToAdhoc.ts:
##########
@@ -75,16 +75,36 @@ export const simpleFilterToAdhoc = (
 
   let result: AdhocFilter;
   if (isAdhocColumn(filterClause.col)) {
-    result = {
-      expressionType: 'SQL',
-      clause,
-      sqlExpression: translateToSql({
-        expressionType: ExpressionTypes.Simple,
-        subject: `(${filterClause.col.sqlExpression})`,
+    // A grain on an adhoc expression has to stay on the column. Compiling it
+    // to raw SQL drops the grain, so the bucket is no longer truncated.
+    if (filterClause.grain) {
+      result = {
+        expressionType: 'SIMPLE',
+        clause,
         operator: filterClause.op,
+        operatorId: Object.entries(OPERATOR_ENUM_TO_OPERATOR_TYPE).find(
+          operatorEntry => operatorEntry[1].operation === filterClause.op,
+        )?.[0],
+        subject: {

Review Comment:
   This is the first path that puts an adhoc column object into a SIMPLE filter's `subject` (hence the `as unknown as`), and `convertFilter` passes it through fine for the query.
   
   The Explore pill only reads `column_name` though (`explore/exploreUtils/index.ts:472`), so after Drill by > Edit chart, or opening Explore from a dashboard with this cross-filter on, it shows something like `[P1M] = '2021-01-01T00:00:00'` with no column. Could that fallback use the adhoc `label`, plus a `getDefaultLabel` test for this shape?



##########
superset-frontend/plugins/plugin-chart-echarts/src/Waterfall/EchartsWaterfall.tsx:
##########
@@ -16,21 +16,146 @@
  * specific language governing permissions and limitations
  * under the License.
  */
+import { useMemo } from 'react';
+import {
+  ContextMenuFilters,
+  getColumnLabel,
+  TimeGranularity,
+} from '@superset-ui/core';
 import Echart from '../components/Echart';
 import { WaterfallChartTransformedProps } from './types';
 import { EventHandlers } from '../types';
 import { useLegendEventHandlers } from '../utils/legendEventHandlers';
+import {
+  getSelectedWaterfallKeys,
+  getWaterfallCrossFilterDataMask,
+  getWaterfallDrillFilters,
+} from './crossFilter';
+
+const noop = () => {};
+
+type WaterfallBarEvent = {
+  dataIndex?: number;
+  event?: { stop: () => void; event: PointerEvent };
+};
 
 export default function EchartsWaterfall(
   props: WaterfallChartTransformedProps,
 ) {
-  const { height, width, echartOptions, refs, onLegendStateChanged, formData } =
-    props;
+  const {
+    categories,
+    coltypeMapping,
+    echartOptions,
+    emitCrossFilters,
+    filterState,
+    formData,
+    height,
+    onContextMenu,
+    onLegendStateChanged,
+    refs,
+    setDataMask = noop,
+    width,
+  } = props;
+  const { xAxisTimeFormat } = formData;
+  const timeGrain: TimeGranularity | undefined =
+    formData.extraFormData?.time_grain_sqla ?? formData.timeGrainSqla;
 
   // The waterfall legend has a fixed set of three entries, so it never
   // paginates and has no scroll position to preserve.
-  const eventHandlers: EventHandlers =
-    useLegendEventHandlers(onLegendStateChanged);
+  const legendEventHandlers = useLegendEventHandlers(onLegendStateChanged);
+
+  const crossFilterHandlers: EventHandlers = useMemo(() => {
+    const selectedKeys = getSelectedWaterfallKeys(filterState?.selectedValues);
+    const categoryAt = (event: WaterfallBarEvent) => {
+      if (event.dataIndex == null) {
+        return undefined;
+      }
+      const category = categories[event.dataIndex];
+      if (!category || category.isGrandTotal) {
+        return undefined;
+      }
+      return category;
+    };
+
+    return {
+      click: (event: WaterfallBarEvent) => {
+        if (!emitCrossFilters) {
+          return;
+        }
+        const category = categoryAt(event);
+        if (!category) {
+          return;
+        }
+        setDataMask(
+          getWaterfallCrossFilterDataMask({
+            category,
+            selectedKeys,
+            coltypeMapping,
+            timeFormat: xAxisTimeFormat,
+            timeGrain,
+          }).dataMask,
+        );
+      },
+      contextmenu: (event: WaterfallBarEvent) => {
+        if (!onContextMenu) {
+          return;
+        }
+        const category = categoryAt(event);
+        if (!category) {
+          return;
+        }
+        event.event?.stop();
+        const pointerEvent = event.event?.event;
+        if (!pointerEvent) {
+          return;
+        }
+        // IS NULL is unary. The menu types only binary operators, and both
+        // drill paths forward `op` unchanged.
+        const drillFilters = getWaterfallDrillFilters({
+          category,
+          coltypeMapping,
+          timeFormat: xAxisTimeFormat,
+          timeGrain,
+        }) as NonNullable<ContextMenuFilters['drillToDetail']>;
+        const xColumnLabel = getColumnLabel(category.xColumn);

Review Comment:
   Nothing tests this with a Custom SQL X axis: the component tests all use string columns, where the old `filter.col === category.xColumn` check behaves the same, so a revert would still pass.
   
   `adhocBucketColumn` returns a copy, so this label match is what keeps an adhoc X clause in `xAxisFilters` (the Drill by scope selector needs it there). Worth one `contextmenu` case with an adhoc temporal X and a month grain?



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(plugin-chart-echarts): add cross-filtering to the Waterfall chart [superset]

Posted by "codecov[bot] (via GitHub)" <gi...@apache.org>.
codecov[bot] commented on PR #45680:
URL: https://github.com/apache/superset/pull/45680#issuecomment-6419365726

   ## [Codecov](https://app.codecov.io/gh/apache/superset/pull/45680?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
   :x: Patch coverage is `95.77465%` with `6 lines` in your changes missing coverage. Please review.
   :white_check_mark: Project coverage is 65.60%. Comparing base ([`63f9059`](https://app.codecov.io/gh/apache/superset/commit/63f90591867b01b9bd664bd63108226733afb52c?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`c187237`](https://app.codecov.io/gh/apache/superset/commit/c187237a7f4b0ade8a01e3f904aedd11e77cfd14?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
   :warning: Report is 1 commits behind head on master.
   
   | [Files with missing lines](https://app.codecov.io/gh/apache/superset/pull/45680?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Patch % | Lines |
   |---|---|---|
   | [...n-chart-echarts/src/Waterfall/EchartsWaterfall.tsx](https://app.codecov.io/gh/apache/superset/pull/45680?src=pr&el=tree&filepath=superset-frontend%2Fplugins%2Fplugin-chart-echarts%2Fsrc%2FWaterfall%2FEchartsWaterfall.tsx&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQtZnJvbnRlbmQvcGx1Z2lucy9wbHVnaW4tY2hhcnQtZWNoYXJ0cy9zcmMvV2F0ZXJmYWxsL0VjaGFydHNXYXRlcmZhbGwudHN4) | 87.17% | [5 Missing :warning: ](https://app.codecov.io/gh/apache/superset/pull/45680?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [.../plugin-chart-echarts/src/Waterfall/crossFilter.ts](https://app.codecov.io/gh/apache/superset/pull/45680?src=pr&el=tree&filepath=superset-frontend%2Fplugins%2Fplugin-chart-echarts%2Fsrc%2FWaterfall%2FcrossFilter.ts&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQtZnJvbnRlbmQvcGx1Z2lucy9wbHVnaW4tY2hhcnQtZWNoYXJ0cy9zcmMvV2F0ZXJmYWxsL2Nyb3NzRmlsdGVyLnRz) | 98.68% | [1 Missing :warning: ](https://app.codecov.io/gh/apache/superset/pull/45680?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   
   <details><summary>Additional details and impacted files</summary>
   
   
   
   ```diff
   @@            Coverage Diff             @@
   ##           master   #45680      +/-   ##
   ==========================================
   + Coverage   65.50%   65.60%   +0.09%     
   ==========================================
     Files        3057     3060       +3     
     Lines      201991   202362     +371     
     Branches    47255    47417     +162     
   ==========================================
   + Hits       132313   132757     +444     
   + Misses      66681    66608      -73     
     Partials     2997     2997              
   ```
   
   | [Flag](https://app.codecov.io/gh/apache/superset/pull/45680/flags?src=pr&el=flags&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage Δ | |
   |---|---|---|
   | [javascript](https://app.codecov.io/gh/apache/superset/pull/45680/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `80.52% <95.77%> (+0.15%)` | :arrow_up: |
   
   Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#carryforward-flags-in-the-pull-request-comment) to find out more.
   </details>
   
   [:umbrella: View full report in Codecov by Harness](https://app.codecov.io/gh/apache/superset/pull/45680?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).   
   :loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
   <details><summary> :rocket: New features to boost your workflow: </summary>
   
   - :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
   - :package: [JS Bundle Analysis](https://docs.codecov.com/docs/javascript-bundle-analysis): Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
   </details>


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(plugin-chart-echarts): add cross-filtering to the Waterfall chart [superset]

Posted by "SBIN2010 (via GitHub) via notifications" <no...@superset.apache.org>.
SBIN2010 commented on code in PR #45680:
URL: https://github.com/apache/superset/pull/45680#discussion_r4620424625


##########
superset-frontend/plugins/plugin-chart-echarts/test/Waterfall/EchartsWaterfall.test.tsx:
##########
@@ -0,0 +1,336 @@
+/**
+ * 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 { GenericDataType } from '@apache-superset/core/common';
+import { supersetTheme } from '@apache-superset/core/theme';
+import { ChartProps, SqlaFormData, TimeGranularity } from '@superset-ui/core';
+import { render } from '@testing-library/react';
+import EchartsWaterfall from '../../src/Waterfall/EchartsWaterfall';
+import transformProps from '../../src/Waterfall/transformProps';
+import { EchartsWaterfallChartProps } from '../../src/Waterfall/types';
+import Echart from '../../src/components/Echart';
+import { EventHandlers } from '../../src/types';
+
+jest.mock('../../src/components/Echart', () => ({
+  __esModule: true,
+  default: jest.fn(() => null),
+}));
+
+const mockedEchart = jest.mocked(Echart);
+
+const rows = [
+  { year: '2019', name: 'Sylvester', sum: 10 },
+  { year: '2019', name: 'Arnold', sum: 3 },
+  { year: '2020', name: 'Sylvester', sum: -10 },
+  { year: '2020', name: 'Arnold', sum: 5 },
+];
+
+const formData = {
+  colorScheme: 'bnbColors',
+  datasource: '3__table',
+  granularity_sqla: 'ds',
+  metric: 'sum',
+  x_axis: 'year',
+  groupby: 'name',
+  showTotal: true,
+};
+
+function renderChart(
+  overrides: Partial<ChartProps> & { emitCrossFilters?: boolean } = {},
+) {
+  const setDataMask = jest.fn();
+  const onContextMenu = jest.fn();
+  const chartProps = new ChartProps({
+    formData: formData as unknown as SqlaFormData,
+    width: 800,
+    height: 600,
+    queriesData: [{ data: rows }],
+    hooks: { setDataMask, onContextMenu },
+    theme: supersetTheme,
+    ...overrides,
+  });
+  const props = transformProps(
+    chartProps as unknown as EchartsWaterfallChartProps,
+  );
+  render(<EchartsWaterfall {...props} />);
+  const lastCall = mockedEchart.mock.calls[mockedEchart.mock.calls.length - 1];
+  const { eventHandlers } = lastCall[0] as { eventHandlers: EventHandlers };
+  return { eventHandlers, setDataMask, onContextMenu };
+}
+
+beforeEach(() => {
+  mockedEchart.mockClear();
+});
+
+function pointerEvent(dataIndex: number) {
+  return {
+    dataIndex,
+    event: {
+      stop: jest.fn(),
+      event: { clientX: 12, clientY: 24 } as PointerEvent,
+    },
+  };
+}
+
+test('clicking a breakdown bar filters the period and the breakdown', () => {
+  const { eventHandlers, setDataMask } = renderChart({
+    emitCrossFilters: true,
+  });
+  eventHandlers.click(pointerEvent(0));
+  expect(setDataMask).toHaveBeenCalledWith(
+    expect.objectContaining({
+      extraFormData: {
+        filters: [
+          { col: 'year', op: 'IN', val: ['2019'] },
+          { col: 'name', op: 'IN', val: ['Sylvester'] },
+        ],
+      },
+    }),
+  );
+});
+
+test('clicking a period total filters the period only', () => {
+  const { eventHandlers, setDataMask } = renderChart({
+    emitCrossFilters: true,
+  });
+  eventHandlers.click(pointerEvent(2));
+  expect(setDataMask).toHaveBeenCalledWith(
+    expect.objectContaining({
+      extraFormData: {
+        filters: [{ col: 'year', op: 'IN', val: ['2019'] }],
+      },
+    }),
+  );
+});
+
+test('clicking the same bar again clears the filter', () => {
+  const { eventHandlers, setDataMask } = renderChart({
+    emitCrossFilters: true,
+    filterState: { selectedValues: [JSON.stringify(['2019', 'Sylvester'])] },
+  });
+  eventHandlers.click(pointerEvent(0));
+  expect(setDataMask).toHaveBeenCalledWith(
+    expect.objectContaining({
+      extraFormData: { filters: [] },
+    }),
+  );
+});
+
+test('does not emit a filter when cross-filtering is disabled', () => {
+  const { eventHandlers, setDataMask } = renderChart({
+    emitCrossFilters: false,
+  });
+  eventHandlers.click(pointerEvent(0));
+  expect(setDataMask).not.toHaveBeenCalled();
+});
+
+test('clicking the grand total does not change the current filter', () => {
+  const { eventHandlers, setDataMask } = renderChart({
+    emitCrossFilters: true,
+    formData: { ...formData, groupby: undefined } as unknown as SqlaFormData,
+  });
+  eventHandlers.click(pointerEvent(2));
+  expect(setDataMask).not.toHaveBeenCalled();
+});
+
+const breakdownCrossFilter = {
+  dataMask: {
+    extraFormData: {
+      filters: [
+        { col: 'year', op: 'IN', val: ['2019'] },
+        { col: 'name', op: 'IN', val: ['Sylvester'] },
+      ],
+    },
+    filterState: {
+      label: '2019, Sylvester',
+      value: '2019, Sylvester',
+      selectedValues: [JSON.stringify(['2019', 'Sylvester'])],
+    },
+  },
+  isCurrentValueSelected: false,
+};
+
+test('a context menu carries the drill filters for the clicked bar', () => {

Review Comment:
   fixed in [e47a335]



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(plugin-chart-echarts): add cross-filtering to the Waterfall chart [superset]

Posted by "rusackas (via GitHub) via notifications" <no...@superset.apache.org>.
rusackas merged PR #45680:
URL: https://github.com/apache/superset/pull/45680


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org