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): connect worksheet exploration controls (#117501)

Marius Andrad36877470a37
diff --git a/docs/published/handbook/engineering/data-warehouse.md b/docs/published/handbook/engineering/data-warehouse.md
index c24c1d7aa465..be67bb4d2208 100644
--- a/docs/published/handbook/engineering/data-warehouse.md
+++ b/docs/published/handbook/engineering/data-warehouse.md
@@ -46,7 +46,9 @@ Choose **Rename** from a shelf field's menu to change its worksheet label withou
**Clear sheet** clears shelves, filters, chart settings, and results while retaining the selected table, connection, date scope, and worksheet-local field definitions. Drag pills onto another pill to reorder them. **Swap rows and columns** exchanges dimensions and measure placement, preserving calculations and sort choices; bar charts switch between vertical and horizontal orientation. The **Charts** picker offers chart types suited to the selected fields.
-The **Charts** picker also includes proportion bars, scatter plots, and box plots. Scatter plots initialize numeric axes and need at least two numeric columns; box plots need six numeric summary columns.
+The **Charts** picker also includes proportion bars, scatter plots, and box plots. Scatter plots initialize numeric axes and need at least two numeric columns; box plots need six numeric summary columns. With two measures, **X measure** and **Y measure** choose the axes. Dimensions on Rows and Columns define point detail, including a dimension selected for Color. Without dimensions, the measures form one aggregate point. Category colors remain stable when results reorder, and aliases do not change category identity. Missing coordinates are omitted; logarithmic axes require positive coordinates.
+
+In the BI editor, click scatter points to toggle selection or drag a rectangle in **Select points** mode. **Keep only** adds the selected dimension tuples to worksheet filters, preserving existing AND/OR conditions; it supports up to 200 result rows. **Undo** restores the prior filters. **Zoom area** changes only the viewport; **Reset zoom** restores it. Selection controls are absent from saved/read-only and shared charts, and are unavailable while query edits are pending.
Drag the right edge of the fields pane to resize it. Docked panes each take at most a quarter of a wide worksheet, leaving at least half the width for the chart. Less frequent worksheet actions, including **Save a copy**, **Save as SQL view**, and **Discard changes**, are in the worksheet actions menu beside **Share**.
@@ -86,9 +88,9 @@ The **Marks** card offers table calculations per measure: percent of total, runn
Pivot tables display every measure beneath nested column headers. Expand or collapse a row or column header to move between hierarchy levels. Collapsed values are reaggregated from source rows, including averages and distinct counts. **Subtotals** also shows the intermediate aggregates while expanded. Row and column grand totals retain their separate controls, and total cells keep drill-down scoped to the visible dimensions. Expansion is local to the view; the worksheet's shelves and settings remain unchanged. Tracking records hierarchy expansion with axis and depth, and adds missing-date and full-window settings to the existing worksheet events.
-**Hierarchies** in the data pane names an ordered set of dimensions, such as Country → State → City. Create a hierarchy with 2–10 levels, then start it on rows or columns. Selecting a result offers **Drill to** the next level in a new worksheet, retaining filters for the selected parent values, the date range, and measures. Leaf values and levels already on a shelf do not offer another drill action; nested pivot expansion remains available for those shelves. Definitions stay with the saved worksheet and survive **Clear sheet**. **Import from worksheet** copies a hierarchy from an accessible saved worksheet using the same table and connection. The copy is independent: edits do not change the source worksheet or create global fields. Deleting a local calculated field removes its uses from hierarchy levels, dropping definitions with fewer than two remaining levels.
+**Hierarchies** in the data pane names an ordered set of dimensions, such as Country → State → City. Create a hierarchy with 2–10 levels, then start it on rows or columns. The level list marks the current field and shows the next levels. Selecting a result offers **Drill to** the next level in the current editor worksheet, retaining parent filters, date range, measures, variables, and formatting. The path above the result offers **Drill up**, removing only filters introduced by that drill. Navigation participates in undo/redo and respects Auto update. Changed or removed hierarchy levels disable an incompatible return path. Outside the editor, the action explicitly opens a new worksheet. Leaf values and levels already on a shelf do not offer another drill action; nested pivot expansion remains available for those shelves. Definitions stay with the saved worksheet and survive **Clear sheet**. **Import from worksheet** copies a hierarchy from an accessible saved worksheet using the same table and connection. The copy is independent: edits do not change the source worksheet or create global fields. Deleting a local calculated field removes its uses from hierarchy levels, dropping definitions with fewer than two remaining levels.
-The **Analysis** card ranks **Top N** categories by a selected measure across the full current date range. **Include "Other"** combines the remaining source rows and re-aggregates them, including averages and distinct counts. Removing the ranking measure turns Top N off. Previous-period comparisons use the current period's category selection. Tables offer a grand total; pivot tables offer row and column grand totals. Both support hierarchy subtotals when an axis has multiple dimensions. Totals re-aggregate source rows; table-calculation cells remain blank on total rows. Summary rows can occupy at most half the result limit, reserving room for detail cells. The BI visualization requests an extra row to determine whether more results exist, then removes it before building tables and charts. Saved SQL and exports retain the worksheet's configured limit. A notice appears only when the response confirms more results beyond that limit, which also applies across comparison periods. Cached results and execution caps may prevent the extra row from being returned.
+The **Analysis** card ranks **Top N** categories by a selected measure across the full current date range. **Include "Other"** combines the remaining source rows and re-aggregates them, including averages and distinct counts. Removing the ranking measure turns Top N off. Previous-period comparisons use the current period's category selection. Tables offer a grand total; pivot tables offer row and column grand totals. Both support hierarchy subtotals when an axis has multiple dimensions. Totals re-aggregate source rows; table-calculation cells remain blank on total rows. Summary rows can occupy at most half the result limit, reserving room for detail cells. The BI visualization requests an extra row to determine whether more results exist, then removes it before building tables and charts. Saved SQL and exports retain the worksheet's configured limit. A notice identifies confirmed extra groups. At the 50,000-row execution cap, it instead says more groups may exist because the extra-row probe cannot complete. The **Aggregated rows** limit applies after aggregation, not to scanned source rows. Limited results can make totals, rankings, running totals, and comparisons incomplete; narrow filters or increase the limit where possible.
Each measure's **Format and display** dialog sets its label, currency, decimal precision, abbreviation, percentage format, and suffix. Percentage formatting expects fractional values (0.25 displays as 25%); percent-of-total and percent-change calculations produce that scale automatically. Formats persist in saved insights and apply to charts, tables, and pivot cells. The **Charts** panel exposes series style and left/right axis selectors for each measure. Bar, line, and area charts support these mixed styles and axes. **Combine line + bar** assigns two measures to separate axes with bar and line styles.
@@ -100,16 +102,20 @@ With `SQL_EDITOR_BI_MODE` enabled, choose **Add calculated field** in the data p
Calculated fields appear in Dimensions or Measures with a ƒ indicator. Drag or double-click them to reuse the definition. Editing a definition updates its name and expression on every shelf, including duplicated uses; date granularities and measure display settings remain independent. A field's role cannot change after creation. **Delete field and all uses** removes the local definition and its shelf/filter uses; Undo restores them. Clear sheet retains the definitions. Save, reload, and Save a copy preserve them inside the worksheet, without creating source-table or project-wide fields.
-The result footer reports distinct dimension groups and non-empty measure values, rather than source-row counts. It excludes total rows and marks truncated results as limited. The grouping labels describe the executed query while edits await Run.
+The result footer reports distinct dimension groups and non-empty measure values, rather than source-row counts. It excludes total rows and marks truncated results as limited. Grouping labels and the expandable **Applied filters** summary describe the executed query while edits await Run. The summary includes source property filters carried by the executed query, retains nested AND/OR groups, separates source-row filters from post-aggregation conditions, and omits disabled or empty conditions. Missing dimension columns produce an unavailable group count and a visible warning instead of a misleading single group.
Date and timestamp drops start with daily buckets. A date pill offers **Timeline (keeps the year)** buckets and **Date part (combines years)** choices: month of year, quarter of year, and day of week. **Duplicate** creates an independently configurable shelf field, so the same date can appear at two granularities. Hold **Alt** (**Option** on Mac) while dragging a dimension or measure to copy it to another shelf or position. Copies retain calculations and settings; dropping with the modifier outside a shelf leaves the original in place.
**Charts → Series → Color** separates series coloring from shelf grouping. **Single color** preserves every group and series while using one color; switching back restores automatic or customized colors. With two categorical dimensions, select either field to define the colored series and use the other on the axis. Date dimensions remain on the timeline. Automatic uses lines for dates, grouped bars for one or two categorical dimensions, and a number for a single total. Explicit chart choices remain selected. **New worksheet** is available directly in the worksheet header.
-Worksheet member aliases apply to table cells, chart labels, legends, tooltips, and equality or membership filter descriptions. Substring conditions and range bounds display their raw operands. Queries, sorting, selection, and data exports retain raw values. Duplicate labels keep separate groups, and grouped values retain their original identities.
+**View source data** in the data pane opens a raw sample even before fields are added. Choose all source rows or rows matching worksheet row/date filters. Samples start at 1,000 rows and can grow to 10,000; result filters and table calculations do not apply. Repeated identifiers remain separate records, and a sample does not establish uniqueness. Closing the preview leaves the worksheet unchanged.
+
+Choose **Edit display aliases** from a field's menu to map individual raw values to worksheet-local labels. Search and load more values, then Save aliases or Cancel. The editor shows 50 members per page; search covers all saved aliases, and paging retains unsaved edits. Closing the editor or replacing its search cancels the outstanding value query. Clearing a label restores the raw value. Null and empty strings have separate entries; duplicate aliases retain separate groups. Aliases apply to table cells, chart labels, legends, tooltips, and equality or membership filter descriptions. Substring conditions and range bounds display their raw operands. Queries, sorting, selection, and data exports retain raw values. Aliases survive save/reopen, copies, and Clear sheet.
## Filters in BI mode
+Row and result filter editors have an independent **Filter name** with **Reset name**. A custom title changes neither the source field nor its conditions, and persists with the worksheet and undo history.
+
Drop a field onto **Row filters** above the chart. Click its pill to edit values and settings. String fields start with
**Is any of**: select several values, or type a value and press Enter. **Is none of** excludes the
selected values. An empty selection leaves all values included. Suggestions load when the picker
@@ -316,6 +322,8 @@ You'll need to install MS SQL drivers for the PostHog app to connect to a MS SQL
symbol not found in flat namespace '_bcp_batch'
```
+Scatter area selection follows legend visibility. Changing axes resets zoom, and numeric detail dimensions are available in the axis pickers. Charts with more than 100 color series, or more than one million point/series combinations, show a message asking you to reduce color cardinality or narrow filters. Pending worksheet edits must be run before drilling, and newly added scatter axes take effect after Run. Closing source preview cancels its query.
+
When groups preserve ungrouped values, named groups and original members retain distinct identities. An ungrouped member whose label matches a group is shown with “(ungrouped)”. Null member aliases also survive saves through MCP. Optional worksheet definitions restore as unset when omitted or null. Saved numeric scatter dimensions remain available as axes even when measure defaults are preferred. Scatter selections require every detail dimension to be representable as a filter; unsupported values cannot broaden a “Keep only” selection.
Repeated dimension pills use distinct result columns so their chart and table bindings stay unambiguous. Generated dimension aliases avoid source identifiers used by measures and filters. Expressions containing percent signs or matching reserved names use supported generated aliases while keeping their original calculation.
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index a17f8124925c..fb0f45a8735d 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6734,6 +6734,22 @@ snapshots:
hash: v1.k794b7964.5272d9fc095372492de4bc666a4fd7c995c2fb3de8c859a48ddbf7dae5094c8b.VCgPn7znPvjkY-Sx_PsctneSMhp8KtDuBPxFoGjYdPA
products-business-intelligence-scatter--read-only--light:
hash: v1.k794b7964.21cf4e3c6d31ac5d3653d176f876dbec5894d2569bd082e4fc5117a7dbe40af3.b-Dnoj2QTxOlUnZTMZuBqQGvSNk2lnMS0V6wnY_Aud0
+ products-business-intelligence-worksheet-exploration--daily-1500-groups--dark:
+ hash: v1.k794b7964.d08598b0c007cde5ab96ffde20d7949541f156f94f9fde229e4b114c9ad97f0c.J1EDVgjR63xWObf5gipEKPfB69hUj6AQFuUs8Hw4PhA
+ products-business-intelligence-worksheet-exploration--daily-1500-groups--light:
+ hash: v1.k794b7964.e09b60eeebdaa92a7c6b625ae5c0b17a342d88f89e7273d0bda5b0a9169a1c15.drdMw36ZHXatmOFS5ao-90666UPg9JVQCWoRDwgEoKQ
+ products-business-intelligence-worksheet-exploration--filters-and-hierarchy--dark:
+ hash: v1.k794b7964.23d21c048f1bb0a63fdb329a6a43bd4905aa5b1e00ca96494ac61b1e4c48793d.SsD_if8LTzrr_e0qegxbvD2QKfuSDmYfY3NlQJY_wq0
+ products-business-intelligence-worksheet-exploration--filters-and-hierarchy--light:
+ hash: v1.k794b7964.8c2bff687cbc922da82ba749edd32061fe5191582e8baac9ddd20b777f297fb2.EgsY3Ud8wKXl6CuNR2L55vxZb1xMvZuNvR42pxQvV8U
+ products-business-intelligence-worksheet-exploration--narrow--dark:
+ hash: v1.k794b7964.84cc0e5ededef8d70ec2afb262cc42d39b3db123a564f1e0663fcb8149793855.yV6x8wpb8M-X_eOhoABzLqsbreU-JcxiG0uERMmVt_k
+ products-business-intelligence-worksheet-exploration--narrow--light:
+ hash: v1.k794b7964.0fee0f5823ffe92065e82cbb68cf41af052ef0686f4af6983f002e14b6b7cc72.VIRLrujj_vgA_1g5UdicDqQ1qqGE4uomAIV93eW7YIk
+ products-business-intelligence-worksheet-exploration--scatter-selection--dark:
+ hash: v1.k794b7964.f9498533f26dcbda10f7e4061038e713a7325f635743eb9977bcdd7cc4a04ae0.uhcKGOmcxsxznbzt19e2cZZcN3lNE-9cSBy5VlVq0pU
+ products-business-intelligence-worksheet-exploration--scatter-selection--light:
+ hash: v1.k794b7964.2f3dee4b9e5f3f86f8d5639a380f16dfa8be646209b4a859d4476e6d2217c344.uykpvzQ3tWg2uGnQUAxfwrDNYlVHEI9zfqjWeaLCtuo
products-business-intelligence-worksheets--worksheets--dark:
hash: v1.k794b7964.3998501a45652d1982a4ae8217c905e0482c6979a4f54642cbc8739d991730ef.x5TzvSg7zyGoyTdnBYKHG__tv6ytXrmifpxCAgkyItg
products-business-intelligence-worksheets--worksheets--light:
@@ -10019,73 +10035,73 @@ snapshots:
scenes-app-data-warehouse-sql-editor--bi-calculated-measure-editor--light:
hash: v1.k794b7964.69c71d482b1b19aa18a81b5ba0fc0bb038d8f3bdc9bdb0a7286c9addb4893dc2.LjgKhmcTELX-Cd50ZnnKmKLTGxv3AH0cD5BfLrBKfQ8
scenes-app-data-warehouse-sql-editor--bi-category-groups--dark:
- hash: v1.k794b7964.93111e77e6be03e5e40918825de43ac2985b6dc34bbe295d9b137957b81d5dcb.UMChg6EYpZ7BXGmh9Tx36jNjZ6ERsNzBGlZ3dYHdnBw
+ hash: v1.k794b7964.c158c80d19a121e48585e800db84ae2125bbb8fbc9bcf0deeddfd263feec998f.JLqXfTgqdGwdzrKjQgf9jSiw9ukb40D2-YALSpZNRi0
scenes-app-data-warehouse-sql-editor--bi-category-groups--light:
- hash: v1.k794b7964.d5e34769fc378768fcf98225dd001e2cf04a6f426e626fe6556bb81397c2b170.Y6etSZ8dq76cbaCMpsCN0b0HSONai8UbCpAsOy-7rpk
+ hash: v1.k794b7964.9366d76f8b1edb1df9b9c82505f006fbf65fc270868e195836b71b3270fc5d78.Vo8WtoaxQ07wF2bqAmTQMEMojU5Y2FHlwYAMA_mlw9A
scenes-app-data-warehouse-sql-editor--bi-combined-measures--dark:
- hash: v1.k794b7964.865d4eb990b497a14f9acf245b156d6c91d564e82254d8a6ec946256a76e8057.Z5aPGxdlS-bBgCuzisWwUW1oeTf7ew3Mluhn7J4hp7s
+ hash: v1.k794b7964.039dfc5ac1a3224b1358554580f5345b074438a646e3b5605bf8e7ad8c9e7948.AjLIYjRJTdHfTNb3UhE0g4-5IBkbo23rsnbptb7S8-0
scenes-app-data-warehouse-sql-editor--bi-combined-measures--light:
- hash: v1.k794b7964.1f903572d448a00bb796711413024469b62c9530a627cdd9cb0dbfd3072e322a.iDIDaX-GAUVQH6UH8CLQR-BJC3Ticdx689vUCM6w-BY
+ hash: v1.k794b7964.582748cd75a7ea4d5422219d44a7565803c569d2b4e271672057a313b416d012.nDtqgPf06i4bncbB6Uvdp8w0LzJs2_jVJu5qR3c6g5M
scenes-app-data-warehouse-sql-editor--bi-connections--dark:
- hash: v1.k794b7964.5ead38bdfedf6a867cccf730ce512bfd81a1207816be9f43b2ff459e1f53f66a.9zBHu_GwPR2mpGP7kurhvZDOBlVzluxXwDloisx_9EA
+ hash: v1.k794b7964.caaa6e84fffcf675878f0a09bad6134ebaa6cfb50cc070c33bb3dff8b958e74a.kVdrknVYYYAU9YHXvyBR_fJY9ECIRMrQjSyQ4wPud2s
scenes-app-data-warehouse-sql-editor--bi-connections--light:
- hash: v1.k794b7964.4349a11054a4e939a512d687e6e79fe9506d06cb7fcfc6ceda1ea08a08cd8b63.CKdN-OxYRnBEd4HPoyStmcVHSgy1ap3TlfzUtSXJPG8
+ hash: v1.k794b7964.875ef03d5e6c52a24f1acee4d533f21f82dad540ab826321c9691e39318b0b07.58UiwOHnzdr3D6hzN9NiL_KBJEB9xt9EYYIhaH2p324
scenes-app-data-warehouse-sql-editor--bi-data-source-picker--dark:
- hash: v1.k794b7964.35cc2cbd62f70064133e54283675857679876c1e7a3a13d70943739cccee8d9e.P15jZlT3qKinaLh4iLp3LzXYM31LAgP_5qVI5wn3g9I
+ hash: v1.k794b7964.92b754e850177df5cc7d2b07fc9f5008d21d29563113a3f327e16eddac47af7c.C6bQoXo3G3rCtd8Pm8qd6W-sVralk-7onTQlATl4BTQ
scenes-app-data-warehouse-sql-editor--bi-data-source-picker--light:
- hash: v1.k794b7964.ce25f62f39a6e1f6c1483b8a4433bad7566425a9f1b478166ee7db2fdc51cc2e.Oy2e9QpVx03iVGhUevNI_OVQda3QFFh4FtQdo5uXH4k
+ hash: v1.k794b7964.4eeb5871a96119890608f584c6f82d59c159b69ffcf2cfb83b809d489882c989.L5Rh7rK7C-esP9pNXkAT41lvr4RO-N2R2mY7wEfRjJk
scenes-app-data-warehouse-sql-editor--bi-drilldown--dark:
- hash: v1.k794b7964.ba29aa7ee46e9d36abf42e48a05532f7a1c29e136dcd0d23e8ada1dfcdb0a309.LrxMD2ghnFj_2mufzrOvzUAeCNtrHtmygqLvHrmflY8
+ hash: v1.k794b7964.545fdaa87925013ed0dfd98d825ec9f7309e29ac368e795a32fe29b0dd5f1dad.fI7cXrNu0lm9NpAgIeZkwRnslEmbc5MwPrU7O3WDwao
scenes-app-data-warehouse-sql-editor--bi-drilldown--light:
- hash: v1.k794b7964.e43a77554e3256a78ae51ef7a04756b1178498ffe1eb66a79c5ec816af394eb7.NHelBdO8fSVLsIQQy_P8BkM9M4fccNiHOVZ-mF1UiVg
+ hash: v1.k794b7964.3221643cb9a04fe71da26820a65fa6dad19f1f080d90fc922e0f20d76bacc2e3.uKlqCiMLuLXaVz4nMUJ0vlMRQx61zEb3iQNaw6smkXA
scenes-app-data-warehouse-sql-editor--bi-edit-saved-insight--dark:
- hash: v1.k794b7964.431ec5d6290cebddae2e6501a2791f97ffb0a278546ea8c9099997e449da7fba.DjG78Z7wuA122QOFn6ZYgEV5dSHlDrsft9h5rU0_v7E
+ hash: v1.k794b7964.f36b0bf584fbbceb8bd969587fbbff7b423ae4e460313014bf2ac20f85946849.hLUzhJxWrWp5aTQt39Imx1_EXEgQVlLaClPf6iPIteE
scenes-app-data-warehouse-sql-editor--bi-edit-saved-insight--light:
- hash: v1.k794b7964.2e753a0347047d535a10a282550f93677cd32a6cf65fc04e573e44177bb70924.uL57udzKGUS_3pi_TbsrusvGgLUEgL9NJBp1hkmPUto
+ hash: v1.k794b7964.79cface1c7e2e6b5dd657a14f6d4a997cc98143d538aa377b580db832f3fdeef._aEyz2kOYYqtgaJeasZE9TTBb3cfGAIcb0wm9shlSfo
scenes-app-data-warehouse-sql-editor--bi-empty-worksheet--dark:
- hash: v1.k794b7964.cda73be4adaa1a9fe5d2b3467a11e119e43f0539e25093f778e2f8dfff397d63.SC23lgvHPbwqALOLh7NBSVUAPwYOH148bvzy3RXnhLM
+ hash: v1.k794b7964.9cdaf1b941fa6fac0d8839b4165ddd0506ce1c1ac263ae447087461a77e85a93.gXKbXKNUGG_zCLxpBvyfnmrOVGKBJj4sYQLELwogzNE
scenes-app-data-warehouse-sql-editor--bi-empty-worksheet--light:
- hash: v1.k794b7964.078f2e9f2eb8f5bab2ae1f560f3c5025c542fe523c51de8523034414daee979b.XKwLbrExUxHw1neScPMF-2MTUaTxopzeW1dXgjD8OFM
+ hash: v1.k794b7964.99ecf94f32c88b943651332b786c3ab33d4497730016ec325f279c53683bfd59.UE1Sw435eYovzC5VHT6kQceuUqT8J1rNMicQQlbSOL0
scenes-app-data-warehouse-sql-editor--bi-measure-display--dark:
- hash: v1.k794b7964.d6f28f89e3e2b5f8b69ea0da60c5e30a933c89aeaf562d7c29002c62bd7492aa.3d9FIlgXOHIH-FDFCi0T0gzNy8NKXGa7k2QZeojDluA
+ hash: v1.k794b7964.f529e2c5638d74fb5bff567fab52f54bbba11defb2c5ab4cb0c45e21d9652480.CJgpLpP8LvLhP6m2xrkg736avQ6KmDSKMiBuhKAButk
scenes-app-data-warehouse-sql-editor--bi-measure-display--light:
- hash: v1.k794b7964.21c1c02eef2de163f6f736cc24bcb6f12455d10a5dbf8afab34420d8e92b5073.qeaVWvqkqfMK1LehuauOSWguNb-vpgEMXavUidF7VPs
+ hash: v1.k794b7964.8ad1dc10c0f6fc238bf3906fbf6859952f8e3f2f0497418f81de81574e6f9c4a.0Jbt4k_doi-EDrEWhuii7dmdNvuQGg69G0dGQlhgeYI
scenes-app-data-warehouse-sql-editor--bi-mode-worksheet--dark:
hash: v1.k794b7964.6309ca3f3ecb88032969e856079e14cda460aa306a5172863693ff8a95ea011c.dIXWRHfmipDgezW97RK0MYne72aosXhe0o1S_uXrt_w
scenes-app-data-warehouse-sql-editor--bi-mode-worksheet--light:
hash: v1.k794b7964.d60ca4f154f5b6aa7dfe97f5907d32aeb07d408ef2ccfdd9b86bd8880c17ba6b.m2J3D-2Zw-ub5S6SSZk2MFZf3rAXWA6146N6UMKx2Xo
scenes-app-data-warehouse-sql-editor--bi-named-hierarchy--dark:
- hash: v1.k794b7964.772553a4fdd7f1b78561948daf275d2cd3a7d8858896efce9d3ec59f4cce0a6d.KQ5s82aUfIBfbmL7cTcEK9uVtvDiXuvpv439cpkGUV4
+ hash: v1.k794b7964.767b0c0fd033909b2a5c1b9d4e3e55677e1574aae943eddc033cde32b01b7667.rdR5M4z_-IMcPVwOMGvIPycXRN-CnJZv1mmmbxggOFk
scenes-app-data-warehouse-sql-editor--bi-named-hierarchy--light:
- hash: v1.k794b7964.7553e70c3976b08a1431cac63043fd6094da73427b6e199c26d7673fdf2a6c17.48MISiCYuPBYgYcflxFw9TEFpoQAwIY56SlQLyFCz6g
+ hash: v1.k794b7964.d6959b2e6ec22afa09a76e85d29eba63a693b9674e174fa3f9ba67b5564171c9.TPdZWIYfmaxK28hhZQIOYX3I_1XpPJtaK_jEk_6gCIQ
scenes-app-data-warehouse-sql-editor--bi-numeric-bins--dark:
- hash: v1.k794b7964.141a2d5cd4618612186479990546e28b62a678f75a16f8125ab91715b17a2c24.GBAI_3lKqJFwiq8MmFwccYxwunjhA1HtRUNiRJdcmcA
+ hash: v1.k794b7964.cabae245ff0e0d2def8041d8f927d377a0d3b058b175cc6a89660d2011b55e74.8pC3w5r2NMav84LvZJoMtgyhz6p3OawsN7T_kEXJZYw
scenes-app-data-warehouse-sql-editor--bi-numeric-bins--light:
- hash: v1.k794b7964.120de8b3789e5492ac3109cdc6eaf76114df2156b2486bff88236a060d9bece9.ZHUJRbOG3tikk_4SFDkft_ftpPa-eo4SCuqElDiDH3A
+ hash: v1.k794b7964.49f47426f598920577bcc65465da4a7f871346b90a1b8a9f1e6ea191be004624.uhKgL-k0RtQFg4FlBhduXL-O1HVVSepEVuNboEHvg_A
scenes-app-data-warehouse-sql-editor--bi-one-click-comparison--dark:
- hash: v1.k794b7964.0a3c311af93ed7d316d6e2cb90402144cdadedce0079f947eaab4247357eb9b2.t98p7S9808hEhTgDBv6qvnLeNFr2Pn3exbudMpmSdLI
+ hash: v1.k794b7964.c6b39669db3163a1446f19e827a1a19ecaba0147d6315d0c86acb7f34f120e20.mxLctVjcrANyDO_D-QE5mtOAIzwOx8ZYIQvvV_TP0hs
scenes-app-data-warehouse-sql-editor--bi-one-click-comparison--light:
- hash: v1.k794b7964.2a0b04c89ee252ec2e4f69a56fe32db2c3f4d3b9de0f9b2d4bd53e0546f4bbe6.7ebhKqs7LBZ7gy5XaehWQgzUHsixe7d8HQz_cbCudJk
+ hash: v1.k794b7964.f23d78e056b8ffbeb9864d12ed14986bded77107199d4ac8cec76f6dacd58155.qwvkjVG4ahNNXSzbgLJ3APNdN6sE92-5XlwCH75MzV0
scenes-app-data-warehouse-sql-editor--bi-pivot-totals--dark:
- hash: v1.k794b7964.a3ca1e94c408158f4ca9bedbd3d4830da8a0e574b6ae6a4275e013d2c39ceecc.9WjwLwhLcyKvBqn5-tqvl54jXwmXS5BgNIiJvSdHAaQ
+ hash: v1.k794b7964.ab316d5b27ed8e3babbeffeaf9c121ed27e17e448054ef9b92454557d3b5072f.7lAjMFoi5uIUAZDKLOmmfXWrP7kFYqOarTO-3SvtXKo
scenes-app-data-warehouse-sql-editor--bi-pivot-totals--light:
- hash: v1.k794b7964.f492de26751475f72e7b7db5c3d006552f01c821f8967aaeaa109b66757a79af.yFAwJ56fVIb8EmApSxMqpT1I7LOXmD4Gjmj4rPq5lyA
+ hash: v1.k794b7964.eb1aea6031e30bcfe43e27164ff819824d11629618fd663fa5bdde8cc9017633.jfPZq39IiqS7_BWpn_l-jnBTj9YRv3CxcGk9T8fwC9M
scenes-app-data-warehouse-sql-editor--bi-quick-filters--dark:
- hash: v1.k794b7964.b3a6ec3c1df46bbf4c92dd8d1219b12c3be1cfbcfacaeff6d552046773865fbe.2daze0fR0GNxqefe-kLOx7Wo1rheaS0kGKs8pa_xRRU
+ hash: v1.k794b7964.4d13b12b769c301fcfc7723fdef2a3e85d530d66ebf8afa42d525ba3c02f662a.DOojzPyaTHL69a5ISTCSU6JNoy7KD97_UXbNoS9mtRM
scenes-app-data-warehouse-sql-editor--bi-quick-filters--light:
- hash: v1.k794b7964.c59e2f8083c699411a9ddca1c78f872bf071f7ea9e81005936beef83e005fc63.ny9HfCoW6AkHqk4CcT35GUtfygnnMfERhtKz0PtLPk8
+ hash: v1.k794b7964.bab558516256c898c7d9e308a63ef5b589c10cc2f49d6c40cc1ef6fe8481bae8.Q5A72Pk-CB-dqEWlUnVwInDKtPV0Ux9qglovSNAQSh4
scenes-app-data-warehouse-sql-editor--bi-quick-filters-narrow--dark:
- hash: v1.k794b7964.ec5c878ebbcf2f811f27bc50775ae9f32937b7d628222e91c5ad56133a44f0b6.8QcK6drEtU4qu-RrnjPCzMConqoVnD1YbRLBSJEm_q0
+ hash: v1.k794b7964.b8c59ff0b3a26d3755c29db048ca81e146b298d141853aaa8aced566f7e6f54a.Q_V-lYTeUHqWrWUJb4N70jjm6KCpdXdpn_tNHZeinhI
scenes-app-data-warehouse-sql-editor--bi-quick-filters-narrow--light:
- hash: v1.k794b7964.4ab4e8c5bf12a2de383d658471dbc9528f697d463b58c9afe8117c1fbd0d21a4.weR6LsySZOU14958G8EIyrrH9wHrpO4LCoA5GAAabN0
+ hash: v1.k794b7964.6ab561d7058c6fcb2782b897f6cb8dc2015fa04fcd2ae9ae65409d4eab434b9b.0A1j8TXXyutI1kgB0ejINCo9XXGZwp45J3NoVg1BTtM
scenes-app-data-warehouse-sql-editor--bi-saved-insight--dark:
hash: v1.k794b7964.06df092616d217a4ebdaf0f5f35015c05fe63f5bc1e9b9c39dcdf6594293c0e3.D8zEjaefT5868HRYC8F6GkfsuMMlcxSxekM5z-VoXyM
scenes-app-data-warehouse-sql-editor--bi-saved-insight--light:
hash: v1.k794b7964.2c5f15b06d4347f767fc34bf934ea1bd53e988c443d528edb457795e778cc556.FcMHWv530RuOEcqg3G_bnos4zzZ4mku3Q9pdsK-VCXU
scenes-app-data-warehouse-sql-editor--bi-table-analysis--dark:
- hash: v1.k794b7964.9d9020314462a44cf7a9beab2a16c7011c9467ef55d8941b6a68385e194a405c.LJFs5OpOCqFp3RtfM0l4PU70-T0fdO3WB3WPJQa4bD4
+ hash: v1.k794b7964.1a6e828bdefabdc1df2bb5ea01d9a17247ae488bb1ca995505e28e70c2ccc2fd.7etXY6I03eGvxnZk0GMG_T4sSJDXbyj1DnIMhGltQJk
scenes-app-data-warehouse-sql-editor--bi-table-analysis--light:
- hash: v1.k794b7964.c3e796908cc19da75b2caa858ac3173fc0706626e69330a538c054382d62f0fb.59AQepvbMBwKgcqbCwaBNSZhT4kzuGviJDIv9FdyhCU
+ hash: v1.k794b7964.d1ec619da02c29bb935289a2b37e564d9bcd7ac12404dc5b3205514981d0cf7b.kFAFIi0y3cmT-hGNH_aQWdzrDPnHl1GglzBNbu1I6r4
scenes-app-data-warehouse-sql-editor--edited-insight--dark:
hash: v1.k794b7964.334b216a8359c768613cdec5b99a8a8ee26b6b5fac76397eaed8d6d1401a23c0.0pI7NMTufzUIfDel9Ngmhv3P3sdBu6IgpSj5xYNmYrY
scenes-app-data-warehouse-sql-editor--edited-insight--light:
diff --git a/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx b/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx
index 26788b61c944..5bad7f8f7098 100644
--- a/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx
@@ -222,7 +222,10 @@ function InternalDataTableVisualization(props: DataTableVisualizationProps): JSX
presetChartHeight: scenePresetChartHeight,
} = useValues(dataVisualizationLogic)
- const presetChartHeight = !props.embedded && scenePresetChartHeight
+ const presetChartHeight =
+ !props.embedded &&
+ scenePresetChartHeight &&
+ !(query.kind === NodeKind.BIVisualizationNode && props.context?.visualizationSettingsPanel)
const drilldownProps = {
key: dataVisualizationProps.key,
query,
@@ -404,6 +407,26 @@ function InternalDataTableVisualization(props: DataTableVisualizationProps): JSX
<StatelessInsightLoadingState queryId={queryId} pollResponse={pollResponse} />
</div>
)
+ } else if (
+ query.kind === NodeKind.BIVisualizationNode &&
+ 'results' in response &&
+ Array.isArray(response.results) &&
+ response.results.length === 0
+ ) {
+ component = (
+ <div className="flex flex-1 items-center justify-center p-4 text-secondary">
+ No results match these filters.
+ </div>
+ )
+ } else if (
+ query.kind === NodeKind.BIVisualizationNode &&
+ getBIResultDimensions(query.config).some(({ column }) => !columns.some((result) => result.name === column))
+ ) {
+ component = (
+ <LemonBanner type="warning">
+ The returned columns do not match this worksheet. Run the query again or check the selected fields.
+ </LemonBanner>
+ )
} else if (
query.kind === NodeKind.BIVisualizationNode &&
(query.config.chartType === ChartDisplayType.TwoDimensionalHeatmap ||
@@ -566,7 +589,15 @@ function InternalDataTableVisualization(props: DataTableVisualizationProps): JSX
</LemonBanner>
) : null}
{component}
- {canDrill ? <BIDrilldownModal logicProps={drilldownProps} /> : null}
+ {canDrill ? (
+ <BIDrilldownModal
+ logicProps={drilldownProps}
+ navigationDisabledReason={props.context?.biHierarchyDrillDisabledReason}
+ onNavigate={
+ props.editMode && !props.inSharedMode ? props.context?.onDrillBIHierarchy : undefined
+ }
+ />
+ ) : null}
</>
)
}
diff --git a/frontend/src/queries/types.ts b/frontend/src/queries/types.ts
index d6a939e5c645..871b1c3bdb97 100644
--- a/frontend/src/queries/types.ts
+++ b/frontend/src/queries/types.ts
@@ -15,6 +15,7 @@ import { InsightLogicProps, TrendResult } from '~/types'
import { ColumnFeature } from './nodes/DataTable/DataTable'
import { DataTableRow } from './nodes/DataTable/dataTableLogic'
+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> {
@@ -108,6 +109,8 @@ export interface QueryContext<Q extends QuerySchema = QuerySchema> {
/** Hide or resize the visualization selector when the host provides its own chart picker. */
chartTypeSelectorClassName?: string
onEditBIAxis?: (axis: 'x' | 'left' | 'right') => void
+ onDrillBIHierarchy?: (worksheet: BIVisualizationNode) => void
+ biHierarchyDrillDisabledReason?: string
onKeepBISelection?: (records: Record<string, unknown>[]) => void
/** Hosts visualization settings in the scene's own panel instead of opening another sidebar. */
visualizationSettingsPanel?: {
diff --git a/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx b/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx
index bd341d32fcae..4927bc8ee6d2 100644
--- a/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx
@@ -1530,7 +1530,13 @@ export const BINamedHierarchy: Story = {
const canvas = within(canvasElement)
await userEvent.click(await canvas.findByRole('button', { name: /^Run$/ }))
await userEvent.click(await canvas.findByText('120', { exact: true }))
- await waitFor(() => expect(within(document.body).getByRole('link', { name: 'Drill to State' })).toBeVisible())
+ await userEvent.click(
+ await within(document.body).findByRole('button', {
+ name: 'Geography: filters this worksheet to the selection',
+ })
+ )
+ await userEvent.click(await canvas.findByRole('button', { name: /^Run$/ }))
+ await waitFor(() => expect(canvas.getByText('Example state', { exact: true })).toBeVisible())
await stabilizeQueryElapsedTime()
},
}
diff --git a/products/business_intelligence/frontend/BIDataPaneField.tsx b/products/business_intelligence/frontend/BIDataPaneField.tsx
index 17e3f908c78c..aa5b2f6704e4 100644
--- a/products/business_intelligence/frontend/BIDataPaneField.tsx
+++ b/products/business_intelligence/frontend/BIDataPaneField.tsx
@@ -1,4 +1,4 @@
-import { useActions } from 'kea'
+import { useActions, useMountedLogic, useValues } from 'kea'
import { IconCalendar, IconEllipsis } from '@posthog/icons'
import { LemonButton, LemonMenu } from '@posthog/lemon-ui'
@@ -15,6 +15,9 @@ import {
isNumericBIField,
} from 'products/business_intelligence/frontend/biEditorTypes'
+import { biMemberFieldKey } from './biMemberAliases'
+import { biMemberAliasesLogic } from './biMemberAliasesLogic'
+
function FieldTypeGlyph({ field, measure }: { field: BIField; measure: boolean }): JSX.Element {
const glyph =
field.localDefinition?.kind === 'expression' ? (
@@ -51,6 +54,18 @@ export function BIDataPaneField({
measure: boolean
path?: string[]
}): JSX.Element {
+ const editor = useMountedLogic(biEditorLogic)
+ const { config } = useValues(editor)
+ const { edit } = useActions(biMemberAliasesLogic({ tabId: editor.props.tabId }))
+ const aliasItem = {
+ label: 'Edit display aliases',
+ onClick: () =>
+ edit(
+ field,
+ config.memberAliases?.find((entry) => biMemberFieldKey(entry.field) === biMemberFieldKey(field))
+ ?.aliases ?? []
+ ),
+ }
const { addFieldToShelf, editLocalField, editCalculatedField, removeLocalField } = useActions(biEditorLogic)
const addField = (field: BIField): void => {
const target = getBIDropTarget(field, 'rows')
@@ -89,6 +104,7 @@ export function BIDataPaneField({
items={
field.localDefinition?.kind === 'expression'
? [
+ aliasItem,
{ label: 'Edit calculated field', onClick: () => editCalculatedField(field) },
{
label: 'Delete field and all uses',
@@ -98,6 +114,7 @@ export function BIDataPaneField({
]
: field.localDefinition
? [
+ aliasItem,
{
label: 'Edit local definition',
onClick: () =>
@@ -108,6 +125,7 @@ export function BIDataPaneField({
},
]
: [
+ aliasItem,
{ label: 'Group categories', onClick: () => editLocalField(field, 'groups') },
...(isNumericBIField(field)
? [
@@ -124,7 +142,7 @@ export function BIDataPaneField({
size="xxsmall"
icon={<IconEllipsis />}
aria-label={`Options for ${field.name}`}
- className="shrink-0 opacity-0 group-hover/bi-field:opacity-100 focus:opacity-100"
+ className="shrink-0"
/>
</LemonMenu>
)}
diff --git a/products/business_intelligence/frontend/BIDrilldownModal.test.tsx b/products/business_intelligence/frontend/BIDrilldownModal.test.tsx
new file mode 100644
index 000000000000..a8101ac08aca
--- /dev/null
+++ b/products/business_intelligence/frontend/BIDrilldownModal.test.tsx
@@ -0,0 +1,55 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, fireEvent, render, screen } from '@testing-library/react'
+
+import { BIField, BIVisualizationNode } from '~/queries/schema/schema-business-intelligence'
+import { NodeKind } from '~/queries/schema/schema-general'
+import { initKeaTests } from '~/test/init'
+
+import { biDrilldownLogic } from './biDrilldownLogic'
+import { BIDrilldownModal } from './BIDrilldownModal'
+import { buildBIQuery, DEFAULT_BI_CONFIG, getBIResultDimensions } from './biEditorTypes'
+
+beforeEach(() => initKeaTests())
+afterEach(cleanup)
+
+it('disables hierarchy navigation while edits are pending without opening a new worksheet', () => {
+ const field = (name: string): BIField => ({
+ id: name,
+ name,
+ expression: name,
+ type: 'string',
+ source: { table: 'events' },
+ })
+ const country = field('country')
+ const config = {
+ ...DEFAULT_BI_CONFIG,
+ source: country.source,
+ rows: [country],
+ hierarchies: [{ id: 'geo', name: 'Geography', levels: [country, field('city')] }],
+ }
+ const query: BIVisualizationNode = { ...buildBIQuery(config)!.node, kind: NodeKind.BIVisualizationNode, config }
+ const props = { key: 'pending-hierarchy', query }
+ const logic = biDrilldownLogic(props)
+ const unmount = logic.mount()
+ logic.actions.inspect({ [getBIResultDimensions(config)[0].column]: 'Example country', count: 4 })
+ const navigate = jest.fn()
+ const { rerender } = render(
+ <BIDrilldownModal
+ logicProps={props}
+ onNavigate={navigate}
+ navigationDisabledReason="Run the worksheet before drilling into edited fields"
+ />
+ )
+ const drill = screen.getByText('Drill to city').closest('button')!
+ expect(drill).toHaveAttribute('aria-disabled', 'true')
+ expect(screen.getByText('Drill to city').closest('a')).toBeNull()
+ fireEvent.click(drill)
+ expect(navigate).not.toHaveBeenCalled()
+ expect(screen.getByRole('dialog')).toBeInTheDocument()
+ rerender(<BIDrilldownModal logicProps={props} onNavigate={navigate} />)
+ fireEvent.click(screen.getByText('Drill to city'))
+ expect(navigate).toHaveBeenCalledTimes(1)
+ expect(navigate.mock.calls[0][0].config.rows[0].name).toBe('city')
+ unmount()
+})
diff --git a/products/business_intelligence/frontend/BIDrilldownModal.tsx b/products/business_intelligence/frontend/BIDrilldownModal.tsx
index 24dd86ea61d1..e38da9b3ad8a 100644
--- a/products/business_intelligence/frontend/BIDrilldownModal.tsx
+++ b/products/business_intelligence/frontend/BIDrilldownModal.tsx
@@ -5,12 +5,21 @@ import { LemonBanner, LemonButton, LemonModal } from '@posthog/lemon-ui'
import { urls } from 'scenes/urls'
import { Query } from '~/queries/Query/Query'
+import { BIVisualizationNode } from '~/queries/schema/schema-business-intelligence'
import { NodeKind } from '~/queries/schema/schema-general'
import { BIDrilldownProps, biDrilldownLogic } from './biDrilldownLogic'
import { captureBIWorksheetAction } from './biEditorAnalytics'
-export function BIDrilldownModal({ logicProps: props }: { logicProps: BIDrilldownProps }): JSX.Element {
+export function BIDrilldownModal({
+ logicProps: props,
+ onNavigate,
+ navigationDisabledReason,
+}: {
+ logicProps: BIDrilldownProps
+ onNavigate?: (worksheet: BIVisualizationNode) => void
+ navigationDisabledReason?: string
+}): JSX.Element {
const { selection, queries, showRows, hierarchyDrills } = useValues(biDrilldownLogic(props))
const { close, viewRows } = useActions(biDrilldownLogic(props))
return (
@@ -35,11 +44,20 @@ export function BIDrilldownModal({ logicProps: props }: { logicProps: BIDrilldow
<LemonButton
key={hierarchy.id}
type="primary"
- to={`${urls.businessIntelligenceNew()}#q=${encodeURIComponent(JSON.stringify(worksheet))}`}
- onClick={close}
- tooltip={`${hierarchy.name}: opens a new worksheet filtered to this selection`}
+ disabledReason={navigationDisabledReason}
+ to={
+ onNavigate
+ ? undefined
+ : `${urls.businessIntelligenceNew()}#q=${encodeURIComponent(JSON.stringify(worksheet))}`
+ }
+ onClick={() => {
+ onNavigate?.(worksheet)
+ close()
+ }}
+ tooltip={`${hierarchy.name}: ${onNavigate ? 'filters this worksheet to the selection' : 'opens a new worksheet filtered to this selection'}`}
>
Drill to {next.name}
+ {onNavigate ? '' : ' in new worksheet'}
</LemonButton>
))}
<LemonButton
diff --git a/products/business_intelligence/frontend/BIHierarchySection.tsx b/products/business_intelligence/frontend/BIHierarchySection.tsx
index 489582b04f6c..43255a91f5d9 100644
--- a/products/business_intelligence/frontend/BIHierarchySection.tsx
+++ b/products/business_intelligence/frontend/BIHierarchySection.tsx
@@ -4,7 +4,7 @@ import { IconEllipsis, IconPlus } from '@posthog/icons'
import { LemonButton, LemonMenu } from '@posthog/lemon-ui'
import { biEditorLogic } from './biEditorLogic'
-import { hierarchyError } from './biHierarchies'
+import { hierarchyError, hierarchyFieldKey } from './biHierarchies'
import { BIHierarchyImportModal } from './BIHierarchyImportModal'
import { biHierarchyLogic } from './biHierarchyLogic'
import { BIHierarchyModal } from './BIHierarchyModal'
@@ -33,7 +33,7 @@ export function BIHierarchySection({ tabId }: { tabId: string }): JSX.Element {
)
)
.map((hierarchy) => (
- <div key={hierarchy.id} className="flex min-w-0 items-center gap-1">
+ <div key={hierarchy.id} className="flex min-w-0 flex-wrap items-center gap-1">
<LemonButton
size="xsmall"
className="min-w-0 flex-1"
@@ -70,6 +70,27 @@ export function BIHierarchySection({ tabId }: { tabId: string }): JSX.Element {
aria-label={`Options for hierarchy ${hierarchy.name}`}
/>
</LemonMenu>
+ <div className="w-full break-words px-2 text-xs text-secondary">
+ {hierarchy.levels
+ .map((level) =>
+ [...config.rows, ...config.columns].some(
+ (field) => hierarchyFieldKey(field) === hierarchyFieldKey(level)
+ )
+ ? `${level.name} (current)`
+ : level.name
+ )
+ .join(' → ')}
+ <div>
+ {hierarchy.levels.length > 0 &&
+ [...config.rows, ...config.columns].some(
+ (field) =>
+ hierarchyFieldKey(field) ===
+ hierarchyFieldKey(hierarchy.levels[hierarchy.levels.length - 1])
+ )
+ ? 'Last level. Use the drill path to return to a parent.'
+ : 'Click a result to drill to the next level.'}
+ </div>
+ </div>
</div>
))}
<BIHierarchyModal tabId={tabId} />
diff --git a/products/business_intelligence/frontend/BILocalFieldModal.tsx b/products/business_intelligence/frontend/BILocalFieldModal.tsx
index 4b4f63322e78..e920f60435e4 100644
--- a/products/business_intelligence/frontend/BILocalFieldModal.tsx
+++ b/products/business_intelligence/frontend/BILocalFieldModal.tsx
@@ -1,6 +1,6 @@
import { useActions, useValues } from 'kea'
-import { LemonButton, LemonInput, LemonInputSelect, LemonModal } from '@posthog/lemon-ui'
+import { LemonButton, LemonInput, LemonInputSelect, LemonModal, LemonSelect } from '@posthog/lemon-ui'
import { LemonField } from 'lib/lemon-ui/LemonField'
@@ -177,15 +177,34 @@ export function BILocalFieldModal(): JSX.Element | null {
Add group
</LemonButton>
<LemonField.Pure label="Other values">
- <LemonInput
- value={definition.other}
- onChange={(other) =>
- setLocalFieldDraft({ ...draft, localDefinition: { ...definition, other } })
+ <LemonSelect
+ value={definition.preserveUngrouped ?? false}
+ options={[
+ { value: true, label: 'Keep each ungrouped value' },
+ { value: false, label: 'Combine in Other' },
+ ]}
+ onChange={(preserveUngrouped) =>
+ setLocalFieldDraft({
+ ...draft,
+ localDefinition: { ...definition, preserveUngrouped },
+ })
}
+ data-attr="bi-group-ungrouped"
/>
+ {!definition.preserveUngrouped && (
+ <LemonInput
+ value={definition.other}
+ onChange={(other) =>
+ setLocalFieldDraft({ ...draft, localDefinition: { ...definition, other } })
+ }
+ />
+ )}
</LemonField.Pure>
<p className="m-0 text-xs text-secondary">
- Unlisted values use this label. Missing values stay missing.
+ {definition.preserveUngrouped
+ ? 'Ungrouped values keep their original labels. A group with the same label combines with that value.'
+ : 'Unlisted values use the Other label.'}{' '}
+ Missing values stay missing.
</p>
</>
)}
diff --git a/products/business_intelligence/frontend/BIResultSummary.test.tsx b/products/business_intelligence/frontend/BIResultSummary.test.tsx
new file mode 100644
index 000000000000..2b94ca5c2274
--- /dev/null
+++ b/products/business_intelligence/frontend/BIResultSummary.test.tsx
@@ -0,0 +1,71 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, render, screen } from '@testing-library/react'
+import { expectLogic } from 'kea-test-utils'
+
+import { useMocks } from '~/mocks/jest'
+import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
+import { BIVisualizationNode } from '~/queries/schema/schema-business-intelligence'
+import { NodeKind } from '~/queries/schema/schema-general'
+import { initKeaTests } from '~/test/init'
+import { PropertyFilterType, PropertyOperator } from '~/types'
+
+import { biEditorLogic } from './biEditorLogic'
+import { buildBIQuery, DEFAULT_BI_CONFIG } from './biEditorTypes'
+import { getBIVisualizationSource } from './biQueryResults'
+import { BIResultSummary } from './BIResultSummary'
+import { biSceneLogic } from './biSceneLogic'
+
+beforeEach(() => {
+ useMocks({
+ post: {
+ '/api/environments/:team_id/query/:kind/': {
+ columns: ['count'],
+ types: ['UInt64'],
+ results: [[4]],
+ tables: {},
+ },
+ },
+ })
+ initKeaTests()
+})
+afterEach(cleanup)
+
+it('shows executed source property filters even with no worksheet filters and pending edits', async () => {
+ const props = { tabId: 'property-filter-summary' }
+ const logic = biSceneLogic(props)
+ const unmount = logic.mount()
+ const config = { ...DEFAULT_BI_CONFIG, source: { table: 'events' }, dateRange: { date_from: 'all' } }
+ const query: BIVisualizationNode = { ...buildBIQuery(config)!.node, kind: NodeKind.BIVisualizationNode, config }
+ query.source.filters = {
+ dateRange: { date_from: 'all' },
+ properties: [
+ {
+ key: 'channel',
+ value: ['example-channel'],
+ type: PropertyFilterType.Event,
+ operator: PropertyOperator.Exact,
+ },
+ ],
+ }
+ logic.actions.restoreWorksheet(query)
+ biEditorLogic(props).actions.setAutoUpdate(false)
+ logic.actions.runQuery()
+ await expectLogic(logic).toFinishAllListeners()
+ const data = dataNodeLogic({
+ key: logic.values.dataNodeKey,
+ query: getBIVisualizationSource(logic.values.lastRunQuery!),
+ autoLoad: true,
+ })
+ const unmountData = data.mount()
+ await expectLogic(data).toFinishAllListeners()
+ data.actions.loadDataSuccess({ columns: ['count'], types: ['UInt64'], results: [[4]] })
+ biEditorLogic(props).actions.setDateRange({ date_from: '-7d' })
+ render(<BIResultSummary {...props} />)
+ expect(screen.getByText('Applied filters')).toBeInTheDocument()
+ expect(screen.getByText('Source property filters')).toBeInTheDocument()
+ expect(screen.getByText('channel = example-channel')).toBeInTheDocument()
+ expect(screen.queryByText(/Date range:/)).not.toBeInTheDocument()
+ unmountData()
+ unmount()
+})
diff --git a/products/business_intelligence/frontend/BIResultSummary.tsx b/products/business_intelligence/frontend/BIResultSummary.tsx
index b460142a89d3..faf1f1f5ef00 100644
--- a/products/business_intelligence/frontend/BIResultSummary.tsx
+++ b/products/business_intelligence/frontend/BIResultSummary.tsx
@@ -2,9 +2,12 @@ import { useValues } from 'kea'
import { Tooltip } from '@posthog/lemon-ui'
+import PropertyFiltersDisplay from 'lib/components/PropertyFilters/components/PropertyFiltersDisplay'
+
import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
import { getBIFieldPillLabel } from './biEditorTypes'
+import { getBIActiveFilterSummary } from './biFilterSummary'
import { getBIResultSummary, getBIVisualizationSource } from './biQueryResults'
import { biSceneLogic } from './biSceneLogic'
@@ -22,6 +25,13 @@ export function BIResultSummary({ tabId }: { tabId: string }): JSX.Element | nul
return null
}
const dimensions = [...lastRunQuery.config.rows, ...lastRunQuery.config.columns]
+ const filters = getBIActiveFilterSummary(lastRunQuery.config)
+ const sourceProperties = lastRunQuery.source.filters?.properties ?? []
+ const dateRange = lastRunQuery.source.filters?.dateRange ?? lastRunQuery.config.dateRange
+ const dateSummary =
+ dateRange && dateRange.date_from !== 'all' && (dateRange.date_from || dateRange.date_to)
+ ? `${dateRange.date_from || 'Start'} to ${dateRange.date_to || 'now'}`
+ : null
return (
<div
className="flex flex-wrap items-center gap-x-3 gap-y-1 border-t px-3 py-2 text-xs text-secondary"
@@ -29,8 +39,9 @@ export function BIResultSummary({ tabId }: { tabId: string }): JSX.Element | nul
>
<Tooltip title="Groups are distinct combinations of the worksheet dimensions. Values count non-empty measure values, including comparison periods. These are aggregated results, not source rows.">
<span>
- {summary.groups.toLocaleString()} groups · {summary.marks.toLocaleString()} values
- {summary.limited ? ' (limited)' : ''}
+ {summary.groups === null ? 'Group count unavailable' : `${summary.groups.toLocaleString()} groups`}
+ {' · '}
+ {summary.marks.toLocaleString()} values
</span>
</Tooltip>
<span className="min-w-0 break-words">
@@ -38,6 +49,32 @@ export function BIResultSummary({ tabId }: { tabId: string }): JSX.Element | nul
? `Grouped by ${dimensions.map(getBIFieldPillLabel).join(' × ')}`
: 'One group across all matching source rows'}
</span>
+ {(filters.rows || filters.results || dateSummary || sourceProperties.length > 0) && (
+ <details className="min-w-0 max-w-full basis-full" data-attr="bi-active-filter-summary">
+ <summary className="cursor-pointer">Applied filters</summary>
+ {dateSummary && <p className="my-1 break-words">Date range: {dateSummary}</p>}
+ {sourceProperties.length > 0 && (
+ <div className="my-1">
+ <p className="mb-1">Source property filters</p>
+ <PropertyFiltersDisplay filters={sourceProperties} />
+ </div>
+ )}
+ {filters.rows && <p className="my-1 break-words">Source rows: {filters.rows}</p>}
+ {filters.results && (
+ <p className="my-1 break-words">After aggregation and calculations: {filters.results}</p>
+ )}
+ </details>
+ )}
+ {(summary.limited || summary.possiblyLimited) && (
+ <span className="min-w-0 break-words text-warning" role="status">
+ {summary.limited
+ ? 'Some result groups are omitted.'
+ : 'The result cap was reached. More groups may exist.'}
+ {' Narrow the filters'}
+ {lastRunQuery.config.limit < 50000 ? ' or increase the aggregated row limit' : ''}. Totals,
+ rankings, and comparisons may be incomplete.
+ </span>
+ )}
</div>
)
}
diff --git a/products/business_intelligence/frontend/BusinessIntelligenceScene.stories.tsx b/products/business_intelligence/frontend/BusinessIntelligenceScene.stories.tsx
new file mode 100644
index 000000000000..0fbd48fa1b81
--- /dev/null
+++ b/products/business_intelligence/frontend/BusinessIntelligenceScene.stories.tsx
@@ -0,0 +1,206 @@
+import { Meta, StoryObj } from '@storybook/react'
+import { useEffect } from 'react'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+
+import { mswDecorator } from '~/mocks/browser'
+import { BIConfig, BIField, BIVisualizationNode } from '~/queries/schema/schema-business-intelligence'
+import { NodeKind } from '~/queries/schema/schema-general'
+import { ChartDisplayType, AccessControlResourceType, AccessControlLevel } from '~/types'
+
+import { buildBIQuery, getBIResultDimensions, getBIResultMeasureColumns } from './biEditorTypes'
+import { biSceneLogic } from './biSceneLogic'
+import { BusinessIntelligenceScene } from './BusinessIntelligenceScene'
+
+const field = (name: string, type: BIField['type'] = 'string'): BIField => ({
+ id: name,
+ name,
+ expression: name === 'Order date' ? '"Order date"' : name,
+ type,
+ source: { table: 'example_orders' },
+})
+const region = field('region')
+const city = field('city')
+const config: BIConfig = {
+ source: region.source,
+ chartType: ChartDisplayType.ActionsBar,
+ limit: 1000,
+ rows: [region],
+ columns: [],
+ values: [{ field: field('revenue', 'float'), aggregation: 'sum' }],
+ filters: [
+ { field: field('channel'), label: 'Sales channel', operator: 'in', values: ['direct', 'partner'], value: '' },
+ ],
+ hierarchies: [{ id: 'geography', name: 'Geography', levels: [region, city] }],
+ memberAliases: [{ field: region, aliases: [{ value: 'east', label: 'East region' }] }],
+ dateRange: { date_from: 'all' },
+}
+const tabId = 'bi-exploration-story'
+
+function WorksheetStage({ config, width = 1200 }: { config: BIConfig; width?: number }): JSX.Element {
+ useEffect(() => {
+ const logic = biSceneLogic({ tabId })
+ const unmount = logic.mount()
+ const node: BIVisualizationNode = {
+ ...buildBIQuery(config)!.node,
+ kind: NodeKind.BIVisualizationNode,
+ config,
+ }
+ logic.actions.restoreWorksheet(node)
+ logic.actions.recordWorksheet(true)
+ return unmount
+ }, [config])
+ return (
+ <div className="h-[850px] max-w-full" style={{ width }}>
+ <BusinessIntelligenceScene tabId={tabId} />
+ </div>
+ )
+}
+
+const meta: Meta = {
+ title: 'Products/Business intelligence/Worksheet exploration',
+ beforeEach: () => {
+ const context = window.POSTHOG_APP_CONTEXT!
+ const previous = context.resource_access_control
+ context.resource_access_control = {
+ ...previous,
+ [AccessControlResourceType.WarehouseObjects]: AccessControlLevel.Editor,
+ }
+ return () => {
+ context.resource_access_control = previous
+ }
+ },
+ parameters: {
+ layout: 'centered',
+ featureFlags: [FEATURE_FLAGS.SQL_EDITOR_BI_MODE],
+ testOptions: { waitForSelector: '[data-attr="bi-result-summary"]' },
+ },
+ decorators: [
+ mswDecorator({
+ get: {
+ '/api/projects/:team_id/insights/': { count: 0, results: [] },
+ '/api/projects/:team_id/warehouse_saved_queries/': { results: [] },
+ '/api/projects/:team_id/external_data_sources/connections/': [],
+ '/api/projects/:team_id/external_data_sources/direct_connection_options/': [],
+ },
+ post: {
+ '/api/environments/:team_id/query/:kind/': async ({ request }) => {
+ const { query } = (await request.json()) as {
+ query: { kind: string; query?: string; limit?: number }
+ }
+ if (query.kind === NodeKind.DatabaseSchemaQuery) {
+ const fields = [
+ region,
+ city,
+ field('channel'),
+ field('item'),
+ field('revenue', 'float'),
+ field('cost', 'float'),
+ field('Order date', 'datetime'),
+ ]
+ return [
+ 200,
+ {
+ tables: {
+ example_orders: {
+ id: 'example_orders',
+ name: 'example_orders',
+ type: 'data_warehouse',
+ fields: Object.fromEntries(
+ fields.map((field) => [
+ field.name,
+ { name: field.name, type: field.type, schema_valid: true },
+ ])
+ ),
+ },
+ },
+ },
+ ]
+ }
+ if (query.query?.includes('bi_filter_values')) {
+ return [
+ 200,
+ {
+ columns: ['value'],
+ types: [['value', 'String']],
+ results: ['east', 'west', 'north', 'south', ''].map((value) => [value]),
+ },
+ ]
+ }
+ if (query.query?.startsWith('SELECT *')) {
+ return [
+ 200,
+ {
+ columns: ['item', 'region', 'revenue', 'cost'],
+ types: [
+ ['item', 'String'],
+ ['region', 'String'],
+ ['revenue', 'Float64'],
+ ['cost', 'Float64'],
+ ],
+ results: [
+ ['Example item', 'east', 30, 12],
+ ['Example item', 'east', 20, 8],
+ ['Another item', 'west', 10, 3],
+ ],
+ },
+ ]
+ }
+ const worksheet = biSceneLogic({ tabId }).values.lastRunQuery
+ const current = worksheet?.config ?? config
+ const dimensions = getBIResultDimensions(current)
+ const measures = getBIResultMeasureColumns(current)
+ const daily = dimensions.some(({ field }) => field.dateBucket === 'day')
+ const columns = [...dimensions.map(({ column }) => column), ...measures.map(({ column }) => column)]
+ const limit = Number(query.query?.match(/LIMIT (\d+)\s*$/)?.[1] ?? 1000)
+ const results = Array.from({ length: Math.min(daily ? 1500 : 4, limit) }, (_, index) => [
+ ...dimensions.map(({ field }) =>
+ field.dateBucket === 'day'
+ ? new Date(Date.UTC(2022, 0, index + 1)).toISOString()
+ : ['east', 'west', 'north', 'south'][index % 4]
+ ),
+ ...measures.map((_, measure) => 20 + ((index * 7 + measure * 13) % 90)),
+ ])
+ return [
+ 200,
+ {
+ columns,
+ types: [
+ ...dimensions.map(({ column, field }) => [
+ column,
+ field.type === 'datetime' ? 'DateTime' : 'String',
+ ]),
+ ...measures.map(({ column }) => [column, 'Float64']),
+ ],
+ results,
+ },
+ ]
+ },
+ },
+ }),
+ ],
+}
+export default meta
+
+export const FiltersAndHierarchy: StoryObj = { render: () => <WorksheetStage config={config} /> }
+export const Narrow: StoryObj = { render: () => <WorksheetStage config={config} width={520} /> }
+const dailyConfig: BIConfig = {
+ ...config,
+ chartType: ChartDisplayType.ActionsLineGraph,
+ limit: 50000,
+ rows: [{ ...field('Order date', 'datetime'), dateBucket: 'day' }],
+ filters: [],
+}
+export const Daily1500Groups: StoryObj = { render: () => <WorksheetStage config={dailyConfig} /> }
+
+const scatterConfig: BIConfig = {
+ ...config,
+ chartType: ChartDisplayType.ScatterPlot,
+ rows: [field('item'), region],
+ values: [
+ { field: field('revenue', 'float'), aggregation: 'sum' },
+ { field: field('cost', 'float'), aggregation: 'sum' },
+ ],
+ colorBy: 'region',
+}
+export const ScatterSelection: StoryObj = { render: () => <WorksheetStage config={scatterConfig} /> }
diff --git a/products/business_intelligence/frontend/BusinessIntelligenceScene.tsx b/products/business_intelligence/frontend/BusinessIntelligenceScene.tsx
index 7403ebf55239..08af5b6784a7 100644
--- a/products/business_intelligence/frontend/BusinessIntelligenceScene.tsx
+++ b/products/business_intelligence/frontend/BusinessIntelligenceScene.tsx
@@ -21,7 +21,10 @@ import { BIChartAxis } from './BIChartAxisControls'
import { BIChartAxisModal } from './BIChartAxisModal'
import { BIEditor } from './BIEditor'
import { biEditorLogic } from './biEditorLogic'
+import { BIEditorView } from './biEditorTypes'
+import { getBIHierarchyParent } from './biHierarchies'
import { BIResultSummary } from './BIResultSummary'
+import { keepBIScatterRows } from './biScatter'
import { biSceneLogic } from './biSceneLogic'
export const scene: SceneExport = {
@@ -35,7 +38,7 @@ export const scene: SceneExport = {
export function BusinessIntelligenceScene({ tabId = 'bi-default' }: { tabId?: string }): JSX.Element {
const { featureFlags } = useValues(featureFlagLogic)
const { activePanel, dataPaneFields, dataPaneFieldsLoading } = useValues(biEditorLogic({ tabId }))
- const { setActivePanel, startSuggestedChart } = useActions(biEditorLogic({ tabId }))
+ const { setActivePanel, startSuggestedChart, restoreState, runAfterChange } = useActions(biEditorLogic({ tabId }))
const [settingsContainer, setSettingsContainer] = useState<HTMLDivElement | null>(null)
const [editingAxis, setEditingAxis] = useState<BIChartAxis | null>(null)
const logic = biSceneLogic({ tabId })
@@ -53,6 +56,7 @@ export function BusinessIntelligenceScene({ tabId = 'bi-default' }: { tabId?: st
canRedo,
copyDisabledReason,
worksheet,
+ displayedQueryIsCurrent,
} = useValues(logic)
const {
setName,
@@ -66,8 +70,11 @@ export function BusinessIntelligenceScene({ tabId = 'bi-default' }: { tabId?: st
exportView,
undo,
redo,
+ navigateHierarchy,
} = useActions(logic)
+ const hierarchyParent = getBIHierarchyParent(worksheet)
+
useKeyboardHotkeys({
z: {
willHandleEvent: true,
@@ -177,6 +184,37 @@ export function BusinessIntelligenceScene({ tabId = 'bi-default' }: { tabId?: st
</div>
) : (
<BIEditor tabId={tabId} settingsPanelRef={setSettingsContainer}>
+ {!!worksheet.config.hierarchyDrillPath?.length && (
+ <div
+ className="flex flex-wrap items-center gap-2 px-3 py-1 text-xs"
+ data-attr="bi-hierarchy-path"
+ >
+ <span>
+ {[
+ worksheet.config.hierarchyDrillPath[0].previousField.name,
+ ...worksheet.config.hierarchyDrillPath.map((step) => step.nextField.name),
+ ].join(' → ')}
+ </span>
+ <LemonButton
+ size="xsmall"
+ disabledReason={
+ !hierarchyParent ? 'The hierarchy or active field has changed' : undefined
+ }
+ onClick={() => {
+ if (hierarchyParent) {
+ navigateHierarchy(hierarchyParent)
+ }
+ }}
+ >
+ Drill up to{' '}
+ {hierarchyParent?.config.hierarchyDrillPath?.at(-1)?.nextField.name ??
+ worksheet.config.hierarchyDrillPath[0].previousField.name}
+ </LemonButton>
+ <span className="text-secondary">
+ Drill up removes only filters added by this drill.
+ </span>
+ </div>
+ )}
{lastRunQuery ? (
<Query
query={lastRunQuery}
@@ -192,6 +230,19 @@ export function BusinessIntelligenceScene({ tabId = 'bi-default' }: { tabId?: st
showOpenEditorButton: false,
chartTypeSelectorClassName: 'hidden',
onEditBIAxis: setEditingAxis,
+ onDrillBIHierarchy: (next) => navigateHierarchy(next),
+ biHierarchyDrillDisabledReason: displayedQueryIsCurrent
+ ? undefined
+ : 'Run the worksheet before drilling into edited fields',
+ onKeepBISelection: displayedQueryIsCurrent
+ ? (records) => {
+ const config = keepBIScatterRows(worksheet.config, records)
+ if (config) {
+ restoreState({ editorView: BIEditorView.BI, config })
+ runAfterChange()
+ }
+ }
+ : undefined,
visualizationSettingsPanel: {
isOpen: activePanel === 'display',
onToggle: () => setActivePanel(activePanel === 'display' ? null : 'display'),
diff --git a/products/business_intelligence/frontend/biComparisonResults.test.ts b/products/business_intelligence/frontend/biComparisonResults.test.ts
index 3b734ba49074..2e126bad76ba 100644
--- a/products/business_intelligence/frontend/biComparisonResults.test.ts
+++ b/products/business_intelligence/frontend/biComparisonResults.test.ts
@@ -6,6 +6,59 @@ import { buildBIComparisonRows, getBIComparisonValues } from './biComparisonResu
import { buildBIQuery, DEFAULT_BI_CONFIG } from './biEditorTypes'
import { getBIResultSummary, getBIVisualizationResponse } from './biQueryResults'
+it.each([0, 99, 100, 101, 50000])(
+ 'reports result limits without claiming a complete population for %s rows',
+ (count) => {
+ const config = {
+ ...DEFAULT_BI_CONFIG,
+ source: { table: 'events' },
+ limit: count === 50000 ? (50000 as const) : (100 as const),
+ rows: [
+ {
+ id: 'event',
+ name: 'event',
+ expression: 'event',
+ type: 'string' as const,
+ source: { table: 'events' },
+ },
+ ],
+ }
+ const query = { ...buildBIQuery(config)!.node, kind: NodeKind.BIVisualizationNode as const, config }
+ const response: HogQLQueryResponse = {
+ columns: ['event', 'count'],
+ types: [],
+ results: Array.from({ length: count }, (_, index) => [`item-${index}`, index === 0 ? null : 2]),
+ }
+ const summary = getBIResultSummary(query, response)!
+ expect(summary.groups).toBe(Math.min(count, config.limit))
+ expect(summary.marks).toBe(Math.max(0, Math.min(count, config.limit) - 1))
+ expect(summary.limited).toBe(count > config.limit)
+ expect(!!summary.possiblyLimited).toBe(count === 50000)
+ }
+)
+
+it('does not report one group or discard comparison rows when a dimension column is missing', () => {
+ const config = {
+ ...DEFAULT_BI_CONFIG,
+ source: { table: 'events' },
+ compareFilter: { compare: true },
+ rows: [
+ { id: 'event', name: 'event', expression: 'event', type: 'string' as const, source: { table: 'events' } },
+ ],
+ }
+ const query = { ...buildBIQuery(config)!.node, kind: NodeKind.BIVisualizationNode as const, config }
+ const response: HogQLQueryResponse = {
+ columns: ['unexpected', 'count', 'bi_comparison'],
+ types: [],
+ results: [
+ ['alpha', 3, 'Current period'],
+ ['beta', 4, 'Previous period'],
+ ],
+ }
+ expect(getBIResultSummary(query, response)).toMatchObject({ groups: null, marks: 2 })
+ expect((getBIVisualizationResponse(query, response) as HogQLQueryResponse).results).toEqual(response.results)
+})
+
it('counts groups and nonempty marks separately from source rows, excluding totals and the probe', () => {
const config = {
...DEFAULT_BI_CONFIG,
diff --git a/products/business_intelligence/frontend/biQueryResults.ts b/products/business_intelligence/frontend/biQueryResults.ts
index 5726ba4e1a09..568aa480c94f 100644
--- a/products/business_intelligence/frontend/biQueryResults.ts
+++ b/products/business_intelligence/frontend/biQueryResults.ts
@@ -14,7 +14,7 @@ export function getBISeriesSettings(query: VisualizationNode, settings: ChartAxi
export function getBIResultSummary(
query: VisualizationNode,
response: AnyResponseType | null
-): { groups: number; marks: number; limited: boolean } | null {
+): { groups: number | null; marks: number; limited: boolean; possiblyLimited?: boolean } | null {
const visible = getBIVisualizationResponse(query, response)
if (
query.kind !== NodeKind.BIVisualizationNode ||
@@ -34,12 +34,17 @@ export function getBIResultSummary(
.map(({ column }) => columns.indexOf(column))
.filter((index) => index !== -1)
return {
- groups: new Set(rows.map((row) => JSON.stringify(dimensions.map((index) => row[index])))).size,
+ groups: dimensions.some((index) => index === -1)
+ ? null
+ : new Set(rows.map((row) => JSON.stringify(dimensions.map((index) => row[index])))).size,
marks: rows.reduce(
(count, row) => count + measures.filter((index) => row[index] !== null && row[index] !== undefined).length,
0
),
limited: 'hasMore' in visible && visible.hasMore === true,
+ ...(query.config.limit === 50000 && visible.results.length >= 50000
+ ? { possiblyLimited: !('hasMore' in visible && visible.hasMore === true) }
+ : {}),
}
}
@@ -63,9 +68,17 @@ export function getBIVisualizationResponse(
) {
return response
}
+ const trimmed = {
+ ...response,
+ results: response.results.slice(0, query.config.limit),
+ hasMore: response.results.length > query.config.limit || ('hasMore' in response && response.hasMore === true),
+ }
if (query.config.compareFilter?.compare) {
const columns = 'columns' in response && Array.isArray(response.columns) ? response.columns : []
const dimensions = getBIResultDimensions(query.config).map(({ column }) => columns.indexOf(column))
+ if (dimensions.some((index) => index === -1)) {
+ return trimmed
+ }
const key = (row: unknown[]): string => JSON.stringify(dimensions.map((index) => row[index]))
const groups = new Set(response.results.map(key))
const selected = new Set([...groups].slice(0, getBIComparisonGroupLimit(query.config)))
@@ -75,9 +88,5 @@ export function getBIVisualizationResponse(
hasMore: groups.size > selected.size || ('hasMore' in response && response.hasMore === true),
}
}
- return {
- ...response,
- results: response.results.slice(0, query.config.limit),
- hasMore: response.results.length > query.config.limit || ('hasMore' in response && response.hasMore === true),
- }
+ return trimmed
}
diff --git a/products/business_intelligence/frontend/biSceneLogic.test.ts b/products/business_intelligence/frontend/biSceneLogic.test.ts
index d69b75b363a0..4cf2e847a21a 100644
--- a/products/business_intelligence/frontend/biSceneLogic.test.ts
+++ b/products/business_intelligence/frontend/biSceneLogic.test.ts
@@ -19,6 +19,7 @@ import { BI_EDITOR_EVENTS } from './biEditorAnalytics'
import { biEditorLogic } from './biEditorLogic'
import { BIEditorView, buildBIQuery } from './biEditorTypes'
import { biMemberAliasesLogic } from './biMemberAliasesLogic'
+import { getBIScatterAxisOptions } from './biScatter'
import { biSceneLogic } from './biSceneLogic'
import { biSourcePreviewLogic } from './biSourcePreviewLogic'
@@ -377,6 +378,71 @@ describe('biSceneLogic', () => {
await expectLogic(logic).toFinishAllListeners()
})
+ it.each(['x', 'y'] as const)('swaps scatter formatting and defers an unrun %s axis', async (pendingAxis) => {
+ const state = {
+ ...config,
+ chartType: ChartDisplayType.ScatterPlot,
+ rows: [{ ...eventField, type: 'integer' as const }],
+ columns: [],
+ values: [{ field: eventField, aggregation: 'count' as const }],
+ }
+ logic.actions.restoreWorksheet(worksheet(state))
+ editor.actions.setAutoUpdate(false)
+ const options = getBIScatterAxisOptions(state)
+ expect(options.map(({ value }) => value)).toEqual(['event', 'count_event'])
+ logic.actions.setChartSettings({
+ ...logic.values.worksheet.chartSettings,
+ xAxisLabel: 'Detail label',
+ leftYAxisSettings: { label: 'Measure label' },
+ xAxis: { column: 'event', settings: { formatting: { prefix: 'ID ' } } },
+ })
+ logic.actions.setScatterAxis('x', 'count_event')
+ expect(logic.values.worksheet.chartSettings).toMatchObject({
+ xAxis: { column: 'count_event' },
+ xAxisLabel: 'Measure label',
+ leftYAxisSettings: { label: 'Detail label' },
+ yAxis: [{ column: 'event', settings: { formatting: { prefix: 'ID ' } } }],
+ })
+ logic.actions.runQuery()
+ const displayed = logic.values.lastRunQuery
+ const previousOptions = new Set(getBIScatterAxisOptions(editor.values.config).map(({ value }) => value))
+ editor.actions.addFieldToShelf(
+ { ...eventField, id: 'amount', name: 'Amount', expression: 'amount', type: 'float' },
+ 'values'
+ )
+ const pendingColumn = getBIScatterAxisOptions(editor.values.config).find(
+ ({ value }) => !previousOptions.has(value)
+ )!.value
+ logic.actions.setScatterAxis(pendingAxis, pendingColumn)
+ expect(logic.values.lastRunQuery).toBe(displayed)
+ const axisColumn = (query: BIVisualizationNode): string | undefined =>
+ pendingAxis === 'x' ? query.chartSettings?.xAxis?.column : query.chartSettings?.yAxis?.[0].column
+ expect(axisColumn(logic.values.worksheet)).toBe(pendingColumn)
+ logic.actions.runQuery()
+ expect(axisColumn(logic.values.lastRunQuery!)).toBe(pendingColumn)
+ await expectLogic(logic).toFinishAllListeners()
+ })
+
+ it('requires running pending config-only edits before drilling', async () => {
+ logic.actions.restoreWorksheet(worksheet(config))
+ editor.actions.setAutoUpdate(false)
+ logic.actions.runQuery()
+ expect(logic.values.displayedQueryIsCurrent).toBe(true)
+ const previousSource = logic.values.worksheet.source
+ editor.actions.restoreState({
+ editorView: BIEditorView.BI,
+ config: {
+ ...config,
+ memberAliases: [{ field: eventField, aliases: [{ value: 'x', label: 'New label' }] }],
+ },
+ })
+ expect(logic.values.worksheet.source).toEqual(previousSource)
+ expect(logic.values.displayedQueryIsCurrent).toBe(false)
+ logic.actions.runQuery()
+ expect(logic.values.displayedQueryIsCurrent).toBe(true)
+ await expectLogic(logic).toFinishAllListeners()
+ })
+
it('cancels only the source preview query when its modal closes', () => {
const preview = biSourcePreviewLogic({ tabId: 'preview-cancel' })
preview.mount()
@@ -579,6 +645,28 @@ describe('biSceneLogic', () => {
unmount()
})
+ it('keeps hierarchy navigation pending with auto update off and records it for undo', async () => {
+ await expectLogic(logic, () => logic.actions.loadInsight(stored.short_id)).toFinishAllListeners()
+ editor.actions.setAutoUpdate(false)
+ logic.actions.setChartSettings({ ...logic.values.worksheet.chartSettings, xAxisLabel: 'Custom label' })
+ const original = logic.values.worksheet
+ const displayed = logic.values.lastRunQuery
+ const next = worksheet({
+ ...original.config,
+ filters: [{ field: eventField, operator: 'equals', value: 'example' }],
+ })
+ logic.actions.navigateHierarchy(next)
+ expect(logic.values.chartSettingsDefaults).toBeNull()
+ expect(logic.values.worksheet.config.filters).toEqual(next.config.filters)
+ expect(logic.values.lastRunQuery).toEqual(displayed)
+ logic.actions.undo()
+ expect(logic.values.worksheet.config.filters).toEqual(original.config.filters)
+ logic.actions.redo()
+ expect(logic.values.worksheet.config.filters).toEqual(next.config.filters)
+ await expectLogic(editor, () => editor.actions.setAutoUpdate(true)).toFinishAllListeners()
+ expect(logic.values.lastRunQuery?.config.filters).toEqual(next.config.filters)
+ })
+
it('runs the restored worksheet when auto update is enabled', async () => {
await expectLogic(logic, () => logic.actions.loadInsight(stored.short_id)).toFinishAllListeners()
await expectLogic(editor, () => editor.actions.setAutoUpdate(true)).toFinishAllListeners()
diff --git a/products/business_intelligence/frontend/biSceneLogic.ts b/products/business_intelligence/frontend/biSceneLogic.ts
index fd83bdbbf5db..2cac561f06c4 100644
--- a/products/business_intelligence/frontend/biSceneLogic.ts
+++ b/products/business_intelligence/frontend/biSceneLogic.ts
@@ -98,6 +98,7 @@ export interface biSceneLogicValues {
chartSettingsDefaults: ChartSettings | null
copyDisabledReason: string | undefined
dataNodeKey: string
+ displayedQueryIsCurrent: boolean
exportViewName: string
exportViewOpen: boolean
exportedView: Awaited<ReturnType<typeof warehouseSavedQueriesCreate>> | null
@@ -167,6 +168,9 @@ export interface biSceneLogicActions {
insight: InsightApi
payload?: string
}
+ navigateHierarchy: (worksheet: BIVisualizationNode) => {
+ worksheet: BIVisualizationNode
+ }
openWorksheet: () => {
value: true
}
@@ -234,6 +238,13 @@ export interface biSceneLogicActions {
setName: (name: string) => {
name: string
}
+ setScatterAxis: (
+ axis: 'x' | 'y',
+ column: string
+ ) => {
+ axis: 'x' | 'y'
+ column: string
+ }
setVisualization: (visualization: VisualizationNode) => {
visualization: VisualizationNode
}
@@ -252,6 +263,7 @@ export interface biSceneLogicActions {
export interface biSceneLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
+ displayedQueryIsCurrent: (lastRunQuery: BIVisualizationNode | null, worksheet: BIVisualizationNode) => boolean
canUndo: (history: BIWorksheetHistory) => boolean
canRedo: (history: BIWorksheetHistory) => boolean
copyDisabledReason: (generatedQuery: BIQueryBuildResult | null, name: string) => string | undefined
@@ -302,9 +314,11 @@ export const biSceneLogic: LogicWrapper<biSceneLogicType> = kea<biSceneLogicType
redo: true,
restoreHistory: true,
restoreWorksheet: (worksheet: BIVisualizationNode) => ({ worksheet }),
+ navigateHierarchy: (worksheet: BIVisualizationNode) => ({ worksheet }),
setVisualization: (visualization: VisualizationNode) => ({ visualization }),
setChartSettings: (chartSettings: ChartSettings) => ({ chartSettings }),
setChartSettingsDefaults: (defaults: ChartSettings | undefined) => ({ defaults }),
+ setScatterAxis: (axis: 'x' | 'y', column: string) => ({ axis, column }),
setName: (name: string) => ({ name }),
runQuery: true,
cancelQuery: true,
@@ -421,6 +435,7 @@ export const biSceneLogic: LogicWrapper<biSceneLogicType> = kea<biSceneLogicType
null as ChartSettings | null,
{
setChartSettingsDefaults: (_, { defaults }) => defaults ?? null,
+ navigateHierarchy: () => null,
restoreWorksheet: () => null,
setVisualization: () => null,
},
@@ -429,6 +444,7 @@ export const biSceneLogic: LogicWrapper<biSceneLogicType> = kea<biSceneLogicType
emptyWorksheet(),
{
restoreWorksheet: (_, { worksheet }) => worksheet,
+ navigateHierarchy: (_, { worksheet }) => worksheet,
setChartSettings: (state, { chartSettings }) => ({ ...state, chartSettings }),
setVisualization: (state, { visualization }) => ({
...state,
@@ -448,6 +464,13 @@ export const biSceneLogic: LogicWrapper<biSceneLogicType> = kea<biSceneLogicType
exportViewOpen: [false, { setExportViewOpen: (_, { open }) => open }],
}),
selectors({
+ displayedQueryIsCurrent: [
+ (s) => [s.lastRunQuery, s.worksheet],
+ (lastRunQuery: BIVisualizationNode | null, worksheet: BIVisualizationNode): boolean =>
+ !!lastRunQuery &&
+ equal(lastRunQuery.source, worksheet.source) &&
+ equal(lastRunQuery.config, worksheet.config),
+ ],
canUndo: [(s) => [s.history], (history: BIWorksheetHistory): boolean => history.past.length > 0],
canRedo: [(s) => [s.history], (history: BIWorksheetHistory): boolean => history.future.length > 0],
copyDisabledReason: [
@@ -557,6 +580,10 @@ export const biSceneLogic: LogicWrapper<biSceneLogicType> = kea<biSceneLogicType
}
actions.runAfterChange()
},
+ navigateHierarchy: ({ worksheet }) => {
+ actions.restoreState({ editorView: BIEditorView.BI, config: worksheet.config })
+ actions.runAfterChange()
+ },
setName: () => actions.recordWorksheet(),
[dataNodeLogic({ key: `InsightViz.new-bi-${props.tabId}`, query: emptyWorksheet().source }).actionTypes
.loadDataSuccess]: ({ response }) => {
@@ -712,12 +739,57 @@ export const biSceneLogic: LogicWrapper<biSceneLogicType> = kea<biSceneLogicType
}
},
cancelQuery: () => dataNodeLogic.findMounted({ key: values.dataNodeKey })?.actions.cancelQuery(),
+ setScatterAxis: ({ axis, column }) => {
+ const options = getBIScatterAxisOptions(values.config)
+ const option = options.find((option) => option.value === column)
+ if (!option) {
+ return
+ }
+ const settings = values.worksheet.chartSettings ?? {}
+ const previousY = settings.yAxis?.find((item) => item.column === column)
+ if (axis === 'x') {
+ const swap = previousY && settings.xAxis
+ actions.setChartSettings({
+ ...settings,
+ xAxis: previousY ?? { column },
+ xAxisLabel:
+ previousY && settings.yAxis?.length === 1
+ ? (settings.leftYAxisSettings?.label ?? option.label)
+ : option.label,
+ yAxis: swap
+ ? settings.yAxis?.map((item) => (item.column === column ? settings.xAxis! : item))
+ : settings.yAxis,
+ leftYAxisSettings: {
+ ...settings.leftYAxisSettings,
+ label:
+ swap && settings.yAxis?.length === 1
+ ? settings.xAxisLabel
+ : settings.leftYAxisSettings?.label,
+ },
+ })
+ } else if (column !== settings.xAxis?.column) {
+ actions.setChartSettings({
+ ...settings,
+ yAxis: [previousY ?? { column }],
+ leftYAxisSettings: { ...settings.leftYAxisSettings, label: option.label },
+ })
+ }
+ },
setChartSettings: ({ chartSettings }) => {
actions.setChartSettingsDefaults(
buildBIQuery(values.lastRunQuery?.config ?? values.config)?.node.chartSettings
)
if (values.lastRunQuery) {
- actions.setLastRunQuery({ ...values.lastRunQuery, chartSettings })
+ const availableColumns = new Set(
+ getBIScatterAxisOptions(values.lastRunQuery.config).map(({ value }) => value)
+ )
+ const axes = [chartSettings.xAxis, ...(chartSettings.yAxis ?? [])].filter((axis) => axis !== undefined)
+ if (
+ values.lastRunQuery.config.chartType !== ChartDisplayType.ScatterPlot ||
+ axes.every((axis) => availableColumns.has(axis.column))
+ ) {
+ actions.setLastRunQuery({ ...values.lastRunQuery, chartSettings })
+ }
}
actions.syncWorksheetUrl()
actions.recordWorksheet()
diff --git a/products/business_intelligence/frontend/components/BIDataPane.tsx b/products/business_intelligence/frontend/components/BIDataPane.tsx
index ef8e22cd6dbe..e3e26fff9e1f 100644
--- a/products/business_intelligence/frontend/components/BIDataPane.tsx
+++ b/products/business_intelligence/frontend/components/BIDataPane.tsx
@@ -9,6 +9,10 @@ import { BIDataSourcePicker } from 'products/business_intelligence/frontend/BIDa
import { biEditorLogic } from 'products/business_intelligence/frontend/biEditorLogic'
import { BIHierarchySection } from 'products/business_intelligence/frontend/BIHierarchySection'
+import { BIMemberAliasesModal } from '../BIMemberAliasesModal'
+import { biSceneLogic } from '../biSceneLogic'
+import { biSourcePreviewLogic } from '../biSourcePreviewLogic'
+import { BISourcePreviewModal } from '../BISourcePreviewModal'
import { BIConnectionSelector } from './BIConnectionSelector'
/** Lists the selected table's fields as dimensions and measures, ready to drag onto shelves. */
@@ -22,15 +26,27 @@ export function BIDataPane({ tabId }: { tabId: string }): JSX.Element {
filteredDataPaneFields,
} = useValues(biEditorLogic)
const { editCalculatedField, hydrateTableFields, setDataPaneSearch } = useActions(biEditorLogic)
+ const { worksheet } = useValues(biSceneLogic({ tabId }))
+ const { open } = useActions(biSourcePreviewLogic({ tabId }))
const hasFields = dataPaneFields.dimensions.length > 0 || dataPaneFields.measures.length > 0
const hasMatches = filteredDataPaneFields.dimensions.length > 0 || filteredDataPaneFields.measures.length > 0
return (
<div className="flex min-h-0 flex-1 flex-col">
+ <BISourcePreviewModal tabId={tabId} />
+ <BIMemberAliasesModal tabId={tabId} />
<div className="flex flex-col gap-1.5 p-2">
<BIConnectionSelector tabId={tabId} />
<BIDataSourcePicker />
+ <LemonButton
+ size="xsmall"
+ onClick={() => open(worksheet)}
+ disabledReason={!config.source ? 'Select a data source first' : undefined}
+ data-attr="bi-source-view-data"
+ >
+ View source data
+ </LemonButton>
{config.source ? (
<LemonInput
type="search"
diff --git a/products/business_intelligence/frontend/components/BIFilterEditor.tsx b/products/business_intelligence/frontend/components/BIFilterEditor.tsx
index 09f0d08cb338..da7b150c9af2 100644
--- a/products/business_intelligence/frontend/components/BIFilterEditor.tsx
+++ b/products/business_intelligence/frontend/components/BIFilterEditor.tsx
@@ -1,7 +1,7 @@
import { useActions, useValues } from 'kea'
import { IconPencil, IconX } from '@posthog/icons'
-import { LemonButton, LemonCheckbox, LemonLabel, LemonSelect } from '@posthog/lemon-ui'
+import { LemonButton, LemonCheckbox, LemonInput, LemonLabel, LemonSelect } from '@posthog/lemon-ui'
import { HogQLDropdown } from 'lib/components/HogQLDropdown/HogQLDropdown'
@@ -10,6 +10,8 @@ import { DATE_BUCKET_OPTIONS, FILTER_OPERATOR_OPTIONS } from 'products/business_
import { isDateTimeBIField, isNumericBIField } from 'products/business_intelligence/frontend/biEditorTypes'
import { BIFilterValueInput } from 'products/business_intelligence/frontend/BIFilterValueInput'
+import { getBIFilterLabel } from '../biFilterSummary'
+
export function BIFilterEditor({ index, onDone }: { index: number; onDone: () => void }): JSX.Element | null {
const { config } = useValues(biEditorLogic)
const {
@@ -40,6 +42,23 @@ export function BIFilterEditor({ index, onDone }: { index: number; onDone: () =>
onClick={onDone}
/>
</div>
+ <div className="flex flex-col gap-1">
+ <LemonLabel>Filter name</LemonLabel>
+ <LemonInput
+ value={filter.label ?? ''}
+ placeholder={getBIFilterLabel({ ...filter, label: undefined })}
+ onChange={(label) => updateFilter(index, { label })}
+ aria-label="Filter display name"
+ data-attr="bi-filter-name"
+ />
+ <LemonButton
+ size="xsmall"
+ onClick={() => updateFilter(index, { label: undefined })}
+ disabledReason={!filter.label ? 'Using the default name' : undefined}
+ >
+ Reset name
+ </LemonButton>
+ </div>
<div className="flex flex-col gap-1">
<LemonLabel>Field</LemonLabel>
<HogQLDropdown
@@ -79,7 +98,7 @@ export function BIFilterEditor({ index, onDone }: { index: number; onDone: () =>
)}
onChange={(operator) => setFilterOperator(index, operator)}
size="small"
- aria-label={`${field.name} filter condition`}
+ aria-label={`${getBIFilterLabel(filter)} filter condition`}
data-attr="bi-filter-condition"
/>
</div>
diff --git a/products/business_intelligence/frontend/components/BIFilterPill.tsx b/products/business_intelligence/frontend/components/BIFilterPill.tsx
index 47ba5e28c080..e82000e22119 100644
--- a/products/business_intelligence/frontend/components/BIFilterPill.tsx
+++ b/products/business_intelligence/frontend/components/BIFilterPill.tsx
@@ -5,15 +5,12 @@ import { LemonDropdown } from '@posthog/lemon-ui'
import { cn } from 'lib/utils/css-classes'
import { biEditorLogic } from 'products/business_intelligence/frontend/biEditorLogic'
-import {
- getBIFieldPillLabel,
- getBIFilterSummary,
- getBIFilterValidationError,
- getBIShelfEditorKey,
-} from 'products/business_intelligence/frontend/biEditorTypes'
+import { getBIFilterValidationError, getBIShelfEditorKey } from 'products/business_intelligence/frontend/biEditorTypes'
import { BIFilterEditor } from 'products/business_intelligence/frontend/components/BIFilterEditor'
import { BIPill } from 'products/business_intelligence/frontend/components/BIPill'
+import { getBIFilterLabel, describeBIFilter } from '../biFilterSummary'
+
export function BIFilterPill({ index }: { index: number }): JSX.Element | null {
const { config, activeExpressionEditorId } = useValues(biEditorLogic)
const { setActiveExpressionEditorId } = useActions(biEditorLogic)
@@ -29,7 +26,8 @@ export function BIFilterPill({ index }: { index: number }): JSX.Element | null {
setActiveExpressionEditorId(null)
}
}
- const label = getBIFieldPillLabel(filter.field)
+ const label = getBIFilterLabel(filter)
+ const description = describeBIFilter(filter, config)
return (
<LemonDropdown
@@ -42,14 +40,8 @@ export function BIFilterPill({ index }: { index: number }): JSX.Element | null {
<BIPill
kind="filter"
label={label}
- detail={
- getBIFilterValidationError(filter)
- ? 'Invalid'
- : filter.enabled === false
- ? 'Off'
- : getBIFilterSummary(filter)
- }
- title={`${label}: ${getBIFilterSummary(filter)}`}
+ detail={getBIFilterValidationError(filter) ? 'Invalid' : filter.enabled === false ? 'Off' : description}
+ title={`${label}: ${description}`}
shelf="filters"
index={index}
incomplete={!filter.field.expression.trim() && !filter.customExpression?.trim()}
diff --git a/products/business_intelligence/frontend/components/BIFiltersCard.tsx b/products/business_intelligence/frontend/components/BIFiltersCard.tsx
index fbfb843ccf29..10c7380420e7 100644
--- a/products/business_intelligence/frontend/components/BIFiltersCard.tsx
+++ b/products/business_intelligence/frontend/components/BIFiltersCard.tsx
@@ -6,7 +6,8 @@ import { LemonButton, LemonDropdown } from '@posthog/lemon-ui'
import { biEditorLogic } from 'products/business_intelligence/frontend/biEditorLogic'
-import { getBIFieldPillLabel, getBIFilterSummary } from '../biEditorTypes'
+import { getBIFilterSummary } from '../biEditorTypes'
+import { getBIFilterLabel } from '../biFilterSummary'
import { BIConditionGroups } from './BIConditionGroups'
import { BIFilterPill } from './BIFilterPill'
import { BIResultFiltersCard } from './BIResultFiltersCard'
@@ -45,7 +46,7 @@ export function BIFiltersCard(): JSX.Element {
group={config.rowFilterGroup}
options={config.filters.map((filter) => ({
value: filter.field.id,
- label: `${getBIFieldPillLabel(filter.field)}: ${getBIFilterSummary(filter)}`,
+ label: `${getBIFilterLabel(filter)}: ${getBIFilterSummary(filter)}`,
}))}
onChange={(group) => setFilterGroup('row', group)}
/>
diff --git a/products/business_intelligence/frontend/components/BIMarksCard.tsx b/products/business_intelligence/frontend/components/BIMarksCard.tsx
index f89f4806a34d..950c679086fc 100644
--- a/products/business_intelligence/frontend/components/BIMarksCard.tsx
+++ b/products/business_intelligence/frontend/components/BIMarksCard.tsx
@@ -2,25 +2,60 @@ import { useActions, useValues } from 'kea'
import { LemonButton, LemonLabel, LemonSelect } from '@posthog/lemon-ui'
+import { ChartDisplayType } from '~/types'
+
import { biEditorLogic } from 'products/business_intelligence/frontend/biEditorLogic'
import { getBIFieldPillLabel, isDateTimeBIField } from 'products/business_intelligence/frontend/biEditorTypes'
import { BIShelfCard } from 'products/business_intelligence/frontend/components/BIShelfCard'
import { BIMeasureAnalysis } from '../BIMeasureAnalysis'
+import { getBIScatterAxisOptions } from '../biScatter'
+import { biSceneLogic } from '../biSceneLogic'
export function BIMarksCard(): JSX.Element {
const { config } = useValues(biEditorLogic)
const { combineMeasures, setColorBy } = useActions(biEditorLogic)
+ const { worksheet } = useValues(biSceneLogic)
+ const { setScatterAxis } = useActions(biSceneLogic)
+ const scatter = config.chartType === ChartDisplayType.ScatterPlot
+ const measures = getBIScatterAxisOptions(config)
return (
<BIShelfCard title="Series">
+ {scatter && (
+ <>
+ <LemonLabel className="text-xs">X axis</LemonLabel>
+ <LemonSelect
+ fullWidth
+ size="xsmall"
+ value={worksheet.chartSettings?.xAxis?.column ?? ''}
+ options={measures}
+ onChange={(column) => setScatterAxis('x', column)}
+ data-attr="bi-scatter-x-measure"
+ />
+ <LemonLabel className="mt-2 text-xs">Y axis</LemonLabel>
+ <LemonSelect
+ fullWidth
+ size="xsmall"
+ value={worksheet.chartSettings?.yAxis?.[0]?.column ?? ''}
+ options={measures.filter((measure) => measure.value !== worksheet.chartSettings?.xAxis?.column)}
+ onChange={(column) => setScatterAxis('y', column)}
+ data-attr="bi-scatter-y-measure"
+ />
+ <p className="my-2 text-xs text-secondary">
+ {config.rows.length + config.columns.length
+ ? `One point per ${[...config.rows, ...config.columns].map(getBIFieldPillLabel).join(' × ')}. Add detail dimensions to Rows or Columns.`
+ : 'One point across all matching rows. Add dimensions to Rows or Columns to define point detail.'}
+ </p>
+ </>
+ )}
<LemonLabel className="mt-2 text-xs">Color</LemonLabel>
<LemonSelect
value={config.colorBy === undefined ? '__automatic' : config.colorBy}
options={[
{ value: '__automatic', label: 'Automatic colors' },
{ value: null, label: 'Single color' },
- ...(config.rows.length + config.columns.length === 2 && !config.compareFilter?.compare
+ ...((scatter || config.rows.length + config.columns.length === 2) && !config.compareFilter?.compare
? [...config.rows, ...config.columns]
.filter((field) => !isDateTimeBIField(field))
.map((field) => ({ value: field.id, label: `By ${getBIFieldPillLabel(field)}` }))
@@ -33,9 +68,11 @@ export function BIMarksCard(): JSX.Element {
data-attr="bi-editor-color-by"
/>
<span className="text-xs text-secondary">
- Shelves define the groups. Color changes how series are distinguished.
+ {scatter
+ ? 'Every shelf dimension contributes to point detail, including the color dimension.'
+ : 'Shelves define the groups. Color changes how series are distinguished.'}
</span>
- {config.values.length === 2 ? (
+ {config.values.length === 2 && !scatter ? (
<LemonButton
size="xsmall"
fullWidth
diff --git a/products/business_intelligence/frontend/components/BIResultFiltersCard.tsx b/products/business_intelligence/frontend/components/BIResultFiltersCard.tsx
index 4bcfb1956837..e675e818261f 100644
--- a/products/business_intelligence/frontend/components/BIResultFiltersCard.tsx
+++ b/products/business_intelligence/frontend/components/BIResultFiltersCard.tsx
@@ -6,6 +6,7 @@ import { BIResultFilter } from '~/queries/schema/schema-business-intelligence'
import { biEditorLogic } from '../biEditorLogic'
import { getBIResultFilterValidationError, getBIValuePillLabel } from '../biEditorTypes'
+import { getBIResultFilterLabel } from '../biFilterSummary'
import { BIConditionGroups } from './BIConditionGroups'
import { BIShelfCard } from './BIShelfCard'
@@ -27,6 +28,20 @@ function ResultFilterEditor({ filter }: { filter: BIResultFilter }): JSX.Element
const error = getBIResultFilterValidationError(config, filter)
return (
<div className="flex w-64 max-w-full flex-col gap-2 p-2">
+ <LemonInput
+ value={filter.label ?? ''}
+ placeholder={getBIResultFilterLabel(config, { ...filter, label: undefined })}
+ onChange={(label) => updateResultFilter(filter.id, { label })}
+ aria-label="Result filter display name"
+ data-attr="bi-result-filter-name"
+ />
+ <LemonButton
+ size="xsmall"
+ onClick={() => updateResultFilter(filter.id, { label: undefined })}
+ disabledReason={!filter.label ? 'Using the default name' : undefined}
+ >
+ Reset name
+ </LemonButton>
<LemonCheckbox
label="Apply result filter"
labelClassName="text-xs"
@@ -87,7 +102,7 @@ export function BIResultFiltersCard(): JSX.Element {
const { config } = useValues(biEditorLogic)
const { addResultFilter, setFilterGroup } = useActions(biEditorLogic)
const label = (filter: BIResultFilter): string =>
- `${config.values[filter.measureIndex] ? getBIValuePillLabel(config.values[filter.measureIndex]) : 'Count'} ${OPERATORS.find((operator) => operator.value === filter.operator)?.label.toLowerCase()} ${filter.value}${filter.operator === 'between' ? ` and ${filter.valueTo ?? ''}` : ''}`
+ `${getBIResultFilterLabel(config, filter)} ${OPERATORS.find((operator) => operator.value === filter.operator)?.label.toLowerCase()} ${filter.value}${filter.operator === 'between' ? ` and ${filter.valueTo ?? ''}` : ''}`
return (
<BIShelfCard title="Result filters">
<p className="mb-1 text-xs text-secondary">Filter measures after aggregation and table calculations.</p>
diff --git a/products/business_intelligence/frontend/components/BIToolbar.tsx b/products/business_intelligence/frontend/components/BIToolbar.tsx
index 18952a8939ad..34640c285c60 100644
--- a/products/business_intelligence/frontend/components/BIToolbar.tsx
+++ b/products/business_intelligence/frontend/components/BIToolbar.tsx
@@ -128,8 +128,8 @@ export function BIToolbar(): JSX.Element {
value={config.limit}
options={LIMIT_OPTIONS}
onChange={setLimit}
- renderButtonContent={(option) => `Limit: ${option?.label ?? config.limit}`}
- aria-label="Query row limit"
+ renderButtonContent={(option) => `Aggregated rows: ${option?.label ?? config.limit}`}
+ aria-label="Aggregated result row limit"
tooltip="Maximum aggregated result rows, after grouping and calculations. This does not limit the source rows read."
size="xsmall"
type="tertiary"