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.

fix(bi): preserve worksheet context during exploration (#115500)

Marius Andra23b1a724c944
diff --git a/docs/published/handbook/engineering/data-warehouse.md b/docs/published/handbook/engineering/data-warehouse.md
index 23eca5c74131..550c265b00a4 100644
--- a/docs/published/handbook/engineering/data-warehouse.md
+++ b/docs/published/handbook/engineering/data-warehouse.md
@@ -34,7 +34,11 @@ Choose a connection in the **Data** panel, then select a table below it. **Run**
**Chart types** opens the chart picker. While it is docked, the visualization hides its duplicate chart selector. Compact dropdowns keep the data pane and chart controls dense. Visualization controls share a toolbar that wraps as the worksheet narrows, and the Series/Display settings panel scrolls independently. Date dimensions sort oldest first by default, including in tables; explicit sorts still take precedence. Time charts show years centered below their date ticks. Clicking a bar opens the drill-down options for that result.
-**Auto update** is off by default and remembers your choice. Selecting a table alone can run a count when you click **Run**. In wide worksheets, drag the divider between the data and analysis panels to resize the data panel, or drag the analysis panel's right edge to resize that panel independently.
+**Auto update** is off by default and remembers your choice. Selecting a table leaves a blank worksheet, even with auto-update enabled. Add a field to rows or columns before running. A worksheet with dimensions and no selected measure shows **Count of rows** on its shelf and value axis. Turning auto-update off keeps the current result; **Run** applies pending changes.
+
+**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 **Show me** picker offers chart types suited to the selected fields.
+
+In wide worksheets, drag the divider between the data and analysis panels to resize the data panel, or drag the analysis panel's right edge to resize that panel independently.
BI usage keeps the existing `sql-editor-bi-mode-selected`, `sql-editor-bi-query-run`, and `sql-editor-bi-query-saved` events. Their properties describe table calculations, Top N, comparisons, formatting, axes, totals, and related/property field counts. The `bi-worksheet-action` event's `action` property defines the funnel: `opened`, `source_selected`, `first_chart`, `saved`, `added_to_dashboard`. The first chart is the first nonempty successful result per editor visit; reruns and failures do not count again. Saved and dashboard steps include `insight_id`. Additional actions record drill-down choices, related-table expansion, and property browsing/search. These events exclude SQL, source names, field names, formulas, search text, filter values, and result contents.
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index b4fcc826881d..bd160552bb81 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -9947,13 +9947,13 @@ snapshots:
scenes-app-data-warehouse-sql-editor--bi-category-groups--light:
hash: v1.k794b7964.81a477c02903248226b1d7926e9255633dd5cc12701133afb1244048bb5c8ae6.jgbC8pd2rT_AUI0ETrU0qlBlcMs_-ake47UxOm_vZjA
scenes-app-data-warehouse-sql-editor--bi-combined-measures--dark:
- hash: v1.k794b7964.aae60216a2288d48b097b0acd69db10681d6ec0351a77c7018431eeec5083212.GFuC4m0VvbcEYMn4q0z7WDKWuO5AyCV3-RGH9wt6iY4
+ hash: v1.k794b7964.44d7ae33514086f010db79b17c065e04ca842882264fe0b0cc21d3d6ea1cb61c.Ts2pbgsDsI7DWW3ZvDHRAAxcxkul-PPwzikPIOqtvz8
scenes-app-data-warehouse-sql-editor--bi-combined-measures--light:
- hash: v1.k794b7964.f75bacccbc710f2775774539cadc709b9abc2e81ce07aadd3e9bdc2b4ae59d6e.KumXcqoOUGDfHs7S3jcFIakY99FaTGBFoQ7mMQsZw-E
+ hash: v1.k794b7964.630d330192f83e4b8428f0c7ed41582a8306684ea5d1a616bd067346db8519a9.qZa8ddELMxZ1LdWj2AcIJsADaQWqJVIf8utzkpeAofg
scenes-app-data-warehouse-sql-editor--bi-connections--dark:
- hash: v1.k794b7964.85e793119bfab812807ee881d0d947d7c7bc703ba59b38895b8d6b2e6831de3a.IXcQpl7SOaT4jT-OBXmNgHJKUxk3WW4WPhqRniCI5Vo
+ hash: v1.k794b7964.4ba64a2c8aebdeed90b8d759c24467f5f367172cb52f98f02f078e149a29b2b6.Bz1xeaT5goXWUgGYfS64ykJFeVlMuW4pxakwANlM-uI
scenes-app-data-warehouse-sql-editor--bi-connections--light:
- hash: v1.k794b7964.64342d64b102cb15df680e45e3775ab077738e1088ef531a635bf00940c8bf4a.an8bPIGZHMUsuJ5q9eaZPLyGDyptetmoepIzpKfuTQg
+ hash: v1.k794b7964.53903ab2249239bc6ebba8c27875199cd8ab4ba92ba9befc1a723bd016d1e8ec.NPRurnOiM83ifGKijhYwkCg1IaTPAQ2T2_CLrNm44LQ
scenes-app-data-warehouse-sql-editor--bi-data-source-picker--dark:
hash: v1.k794b7964.0bcebcb125477fff88cc5f3603782cabfe3663fa67436f6ff1d97d3b7333f7aa.03zp45mQbNsNqbjyc1HIX6R2kyjtg0zoFlqir2fkeE8
scenes-app-data-warehouse-sql-editor--bi-data-source-picker--light:
@@ -9963,17 +9963,17 @@ snapshots:
scenes-app-data-warehouse-sql-editor--bi-drilldown--light:
hash: v1.k794b7964.64086844ccfeee7b554e8800720fbdc36338ff0be87382481ed98a357bd7eada.1bOKRn1KYdVw_meBxCBcLH0l6KYqr7wUFFhwZG2d3dM
scenes-app-data-warehouse-sql-editor--bi-edit-saved-insight--dark:
- hash: v1.k794b7964.7c3fe1ba42a4fc4f4c325c89bf4392d6af99dafb14bccb1a23eefdab88d7fe1f.xKcolxz25yu5zobGf1ZDsNQiyHgbV6-8wazoYW3QiV4
+ hash: v1.k794b7964.174133b1cc2fa7cf1f3fc18f2b50d04da5bc4bfd45abb09c2fb817bbae29d7fe.wAqWMojan5uFXu_opAVpbufyR-v2k07RHEtIIHueq_c
scenes-app-data-warehouse-sql-editor--bi-edit-saved-insight--light:
- hash: v1.k794b7964.2e64417ea9fcb4976527abd32ac4ada02c47eaf4f73fad15926e6725418bc845.H7WmCLHHz3Kyje1Zq7ZyBBwzQX-WSzSxPI4Dl9_15hc
+ hash: v1.k794b7964.43c88df7c142aab9eb4978f07d155e69efd5a55673e0431f25e2bb341310da51.zLGzPdS3rqEmdO6bAfQQzb0pfmT0UR1gL9zeC_a9ywU
scenes-app-data-warehouse-sql-editor--bi-empty-worksheet--dark:
- hash: v1.k794b7964.a170032c57df0f7a688bf31af7447bf57b41a1ad409cf780eef81a64a60e2469.MFLzlChSLXxmCsubO1GfEO6zSMGJo1nBHVa9-vgir2g
+ hash: v1.k794b7964.c0918b4e1a449da65dacb438f9a82f06a320ac80d55f0cfba78272a85c61f779.QDZBhUdS8See7ooivQEJfykKGrlvyqpPMk7shDIwRb0
scenes-app-data-warehouse-sql-editor--bi-empty-worksheet--light:
- hash: v1.k794b7964.df208814a9f5ec08690c857c3022a77b74a6b103a98ac92c8ee93e3dc972f3a0.oSPLcdtvlrVFgbDeX5CM0V_Ok0smRmt-hQpyTsx4PkY
+ hash: v1.k794b7964.ac5b35044efab39569660efa75f5aa17ea2fb907ebbfaafb096c2d5f51b2e12e.lja2d0iU53cK5AijffEU5sVXSL4sBbOq34pueAPknh0
scenes-app-data-warehouse-sql-editor--bi-measure-display--dark:
- hash: v1.k794b7964.1f1d13fb4ce71f3bb6a8462337b417f366ba9728fc7cfe7815c7848832c4bb28.wpINoBXgRTrOAHUSjyGjgTFZP_N9dqWg9umtiMM2nHU
+ hash: v1.k794b7964.576082ee8f5937473e0bffbc67bb4db11f73dd3391fb0764f00346aa59a99c58.1d61wElvaaI8VC9BMCTv4eTNYuIcV-IWGCqfUe1X_BA
scenes-app-data-warehouse-sql-editor--bi-measure-display--light:
- hash: v1.k794b7964.c8e9eb07cf403a27ecbaa5ff93899bbafee4f194653d2b967e46dcb1e5910073.0O9yXMzXEZk83pH3eJ69yNfa2KUR5pULsgaHg8syyH4
+ hash: v1.k794b7964.0975058421242b00ffd2a38e4c96ee2f80ea72cd01cd9368d265a5f47c47a238.wItZQYUYBP0XvuPnPyelGTVuh3JhCeByY6PJFtO2ZIY
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:
@@ -9983,9 +9983,9 @@ snapshots:
scenes-app-data-warehouse-sql-editor--bi-numeric-bins--light:
hash: v1.k794b7964.003a65922e0b0b3df7f202a6266532ab990c04eee188486eec565bf3a287c48c.ppIpaZ3GKuxnX5hoiMzYdtcq2c7pMKJl5AKeVTJAQkM
scenes-app-data-warehouse-sql-editor--bi-one-click-comparison--dark:
- hash: v1.k794b7964.0c59b3e1c90da6324505aecf74d1a7cb0f80df6acb867a1a7faaf9dcbf80a9cb.VLXgicQzk8TTEKODWzOpe13Dczpb-0xucxU1LLUGa-o
+ hash: v1.k794b7964.d0a7b49acf3c54dbf554c8b837bfe52d9e70b52b3fe8ed094b1205bdd92bebe4.t9cbNd5EVW7Plo8ITkRTkky1-47gRpgh_MWB9P-pSX0
scenes-app-data-warehouse-sql-editor--bi-one-click-comparison--light:
- hash: v1.k794b7964.a7d88cdef92e7b49cdda12c3ebc3f4e386516a557d6439c85620a9e8ee1373b6.LBE--oihN1Aae_qLek7tZ_UmM3QZPEJkmQL6lAo_eDs
+ hash: v1.k794b7964.0cdf30f22fe75faee031a243a558f0d0d986d9ee4dc326318fe5d495698eab2a.bJJtZf7WymErlihjjXnYGBVfti9ugV_-ti4RHs5Tvcc
scenes-app-data-warehouse-sql-editor--bi-pivot-totals--dark:
hash: v1.k794b7964.aab9e3fccc447b883fc831a2f66702fbb88386a0b6e6576144627e707962e5ba.a9z8cq1U7rh2m3M7ZHOlsfNZ8mO5uqJ9PpEwswLkKIM
scenes-app-data-warehouse-sql-editor--bi-pivot-totals--light:
@@ -9995,13 +9995,13 @@ snapshots:
scenes-app-data-warehouse-sql-editor--bi-quick-filters--light:
hash: v1.k794b7964.f71b920765b40a67bc469a1e247040dffa52eafd3617a6a8e19dd2d2a03ed7ea.ZLQRm6vISDJ0ecDRC6sy5iLMVbm-urWlsRdrutVmGOk
scenes-app-data-warehouse-sql-editor--bi-quick-filters-narrow--dark:
- hash: v1.k794b7964.fd3f20adf9fc6bf746f8988f1a7c1d627bff099e1e8b19b8a480ed573b7eb4ab.lEOhofKVjITKytr77tjg6jf660bwa5KmEm4YJlc6UCE
+ hash: v1.k794b7964.5fed43fa62d4326c105518de970f184c4e257d4d76174d60650a27fe150c147a.HfHr6oX_T6TOx3yHHEutql1Sg5wPHry76E0yEAHrh7o
scenes-app-data-warehouse-sql-editor--bi-quick-filters-narrow--light:
- hash: v1.k794b7964.dddbf848e1fc7ca07774fa11456b1184ac048144917339fbe9a9ce5448f2947f.i3reZPyAOzno3cwRy5FxK46UxLHLt6paZvtg4iSjW50
+ hash: v1.k794b7964.13c0d54b44dc128c7488b396ed04d2b9eba236305ea7e1851f323ef9177805fa.1_Yrx3mAKctPBRvZjmRSq9mZfZ4OqWTz0Pv_6GjDZqA
scenes-app-data-warehouse-sql-editor--bi-saved-insight--dark:
- hash: v1.k794b7964.b5232e6c73960ca4f1ebb963ee8a0d82d4b419d4ebdaf8d2564d7535684c0c7c.-z4_dSLh23mW5qEG88QK4ybNGNbLLBfbd4kAHo6BT7U
+ hash: v1.k794b7964.06df092616d217a4ebdaf0f5f35015c05fe63f5bc1e9b9c39dcdf6594293c0e3.D8zEjaefT5868HRYC8F6GkfsuMMlcxSxekM5z-VoXyM
scenes-app-data-warehouse-sql-editor--bi-saved-insight--light:
- hash: v1.k794b7964.2e321b996c4f4216c36e9e8272cbffa243759e37dfc1685c5a33bdceaa411110.Cfm4ZrRTvWUUa_rl2kP_6sGvXH5Quw6fkPsvo-rkuBM
+ hash: v1.k794b7964.2c5f15b06d4347f767fc34bf934ea1bd53e988c443d528edb457795e778cc556.FcMHWv530RuOEcqg3G_bnos4zzZ4mku3Q9pdsK-VCXU
scenes-app-data-warehouse-sql-editor--bi-table-analysis--dark:
hash: v1.k794b7964.698efecc8dd863d7eec52fb2a4e7bf55de1fa9d498cdc2f527cf09b7eb6dedab.V1VDO9CX4qvGtZPcmWuKwoUUKr5ykUOljulg_TAkjpI
scenes-app-data-warehouse-sql-editor--bi-table-analysis--light:
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index e3fe0eaf4c78..8ff3ce5ec33d 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -6529,6 +6529,11 @@
"label": {
"type": "string"
},
+ "shelf": {
+ "description": "Measures in older worksheets belong to rows.",
+ "enum": ["rows", "columns"],
+ "type": "string"
+ },
"tableCalculation": {
"$ref": "#/definitions/BITableCalculation"
}
diff --git a/frontend/src/queries/schema/schema-business-intelligence.ts b/frontend/src/queries/schema/schema-business-intelligence.ts
index 1e090d594d5f..67db91104e8c 100644
--- a/frontend/src/queries/schema/schema-business-intelligence.ts
+++ b/frontend/src/queries/schema/schema-business-intelligence.ts
@@ -76,6 +76,8 @@ export interface BICategoryGroup {
export interface BIValue {
field: BIField
+ /** Measures in older worksheets belong to rows. */
+ shelf?: 'rows' | 'columns'
aggregation: BIAggregation
customExpression?: string
label?: string
diff --git a/posthog/schema.py b/posthog/schema.py
index a61422c3ff52..37c310253674 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -280,6 +280,7 @@ from posthog.schema_enums import (
SessionAttributionGroupBy as SessionAttributionGroupBy,
SessionsV2JoinMode as SessionsV2JoinMode,
SessionTableVersion as SessionTableVersion,
+ Shelf as Shelf,
SidebarDensity as SidebarDensity,
SlackIntegrationScope as SlackIntegrationScope,
SlashCommandName as SlashCommandName,
@@ -5190,6 +5191,7 @@ class BIValue(BaseModel):
field: BIField
formatting: ChartSettingsFormatting | None = None
label: str | None = None
+ shelf: Shelf | None = Field(default=None, description="Measures in older worksheets belong to rows.")
tableCalculation: BITableCalculation | None = None
diff --git a/posthog/schema_enums.py b/posthog/schema_enums.py
index eb01329797c9..0f88026fdc83 100644
--- a/posthog/schema_enums.py
+++ b/posthog/schema_enums.py
@@ -722,6 +722,11 @@ class BITableCalculationType(StrEnum):
RANK = "rank"
+class Shelf(StrEnum):
+ ROWS = "rows"
+ COLUMNS = "columns"
+
+
class BaseMathType(StrEnum):
TOTAL = "total"
DAU = "dau"
diff --git a/products/business_intelligence/frontend/BIEditor.tsx b/products/business_intelligence/frontend/BIEditor.tsx
index 1222832da196..be1c1716e8a7 100644
--- a/products/business_intelligence/frontend/BIEditor.tsx
+++ b/products/business_intelligence/frontend/BIEditor.tsx
@@ -1,6 +1,8 @@
import { BindLogic, useActions, useValues } from 'kea'
import { useRef, type ReactNode } from 'react'
+import { LemonTag } from '@posthog/lemon-ui'
+
import { Resizer } from 'lib/components/Resizer/Resizer'
import { resizerLogic, ResizerLogicProps } from 'lib/components/Resizer/resizerLogic'
import { IconTableChart } from 'lib/lemon-ui/icons'
@@ -109,9 +111,22 @@ export function BIEditor({ tabId, children }: { tabId: string; children: ReactNo
icon={<IconTableChart className="rotate-90" />}
emptyText="Drop dimensions here for a second grouping"
>
- {config.columns.map((field, index) => (
- <BIFieldPill key={field.id} shelf="columns" index={index} />
- ))}
+ {[
+ ...config.columns.map((field, index) => (
+ <BIFieldPill key={field.id} shelf="columns" index={index} />
+ )),
+ ...config.values.flatMap((value, index) =>
+ value.shelf === 'columns'
+ ? [
+ <BIFieldPill
+ key={`${value.field.id}-${index}`}
+ shelf="values"
+ index={index}
+ />,
+ ]
+ : []
+ ),
+ ]}
</BIShelfStrip>
<BIShelfStrip
shelf="rows"
@@ -123,9 +138,28 @@ export function BIEditor({ tabId, children }: { tabId: string; children: ReactNo
...config.rows.map((field, index) => (
<BIFieldPill key={field.id} shelf="rows" index={index} />
)),
- ...config.values.map((value, index) => (
- <BIFieldPill key={`${value.field.id}-${index}`} shelf="values" index={index} />
- )),
+ ...config.values.flatMap((value, index) =>
+ value.shelf !== 'columns'
+ ? [
+ <BIFieldPill
+ key={`${value.field.id}-${index}`}
+ shelf="values"
+ index={index}
+ />,
+ ]
+ : []
+ ),
+ ...(config.values.length === 0 && (config.rows.length > 0 || config.columns.length > 0)
+ ? [
+ <LemonTag
+ key="count"
+ type="success"
+ title="Counts source rows in each group. Add a measure to replace this count."
+ >
+ Count of rows
+ </LemonTag>,
+ ]
+ : []),
]}
</BIShelfStrip>
<div className="flex min-h-0 flex-1 flex-col">{children}</div>
diff --git a/products/business_intelligence/frontend/BusinessIntelligenceScene.tsx b/products/business_intelligence/frontend/BusinessIntelligenceScene.tsx
index cf1c19238806..b58e90dfa13a 100644
--- a/products/business_intelligence/frontend/BusinessIntelligenceScene.tsx
+++ b/products/business_intelligence/frontend/BusinessIntelligenceScene.tsx
@@ -178,7 +178,11 @@ export function BusinessIntelligenceScene({ tabId = 'bi-default' }: { tabId?: st
) : (
<div className="flex flex-1 items-center justify-center p-4 text-secondary">
{worksheet.config.source
- ? 'Press Run to see the results of this worksheet.'
+ ? worksheet.config.rows.length ||
+ worksheet.config.columns.length ||
+ worksheet.config.values.length
+ ? 'Press Run to see the results of this worksheet.'
+ : 'Drag a field to rows or columns to build your worksheet.'
: 'Select a table and add fields to build your worksheet.'}
</div>
)}
diff --git a/products/business_intelligence/frontend/biEditorLogic.test.ts b/products/business_intelligence/frontend/biEditorLogic.test.ts
index 9a0039d8fc17..a415433adc86 100644
--- a/products/business_intelligence/frontend/biEditorLogic.test.ts
+++ b/products/business_intelligence/frontend/biEditorLogic.test.ts
@@ -51,7 +51,14 @@ describe('biEditorLogic', () => {
limit: 1000,
sort: null,
}
- it.each([0, 1, 2])('keeps Top N and result filters attached to their measures when removing value %s', (index) => {
+ it.each([
+ ['remove', 0],
+ ['remove', 1],
+ ['remove', 2],
+ ['reorder', 0],
+ ['reorder', 1],
+ ['reorder', 2],
+ ] as const)('keeps Top N and result filters attached when %s changes value %s', (operation, index) => {
const logic = biEditorLogic({ tabId: TAB_ID })
logic.mount()
logic.actions.setAutoUpdate(false)
@@ -72,14 +79,18 @@ describe('biEditorLogic', () => {
})),
},
})
- logic.actions.removeFieldFromShelf('values', index)
- expect(logic.values.config.resultFilters).toHaveLength(2)
+ if (operation === 'remove') {
+ logic.actions.removeFieldFromShelf('values', index)
+ } else {
+ logic.actions.moveFieldToShelf('values', index, 'values', index === 0 ? 3 : 0)
+ }
+ expect(logic.values.config.resultFilters).toHaveLength(operation === 'remove' ? 2 : 3)
for (const filter of logic.values.config.resultFilters!) {
expect(logic.values.config.values[filter.measureIndex].field.id).toBe(
filter.id.replace('filter-', 'measure-')
)
}
- if (index === 1) {
+ if (index === 1 && operation === 'remove') {
expect(logic.values.config.topN).toBeUndefined()
} else {
const measureIndex = logic.values.config.topN!.measureIndex
@@ -88,6 +99,44 @@ describe('biEditorLogic', () => {
logic.unmount()
})
+ it('reorders dimension pills and swaps measures without losing their calculations or placement on reload', () => {
+ const logic = biEditorLogic({ tabId: TAB_ID })
+ logic.mount()
+ const category = { ...eventField, id: 'category', name: 'Category', expression: 'properties.category' }
+ const revenue = {
+ field: { ...eventField, id: 'revenue', expression: 'properties.revenue' },
+ aggregation: 'sum' as const,
+ tableCalculation: { type: 'running_total' as const },
+ }
+ logic.actions.restoreState({
+ editorView: BIEditorView.BI,
+ config: {
+ ...config,
+ columns: [eventField, category],
+ rows: [],
+ values: [revenue],
+ sort: { key: `columns:${category.id}`, direction: 'asc' },
+ },
+ })
+ logic.actions.moveFieldToShelf('columns', 1, 'columns', 0)
+ expect(logic.values.config.columns).toEqual([category, eventField])
+ logic.actions.swapRowsAndColumns()
+ expect(logic.values.config.rows).toEqual([category, eventField])
+ expect(logic.values.config.columns).toEqual([])
+ expect(logic.values.config.values).toEqual([{ ...revenue, shelf: 'columns' }])
+ expect(logic.values.config.sort?.key).toBe(`rows:${category.id}`)
+ expect(logic.values.config.chartType).toBe(ChartDisplayType.ActionsBarValue)
+ expect(parseBIEditorState(BIEditorView.BI, JSON.stringify(logic.values.config))?.config.values).toEqual(
+ logic.values.config.values
+ )
+ logic.actions.moveFieldToShelf('values', 0, 'rows')
+ expect(logic.values.config.values).toEqual([{ ...revenue, shelf: 'rows' }])
+ logic.actions.convertMeasureToDimension(0)
+ expect(logic.values.config.values).toEqual([])
+ expect(logic.values.config.rows).toEqual([category, eventField, revenue.field])
+ logic.unmount()
+ })
+
it.each(['field', 'blank', 'calculation', 'move'] as const)(
'preserves a Count result filter when adding the first measure via %s',
(method) => {
diff --git a/products/business_intelligence/frontend/biEditorLogic.ts b/products/business_intelligence/frontend/biEditorLogic.ts
index e49d9d829a16..84b82e87b93c 100644
--- a/products/business_intelligence/frontend/biEditorLogic.ts
+++ b/products/business_intelligence/frontend/biEditorLogic.ts
@@ -46,6 +46,7 @@ import {
getBIDataSourceKey,
getBIShelfEditorKey,
getBISortOptions,
+ getBIValueSortKey,
isBIFieldCompatible,
normalizeBIConfig,
} from 'products/business_intelligence/frontend/biEditorTypes'
@@ -182,16 +183,67 @@ function fieldOnShelf(config: BIConfig, shelf: BIShelf, index: number): BIField
}
}
-function moveFieldInConfig(config: BIConfig, fromShelf: BIShelf, fromIndex: number, toShelf: BIShelf): BIConfig {
+function moveFieldInConfig(
+ config: BIConfig,
+ fromShelf: BIShelf,
+ fromIndex: number,
+ toShelf: BIShelf,
+ toIndex?: number
+): BIConfig {
+ if (fromShelf === toShelf) {
+ const fields = [...config[fromShelf]]
+ const target = Math.max(0, Math.min(toIndex ?? fields.length, fields.length))
+ const [field] = fields.splice(fromIndex, 1)
+ if (!field) {
+ return config
+ }
+ fields.splice(target > fromIndex ? target - 1 : target, 0, field)
+ if (fromShelf === 'values') {
+ const indices = (fields as BIValue[]).map((value) => config.values.indexOf(value))
+ const sortedIndex = config.values.findIndex(
+ (_, index) => getBIValueSortKey(config, index) === config.sort?.key
+ )
+ return {
+ ...config,
+ values: fields as BIValue[],
+ sort:
+ config.sort && sortedIndex !== -1
+ ? {
+ ...config.sort,
+ key:
+ getBIValueSortKey(
+ { ...config, values: fields as BIValue[] },
+ indices.indexOf(sortedIndex)
+ ) ?? config.sort.key,
+ }
+ : config.sort,
+ resultFilters: config.resultFilters?.map((filter) => ({
+ ...filter,
+ measureIndex: indices.indexOf(filter.measureIndex),
+ })),
+ topN: config.topN
+ ? { ...config.topN, measureIndex: indices.indexOf(config.topN.measureIndex) }
+ : undefined,
+ }
+ }
+ return { ...config, [fromShelf]: fields }
+ }
+ if (fromShelf === 'values' && (toShelf === 'rows' || toShelf === 'columns')) {
+ return {
+ ...config,
+ values: config.values.map((value, index) => (index === fromIndex ? { ...value, shelf: toShelf } : value)),
+ }
+ }
if (fromShelf === 'values' && config.values[fromIndex]?.label) {
return config
}
const field = fieldOnShelf(config, fromShelf, fromIndex)
- if (!field || fromShelf === toShelf) {
+ if (!field) {
return config
}
- return addFieldToConfig(removeFieldFromConfig(config, fromShelf, fromIndex), field, toShelf)
+ const next = addFieldToConfig(removeFieldFromConfig(config, fromShelf, fromIndex), field, toShelf)
+ return toIndex === undefined ? next : moveFieldInConfig(next, toShelf, next[toShelf].length - 1, toShelf, toIndex)
}
function removeFieldFromConfig(config: BIConfig, shelf: BIShelf, index: number): BIConfig {
@@ -356,6 +408,9 @@ export interface biEditorLogicActions {
combineMeasures: () => {
value: true
}
+ convertMeasureToDimension: (index: number) => {
+ index: number
+ }
editCalculatedMeasure: (index?: number | null) => {
index: number | null
}
@@ -372,10 +427,12 @@ export interface biEditorLogicActions {
moveFieldToShelf: (
fromShelf: BIShelf,
fromIndex: number,
- toShelf: BIShelf
+ toShelf: BIShelf,
+ toIndex?: number
) => {
fromIndex: number
fromShelf: BIShelf
+ toIndex: number | undefined
toShelf: BIShelf
}
removeFieldFromShelf: (
@@ -498,6 +555,13 @@ export interface biEditorLogicActions {
setLocalFieldDraft: (field: BIField | null) => {
field: BIField | null
}
+ setMeasureShelf: (
+ index: number,
+ shelf: 'columns' | 'rows'
+ ) => {
+ index: number
+ shelf: 'columns' | 'rows'
+ }
setMissingDates: (missingDates: BIConfig['missingDates']) => {
missingDates: 'gap' | 'zero' | undefined
}
@@ -640,12 +704,15 @@ export const biEditorLogic = kea<biEditorLogicType>([
saveCalculatedMeasure: true,
upsertCalculatedMeasure: (draft: BICalculatedMeasureDraft) => ({ draft, fieldId: `bi-calculated-${uuid()}` }),
clearActiveDropShelf: (shelf: BIShelf) => ({ shelf }),
- moveFieldToShelf: (fromShelf: BIShelf, fromIndex: number, toShelf: BIShelf) => ({
+ moveFieldToShelf: (fromShelf: BIShelf, fromIndex: number, toShelf: BIShelf, toIndex?: number) => ({
fromShelf,
fromIndex,
toShelf,
+ toIndex,
}),
+ setMeasureShelf: (index: number, shelf: 'rows' | 'columns') => ({ index, shelf }),
swapRowsAndColumns: true,
+ convertMeasureToDimension: (index: number) => ({ index }),
setAutoUpdate: (autoUpdate: boolean) => ({ autoUpdate }),
setChartTypesOpen: (chartTypesOpen: boolean) => ({ chartTypesOpen }),
setHoveredChartType: (chartType: ChartDisplayType | null) => ({ chartType }),
@@ -778,6 +845,7 @@ export const biEditorLogic = kea<biEditorLogicType>([
}
const existing = draft.index === null ? null : config.values[draft.index]
const value = {
+ ...existing,
field: existing?.field ?? { ...blankField(config.source, fieldId), type: 'float' as const },
aggregation: 'custom' as const,
customExpression: draft.expression.trim(),
@@ -815,10 +883,65 @@ export const biEditorLogic = kea<biEditorLogicType>([
addBlankFieldToShelf: (config, { shelf, fieldId }) =>
config.source ? addFieldToConfig(config, blankField(config.source, fieldId), shelf) : config,
removeFieldFromShelf: (config, { shelf, index }) => removeFieldFromConfig(config, shelf, index),
- moveFieldToShelf: (config, { fromShelf, fromIndex, toShelf }) =>
- normalizeBIConfig(moveFieldInConfig(config, fromShelf, fromIndex, toShelf)),
+ moveFieldToShelf: (config, { fromShelf, fromIndex, toShelf, toIndex }) =>
+ normalizeBIConfig(moveFieldInConfig(config, fromShelf, fromIndex, toShelf, toIndex)),
+ setMeasureShelf: (config, { index, shelf }) => ({
+ ...config,
+ values: config.values.map((value, i) => (i === index ? { ...value, shelf } : value)),
+ }),
+ convertMeasureToDimension: (config, { index }) => {
+ const value = config.values[index]
+ if (!value || (value.aggregation === 'custom' && value.label)) {
+ return config
+ }
+ return normalizeBIConfig(
+ addFieldToConfig(
+ removeFieldFromConfig(config, 'values', index),
+ value.field,
+ value.shelf ?? 'rows'
+ )
+ )
+ },
swapRowsAndColumns: (config) =>
- normalizeBIConfig({ ...config, rows: config.columns, columns: config.rows }),
+ normalizeBIConfig({
+ ...config,
+ rows: config.columns,
+ columns: config.rows,
+ values: (config.values.length
+ ? config.values
+ : config.source && (config.rows.length || config.columns.length)
+ ? [
+ {
+ field: blankField(config.source, 'bi-default-count'),
+ aggregation: 'custom' as const,
+ customExpression: 'count(*)',
+ label: 'Count of rows',
+ },
+ ]
+ : []
+ ).map((value: BIValue) => ({
+ ...value,
+ shelf: value.shelf === 'columns' ? 'rows' : 'columns',
+ })),
+ sort: config.sort
+ ? {
+ ...config.sort,
+ key: (config.sort.key === 'values:count' && !config.values.length
+ ? 'values:bi-default-count'
+ : config.sort.key
+ ).replace(
+ /^(rows|columns):/,
+ (_, shelf) => `${shelf === 'rows' ? 'columns' : 'rows'}:`
+ ),
+ }
+ : config.sort,
+ chartType:
+ config.chartType === ChartDisplayType.ActionsBar
+ ? ChartDisplayType.ActionsBarValue
+ : config.chartType === ChartDisplayType.ActionsBarValue
+ ? ChartDisplayType.ActionsBar
+ : config.chartType,
+ }),
setChartType: (config, { chartType }) => normalizeBIConfig({ ...config, chartType }),
setDateRange: (config, { dateRange }) => ({ ...config, dateRange }),
setCompareFilter: (config, { compareFilter }) => ({ ...config, compareFilter }),
@@ -907,7 +1030,13 @@ export const biEditorLogic = kea<biEditorLogicType>([
),
}),
restoreState: (_, { state }) => normalizeBIConfig(state.config),
- resetConfig: freshBIConfig,
+ resetConfig: (config) => ({
+ ...freshBIConfig(),
+ source: config.source,
+ localFields: config.localFields,
+ dateField: config.dateField,
+ dateRange: config.dateRange,
+ }),
},
],
})),
@@ -945,7 +1074,8 @@ export const biEditorLogic = kea<biEditorLogicType>([
],
generatedQuery: [
(selectors) => [selectors.config],
- (config: BIConfig): BIQueryBuildResult | null => buildBIQuery(config),
+ (config: BIConfig): BIQueryBuildResult | null =>
+ config.rows.length || config.columns.length || config.values.length ? buildBIQuery(config) : null,
],
sortOptions: [
(selectors) => [selectors.config],
@@ -1085,6 +1215,8 @@ export const biEditorLogic = kea<biEditorLogicType>([
},
addFieldToShelf: () => actions.runAfterChange(),
moveFieldToShelf: () => actions.runAfterChange(),
+ convertMeasureToDimension: () => actions.runAfterChange(),
+ setMeasureShelf: () => actions.runAfterChange(),
swapRowsAndColumns: () => actions.runAfterChange(),
setAutoUpdate: ({ autoUpdate }) => {
if (autoUpdate) {
@@ -1117,7 +1249,6 @@ export const biEditorLogic = kea<biEditorLogicType>([
setFieldDateBucket: () => actions.runAfterChange(),
setValueCustomExpression: () => actions.runAfterChange(),
setFilterCustomExpression: () => actions.runAfterChange(),
- resetConfig: () => actions.runAfterChange(),
})),
subscriptions(({ actions, values }) => ({
config: (config: BIConfig, oldConfig: BIConfig | undefined) => {
diff --git a/products/business_intelligence/frontend/biEditorTypes.test.ts b/products/business_intelligence/frontend/biEditorTypes.test.ts
index 98b98fce1b71..dac19f9fbbb1 100644
--- a/products/business_intelligence/frontend/biEditorTypes.test.ts
+++ b/products/business_intelligence/frontend/biEditorTypes.test.ts
@@ -309,6 +309,12 @@ describe('BI editor query generation', () => {
filters: { dateRange: { date_from: 'all' } },
},
display: ChartDisplayType.ActionsBar,
+ chartSettings: {
+ xAxis: { column: 'event' },
+ yAxis: [{ column: 'sum_revenue' }],
+ xAxisLabel: 'event',
+ leftYAxisSettings: { label: 'SUM(revenue)' },
+ },
},
})
})
@@ -368,6 +374,7 @@ describe('BI editor query generation', () => {
expect(result.node.chartSettings).toEqual({
xAxis: { column: 'bi_column_revenue' },
xAxisLabel: 'revenue',
+ leftYAxisSettings: { label: 'Count of rows' },
yAxis: [{ column: 'count' }],
seriesBreakdownColumn: 'bi_row_browser',
showLegend: true,
diff --git a/products/business_intelligence/frontend/biEditorTypes.ts b/products/business_intelligence/frontend/biEditorTypes.ts
index ae3cd0a31219..ddb3d5b8dc06 100644
--- a/products/business_intelligence/frontend/biEditorTypes.ts
+++ b/products/business_intelligence/frontend/biEditorTypes.ts
@@ -113,6 +113,7 @@ export function mergeBIChartSettings(
return {
...current,
...generated,
+ leftYAxisSettings: { ...current?.leftYAxisSettings, ...generated.leftYAxisSettings },
xAxis: generated.xAxis
? {
...(current?.xAxis?.column === generated.xAxis.column ? current.xAxis : {}),
@@ -544,6 +545,7 @@ export function parseBIEditorState(editorViewValue: unknown, configValue: unknow
!field ||
!isBIMeasureSettings(valueCandidate) ||
!BI_AGGREGATIONS.has(valueCandidate.aggregation as BIAggregation) ||
+ (valueCandidate.shelf !== undefined && !['rows', 'columns'].includes(valueCandidate.shelf)) ||
(valueCandidate.label !== undefined && typeof valueCandidate.label !== 'string') ||
(valueCandidate.tableCalculation !== undefined &&
!isBITableCalculation(valueCandidate.tableCalculation)) ||
@@ -556,6 +558,7 @@ export function parseBIEditorState(editorViewValue: unknown, configValue: unknow
aggregation: valueCandidate.aggregation as BIAggregation,
customExpression: valueCandidate.customExpression,
label: valueCandidate.label,
+ ...(valueCandidate.shelf ? { shelf: valueCandidate.shelf } : {}),
...(valueCandidate.formatting ? { formatting: valueCandidate.formatting } : {}),
...(valueCandidate.display ? { display: valueCandidate.display } : {}),
...(valueCandidate.tableCalculation ? { tableCalculation: valueCandidate.tableCalculation } : {}),
@@ -1257,6 +1260,7 @@ export function buildBIQuery(config: BIConfig, probeForMoreRows = false): BIQuer
[
ChartDisplayType.Auto,
ChartDisplayType.ActionsBar,
+ ChartDisplayType.ActionsBarValue,
ChartDisplayType.ActionsStackedBar,
ChartDisplayType.ActionsLineGraph,
ChartDisplayType.ActionsAreaGraph,
@@ -1317,7 +1321,15 @@ export function buildBIQuery(config: BIConfig, probeForMoreRows = false): BIQuer
seriesBreakdownColumn: breakdownDimension.alias,
showLegend: true,
}
- : undefined
+ : {
+ xAxis: xDimension
+ ? { column: hasBIAnalysis(config) ? xDimension.alias : fieldExpression(xDimension.field) }
+ : undefined,
+ yAxis: configuredValues.length
+ ? configuredValues.map(({ alias }) => ({ column: alias }))
+ : [{ column: 'count' }],
+ seriesBreakdownColumn: undefined,
+ }
if (comparing) {
const orderDimension = dimensions.find(({ field }) =>
@@ -1437,6 +1449,18 @@ export function buildBIQuery(config: BIConfig, probeForMoreRows = false): BIQuer
column: alias,
settings: getBIMeasureSettings(value),
}))
+ seriesSettings = {
+ ...seriesSettings,
+ xAxisLabel: seriesSettings?.xAxisLabel ?? (xDimension ? getBIFieldPillLabel(xDimension.field) : undefined),
+ leftYAxisSettings: {
+ label:
+ configuredValues.length === 0
+ ? 'Count of rows'
+ : configuredValues.length === 1
+ ? getBIValuePillLabel(configuredValues[0].value)
+ : undefined,
+ },
+ }
if (config.missingDates) {
seriesSettings = { ...seriesSettings, showNullsAsZero: false }
}
diff --git a/products/business_intelligence/frontend/biSceneLogic.test.ts b/products/business_intelligence/frontend/biSceneLogic.test.ts
index 0ab03d2d6a0f..b3f4dec454ab 100644
--- a/products/business_intelligence/frontend/biSceneLogic.test.ts
+++ b/products/business_intelligence/frontend/biSceneLogic.test.ts
@@ -156,15 +156,22 @@ describe('biSceneLogic', () => {
}
})
- it('waits for Run after selecting a table unless auto update is enabled', async () => {
+ it('keeps a selected table blank until fields are added, including with auto update enabled', async () => {
editor.actions.setDataSource({ table: 'events' })
await expectLogic(logic).toFinishAllListeners()
expect(logic.values.lastRunQuery).toBeNull()
logic.actions.runQuery()
- expect(logic.values.lastRunQuery?.source.query).toContain('count(*) AS count')
- logic.actions.setLastRunQuery(null)
+ expect(logic.values.lastRunQuery).toBeNull()
await expectLogic(editor, () => editor.actions.setAutoUpdate(true)).toFinishAllListeners()
+ expect(logic.values.lastRunQuery).toBeNull()
+ await expectLogic(editor, () => editor.actions.addFieldToShelf(eventField, 'columns')).toFinishAllListeners()
expect(logic.values.lastRunQuery?.source.query).toContain('count(*) AS count')
+ const lastRun = logic.values.lastRunQuery
+ await expectLogic(editor, () => editor.actions.setAutoUpdate(false)).toFinishAllListeners()
+ await expectLogic(editor, () => editor.actions.setLimit(100)).toFinishAllListeners()
+ expect(logic.values.lastRunQuery).toBe(lastRun)
+ logic.actions.runQuery()
+ expect(logic.values.lastRunQuery?.config.limit).toBe(100)
})
it('tracks the first successful chart once, without counting empty results or reruns', async () => {
@@ -252,7 +259,7 @@ describe('biSceneLogic', () => {
expect(logic.values.hasUnsavedChanges).toBe(false)
editor.actions.removeFieldFromShelf('rows', 0)
expect(logic.values.worksheet.chartSettings?.seriesBreakdownColumn).toBeUndefined()
- expect(logic.values.worksheet.chartSettings?.xAxis).toBeUndefined()
+ expect(logic.values.worksheet.chartSettings?.xAxis).toEqual({ column: 'timestamp' })
logic.actions.discardChanges()
expect(logic.values.worksheet.config).toEqual(config)
})
@@ -395,6 +402,14 @@ describe('biSceneLogic', () => {
expect(logic.values.config.limit).toBe(50000)
})
+ it('restores saved source-only count charts with an explicit measure without mutating the saved query', () => {
+ const saved = worksheet({ ...config, rows: [], columns: [], values: [] })
+ logic.actions.restoreWorksheet(saved)
+ expect(saved.config.values).toEqual([])
+ expect(editor.values.config.values).toMatchObject([{ label: 'Count of rows', customExpression: 'count(*)' }])
+ expect(editor.values.generatedQuery?.query).toContain('count(*)')
+ })
+
it('resets fields and results when switching connections', async () => {
logic.actions.restoreWorksheet(worksheet())
logic.actions.selectConnection('example-connection')
@@ -486,19 +501,44 @@ describe('biSceneLogic', () => {
}
)
- it('clears cached results when clearing the worksheet', async () => {
- logic.actions.restoreWorksheet(worksheet())
- const data = dataNodeLogic({
- key: logic.values.dataNodeKey,
- query: logic.values.worksheet.source,
- autoLoad: false,
- })
- data.mount()
- data.actions.setResponse({ results: [[1]], columns: ['1'], types: ['Int64'] })
- await expectLogic(editor, () => editor.actions.resetConfig()).toFinishAllListeners()
- expect(data.values.response).toBeNull()
- expect(data.values.queryCancelled).toBe(false)
- expect(logic.values.lastRunQuery).toBeNull()
- data.unmount()
- })
+ it.each([undefined, 'example-connection'])(
+ 'clears the view while keeping its source and local fields (%s)',
+ async (connectionId) => {
+ const source = { table: 'events', connectionId }
+ const localField = {
+ ...eventField,
+ source,
+ id: 'local-category',
+ name: 'Category',
+ expression: 'lower(event)',
+ }
+ logic.actions.restoreWorksheet(worksheet({ ...config, source, localFields: [localField] }))
+ logic.actions.recordWorksheet()
+ const data = dataNodeLogic({
+ key: logic.values.dataNodeKey,
+ query: logic.values.worksheet.source,
+ autoLoad: false,
+ })
+ data.mount()
+ data.actions.setResponse({ results: [[1]], columns: ['1'], types: ['Int64'] })
+ await expectLogic(editor, () => editor.actions.resetConfig()).toFinishAllListeners()
+ expect(data.values.response).toBeNull()
+ expect(data.values.queryCancelled).toBe(false)
+ expect(logic.values.lastRunQuery).toBeNull()
+ expect(logic.values.config).toMatchObject({
+ source,
+ localFields: [localField],
+ rows: [],
+ columns: [],
+ values: [],
+ filters: [],
+ })
+ expect(logic.values.generatedQuery).toBeNull()
+ const cleared = JSON.parse(localStorage.getItem('bi-worksheet-997-bi-test')!)
+ expect(cleared.config.source).toEqual(JSON.parse(JSON.stringify(source)))
+ logic.actions.undo()
+ expect(logic.values.config.rows).toEqual(config.rows)
+ data.unmount()
+ }
+ )
})
diff --git a/products/business_intelligence/frontend/biSceneLogic.ts b/products/business_intelligence/frontend/biSceneLogic.ts
index ac180401749c..48b9eb8f6573 100644
--- a/products/business_intelligence/frontend/biSceneLogic.ts
+++ b/products/business_intelligence/frontend/biSceneLogic.ts
@@ -543,8 +543,12 @@ export const biSceneLogic: LogicWrapper<biSceneLogicType> = kea<biSceneLogicType
}
},
resetConfig: () => {
+ const dataLogic = dataNodeLogic.findMounted({ key: values.dataNodeKey })
+ dataLogic?.actions.cancelQuery()
+ dataLogic?.actions.clearResponse()
actions.restoreWorksheet({
...emptyWorksheet(),
+ config: values.config,
source: { kind: NodeKind.HogQLQuery, query: '', connectionId: values.connectionId ?? undefined },
})
actions.syncWorksheetUrl()
@@ -567,9 +571,32 @@ export const biSceneLogic: LogicWrapper<biSceneLogicType> = kea<biSceneLogicType
if (connectionChanged) {
databaseTableListLogic.actions.setConnection(connectionId)
}
+ const config = { ...applyBIDateRange(worksheet.config, worksheet.source.filters?.dateRange) }
+ if (
+ worksheet.source.query &&
+ config.source &&
+ !config.rows.length &&
+ !config.columns.length &&
+ !config.values.length
+ ) {
+ config.values = [
+ {
+ field: {
+ id: 'bi-default-count',
+ name: 'Count of rows',
+ expression: '',
+ type: 'integer',
+ source: config.source,
+ },
+ aggregation: 'custom',
+ customExpression: 'count(*)',
+ label: 'Count of rows',
+ },
+ ]
+ }
actions.restoreState({
editorView: BIEditorView.BI,
- config: applyBIDateRange(worksheet.config, worksheet.source.filters?.dateRange),
+ config,
})
if (connectionChanged || !databaseTableListLogic.values.database) {
databaseTableListLogic.actions.loadDatabase({ shallow: true })
diff --git a/products/business_intelligence/frontend/components/BIChartTypes.tsx b/products/business_intelligence/frontend/components/BIChartTypes.tsx
index f737a9e19028..111b59920a14 100644
--- a/products/business_intelligence/frontend/components/BIChartTypes.tsx
+++ b/products/business_intelligence/frontend/components/BIChartTypes.tsx
@@ -26,7 +26,7 @@ export function BIChartTypes({ docked }: { docked: boolean }): JSX.Element {
return (
<div className={cn('flex flex-col', docked ? 'w-full' : 'w-44')}>
<div className="flex min-h-7 items-center justify-between px-2 pt-2">
- <span className="text-sm font-semibold">Chart types</span>
+ <span className="text-sm font-semibold">Show me</span>
{docked ? (
<LemonButton
icon={<IconX />}
diff --git a/products/business_intelligence/frontend/components/BIFieldPill.tsx b/products/business_intelligence/frontend/components/BIFieldPill.tsx
index 385bca6fcabf..b36cb094c2f1 100644
--- a/products/business_intelligence/frontend/components/BIFieldPill.tsx
+++ b/products/business_intelligence/frontend/components/BIFieldPill.tsx
@@ -21,6 +21,8 @@ import {
import { BIExpressionPopover } from 'products/business_intelligence/frontend/components/BIExpressionPopover'
import { BIPill } from 'products/business_intelligence/frontend/components/BIPill'
+import { BIShelfDropTarget } from './BIShelfDropTarget'
+
type ExpressionTarget = 'field' | 'aggregation'
/** A dimension on rows or columns, or a measure from the values shelf. */
@@ -34,6 +36,7 @@ export function BIFieldPill({
const { config, activeExpressionEditorId, activeExpressionEditorTarget, sortOptions } = useValues(biEditorLogic)
const {
addFieldToShelf,
+ convertMeasureToDimension,
editCalculatedMeasure,
moveFieldToShelf,
removeFieldFromShelf,
@@ -97,6 +100,13 @@ export function BIFieldPill({
: null,
{
items: [
+ isMeasure
+ ? {
+ label: value?.shelf === 'columns' ? 'Move to rows' : 'Move to columns',
+ onClick: () =>
+ moveFieldToShelf('values', index, value?.shelf === 'columns' ? 'rows' : 'columns'),
+ }
+ : null,
!isCalculatedMeasure ? { label: 'Edit field expression', onClick: () => setEditing('field') } : null,
value?.aggregation === 'custom'
? { label: 'Edit calculated measure', onClick: () => editCalculatedMeasure(index) }
@@ -123,7 +133,7 @@ export function BIFieldPill({
? {
label: 'Convert to dimension',
disabledReason: isCalculatedMeasure ? 'Calculated measures aggregate each group' : undefined,
- onClick: () => moveFieldToShelf('values', index, 'rows'),
+ onClick: () => convertMeasureToDimension(index),
}
: { label: 'Convert to measure', onClick: () => moveFieldToShelf(shelf, index, 'values') },
!isMeasure
@@ -161,7 +171,7 @@ export function BIFieldPill({
}
}}
>
- <span className="inline-flex min-w-0 max-w-[min(18rem,100%)]">
+ <BIShelfDropTarget shelf={shelf} index={index} className="inline-flex min-w-0 max-w-[min(18rem,100%)]">
<LemonMenu items={items} placement="bottom-start">
<BIPill
kind={isMeasure ? 'measure' : 'dimension'}
@@ -173,7 +183,7 @@ export function BIFieldPill({
data-attr={`bi-editor-${shelf}-pill`}
/>
</LemonMenu>
- </span>
+ </BIShelfDropTarget>
</BIExpressionPopover>
)
}
diff --git a/products/business_intelligence/frontend/components/BIShelfDropTarget.tsx b/products/business_intelligence/frontend/components/BIShelfDropTarget.tsx
index 5a50022bed88..85db71d0f35c 100644
--- a/products/business_intelligence/frontend/components/BIShelfDropTarget.tsx
+++ b/products/business_intelligence/frontend/components/BIShelfDropTarget.tsx
@@ -25,15 +25,19 @@ function carriesBIDrag(event: DragEvent<HTMLElement>): 'field' | 'pill' | null {
/** Accepts fields from the data pane or the database tree, and pills moved from other shelves. */
export function BIShelfDropTarget({
shelf,
+ index,
className,
children,
}: {
shelf: BIShelf
+ index?: number
className?: string
children: ReactNode
}): JSX.Element {
const { activeDropShelf, dragSessionId } = useValues(biEditorLogic)
- const { addFieldToShelf, clearActiveDropShelf, moveFieldToShelf, setActiveDropShelf } = useActions(biEditorLogic)
+ const { config } = useValues(biEditorLogic)
+ const { addFieldToShelf, clearActiveDropShelf, moveFieldToShelf, setActiveDropShelf, setMeasureShelf } =
+ useActions(biEditorLogic)
return (
<div
@@ -42,7 +46,7 @@ export function BIShelfDropTarget({
activeDropShelf === shelf && 'bg-accent-highlight-secondary ring-2 ring-inset ring-accent',
className
)}
- data-attr={`bi-editor-${shelf}-shelf`}
+ data-attr={`bi-editor-${shelf}-${index === undefined ? 'shelf' : 'drop-target'}`}
onDragEnter={(event) => {
if (carriesBIDrag(event)) {
setActiveDropShelf(shelf)
@@ -70,17 +74,24 @@ export function BIShelfDropTarget({
if (pill.dragSessionId !== dragSessionId) {
return
}
- // Measures sit on the rows strip, so dropping one on rows or columns keeps it a measure
- const keepsMeasure = pill.shelf === 'values' && (shelf === 'rows' || shelf === 'columns')
- if (!keepsMeasure) {
- moveFieldToShelf(pill.shelf, pill.index, shelf)
+ if (pill.shelf === 'values' && shelf === 'values' && index !== undefined) {
+ setMeasureShelf(pill.index, config.values[index]?.shelf ?? 'rows')
}
+ moveFieldToShelf(pill.shelf, pill.index, shelf, index)
return
}
const field = parseBIField(event.dataTransfer.getData(BI_FIELD_DRAG_MIME_TYPE))
if (field) {
const target = getBIDropTarget(field, shelf)
addFieldToShelf(target.field, target.shelf)
+ if (target.shelf === 'values' && (shelf === 'rows' || shelf === 'columns')) {
+ setMeasureShelf(config.values.length, shelf)
+ } else if (target.shelf === 'values' && index !== undefined) {
+ setMeasureShelf(config.values.length, config.values[index]?.shelf ?? 'rows')
+ moveFieldToShelf('values', config.values.length, 'values', index)
+ } else if (index !== undefined) {
+ moveFieldToShelf(target.shelf, config[target.shelf].length, target.shelf, index)
+ }
}
}}
>
diff --git a/products/business_intelligence/frontend/components/BIToolbar.tsx b/products/business_intelligence/frontend/components/BIToolbar.tsx
index 08b565b75f53..638a97f23bc3 100644
--- a/products/business_intelligence/frontend/components/BIToolbar.tsx
+++ b/products/business_intelligence/frontend/components/BIToolbar.tsx
@@ -51,7 +51,9 @@ export function BIToolbar(): JSX.Element {
!config.source
? 'Select a table before running'
: !generatedQuery
- ? 'Fix invalid worksheet fields before running'
+ ? config.rows.length || config.columns.length || config.values.length
+ ? 'Fix invalid worksheet fields before running'
+ : 'Add a field to rows or columns before running'
: undefined
}
data-attr="bi-editor-run-query"
@@ -74,7 +76,9 @@ export function BIToolbar(): JSX.Element {
tooltip="Swap rows and columns"
aria-label="Swap rows and columns"
disabledReason={
- config.rows.length === 0 && config.columns.length === 0 ? 'No fields to swap' : undefined
+ config.rows.length === 0 && config.columns.length === 0 && config.values.length === 0
+ ? 'No fields to swap'
+ : undefined
}
onClick={swapRowsAndColumns}
data-attr="bi-editor-swap"
@@ -156,7 +160,7 @@ export function BIToolbar(): JSX.Element {
className="@3xl/bi-editor:hidden"
data-attr="bi-editor-show-me"
>
- Chart types
+ Show me
</LemonButton>
</LemonDropdown>
{!chartTypesOpen ? (
@@ -167,7 +171,7 @@ export function BIToolbar(): JSX.Element {
onClick={() => setChartTypesOpen(true)}
data-attr="bi-editor-show-me"
>
- Chart types
+ Show me
</LemonButton>
) : null}
</div>
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index e9973b7002ff..579efcd9928e 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -9614,6 +9614,13 @@ export const BIAggregationApi = {
Custom: 'custom',
} as const
+export type ShelfApi = (typeof ShelfApi)[keyof typeof ShelfApi]
+
+export const ShelfApi = {
+ Rows: 'rows',
+ Columns: 'columns',
+} as const
+
export type BITableCalculationTypeApi = (typeof BITableCalculationTypeApi)[keyof typeof BITableCalculationTypeApi]
export const BITableCalculationTypeApi = {
@@ -9642,6 +9649,8 @@ export interface BIValueApi {
field: BIFieldApi
formatting?: ChartSettingsFormattingApi | null
label?: string | null
+ /** Measures in older worksheets belong to rows. */
+ shelf?: ShelfApi | null
tableCalculation?: BITableCalculationApi | null
}
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index 6abb8f0db423..c6bb91c6d64b 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -8478,6 +8478,13 @@ export const BIAggregationApi = {
Custom: 'custom',
} as const
+export type ShelfApi = (typeof ShelfApi)[keyof typeof ShelfApi]
+
+export const ShelfApi = {
+ Rows: 'rows',
+ Columns: 'columns',
+} as const
+
export type BITableCalculationTypeApi = (typeof BITableCalculationTypeApi)[keyof typeof BITableCalculationTypeApi]
export const BITableCalculationTypeApi = {
@@ -8506,6 +8513,8 @@ export interface BIValueApi {
field: BIFieldApi
formatting?: ChartSettingsFormattingApi | null
label?: string | null
+ /** Measures in older worksheets belong to rows. */
+ shelf?: ShelfApi | null
tableCalculation?: BITableCalculationApi | null
}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 4c276d007e5d..904c8783a0a3 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -10925,6 +10925,14 @@ export namespace Schemas {
Custom: 'custom',
} as const;
+ export type Shelf = typeof Shelf[keyof typeof Shelf];
+
+
+ export const Shelf = {
+ Rows: 'rows',
+ Columns: 'columns',
+ } as const;
+
export type BITableCalculationType = typeof BITableCalculationType[keyof typeof BITableCalculationType];
@@ -10954,6 +10962,8 @@ export namespace Schemas {
field: BIField;
formatting?: ChartSettingsFormatting | null;
label?: string | null;
+ /** Measures in older worksheets belong to rows. */
+ shelf?: Shelf | null;
tableCalculation?: BITableCalculation | null;
}