Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(bi): filter dashboard worksheets by selected results (#123561)

Marius Andraaafe4447bd16
diff --git a/docs/published/handbook/engineering/data-warehouse.md b/docs/published/handbook/engineering/data-warehouse.md
index 40d572128bc1..5a737a60d220 100644
--- a/docs/published/handbook/engineering/data-warehouse.md
+++ b/docs/published/handbook/engineering/data-warehouse.md
@@ -137,7 +137,9 @@ Each measure's **Format and display** dialog sets its label, currency, decimal p
In the worksheet editor, click a bar, line point, table cell, or pivot cell to explore its source rows. **Filter in new worksheet** preserves the original insight and adds the selected dimensions to a new worksheet. **View underlying rows** loads up to 1,000 matching source rows before aggregation; **Open in SQL editor** carries the same conditions, connection, and effective dashboard filters. When adding a drill-down condition would exceed the filter-group nesting limit, use **View underlying rows** or **Open in SQL editor**. Total cells omit rolled-up dimensions, and **Other** selects the categories outside the current Top N. Comparison-period points open rows from their original dates; their filtered-worksheet action is disabled to avoid combining current dates with prior-period conditions. These actions are unavailable on public shared insights.
-On authenticated dashboards in view mode, right-clicking a chart result opens a context menu beside the pointer. A left click keeps its usual action, such as opening the people modal, pinning a multi-series tooltip, or opening the BI drill-down dialog. Right-clicking a link or an input keeps the browser menu. Chart tooltips stay hidden until the menu closes. BI worksheets offer **View underlying rows**, then **Open in SQL editor**. Product analytics datapoints offer **View people**, **View recordings** when the existing drilldown selects matched recordings, then **Open in SQL editor**. Lifecycle results offer people and SQL only: their actor query identifies bucket members without projecting matched events. The people and SQL actions preserve the selected date, breakdown, and aggregation. SQL and recording links become available after the selected actor rows load. Selecting another result or closing the menu cancels any pending query. Recordings use matched session IDs; when no sessions match, the recordings action stays disabled. A left click, Escape, or a click outside closes the menu. Right-clicking another result moves the menu to it. Native links support opening actions in another tab. These actions do not change dashboard filters or create saved insights. Public shares, embeds, exports, and layout editing retain their existing behavior.
+On authenticated dashboards in view mode, right-clicking a chart result opens a context menu beside the pointer. A left click keeps its usual action, such as opening the people modal, pinning a multi-series tooltip, or opening the BI drill-down dialog. Right-clicking a link or an input keeps the browser menu. Chart tooltips stay hidden until the menu closes. BI worksheets offer **View underlying rows**, then **Open in SQL editor**. Product analytics datapoints offer **View people**, **View recordings** when the existing drilldown selects matched recordings, then **Open in SQL editor**. Lifecycle results offer people and SQL only: their actor query identifies bucket members without projecting matched events. The people and SQL actions preserve the selected date, breakdown, and aggregation. SQL and recording links become available after the selected actor rows load. Selecting another result or closing the menu cancels any pending query. Recordings use matched session IDs; when no sessions match, the recordings action stays disabled. A left click, Escape, or a click outside closes the menu. Right-clicking another result moves the menu to it. Native links support opening actions in another tab. Exploration actions do not change dashboard filters or create saved insights. Public shares, embeds, exports, and layout editing retain their existing behavior.
+
+BI worksheet menus also offer **Filter dashboard by this result** for current-period dimension values. The selection filters other BI worksheets using the same table and connection, combining with their existing conditions before aggregation. The source worksheet retains its full results. Each insight card header shows its filter status beside the title, before the menu; the status stays visible when the title is truncated. Cards unaffected by the active BI filter dim to 30% opacity; the source and matching worksheets remain fully visible. Clearing the filter restores all cards. The BI selection appears beside the existing dashboard filters and unsaved-filter controls. Click it to see the source worksheet and affected count, or use **Clear BI filters** or **Remove filter** to restore the saved results. Selections persist in the dashboard URL without changing saved insights, including when dashboard dates or variables change. Changing the source worksheet's table, dimensions, comparison period, or Top N configuration clears the selection. Product analytics, raw SQL visualizations, query snapshots, public shares, embeds, exports, and layout editing do not participate. Grand totals, previous-period results, and Top N **Other** remain available for exploration only.
**Compare previous period** turns date comparison on or off in one click. The adjacent comparison picker still supports custom offsets. Select a bounded date range before enabling comparison.
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 304dff80714c..2fa8be67381b 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6882,6 +6882,22 @@ snapshots:
hash: v1.k794b7964.4d9cb89cf4df116ff3e473c6484b641d675a0ea9c42f05bf132ae946b8fb5ca8.7gZROaPmb_dBk2rRnqWl_FEMGXi-hHVdsl42uYiZE44
products-business-intelligence-comparison-summary--table--light:
hash: v1.k794b7964.2476db083ec4c26dd53dab30351f38104c63d9578cd30eae620b60e8cc22a438.plfjAxTsZmL_nRDwhmqufs8yWeTX0wXrr0u5Is8_RUw
+ products-business-intelligence-dashboard-filter-bar--active--dark:
+ hash: v1.k794b7964.bb6d728290bfcbe4f44c55861165e8a8fd4cdfa854d01ddd22557595d9392ab7.9QnB2QMMrSzzYAU8JOmq0Rzmlw6tdZTmI9Manf6rZec
+ products-business-intelligence-dashboard-filter-bar--active--light:
+ hash: v1.k794b7964.2452162ce2d7e6fe8aec954aa863db7acb2809d3d8c48ad7017ae38b515291ba.XFGlvuZJD6jkMT0LgqLrZO6sK98AL6zmQ0Yqr79pBPs
+ products-business-intelligence-dashboard-filter-bar--long-label--dark:
+ hash: v1.k794b7964.56f7648f9fe0eaf4498beb167c7b2e0021fa5e6fefac31aa3e20d8d2045d028b.HUsQ39LTdyCAopEKwJI4dF4FgkqOleXraSeZQcc0H7k
+ products-business-intelligence-dashboard-filter-bar--long-label--light:
+ hash: v1.k794b7964.f1a8f2002e0f35caac691b719c62e3824e96b96cde6006bf06c2cdd92180d159.R7V7YeSOPm3HK_x09e-0hK8oJFkQ16ODA43wCUW1xso
+ products-business-intelligence-dashboard-filter-bar--no-related-worksheets--dark:
+ hash: v1.k794b7964.bb6d728290bfcbe4f44c55861165e8a8fd4cdfa854d01ddd22557595d9392ab7.osUoVBdIX20XbgRt37eL3vCVSakCf5SQ1mB_4lyqaP4
+ products-business-intelligence-dashboard-filter-bar--no-related-worksheets--light:
+ hash: v1.k794b7964.2452162ce2d7e6fe8aec954aa863db7acb2809d3d8c48ad7017ae38b515291ba.3z328n_ZiUnKO5NZn9-RqWXuRDs_iD7ygC6On9hOVFo
+ products-business-intelligence-dashboard-filter-bar--quill--dark:
+ hash: v1.k794b7964.685e595b2d82e74d28e617318f7ab37134911236fe466774afd1d226973032c8.W4MK1HnWdy6MWAiwx5r9tbBjfoDjCeHmfEBHofnhsYc
+ products-business-intelligence-dashboard-filter-bar--quill--light:
+ hash: v1.k794b7964.c62c158d76af1654b660d3d06e658d279edbc27a2c4887574d2c94206ce8eca7.1bXevOAdN31g-PzyVyWxCY5d8UwJKMv5T2FJ6Sv12K8
products-business-intelligence-pivot-table--multiple-measures-and-hierarchies--dark:
hash: v1.k794b7964.26ebc58171eb340426f9fe220739132bca02f59b8489cb5a0b8a6411f99bb34d.oNv5X9sNKiPmhC_sE607b5P0yHAJju-hcC7higWxX9g
products-business-intelligence-pivot-table--multiple-measures-and-hierarchies--light:
diff --git a/frontend/src/lib/components/Cards/CardMeta.scss b/frontend/src/lib/components/Cards/CardMeta.scss
index e71b6a715bc1..947ebd8fb175 100644
--- a/frontend/src/lib/components/Cards/CardMeta.scss
+++ b/frontend/src/lib/components/Cards/CardMeta.scss
@@ -119,6 +119,27 @@
margin: 0;
}
+ &.CardMeta--header-status {
+ .CardMeta__primary {
+ gap: 0.25rem;
+ padding-right: 0.75rem;
+ }
+
+ .CardMeta__main {
+ flex: 1;
+ }
+
+ .CardMeta__controls {
+ position: static;
+ flex-shrink: 0;
+ align-self: flex-start;
+
+ .LemonButton {
+ height: 1.75rem;
+ }
+ }
+ }
+
@container (min-width: 14rem) {
.CardMeta__heading {
// Let the top-heading row participate in CardMeta__top flex layout without an extra wrapper box.
@@ -220,4 +241,8 @@
.CardMeta:hover .CardMeta__refresh {
visibility: hidden;
}
+
+ .CardMeta--header-status .CardMeta__refresh {
+ display: none;
+ }
}
diff --git a/frontend/src/lib/components/Cards/CardMeta.tsx b/frontend/src/lib/components/Cards/CardMeta.tsx
index fcdc406b9eb8..ddfaf8e89e67 100644
--- a/frontend/src/lib/components/Cards/CardMeta.tsx
+++ b/frontend/src/lib/components/Cards/CardMeta.tsx
@@ -41,6 +41,7 @@ export interface CardMetaProps extends Pick<React.HTMLAttributes<HTMLDivElement>
extraControls?: JSX.Element | null
/** Refresh control revealed on card hover, shown in the top controls area. */
refreshControl?: JSX.Element | null
+ headerStatus?: JSX.Element | null
/** Description shown in the compact popover. */
metaDescription?: JSX.Element | null
/** Heading always shown in the popover (e.g. insight type + date range). Falls back to topHeading. */
@@ -71,6 +72,7 @@ export function CardMeta({
samplingFactor,
extraControls,
refreshControl,
+ headerStatus,
}: CardMetaProps): JSX.Element {
const { ref: primaryRef, width: primaryWidth } = useResizeObserver()
const { ref: detailsRef, height: detailsHeight } = useResizeObserver()
@@ -111,12 +113,30 @@ export function CardMeta({
})
: null
+ const editingControl = showEditingControls ? (
+ moreTooltip ? (
+ <Tooltip title={moreTooltip}>
+ <More overlay={moreButtons} />
+ </Tooltip>
+ ) : (
+ <More overlay={moreButtons} />
+ )
+ ) : null
+ const compactControls = (
+ <div className="CardMeta__controls">
+ {refreshControl}
+ {headerStatus}
+ {editingControl}
+ </div>
+ )
+
return (
<div
className={clsx(
'CardMeta',
className,
compact && 'CardMeta--compact',
+ compact && headerStatus && 'CardMeta--header-status',
areDetailsShown && 'CardMeta--details-shown',
onMouseDown && 'cursor-grab'
)}
@@ -133,17 +153,7 @@ export function CardMeta({
<>
<div className="CardMeta__top">
<div className="CardMeta__heading">{topHeading}</div>
- <div className="CardMeta__controls">
- {refreshControl}
- {showEditingControls &&
- (moreTooltip ? (
- <Tooltip title={moreTooltip}>
- <More overlay={moreButtons} />
- </Tooltip>
- ) : (
- <More overlay={moreButtons} />
- ))}
- </div>
+ {!headerStatus && compactControls}
</div>
{meta}
</>
@@ -179,20 +189,15 @@ export function CardMeta({
</LemonButton>
</Tooltip>
)}
- {showEditingControls &&
- (moreTooltip ? (
- <Tooltip title={moreTooltip}>
- <More overlay={moreButtons} />
- </Tooltip>
- ) : (
- <More overlay={moreButtons} />
- ))}
+ {headerStatus}
+ {editingControl}
</div>
</div>
{meta}
</>
)}
</div>
+ {compact && headerStatus && compactControls}
</div>
<div className="CardMeta__divider" />
diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightCard.scss b/frontend/src/lib/components/Cards/InsightCard/InsightCard.scss
index 16466048edbd..9d03b5e4c66b 100644
--- a/frontend/src/lib/components/Cards/InsightCard/InsightCard.scss
+++ b/frontend/src/lib/components/Cards/InsightCard/InsightCard.scss
@@ -11,6 +11,10 @@
border-radius: var(--radius);
transition: border 200ms ease;
+ &:has([data-bi-filter-status='unaffected']) {
+ opacity: 0.3;
+ }
+
&--highlighted {
border-color: var(--color-accent);
outline: 1px solid var(--color-accent);
diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
index 0264fbab7080..f67fdf537b69 100644
--- a/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
@@ -47,6 +47,9 @@ import {
} from '~/types'
import type { AlertType } from 'products/alerts/frontend/types'
+import { isCrossFilterWorksheet } from 'products/business_intelligence/frontend/biDashboardCrossFilters'
+import { BIDashboardFilterStatus } from 'products/business_intelligence/frontend/BIDashboardFilterStatus'
+import { BIDashboardTile } from 'products/business_intelligence/frontend/BIDashboardTile'
import { DashboardInsightResultMenu } from 'products/dashboards/frontend/components/DashboardInsightResultMenu'
import type { TileGroupMoveOptions } from 'products/dashboards/frontend/dashboardTileSections'
@@ -92,6 +95,7 @@ type AlertModalState = {
}
export interface InsightCardProps extends Resizeable {
+ biDashboardTileId?: number
resultMenuEnabled?: boolean
/** Insight to display. */
insight: InsightModel
@@ -213,6 +217,7 @@ function InsightCardInternal(
filtersOverride,
variablesOverride,
resultMenuEnabled,
+ biDashboardTileId,
children,
projectId,
projectTimezone,
@@ -402,6 +407,17 @@ function InsightCardInternal(
if (BlockingEmptyState) {
return BlockingEmptyState
}
+ if (biDashboardTileId !== undefined && dashboardId && isCrossFilterWorksheet(insight.query)) {
+ return (
+ <BIDashboardTile
+ dashboardId={dashboardId}
+ tileId={biDashboardTileId}
+ insight={insight}
+ query={insight.query}
+ loadPriority={loadPriority}
+ />
+ )
+ }
return (
<Query
query={insight.query}
@@ -429,6 +445,9 @@ function InsightCardInternal(
placement,
renderVizWhenMounted,
resultMenuEnabled,
+ biDashboardTileId,
+ dashboardId,
+ loadPriority,
])
const vizContent = shouldRenderViz ? (
@@ -463,6 +482,11 @@ function InsightCardInternal(
<ErrorBoundary exceptionProps={{ feature: 'insight' }}>
<BindLogic logic={insightLogic} props={insightLogicProps}>
<InsightMeta
+ headerStatus={
+ biDashboardTileId !== undefined && dashboardId ? (
+ <BIDashboardFilterStatus dashboardId={dashboardId} tileId={biDashboardTileId} />
+ ) : undefined
+ }
tile={tile}
insight={insight}
projectId={projectId}
diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx
index 1c421dcaf2d4..ff65296c62a8 100644
--- a/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx
@@ -122,6 +122,7 @@ interface InsightMetaProps extends Pick<
/** Called when the user mousedowns on the card meta (drag handle) in view mode to enter edit mode. */
onDragHandleMouseDown?: React.MouseEventHandler<HTMLDivElement>
tile?: DashboardTile
+ headerStatus?: JSX.Element
insight: InsightModel
refreshDisabledReason?: string
areDetailsShown?: boolean
@@ -134,6 +135,7 @@ interface InsightMetaProps extends Pick<
}
export function InsightMeta({
+ headerStatus,
tile,
insight,
ribbonColor,
@@ -482,6 +484,7 @@ export function InsightMeta({
<>
<CardMeta
compact={showCompactTile}
+ headerStatus={headerStatus}
ribbonColor={ribbonColor}
showEditingControls={showEditingControls}
showDetailsControls={showDetailsControls}
diff --git a/frontend/src/lib/utils/metricVariableUrlRedaction.test.ts b/frontend/src/lib/utils/metricVariableUrlRedaction.test.ts
index 355c0e8ae0c2..092ad57330af 100644
--- a/frontend/src/lib/utils/metricVariableUrlRedaction.test.ts
+++ b/frontend/src/lib/utils/metricVariableUrlRedaction.test.ts
@@ -21,15 +21,19 @@ describe('redactMetricVariableUrl', () => {
`https://us.posthog.com/login?next=${encodeURIComponent(`/dashboard/1?query_filters=${filters}`)}`,
'https://us.posthog.com/login',
],
+ ['a BI selection', '/dashboard/1#bi_filter=%7B%22country%22%3A%22US%22%7D', '/dashboard/1'],
+ ['a BI redirect', '/login?next=%2Fdashboard%2F1%23bi_filter%3Dvalue', '/login'],
+ ['an autocaptured BI link', 'a:attr__href="/dashboard/1#bi_filter=value"', ''],
['a relative link', `/insights/abc?filters_override=${filters}`, '/insights/abc'],
['an element chain', `a:attr__href="/insights/abc?filters_override=${filters}"`, ''],
])('keeps only the path of %s', (_name, text, expected) => {
expect(redactMetricVariableUrl(text)).toBe(expected)
})
- it('redacts every property of an event', () => {
- const url = `https://us.posthog.com/dashboard/1?query_filters=${filters}`
-
+ it.each([
+ `https://us.posthog.com/dashboard/1?query_filters=${filters}`,
+ `https://us.posthog.com/dashboard/1#bi_filter=${encodeURIComponent(JSON.stringify({ record: { country: 'private_value' } }))}`,
+ ])('redacts every property of an event containing %s', (url) => {
const event = redactMetricVariableUrls({
event: '$pageview',
properties: {
diff --git a/frontend/src/lib/utils/metricVariableUrlRedaction.ts b/frontend/src/lib/utils/metricVariableUrlRedaction.ts
index cb6a3f5cf810..1085c003cc10 100644
--- a/frontend/src/lib/utils/metricVariableUrlRedaction.ts
+++ b/frontend/src/lib/utils/metricVariableUrlRedaction.ts
@@ -1,14 +1,18 @@
import type { BeforeSendFn } from 'posthog-js'
-const MARKER = 'metricVariables'
+const MARKERS = ['metricVariables', 'bi_filter']
// The options requests of dashboard variables carry queries and selected values, and return query results.
const VARIABLE_OPTIONS_PATH = '/metrics/variable_options'
const NETWORK_PLUGIN = 'rrweb/network@1'
-/** A URL that holds metric variables, in any parameter or encoding, keeps only its path, so the queries, options and
+function holdsFilterData(text: string): boolean {
+ return MARKERS.some((marker) => text.includes(marker))
+}
+
+/** A URL that holds metric variables or BI selections, in any parameter or encoding, keeps only its path, so the queries, options and
* selected values of the variables stay out of analytics. Other text that holds them is dropped. */
export function redactMetricVariableUrl(text: string): string {
- if (!text.includes(MARKER)) {
+ if (!holdsFilterData(text)) {
return text
}
if (text.startsWith('/') || /^https?:\/\/\S+$/.test(text)) {
@@ -55,8 +59,8 @@ function holdsVariableData(request: unknown): boolean {
}
const { name, requestBody, responseBody } = request as Record<string, unknown>
return (
- (typeof name === 'string' && (name.includes(VARIABLE_OPTIONS_PATH) || name.includes(MARKER))) ||
- [requestBody, responseBody].some((body) => typeof body === 'string' && body.includes(MARKER))
+ (typeof name === 'string' && (name.includes(VARIABLE_OPTIONS_PATH) || holdsFilterData(name))) ||
+ [requestBody, responseBody].some((body) => typeof body === 'string' && holdsFilterData(body))
)
}
diff --git a/frontend/src/queries/nodes/DataNode/dataNodeLogic.test.ts b/frontend/src/queries/nodes/DataNode/dataNodeLogic.test.ts
index 4b6b3b3b9bea..883241409973 100644
--- a/frontend/src/queries/nodes/DataNode/dataNodeLogic.test.ts
+++ b/frontend/src/queries/nodes/DataNode/dataNodeLogic.test.ts
@@ -1,7 +1,9 @@
+import { waitFor } from '@testing-library/react'
import { expectLogic, partial } from 'kea-test-utils'
import api, { ApiError } from 'lib/api'
import { promiseResolveReject } from 'lib/utils/async'
+import { TaskQueue } from 'scenes/dashboard/dashboardUtils'
import { useMocks } from '~/mocks/jest'
import { dataNodeCollectionLogic } from '~/queries/nodes/DataNode/dataNodeCollectionLogic'
@@ -72,6 +74,37 @@ describe('dataNodeLogic', () => {
})
afterEach(() => logic?.unmount())
+ it('shares the dashboard queue capacity with other tile loads', async () => {
+ const loadQueue = new TaskQueue(3)
+ const dashboardLoad = promiseResolveReject<void>()
+ const occupied = loadQueue.run(() => dashboardLoad.promise)
+ const response = { results: [[1]], columns: ['value'] }
+ const queryResult = promiseResolveReject<typeof response>()
+ mockedQuery.mockReset()
+ mockedQuery.mockReturnValue(queryResult.promise)
+ const queries = [1, 2, 3].map((id) =>
+ dataNodeLogic({
+ key: `dashboard-queue-${id}`,
+ query: setLatestVersionsOnQuery({ kind: NodeKind.HogQLQuery, query: `SELECT ${id}` }),
+ loadQueue,
+ })
+ )
+ const unmounts = queries.map((query) => query.mount())
+ try {
+ await waitFor(() => expect(mockedQuery).toHaveBeenCalledTimes(2))
+ dashboardLoad.resolve()
+ await occupied
+ await waitFor(() => expect(mockedQuery).toHaveBeenCalledTimes(3))
+ queryResult.resolve(response)
+ await Promise.all(queries.map((query) => expectLogic(query).toFinishAllListeners()))
+ expect(queries.map((query) => query.values.response)).toEqual([response, response, response])
+ } finally {
+ dashboardLoad.resolve()
+ queryResult.resolve(response)
+ unmounts.forEach((unmount) => unmount())
+ }
+ })
+
it.each(['pending', 'failed'] as const)('restores a retained query after another query is %s', async (state) => {
const query = setLatestVersionsOnQuery({ kind: NodeKind.HogQLQuery, query: 'SELECT 1' })
const response = { results: [[1]], columns: ['value'] }
diff --git a/frontend/src/queries/nodes/DataNode/dataNodeLogic.ts b/frontend/src/queries/nodes/DataNode/dataNodeLogic.ts
index 422c00d491fe..c42c11c76d34 100644
--- a/frontend/src/queries/nodes/DataNode/dataNodeLogic.ts
+++ b/frontend/src/queries/nodes/DataNode/dataNodeLogic.ts
@@ -24,6 +24,7 @@ import { dayjs } from 'lib/dayjs'
import { ConcurrencyController } from 'lib/utils/concurrencyController'
import { inStorybook, inStorybookTestRunner, uuid } from 'lib/utils/dom'
import { shouldCancelQuery } from 'lib/utils/requests'
+import type { TaskQueue } from 'scenes/dashboard/dashboardUtils'
import { UNSAVED_INSIGHT_MIN_REFRESH_INTERVAL_MINUTES } from 'scenes/insights/insightLogic'
import { compareDataNodeQuery, haveVariablesOrFiltersChanged, validateQuery } from 'scenes/insights/utils/queryUtils'
import { sceneLogic } from 'scenes/sceneLogic'
@@ -125,6 +126,7 @@ import {
} from './responseCache'
export interface DataNodeLogicProps {
+ loadQueue?: TaskQueue
key: string
query: DataNode
/** Cached results when fetching nodes in bulk (list endpoint), sharing or exporting. */
@@ -1210,39 +1212,42 @@ export const dataNodeLogic = kea<dataNodeLogicType>([
) {
reclaimReleasedQuery()
}
- const responsePromise = queryConcurrencyController.run({
- debugTag: query.kind,
- abortController,
- priority:
- props.loadPriority ??
- (queryConcurrencyController === notebookConcurrencyController
- ? notebookLoadOrder++
- : undefined),
- fn: async (): Promise<{ duration: number; data: Record<string, any> }> => {
- const now = performance.now()
- try {
- breakpoint()
- const data =
- (await performQuery<DataNode>(
- addModifiers(query, props.modifiers),
- methodOptions,
- refresh,
- queryId,
- actions.setPollResponse,
- props.filtersOverride,
- props.variablesOverride,
- pollOnly,
- props.limitContext
- )) ?? null
- const duration = performance.now() - now
- return { data, duration }
- } catch (error: any) {
- const duration = performance.now() - now
- error.duration = duration
- throw error
- }
- },
- })
+ const runQuery = async (): Promise<{ duration: number; data: Record<string, any> }> => {
+ const now = performance.now()
+ try {
+ breakpoint()
+ const data =
+ (await performQuery<DataNode>(
+ addModifiers(query, props.modifiers),
+ methodOptions,
+ refresh,
+ queryId,
+ actions.setPollResponse,
+ props.filtersOverride,
+ props.variablesOverride,
+ pollOnly,
+ props.limitContext
+ )) ?? null
+ const duration = performance.now() - now
+ return { data, duration }
+ } catch (error: any) {
+ const duration = performance.now() - now
+ error.duration = duration
+ throw error
+ }
+ }
+ const responsePromise = props.loadQueue
+ ? props.loadQueue.run(runQuery, abortController.signal)
+ : queryConcurrencyController.run({
+ debugTag: query.kind,
+ abortController,
+ priority:
+ props.loadPriority ??
+ (queryConcurrencyController === notebookConcurrencyController
+ ? notebookLoadOrder++
+ : undefined),
+ fn: runQuery,
+ })
if (key && keepRunningOnUnmount) {
const teamId = values.currentTeamId
// The in-flight entry retains the result, so `loadDataSuccess` skips its copy.
diff --git a/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx b/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx
index 31b09f0daf2f..4372da7ec6de 100644
--- a/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx
@@ -125,6 +125,7 @@ export function DataTableVisualization({
const vizKey = insightVizDataNodeKey(insightProps)
const dataNodeCollectionId = insightVizDataCollectionId(insightProps, key)
const dataVisualizationLogicProps: DataVisualizationLogicProps = {
+ loadQueue: context?.loadQueue,
key: vizKey,
query,
dashboardId: insightProps.dashboardId,
@@ -142,6 +143,7 @@ export function DataTableVisualization({
}
const dataNodeLogicProps: DataNodeLogicProps = {
+ loadQueue: context?.loadQueue,
query: getBIVisualizationSource(query),
retainResponseOnUnmount: insightProps.retainResponseOnUnmount,
key: vizKey,
@@ -235,6 +237,9 @@ function InternalDataTableVisualization(props: DataTableVisualizationProps): JSX
query,
filtersOverride: props.filtersOverride,
variablesOverride: props.variablesOverride,
+ onFilterDashboard: !props.inSharedMode ? props.context?.onSelectBIMark : undefined,
+ isDashboardFilterSelected: !props.inSharedMode ? props.context?.isBIMarkActiveFilter : undefined,
+ getDashboardFilterUrl: !props.inSharedMode ? props.context?.getBIMarkDashboardUrl : undefined,
}
const drilldownLogic = biDrilldownLogic(drilldownProps)
const { inspect: inspectResult, setInteraction, close: closeResultMenu } = useActions(drilldownLogic)
diff --git a/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.ts b/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.ts
index 24c55c79bb49..de900f2736f6 100644
--- a/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.ts
+++ b/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.ts
@@ -75,7 +75,7 @@ import type {
TraceSpansQueryResponse,
} from '../../schema/schema-general'
import type { TraceSpansTreeQueryResponse } from '../../schema/schema-general'
-import { dataNodeLogic } from '../DataNode/dataNodeLogic'
+import { DataNodeLogicProps, dataNodeLogic } from '../DataNode/dataNodeLogic'
import { QueryFeature, getQueryFeatures } from '../DataTable/queryFeatures'
import { getAutoBoxPlotSettings } from './Components/Charts/sqlBoxPlotAdapter'
import { humanizeEventColumnValue } from './eventColumnLabels'
@@ -123,6 +123,7 @@ export interface AxisSeries<T> {
}
export interface DataVisualizationLogicProps {
+ loadQueue?: DataNodeLogicProps['loadQueue']
key: string
query: VisualizationNode
editMode?: boolean
@@ -990,6 +991,7 @@ export const dataVisualizationLogic = kea<dataVisualizationLogicType>([
teamLogic,
['currentTeamId'],
dataNodeLogic({
+ loadQueue: props.loadQueue,
cachedResults: props.cachedResults,
key: props.key,
query: getBIVisualizationSource(props.query),
@@ -1014,6 +1016,7 @@ export const dataVisualizationLogic = kea<dataVisualizationLogicType>([
],
actions: [
dataNodeLogic({
+ loadQueue: props.loadQueue,
cachedResults: props.cachedResults,
retainResponseOnUnmount: props.retainResponseOnUnmount,
key: props.key,
diff --git a/frontend/src/queries/types.ts b/frontend/src/queries/types.ts
index 22098023ac8c..70673bd043e3 100644
--- a/frontend/src/queries/types.ts
+++ b/frontend/src/queries/types.ts
@@ -1,6 +1,7 @@
import { CSSProperties, ComponentType, HTMLProps } from 'react'
import { ExpandableConfig } from 'lib/lemon-ui/LemonTable'
+import type { TaskQueue } from 'scenes/dashboard/dashboardUtils'
import { QueryFeature } from '~/queries/nodes/DataTable/queryFeatures'
import {
@@ -19,7 +20,11 @@ import { BIVisualizationNode } from './schema/schema-business-intelligence'
/** Pass custom metadata to queries. Used for e.g. custom columns in the DataTable. */
export interface QueryContext<Q extends QuerySchema = QuerySchema> {
+ onSelectBIMark?: (record: Record<string, unknown>) => void
+ isBIMarkActiveFilter?: (record: Record<string, unknown>) => boolean
+ getBIMarkDashboardUrl?: (record: Record<string, unknown>) => string
dashboardResultMenu?: boolean
+ loadQueue?: TaskQueue
/** Column templates for the DataTable */
columns?: Record<string, QueryContextColumn>
diff --git a/frontend/src/scenes/dashboard/DashboardFilters.tsx b/frontend/src/scenes/dashboard/DashboardFilters.tsx
index f7e7948d488b..03916e8063d5 100644
--- a/frontend/src/scenes/dashboard/DashboardFilters.tsx
+++ b/frontend/src/scenes/dashboard/DashboardFilters.tsx
@@ -7,8 +7,10 @@ import { LemonButton, LemonMenu } from '@posthog/lemon-ui'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { urls } from 'scenes/urls'
+import { isSharedView } from '~/exporter/exporterViewLogic'
import { DashboardPlacement } from '~/types'
+import { BIDashboardFilterBar } from 'products/business_intelligence/frontend/BIDashboardFilterBar'
import { DashboardUnsavedChangesIndicator } from 'products/dashboards/frontend/dashboardSettings/DashboardUnsavedChangesIndicator'
import { DashboardMetricVariables } from 'products/metrics/frontend/components/dashboardVariables/DashboardMetricVariables'
@@ -21,7 +23,7 @@ interface DashboardFilterBarProps {
}
export function DashboardFilterBar({ backTo }: DashboardFilterBarProps): JSX.Element {
- const { placement, dashboard, hasVariables, effectiveEditBarFilters } = useValues(dashboardLogic)
+ const { placement, dashboard, layoutEditMode, hasVariables, effectiveEditBarFilters } = useValues(dashboardLogic)
const controlsEnabled = useFeatureFlag('METRICS_DASHBOARD_CONTROLS')
return (
<div className="@container/dashboard-filters flex min-w-0 flex-1 flex-col gap-2">
@@ -42,7 +44,14 @@ export function DashboardFilterBar({ backTo }: DashboardFilterBarProps): JSX.Ele
!!effectiveEditBarFilters.metricVariables?.length && (
<DashboardMetricVariables editable={false} />
)}
- {placement === DashboardPlacement.Dashboard && <DashboardUnsavedChangesIndicator />}
+ {placement === DashboardPlacement.Dashboard && (
+ <div className="flex min-w-0 max-w-full flex-wrap items-center gap-2 empty:hidden">
+ <DashboardUnsavedChangesIndicator />
+ {dashboard && !layoutEditMode && !isSharedView() && (
+ <BIDashboardFilterBar dashboardId={dashboard.id} />
+ )}
+ </div>
+ )}
</div>
</div>
{![DashboardPlacement.Export, DashboardPlacement.Builtin].includes(placement) && (
diff --git a/frontend/src/scenes/dashboard/DashboardItems.tsx b/frontend/src/scenes/dashboard/DashboardItems.tsx
index 5e19a19827c1..2711dcd45715 100644
--- a/frontend/src/scenes/dashboard/DashboardItems.tsx
+++ b/frontend/src/scenes/dashboard/DashboardItems.tsx
@@ -1,7 +1,7 @@
import './DashboardItems.scss'
import clsx from 'clsx'
-import { useActions, useAsyncActions, useValues } from 'kea'
+import { useActions, useAsyncActions, useMountedLogic, useValues } from 'kea'
import { router } from 'kea-router'
import { RefObject, memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { GridLayout, Responsive as ReactGridLayout } from 'react-grid-layout'
@@ -40,6 +40,7 @@ import { urls } from 'scenes/urls'
import { getCurrentExporterData, isSharedView } from '~/exporter/exporterViewLogic'
import { DashboardLayoutSize, DashboardPlacement, DashboardTile, DashboardType } from '~/types'
+import { biDashboardCrossFilterLogic } from 'products/business_intelligence/frontend/biDashboardCrossFilterLogic'
import { DashboardGridBackground } from 'products/dashboards/frontend/components/DashboardGridBackground'
import { DashboardInsightTile } from 'products/dashboards/frontend/components/DashboardInsightTile'
import { DashboardTextItem } from 'products/dashboards/frontend/components/DashboardTextItem/DashboardTextItem'
@@ -128,7 +129,16 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
collapsedTileGroupKeys,
tileGroupMoveOptions,
activeTileGroupTab,
+ queryLoadQueue,
} = useValues(dashboardLogic)
+ const canCrossFilter = placement === DashboardPlacement.Dashboard && !isSharedView() && !layoutEditMode
+ useMountedLogic(
+ biDashboardCrossFilterLogic({
+ dashboardId: dashboard?.id ?? 0,
+ tiles: canCrossFilter ? (tiles ?? []) : [],
+ loadQueue: queryLoadQueue,
+ })
+ )
const { layoutZoom = 1 } = useValues(dashboardLogic)
const {
stageLayouts,
@@ -660,7 +670,8 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
key={tile.id}
tile={tile}
insight={insight}
- resultMenuEnabled={placement === DashboardPlacement.Dashboard && !isSharedView() && !layoutEditMode}
+ resultMenuEnabled={canCrossFilter}
+ biDashboardTileId={canCrossFilter ? tile.id : undefined}
loadingQueued={loadingQueued}
loading={loading}
// The dashboard load queue owns this tile, so the card must not start its own query.
diff --git a/frontend/src/scenes/dashboard/dashboardLogic.tsx b/frontend/src/scenes/dashboard/dashboardLogic.tsx
index 60dd090194b2..e7467f5aaf7c 100644
--- a/frontend/src/scenes/dashboard/dashboardLogic.tsx
+++ b/frontend/src/scenes/dashboard/dashboardLogic.tsx
@@ -772,6 +772,7 @@ export interface dashboardLogicValues {
placement: DashboardPlacement
previewedDashboardSettings: DashboardSettings | null
projectTreeRef: ProjectTreeRef
+ queryLoadQueue: TaskQueue
readOnly: boolean
refreshEligibilityTick: number
refreshMetrics: {
@@ -3474,7 +3475,8 @@ export const dashboardLogic = kea<dashboardLogicType>([
},
],
})),
- selectors(() => ({
+ selectors(({ cache }) => ({
+ queryLoadQueue: [() => [], (): TaskQueue => tileLoadQueue(cache)],
filterEditModeActive: [
(s) => [s.dashboardEditing],
(dashboardEditing: DashboardEditing | null): boolean => dashboardEditing?.filters === true,
diff --git a/products/business_intelligence/frontend/BIDashboardFilterBar.stories.tsx b/products/business_intelligence/frontend/BIDashboardFilterBar.stories.tsx
new file mode 100644
index 000000000000..cb079f71bd3c
--- /dev/null
+++ b/products/business_intelligence/frontend/BIDashboardFilterBar.stories.tsx
@@ -0,0 +1,63 @@
+import { Meta, StoryObj } from '@storybook/react'
+import { useEffect } from 'react'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+
+import { BIConfig, BIVisualizationNode } from '~/queries/schema/schema-business-intelligence'
+import { NodeKind } from '~/queries/schema/schema-general'
+import { DashboardTile } from '~/types'
+
+import { biDashboardCrossFilterLogic } from './biDashboardCrossFilterLogic'
+import { BIDashboardFilterBar } from './BIDashboardFilterBar'
+import { buildBIQuery, DEFAULT_BI_CONFIG } from './biEditorTypes'
+
+const config: BIConfig = {
+ ...DEFAULT_BI_CONFIG,
+ source: { table: 'example_orders' },
+ rows: [
+ { id: 'country', name: 'Country', expression: 'country', type: 'string', source: { table: 'example_orders' } },
+ ],
+}
+const query: BIVisualizationNode = { ...buildBIQuery(config)!.node, kind: NodeKind.BIVisualizationNode, config }
+const tiles = [1, 2, 3].map((id) => ({
+ id,
+ color: null,
+ layouts: {},
+ insight: { query, name: 'Orders by country', short_id: `example-${id}` },
+})) as unknown as DashboardTile[]
+
+function FilterBarPreview({
+ longLabel = false,
+ noTargets = false,
+}: {
+ longLabel?: boolean
+ noTargets?: boolean
+}): JSX.Element {
+ useEffect(() => {
+ const logic = biDashboardCrossFilterLogic({ dashboardId: 777, tiles: noTargets ? tiles.slice(0, 1) : tiles })
+ const unmount = logic.mount()
+ logic.actions.selectMark(1, 'Orders by country', query, {
+ country: longLabel ? 'A long country label that must fit beside other dashboard controls' : 'US',
+ })
+ return unmount
+ }, [longLabel, noTargets])
+ return (
+ <div className="w-[520px] max-w-full p-3">
+ <BIDashboardFilterBar dashboardId={777} />
+ </div>
+ )
+}
+
+const meta: Meta = {
+ title: 'Products/Business intelligence/Dashboard filter bar',
+ parameters: { testOptions: { waitForSelector: '[data-attr="bi-dashboard-filter-bar"]' } },
+}
+export default meta
+
+export const Active: StoryObj = { render: () => <FilterBarPreview /> }
+export const LongLabel: StoryObj = { render: () => <FilterBarPreview longLabel /> }
+export const NoRelatedWorksheets: StoryObj = { render: () => <FilterBarPreview noTargets /> }
+export const Quill: StoryObj = {
+ parameters: { featureFlags: [FEATURE_FLAGS.TODAY_RAIL_NAV] },
+ render: () => <FilterBarPreview longLabel />,
+}
diff --git a/products/business_intelligence/frontend/BIDashboardFilterBar.test.tsx b/products/business_intelligence/frontend/BIDashboardFilterBar.test.tsx
new file mode 100644
index 000000000000..7c7edbbcdd1a
--- /dev/null
+++ b/products/business_intelligence/frontend/BIDashboardFilterBar.test.tsx
@@ -0,0 +1,58 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
+import { BIVisualizationNode } from '~/queries/schema/schema-business-intelligence'
+import { NodeKind } from '~/queries/schema/schema-general'
+import { initKeaTests } from '~/test/init'
+
+import { biDashboardCrossFilterLogic } from './biDashboardCrossFilterLogic'
+import { BIDashboardFilterBar } from './BIDashboardFilterBar'
+import { buildBIQuery, DEFAULT_BI_CONFIG } from './biEditorTypes'
+
+describe('dashboard BI filter autocapture', () => {
+ beforeEach(() => initKeaTests())
+ afterEach(cleanup)
+
+ it.each([false, true])('excludes the summary and portaled selection details (quill=%s)', async (quill) => {
+ featureFlagLogic.actions.setFeatureFlags([], { 'today-rail-nav': quill })
+ const config = {
+ ...DEFAULT_BI_CONFIG,
+ source: { table: 'example_orders' },
+ rows: [
+ {
+ id: 'country',
+ name: 'Country',
+ expression: 'country',
+ type: 'string' as const,
+ source: { table: 'example_orders' },
+ },
+ ],
+ }
+ const query: BIVisualizationNode = {
+ ...buildBIQuery(config)!.node,
+ kind: NodeKind.BIVisualizationNode,
+ config,
+ }
+ const logic = biDashboardCrossFilterLogic({ dashboardId: 777 })
+ const unmount = logic.mount()
+ try {
+ logic.actions.selectMark(1, 'Example orders', query, { country: 'US' })
+ const { container } = render(<BIDashboardFilterBar dashboardId={777} />)
+ const summary = screen.getByLabelText('BI filter: Country: US')
+ expect(summary.closest('.ph-no-capture')).not.toBeNull()
+
+ await userEvent.click(summary)
+ const value = await screen.findByText('Country: US', { exact: true })
+ const source = screen.getByText('Example orders')
+ expect(container).not.toContainElement(value)
+ expect(value.closest('.ph-no-capture')).not.toBeNull()
+ expect(source.closest('.ph-no-capture')).not.toBeNull()
+ } finally {
+ unmount()
+ }
+ })
+})
diff --git a/products/business_intelligence/frontend/BIDashboardFilterBar.tsx b/products/business_intelligence/frontend/BIDashboardFilterBar.tsx
new file mode 100644
index 000000000000..a1c2b32d835b
--- /dev/null
+++ b/products/business_intelligence/frontend/BIDashboardFilterBar.tsx
@@ -0,0 +1,90 @@
+import { useActions, useValues } from 'kea'
+
+import { IconFilter, IconX } from '@posthog/icons'
+import { LemonButton } from '@posthog/lemon-ui'
+import { Button, ButtonGroup, Popover, PopoverContent, PopoverTrigger } from '@posthog/quill'
+
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
+import { LemonDropdown } from 'lib/lemon-ui/LemonDropdown'
+import { Link, LinkPrimitive } from 'lib/lemon-ui/Link'
+
+import { biDashboardCrossFilterLogic } from './biDashboardCrossFilterLogic'
+
+export function BIDashboardFilterBar({ dashboardId }: { dashboardId: number }): JSX.Element | null {
+ const { selection, targets, sourceInsightUrl } = useValues(biDashboardCrossFilterLogic({ dashboardId }))
+ const { setSelection } = useActions(biDashboardCrossFilterLogic({ dashboardId }))
+ const todayRailNav = useFeatureFlag('TODAY_RAIL_NAV')
+ if (!selection) {
+ return null
+ }
+ const targetCount = Object.keys(targets).length
+ const summary = selection.selection.labels.map(({ name, value }) => `${name}: ${value}`).join(', ')
+ const clear = (): void => setSelection(null)
+ const details = (
+ <div className="ph-no-capture flex max-w-80 flex-col gap-2 text-xs">
+ <span className="font-semibold break-words">{summary}</span>
+ <span className="break-words">
+ <span>Filter from </span>
+ {todayRailNav ? (
+ <LinkPrimitive to={sourceInsightUrl} className="underline">
+ {selection.title}
+ </LinkPrimitive>
+ ) : (
+ <Link to={sourceInsightUrl}>{selection.title}</Link>
+ )}
+ </span>
+ <span>{`${targetCount} ${targetCount === 1 ? 'worksheet' : 'worksheets'} filtered`}</span>
+ </div>
+ )
+ return (
+ <div className="ph-no-capture flex min-w-0 max-w-full" data-attr="bi-dashboard-filter-bar">
+ {todayRailNav ? (
+ <Popover>
+ <ButtonGroup className="min-w-0 max-w-full">
+ <PopoverTrigger
+ render={
+ <Button variant="outline" className="min-w-0" aria-label={`BI filter: ${summary}`} />
+ }
+ >
+ <IconFilter />
+ <span className="max-w-64 truncate">{`BI: ${summary}`}</span>
+ </PopoverTrigger>
+ <Button
+ variant="outline"
+ size="icon"
+ onClick={clear}
+ aria-label="Clear BI filters"
+ tooltip="Clear BI filters"
+ >
+ <IconX />
+ </Button>
+ </ButtonGroup>
+ <PopoverContent align="start">{details}</PopoverContent>
+ </Popover>
+ ) : (
+ <>
+ <LemonDropdown overlay={details} placement="bottom-start">
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={<IconFilter />}
+ className="min-w-0 rounded-r-none"
+ aria-label={`BI filter: ${summary}`}
+ >
+ <span className="max-w-64 truncate">{`BI: ${summary}`}</span>
+ </LemonButton>
+ </LemonDropdown>
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={<IconX />}
+ className="rounded-l-none border-l-0"
+ onClick={clear}
+ aria-label="Clear BI filters"
+ tooltip="Clear BI filters"
+ />
+ </>
+ )}
+ </div>
+ )
+}
diff --git a/products/business_intelligence/frontend/BIDashboardFilterStatus.tsx b/products/business_intelligence/frontend/BIDashboardFilterStatus.tsx
new file mode 100644
index 000000000000..113d72555ab6
--- /dev/null
+++ b/products/business_intelligence/frontend/BIDashboardFilterStatus.tsx
@@ -0,0 +1,44 @@
+import { useValues } from 'kea'
+
+import { LemonTag } from '@posthog/lemon-ui'
+import { Badge } from '@posthog/quill'
+
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
+
+import { biDashboardCrossFilterLogic } from './biDashboardCrossFilterLogic'
+
+export function BIDashboardFilterStatus({
+ dashboardId,
+ tileId,
+}: {
+ dashboardId: number
+ tileId: number
+}): JSX.Element | null {
+ const { selection, targets } = useValues(biDashboardCrossFilterLogic({ dashboardId }))
+ const todayRailNav = useFeatureFlag('TODAY_RAIL_NAV')
+ if (!selection) {
+ return null
+ }
+ const filtered = !!targets[tileId]
+ const isSource = selection.tileId === tileId
+ const active = filtered || isSource
+ const filterStatus = filtered ? 'filtered' : isSource ? 'source' : 'unaffected'
+ const status = filtered ? 'Filtered by selection' : isSource ? 'Filter source' : 'Not filtered'
+ return todayRailNav ? (
+ <Badge
+ className="shrink-0 whitespace-nowrap border-current"
+ variant={active ? 'info' : 'default'}
+ data-bi-filter-status={filterStatus}
+ >
+ {status}
+ </Badge>
+ ) : (
+ <LemonTag
+ className="shrink-0 whitespace-nowrap"
+ type={active ? 'info' : 'default'}
+ data-bi-filter-status={filterStatus}
+ >
+ {status}
+ </LemonTag>
+ )
+}
diff --git a/products/business_intelligence/frontend/BIDashboardTile.test.tsx b/products/business_intelligence/frontend/BIDashboardTile.test.tsx
new file mode 100644
index 000000000000..a681d9282efa
--- /dev/null
+++ b/products/business_intelligence/frontend/BIDashboardTile.test.tsx
@@ -0,0 +1,145 @@
+import '@testing-library/jest-dom'
+
+import { act, cleanup, render, screen, waitFor } from '@testing-library/react'
+
+import { InsightCard } from 'lib/components/Cards/InsightCard/InsightCard'
+
+import { useMocks } from '~/mocks/jest'
+import { BIConfig, BIVisualizationNode } from '~/queries/schema/schema-business-intelligence'
+import { HogQLQuery, NodeKind, RefreshType } from '~/queries/schema/schema-general'
+import { insightOnDashboard, tileFromInsight } from '~/scenes/dashboard/dashboardLogic.testHelpers'
+import { initKeaTests } from '~/test/init'
+import { ChartDisplayType, DashboardPlacement, DashboardTile, InsightModel, InsightShortId } from '~/types'
+
+import { biDashboardCrossFilterLogic } from './biDashboardCrossFilterLogic'
+import { BIDashboardTile } from './BIDashboardTile'
+import { buildBIQuery, DEFAULT_BI_CONFIG } from './biEditorTypes'
+
+describe('dashboard worksheet query execution', () => {
+ afterEach(cleanup)
+
+ it.each(['tile', 'card'])(
+ 'refreshes filtered results and preserves resolved filters and metadata in the %s',
+ async (surface) => {
+ const requests: { query: HogQLQuery; refresh: RefreshType }[] = []
+ const alertInsightIds: string[] = []
+ useMocks({
+ get: {
+ '/api/projects/:team_id/alerts/': ({ request }) => {
+ alertInsightIds.push(new URL(request.url).searchParams.get('insight_id')!)
+ return [200, { results: [] }]
+ },
+ },
+ post: {
+ '/api/environments/:team_id/query/:kind/': async ({ request }) => {
+ requests.push((await request.json()) as { query: HogQLQuery; refresh: RefreshType })
+ return [
+ 200,
+ { columns: ['count'], types: [['count', 'Int64']], results: [[42 * requests.length]] },
+ ]
+ },
+ },
+ })
+ initKeaTests()
+ const config: BIConfig = {
+ ...DEFAULT_BI_CONFIG,
+ source: { table: 'orders' },
+ chartType: ChartDisplayType.BoldNumber,
+ }
+ const query: BIVisualizationNode = {
+ ...buildBIQuery(config)!.node,
+ kind: NodeKind.BIVisualizationNode,
+ config,
+ }
+ query.source.filters = { dateRange: { date_from: '-30d' }, properties: [] }
+ query.source.variables = { plan: { variableId: 'plan', code_name: 'plan', value: 'pro' } }
+ const insight: InsightModel = {
+ ...insightOnDashboard(2, [777]),
+ id: 2,
+ short_id: 'target' as InsightShortId,
+ name: 'Total',
+ query,
+ columns: ['count'],
+ types: [['count', 'Int64']],
+ result: [[160]],
+ last_refresh: '2026-01-01T00:00:00Z',
+ alerts: undefined,
+ }
+ const source = tileFromInsight({ ...insight, id: 1, short_id: 'source' as InsightShortId }, 1)
+ const tiles: DashboardTile[] = [source, tileFromInsight(insight, 2)]
+ const logic = biDashboardCrossFilterLogic({ dashboardId: 777, tiles })
+ const unmount = logic.mount()
+ const original = structuredClone(insight)
+ const card = (insight: InsightModel): JSX.Element =>
+ surface === 'tile' ? (
+ <BIDashboardTile dashboardId={777} tileId={2} insight={insight} query={query} />
+ ) : (
+ <InsightCard
+ dashboardId={777}
+ biDashboardTileId={2}
+ insight={insight}
+ placement={DashboardPlacement.Dashboard}
+ renderVizWhenMounted
+ filtersOverride={{ date_from: '-7d', filterTestAccounts: true }}
+ variablesOverride={{ plan: { variableId: 'plan', code_name: 'plan', value: 'free' } }}
+ />
+ )
+ const rendered = render(card(insight))
+ try {
+ await screen.findByText('160')
+ expect(requests).toHaveLength(0)
+ if (surface === 'tile') {
+ await waitFor(() => expect(alertInsightIds).toEqual(['2']))
+ }
+ act(() =>
+ logic.actions.setSelection({
+ tileId: 1,
+ title: 'Countries',
+ source: { table: 'orders' },
+ selection: {
+ previous: false,
+ labels: [{ name: 'Country', value: 'US' }],
+ filters: [
+ {
+ field: {
+ id: 'country',
+ name: 'Country',
+ expression: 'country',
+ type: 'string',
+ source: { table: 'orders' },
+ },
+ operator: 'equals',
+ value: 'US',
+ },
+ ],
+ },
+ })
+ )
+ await screen.findByText('42')
+ expect(requests).toHaveLength(1)
+ expect(requests[0].query.query).toContain("country = 'US'")
+ expect(requests[0].query.filters).toEqual(query.source.filters)
+ expect(requests[0].query.variables).toEqual(query.source.variables)
+ const refreshedInsight = { ...insight, result: [[200]], last_refresh: '2026-01-01T00:01:00Z' }
+ act(() => {
+ biDashboardCrossFilterLogic({
+ dashboardId: 777,
+ tiles: [source, tileFromInsight(refreshedInsight, 2)],
+ })
+ })
+ rendered.rerender(card(refreshedInsight))
+ await screen.findByText('84')
+ expect(requests).toHaveLength(2)
+ expect(requests[1]).toMatchObject({ query: requests[0].query, refresh: 'force_blocking' })
+ expect(alertInsightIds.every((id) => id === '2')).toBe(true)
+ act(() => logic.actions.setSelection(null))
+ await waitFor(() => expect(screen.getByText('200')).toBeInTheDocument())
+ expect(requests).toHaveLength(2)
+ expect(insight).toEqual(original)
+ } finally {
+ rendered.unmount()
+ unmount()
+ }
+ }
+ )
+})
diff --git a/products/business_intelligence/frontend/BIDashboardTile.tsx b/products/business_intelligence/frontend/BIDashboardTile.tsx
new file mode 100644
index 000000000000..0e91321e6392
--- /dev/null
+++ b/products/business_intelligence/frontend/BIDashboardTile.tsx
@@ -0,0 +1,72 @@
+import { deepEqual } from 'fast-equals'
+import { useActions, useValues } from 'kea'
+
+import { Query } from '~/queries/Query/Query'
+import { BIVisualizationNode } from '~/queries/schema/schema-business-intelligence'
+import { InsightModel } from '~/types'
+
+import { biDashboardCrossFilterLogic } from './biDashboardCrossFilterLogic'
+import { canSelectBIWorksheet, createBIDashboardSelection, getBIDashboardItemId } from './biDashboardCrossFilters'
+import { getBIDashboardFilterLink } from './biDashboardFilterLinks'
+
+export interface BIDashboardTileProps {
+ dashboardId: number
+ tileId: number
+ insight: InsightModel
+ query: BIVisualizationNode
+ loadPriority?: number
+}
+
+export function BIDashboardTile({
+ dashboardId,
+ tileId,
+ insight,
+ query,
+ loadPriority,
+}: BIDashboardTileProps): JSX.Element {
+ const { selection, targets, loadQueue } = useValues(biDashboardCrossFilterLogic({ dashboardId }))
+ const { selectMark } = useActions(biDashboardCrossFilterLogic({ dashboardId }))
+ const filtered = targets[tileId]
+ const effectiveQuery = filtered ?? query
+ const isActiveFilter = (record: Record<string, unknown>): boolean =>
+ !!selection &&
+ deepEqual(
+ selection,
+ createBIDashboardSelection(tileId, insight.name || 'Untitled worksheet', effectiveQuery, record)
+ )
+ return (
+ <div className="flex h-full min-h-0 flex-col">
+ <Query
+ query={effectiveQuery}
+ cachedResults={filtered ? undefined : insight}
+ context={{
+ dashboardResultMenu: true,
+ loadQueue,
+ isBIMarkActiveFilter: isActiveFilter,
+ dataVisualizationTableVirtualized: true,
+ dataVisualizationTableVirtualizationCellThreshold: 100,
+ insightProps: {
+ dashboardItemId: getBIDashboardItemId(dashboardId, tileId, !!filtered),
+ cachedInsight: { ...insight, query: effectiveQuery, result: filtered ? null : insight.result },
+ query: effectiveQuery,
+ loadPriority,
+ },
+ onSelectBIMark: canSelectBIWorksheet(query)
+ ? (record) => selectMark(tileId, insight.name || 'Untitled worksheet', effectiveQuery, record)
+ : undefined,
+ getBIMarkDashboardUrl: (record) =>
+ getBIDashboardFilterLink(
+ window.location.href,
+ dashboardId,
+ tileId,
+ effectiveQuery.config,
+ record,
+ isActiveFilter(record)
+ ),
+ }}
+ readOnly
+ embedded
+ />
+ </div>
+ )
+}
diff --git a/products/business_intelligence/frontend/BIDrilldownMenu.test.tsx b/products/business_intelligence/frontend/BIDrilldownMenu.test.tsx
index 10fb7536bdd8..f81af280b21e 100644
--- a/products/business_intelligence/frontend/BIDrilldownMenu.test.tsx
+++ b/products/business_intelligence/frontend/BIDrilldownMenu.test.tsx
@@ -16,9 +16,14 @@ describe('native result-menu links', () => {
beforeEach(() => initKeaTests())
afterEach(cleanup)
- it.each([false, true])(
- 'renders real destinations without intercepting modified clicks (quill=%s)',
- async (quill) => {
+ it.each([
+ [false, false],
+ [true, false],
+ [false, true],
+ [true, true],
+ ])(
+ 'renders real destinations without intercepting modified clicks (quill=%s, filtering=%s)',
+ async (quill, filtering) => {
featureFlagLogic.actions.setFeatureFlags([], { 'today-rail-nav': quill })
const config = {
...DEFAULT_BI_CONFIG,
@@ -38,9 +43,13 @@ describe('native result-menu links', () => {
kind: NodeKind.BIVisualizationNode,
config,
}
+ const onFilterDashboard = jest.fn()
const props = {
key: 'native-links',
query,
+ onFilterDashboard: filtering ? onFilterDashboard : undefined,
+ getDashboardFilterUrl: () => '/project/1/dashboard/1#bi_filter=selection',
+ isDashboardFilterSelected: (record: Record<string, unknown>) => record.status === 'paid',
}
const logic = biDrilldownLogic(props)
const unmount = logic.mount()
@@ -49,7 +58,7 @@ describe('native result-menu links', () => {
logic.actions.inspect({ status: 'paid' })
render(<BIDrilldownMenu logicProps={props} />)
await screen.findByText('View underlying rows')
- const names = ['View underlying rows', 'Open in SQL editor']
+ const names = ['View underlying rows', 'Open in SQL editor', ...(filtering ? ['Remove filter'] : [])]
for (const name of names) {
const link = screen.getByText(name).closest('a')!
expect(link).not.toBeNull()
@@ -66,11 +75,26 @@ describe('native result-menu links', () => {
expect(screen.getAllByRole('menuitem').map((item) => item.textContent)).toEqual(names)
expect(screen.queryByText('Filter dashboard by this result')).not.toBeInTheDocument()
expect(screen.queryByText('Filter in new worksheet')).not.toBeInTheDocument()
+ if (filtering) {
+ expect(onFilterDashboard).not.toHaveBeenCalled()
+ fireEvent.click(screen.getByText('Remove filter'))
+ expect(onFilterDashboard).toHaveBeenCalledWith({ status: 'paid' })
+ expect(logic.values.record).toBeNull()
+ act(() => {
+ logic.actions.setInteraction({ x: 40, y: 40 })
+ logic.actions.inspect({ status: 'refunded' })
+ })
+ expect(screen.getByText('Filter dashboard by this result')).toBeInTheDocument()
+ }
fireEvent.click(screen.getByText('View underlying rows'))
expect(logic.values.showRows).toBe(true)
act(() => logic.actions.inspect({ count: 8 }))
- expect(screen.queryByText('Filter dashboard by this result')).not.toBeInTheDocument()
- expect(screen.getAllByRole('menuitem')).toHaveLength(2)
+ expect(screen.getAllByRole('menuitem')).toHaveLength(filtering ? 3 : 2)
+ if (filtering) {
+ act(() => logic.actions.filterDashboard())
+ expect(onFilterDashboard).toHaveBeenCalledTimes(1)
+ expect(logic.values.record).toEqual({ count: 8 })
+ }
fireEvent.keyDown(screen.getByRole('menu'), { key: 'Escape' })
expect(logic.values.record).toBeNull()
} finally {
diff --git a/products/business_intelligence/frontend/BIDrilldownMenu.tsx b/products/business_intelligence/frontend/BIDrilldownMenu.tsx
index 22d98a351fc7..4e6ee5a575b8 100644
--- a/products/business_intelligence/frontend/BIDrilldownMenu.tsx
+++ b/products/business_intelligence/frontend/BIDrilldownMenu.tsx
@@ -13,8 +13,10 @@ export function BIDrilldownMenu({
logicProps: BIDrilldownProps
triggerRef?: RefObject<HTMLDivElement>
}): JSX.Element | null {
- const { selection, queries, interaction, showRows } = useValues(biDrilldownLogic(logicProps))
- const { close, viewRows, openSqlEditor } = useActions(biDrilldownLogic(logicProps))
+ const { selection, queries, interaction, showRows, record, dashboardFilterDisabledReason } = useValues(
+ biDrilldownLogic(logicProps)
+ )
+ const { close, viewRows, openSqlEditor, filterDashboard } = useActions(biDrilldownLogic(logicProps))
if (!selection || !interaction || showRows) {
return null
}
@@ -38,6 +40,20 @@ export function BIDrilldownMenu({
},
]
+ if (logicProps.onFilterDashboard) {
+ actions.push({
+ name:
+ record && logicProps.isDashboardFilterSelected?.(record)
+ ? 'Remove filter'
+ : 'Filter dashboard by this result',
+ className: 'ResultMenu__filter',
+ disabledReason: dashboardFilterDisabledReason,
+ onClick: filterDashboard,
+ to: record && !dashboardFilterDisabledReason ? logicProps.getDashboardFilterUrl?.(record) : undefined,
+ inPlace: true,
+ })
+ }
+
return (
<ResultMenu
triggerRef={triggerRef}
diff --git a/products/business_intelligence/frontend/biDashboardCrossFilterLogic.ts b/products/business_intelligence/frontend/biDashboardCrossFilterLogic.ts
new file mode 100644
index 000000000000..672d36be9e7f
--- /dev/null
+++ b/products/business_intelligence/frontend/biDashboardCrossFilterLogic.ts
@@ -0,0 +1,239 @@
+import { deepEqual as equal } from 'fast-equals'
+import {
+ LogicWrapper,
+ MakeLogicType,
+ actions,
+ afterMount,
+ kea,
+ key,
+ listeners,
+ path,
+ props,
+ propsChanged,
+ reducers,
+ selectors,
+} from 'kea'
+import { router, urlToAction } from 'kea-router'
+
+import { lemonToast } from 'lib/lemon-ui/LemonToast'
+import type { TaskQueue } from 'scenes/dashboard/dashboardUtils'
+import { urls } from 'scenes/urls'
+
+import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
+import { insightVizDataNodeKey } from '~/queries/nodes/InsightViz/insightVizKeys'
+import { BIVisualizationNode } from '~/queries/schema/schema-business-intelligence'
+import { DashboardTile } from '~/types'
+
+import {
+ BIDashboardSelection,
+ createBIDashboardSelection,
+ getBIDashboardItemId,
+ getBIDashboardSelectionScope,
+ getBIDashboardTargets,
+ isCrossFilterWorksheet,
+} from './biDashboardCrossFilters'
+import { getBIDashboardFilterLink, readBIDashboardFilterLink } from './biDashboardFilterLinks'
+import { captureBIWorksheetAction } from './biEditorAnalytics'
+import { getBIVisualizationSource } from './biQueryResults'
+
+export interface BIDashboardCrossFilterProps {
+ dashboardId: number
+ tiles?: DashboardTile[]
+ loadQueue?: TaskQueue
+}
+
+function refreshUpdatedTiles(
+ props: BIDashboardCrossFilterProps,
+ oldProps: BIDashboardCrossFilterProps,
+ targets: Record<number, BIVisualizationNode>
+): void {
+ const previousTiles = new Map(oldProps.tiles?.map((tile) => [tile.id, tile]))
+ for (const tile of props.tiles ?? []) {
+ const target = targets[tile.id]
+ const previous = previousTiles.get(tile.id)
+ if (!target || !previous || tile.insight?.last_refresh === previous.insight?.last_refresh) {
+ continue
+ }
+ const dataLogic = dataNodeLogic.findMounted({
+ key: insightVizDataNodeKey({ dashboardItemId: getBIDashboardItemId(props.dashboardId, tile.id, true) }),
+ })
+ if (dataLogic && equal(dataLogic.props.query, getBIVisualizationSource(target))) {
+ dataLogic.actions.loadData('force_blocking')
+ }
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface biDashboardCrossFilterLogicValues {
+ loadQueue: TaskQueue | undefined
+ selection: BIDashboardSelection | null
+ sourceInsightUrl: string | undefined
+ targets: Record<number, BIVisualizationNode>
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface biDashboardCrossFilterLogicActions {
+ restoreFromUrl: () => {
+ value: true
+ }
+ selectMark: (
+ tileId: number,
+ title: string,
+ query: BIVisualizationNode,
+ record: Record<string, unknown>
+ ) => {
+ query: BIVisualizationNode
+ record: Record<string, unknown>
+ tileId: number
+ title: string
+ }
+ setSelection: (selection: BIDashboardSelection | null) => {
+ selection: BIDashboardSelection | null
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface biDashboardCrossFilterLogicMeta {
+ key: number
+ __keaTypeGenInternalSelectorTypes: {
+ loadQueue: (arg: any) => TaskQueue | undefined
+ sourceInsightUrl: (selection: BIDashboardSelection | null, arg: any) => string | undefined
+ targets: (selection: BIDashboardSelection | null, arg: any) => Record<number, BIVisualizationNode>
+ }
+}
+
+export type biDashboardCrossFilterLogicType = MakeLogicType<
+ biDashboardCrossFilterLogicValues,
+ biDashboardCrossFilterLogicActions,
+ BIDashboardCrossFilterProps,
+ biDashboardCrossFilterLogicMeta
+>
+
+export const biDashboardCrossFilterLogic: LogicWrapper<biDashboardCrossFilterLogicType> =
+ kea<biDashboardCrossFilterLogicType>([
+ props({} as BIDashboardCrossFilterProps),
+ key(({ dashboardId }) => dashboardId),
+ path((key) => ['products', 'business_intelligence', 'biDashboardCrossFilterLogic', key]),
+ actions({
+ restoreFromUrl: true,
+ setSelection: (selection: BIDashboardSelection | null) => ({ selection }),
+ selectMark: (
+ tileId: number,
+ title: string,
+ query: BIVisualizationNode,
+ record: Record<string, unknown>
+ ) => ({ tileId, title, query, record }),
+ }),
+ reducers({
+ selection: [null as BIDashboardSelection | null, { setSelection: (_, { selection }) => selection }],
+ }),
+ selectors({
+ loadQueue: [() => [(_, props) => props.loadQueue], (loadQueue: TaskQueue | undefined) => loadQueue],
+ sourceInsightUrl: [
+ (s) => [s.selection, (_, props) => props.tiles],
+ (selection: BIDashboardSelection | null, tiles: DashboardTile[] | undefined): string | undefined => {
+ const insight = tiles?.find((tile) => tile.id === selection?.tileId)?.insight
+ return insight ? urls.insightView(insight.short_id) : undefined
+ },
+ ],
+ targets: [
+ (s) => [s.selection, (_, props) => props.tiles],
+ (selection: BIDashboardSelection | null, tiles: DashboardTile[] | undefined) =>
+ getBIDashboardTargets(tiles ?? [], selection),
+ ],
+ }),
+ listeners(({ actions, values, props, cache }) => ({
+ restoreFromUrl: () => {
+ const link = readBIDashboardFilterLink(router.values.currentLocation.hashParams.bi_filter)
+ if (equal(link, cache.restoredFilterLink)) {
+ return
+ }
+ if (!link) {
+ if (cache.restoredFilterLink) {
+ actions.setSelection(null)
+ }
+ cache.restoredFilterLink = null
+ return
+ }
+ if (link.dashboardId !== props.dashboardId) {
+ return
+ }
+ const tile = props.tiles?.find(({ id }) => id === link.tileId)
+ const query = tile?.insight?.query
+ if (!tile || !isCrossFilterWorksheet(query)) {
+ return
+ }
+ cache.restoredFilterLink = link
+ actions.setSelection(
+ createBIDashboardSelection(tile.id, tile.insight?.name || 'Untitled worksheet', query, link.record)
+ )
+ },
+ setSelection: ({ selection }) => {
+ if (
+ !selection &&
+ readBIDashboardFilterLink(router.values.currentLocation.hashParams.bi_filter)?.dashboardId ===
+ props.dashboardId
+ ) {
+ const location = router.values.currentLocation
+ const hash = { ...location.hashParams }
+ delete hash.bi_filter
+ cache.restoredFilterLink = null
+ router.actions.replace(location.pathname, location.searchParams, hash)
+ }
+ },
+ selectMark: ({ tileId, title, query, record }) => {
+ const selection = createBIDashboardSelection(tileId, title, query, record)
+ if (!selection) {
+ lemonToast.info(
+ 'Choose a dimension value in the current period. Grand totals and Other are not supported.'
+ )
+ return
+ }
+ const next = equal(values.selection, selection) ? null : selection
+ actions.setSelection(next)
+ if (next) {
+ const location = router.values.currentLocation
+ const url = getBIDashboardFilterLink(
+ new URL(`${location.pathname}${location.search}${location.hash}`, window.location.origin).href,
+ props.dashboardId,
+ tileId,
+ query.config,
+ record
+ )
+ cache.restoredFilterLink = readBIDashboardFilterLink(
+ new URLSearchParams(url.split('#')[1]).get('bi_filter')
+ )
+ router.actions.replace(url)
+ }
+ captureBIWorksheetAction('dashboard_segment_selected', query.config)
+ },
+ })),
+ afterMount(({ actions }) => actions.restoreFromUrl()),
+ urlToAction(({ actions, props }) => ({
+ '/dashboard/:id': ({ id }) => {
+ if (Number(id) === props.dashboardId) {
+ actions.restoreFromUrl()
+ }
+ },
+ })),
+ propsChanged(({ props, values, actions }, oldProps) => {
+ if (props.tiles === oldProps.tiles) {
+ return
+ }
+ if (values.selection && props.tiles && oldProps.tiles) {
+ const source = props.tiles.find(({ id }) => id === values.selection!.tileId)
+ const previous = oldProps.tiles.find(({ id }) => id === values.selection!.tileId)
+ if (
+ !source ||
+ !equal(
+ getBIDashboardSelectionScope(source.insight?.query),
+ getBIDashboardSelectionScope(previous?.insight?.query)
+ )
+ ) {
+ actions.setSelection(null)
+ }
+ }
+ refreshUpdatedTiles(props, oldProps, values.targets)
+ actions.restoreFromUrl()
+ }),
+ ])
diff --git a/products/business_intelligence/frontend/biDashboardCrossFilters.test.ts b/products/business_intelligence/frontend/biDashboardCrossFilters.test.ts
new file mode 100644
index 000000000000..69f608a78e83
--- /dev/null
+++ b/products/business_intelligence/frontend/biDashboardCrossFilters.test.ts
@@ -0,0 +1,238 @@
+import { router } from 'kea-router'
+
+import { BIConfig, BIField, BIVisualizationNode } from '~/queries/schema/schema-business-intelligence'
+import { NodeKind } from '~/queries/schema/schema-general'
+import { insightOnDashboard, tileFromInsight } from '~/scenes/dashboard/dashboardLogic.testHelpers'
+import { initKeaTests } from '~/test/init'
+import { ChartDisplayType, DashboardTile } from '~/types'
+
+import { biDashboardCrossFilterLogic } from './biDashboardCrossFilterLogic'
+import { applyBIDashboardSelection, createBIDashboardSelection, getBIDashboardTargets } from './biDashboardCrossFilters'
+import { getBIDashboardFilterLink, readBIDashboardFilterLink } from './biDashboardFilterLinks'
+import { buildBIQuery, DEFAULT_BI_CONFIG, getBIResultDimensions } from './biEditorTypes'
+import { getBIVisualizationSource } from './biQueryResults'
+
+const country: BIField = {
+ id: 'country',
+ name: 'Country',
+ expression: 'country',
+ type: 'string',
+ source: { table: 'orders' },
+}
+const base: BIConfig = {
+ ...DEFAULT_BI_CONFIG,
+ source: country.source,
+ rows: [country],
+ chartType: ChartDisplayType.ActionsBar,
+}
+function worksheet(config: BIConfig = base): BIVisualizationNode {
+ return { ...buildBIQuery(config)!.node, kind: NodeKind.BIVisualizationNode, config }
+}
+function mark(query: BIVisualizationNode, value: unknown): Record<string, unknown> {
+ return { [getBIResultDimensions(query.config)[0].column]: value }
+}
+
+describe('dashboard worksheet cross filters', () => {
+ it.each(['US', null, ''])('links only the selected dimensions and restores %j after tiles load', (value) => {
+ initKeaTests()
+ const query = worksheet()
+ const url = getBIDashboardFilterLink(
+ 'http://localhost/project/1/dashboard/1?date_from=all#other=value',
+ 1,
+ 1,
+ query.config,
+ { ...mark(query, value), count: 10, unrelated: 'not part of the selection' }
+ )
+ const hash = new URLSearchParams(url.split('#')[1])
+ expect(url).toContain('?date_from=all')
+ expect(hash.get('other')).toBe('value')
+ expect(readBIDashboardFilterLink(hash.get('bi_filter'))?.record).toEqual(mark(query, value))
+ const clearedUrl = getBIDashboardFilterLink(
+ new URL(url, 'http://localhost').href,
+ 1,
+ 1,
+ query.config,
+ mark(query, value),
+ true
+ )
+ expect(clearedUrl).not.toContain('bi_filter=')
+ expect(clearedUrl).toContain('?date_from=all#other=value')
+ router.actions.push(url)
+ const logic = biDashboardCrossFilterLogic({ dashboardId: 1, tiles: [] })
+ const unmount = logic.mount()
+ try {
+ expect(logic.values.selection).toBeNull()
+ const other = biDashboardCrossFilterLogic({ dashboardId: 2 })
+ const unmountOther = other.mount()
+ other.actions.setSelection(null)
+ expect(readBIDashboardFilterLink(router.values.currentLocation.hashParams.bi_filter)?.dashboardId).toBe(1)
+ unmountOther()
+ const tiles = [1, 2].map((id) => tileFromInsight({ ...insightOnDashboard(id, [1]), query }, id))
+ biDashboardCrossFilterLogic({ dashboardId: 1, tiles })
+ expect(logic.values.selection?.selection).toEqual(
+ createBIDashboardSelection(1, '', query, mark(query, value))?.selection
+ )
+ expect(Object.keys(logic.values.targets)).toEqual(['2'])
+ logic.actions.setSelection(null)
+ expect(logic.values.selection).toBeNull()
+ expect(router.values.currentLocation.hashParams.bi_filter).toBeUndefined()
+ expect(router.values.currentLocation.hashParams.other).toBe('value')
+ } finally {
+ unmount()
+ window.history.replaceState({}, '', '/')
+ }
+ })
+
+ it.each(['bad-json', 'null', '{"dashboardId":1,"tileId":1,"record":{"status":{}}}'])(
+ 'ignores malformed result links: %s',
+ (raw) => {
+ expect(readBIDashboardFilterLink(raw)).toBeNull()
+ }
+ )
+ it.each([
+ ["Cote d'Ivoire", "country = 'Cote d\\'Ivoire'"],
+ [null, 'country IS NULL'],
+ ['', "country IN ('')"],
+ ])('adds %s before aggregation without mutating filters, variables, or presentation', (value, expression) => {
+ const target = worksheet({
+ ...base,
+ filters: [
+ { field: { ...country, id: 'existing' }, operator: 'equals', value: 'US' },
+ { field: { ...country, id: 'second' }, operator: 'equals', value: 'GB' },
+ ],
+ rowFilterGroup: { operator: 'OR', filters: ['existing', 'second'], groups: [] },
+ })
+ target.source.filters = { dateRange: { date_from: '-30d' }, filterTestAccounts: true }
+ target.source.variables = { v: { variableId: 'v', code_name: 'plan', value: 'pro' } }
+ target.chartSettings = { showLegend: false }
+ const original = structuredClone(target)
+ const active = createBIDashboardSelection(1, 'Countries', worksheet(), mark(worksheet(), value))!
+ const filtered = applyBIDashboardSelection(target, active)!
+ const sql = getBIVisualizationSource(filtered).query
+ expect(sql).toContain(expression)
+ expect(sql).toContain("(country = 'US') OR (country = 'GB')")
+ expect(sql.indexOf(expression)).toBeLessThan(sql.indexOf('GROUP BY'))
+ expect(filtered.source.filters).toEqual(target.source.filters)
+ expect(filtered.source.variables).toEqual(target.source.variables)
+ expect(filtered.chartSettings).toEqual(target.chartSettings)
+ expect(target).toEqual(original)
+ })
+
+ it('filters the source date bucket even when the target has a different grain', () => {
+ const date: BIField = { ...country, id: 'date', expression: 'timestamp', type: 'datetime', dateBucket: 'month' }
+ const source = worksheet({ ...base, rows: [date] })
+ const active = createBIDashboardSelection(1, 'Monthly', source, mark(source, '2026-01-01'))!
+ const filtered = applyBIDashboardSelection(worksheet(), active)!
+ expect(getBIVisualizationSource(filtered).query).toContain("toStartOfMonth(timestamp) = '2026-01-01'")
+ expect(filtered.config.rows).toEqual([country])
+ })
+
+ it('only targets other worksheets on the exact source and connection', () => {
+ const query = worksheet()
+ const active = createBIDashboardSelection(1, 'Countries', query, mark(query, 'US'))!
+ const tiles = [
+ { id: 1, insight: { query } },
+ { id: 2, insight: { query } },
+ { id: 3, insight: { query: { ...query, config: { ...base, source: { table: 'customers' } } } } },
+ {
+ id: 4,
+ insight: {
+ query: { ...query, config: { ...base, source: { ...base.source, connectionId: 'other' } } },
+ },
+ },
+ { id: 5, insight: { query: { ...query, config: { ...base, querySnapshot: query.source } } } },
+ { id: 6, insight: { query: { kind: NodeKind.DataVisualizationNode, source: query.source } } },
+ { id: 7, text: { body: 'Notes' } },
+ ] as DashboardTile[]
+ expect(Object.keys(getBIDashboardTargets(tiles, active))).toEqual(['2'])
+ })
+
+ it.each([
+ [{ bi_comparison: 'Previous period' }, {}, 'US'],
+ [{}, { topN: { fieldId: 'country', count: 3, measureIndex: 0, includeOther: true } }, 'Other'],
+ [{ count: 10 }, {}, undefined],
+ ])('rejects unsupported marks without silently applying a partial segment', (record, extra, value) => {
+ const query = worksheet({ ...base, ...extra })
+ expect(
+ createBIDashboardSelection(1, 'Countries', query, {
+ ...record,
+ ...(value !== undefined ? mark(query, value) : {}),
+ })
+ ).toBeNull()
+ })
+
+ it.each(['dashboard filters', 'variables', 'presentation', 'source', 'dimensions'])(
+ 'keeps selections only when their meaning survives a change to %s',
+ (change) => {
+ initKeaTests()
+ router.actions.push('/dashboard/1')
+ const query = worksheet()
+ const tiles = [1, 2].map((id) => tileFromInsight({ ...insightOnDashboard(id, [1]), query }, id))
+ const logic = biDashboardCrossFilterLogic({ dashboardId: 1, tiles })
+ const unmount = logic.mount()
+ try {
+ logic.actions.selectMark(1, 'Countries', query, mark(query, 'US'))
+ const updated: BIVisualizationNode = JSON.parse(JSON.stringify(query))
+ if (change === 'dashboard filters') {
+ updated.source.filters = { dateRange: { date_from: '-30d' }, filterTestAccounts: true }
+ } else if (change === 'variables') {
+ updated.source.variables = { plan: { variableId: 'plan', code_name: 'plan', value: 'pro' } }
+ } else if (change === 'presentation') {
+ updated.chartSettings = { showLegend: false }
+ } else if (change === 'source') {
+ updated.config.source = { table: 'customers' }
+ } else {
+ updated.config.rows = [{ ...country, expression: 'billing_country' }]
+ }
+ biDashboardCrossFilterLogic({
+ dashboardId: 1,
+ tiles: tiles.map((tile) => ({ ...tile, insight: { ...tile.insight!, query: updated } })),
+ })
+ const shouldKeep = !['source', 'dimensions'].includes(change)
+ expect(!!logic.values.selection).toBe(shouldKeep)
+ expect(!!router.values.currentLocation.hashParams.bi_filter).toBe(shouldKeep)
+ if (shouldKeep) {
+ expect(logic.values.targets[2].source.filters).toEqual(updated.source.filters)
+ expect(logic.values.targets[2].source.variables).toEqual(updated.source.variables)
+ }
+ } finally {
+ unmount()
+ }
+ }
+ )
+
+ it('toggles a selection, replaces it from another tile, clears on exit, and isolates dashboards', () => {
+ initKeaTests()
+ router.actions.push('/dashboard/1', { date_from: '-7d' }, { other: 'preserved' })
+ const originalPath = router.values.currentLocation.pathname
+ const query = worksheet()
+ const tiles = [1, 2].map((id) => tileFromInsight({ ...insightOnDashboard(id, [1]), query }, id))
+ const logic = biDashboardCrossFilterLogic({ dashboardId: 1, tiles })
+ const other = biDashboardCrossFilterLogic({ dashboardId: 2 })
+ const unmount = logic.mount()
+ const unmountOther = other.mount()
+ try {
+ logic.actions.selectMark(1, 'Countries', query, mark(query, 'US'))
+ expect(logic.values.selection?.tileId).toBe(1)
+ expect(readBIDashboardFilterLink(router.values.currentLocation.hashParams.bi_filter)?.record).toEqual(
+ mark(query, 'US')
+ )
+ expect(other.values.selection).toBeNull()
+ expect(router.values.currentLocation.pathname).toBe(originalPath)
+ expect(router.values.currentLocation.searchParams.date_from).toBe('-7d')
+ expect(router.values.currentLocation.hashParams.other).toBe('preserved')
+ logic.actions.selectMark(1, 'Countries', query, mark(query, 'US'))
+ expect(logic.values.selection).toBeNull()
+ logic.actions.selectMark(2, 'Other chart', query, mark(query, 'GB'))
+ expect(logic.values.selection?.tileId).toBe(2)
+ biDashboardCrossFilterLogic({ dashboardId: 1, tiles: [tiles[0]] })
+ expect(logic.values.selection).toBeNull()
+ logic.actions.selectMark(1, 'Countries', query, mark(query, 'US'))
+ logic.actions.setSelection(null)
+ expect(logic.values.selection).toBeNull()
+ } finally {
+ unmount()
+ unmountOther()
+ }
+ })
+})
diff --git a/products/business_intelligence/frontend/biDashboardCrossFilters.ts b/products/business_intelligence/frontend/biDashboardCrossFilters.ts
new file mode 100644
index 000000000000..0c5c3157a53c
--- /dev/null
+++ b/products/business_intelligence/frontend/biDashboardCrossFilters.ts
@@ -0,0 +1,144 @@
+import { BIConfig, BIVisualizationNode } from '~/queries/schema/schema-business-intelligence'
+import { isBIVisualizationNode } from '~/queries/utils'
+import { DashboardTile } from '~/types'
+
+import { BIDrillSelection, getBIDrillSelection } from './biDrilldown'
+import { buildBIQuery, fieldExpression, getBIDataSourceKey, getBIResultDimensions } from './biEditorTypes'
+import { isBIConditionGroup, normalizeBIConditionGroup } from './biFilterGroups'
+
+export interface BIDashboardSelection {
+ tileId: number
+ title: string
+ source: NonNullable<BIConfig['source']>
+ selection: BIDrillSelection
+}
+
+export function getBIDashboardItemId(dashboardId: number, tileId: number, filtered: boolean): `new-${string}` {
+ return `new-SQL-cross-filter-${dashboardId}-${tileId}-${filtered ? 'selection' : 'saved'}`
+}
+
+export function isCrossFilterWorksheet(query: unknown): query is BIVisualizationNode {
+ return (
+ !!query &&
+ typeof query === 'object' &&
+ isBIVisualizationNode(query as Record<string, unknown>) &&
+ !!(query as BIVisualizationNode).config.source &&
+ !(query as BIVisualizationNode).config.querySnapshot
+ )
+}
+
+export function getBIDashboardSelectionScope(query: unknown): unknown {
+ return isCrossFilterWorksheet(query)
+ ? {
+ source: query.config.source,
+ dimensions: getBIResultDimensions(query.config),
+ comparisonPeriod: query.config.comparisonPeriod,
+ topN: query.config.topN,
+ }
+ : null
+}
+
+export function createBIDashboardSelection(
+ tileId: number,
+ title: string,
+ query: BIVisualizationNode,
+ record: Record<string, unknown>
+): BIDashboardSelection | null {
+ if (!isCrossFilterWorksheet(query)) {
+ return null
+ }
+ const selection = getBIDrillSelection(query.config, record)
+ if (
+ !selection.filters.length ||
+ selection.previous ||
+ query.config.comparisonPeriod === 'previous' ||
+ selection.filters.some(
+ (filter) =>
+ filter.operator === 'custom' &&
+ filter.field.id === query.config.topN?.fieldId &&
+ query.config.topN.includeOther
+ )
+ ) {
+ return null
+ }
+ return { tileId, title, source: query.config.source!, selection }
+}
+
+export function applyBIDashboardSelection(
+ query: BIVisualizationNode,
+ active: BIDashboardSelection
+): BIVisualizationNode | null {
+ if (
+ !isCrossFilterWorksheet(query) ||
+ getBIDataSourceKey(query.config.source!) !== getBIDataSourceKey(active.source)
+ ) {
+ return null
+ }
+ const saved = query.config
+ const ids = new Set(saved.filters.map(({ field }) => field.id))
+ const filters = active.selection.filters.map((filter) => {
+ let id = `dashboard:${filter.field.id}`
+ while (ids.has(id)) {
+ id += ':'
+ }
+ ids.add(id)
+ return {
+ ...filter,
+ field: {
+ id,
+ name: filter.field.name,
+ expression: fieldExpression(filter.field),
+ type: filter.field.type,
+ source: filter.field.source,
+ },
+ }
+ })
+ const existing = normalizeBIConditionGroup(
+ saved.rowFilterGroup ?? { operator: 'AND', filters: [], groups: [] },
+ saved.filters.map(({ field }) => field.id)
+ )
+ const config: BIConfig = {
+ ...saved,
+ filters: [...saved.filters, ...filters],
+ rowFilterGroup: {
+ operator: 'AND',
+ filters: [
+ ...filters.map(({ field }) => field.id),
+ ...(existing.operator === 'AND' ? existing.filters : []),
+ ],
+ groups: existing.operator === 'AND' ? existing.groups : [existing],
+ },
+ }
+ if (!isBIConditionGroup(config.rowFilterGroup)) {
+ return null
+ }
+ const generated = buildBIQuery(config)
+ return generated ? { ...query, config, source: { ...query.source, query: generated.query } } : null
+}
+
+export function getBIDashboardTargets(
+ tiles: DashboardTile[],
+ active: BIDashboardSelection | null
+): Record<number, BIVisualizationNode> {
+ if (!active) {
+ return {}
+ }
+ return Object.fromEntries(
+ tiles.flatMap((tile) => {
+ const query = tile.insight?.query
+ if (tile.id === active.tileId || !isCrossFilterWorksheet(query)) {
+ return []
+ }
+ const filtered = applyBIDashboardSelection(query, active)
+ return filtered ? [[tile.id, filtered]] : []
+ })
+ )
+}
+
+export function canSelectBIWorksheet(query: BIVisualizationNode): boolean {
+ return (
+ isCrossFilterWorksheet(query) &&
+ query.config.comparisonPeriod !== 'previous' &&
+ getBIResultDimensions(query.config).length > 0
+ )
+}
diff --git a/products/business_intelligence/frontend/biDashboardFilterLinks.ts b/products/business_intelligence/frontend/biDashboardFilterLinks.ts
new file mode 100644
index 000000000000..49a80a58a7f8
--- /dev/null
+++ b/products/business_intelligence/frontend/biDashboardFilterLinks.ts
@@ -0,0 +1,50 @@
+import { z } from 'zod'
+
+import { BIConfig } from '~/queries/schema/schema-business-intelligence'
+
+import { getBIResultDimensions } from './biEditorTypes'
+
+const filterLinkSchema = z.object({
+ dashboardId: z.number().int().safe(),
+ tileId: z.number().int().safe(),
+ record: z.record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.null()])),
+})
+
+export type BIDashboardFilterLink = z.infer<typeof filterLinkSchema>
+
+export function readBIDashboardFilterLink(value: unknown): BIDashboardFilterLink | null {
+ try {
+ const result = filterLinkSchema.safeParse(typeof value === 'string' ? JSON.parse(value) : value)
+ return result.success ? result.data : null
+ } catch {
+ return null
+ }
+}
+
+export function getBIDashboardFilterLink(
+ currentUrl: string,
+ dashboardId: number,
+ tileId: number,
+ config: BIConfig,
+ record: Record<string, unknown>,
+ remove = false
+): string {
+ const url = new URL(currentUrl)
+ const hash = new URLSearchParams(url.hash.slice(1))
+ if (remove) {
+ hash.delete('bi_filter')
+ return `${url.pathname}${url.search}#${hash}`
+ }
+ const columns = [...getBIResultDimensions(config).map(({ column }) => column), 'bi_comparison']
+ hash.set(
+ 'bi_filter',
+ JSON.stringify({
+ dashboardId,
+ tileId,
+ record: Object.fromEntries(
+ columns.filter((column) => column in record).map((column) => [column, record[column]])
+ ),
+ })
+ )
+ return `${url.pathname}${url.search}#${hash}`
+}
diff --git a/products/business_intelligence/frontend/biDrilldownLogic.ts b/products/business_intelligence/frontend/biDrilldownLogic.ts
index d036c9f06ec5..7b46162a8074 100644
--- a/products/business_intelligence/frontend/biDrilldownLogic.ts
+++ b/products/business_intelligence/frontend/biDrilldownLogic.ts
@@ -2,6 +2,7 @@ import { MakeLogicType, actions, kea, key, path, props, reducers, selectors, lis
import { VisualizationNode, NodeKind, DashboardFilter, HogQLVariable } from '~/queries/schema/schema-general'
+import { createBIDashboardSelection } from './biDashboardCrossFilters'
import { BIDrillSelection, getBIDrillQueries, getBIDrillSelection, getBIEffectiveQuery } from './biDrilldown'
import { captureBIWorksheetAction } from './biEditorAnalytics'
import { getBIHierarchyDrills, BIHierarchyDrill } from './biHierarchies'
@@ -11,6 +12,9 @@ export interface BIDrilldownProps {
query: VisualizationNode
filtersOverride?: DashboardFilter | null
variablesOverride?: Record<string, HogQLVariable> | null
+ onFilterDashboard?: (record: Record<string, unknown>) => void
+ isDashboardFilterSelected?: (record: Record<string, unknown>) => boolean
+ getDashboardFilterUrl?: (record: Record<string, unknown>) => string
}
export interface BIDrillInteraction {
@@ -21,6 +25,7 @@ export interface BIDrillInteraction {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface biDrilldownLogicValues {
+ dashboardFilterDisabledReason: string | undefined
hierarchyDrills: BIHierarchyDrill[]
interaction: BIDrillInteraction | null
queries: ReturnType<typeof getBIDrillQueries>
@@ -35,6 +40,9 @@ export interface biDrilldownLogicActions {
close: () => {
value: true
}
+ filterDashboard: () => {
+ value: true
+ }
inspect: (record: Record<string, unknown>) => {
record: Record<string, unknown>
}
@@ -53,6 +61,10 @@ export interface biDrilldownLogicActions {
export interface biDrilldownLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
+ dashboardFilterDisabledReason: (
+ record: Record<string, unknown> | null,
+ query: VisualizationNode
+ ) => string | undefined
hierarchyDrills: (selection: BIDrillSelection | null, query: VisualizationNode) => BIHierarchyDrill[]
query: (arg: any, arg2: any, arg3: any) => VisualizationNode
selection: (record: Record<string, unknown> | null, query: VisualizationNode) => BIDrillSelection | null
@@ -75,6 +87,7 @@ export const biDrilldownLogic = kea<biDrilldownLogicType>([
inspect: (record: Record<string, unknown>) => ({ record }),
setInteraction: (interaction: BIDrillInteraction) => ({ interaction }),
openSqlEditor: true,
+ filterDashboard: true,
close: true,
viewRows: true,
}),
@@ -93,6 +106,15 @@ export const biDrilldownLogic = kea<biDrilldownLogicType>([
showRows: [false, { inspect: () => false, viewRows: () => true, close: () => false }],
}),
selectors({
+ dashboardFilterDisabledReason: [
+ (s) => [s.record, s.query],
+ (record: Record<string, unknown> | null, query: VisualizationNode): string | undefined =>
+ record &&
+ query.kind === NodeKind.BIVisualizationNode &&
+ createBIDashboardSelection(0, '', query, record)
+ ? undefined
+ : 'Choose a dimension in the current period. Grand totals and Other cannot filter a dashboard.',
+ ],
hierarchyDrills: [
(s) => [s.selection, s.query],
(selection: BIDrillSelection | null, query: VisualizationNode): BIHierarchyDrill[] =>
@@ -119,7 +141,7 @@ export const biDrilldownLogic = kea<biDrilldownLogicType>([
selection ? getBIDrillQueries(query, selection) : null,
],
}),
- listeners(({ values, actions }) => ({
+ listeners(({ values, actions, props }) => ({
inspect: () => {
if (values.query.kind === NodeKind.BIVisualizationNode && values.selection) {
captureBIWorksheetAction('drilldown_opened', values.query.config, {
@@ -127,6 +149,12 @@ export const biDrilldownLogic = kea<biDrilldownLogicType>([
})
}
},
+ filterDashboard: () => {
+ if (props.onFilterDashboard && values.record && !values.dashboardFilterDisabledReason) {
+ props.onFilterDashboard(values.record)
+ actions.close()
+ }
+ },
openSqlEditor: () => {
if (values.queries) {
if (values.query.kind === NodeKind.BIVisualizationNode) {
diff --git a/products/business_intelligence/frontend/biEditorAnalytics.ts b/products/business_intelligence/frontend/biEditorAnalytics.ts
index e8e7c13f0b3e..f6f5e2b717dc 100644
--- a/products/business_intelligence/frontend/biEditorAnalytics.ts
+++ b/products/business_intelligence/frontend/biEditorAnalytics.ts
@@ -108,6 +108,7 @@ export type BIWorksheetAction =
| 'first_chart'
| 'saved'
| 'added_to_dashboard'
+ | 'dashboard_segment_selected'
| 'drilldown_opened'
| 'underlying_rows_viewed'
| 'drilldown_worksheet_opened'