sadpandajoe commented on code in PR #41907: URL: https://github.com/apache/superset/pull/41907#discussion_r4033301897
########## superset-frontend/src/components/Chart/DrillDown/DrillDownHost.tsx: ########## @@ -0,0 +1,364 @@ +/** + * 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 { + ComponentType, + useCallback, + useMemo, + useRef, + useState, + useEffect, +} from 'react'; +import { + QueryData, + QueryFormData, + BinaryQueryObjectFilterClause, + FeatureFlag, + isFeatureEnabled, + ensureIsArray, +} from '@superset-ui/core'; +import { useSelector } from 'react-redux'; +import { css } from '@apache-superset/core/theme'; +import { ChartSource } from 'src/types/ChartSource'; +import type { RootState } from 'src/dashboard/types'; +import { selectAsyncModeOverride } from 'src/utils/asyncMode'; +import type { RequestParams } from 'src/components/Chart/chartAction'; +import { useDrillDownState } from './useDrillDownState'; +import { DrillDownBreadcrumb } from './DrillDownBreadcrumb'; +import type { ChartRendererProps } from '../ChartRenderer'; + +/** + * Hook payload contract: chart plugins call `onDrillDown(filters, label)` + * via the chart's hooks bag when the user clicks a data point and a + * drill-down hierarchy is configured. + */ +export type OnDrillDownHook = ( + filters: BinaryQueryObjectFilterClause[], + label: string, +) => void; + +/** + * Build the cross-filter clauses the dashboard data-mask expects from a set of + * drill-down filter clauses. Shared by the drill (onDrillDown) and the + * breadcrumb navigation (handleResetTo) paths so their cross-filter shape can + * never diverge. Special cases mirror the native ECharts cross-filter path: a + * temporal bucket click is passed through as a `TEMPORAL_RANGE`, and a null + * value becomes `IS NULL` (rather than `IN [null]`, which selects nothing). + */ +const toCrossFilterClauses = (filters: BinaryQueryObjectFilterClause[]) => + filters.map(f => { + if (f.op === 'TEMPORAL_RANGE') { + return { col: f.col, op: 'TEMPORAL_RANGE' as const, val: f.val }; + } + if (f.val == null) { + return { col: f.col, op: 'IS NULL' as const }; + } + return { + col: f.col, + op: 'IN' as const, + val: [f.val] as (string | number | boolean)[], + }; + }); + +interface DrillDownHostProps extends ChartRendererProps { + /** The wrapped renderer component */ + ChartRendererComponent: ComponentType< + ChartRendererProps & { onDrillDown?: OnDrillDownHook } + >; +} + +/** + * Wraps `<ChartRenderer>` with drill-down behavior. When the chart's + * form_data declares a `drilldown_hierarchy`, this host: + * + * 1. Tracks how deep the user has drilled (a stack of levels) + * 2. Computes "effective" form_data for the current level (swapping the + * grouping dimension — groupby or x_axis — and adding accumulated filters) + * 3. Re-fetches chart data for that level + * 4. Renders a breadcrumb above the chart for navigating back up + * + * If the chart has no hierarchy, this is a thin pass-through. + */ +export function DrillDownHost({ + ChartRendererComponent, + ...rendererProps +}: DrillDownHostProps) { + const { formData, queriesResponse } = rendererProps; + + // Live cross-filter selection this chart has emitted into the dashboard data + // mask. A drilled chart writes its path here; when the mask is cleared + // (dashboard teardown, or the user removes the cross-filter from the filter + // bar) this goes empty. The hook uses it to discard persisted drill state + // that outlived its data mask instead of replaying it on remount. + const crossFilterValue = useSelector<RootState, unknown>( + state => state.dataMask?.[rendererProps.chartId]?.filterState?.value, + ); + const crossFilterCleared = + !!rendererProps.emitCrossFilters && + ensureIsArray(crossFilterValue).length === 0; + + // Request params for drill queries, mirroring exploreJSON so superseded + // drills abort, hung queries time out, and the per-dashboard async override + // is honored. The hook adds the per-request AbortSignal. + const asyncModeOverride = useSelector(selectAsyncModeOverride); + const dashboardId = useSelector<RootState, number | undefined>( + state => state.dashboardInfo?.id, + ); + const webserverTimeout = useSelector<RootState, number | undefined>( + state => state.common?.conf?.SUPERSET_WEBSERVER_TIMEOUT, + ); + const drillRequestParams = useMemo<RequestParams>(() => { + const params: RequestParams = {}; + if (webserverTimeout) { + params.timeout = webserverTimeout * 1000; + } + if (dashboardId) { + params.dashboard_id = dashboardId; + } + if (asyncModeOverride) { + params.async_mode_override = asyncModeOverride; + } + return params; + }, [webserverTimeout, dashboardId, asyncModeOverride]); + + const { + isDrilling, + drillStack, + selectedLeaf, + hierarchy, + effectiveFormData, + effectiveQueriesResponse, + isLoading, + error, + hasHierarchy, + drillDown, + resetTo, + } = useDrillDownState({ + chartId: rendererProps.chartId, + formData, + baseQueriesResponse: queriesResponse, + crossFilterCleared, + requestParams: drillRequestParams, + }); + + // Drill-down is a dashboard interaction gated behind the DRILL_DOWN feature + // flag. In Explore the control panel and the rendered chart would disagree + // (and clicks there mean something else), so only enable it when rendered + // inside a dashboard. + const drillEnabled = + isFeatureEnabled(FeatureFlag.DrillDown) && + hasHierarchy && + rendererProps.source === ChartSource.Dashboard; + + const onDrillDown = useMemo<OnDrillDownHook | undefined>(() => { + // Suspend drilling while a drill query is in error: the overlay has fallen + // back to the base chart, so a click here would append a base-level value + // as the next level and emit contradictory filters (e.g. country=USA plus + // country=Canada). The breadcrumb still allows navigating up, which + // re-queries and clears the error. + if (!drillEnabled || error != null) { + return undefined; + } + return (filters, label) => { + // Emit a cross-filter for the FULL drill path — every level reached so + // far plus this click — so other dashboard charts are scoped to exactly + // what the drilled chart shows, not just the deepest clicked column. + const pathFilters = [ + ...drillStack.flatMap(level => level.filters), + ...filters, + ]; + const pathLabels = [...drillStack.map(level => level.label), label]; + drillDown(filters, label); + if ( + rendererProps.emitCrossFilters && + rendererProps.actions?.updateDataMask + ) { + rendererProps.actions.updateDataMask(rendererProps.chartId, { + extraFormData: { + filters: toCrossFilterClauses(pathFilters), + }, + filterState: { + value: pathLabels, + selectedValues: pathLabels, + }, + }); + } + }; + }, [ + drillEnabled, + error, + drillDown, + drillStack, + rendererProps.emitCrossFilters, + rendererProps.actions, + rendererProps.chartId, + ]); + + const overlayProps = useMemo<Partial<ChartRendererProps>>(() => { + if (!isDrilling) { + // At the base level, render the chart unchanged. + return {}; + } + // A failed drill query leaves effectiveQueriesResponse null. Rather than + // pin the chart body to a perpetual loading spinner, fall back to the base + // chart (recoverable): the breadcrumb and error banner above convey the + // failure and let the user navigate back or retry. + if (error != null && !isLoading) { + return {}; + } + return { + formData: effectiveFormData as QueryFormData, + queriesResponse: (effectiveQueriesResponse ?? null) as QueryData[] | null, + // Treat "no data yet" as loading. On the first render after a drill the + // fetch effect hasn't run (isLoading is still false, drillData is null); + // without this the renderer would briefly paint a "No results" state. + chartStatus: Review Comment: This sets only the nested renderer to `loading`; the dashboard spinner still follows the unchanged Redux chart status, while `ChartRenderer` returns `null` for this state. A slow drill therefore blanks the chart with no loading affordance for the whole request/retry window. Could this keep the prior data visible or render a drill-local spinner? ########## superset-frontend/plugins/plugin-chart-echarts/src/utils/eventHandlers.ts: ########## @@ -167,16 +167,58 @@ export const allEventHandlers = ( selectedValues, coltypeMapping, formData, + onDrillDown, } = transformedProps; + + // When a drill-down hierarchy is configured, left-click drills instead of + // emitting a cross-filter. The DrillDownHost provides onDrillDown only when + // a hierarchy exists. + const hasDrillHierarchy = !!onDrillDown; + + const drillDownClickHandler = + hasDrillHierarchy && groupby.length > 0 + ? (e: { name: string }) => { + const values = labelMap[e.name]; Review Comment: When `threshold_for_other` creates the visible `Other` slice, that synthetic label has no `labelMap` entry, so clicking it silently returns without querying or updating the breadcrumb. Could this either represent the aggregate as a filter or make the `Other` slice explicitly non-drillable? ########## superset-frontend/src/components/Chart/DrillDown/useDrillDownState.ts: ########## @@ -0,0 +1,600 @@ +/** + * 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 { + useCallback, + useEffect, + useLayoutEffect, + useMemo, + useRef, + useState, +} from 'react'; +import { t } from '@apache-superset/core/translation'; +import { + BinaryQueryObjectFilterClause, + ensureIsArray, + getClientErrorObject, + getXAxisLabel, + isQueryFormColumn, + isXAxisSet, + QueryData, + QueryFormData, +} from '@superset-ui/core'; +import { simpleFilterToAdhoc } from 'src/utils/simpleFilterToAdhoc'; +import { + requestChartDataResolved, + type RequestParams, +} from 'src/components/Chart/chartAction'; +import { DrillDownLevel } from './types'; + +/** + * The form-data field name that stores the ordered list of drill columns. + * The chart starts at hierarchy[0] and advances one level per click. + */ +const HIERARCHY_FIELD = 'drilldown_hierarchy'; +const HIERARCHY_FIELD_CAMEL = 'drilldownHierarchy'; + +/** + * Default form-data field that holds the chart's grouping dimension. + * Most echarts plugins use 'groupby'; Sunburst uses 'columns'. The click + * handler can override this on a per-event basis. + */ +const DEFAULT_GROUPBY_FIELD = 'groupby'; +const DEFAULT_ADHOC_FILTERS_FIELD = 'adhoc_filters'; + +/** + * Drill navigation is kept in a module-level store keyed by chart id so it + * survives incidental remounts of the chart component. On a dashboard, an + * unrelated filter change (e.g. removing another chart's cross-filter) can + * cause the grid to re-render and remount the chart, which would otherwise + * reset the local React state and make the breadcrumb vanish mid-drill, + * stranding the user with no way to navigate back up. The store is process + * memory only — a full page reload still starts fresh. + */ +interface StoredDrillState { + drillStack: DrillDownLevel[]; + selectedLeaf?: string; + /** Filters for the value selected at the deepest level, if any. */ + selectedLeafFilters?: BinaryQueryObjectFilterClause[]; + /** + * Identity of the chart configuration (and dashboard slot) this state + * belongs to. A remount that restores from the store compares this against + * the current config so a stale record from a different configuration is + * discarded rather than replayed. + */ + configKey: string; +} +const drillStateStore = new Map<string | number, StoredDrillState>(); + +/** + * Clear persisted drill state. Without arguments clears everything (used by + * tests to isolate cases); with a chart id clears just that chart. + */ +export function clearDrillDownState(chartKey?: string | number): void { + if (chartKey === undefined) { + drillStateStore.clear(); + } else { + drillStateStore.delete(chartKey); + } +} + +interface UseDrillDownStateArgs { + /** Unique chart instance id (dashboard grid assigns one per slot). */ + chartId: string | number; + formData: QueryFormData; + /** Original chart data, shown when the drill stack is empty */ + baseQueriesResponse?: QueryData[] | null; + /** + * True when the chart's owning cross-filter data mask has been cleared + * (dashboard teardown, or the user removed this chart's cross-filter from the + * filter bar). Persisted drill state mirrors that data mask, so when it is + * gone the stored stack is orphaned: on mount it is discarded instead of + * replayed (which would re-fire a drilled query while linked charts sit at + * root). Defaults to false so non-dashboard callers keep plain persistence. + */ + crossFilterCleared?: boolean; + /** + * Base request params (timeout, dashboard_id, async_mode_override) for drill + * queries, mirroring exploreJSON. The hook adds the per-request AbortSignal. + * Without these a superseded synchronous drill keeps running, hung queries + * lack the normal timeout, and per-dashboard async overrides are ignored. + */ + requestParams?: RequestParams; +} + +interface UseDrillDownStateResult { + /** True if the user has drilled at least one level deep */ + isDrilling: boolean; + /** The breadcrumb path showing where the user is in the hierarchy */ + drillStack: DrillDownLevel[]; + /** Value selected at the deepest level */ + selectedLeaf?: string; + /** The computed hierarchy of column names */ + hierarchy: string[]; + /** form_data adjusted for the current drill level */ + effectiveFormData: QueryFormData; + /** Chart data for the current drill level (or base data when not drilling) */ + effectiveQueriesResponse: QueryData[] | null | undefined; + /** True while the next-level data is being fetched */ + isLoading: boolean; + /** Error message if the drill query failed */ + error?: string; + /** Whether the chart has a configured drill-down hierarchy */ + hasHierarchy: boolean; + /** + * Push a new level onto the drill stack. Called from the chart's click + * handler with the filters that identify the clicked data point. + */ + drillDown: (filters: BinaryQueryObjectFilterClause[], label: string) => void; + /** Truncate the drill stack to the given depth (0 = back to start) */ + resetTo: (depth: number) => void; +} + +/** + * Hook that manages a chart's drill-down state. Owns the drill stack, + * computes the effective form_data for the current level, fetches the + * data for that level, and exposes navigation helpers (drillDown / resetTo). + * + * The hook never mutates the upstream Redux store: closing or refreshing + * the dashboard wipes the drill state and restores the original chart. + */ +export function useDrillDownState({ + chartId, + formData, + baseQueriesResponse, + crossFilterCleared, + requestParams, +}: UseDrillDownStateArgs): UseDrillDownStateResult { + const chartKey = chartId; + + // Identity of the current drill configuration (and dashboard slot). The drill + // stack is anchored to the primary dimension (x_axis or groupby) and the + // hierarchy list, so this key changes whenever the drill would target a + // different set of columns. It is stored alongside persisted state and + // compared on restore. + const configFd = formData as Record<string, unknown>; + const configKey = JSON.stringify([ + chartId, + formData.viz_type, + configFd.x_axis ?? configFd.xAxis, + configFd[HIERARCHY_FIELD] ?? configFd[HIERARCHY_FIELD_CAMEL], + configFd[DEFAULT_GROUPBY_FIELD], + ]); + + // Restore persisted state only when it still belongs to this chart: the + // stored config identity must match, and the cross-filter data mask that + // backed the drill must not have been cleared while the chart was unmounted. + // Otherwise the record is orphaned and replaying it would re-fire a drilled + // query while linked charts are back at root. + const storedState = + chartKey != null ? drillStateStore.get(chartKey) : undefined; + const restoredState = + storedState && storedState.configKey === configKey && !crossFilterCleared + ? storedState + : undefined; + + // Drill state intentionally persists in drillStateStore across unmounts + // (dashboard virtualization scroll-out, tab switches, filter re-layouts) so + // it stays in sync with the cross-filter the drill emits into Redux. Evicting + // it on unmount previously left the emitted cross-filter orphaned — the drill + // appeared to reset while the filter lingered. The store is cleared on chart + // reconfigure (the layout effect below), on an orphaned restore (below), and + // via clearDrillDownState. + + const [drillStack, setDrillStack] = useState<DrillDownLevel[]>( + () => restoredState?.drillStack ?? [], + ); + const [selectedLeaf, setSelectedLeaf] = useState<string | undefined>( + () => restoredState?.selectedLeaf, + ); + // Filters for the value picked at the deepest level. Applied to the drilled + // chart's own query so it narrows to the selected leaf (a single bar), + // independent of the dashboard's cross-filter scope config. Without this the + // drilled chart keeps showing the full leaf distribution and only charts that + // happen to include themselves in their cross-filter scope look "filtered". + const [selectedLeafFilters, setSelectedLeafFilters] = useState< + BinaryQueryObjectFilterClause[] | undefined + >(() => restoredState?.selectedLeafFilters); + const [drillData, setDrillData] = useState<QueryData[] | null>(null); + const [isLoading, setIsLoading] = useState(false); + const [error, setError] = useState<string | undefined>(); + + // Evict a persisted record that exists but was not restored (orphaned by a + // config change or a cleared data mask) so it cannot leak to a later remount. + const evictedOrphanRef = useRef(false); + useLayoutEffect(() => { + if (evictedOrphanRef.current) { + return; + } + evictedOrphanRef.current = true; + if (chartKey != null && storedState && !restoredState) { + drillStateStore.delete(chartKey); + } + // Run once on mount; storedState/restoredState reflect the initial state. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + + // Reset live when the owning cross-filter is cleared while the chart stays + // mounted (the user removes this chart's cross-filter from the filter bar). + // Only a false -> true transition counts: mount and the normal drill sequence + // (the click writes a non-empty mask, so crossFilterCleared stays false) must + // not trip this, otherwise an in-progress drill would reset itself. + const prevCrossFilterClearedRef = useRef(crossFilterCleared); + useLayoutEffect(() => { + const wasCleared = prevCrossFilterClearedRef.current; + prevCrossFilterClearedRef.current = crossFilterCleared; + if (!crossFilterCleared || wasCleared) { + return; + } + if (chartKey != null) { + drillStateStore.delete(chartKey); + } + setDrillStack([]); + setSelectedLeaf(undefined); + setSelectedLeafFilters(undefined); + setDrillData(null); + setError(undefined); + }, [crossFilterCleared, chartKey]); + + // Persist drill navigation synchronously so it survives remounts (see + // drillStateStore) without racing. Writing on a deferred effect would let a + // remount triggered by the same interaction (e.g. clearing a cross-filter) + // restore stale state before the effect runs, so the mutators below write + // through this helper immediately instead. + const persist = useCallback( + ( + stack: DrillDownLevel[], + leaf: string | undefined, + leafFilters: BinaryQueryObjectFilterClause[] | undefined, + ) => { + if (chartKey == null) { + return; + } + if (stack.length === 0 && !leaf) { + drillStateStore.delete(chartKey); + } else { + drillStateStore.set(chartKey, { + drillStack: stack, + selectedLeaf: leaf, + selectedLeafFilters: leafFilters, + configKey, + }); + } + }, + [chartKey, configKey], + ); + + // Reset when the drill configuration changes, not just chart id or viz type. + // The drill stack is anchored to the primary dimension (x_axis or groupby) + // and the hierarchy list, so editing either — even without a viz-type change + // — must clear stale state whose next dimension no longer exists. A ref guard + // ensures the initial mount (which restores persisted state) does not wipe + // it, and that incidental re-renders from filter changes don't either. + // useLayoutEffect runs synchronously before paint so the stale drill state + // is cleared without a visible flash when the chart is reconfigured. + const prevConfigKeyRef = useRef(configKey); + useLayoutEffect(() => { + if (prevConfigKeyRef.current === configKey) { + return; + } + prevConfigKeyRef.current = configKey; + if (chartKey != null) { + drillStateStore.delete(chartKey); + } + setDrillStack([]); + setSelectedLeaf(undefined); + setSelectedLeafFilters(undefined); + setDrillData(null); + setError(undefined); + }, [configKey, chartKey]); + + const hierarchy = useMemo<string[]>(() => { + const fd = formData as Record<string, unknown>; + const xAxis = fd.x_axis ?? fd.xAxis; + + // Primary source: the dedicated `drilldown_hierarchy` control. The chart's + // own primary dimension (x_axis for axis charts, the first groupby column + // for groupby charts) is the top level and is prepended automatically when + // the author lists only the deeper levels. + const drillLevels = ensureIsArray( + fd[HIERARCHY_FIELD] ?? fd[HIERARCHY_FIELD_CAMEL], + ) as string[]; + if (drillLevels.length > 0) { + // The primary dimension is always the initial (index 0) level, even if + // the author listed it later in the control; normalize it to the front + // (deduped) so the first drill advances off the primary dimension. An + // x-axis may be an ad-hoc (Custom SQL) column, so resolve its label + // rather than assuming a plain string. + const xAxisStr = isXAxisSet(formData) + ? getXAxisLabel(formData) + : typeof xAxis === 'string' + ? xAxis + : undefined; + if (xAxisStr) { + return [xAxisStr, ...drillLevels.filter(col => col !== xAxisStr)]; + } + const firstGroupby = ensureIsArray(fd[DEFAULT_GROUPBY_FIELD]).find( Review Comment: A Custom SQL primary `groupby` is ignored here, so after the first click `currentDepth` advances against only the configured deeper levels: `[region, city]` jumps straight to `city`, and a single `[region]` leaves drilling disabled. Could this normalize the `AdhocColumn` label just as the x-axis branch does? ########## superset-frontend/plugins/plugin-chart-echarts/src/Timeseries/drillFilters.ts: ########## @@ -0,0 +1,146 @@ +/** + * 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 { + AxisType, + BinaryQueryObjectFilterClause, + DTTM_ALIAS, + getNumberFormatter, + getTimeFormatter, + TimeGranularity, +} from '@superset-ui/core'; +import { GenericDataType } from '@apache-superset/core/common'; +import { OrientationType } from './types'; +import { formatSeriesName } from '../utils/series'; +import { getTemporalXAxisDrillByFilter } from '../utils/xAxisDrillByFilter'; + +/** + * Resolve the category (x-axis) value from an ECharts click event. Horizontal + * bar charts hold the category at a different tuple index than vertical ones; + * fall back to the event `name` when the data tuple is unavailable. + */ +export function getCategoryAxisValue( + data: unknown, + name: unknown, + orientation?: OrientationType, +): string | number | undefined { + const index = orientation === OrientationType.Horizontal ? 1 : 0; + if (Array.isArray(data)) { + const categoryAxisValue = data[index]; + if ( + typeof categoryAxisValue === 'string' || + typeof categoryAxisValue === 'number' + ) { + return categoryAxisValue; + } + } + if (typeof name === 'string' || typeof name === 'number') { + return name; + } + return undefined; +} + +export interface TimeseriesDrillFilterParams { + /** ECharts click event `componentType` — only `series` clicks drill. */ + componentType?: string; + /** ECharts click event `data` tuple. */ + data: unknown; + /** ECharts click event `name`. */ + name: unknown; + /** The x-axis type (drilling only advances a category axis by value). */ + xAxisType?: AxisType; + /** The x-axis column name the filter is built against. */ + xAxisLabel: string; + orientation?: OrientationType; + dateFormat?: string; + numberFormat?: string; + /** Column type of the x-axis, used to format the breadcrumb label. */ + coltype?: GenericDataType; + /** For a temporal x-axis: the real granularity column (maps __timestamp). */ + granularitySqla?: string; + /** For a temporal x-axis: the active grain, for a bucket-range filter. */ + timeGrain?: TimeGranularity; +} + +/** + * Build the drill-down filter(s) for a Timeseries-family chart click. + * + * Timeseries charts are always x-axis driven: the hierarchy advances along the + * x-axis column and any groupby is only a series breakdown, so the drill filter + * is always keyed to the clicked x-axis value — never the series dimension. + * Clicks that are not on a series (e.g. axis labels, `componentType: 'xAxis'`) + * return no filters so they never trigger a drill. + * + * The breadcrumb/cross-filter label uses `formatSeriesName` for parity with the + * groupby drill path, so dates and decimals render formatted, not raw. + */ +export function buildTimeseriesDrillFilters({ + componentType, + data, + name, + xAxisType, + xAxisLabel, + orientation, + dateFormat, + numberFormat, + coltype, + granularitySqla, + timeGrain, +}: TimeseriesDrillFilterParams): BinaryQueryObjectFilterClause[] { + if (componentType !== 'series') { + return []; + } + + const format = (value: string | number) => + formatSeriesName(value, { + timeFormatter: getTimeFormatter(dateFormat), + numberFormatter: getNumberFormatter(numberFormat), + coltype, + }); + + // Orientation-aware x-axis value from the clicked series; falls back to the + // event name. Null check so zero-like labels (e.g. 0) still drill. + const axisValue = getCategoryAxisValue(data, name, orientation); + if (axisValue == null) { + return []; + } + + if (xAxisType === AxisType.Time) { + // Mirror drill-to-detail: map __timestamp to the real granularity column + // and build a grain-aware TEMPORAL_RANGE so a bucketed click scopes to the + // whole bucket, not an exact-timestamp equality that matches no rows. + const col = + xAxisLabel === DTTM_ALIAS ? (granularitySqla ?? xAxisLabel) : xAxisLabel; + const filter = getTemporalXAxisDrillByFilter( + col, + axisValue, + timeGrain, + format(axisValue), + ); + return filter ? [filter] : []; + } + + return [ + { + col: xAxisLabel, Review Comment: For a physical column with a verbose name—or a Custom SQL x-axis—this stores the display label in `col`, so `simpleFilterToAdhoc` treats `Order Date`/`country_expr` as a physical column instead of filtering `order_date`/the SQL expression. Could this preserve the original `QueryFormColumn` for the filter and use the label only for display? -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
