: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(sql-editor): lay out bi mode like a desktop bi tool (#108850)
Marius Andrad86467925b7b
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex a763196a1b2a..177469049164 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -9486,6 +9486,10 @@ snapshots:hash: v1.k794b7964.22840c30d80b9e1a3bd41d5a31af2ab81a54d9f90fb82d540fb9494b44cda050.oC_UUgUXZVqKMZ6LuInaQADAzqeWAvw2dZ8T5eENhIQscenes-app-data-warehouse-settings-schemas--multi-schema--light:hash: v1.k794b7964.e5d678194a8e191fdf4f8a92cd7328f1e3cb162a81d3c4d05ef608f3c61537da.ZshlecoDn8CpsaVHaONi7UiXq8r-Xi4zJSWKeg7nAP0+ scenes-app-data-warehouse-sql-editor--bi-mode-worksheet--dark:+ hash: v1.k794b7964.c658d01e1ed459e380f64ae18cc893a3bdd4d14d60924691224143b4133d304c.bJ8fJvADbAl-CJHuO6-1i9Ng1abedjo0nuR3uHQ42KM+ scenes-app-data-warehouse-sql-editor--bi-mode-worksheet--light:+ hash: v1.k794b7964.e6e8b6fc3608d3bd734534aae37eb9a8c3d56f5979791ce904a8cf0e18f11f88.S4-L9C5xAT431duxCiXdzDM4sJw1eJ4URMS5uZnhUMIscenes-app-data-warehouse-sql-editor--edited-insight--dark:hash: v1.k794b7964.94eba9d351ec4c6b649fc4b09f5d4a69fed2995448c0cc1dac5d63d3df0ad20c.U6hnpHxuk9RKFoPU8bc536a9dTuzluwHE0pF4J0nPYcscenes-app-data-warehouse-sql-editor--edited-insight--light:diff --git a/frontend/src/queries/nodes/DataNode/dataNodeLogic.ts b/frontend/src/queries/nodes/DataNode/dataNodeLogic.tsindex b8033de9b195..9777f848ac26 100644--- a/frontend/src/queries/nodes/DataNode/dataNodeLogic.ts+++ b/frontend/src/queries/nodes/DataNode/dataNodeLogic.ts@@ -1341,6 +1341,7 @@ export const dataNodeLogic = kea<dataNodeLogicType>([loadNewData: () => false,loadData: () => false,cancelQuery: () => true,+ clearResponse: () => false,},],pollResponse: [diff --git a/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx b/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsxindex c559addf6c7a..8857994ea33c 100644--- a/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx+++ b/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx@@ -352,7 +352,11 @@ export function QueryWindow({</div>) : null}- {showQueryPanel && showBIEditor ? <BIEditor tabId={tabId} /> : null}+ {showQueryPanel && showBIEditor ? (+ <BIEditor tabId={tabId}>+ {showOutputPanel ? <InternalQueryWindow tabId={tabId} biMode onShareTab={onShareTab} /> : null}+ </BIEditor>+ ) : null}{showQueryPanel && !showBIEditor ? (<QueryPane@@ -417,7 +421,7 @@ export function QueryWindow({/>) : null}- {showOutputPanel ? (+ {showOutputPanel && !(showQueryPanel && showBIEditor) ? (<InternalQueryWindow tabId={tabId} biMode={showBIEditor} onShareTab={onShareTab} />) : null}</div>diff --git a/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx b/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsxindex a6f3d361095b..7ca1278b0af2 100644--- a/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx+++ b/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx@@ -144,8 +144,8 @@ export function SQLEditor({queryPaneMinHeight,biEditorResizerProps: {containerRef: biEditorRef,- logicKey: 'bi-editor-pane',- placement: 'bottom' as const,+ logicKey: 'bi-editor-side-pane',+ placement: 'right' as const,persistent: true,persistPrefix: 'v1',},diff --git a/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx b/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsxindex ed0f760e59f9..74aab7e61706 100644--- a/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx+++ b/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx@@ -2,15 +2,17 @@ import { Decorator, Meta, StoryObj } from '@storybook/react'import { BindLogic } from 'kea'import { useEffect, useRef } from 'react'+import { FEATURE_FLAGS } from 'lib/constants'import { App } from 'scenes/App'import { urls } from 'scenes/urls'import { mswDecorator } from '~/mocks/browser'import type { DataWarehouseSavedQuery } from '~/types'-import { AccessControlLevel, AccessControlResourceType } from '~/types'+import { AccessControlLevel, AccessControlResourceType, ChartDisplayType } from '~/types'import { expect, userEvent, waitFor, within } from 'storybook/test'+import { BIConfig, BIField, buildBIQuery } from './bi/biEditorTypes'import { QueryInfo } from './output-pane-tabs/QueryInfo'import { sqlEditorLogic } from './sqlEditorLogic'@@ -104,6 +106,40 @@ const MANAGED_WAREHOUSE_CONNECTIONS = [},]+// A worksheet restored from the URL, so the snapshot shows every shelf holding a pill+const BI_EVENTS_SOURCE = { table: 'events' }+const biEventsField = (name: string, type: BIField['type']): BIField => ({+ id: JSON.stringify([null, 'events', name]),+ name,+ expression: name,+ type,+ source: BI_EVENTS_SOURCE,+})+const BI_WORKSHEET_CONFIG: BIConfig = {+ source: BI_EVENTS_SOURCE,+ chartType: ChartDisplayType.ActionsLineGraph,+ rows: [{ ...biEventsField('timestamp', 'datetime'), dateBucket: 'day' }],+ columns: [biEventsField('event', 'string')],+ values: [{ field: biEventsField('revenue', 'float'), aggregation: 'sum' }],+ filters: [{ field: biEventsField('event', 'string'), operator: 'equals', value: 'purchase' }],+ limit: 1000,+ sort: null,+}+const BI_EVENTS_FIELDS = Object.fromEntries(+ (+ [+ ['event', 'string'],+ ['distinct_id', 'string'],+ ['timestamp', 'datetime'],+ ['$is_bot', 'boolean'],+ ['properties', 'json'],+ ['user_id', 'integer'],+ ['revenue', 'float'],+ ['duration_ms', 'integer'],+ ] as const+ ).map(([name, type]) => [name, { name, hogql_value: name, type, schema_valid: true }])+)+const meta: Meta = {component: App,title: 'Scenes-App/Data Warehouse/SQL Editor',@@ -321,9 +357,43 @@ export const MaterializationSettings: StoryObj = {],}+export const BIModeWorksheet: Story = {+ parameters: {+ featureFlags: [FEATURE_FLAGS.SQL_EDITOR_BI_MODE],+ // The editor restores BI state only alongside the query it generated+ pageUrl: `${urls.sqlEditor()}#${new URLSearchParams({+ q: buildBIQuery(BI_WORKSHEET_CONFIG)?.query ?? '',+ mode: 'bi',+ bi: JSON.stringify(BI_WORKSHEET_CONFIG),+ })}`,+ testOptions: {+ waitForSelector: '[data-attr="bi-editor-data-pane-measure"]',+ viewport: { width: 1600, height: 900 },+ },+ msw: {+ mocks: {+ get: {+ '/api/projects/:team_id/warehouse_expressions/': { results: [] },+ },+ post: {+ // The specific path wins over the catch-all query mock on the meta+ '/api/environments/:team_id/query/DatabaseSchemaQuery/': {+ tables: {+ events: { id: 'events', name: 'events', type: 'posthog', fields: BI_EVENTS_FIELDS },+ },+ },+ },+ },+ },+ },+}+export const LazySchema: Story = {parameters: {pageUrl: urls.sqlEditor({ query: 'SELECT * FROM events LIMIT 100' }),+ testOptions: {+ waitForSelector: ['.monaco-editor', '[data-attr="menu-item-posthog"]'],+ },msw: {mocks: {get: {diff --git a/frontend/src/scenes/data-warehouse/editor/bi/BIEditor.tsx b/frontend/src/scenes/data-warehouse/editor/bi/BIEditor.tsxindex 582ff1e12b98..858c0c898853 100644--- a/frontend/src/scenes/data-warehouse/editor/bi/BIEditor.tsx+++ b/frontend/src/scenes/data-warehouse/editor/bi/BIEditor.tsx@@ -1,713 +1,100 @@-import { useActions, useValues } from 'kea'-import type { DragEvent, ReactNode } from 'react'+import { BindLogic, useActions, useValues } from 'kea'+import type { ReactNode } from 'react'-import {- IconCalculator,- IconDatabase,- IconFilter,- IconGraph,- IconLifecycle,- IconMagicWand,- IconPencil,- IconPieChart,- IconPlus,- IconTrends,- IconX,-} from '@posthog/icons'-import { LemonButton, LemonCard, LemonInput, LemonLabel, LemonSearchableSelect, LemonSelect } from '@posthog/lemon-ui'--import { HogQLDropdown } from 'lib/components/HogQLDropdown/HogQLDropdown'import { Resizer } from 'lib/components/Resizer/Resizer'-import { FEATURE_FLAGS } from 'lib/constants'-import { dayjs } from 'lib/dayjs'-import { Icon123, IconAreaChart, IconDonutChart, IconHeatmap, IconTableChart } from 'lib/lemon-ui/icons'-import { LemonCalendarSelectInput } from 'lib/lemon-ui/LemonCalendar/LemonCalendarSelect'-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'-import { cn } from 'lib/utils/css-classes'--import { ChartDisplayType } from '~/types'+import { IconTableChart } from 'lib/lemon-ui/icons'import { editorSizingLogic } from '../editorSizingLogic'-import { queryDatabaseLogic } from '../sidebar/queryDatabaseLogic'import { biEditorLogic } from './biEditorLogic'-import {- BIAggregation,- BIDateBucket,- BI_FIELD_DRAG_MIME_TYPE,- BI_QUERY_LIMITS,- BIFilterOperator,- BIShelf,- BIField,- BISortDirection,- getBIDataSourceKey,- isDateTimeBIField,- isNumericBIField,- parseBIField,-} from './biEditorTypes'--const CHART_TYPE_OPTIONS: { value: ChartDisplayType; label: string; icon: JSX.Element }[] = [- { value: ChartDisplayType.Auto, label: 'Auto', icon: <IconMagicWand /> },- { value: ChartDisplayType.ActionsTable, label: 'Table', icon: <IconTableChart /> },- { value: ChartDisplayType.ActionsLineGraph, label: 'Line chart', icon: <IconTrends /> },- { value: ChartDisplayType.ActionsBar, label: 'Bar chart', icon: <IconGraph /> },- { value: ChartDisplayType.ActionsStackedBar, label: 'Stacked bar chart', icon: <IconLifecycle /> },- { value: ChartDisplayType.ActionsAreaGraph, label: 'Area chart', icon: <IconAreaChart /> },- { value: ChartDisplayType.ActionsPie, label: 'Pie chart', icon: <IconPieChart /> },- { value: ChartDisplayType.ActionsDonut, label: 'Donut chart', icon: <IconDonutChart /> },- { value: ChartDisplayType.TwoDimensionalHeatmap, label: 'Pivot table', icon: <IconHeatmap /> },- { value: ChartDisplayType.BoldNumber, label: 'Big number', icon: <Icon123 /> },- { value: ChartDisplayType.Metric, label: 'Metric', icon: <IconTrends /> },-]--const AGGREGATION_OPTIONS: { value: BIAggregation; label: string }[] = [- { value: 'custom', label: 'SQL expression' },- { value: 'count', label: 'Count' },- { value: 'count_distinct', label: 'Count distinct' },- { value: 'sum', label: 'Sum' },- { value: 'average', label: 'Average' },- { value: 'minimum', label: 'Minimum' },- { value: 'maximum', label: 'Maximum' },-]--const FILTER_OPERATOR_OPTIONS: { value: BIFilterOperator; label: string }[] = [- { value: 'equals', label: 'Equals' },- { value: 'not_equals', label: 'Does not equal' },- { value: 'contains', label: 'Contains' },- { value: 'greater_than', label: 'Greater than' },- { value: 'less_than', label: 'Less than' },- { value: 'last_7_days', label: 'Last 7 days' },- { value: 'is_set', label: 'Is set' },- { value: 'is_not_set', label: 'Is not set' },- { value: 'custom', label: 'SQL condition' },-]--const DATE_BUCKET_OPTIONS: { value: BIDateBucket | null; label: string }[] = [- { value: null, label: 'Exact' },- { value: 'minute', label: 'Minute' },- { value: 'hour', label: 'Hour' },- { value: 'day', label: 'Day' },- { value: 'week', label: 'Week' },- { value: 'month', label: 'Month' },- { value: 'quarter', label: 'Quarter' },- { value: 'year', label: 'Year' },-]--const LIMIT_OPTIONS = BI_QUERY_LIMITS.map((limit) => ({- value: limit,- label: limit === 1000 ? '1k' : limit === 10000 ? '10k' : limit === 50000 ? '50k' : String(limit),-}))--const SORT_DIRECTION_OPTIONS: { value: BISortDirection; label: string }[] = [- { value: 'desc', label: 'Descending' },- { value: 'asc', label: 'Ascending' },-]--export function BIEditor({ tabId }: { tabId: string }): JSX.Element {- const logic = biEditorLogic({ tabId })- const { activeDropShelf, activeExpressionEditorId, availableDataSources, config, databaseLoading, sortOptions } =- useValues(logic)- const { biEditorHeight, biEditorResizerProps } = useValues(editorSizingLogic)- const { featureFlags } = useValues(featureFlagLogic)- const { setDatabaseTreeCollapsed } = useActions(editorSizingLogic)- const { locateTable } = useActions(queryDatabaseLogic)- const {- addBlankFieldToShelf,- addFieldToShelf,- clearActiveDropShelf,- removeFieldFromShelf,- resetConfig,- setActiveDropShelf,- setActiveExpressionEditorId,- setChartType,- setDataSource,- setFieldDateBucket,- setFieldExpression,- setFilterCustomExpression,- setFilterOperator,- setFilterValue,- setLimit,- setSort,- setValueAggregation,- setValueCustomExpression,- } = useActions(logic)+import { BI_SHELF_PILL_DRAG_MIME_TYPE, parseBIShelfPillDragData } from './biEditorTypes'+import { BIDataPane } from './components/BIDataPane'+import { BIFieldPill } from './components/BIFieldPill'+import { BIFiltersCard } from './components/BIFiltersCard'+import { BIMarksCard } from './components/BIMarksCard'+import { BIShelfStrip } from './components/BIShelfStrip'+import { BIShowMe } from './components/BIShowMe'+import { BIToolbar } from './components/BIToolbar'++/**+ * A worksheet laid out like desktop BI tools: data pane, filter and marks cards, rows and columns+ * shelves above the view, and a chart picker on the right.+ */+export function BIEditor({ tabId, children }: { tabId: string; children: ReactNode }): JSX.Element {+ const { config, showMeOpen, dragSessionId } = useValues(biEditorLogic({ tabId }))+ const { removeFieldFromShelf, setActiveDropShelf } = useActions(biEditorLogic({ tabId }))+ const { biSidePaneWidth, biEditorResizerProps } = useValues(editorSizingLogic)return (- <div- className="relative flex min-h-44 shrink-0 flex-col gap-3 overflow-hidden border-b bg-primary p-3"- // eslint-disable-next-line react/forbid-dom-props- style={{ height: `${biEditorHeight}px`, maxHeight: 'calc(100% - 10rem)' }}- ref={biEditorResizerProps.containerRef}- >- <div className="flex flex-wrap items-end justify-between gap-3">- <div className="flex min-w-0 flex-col gap-1">- <div className="flex items-center gap-1">- <LemonLabel info="Fields are limited to this table and its related folders.">- Data source- </LemonLabel>- <LemonButton- type="tertiary"- size="xsmall"- disabledReason={!config.source ? 'Select a data source first' : undefined}- onClick={() => {- if (config.source) {- setDatabaseTreeCollapsed(false)- locateTable(config.source.table)- }- }}- >- Locate- </LemonButton>- </div>- <div className="flex items-center gap-2">- <LemonSearchableSelect- value={config.source ? getBIDataSourceKey(config.source) : undefined}- options={availableDataSources.map((source) => ({- value: getBIDataSourceKey(source),- label: source.table,- }))}- onSelect={(sourceKey) => {- const source = availableDataSources.find(- (candidate) => getBIDataSourceKey(candidate) === sourceKey- )- if (source) {- setDataSource(source)- }- }}- icon={<IconDatabase />}- loading={databaseLoading}- disabledReason={- !databaseLoading && availableDataSources.length === 0- ? 'No tables available for this connection'- : undefined- }- placeholder="Select a table"- searchPlaceholder="Search tables"- searchInputDataAttr="bi-editor-data-source-search"- noResultsMessage="No matching tables"- size="small"- className="min-w-64 max-w-120"- truncateText={{ maxWidthClass: 'max-w-96' }}- dropdownMaxContentWidth- data-attr="bi-editor-data-source"- />- <LemonSelect- value={config.limit}- options={LIMIT_OPTIONS}- onChange={setLimit}- renderButtonContent={(option) => `Limit: ${option?.label ?? config.limit}`}- aria-label="Query row limit"- size="small"- dropdownMatchSelectWidth={false}- data-attr="bi-editor-query-limit"- />- <LemonSelect- value={config.sort?.key ?? null}- options={[- {- value: null,- label: 'Auto',- tooltip:- 'Sorts by the newest date or the highest value first, so the top rows stay within the limit.',- },- ...sortOptions.map((option) => ({ value: option.key, label: option.label })),- ]}- onChange={(key) =>- setSort(key === null ? null : { key, direction: config.sort?.direction ?? 'desc' })- }- renderButtonContent={(option) => `Sort: ${option?.label ?? 'Auto'}`}- aria-label="Sort results by"- size="small"- dropdownMatchSelectWidth={false}- disabledReason={- sortOptions.length === 0 ? 'Add a field to rows or columns first' : undefined- }- data-attr="bi-editor-sort"- />- {config.sort ? (- <LemonSelect- value={config.sort.direction}- options={SORT_DIRECTION_OPTIONS}- onChange={(direction) => config.sort && setSort({ key: config.sort.key, direction })}- aria-label="Sort direction"- size="small"- dropdownMatchSelectWidth={false}- data-attr="bi-editor-sort-direction"- />- ) : null}- <LemonButton- type="secondary"- size="small"- onClick={resetConfig}- disabledReason={!config.source ? 'No BI setup to clear' : undefined}- >- Clear- </LemonButton>- </div>- </div>- <div className="flex flex-col gap-1">- <LemonLabel>Chart type</LemonLabel>- <div className="flex flex-wrap gap-1" role="group" aria-label="Chart type">- {CHART_TYPE_OPTIONS.filter(- (option) =>- option.value !== ChartDisplayType.Metric || !!featureFlags[FEATURE_FLAGS.METRIC_INSIGHT]- ).map((option) => (- <LemonButton- key={option.value}- type={config.chartType === option.value ? 'primary' : 'secondary'}- active={config.chartType === option.value}- icon={option.icon}- size="small"- tooltip={option.label}- aria-label={option.label}- data-attr={`bi-editor-chart-type-${option.value}`}- onClick={() => setChartType(option.value)}- />- ))}- </div>- </div>- </div>-- <div className="grid min-h-0 flex-1 grid-cols-1 gap-3 overflow-auto lg:grid-cols-2">- <Shelf- shelf="rows"- title="Rows"- description="Group results by these fields"- icon={<IconTableChart />}- itemCount={config.rows.length}- isActiveDropTarget={activeDropShelf === 'rows'}- onDropField={addFieldToShelf}- onActiveDropTargetChange={(active) =>- active ? setActiveDropShelf('rows') : clearActiveDropShelf('rows')- }- onAddField={() => addBlankFieldToShelf('rows')}- addFieldDisabledReason={!config.source ? 'Select a data source first' : undefined}- >- {config.rows.map((field, index) => (- <FieldExpressionEditor- key={field.id}- field={field}- autoOpen={activeExpressionEditorId === field.id}- onAutoOpenClose={() => setActiveExpressionEditorId(null)}- onChange={(expression) => setFieldExpression('rows', index, expression)}- onDateBucketChange={(dateBucket) => setFieldDateBucket('rows', index, dateBucket)}- onRemove={() => removeFieldFromShelf('rows', index)}- />- ))}- </Shelf>-- <Shelf- shelf="columns"- title="Columns"- description="Add a second grouping for charts that use one"- icon={<IconTableChart />}- itemCount={config.columns.length}- isActiveDropTarget={activeDropShelf === 'columns'}- onDropField={addFieldToShelf}- onActiveDropTargetChange={(active) =>- active ? setActiveDropShelf('columns') : clearActiveDropShelf('columns')- }- onAddField={() => addBlankFieldToShelf('columns')}- addFieldDisabledReason={!config.source ? 'Select a data source first' : undefined}- >- {config.columns.map((field, index) => (- <FieldExpressionEditor- key={field.id}- field={field}- autoOpen={activeExpressionEditorId === field.id}- onAutoOpenClose={() => setActiveExpressionEditorId(null)}- onChange={(expression) => setFieldExpression('columns', index, expression)}- onDateBucketChange={(dateBucket) => setFieldDateBucket('columns', index, dateBucket)}- onRemove={() => removeFieldFromShelf('columns', index)}- />- ))}- </Shelf>-- <Shelf- shelf="values"- title="Values"- description="Calculate the values shown in the chart"- icon={<IconCalculator />}- itemCount={config.values.length}- isActiveDropTarget={activeDropShelf === 'values'}- onDropField={addFieldToShelf}- onActiveDropTargetChange={(active) =>- active ? setActiveDropShelf('values') : clearActiveDropShelf('values')- }- onAddField={() => addBlankFieldToShelf('values')}- addFieldDisabledReason={!config.source ? 'Select a data source first' : undefined}- >- {config.values.map((value, index) => (- <div- key={`${value.field.id}-${index}`}- className="flex w-full min-w-0 items-center gap-2 rounded"- >- <LemonSelect- value={value.aggregation}- options={AGGREGATION_OPTIONS.map((option) => ({- ...option,- disabledReason:- !isNumericBIField(value.field) &&- ['sum', 'average', 'minimum', 'maximum'].includes(option.value)- ? 'This calculation requires a numeric field'- : undefined,- }))}- onChange={(aggregation) => setValueAggregation(index, aggregation)}- size="xsmall"- dropdownMatchSelectWidth={false}- />- <ExpressionEditorButton- value={value.field.expression}- field={value.field}- label="Edit field expression"- emptyLabel="Select field"- visible={activeExpressionEditorId === value.field.id ? true : undefined}- onVisibilityChange={(visible) => {- if (!visible) {- setActiveExpressionEditorId(null)- }- }}- onChange={(expression) => setFieldExpression('values', index, expression)}- />- <DateBucketSelect- field={value.field}- onChange={(dateBucket) => setFieldDateBucket('values', index, dateBucket)}- />- {value.aggregation === 'custom' ? (- <ExpressionEditorButton- value={value.customExpression ?? ''}- field={value.field}- label={- value.customExpression- ? 'Edit aggregation SQL expression'- : 'Add aggregation SQL expression'- }- emptyLabel="Add aggregation SQL expression"- onChange={(customExpression) => setValueCustomExpression(index, customExpression)}- />- ) : null}- <RemoveFieldButton- field={value.field}- onClick={() => removeFieldFromShelf('values', index)}- />- </div>- ))}- </Shelf>-- <Shelf- shelf="filters"- title="Filters"- description="Limit which rows are included"- icon={<IconFilter />}- itemCount={config.filters.length}- isActiveDropTarget={activeDropShelf === 'filters'}- onDropField={addFieldToShelf}- onActiveDropTargetChange={(active) =>- active ? setActiveDropShelf('filters') : clearActiveDropShelf('filters')- }- onAddField={() => addBlankFieldToShelf('filters')}- addFieldDisabledReason={!config.source ? 'Select a data source first' : undefined}- >- {config.filters.map((filter, index) => {- const filterNeedsValue = !['last_7_days', 'is_set', 'is_not_set', 'custom'].includes(- filter.operator- )- return (- <div key={filter.field.id} className="flex w-full min-w-0 items-center gap-2 rounded">- <ExpressionEditorButton- value={filter.field.expression}- field={filter.field}- label="Edit field expression"- emptyLabel="Select field"- visible={activeExpressionEditorId === filter.field.id ? true : undefined}- onVisibilityChange={(visible) => {- if (!visible) {- setActiveExpressionEditorId(null)- }- }}- onChange={(expression) => setFieldExpression('filters', index, expression)}- />- <DateBucketSelect- field={filter.field}- onChange={(dateBucket) => setFieldDateBucket('filters', index, dateBucket)}- />- <LemonSelect- value={filter.operator}- options={FILTER_OPERATOR_OPTIONS.map((option) => ({- ...option,- disabledReason:- option.value === 'last_7_days' && !isDateTimeBIField(filter.field)- ? 'Choose a date or date-time field'- : undefined,- }))}- onChange={(operator) => setFilterOperator(index, operator)}- size="xsmall"- dropdownMatchSelectWidth={false}- />- {filter.operator === 'custom' ? (- <ExpressionEditorButton- value={filter.customExpression ?? ''}- field={filter.field}- label={- filter.customExpression- ? 'Edit filter SQL condition'- : 'Add filter SQL condition'- }- emptyLabel="Add filter SQL condition"- onChange={(customExpression) =>- setFilterCustomExpression(index, customExpression)- }- />- ) : filterNeedsValue ? (- isDateTimeBIField(filter.field) ? (- <DateTimeFilterInput- field={filter.field}- value={filter.value}- onChange={(value) => setFilterValue(index, value)}- />- ) : (- <LemonInput- value={filter.value}- onChange={(value) => setFilterValue(index, value)}- placeholder="Value"- aria-label={`${filter.field.name} filter value`}- size="small"- />- )- ) : null}- <RemoveFieldButton- field={filter.field}- onClick={() => removeFieldFromShelf('filters', index)}- />- </div>- )- })}- </Shelf>- </div>- <Resizer {...biEditorResizerProps} />- </div>- )-}--function FieldExpressionEditor({- field,- autoOpen,- onAutoOpenClose,- onChange,- onDateBucketChange,- onRemove,-}: {- field: BIField- autoOpen: boolean- onAutoOpenClose: () => void- onChange: (expression: string) => void- onDateBucketChange: (dateBucket: BIDateBucket | null) => void- onRemove: () => void-}): JSX.Element {- return (- <div className="flex w-full min-w-0 items-center gap-2 rounded">- <ExpressionEditorButton- value={field.expression}- field={field}- label="Edit field expression"- emptyLabel="Select field"- visible={autoOpen ? true : undefined}- onVisibilityChange={(visible) => {- if (!visible) {- onAutoOpenClose()- }- }}- onChange={onChange}- />- <DateBucketSelect field={field} onChange={onDateBucketChange} />- <RemoveFieldButton field={field} onClick={onRemove} />- </div>- )-}--function DateBucketSelect({- field,- onChange,-}: {- field: BIField- onChange: (dateBucket: BIDateBucket | null) => void-}): JSX.Element | null {- if (!isDateTimeBIField(field)) {- return null- }-- return (- <LemonSelect- value={field.dateBucket ?? null}- options={DATE_BUCKET_OPTIONS}- onChange={onChange}- size="xsmall"- dropdownMatchSelectWidth={false}- data-attr="bi-editor-date-bucket"- />- )-}--function RemoveFieldButton({ field, onClick }: { field: BIField; onClick: () => void }): JSX.Element {- const fieldName = field.name || 'field'-- return (- <LemonButton- icon={<IconX />}- size="xsmall"- type="tertiary"- noPadding- className="shrink-0"- tooltip={`Remove ${fieldName}`}- aria-label={`Remove ${fieldName}`}- onClick={onClick}- />- )-}--function ExpressionEditorButton({- value,- field,- label,- emptyLabel,- visible,- onVisibilityChange,- onChange,-}: {- value: string- field: BIField- label: string- emptyLabel?: string- visible?: boolean- onVisibilityChange?: (visible: boolean) => void- onChange: (value: string) => void-}): JSX.Element {- return (- <HogQLDropdown- hogQLValue={value}- onHogQLValueChange={onChange}- tableName={field.source.table}- connectionId={field.source.connectionId}- size="small"- buttonIcon={<IconPencil />}- buttonLabel={value ? <code className="truncate">{value}</code> : emptyLabel}- buttonTooltip={label}- buttonAriaLabel={`${label} for ${field.name || 'field'}`}- visible={visible}- onVisibilityChange={onVisibilityChange}- />- )-}--function DateTimeFilterInput({- field,- value,- onChange,-}: {- field: BIField- value: string- onChange: (value: string) => void-}): JSX.Element {- const selectedDate = value && dayjs(value).isValid() ? dayjs(value) : null- const includesTime = field.type === 'datetime'-- return (- <LemonCalendarSelectInput- value={selectedDate}- onChange={(date) => onChange(date?.format(includesTime ? 'YYYY-MM-DD HH:mm:ss' : 'YYYY-MM-DD') ?? '')}- granularity={includesTime ? 'minute' : 'day'}- format={includesTime ? 'MMM D, YYYY HH:mm' : 'MMM D, YYYY'}- use24HourFormat- clearable- placeholder={includesTime ? 'Select date and time' : 'Select date'}- buttonProps={{ size: 'small', 'aria-label': `${field.name} filter date` }}- />- )-}--function Shelf({- shelf,- title,- description,- icon,- itemCount,- isActiveDropTarget,- children,- onDropField,- onActiveDropTargetChange,- onAddField,- addFieldDisabledReason,-}: {- shelf: BIShelf- title: string- description: string- icon: ReactNode- itemCount: number- isActiveDropTarget: boolean- children: ReactNode- onDropField: (field: NonNullable<ReturnType<typeof parseBIField>>, shelf: BIShelf) => void- onActiveDropTargetChange: (active: boolean) => void- onAddField: () => void- addFieldDisabledReason?: string-}): JSX.Element {- const handleDrop = (event: DragEvent<HTMLDivElement>): void => {- event.preventDefault()- onActiveDropTargetChange(false)- const field = parseBIField(event.dataTransfer.getData(BI_FIELD_DRAG_MIME_TYPE))- if (field) {- onDropField(field, shelf)- }- }-- return (- <LemonCard- hoverEffect={false}- className={cn(- 'flex min-h-28 max-h-64 flex-col gap-2 overflow-hidden border-dashed p-3 transition-colors',- isActiveDropTarget && 'border-accent bg-accent-highlight-secondary ring-2 ring-inset ring-accent'- )}- >+ <BindLogic logic={biEditorLogic} props={{ tabId }}><div- className="flex min-h-0 flex-1 flex-col gap-2"- data-attr={`bi-editor-${shelf}-shelf`}- onDragEnter={(event) => {- if (Array.from(event.dataTransfer.types).includes(BI_FIELD_DRAG_MIME_TYPE)) {- onActiveDropTargetChange(true)- }- }}+ className="@container/bi-editor flex min-h-0 flex-1 flex-col overflow-hidden bg-primary"onDragOver={(event) => {- if (Array.from(event.dataTransfer.types).includes(BI_FIELD_DRAG_MIME_TYPE)) {+ if (event.dataTransfer.types.includes(BI_SHELF_PILL_DRAG_MIME_TYPE)) {event.preventDefault()- event.dataTransfer.dropEffect = 'copy'}}}- onDragLeave={(event) => {- const nextTarget = event.relatedTarget- if (!nextTarget || !event.currentTarget.contains(nextTarget as Node)) {- onActiveDropTargetChange(false)+ onDrop={(event) => {+ const pill = parseBIShelfPillDragData(event.dataTransfer.getData(BI_SHELF_PILL_DRAG_MIME_TYPE))+ if (pill?.dragSessionId === dragSessionId) {+ event.preventDefault()+ removeFieldFromShelf(pill.shelf, pill.index)}+ setActiveDropShelf(null)}}- onDrop={handleDrop}+ onDragEnd={() => setActiveDropShelf(null)}>- <div className="flex items-center justify-between gap-2">- <div className="flex items-center gap-2 font-medium">- <span className="text-tertiary">{icon}</span>- {title} ({itemCount})+ <BIToolbar />+ <div className="flex min-h-0 flex-1">+ <div+ className="relative flex w-[var(--bi-side-pane-width)] shrink-0 flex-col border-r @4xl/bi-editor:w-[calc(var(--bi-side-pane-width)+12rem)] @4xl/bi-editor:flex-row"+ // eslint-disable-next-line react/forbid-dom-props+ style={{ '--bi-side-pane-width': `${biSidePaneWidth}px` } as React.CSSProperties}+ >+ {/* The resizer measures the data pane alone, because the cards column has a fixed width */}+ <div ref={biEditorResizerProps.containerRef} className="flex min-h-0 min-w-0 flex-1 flex-col">+ <BIDataPane />+ </div>+ <div className="flex max-h-[50%] shrink-0 flex-col overflow-y-auto border-t @4xl/bi-editor:max-h-none @4xl/bi-editor:w-48 @4xl/bi-editor:border-l @4xl/bi-editor:border-t-0">+ <BIFiltersCard />+ <BIMarksCard />+ </div>+ <Resizer {...biEditorResizerProps} />+ </div>+ <div className="flex min-w-0 flex-1 flex-col">+ <BIShelfStrip+ shelf="columns"+ title="Columns"+ 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} />+ ))}+ </BIShelfStrip>+ <BIShelfStrip+ shelf="rows"+ title="Rows"+ icon={<IconTableChart />}+ emptyText="Drop dimensions or measures here"+ >+ {[+ ...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} />+ )),+ ]}+ </BIShelfStrip>+ <div className="flex min-h-0 flex-1 flex-col">{children}</div></div>- <LemonButton- icon={<IconPlus />}- size="xsmall"- type="tertiary"- noPadding- tooltip="Add field"- aria-label={`Add field to ${title.toLowerCase()}`}- disabledReason={addFieldDisabledReason}- onClick={onAddField}- data-attr={`bi-editor-${shelf}-add-field`}- />+ {showMeOpen ? (+ <div className="hidden shrink-0 border-l bg-surface-primary @3xl/bi-editor:flex">+ <BIShowMe docked />+ </div>+ ) : null}</div>- <span className="shrink-0 text-xs text-secondary">{description}</span>- <div className="flex min-h-0 flex-1 flex-col gap-2 overflow-y-auto pr-1">{children}</div></div>- </LemonCard>+ </BindLogic>)}diff --git a/frontend/src/scenes/data-warehouse/editor/bi/biEditorLogic.ts b/frontend/src/scenes/data-warehouse/editor/bi/biEditorLogic.tsindex 92865abf1703..a46345cf2ebe 100644--- a/frontend/src/scenes/data-warehouse/editor/bi/biEditorLogic.ts+++ b/frontend/src/scenes/data-warehouse/editor/bi/biEditorLogic.ts@@ -1,8 +1,10 @@import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { subscriptions } from 'kea-subscriptions'import { uuid } from 'lib/utils/dom'-import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'+import { TableFieldsStatus, databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'+import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'import { DatabaseSchemaTable } from '~/queries/schema/schema-general'import { ChartDisplayType } from '~/types'@@ -11,7 +13,9 @@ import type { QueryTab } from '../sqlEditorLogic'import { captureBIEditorModeSelected } from './biEditorAnalytics'import {BIAggregation,+ BIChartFit,BIConfig,+ BIDataPaneFields,BIDataSource,BIDateBucket,BIEditorState,@@ -27,6 +31,10 @@ import {buildBIQuery,createDefaultDateFilter,defaultAggregationForField,+ getBIChartFit,+ getBIDataPaneFields,+ getBIDataSourceKey,+ getBIShelfEditorKey,getBISortOptions,isBIFieldCompatible,normalizeBIConfig,@@ -118,6 +126,27 @@ function addFieldToConfig(config: BIConfig, field: BIField, shelf: BIShelf): BIC}}+function fieldOnShelf(config: BIConfig, shelf: BIShelf, index: number): BIField | null {+ switch (shelf) {+ case 'rows':+ case 'columns':+ return config[shelf][index] ?? null+ case 'values':+ return config.values[index]?.field ?? null+ case 'filters':+ return config.filters[index]?.field ?? null+ }+}++function moveFieldInConfig(config: BIConfig, fromShelf: BIShelf, fromIndex: number, toShelf: BIShelf): BIConfig {+ const field = fieldOnShelf(config, fromShelf, fromIndex)+ if (!field || fromShelf === toShelf) {+ return config+ }++ return addFieldToConfig(removeFieldFromConfig(config, fromShelf, fromIndex), field, toShelf)+}+function removeFieldFromConfig(config: BIConfig, shelf: BIShelf, index: number): BIConfig {switch (shelf) {case 'rows':@@ -131,27 +160,26 @@ function removeFieldFromConfig(config: BIConfig, shelf: BIShelf, index: number):}function setFieldExpressionInConfig(config: BIConfig, shelf: BIShelf, index: number, expression: string): BIConfig {+ const updateField = (field: BIField): BIField => ({ ...field, expression, name: expression.trim() })switch (shelf) {case 'rows':case 'columns':return {...config,- [shelf]: config[shelf].map((field, fieldIndex) =>- fieldIndex === index ? { ...field, expression } : field- ),+ [shelf]: config[shelf].map((field, fieldIndex) => (fieldIndex === index ? updateField(field) : field)),}case 'values':return {...config,values: config.values.map((value, valueIndex) =>- valueIndex === index ? { ...value, field: { ...value.field, expression } } : value+ valueIndex === index ? { ...value, field: updateField(value.field) } : value),}case 'filters':return {...config,filters: config.filters.map((filter, filterIndex) =>- filterIndex === index ? { ...filter, field: { ...filter.field, expression } } : filter+ filterIndex === index ? { ...filter, field: updateField(filter.field) } : filter),}}@@ -195,18 +223,49 @@ export interface biEditorLogicValues {databaseConnectionId: string | null // databaseTableListLogicdatabaseLoading: boolean // databaseTableListLogicposthogTables: DatabaseSchemaTable[] // databaseTableListLogic+ tableFieldsStatus: TableFieldsStatus // databaseTableListLogicactiveTab: QueryTab | null // sqlEditorLogicactiveDropShelf: BIShelf | nullactiveExpressionEditorId: string | null+ activeExpressionEditorTarget: 'aggregation' | 'field'+ autoUpdate: booleanavailableDataSources: BIDataSource[]+ chartFits: Partial<Record<ChartDisplayType, BIChartFit>>config: BIConfig+ dataPaneFields: BIDataPaneFields+ dataPaneFieldsError: boolean+ dataPaneFieldsLoading: boolean+ dataPaneSearch: string+ dragSessionId: stringeditorView: BIEditorView+ filteredDataPaneFields: BIDataPaneFieldsgeneratedQuery: BIQueryBuildResult | null+ hoveredChartType: ChartDisplayType | null+ selectableDataSources: BIDataSource[]+ showMeOpen: booleansortOptions: BISortOption[]}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface biEditorLogicActions {+ hydrateTableFields: (tableNames: string[]) => {+ tableNames: string[]+ } // databaseTableListLogic+ loadDatabaseSuccess: (+ database: Required<import('~/queries/schema/schema-general').DatabaseSchemaQueryResponse> | null,+ payload?:+ | {+ force?: boolean+ shallow?: boolean+ }+ | undefined+ ) => {+ database: Required<import('~/queries/schema/schema-general').DatabaseSchemaQueryResponse> | null+ payload?: {+ force?: boolean+ shallow?: boolean+ }+ } // databaseTableListLogicsetSourceQuery: (sourceQuery: import('~/queries/schema/schema-general').DataVisualizationNode) => {sourceQuery: import('~/queries/schema/schema-general').DataVisualizationNode} // sqlEditorLogic@@ -230,6 +289,15 @@ export interface biEditorLogicActions {clearActiveDropShelf: (shelf: BIShelf) => {shelf: BIShelf}+ moveFieldToShelf: (+ fromShelf: BIShelf,+ fromIndex: number,+ toShelf: BIShelf+ ) => {+ fromIndex: number+ fromShelf: BIShelf+ toShelf: BIShelf+ }persistState: (editorView: BIEditorView,config: BIConfig@@ -250,15 +318,28 @@ export interface biEditorLogicActions {restoreState: (state: BIEditorState) => {state: BIEditorState}- setActiveDropShelf: (shelf: BIShelf) => {- shelf: BIShelf+ runAfterChange: () => {+ value: true+ }+ setActiveDropShelf: (shelf: BIShelf | null) => {+ shelf: BIShelf | null}- setActiveExpressionEditorId: (fieldId: string | null) => {+ setActiveExpressionEditorId: (+ fieldId: string | null,+ target?: 'aggregation' | 'field'+ ) => {fieldId: string | null+ target: 'aggregation' | 'field'+ }+ setAutoUpdate: (autoUpdate: boolean) => {+ autoUpdate: boolean}setChartType: (chartType: ChartDisplayType) => {chartType: ChartDisplayType}+ setDataPaneSearch: (search: string) => {+ search: string+ }setDataSource: (source: BIDataSource) => {source: BIDataSource}@@ -304,9 +385,15 @@ export interface biEditorLogicActions {index: numbervalue: string}+ setHoveredChartType: (chartType: ChartDisplayType | null) => {+ chartType: ChartDisplayType | null+ }setLimit: (limit: BIQueryLimit) => {limit: 100 | 1000 | 10000 | 50000}+ setShowMeOpen: (showMeOpen: boolean) => {+ showMeOpen: boolean+ }setSort: (sort: BISort | null) => {sort: BISort | null}@@ -324,6 +411,9 @@ export interface biEditorLogicActions {customExpression: stringindex: number}+ swapRowsAndColumns: () => {+ value: true+ }syncGeneratedQuery: () => {value: true}@@ -338,8 +428,22 @@ export interface biEditorLogicMeta {posthogTables: DatabaseSchemaTable[],databaseConnectionId: string | null) => BIDataSource[]+ selectableDataSources: (availableDataSources: BIDataSource[], config: BIConfig) => BIDataSource[]generatedQuery: (config: BIConfig) => BIQueryBuildResult | nullsortOptions: (config: BIConfig) => BISortOption[]+ chartFits: (config: BIConfig) => Partial<Record<ChartDisplayType, BIChartFit>>+ dataPaneFields: (+ config: BIConfig,+ allTables: DatabaseSchemaTable[],+ databaseConnectionId: string | null+ ) => BIDataPaneFields+ dataPaneFieldsLoading: (+ config: BIConfig,+ tableFieldsStatus: TableFieldsStatus,+ databaseLoading: boolean+ ) => boolean+ dataPaneFieldsError: (config: BIConfig, tableFieldsStatus: TableFieldsStatus) => boolean+ filteredDataPaneFields: (dataPaneFields: BIDataPaneFields, dataPaneSearch: string) => BIDataPaneFields}}@@ -359,9 +463,20 @@ export const biEditorLogic = kea<biEditorLogicType>([sqlEditorLogic({ tabId: logicProps.tabId }),['activeTab'],databaseTableListLogic,- ['allTables', 'posthogTables', 'connectionId as databaseConnectionId', 'databaseLoading'],+ [+ 'allTables',+ 'posthogTables',+ 'connectionId as databaseConnectionId',+ 'databaseLoading',+ 'tableFieldsStatus',+ ],+ ],+ actions: [+ sqlEditorLogic({ tabId: logicProps.tabId }),+ ['setSourceQuery', 'syncUrlWithQuery', 'updateTab'],+ databaseTableListLogic,+ ['hydrateTableFields', 'loadDatabaseSuccess'],],- actions: [sqlEditorLogic({ tabId: logicProps.tabId }), ['setSourceQuery', 'syncUrlWithQuery', 'updateTab']],})),actions({setEditorView: (editorView: BIEditorView) => ({ editorView }),@@ -370,9 +485,23 @@ export const biEditorLogic = kea<biEditorLogicType>([addFieldToShelf: (field: BIField, shelf: BIShelf) => ({ field, shelf }),addBlankFieldToShelf: (shelf: BIShelf) => ({ shelf, fieldId: `bi-blank-${uuid()}` }),clearActiveDropShelf: (shelf: BIShelf) => ({ shelf }),+ moveFieldToShelf: (fromShelf: BIShelf, fromIndex: number, toShelf: BIShelf) => ({+ fromShelf,+ fromIndex,+ toShelf,+ }),+ swapRowsAndColumns: true,+ setAutoUpdate: (autoUpdate: boolean) => ({ autoUpdate }),+ setShowMeOpen: (showMeOpen: boolean) => ({ showMeOpen }),+ setHoveredChartType: (chartType: ChartDisplayType | null) => ({ chartType }),+ setDataPaneSearch: (search: string) => ({ search }),+ runAfterChange: true,removeFieldFromShelf: (shelf: BIShelf, index: number) => ({ shelf, index }),- setActiveDropShelf: (shelf: BIShelf) => ({ shelf }),- setActiveExpressionEditorId: (fieldId: string | null) => ({ fieldId }),+ setActiveDropShelf: (shelf: BIShelf | null) => ({ shelf }),+ setActiveExpressionEditorId: (fieldId: string | null, target: 'field' | 'aggregation' = 'field') => ({+ fieldId,+ target,+ }),setChartType: (chartType: ChartDisplayType) => ({ chartType }),setDataSource: (source: BIDataSource) => ({ source }),setValueAggregation: (index: number, aggregation: BIAggregation) => ({ index, aggregation }),@@ -391,7 +520,8 @@ export const biEditorLogic = kea<biEditorLogicType>([resetConfig: true,syncGeneratedQuery: true,}),- reducers({+ reducers(() => ({+ dragSessionId: [uuid(), {}],activeDropShelf: [null as BIShelf | null,{@@ -400,13 +530,40 @@ export const biEditorLogic = kea<biEditorLogicType>([activeDropShelf === shelf ? null : activeDropShelf,},],+ autoUpdate: [true, { persist: true }, { setAutoUpdate: (_, { autoUpdate }) => autoUpdate }],+ showMeOpen: [true, { persist: true }, { setShowMeOpen: (_, { showMeOpen }) => showMeOpen }],+ hoveredChartType: [+ null as ChartDisplayType | null,+ { setHoveredChartType: (_, { chartType }) => chartType, setShowMeOpen: () => null },+ ],+ activeExpressionEditorTarget: [+ 'field' as 'field' | 'aggregation',+ {+ setActiveExpressionEditorId: (_, { target }) => target,+ addBlankFieldToShelf: () => 'field',+ addFieldToShelf: () => 'field',+ },+ ],+ dataPaneSearch: [+ '',+ {+ setDataPaneSearch: (_, { search }) => search,+ setDataSource: () => '',+ },+ ],activeExpressionEditorId: [null as string | null,{- addBlankFieldToShelf: (_, { fieldId }) => fieldId,+ addBlankFieldToShelf: (_, { shelf, fieldId }) => getBIShelfEditorKey(shelf, fieldId),+ // Opens the filter editor as soon as a field lands on the filters shelf+ addFieldToShelf: (activeExpressionEditorId, { field, shelf }) =>+ shelf === 'filters' ? getBIShelfEditorKey('filters', field.id) : activeExpressionEditorId,setActiveExpressionEditorId: (_, { fieldId }) => fieldId,resetConfig: () => null,restoreState: () => null,+ removeFieldFromShelf: () => null,+ moveFieldToShelf: () => null,+ swapRowsAndColumns: () => null,setDataSource: () => null,setEditorView: () => null,},@@ -427,6 +584,10 @@ 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)),+ swapRowsAndColumns: (config) =>+ normalizeBIConfig({ ...config, rows: config.columns, columns: config.rows }),setChartType: (config, { chartType }) => normalizeBIConfig({ ...config, chartType }),setDataSource: (config, { source }) => setDataSourceInConfig(config, source),setValueAggregation: (config, { index, aggregation }) => ({@@ -472,7 +633,7 @@ export const biEditorLogic = kea<biEditorLogicType>([resetConfig: freshBIConfig,},],- }),+ })),selectors({availableDataSources: [(selectors) => [selectors.allTables, selectors.posthogTables, selectors.databaseConnectionId],@@ -491,6 +652,19 @@ export const biEditorLogic = kea<biEditorLogicType>([.sort((first, second) => first.table.localeCompare(second.table))},],+ selectableDataSources: [+ (selectors) => [selectors.availableDataSources, selectors.config],+ (availableDataSources: BIDataSource[], config: BIConfig): BIDataSource[] => {+ const source = config.source+ // Keeps the chosen table selectable while tables load, or after it leaves the list+ return !source ||+ availableDataSources.some(+ (candidate) => getBIDataSourceKey(candidate) === getBIDataSourceKey(source)+ )+ ? availableDataSources+ : [source, ...availableDataSources]+ },+ ],generatedQuery: [(selectors) => [selectors.config],(config: BIConfig): BIQueryBuildResult | null => buildBIQuery(config),@@ -499,8 +673,58 @@ export const biEditorLogic = kea<biEditorLogicType>([(selectors) => [selectors.config],(config: BIConfig): BISortOption[] => getBISortOptions(config),],+ chartFits: [+ (selectors) => [selectors.config],+ (config: BIConfig): Partial<Record<ChartDisplayType, BIChartFit>> =>+ Object.fromEntries(+ Object.values(ChartDisplayType).map((chartType) => [chartType, getBIChartFit(config, chartType)])+ ),+ ],+ dataPaneFields: [+ (selectors) => [selectors.config, selectors.allTables, selectors.databaseConnectionId],+ (+ config: BIConfig,+ allTables: DatabaseSchemaTable[],+ databaseConnectionId: string | null+ ): BIDataPaneFields =>+ config.source && (config.source.connectionId ?? null) === databaseConnectionId+ ? getBIDataPaneFields(+ allTables.find((table) => table.name === config.source?.table),+ config.source+ )+ : { dimensions: [], measures: [] },+ ],+ dataPaneFieldsLoading: [+ (selectors) => [selectors.config, selectors.tableFieldsStatus, selectors.databaseLoading],+ (config: BIConfig, tableFieldsStatus: TableFieldsStatus, databaseLoading: boolean): boolean =>+ !!config.source && (databaseLoading || tableFieldsStatus[config.source.table] === 'loading'),+ ],+ dataPaneFieldsError: [+ (selectors) => [selectors.config, selectors.tableFieldsStatus],+ (config: BIConfig, tableFieldsStatus: TableFieldsStatus): boolean =>+ !!config.source && tableFieldsStatus[config.source.table] === 'error',+ ],+ filteredDataPaneFields: [+ (selectors) => [selectors.dataPaneFields, selectors.dataPaneSearch],+ (dataPaneFields: BIDataPaneFields, dataPaneSearch: string): BIDataPaneFields => {+ const needle = dataPaneSearch.trim().toLowerCase()+ if (!needle) {+ return dataPaneFields+ }+ const matches = (field: BIField): boolean => field.name.toLowerCase().includes(needle)+ return {+ dimensions: dataPaneFields.dimensions.filter(matches),+ measures: dataPaneFields.measures.filter(matches),+ }+ },+ ],}),- listeners(({ actions, props: logicProps, values }) => ({+ listeners(({ actions, props: logicProps, values, cache }) => ({+ loadDatabaseSuccess: () => {+ if (values.config.source && (values.config.source.connectionId ?? null) === values.databaseConnectionId) {+ actions.hydrateTableFields([values.config.source.table])+ }+ },persistState: ({ editorView, config }) => {if (!values.activeTab) {return@@ -512,81 +736,99 @@ export const biEditorLogic = kea<biEditorLogicType>([actions.syncUrlWithQuery()},setEditorView: ({ editorView }) => {+ cache.autoUpdateRevision = (cache.autoUpdateRevision ?? 0) + 1captureBIEditorModeSelected(editorView, values.config)actions.persistState(editorView, values.config)if (editorView === BIEditorView.BI) {+ const connectionId = sqlEditorLogic({ tabId: logicProps.tabId }).values.selectedConnectionId+ if (values.config.source && (values.config.source.connectionId ?? null) !== (connectionId ?? null)) {+ actions.resetConfig()+ return+ }actions.syncGeneratedQuery()}},- addFieldToShelf: () => {- actions.persistState(values.editorView, values.config)- actions.syncGeneratedQuery()- },- addBlankFieldToShelf: () => {- actions.persistState(values.editorView, values.config)- actions.syncGeneratedQuery()- },- removeFieldFromShelf: () => {- actions.persistState(values.editorView, values.config)- actions.syncGeneratedQuery()- },- setChartType: () => {- actions.persistState(values.editorView, values.config)- actions.syncGeneratedQuery()- },- setDataSource: () => {- actions.persistState(values.editorView, values.config)- actions.syncGeneratedQuery()- },- setValueAggregation: () => {- actions.persistState(values.editorView, values.config)- actions.syncGeneratedQuery()- },- setFilterOperator: () => {- actions.persistState(values.editorView, values.config)- actions.syncGeneratedQuery()- },- setFilterValue: () => {- actions.persistState(values.editorView, values.config)- actions.syncGeneratedQuery()- },- setLimit: () => {- actions.persistState(values.editorView, values.config)- actions.syncGeneratedQuery()- },- setSort: () => {- actions.persistState(values.editorView, values.config)- actions.syncGeneratedQuery()- },- setFieldExpression: () => {- actions.persistState(values.editorView, values.config)- actions.syncGeneratedQuery()- },- setFieldDateBucket: () => {- actions.persistState(values.editorView, values.config)- actions.syncGeneratedQuery()- },- setValueCustomExpression: () => {- actions.persistState(values.editorView, values.config)- actions.syncGeneratedQuery()+ addFieldToShelf: () => actions.runAfterChange(),+ moveFieldToShelf: () => actions.runAfterChange(),+ swapRowsAndColumns: () => actions.runAfterChange(),+ setAutoUpdate: ({ autoUpdate }) => {+ cache.autoUpdateRevision = (cache.autoUpdateRevision ?? 0) + 1+ if (autoUpdate) {+ actions.runAfterChange()+ }},- setFilterCustomExpression: () => {+ runAfterChange: async (_, breakpoint) => {actions.persistState(values.editorView, values.config)actions.syncGeneratedQuery()+ if (!values.autoUpdate || values.editorView !== BIEditorView.BI || !values.generatedQuery) {+ return+ }+ const revision = cache.autoUpdateRevision+ // Debounced so typing a filter value or clicking through menus runs one query+ await breakpoint(400)+ if (+ !values.autoUpdate ||+ values.editorView !== BIEditorView.BI ||+ !values.generatedQuery ||+ revision !== cache.autoUpdateRevision+ ) {+ return+ }+ const editorLogic = sqlEditorLogic({ tabId: logicProps.tabId })+ const lastSource = editorLogic.values.lastRunQuery?.source+ const nextSource = values.generatedQuery.node.source+ const dataLogic = dataNodeLogic.findMounted({ key: `data-warehouse-editor-data-node-${logicProps.tabId}` })+ if (+ lastSource?.query === nextSource.query &&+ (lastSource.connectionId ?? null) === (nextSource.connectionId ?? null) &&+ dataLogic &&+ !dataLogic.values.queryCancelled &&+ !dataLogic.values.responseError &&+ (dataLogic.values.responseLoading || dataLogic.values.response)+ ) {+ return+ }+ editorLogic.actions.runQuery()},+ addBlankFieldToShelf: () => actions.runAfterChange(),+ removeFieldFromShelf: () => actions.runAfterChange(),+ setChartType: () => actions.runAfterChange(),+ setDataSource: () => actions.runAfterChange(),+ setValueAggregation: () => actions.runAfterChange(),+ setFilterOperator: () => actions.runAfterChange(),+ setFilterValue: () => actions.runAfterChange(),+ setLimit: () => actions.runAfterChange(),+ setSort: () => actions.runAfterChange(),+ setFieldExpression: () => actions.runAfterChange(),+ setFieldDateBucket: () => actions.runAfterChange(),+ setValueCustomExpression: () => actions.runAfterChange(),+ setFilterCustomExpression: () => actions.runAfterChange(),setSourceQuery: ({ sourceQuery }) => {if (!values.activeTab?.biEditorState && values.editorView === BIEditorView.SQL) {return}+ if (+ values.editorView === BIEditorView.BI &&+ values.config.source &&+ (values.config.source.connectionId ?? null) !== (sourceQuery.source.connectionId ?? null)+ ) {+ actions.resetConfig()+ return+ }actions.persistState(values.editorView, {...values.config,chartType: sourceQuery.display ?? values.config.chartType,})},resetConfig: () => {+ cache.autoUpdateRevision = (cache.autoUpdateRevision ?? 0) + 1actions.persistState(values.editorView, values.config)+ const dataLogic = dataNodeLogic.findMounted({ key: `data-warehouse-editor-data-node-${logicProps.tabId}` })+ dataLogic?.actions.cancelQuery()+ dataLogic?.actions.clearResponse()const editorLogic = sqlEditorLogic({ tabId: logicProps.tabId })const sourceQuery = editorLogic.values.sourceQuery+ editorLogic.actions.setLastRunQuery(null)editorLogic.actions.setQueryInput('')editorLogic.actions.setSourceQuery({...sourceQuery,@@ -623,6 +865,16 @@ export const biEditorLogic = kea<biEditorLogicType>([})},})),+ subscriptions(({ actions }) => ({+ config: (config: BIConfig, oldConfig: BIConfig | undefined) => {+ if (+ config.source &&+ (!oldConfig?.source || getBIDataSourceKey(config.source) !== getBIDataSourceKey(oldConfig.source))+ ) {+ actions.hydrateTableFields([config.source.table])+ }+ },+ })),afterMount(({ actions, values }) => {if (values.activeTab?.biEditorState) {actions.restoreState(values.activeTab.biEditorState)diff --git a/frontend/src/scenes/data-warehouse/editor/bi/biEditorOptions.tsx b/frontend/src/scenes/data-warehouse/editor/bi/biEditorOptions.tsxnew file mode 100644index 000000000000..4b1bf73e90fb--- /dev/null+++ b/frontend/src/scenes/data-warehouse/editor/bi/biEditorOptions.tsx@@ -0,0 +1,69 @@+import { IconGraph, IconLifecycle, IconMagicWand, IconPieChart, IconPulse, IconTrends } from '@posthog/icons'++import { FEATURE_FLAGS } from 'lib/constants'+import { Icon123, IconAreaChart, IconDonutChart, IconHeatmap, IconTableChart } from 'lib/lemon-ui/icons'+import { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'++import { ChartDisplayType } from '~/types'++import { BIAggregation, BIDateBucket, BIFilterOperator, BI_QUERY_LIMITS } from './biEditorTypes'++export const CHART_TYPE_OPTIONS: { value: ChartDisplayType; label: string; icon: JSX.Element }[] = [+ { value: ChartDisplayType.Auto, label: 'Automatic', icon: <IconMagicWand /> },+ { value: ChartDisplayType.ActionsTable, label: 'Table', icon: <IconTableChart /> },+ { value: ChartDisplayType.TwoDimensionalHeatmap, label: 'Pivot table', icon: <IconHeatmap /> },+ { value: ChartDisplayType.BoldNumber, label: 'Big number', icon: <Icon123 /> },+ { value: ChartDisplayType.Metric, label: 'Metric', icon: <IconPulse /> },+ { value: ChartDisplayType.ActionsLineGraph, label: 'Line chart', icon: <IconTrends /> },+ { value: ChartDisplayType.ActionsAreaGraph, label: 'Area chart', icon: <IconAreaChart /> },+ { value: ChartDisplayType.ActionsBar, label: 'Bar chart', icon: <IconGraph /> },+ { value: ChartDisplayType.ActionsStackedBar, label: 'Stacked bar chart', icon: <IconLifecycle /> },+ { value: ChartDisplayType.ActionsPie, label: 'Pie chart', icon: <IconPieChart /> },+ { value: ChartDisplayType.ActionsDonut, label: 'Donut chart', icon: <IconDonutChart /> },+]++export function getChartTypeOptions(featureFlags: FeatureFlagsSet): typeof CHART_TYPE_OPTIONS {+ return CHART_TYPE_OPTIONS.filter(+ (option) => option.value !== ChartDisplayType.Metric || !!featureFlags[FEATURE_FLAGS.METRIC_INSIGHT]+ )+}++export const AGGREGATION_OPTIONS: { value: BIAggregation; label: string }[] = [+ { value: 'sum', label: 'Sum' },+ { value: 'average', label: 'Average' },+ { value: 'minimum', label: 'Minimum' },+ { value: 'maximum', label: 'Maximum' },+ { value: 'count', label: 'Count' },+ { value: 'count_distinct', label: 'Count distinct' },+ { value: 'custom', label: 'SQL expression' },+]++export const NUMERIC_AGGREGATIONS: BIAggregation[] = ['sum', 'average', 'minimum', 'maximum']++export const FILTER_OPERATOR_OPTIONS: { value: BIFilterOperator; label: string }[] = [+ { value: 'equals', label: 'Equals' },+ { value: 'not_equals', label: 'Does not equal' },+ { value: 'contains', label: 'Contains' },+ { value: 'greater_than', label: 'Greater than' },+ { value: 'less_than', label: 'Less than' },+ { value: 'last_7_days', label: 'Last 7 days' },+ { value: 'is_set', label: 'Is set' },+ { value: 'is_not_set', label: 'Is not set' },+ { value: 'custom', label: 'SQL condition' },+]++export const DATE_BUCKET_OPTIONS: { value: BIDateBucket | null; label: string }[] = [+ { value: null, label: 'Exact date' },+ { value: 'minute', label: 'Minute' },+ { value: 'hour', label: 'Hour' },+ { value: 'day', label: 'Day' },+ { value: 'week', label: 'Week' },+ { value: 'month', label: 'Month' },+ { value: 'quarter', label: 'Quarter' },+ { value: 'year', label: 'Year' },+]++export const LIMIT_OPTIONS = BI_QUERY_LIMITS.map((limit) => ({+ value: limit,+ label: limit === 1000 ? '1k' : limit === 10000 ? '10k' : limit === 50000 ? '50k' : String(limit),+}))diff --git a/frontend/src/scenes/data-warehouse/editor/bi/biEditorTypes.test.ts b/frontend/src/scenes/data-warehouse/editor/bi/biEditorTypes.test.tsindex b238d655486e..85ac2f71de4a 100644--- a/frontend/src/scenes/data-warehouse/editor/bi/biEditorTypes.test.ts+++ b/frontend/src/scenes/data-warehouse/editor/bi/biEditorTypes.test.ts@@ -9,9 +9,13 @@ import {createDefaultDateFilter,defaultAggregationForField,getBIDataSourceKey,+ getBIChartFit,+ getBIDropTarget,getBIFieldId,getBISortOptions,+ getBIValueSortKey,isBIFieldCompatible,+ isBIMeasureField,parseBIEditorState,} from './biEditorTypes'@@ -388,6 +392,10 @@ describe('BI editor query generation', () => {`values:${revenueField.id}`,`values:${revenueField.id}:2`,])+ expect([0, 1].map((index) => getBIValueSortKey(twoAggregationsConfig, index))).toEqual([+ `values:${revenueField.id}`,+ `values:${revenueField.id}:2`,+ ])expect(buildBIQuery({...twoAggregationsConfig,@@ -396,6 +404,61 @@ describe('BI editor query generation', () => {).toContain('ORDER BY\n average_revenue_2 ASC')})+ const userIdField: BIField = { ...revenueField, id: 'warehouse:events:user_id', name: 'user_id', type: 'integer' }++ test.each([+ ['userId', false],+ ['accountId', false],+ ['userID', false],+ ['accountUuid', false],+ ['accountUUID', false],+ ['USER_ID', false],+ ['UUID', false],+ ['grid', true],+ ['paid', true],+ ])('classifies numeric field %s as a measure: %s', (name, isMeasure) => {+ const field = { ...userIdField, name }+ expect(isBIMeasureField(field)).toBe(isMeasure)+ expect(getBIDropTarget(field, 'rows').shelf).toBe(isMeasure ? 'values' : 'rows')+ })++ test.each([0, 1, 2])('checks pivot fit with %i measures', (measureCount) => {+ const pivotConfig: BIConfig = {+ ...sortableConfig,+ chartType: ChartDisplayType.TwoDimensionalHeatmap,+ rows: [browserField],+ columns: [countryField],+ values: Array.from({ length: measureCount }, () => ({ field: revenueField, aggregation: 'sum' })),+ }+ expect(getBIChartFit(pivotConfig, ChartDisplayType.TwoDimensionalHeatmap).fits).toBe(measureCount <= 1)+ expect(buildBIQuery(pivotConfig)?.node.chartSettings?.heatmap?.valueColumn).toBe(+ measureCount === 0 ? 'count' : 'sum_revenue'+ )+ })++ test.each([+ ['a measure dropped on rows becomes a value', revenueField, 'rows', revenueField, 'values'],+ ['a measure dropped on columns becomes a value', revenueField, 'columns', revenueField, 'values'],+ ['a measure dropped on filters stays a filter', revenueField, 'filters', revenueField, 'filters'],+ ['a numeric identifier stays a dimension', userIdField, 'rows', userIdField, 'rows'],+ [+ 'a timestamp on rows is bucketed by day',+ timestampField,+ 'rows',+ { ...timestampField, dateBucket: 'day' },+ 'rows',+ ],+ [+ 'a bucketed timestamp keeps its bucket',+ { ...timestampField, dateBucket: 'month' },+ 'columns',+ { ...timestampField, dateBucket: 'month' },+ 'columns',+ ],+ ] as const)('routes a dropped field: %s', (_, field, shelf, expectedField, expectedShelf) => {+ expect(getBIDropTarget(field as BIField, shelf)).toEqual({ field: expectedField, shelf: expectedShelf })+ })+test.each([['a state persisted before sort existed', {}, null],[diff --git a/frontend/src/scenes/data-warehouse/editor/bi/biEditorTypes.ts b/frontend/src/scenes/data-warehouse/editor/bi/biEditorTypes.tsindex a601e3f51c6d..e718db82de80 100644--- a/frontend/src/scenes/data-warehouse/editor/bi/biEditorTypes.ts+++ b/frontend/src/scenes/data-warehouse/editor/bi/biEditorTypes.ts@@ -1,4 +1,9 @@-import { DataVisualizationNode, DatabaseSerializedFieldType, NodeKind } from '~/queries/schema/schema-general'+import {+ DataVisualizationNode,+ DatabaseSchemaTable,+ DatabaseSerializedFieldType,+ NodeKind,+} from '~/queries/schema/schema-general'import { escapeDottedHogQLIdentifier, escapeHogQLString, escapePropertyAsHogQLIdentifier } from '~/queries/utils'import { ChartDisplayType } from '~/types'@@ -50,6 +55,11 @@ export function getBIDataSourceKey(source: BIDataSource): string {return JSON.stringify([source.connectionId ?? null, source.table])}+/** Keys an open editor by shelf too, because the same field can sit on several shelves at once. */+export function getBIShelfEditorKey(shelf: BIShelf, fieldId: string): string {+ return `${shelf}:${fieldId}`+}+export function getBIFieldId(source: BIDataSource, expression: string): string {return JSON.stringify([source.connectionId ?? null, source.table, expression])}@@ -187,6 +197,142 @@ export function defaultAggregationForField(field: BIField): BIAggregation {return isNumericBIField(field) ? 'sum' : 'count_distinct'}+const IDENTIFIER_FIELD_NAME_REGEX = /(^|_)(id|uuid)$/i++/** Numeric fields that are not identifiers aggregate by default, like measures in a BI tool. */+export function isBIMeasureField(field: BIField): boolean {+ return (+ isNumericBIField(field) &&+ defaultAggregationForField(field) !== 'count' &&+ !IDENTIFIER_FIELD_NAME_REGEX.test(field.name.replace(/([a-z0-9])([A-Z])/g, '$1_$2'))+ )+}++export const BI_SHELF_PILL_DRAG_MIME_TYPE = 'application/x-posthog-bi-shelf-pill'++export interface BIShelfPillDragData {+ shelf: BIShelf+ index: number+ dragSessionId: string+}++export function parseBIShelfPillDragData(serialized: string): BIShelfPillDragData | null {+ try {+ const candidate = JSON.parse(serialized) as Partial<BIShelfPillDragData>+ if (+ ['rows', 'columns', 'values', 'filters'].includes(candidate.shelf as string) &&+ typeof candidate.index === 'number' &&+ Number.isInteger(candidate.index) &&+ candidate.index >= 0 &&+ typeof candidate.dragSessionId === 'string'+ ) {+ return { shelf: candidate.shelf as BIShelf, index: candidate.index, dragSessionId: candidate.dragSessionId }+ }+ } catch {+ return null+ }+ return null+}++/**+ * Where a field dropped from the data pane lands. Measures dropped on rows or columns are aggregated+ * rather than grouped, and exact timestamps are bucketed by day so grouping stays readable.+ */+export function getBIDropTarget(field: BIField, shelf: BIShelf): { field: BIField; shelf: BIShelf } {+ if ((shelf === 'rows' || shelf === 'columns') && isBIMeasureField(field)) {+ return { field, shelf: 'values' }+ }+ if ((shelf === 'rows' || shelf === 'columns') && field.type === 'datetime' && !field.dateBucket) {+ return { field: { ...field, dateBucket: 'day' }, shelf }+ }+ return { field, shelf }+}++const DATA_PANE_FIELD_TYPES = new Set<DatabaseSerializedFieldType>([+ 'integer',+ 'float',+ 'decimal',+ 'string',+ 'datetime',+ 'date',+ 'boolean',+ 'array',+ 'json',+ 'expression',+ 'unknown',+])++export interface BIDataPaneFields {+ dimensions: BIField[]+ measures: BIField[]+}++export function getBIDataPaneFields(table: DatabaseSchemaTable | undefined, source: BIDataSource): BIDataPaneFields {+ const fields = Object.values(table?.fields ?? {})+ .filter((field) => DATA_PANE_FIELD_TYPES.has(field.type))+ .map((field): BIField => {+ const expression = escapeDottedHogQLIdentifier(field.name)+ return { id: getBIFieldId(source, expression), name: field.name, expression, type: field.type, source }+ })+ .sort((first, second) => first.name.localeCompare(second.name))++ return {+ dimensions: fields.filter((field) => !isBIMeasureField(field)),+ measures: fields.filter(isBIMeasureField),+ }+}++export interface BIChartFit {+ fits: boolean+ requirement: string+}++/** Mirrors the "Show me" panel of desktop BI tools: which chart types suit the fields on the shelves. */+export function getBIChartFit(config: BIConfig, chartType: ChartDisplayType): BIChartFit {+ const rowCount = config.rows.length+ const columnCount = config.columns.length+ const dimensionCount = rowCount + columnCount+ const hasDateDimension = [...config.rows, ...config.columns].some(isDateTimeBIField)++ switch (chartType) {+ case ChartDisplayType.Auto:+ return { fits: true, requirement: 'Picks a chart type from the query results' }+ case ChartDisplayType.ActionsTable:+ return { fits: true, requirement: 'any combination of fields' }+ case ChartDisplayType.ActionsLineGraph:+ case ChartDisplayType.ActionsAreaGraph:+ return {+ fits: hasDateDimension && dimensionCount <= 2,+ requirement: '1 date, up to 1 more dimension, and any measures',+ }+ case ChartDisplayType.ActionsBar:+ case ChartDisplayType.ActionsStackedBar:+ return {+ fits: dimensionCount >= 1 && dimensionCount <= 2,+ requirement: '1 or 2 dimensions, and any measures',+ }+ case ChartDisplayType.ActionsPie:+ case ChartDisplayType.ActionsDonut:+ return {+ fits: dimensionCount === 1 && config.values.length <= 1,+ requirement: '1 dimension and up to 1 measure',+ }+ case ChartDisplayType.TwoDimensionalHeatmap:+ return {+ fits: rowCount >= 1 && columnCount >= 1 && config.values.length <= 1,+ requirement: '1 or more dimensions on rows and on columns, and up to 1 measure',+ }+ case ChartDisplayType.BoldNumber:+ case ChartDisplayType.Metric:+ return {+ fits: dimensionCount === 0 && config.values.length <= 1,+ requirement: 'no dimensions and up to 1 measure',+ }+ default:+ return { fits: true, requirement: '' }+ }+}+export function createDefaultDateFilter(source: BIDataSource): BIFilter | null {if (source.connectionId) {return null@@ -588,6 +734,42 @@ export function getBISortOptions(config: BIConfig): BISortOption[] {})}+/** The sort option key for the value at `index`, matching the keys `getBISortOptions` returns. */+export function getBIValueSortKey(config: BIConfig, index: number): string | null {+ const value = config.values[index]+ if (!value || !aggregationExpression(value)) {+ return null+ }+ const occurrence = config.values+ .slice(0, index)+ .filter((previous) => previous.field.id === value.field.id && !!aggregationExpression(previous)).length+ return occurrence === 0 ? `values:${value.field.id}` : `values:${value.field.id}:${occurrence + 1}`+}++const PILL_AGGREGATION_PREFIXES: Record<Exclude<BIAggregation, 'custom'>, string> = {+ count: 'COUNT',+ count_distinct: 'COUNTD',+ sum: 'SUM',+ average: 'AVG',+ minimum: 'MIN',+ maximum: 'MAX',+}++export function getBIFieldPillLabel(field: BIField): string {+ const name = field.name || field.expression.trim()+ if (!name) {+ return 'New calculation'+ }+ return field.dateBucket ? `${field.dateBucket.toUpperCase()}(${name})` : name+}++export function getBIValuePillLabel(value: BIValue): string {+ if (value.aggregation === 'custom') {+ return value.customExpression?.trim() || 'New calculation'+ }+ return `${PILL_AGGREGATION_PREFIXES[value.aggregation]}(${getBIFieldPillLabel(value.field)})`+}+function buildOrderByExpression(config: BIConfig,dimensions: BIDimension[],diff --git a/frontend/src/scenes/data-warehouse/editor/bi/components/BIDataPane.tsx b/frontend/src/scenes/data-warehouse/editor/bi/components/BIDataPane.tsxnew file mode 100644index 000000000000..7dcb334ff788--- /dev/null+++ b/frontend/src/scenes/data-warehouse/editor/bi/components/BIDataPane.tsx@@ -0,0 +1,228 @@+import { useActions, useValues } from 'kea'++import { IconCalendar, IconDatabase } from '@posthog/icons'+import { LemonButton, LemonInput, LemonSearchableSelect, Spinner } from '@posthog/lemon-ui'++import { cn } from 'lib/utils/css-classes'++import { editorSizingLogic } from '../../editorSizingLogic'+import { queryDatabaseLogic } from '../../sidebar/queryDatabaseLogic'+import { biEditorLogic } from '../biEditorLogic'+import {+ BIField,+ BI_FIELD_DRAG_MIME_TYPE,+ getBIDataSourceKey,+ getBIDropTarget,+ serializeBIField,+} from '../biEditorTypes'++function FieldTypeGlyph({ field, measure }: { field: BIField; measure: boolean }): JSX.Element {+ const glyph =+ field.type === 'date' || field.type === 'datetime' ? (+ <IconCalendar />+ ) : measure || ['integer', 'float', 'decimal'].includes(field.type) ? (+ '#'+ ) : field.type === 'boolean' ? (+ 'T|F'+ ) : field.type === 'json' || field.type === 'array' ? (+ '{ }'+ ) : (+ 'Abc'+ )+ return (+ <span+ className={cn(+ 'flex w-7 shrink-0 justify-center font-mono text-[10px] font-semibold',+ measure ? 'text-success' : 'text-brand-blue'+ )}+ >+ {glyph}+ </span>+ )+}++function DataPaneSection({+ title,+ fields,+ measure,+ emptyText,+}: {+ title: string+ fields: BIField[]+ measure: boolean+ emptyText: string+}): JSX.Element {+ const { addFieldToShelf } = useActions(biEditorLogic)++ const addField = (field: BIField): void => {+ const target = getBIDropTarget(field, 'rows')+ addFieldToShelf(target.field, target.shelf)+ }++ return (+ <div className="flex flex-col">+ <div className="px-2 pb-1 pt-2 text-xs font-semibold text-secondary">{title}</div>+ {fields.length === 0 ? <span className="px-2 text-xs text-tertiary">{emptyText}</span> : null}+ {fields.map((field) => (+ <button+ key={field.id}+ type="button"+ draggable+ title={field.name}+ className={cn(+ 'flex h-6 w-full cursor-grab items-center gap-1 rounded px-1 text-left text-xs hover:bg-fill-highlight-100',+ 'focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent'+ )}+ onDragStart={(event) => {+ event.dataTransfer.effectAllowed = 'copy'+ event.dataTransfer.setData(BI_FIELD_DRAG_MIME_TYPE, serializeBIField(field))+ }}+ onDoubleClick={() => addField(field)}+ onKeyDown={(event) => {+ if (event.key === 'Enter') {+ addField(field)+ }+ }}+ data-attr={measure ? 'bi-editor-data-pane-measure' : 'bi-editor-data-pane-dimension'}+ >+ <FieldTypeGlyph field={field} measure={measure} />+ <span className="truncate">{field.name}</span>+ </button>+ ))}+ </div>+ )+}++/** Lists the selected table's fields as dimensions and measures, ready to drag onto shelves. */+export function BIDataPane(): JSX.Element {+ const {+ availableDataSources,+ config,+ databaseLoading,+ dataPaneFields,+ dataPaneFieldsLoading,+ dataPaneFieldsError,+ dataPaneSearch,+ filteredDataPaneFields,+ selectableDataSources,+ } = useValues(biEditorLogic)+ const { hydrateTableFields, setDataPaneSearch, setDataSource } = useActions(biEditorLogic)+ const { setDatabaseTreeCollapsed } = useActions(editorSizingLogic)+ const { locateTable } = useActions(queryDatabaseLogic)++ 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">+ <div className="flex items-center justify-between gap-1 px-2 pt-2">+ <span className="text-sm font-semibold">Data</span>+ <LemonButton+ type="tertiary"+ size="xsmall"+ disabledReason={!config.source ? 'Select a data source first' : undefined}+ tooltip="Show this table in the database tree"+ onClick={() => {+ if (config.source) {+ setDatabaseTreeCollapsed(false)+ locateTable(config.source.table)+ }+ }}+ >+ Locate+ </LemonButton>+ </div>+ <div className="flex flex-col gap-1.5 p-2">+ <LemonSearchableSelect+ value={config.source ? getBIDataSourceKey(config.source) : undefined}+ options={selectableDataSources.map((source) => ({+ value: getBIDataSourceKey(source),+ label: source.table,+ }))}+ onSelect={(sourceKey) => {+ const source = selectableDataSources.find(+ (candidate) => getBIDataSourceKey(candidate) === sourceKey+ )+ if (source) {+ setDataSource(source)+ }+ }}+ icon={<IconDatabase />}+ loading={databaseLoading}+ disabledReason={+ !databaseLoading && availableDataSources.length === 0+ ? 'No tables available for this connection'+ : undefined+ }+ placeholder="Select a table"+ searchPlaceholder="Search tables"+ searchInputDataAttr="bi-editor-data-source-search"+ noResultsMessage="No matching tables"+ size="small"+ fullWidth+ truncateText={{ maxWidthClass: 'max-w-full' }}+ dropdownMaxContentWidth+ data-attr="bi-editor-data-source"+ />+ {config.source ? (+ <LemonInput+ type="search"+ size="small"+ value={dataPaneSearch}+ onChange={setDataPaneSearch}+ placeholder="Search fields"+ aria-label="Search fields"+ />+ ) : null}+ </div>+ <div className="min-h-0 flex-1 overflow-y-auto px-1 pb-2">+ {!config.source ? (+ <p className="px-2 text-xs text-secondary">+ Select a table to list its fields. You can also drag columns from the database tree.+ </p>+ ) : dataPaneFieldsLoading && !hasFields ? (+ <div className="flex items-center gap-2 px-2 text-xs text-secondary">+ <Spinner /> Loading fields+ </div>+ ) : dataPaneFieldsError ? (+ <div className="flex flex-col items-start gap-2 px-2 text-xs text-secondary">+ <span>Couldn't load fields for this table.</span>+ <LemonButton+ size="xsmall"+ type="secondary"+ loading={dataPaneFieldsLoading}+ onClick={() => config.source && hydrateTableFields([config.source.table])}+ >+ Retry+ </LemonButton>+ </div>+ ) : !hasFields ? (+ <p className="px-2 text-xs text-secondary">+ No fields found. Drag columns from the database tree instead.+ </p>+ ) : !hasMatches ? (+ <p className="px-2 text-xs text-secondary">No matching fields</p>+ ) : (+ <>+ <DataPaneSection+ title="Dimensions"+ fields={filteredDataPaneFields.dimensions}+ measure={false}+ emptyText="No matching dimensions"+ />+ <DataPaneSection+ title="Measures"+ fields={filteredDataPaneFields.measures}+ measure+ emptyText={+ dataPaneSearch+ ? 'No matching measures'+ : 'No measures listed. Add a dimension to Rows, then choose Convert to measure from its menu.'+ }+ />+ </>+ )}+ </div>+ </div>+ )+}diff --git a/frontend/src/scenes/data-warehouse/editor/bi/components/BIExpressionPopover.tsx b/frontend/src/scenes/data-warehouse/editor/bi/components/BIExpressionPopover.tsxnew file mode 100644index 000000000000..f3d6f7fb0b1b--- /dev/null+++ b/frontend/src/scenes/data-warehouse/editor/bi/components/BIExpressionPopover.tsx@@ -0,0 +1,55 @@+import { LemonDropdown } from '@posthog/lemon-ui'++import { HogQLEditor } from 'lib/components/HogQLEditor/HogQLEditor'++import { NodeKind } from '~/queries/schema/schema-general'+import { escapeDottedHogQLIdentifier } from '~/queries/utils'++import { BIDataSource } from '../biEditorTypes'++export function BIExpressionPopover({+ visible,+ value,+ source,+ placeholder,+ onChange,+ onClose,+ children,+}: {+ visible: boolean+ value: string+ source: BIDataSource+ placeholder?: string+ onChange: (value: string) => void+ onClose: () => void+ children: React.ReactElement+}): JSX.Element {+ return (+ <LemonDropdown+ visible={visible}+ closeOnClickInside={false}+ // The trigger opens a menu of its own, so only closing is handled here+ onVisibilityChange={(nextVisible) => !nextVisible && onClose()}+ placement="bottom-start"+ overlay={+ <div className="w-120 max-w-[max(60vw,20rem)]">+ <HogQLEditor+ value={value}+ placeholder={placeholder}+ metadataSource={{+ kind: NodeKind.HogQLQuery,+ query: `SELECT * FROM ${escapeDottedHogQLIdentifier(source.table)}`,+ connectionId: source.connectionId,+ }}+ onChange={(nextValue) => {+ onChange(nextValue)+ onClose()+ }}+ />+ </div>+ }+ >+ {children}+ </LemonDropdown>+ )+}diff --git a/frontend/src/scenes/data-warehouse/editor/bi/components/BIFieldPill.tsx b/frontend/src/scenes/data-warehouse/editor/bi/components/BIFieldPill.tsxnew file mode 100644index 000000000000..68374e28ef1a--- /dev/null+++ b/frontend/src/scenes/data-warehouse/editor/bi/components/BIFieldPill.tsx@@ -0,0 +1,165 @@+import { useActions, useValues } from 'kea'++import { IconArrowDown, IconArrowUp } from 'lib/lemon-ui/icons'+import { LemonMenu, LemonMenuItems } from 'lib/lemon-ui/LemonMenu'++import { biEditorLogic } from '../biEditorLogic'+import { AGGREGATION_OPTIONS, DATE_BUCKET_OPTIONS, NUMERIC_AGGREGATIONS } from '../biEditorOptions'+import {+ BIShelf,+ getBIFieldPillLabel,+ getBIShelfEditorKey,+ getBIValuePillLabel,+ getBIValueSortKey,+ isDateTimeBIField,+ isNumericBIField,+} from '../biEditorTypes'+import { BIExpressionPopover } from './BIExpressionPopover'+import { BIPill } from './BIPill'++type ExpressionTarget = 'field' | 'aggregation'++/** A dimension on rows or columns, or a measure from the values shelf. */+export function BIFieldPill({+ shelf,+ index,+}: {+ shelf: Exclude<BIShelf, 'filters'>+ index: number+}): JSX.Element | null {+ const { config, activeExpressionEditorId, activeExpressionEditorTarget, sortOptions } = useValues(biEditorLogic)+ const {+ addFieldToShelf,+ moveFieldToShelf,+ removeFieldFromShelf,+ setActiveExpressionEditorId,+ setFieldDateBucket,+ setFieldExpression,+ setSort,+ setValueAggregation,+ setValueCustomExpression,+ } = useActions(biEditorLogic)++ const value = shelf === 'values' ? config.values[index] : null+ const field = value ? value.field : shelf === 'values' ? null : config[shelf][index]+ if (!field) {+ return null+ }++ const isMeasure = shelf === 'values'+ const occurrence = isMeasure+ ? config.values.slice(0, index).filter((previous) => previous.field.id === field.id).length+ : 0+ const editorKey = `${getBIShelfEditorKey(shelf, field.id)}${occurrence ? `:${occurrence + 1}` : ''}`+ const expressionTarget = activeExpressionEditorId === editorKey ? activeExpressionEditorTarget : null+ const setEditing = (target: ExpressionTarget): void => setActiveExpressionEditorId(editorKey, target)+ const candidateSortKey = isMeasure ? getBIValueSortKey(config, index) : `${shelf}:${field.id}`+ const sortKey = sortOptions.some((option) => option.key === candidateSortKey) ? candidateSortKey : null+ const otherDimensionShelf = shelf === 'rows' ? 'columns' : 'rows'+ const label = value ? getBIValuePillLabel(value) : getBIFieldPillLabel(field)+ const incomplete = value?.aggregation === 'custom' ? !value.customExpression?.trim() : !field.expression.trim()++ const items: LemonMenuItems = [+ isMeasure && value+ ? {+ title: 'Measure',+ items: AGGREGATION_OPTIONS.map((option) => ({+ label: option.label,+ active: value.aggregation === option.value,+ disabledReason:+ !isNumericBIField(field) && NUMERIC_AGGREGATIONS.includes(option.value)+ ? 'This calculation needs a numeric field'+ : undefined,+ onClick: () => {+ setValueAggregation(index, option.value)+ if (option.value === 'custom' && !value.customExpression) {+ setEditing('aggregation')+ }+ },+ })),+ }+ : null,+ isDateTimeBIField(field)+ ? {+ title: 'Date',+ items: DATE_BUCKET_OPTIONS.map((option) => ({+ label: option.label,+ active: (field.dateBucket ?? null) === option.value,+ onClick: () => setFieldDateBucket(shelf, index, option.value),+ })),+ }+ : null,+ {+ items: [+ { label: 'Edit field expression', onClick: () => setEditing('field') },+ value?.aggregation === 'custom'+ ? { label: 'Edit SQL aggregation', onClick: () => setEditing('aggregation') }+ : null,+ sortKey+ ? {+ label: 'Sort ascending',+ icon: <IconArrowUp />,+ onClick: () => setSort({ key: sortKey, direction: 'asc' }),+ }+ : null,+ sortKey+ ? {+ label: 'Sort descending',+ icon: <IconArrowDown />,+ onClick: () => setSort({ key: sortKey, direction: 'desc' }),+ }+ : null,+ ],+ },+ {+ items: [+ isMeasure+ ? { label: 'Convert to dimension', onClick: () => moveFieldToShelf('values', index, 'rows') }+ : { label: 'Convert to measure', onClick: () => moveFieldToShelf(shelf, index, 'values') },+ !isMeasure+ ? {+ label: `Move to ${otherDimensionShelf}`,+ onClick: () => moveFieldToShelf(shelf, index, otherDimensionShelf),+ }+ : null,+ { label: 'Add to filters', onClick: () => addFieldToShelf(field, 'filters') },+ ],+ },+ {+ items: [{ label: 'Remove', status: 'danger', onClick: () => removeFieldFromShelf(shelf, index) }],+ },+ ]++ return (+ <BIExpressionPopover+ visible={expressionTarget !== null}+ value={expressionTarget === 'aggregation' ? (value?.customExpression ?? '') : field.expression}+ source={field.source}+ placeholder={expressionTarget === 'aggregation' ? 'For example: sum(amount) / count()' : undefined}+ onChange={(nextExpression) =>+ expressionTarget === 'aggregation'+ ? setValueCustomExpression(index, nextExpression)+ : setFieldExpression(shelf, index, nextExpression)+ }+ onClose={() => {+ if (activeExpressionEditorId === editorKey) {+ setActiveExpressionEditorId(null)+ }+ }}+ >+ <span className="inline-flex min-w-0 max-w-[min(18rem,100%)]">+ <LemonMenu items={items} placement="bottom-start">+ <BIPill+ kind={isMeasure ? 'measure' : 'dimension'}+ label={label}+ shelf={shelf}+ index={index}+ incomplete={incomplete}+ aria-label={`${label} options`}+ data-attr={`bi-editor-${shelf}-pill`}+ />+ </LemonMenu>+ </span>+ </BIExpressionPopover>+ )+}diff --git a/frontend/src/scenes/data-warehouse/editor/bi/components/BIFilterEditor.tsx b/frontend/src/scenes/data-warehouse/editor/bi/components/BIFilterEditor.tsxnew file mode 100644index 000000000000..17dbefd1bbbd--- /dev/null+++ b/frontend/src/scenes/data-warehouse/editor/bi/components/BIFilterEditor.tsx@@ -0,0 +1,148 @@+import { useActions, useValues } from 'kea'++import { IconPencil } from '@posthog/icons'+import { LemonButton, LemonInput, LemonLabel, LemonSelect } from '@posthog/lemon-ui'++import { HogQLDropdown } from 'lib/components/HogQLDropdown/HogQLDropdown'+import { dayjs } from 'lib/dayjs'+import { LemonCalendarSelectInput } from 'lib/lemon-ui/LemonCalendar/LemonCalendarSelect'++import { biEditorLogic } from '../biEditorLogic'+import { DATE_BUCKET_OPTIONS, FILTER_OPERATOR_OPTIONS } from '../biEditorOptions'+import { isDateTimeBIField } from '../biEditorTypes'++export function BIFilterEditor({ index, onDone }: { index: number; onDone: () => void }): JSX.Element | null {+ const { config } = useValues(biEditorLogic)+ const {+ removeFieldFromShelf,+ setFieldDateBucket,+ setFieldExpression,+ setFilterCustomExpression,+ setFilterOperator,+ setFilterValue,+ } = useActions(biEditorLogic)+ const filter = config.filters[index]+ if (!filter) {+ return null+ }++ const { field } = filter+ const needsValue = !['last_7_days', 'is_set', 'is_not_set', 'custom'].includes(filter.operator)+ const includesTime = field.type === 'datetime'+ const selectedDate = filter.value && dayjs(filter.value).isValid() ? dayjs(filter.value) : null++ return (+ <div className="flex w-80 flex-col gap-3 p-1">+ <div className="flex flex-col gap-1">+ <LemonLabel>Field</LemonLabel>+ <HogQLDropdown+ hogQLValue={field.expression}+ onHogQLValueChange={(expression) => setFieldExpression('filters', index, expression)}+ tableName={field.source.table}+ connectionId={field.source.connectionId}+ size="small"+ buttonIcon={<IconPencil />}+ buttonLabel={+ field.expression ? <code className="truncate">{field.expression}</code> : 'Select field'+ }+ buttonAriaLabel={`Edit field expression for ${field.name || 'field'}`}+ />+ </div>+ {isDateTimeBIField(field) ? (+ <div className="flex flex-col gap-1">+ <LemonLabel>Date part</LemonLabel>+ <LemonSelect+ value={field.dateBucket ?? null}+ options={DATE_BUCKET_OPTIONS}+ onChange={(dateBucket) => setFieldDateBucket('filters', index, dateBucket)}+ size="small"+ data-attr="bi-editor-date-bucket"+ />+ </div>+ ) : null}+ <div className="flex flex-col gap-1">+ <LemonLabel>Condition</LemonLabel>+ <LemonSelect+ value={filter.operator}+ options={FILTER_OPERATOR_OPTIONS.map((option) => ({+ ...option,+ disabledReason:+ option.value === 'last_7_days' && !isDateTimeBIField(field)+ ? 'Choose a date or date-time field'+ : undefined,+ }))}+ onChange={(operator) => setFilterOperator(index, operator)}+ size="small"+ />+ </div>+ {filter.operator === 'custom' ? (+ <div className="flex flex-col gap-1">+ <LemonLabel>SQL condition</LemonLabel>+ <HogQLDropdown+ hogQLValue={filter.customExpression ?? ''}+ onHogQLValueChange={(customExpression) => setFilterCustomExpression(index, customExpression)}+ tableName={field.source.table}+ connectionId={field.source.connectionId}+ size="small"+ buttonIcon={<IconPencil />}+ buttonLabel={+ filter.customExpression ? (+ <code className="truncate">{filter.customExpression}</code>+ ) : (+ 'Add SQL condition'+ )+ }+ buttonAriaLabel="Edit filter SQL condition"+ />+ </div>+ ) : needsValue ? (+ <div className="flex flex-col gap-1">+ <LemonLabel>Value</LemonLabel>+ {isDateTimeBIField(field) ? (+ <LemonCalendarSelectInput+ value={selectedDate}+ onChange={(date) =>+ setFilterValue(+ index,+ date?.format(includesTime ? 'YYYY-MM-DD HH:mm:ss' : 'YYYY-MM-DD') ?? ''+ )+ }+ granularity={includesTime ? 'minute' : 'day'}+ format={includesTime ? 'MMM D, YYYY HH:mm' : 'MMM D, YYYY'}+ use24HourFormat+ clearable+ placeholder={includesTime ? 'Select date and time' : 'Select date'}+ buttonProps={{ size: 'small', 'aria-label': `${field.name} filter date` }}+ />+ ) : (+ <LemonInput+ value={filter.value}+ onChange={(value) => setFilterValue(index, value)}+ onPressEnter={onDone}+ placeholder="Value"+ aria-label={`${field.name} filter value`}+ size="small"+ autoFocus+ />+ )}+ </div>+ ) : null}+ <div className="flex justify-between gap-2">+ <LemonButton+ type="tertiary"+ status="danger"+ size="small"+ onClick={() => {+ removeFieldFromShelf('filters', index)+ onDone()+ }}+ >+ Remove filter+ </LemonButton>+ <LemonButton type="primary" size="small" onClick={onDone} data-attr="bi-editor-filter-done">+ Done+ </LemonButton>+ </div>+ </div>+ )+}diff --git a/frontend/src/scenes/data-warehouse/editor/bi/components/BIFilterPill.tsx b/frontend/src/scenes/data-warehouse/editor/bi/components/BIFilterPill.tsxnew file mode 100644index 000000000000..6853c813defd--- /dev/null+++ b/frontend/src/scenes/data-warehouse/editor/bi/components/BIFilterPill.tsx@@ -0,0 +1,61 @@+import { useActions, useValues } from 'kea'++import { LemonDropdown } from '@posthog/lemon-ui'++import { biEditorLogic } from '../biEditorLogic'+import { FILTER_OPERATOR_OPTIONS } from '../biEditorOptions'+import { BIFilter, getBIFieldPillLabel, getBIShelfEditorKey } from '../biEditorTypes'+import { BIFilterEditor } from './BIFilterEditor'+import { BIPill } from './BIPill'++function filterSummary(filter: BIFilter): string | undefined {+ const operatorLabel = FILTER_OPERATOR_OPTIONS.find((option) => option.value === filter.operator)?.label+ if (filter.operator === 'custom') {+ return filter.customExpression?.trim() || undefined+ }+ if (['last_7_days', 'is_set', 'is_not_set'].includes(filter.operator)) {+ return operatorLabel?.toLowerCase()+ }+ return filter.value.trim() ? `${operatorLabel?.toLowerCase()} ${filter.value}` : undefined+}++export function BIFilterPill({ index }: { index: number }): JSX.Element | null {+ const { config, activeExpressionEditorId } = useValues(biEditorLogic)+ const { setActiveExpressionEditorId } = useActions(biEditorLogic)+ const filter = config.filters[index]+ if (!filter) {+ return null+ }++ const editorKey = getBIShelfEditorKey('filters', filter.field.id)+ const visible = activeExpressionEditorId === editorKey+ const close = (): void => {+ if (activeExpressionEditorId === editorKey) {+ setActiveExpressionEditorId(null)+ }+ }+ const label = getBIFieldPillLabel(filter.field)+ const summary = filterSummary(filter)++ return (+ <LemonDropdown+ visible={visible}+ onVisibilityChange={(nextVisible) => (nextVisible ? setActiveExpressionEditorId(editorKey) : close())}+ closeOnClickInside={false}+ placement="right-start"+ overlay={<BIFilterEditor index={index} onDone={close} />}+ >+ <BIPill+ kind="filter"+ label={label}+ detail={summary}+ shelf="filters"+ index={index}+ incomplete={!filter.field.expression.trim() && !filter.customExpression?.trim()}+ className="w-full justify-between"+ aria-label={`${label} filter`}+ data-attr="bi-editor-filters-pill"+ />+ </LemonDropdown>+ )+}diff --git a/frontend/src/scenes/data-warehouse/editor/bi/components/BIFiltersCard.tsx b/frontend/src/scenes/data-warehouse/editor/bi/components/BIFiltersCard.tsxnew file mode 100644index 000000000000..bbc57ee9b978--- /dev/null+++ b/frontend/src/scenes/data-warehouse/editor/bi/components/BIFiltersCard.tsx@@ -0,0 +1,36 @@+import { useActions, useValues } from 'kea'++import { IconPlus } from '@posthog/icons'+import { LemonButton } from '@posthog/lemon-ui'++import { biEditorLogic } from '../biEditorLogic'+import { BIFilterPill } from './BIFilterPill'+import { BIShelfCard } from './BIShelfCard'+import { BIShelfDropTarget } from './BIShelfDropTarget'++export function BIFiltersCard(): JSX.Element {+ const { config } = useValues(biEditorLogic)+ const { addBlankFieldToShelf } = useActions(biEditorLogic)++ return (+ <BIShelfCard title="Filters">+ <BIShelfDropTarget shelf="filters" className="flex min-h-12 flex-col gap-1 border border-dashed p-1">+ {config.filters.length > 0 ? (+ config.filters.map((filter, index) => <BIFilterPill key={filter.field.id} index={index} />)+ ) : (+ <span className="p-1 text-xs text-tertiary">Drop fields here to filter rows</span>+ )}+ </BIShelfDropTarget>+ <LemonButton+ icon={<IconPlus />}+ size="xsmall"+ type="tertiary"+ disabledReason={!config.source ? 'Select a data source first' : undefined}+ onClick={() => addBlankFieldToShelf('filters')}+ data-attr="bi-editor-filters-add-field"+ >+ Add a calculated filter+ </LemonButton>+ </BIShelfCard>+ )+}diff --git a/frontend/src/scenes/data-warehouse/editor/bi/components/BIMarksCard.tsx b/frontend/src/scenes/data-warehouse/editor/bi/components/BIMarksCard.tsxnew file mode 100644index 000000000000..dcd541a77caf--- /dev/null+++ b/frontend/src/scenes/data-warehouse/editor/bi/components/BIMarksCard.tsx@@ -0,0 +1,36 @@+import { useActions, useValues } from 'kea'++import { LemonSelect } from '@posthog/lemon-ui'++import { featureFlagLogic } from 'lib/logic/featureFlagLogic'++import { biEditorLogic } from '../biEditorLogic'+import { getChartTypeOptions } from '../biEditorOptions'+import { BIShelfCard } from './BIShelfCard'++export function BIMarksCard(): JSX.Element {+ const { config } = useValues(biEditorLogic)+ const { setChartType } = useActions(biEditorLogic)+ const { featureFlags } = useValues(featureFlagLogic)++ return (+ <BIShelfCard title="Marks">+ <LemonSelect+ value={config.chartType}+ options={getChartTypeOptions(featureFlags).map((option) => ({+ value: option.value,+ label: option.label,+ icon: option.icon,+ }))}+ onChange={setChartType}+ size="small"+ fullWidth+ aria-label="Mark type"+ data-attr="bi-editor-mark-type"+ />+ <span className="text-xs text-secondary">+ Measures on rows set the values. Change how a measure is calculated from its menu.+ </span>+ </BIShelfCard>+ )+}diff --git a/frontend/src/scenes/data-warehouse/editor/bi/components/BIPill.tsx b/frontend/src/scenes/data-warehouse/editor/bi/components/BIPill.tsxnew file mode 100644index 000000000000..b71f33b4aa32--- /dev/null+++ b/frontend/src/scenes/data-warehouse/editor/bi/components/BIPill.tsx@@ -0,0 +1,57 @@+import { useValues } from 'kea'+import { forwardRef } from 'react'++import { IconChevronDown } from '@posthog/icons'++import { cn } from 'lib/utils/css-classes'++import { biEditorLogic } from '../biEditorLogic'+import { BIShelf, BI_SHELF_PILL_DRAG_MIME_TYPE, BIShelfPillDragData } from '../biEditorTypes'++export type BIPillKind = 'dimension' | 'measure' | 'filter'++export interface BIPillProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {+ kind: BIPillKind+ label: string+ detail?: string+ shelf: BIShelf+ index: number+ incomplete?: boolean+}++/** A draggable field on a shelf. Blue for dimensions, green for measures, like desktop BI tools. */+export const BIPill = forwardRef<HTMLButtonElement, BIPillProps>(function BIPill(+ { kind, label, detail, shelf, index, incomplete, className, ...buttonProps },+ ref+) {+ const { dragSessionId } = useValues(biEditorLogic)+ return (+ <button+ ref={ref}+ type="button"+ draggable+ onDragStart={(event) => {+ const dragData: BIShelfPillDragData = { shelf, index, dragSessionId }+ event.dataTransfer.effectAllowed = 'move'+ event.dataTransfer.setData(BI_SHELF_PILL_DRAG_MIME_TYPE, JSON.stringify(dragData))+ }}+ className={cn(+ 'inline-flex h-6 min-w-0 max-w-full cursor-grab items-center gap-1 rounded border px-2 text-xs font-semibold',+ 'focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-accent',+ incomplete+ ? 'border-dashed border-primary bg-surface-primary text-secondary'+ : kind === 'measure'+ ? 'border-transparent bg-success text-white hover:opacity-90'+ : kind === 'dimension'+ ? 'border-transparent bg-brand-blue text-white hover:opacity-90'+ : 'border-primary bg-surface-primary text-primary hover:bg-fill-highlight-100',+ className+ )}+ {...buttonProps}+ >+ <span className="truncate">{label}</span>+ {detail ? <span className="truncate font-normal opacity-80">{detail}</span> : null}+ <IconChevronDown className="shrink-0 opacity-70" />+ </button>+ )+})diff --git a/frontend/src/scenes/data-warehouse/editor/bi/components/BIShelfCard.tsx b/frontend/src/scenes/data-warehouse/editor/bi/components/BIShelfCard.tsxnew file mode 100644index 000000000000..afa5cc5b5796--- /dev/null+++ b/frontend/src/scenes/data-warehouse/editor/bi/components/BIShelfCard.tsx@@ -0,0 +1,11 @@+import type { ReactNode } from 'react'++/** A titled card in the column next to the data pane, like the Filters and Marks cards. */+export function BIShelfCard({ title, children }: { title: string; children: ReactNode }): JSX.Element {+ return (+ <section className="flex flex-col gap-1.5 border-b p-2">+ <h3 className="m-0 text-sm font-semibold">{title}</h3>+ {children}+ </section>+ )+}diff --git a/frontend/src/scenes/data-warehouse/editor/bi/components/BIShelfDropTarget.tsx b/frontend/src/scenes/data-warehouse/editor/bi/components/BIShelfDropTarget.tsxnew file mode 100644index 000000000000..7cc36ae8ba4b--- /dev/null+++ b/frontend/src/scenes/data-warehouse/editor/bi/components/BIShelfDropTarget.tsx@@ -0,0 +1,90 @@+import { useActions, useValues } from 'kea'+import type { DragEvent, ReactNode } from 'react'++import { cn } from 'lib/utils/css-classes'++import { biEditorLogic } from '../biEditorLogic'+import {+ BIShelf,+ BI_FIELD_DRAG_MIME_TYPE,+ BI_SHELF_PILL_DRAG_MIME_TYPE,+ getBIDropTarget,+ parseBIField,+ parseBIShelfPillDragData,+} from '../biEditorTypes'++function carriesBIDrag(event: DragEvent<HTMLElement>): 'field' | 'pill' | null {+ const types = Array.from(event.dataTransfer.types)+ return types.includes(BI_SHELF_PILL_DRAG_MIME_TYPE)+ ? 'pill'+ : types.includes(BI_FIELD_DRAG_MIME_TYPE)+ ? 'field'+ : null+}++/** Accepts fields from the data pane or the database tree, and pills moved from other shelves. */+export function BIShelfDropTarget({+ shelf,+ className,+ children,+}: {+ shelf: BIShelf+ className?: string+ children: ReactNode+}): JSX.Element {+ const { activeDropShelf, dragSessionId } = useValues(biEditorLogic)+ const { addFieldToShelf, clearActiveDropShelf, moveFieldToShelf, setActiveDropShelf } = useActions(biEditorLogic)++ return (+ <div+ className={cn(+ 'rounded transition-colors',+ activeDropShelf === shelf && 'bg-accent-highlight-secondary ring-2 ring-inset ring-accent',+ className+ )}+ data-attr={`bi-editor-${shelf}-shelf`}+ onDragEnter={(event) => {+ if (carriesBIDrag(event)) {+ setActiveDropShelf(shelf)+ }+ }}+ onDragOver={(event) => {+ const dragKind = carriesBIDrag(event)+ if (dragKind) {+ event.preventDefault()+ event.dataTransfer.dropEffect = dragKind === 'pill' ? 'move' : 'copy'+ }+ }}+ onDragLeave={(event) => {+ const nextTarget = event.relatedTarget+ if (!nextTarget || !event.currentTarget.contains(nextTarget as Node)) {+ clearActiveDropShelf(shelf)+ }+ }}+ onDrop={(event) => {+ event.preventDefault()+ event.stopPropagation()+ clearActiveDropShelf(shelf)+ const pill = parseBIShelfPillDragData(event.dataTransfer.getData(BI_SHELF_PILL_DRAG_MIME_TYPE))+ if (pill) {+ 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)+ }+ return+ }+ const field = parseBIField(event.dataTransfer.getData(BI_FIELD_DRAG_MIME_TYPE))+ if (field) {+ const target = getBIDropTarget(field, shelf)+ addFieldToShelf(target.field, target.shelf)+ }+ }}+ >+ {children}+ </div>+ )+}diff --git a/frontend/src/scenes/data-warehouse/editor/bi/components/BIShelfStrip.tsx b/frontend/src/scenes/data-warehouse/editor/bi/components/BIShelfStrip.tsxnew file mode 100644index 000000000000..2cb4a120e6c7--- /dev/null+++ b/frontend/src/scenes/data-warehouse/editor/bi/components/BIShelfStrip.tsx@@ -0,0 +1,50 @@+import { useActions, useValues } from 'kea'+import type { ReactNode } from 'react'++import { IconPlus } from '@posthog/icons'+import { LemonButton } from '@posthog/lemon-ui'++import { biEditorLogic } from '../biEditorLogic'+import { BIShelf } from '../biEditorTypes'+import { BIShelfDropTarget } from './BIShelfDropTarget'++/** A horizontal Rows or Columns shelf above the view. */+export function BIShelfStrip({+ shelf,+ title,+ icon,+ emptyText,+ children,+}: {+ shelf: Extract<BIShelf, 'rows' | 'columns'>+ title: string+ icon: ReactNode+ emptyText: string+ children: ReactNode[]+}): JSX.Element {+ const { config } = useValues(biEditorLogic)+ const { addBlankFieldToShelf } = useActions(biEditorLogic)++ return (+ <BIShelfDropTarget shelf={shelf} className="flex min-h-9 items-stretch rounded-none border-b">+ <div className="flex w-24 shrink-0 items-center gap-1.5 border-r px-2 text-xs font-semibold text-secondary">+ <span className="flex shrink-0">{icon}</span>+ {title}+ </div>+ <div className="flex min-w-0 flex-1 flex-wrap items-center gap-1 px-1.5 py-1">+ {children.length > 0 ? children : <span className="px-1 text-xs text-tertiary">{emptyText}</span>}+ <LemonButton+ icon={<IconPlus />}+ size="xsmall"+ type="tertiary"+ className="ml-auto"+ tooltip="Add a calculated field"+ aria-label={`Add a calculated field to ${title.toLowerCase()}`}+ disabledReason={!config.source ? 'Select a data source first' : undefined}+ onClick={() => addBlankFieldToShelf(shelf)}+ data-attr={`bi-editor-${shelf}-add-field`}+ />+ </div>+ </BIShelfDropTarget>+ )+}diff --git a/frontend/src/scenes/data-warehouse/editor/bi/components/BIShowMe.tsx b/frontend/src/scenes/data-warehouse/editor/bi/components/BIShowMe.tsxnew file mode 100644index 000000000000..3c58025d83dc--- /dev/null+++ b/frontend/src/scenes/data-warehouse/editor/bi/components/BIShowMe.tsx@@ -0,0 +1,76 @@+import { useActions, useValues } from 'kea'++import { IconX } from '@posthog/icons'+import { LemonButton } from '@posthog/lemon-ui'++import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { cn } from 'lib/utils/css-classes'++import { ChartDisplayType } from '~/types'++import { biEditorLogic } from '../biEditorLogic'+import { getChartTypeOptions } from '../biEditorOptions'++/** Chart picker that highlights the chart types that suit the fields on the shelves. */+export function BIShowMe({ docked }: { docked: boolean }): JSX.Element {+ const { chartFits, config, hoveredChartType } = useValues(biEditorLogic)+ const { setChartType, setShowMeOpen, setHoveredChartType } = useActions(biEditorLogic)+ const { featureFlags } = useValues(featureFlagLogic)++ const options = getChartTypeOptions(featureFlags)+ const describedOption =+ options.find((option) => option.value === hoveredChartType) ??+ options.find((option) => option.value === config.chartType)+ const describedFit = describedOption ? chartFits[describedOption.value] : undefined++ return (+ <div className="flex w-44 flex-col">+ <div className="flex min-h-7 items-center justify-between px-2 pt-2">+ <span className="text-sm font-semibold">Show me</span>+ {docked ? (+ <LemonButton+ icon={<IconX />}+ size="xsmall"+ type="tertiary"+ tooltip="Hide chart picker"+ aria-label="Hide chart picker"+ onClick={() => setShowMeOpen(false)}+ />+ ) : null}+ </div>+ <div className="grid grid-cols-3 gap-1 p-2" role="group" aria-label="Chart type">+ {options.map((option) => {+ const fits = chartFits[option.value]?.fits ?? true+ const selected = config.chartType === option.value+ return (+ <LemonButton+ key={option.value}+ type={selected ? 'primary' : 'tertiary'}+ active={selected}+ icon={option.icon}+ size="small"+ className={cn('justify-center', !fits && !selected && 'opacity-40')}+ tooltip={option.label}+ aria-label={option.label}+ aria-pressed={selected}+ onClick={() => setChartType(option.value)}+ onMouseEnter={() => setHoveredChartType(option.value)}+ onMouseLeave={() => setHoveredChartType(null)}+ data-attr={`bi-editor-chart-type-${option.value}`}+ />+ )+ })}+ </div>+ {describedOption && describedFit ? (+ <div className="border-t px-2 py-2 text-xs">+ <div className="font-semibold">{describedOption.label}</div>+ <div className="text-secondary">+ {describedOption.value === ChartDisplayType.Auto+ ? `${describedFit.requirement}.`+ : `${describedFit.fits ? 'Uses' : 'Needs'} ${describedFit.requirement}.`}+ </div>+ </div>+ ) : null}+ </div>+ )+}diff --git a/frontend/src/scenes/data-warehouse/editor/bi/components/BIToolbar.tsx b/frontend/src/scenes/data-warehouse/editor/bi/components/BIToolbar.tsxnew file mode 100644index 000000000000..6512f585cac7--- /dev/null+++ b/frontend/src/scenes/data-warehouse/editor/bi/components/BIToolbar.tsx@@ -0,0 +1,139 @@+import { useActions, useValues } from 'kea'++import { IconSort } from '@posthog/icons'+import { LemonButton, LemonDivider, LemonDropdown, LemonSelect, LemonSwitch } from '@posthog/lemon-ui'++import { IconArrowDown, IconArrowUp, IconSwapHoriz } from 'lib/lemon-ui/icons'++import { biEditorLogic } from '../biEditorLogic'+import { LIMIT_OPTIONS } from '../biEditorOptions'+import { BISortDirection } from '../biEditorTypes'+import { BIShowMe } from './BIShowMe'++export function BIToolbar(): JSX.Element {+ const { autoUpdate, config, showMeOpen, sortOptions } = useValues(biEditorLogic)+ const { resetConfig, setAutoUpdate, setLimit, setShowMeOpen, setSort, swapRowsAndColumns } =+ useActions(biEditorLogic)++ // Quick sort follows the chosen sort field, or the first measure like desktop BI tools do+ const quickSortKey = config.sort?.key ?? sortOptions.find((option) => option.key.startsWith('values:'))?.key ?? null+ const quickSort = (direction: BISortDirection): void => {+ if (quickSortKey) {+ setSort({ key: quickSortKey, direction })+ }+ }+ const noSortReason = quickSortKey ? undefined : 'Add a field to rows or columns first'++ return (+ <div className="flex flex-wrap items-center gap-1 border-b px-2 py-1">+ <LemonButton+ icon={<IconSwapHoriz />}+ size="small"+ type="tertiary"+ 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+ }+ onClick={swapRowsAndColumns}+ data-attr="bi-editor-swap"+ />+ <LemonButton+ icon={<IconArrowUp />}+ size="small"+ type="tertiary"+ active={config.sort?.direction === 'asc'}+ tooltip="Sort ascending"+ aria-label="Sort ascending"+ disabledReason={noSortReason}+ onClick={() => quickSort('asc')}+ data-attr="bi-editor-sort-ascending"+ />+ <LemonButton+ icon={<IconArrowDown />}+ size="small"+ type="tertiary"+ active={config.sort?.direction === 'desc'}+ tooltip="Sort descending"+ aria-label="Sort descending"+ disabledReason={noSortReason}+ onClick={() => quickSort('desc')}+ data-attr="bi-editor-sort-descending"+ />+ <LemonSelect+ value={config.sort?.key ?? null}+ options={[+ {+ value: null,+ label: 'Auto',+ tooltip:+ 'Sorts by the newest date or the highest value first, so the top rows stay within the limit.',+ },+ ...sortOptions.map((option) => ({ value: option.key, label: option.label })),+ ]}+ onChange={(key) => setSort(key === null ? null : { key, direction: config.sort?.direction ?? 'desc' })}+ renderButtonContent={(option) => `Sort: ${option?.label ?? 'Auto'}`}+ icon={<IconSort />}+ aria-label="Sort results by"+ size="small"+ type="tertiary"+ dropdownMatchSelectWidth={false}+ disabledReason={sortOptions.length === 0 ? 'Add a field to rows or columns first' : undefined}+ data-attr="bi-editor-sort"+ />+ <LemonSelect+ value={config.limit}+ options={LIMIT_OPTIONS}+ onChange={setLimit}+ renderButtonContent={(option) => `Limit: ${option?.label ?? config.limit}`}+ aria-label="Query row limit"+ size="small"+ type="tertiary"+ dropdownMatchSelectWidth={false}+ data-attr="bi-editor-query-limit"+ />+ <LemonDivider vertical />+ <LemonButton+ size="small"+ type="tertiary"+ onClick={resetConfig}+ disabledReason={!config.source ? 'Nothing to clear' : undefined}+ data-attr="bi-editor-clear"+ >+ Clear sheet+ </LemonButton>+ <div className="ml-auto flex items-center gap-2">+ <LemonSwitch+ checked={autoUpdate}+ onChange={setAutoUpdate}+ label="Auto-update"+ size="small"+ tooltip="Run the query after every change"+ data-attr="bi-editor-auto-update"+ />+ {/* Narrow sheets have no room to dock the chart picker, so it opens as a dropdown */}+ <LemonDropdown overlay={<BIShowMe docked={false} />} placement="bottom-end">+ <LemonButton+ size="small"+ type="secondary"+ className="@3xl/bi-editor:hidden"+ data-attr="bi-editor-show-me"+ >+ Show me+ </LemonButton>+ </LemonDropdown>+ {!showMeOpen ? (+ <LemonButton+ size="small"+ type="secondary"+ className="hidden @3xl/bi-editor:flex"+ onClick={() => setShowMeOpen(true)}+ data-attr="bi-editor-show-me"+ >+ Show me+ </LemonButton>+ ) : null}+ </div>+ </div>+ )+}diff --git a/frontend/src/scenes/data-warehouse/editor/editorSizingLogic.tsx b/frontend/src/scenes/data-warehouse/editor/editorSizingLogic.tsxindex 2f645ee9d9d2..6211dc7c8dbf 100644--- a/frontend/src/scenes/data-warehouse/editor/editorSizingLogic.tsx+++ b/frontend/src/scenes/data-warehouse/editor/editorSizingLogic.tsx@@ -23,8 +23,9 @@ const MINIMUM_NAVIGATOR_WIDTH = 100const NAVIGATOR_DEFAULT_WIDTH = 350const MINIMUM_QUERY_PANE_HEIGHT = 100const DEFAULT_QUERY_PANE_HEIGHT = 300-const MINIMUM_BI_EDITOR_HEIGHT = 180-const DEFAULT_BI_EDITOR_HEIGHT = 324+const MINIMUM_BI_SIDE_PANE_WIDTH = 200+const DEFAULT_BI_SIDE_PANE_WIDTH = 240+const MAXIMUM_BI_SIDE_PANE_WIDTH = 480const MINIMUM_SIDEBAR_WIDTH = 150export const SIDEBAR_DEFAULT_WIDTH = 300const MAXIMUM_SIDEBAR_WIDTH = 550@@ -42,8 +43,8 @@ export interface editorSizingLogicValues {queryPaneDesiredSize: number | null // resizerLogicsidebarDesiredSize: number | null // resizerLogicsourceNavigatorDesiredSize: number | null // resizerLogic- biEditorHeight: numberbiEditorResizerProps: ResizerLogicProps+ biSidePaneWidth: numberdatabaseTreeResizerProps: ResizerLogicPropsdatabaseTreeWidth: numberdatabaseTreeWillCollapse: boolean@@ -88,7 +89,7 @@ export interface editorSizingLogicMeta {key: string__keaTypeGenInternalSelectorTypes: {editorSceneRef: (editorSceneRef: any) => any- biEditorHeight: (biEditorDesiredSize: number | null) => number+ biSidePaneWidth: (biEditorDesiredSize: number | null) => numberbiEditorResizerProps: (biEditorResizerProps: ResizerLogicProps) => ResizerLogicPropssourceNavigatorWidth: (sourceNavigatorDesiredSize: number | null) => numberqueryPaneHeight: (@@ -182,9 +183,13 @@ export const editorSizingLogic = kea<editorSizingLogicType>([})),selectors({editorSceneRef: [(p) => [p.editorSceneRef], (editorSceneRef) => editorSceneRef],- biEditorHeight: [+ biSidePaneWidth: [(s) => [s.biEditorDesiredSize],- (desiredSize: number | null) => Math.max(desiredSize || DEFAULT_BI_EDITOR_HEIGHT, MINIMUM_BI_EDITOR_HEIGHT),+ (desiredSize: number | null) =>+ Math.min(+ Math.max(desiredSize || DEFAULT_BI_SIDE_PANE_WIDTH, MINIMUM_BI_SIDE_PANE_WIDTH),+ MAXIMUM_BI_SIDE_PANE_WIDTH+ ),],biEditorResizerProps: [(_, p) => [p.biEditorResizerProps],diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.tsindex 8bf1a087a4c7..12d1f67a75ad 100644--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts@@ -36,7 +36,7 @@ import { sqlEditorDraftStorage } from 'products/data_warehouse/frontend/sqlEditoimport { BI_EDITOR_EVENTS } from './bi/biEditorAnalytics'import { biEditorLogic } from './bi/biEditorLogic'-import { BIConfig, BIEditorView, BIField } from './bi/biEditorTypes'+import { BIConfig, BIEditorView, BIField, getBIFieldPillLabel, getBIShelfEditorKey } from './bi/biEditorTypes'import { buildSqlNotebook, editorSceneLogic } from './editorSceneLogic'import { OutputTab } from './outputPaneLogic'import { SELECTION_NOT_A_QUERY } from './saveCandidateProblems'@@ -2511,10 +2511,210 @@ describe('sqlEditorLogic', () => {{ table: 'system_metrics', connectionId: undefined },])+ biLogic.actions.setDataSource({ table: 'hidden_table' })+ expect(biLogic.values.selectableDataSources[0]).toEqual({ table: 'hidden_table' })+ expect(biLogic.values.selectableDataSources).toHaveLength(biLogic.values.availableDataSources.length + 1)++ biLogic.unmount()+ })++ it('hydrates fields when the schema arrives after restoring a worksheet', async () => {+ await expectLogic(databaseLogic).toFinishAllListeners()+ const biLogic = biEditorLogic({ tabId: TAB_ID })+ biLogic.mount()+ biLogic.actions.restoreState({ editorView: BIEditorView.BI, config })+ expect(biLogic.values.dataPaneFields.dimensions).toEqual([])+ databaseLogic.actions.hydrateTableFieldsFailure(['events'])+ expect(biLogic.values.dataPaneFieldsError).toBe(true)++ queryEndpointMock.mockReturnValue([+ 200,+ {+ tables: {+ events: {+ id: 'events',+ name: 'events',+ type: 'posthog',+ fields: {+ event: { name: 'event', type: 'string', schema_valid: true },+ },+ },+ },+ joins: [],+ },+ ])+ useMocks({ post: { '/api/environments/:team_id/query/DatabaseSchemaQuery/': queryEndpointMock } })+ databaseLogic.actions.setDatabaseFieldsComplete(false)++ await expectLogic(databaseLogic, () =>+ databaseLogic.actions.loadDatabaseSuccess({+ tables: { events: { id: 'events', name: 'events', type: 'posthog', fields: {} } },+ joins: [],+ })+ ).toDispatchActions(['hydrateTableFieldsSuccess'])++ expect(biLogic.values.dataPaneFields.dimensions).toEqual([+ expect.objectContaining({ name: 'event', expression: 'event' }),+ ])+ expect(biLogic.values.dataPaneFieldsError).toBe(false)+ biLogic.unmount()+ })++ it('keeps field labels consistent with edited expressions', () => {+ const biLogic = biEditorLogic({ tabId: TAB_ID })+ biLogic.mount()+ biLogic.actions.restoreState({ editorView: BIEditorView.BI, config })+ biLogic.actions.setAutoUpdate(false)+ biLogic.actions.setFieldExpression('rows', 0, 'distinct_id')+ expect(getBIFieldPillLabel(biLogic.values.config.rows[0])).toBe('distinct_id')+ expect(biLogic.values.generatedQuery?.query).toContain('SELECT\n distinct_id,')+ biLogic.unmount()+ })++ it("does not expose another connection's fields and resets the worksheet when switching connections", () => {+ logic = sqlEditorLogic({ tabId: TAB_ID, monaco: createMockMonaco(), editor: createMockEditor() })+ logic.mount()+ const biLogic = biEditorLogic({ tabId: TAB_ID })+ biLogic.mount()+ biLogic.actions.restoreState({ editorView: BIEditorView.BI, config })+ databaseLogic.actions.setConnection('other-connection')+ databaseLogic.actions.loadDatabaseSuccess({+ tables: {+ events: {+ id: 'events',+ name: 'events',+ type: 'data_warehouse',+ fields: {+ private_field: {+ name: 'private_field',+ hogql_value: 'private_field',+ type: 'string',+ schema_valid: true,+ },+ },+ },+ },+ joins: [],+ })+ expect(biLogic.values.dataPaneFields).toEqual({ dimensions: [], measures: [] })+ logic.actions.setSourceQuery({+ ...logic.values.sourceQuery,+ source: { ...logic.values.sourceQuery.source, connectionId: 'other-connection' },+ })+ expect(biLogic.values.config.source).toBeNull()+ expect(biLogic.values.config.rows).toEqual([])+ expect(logic.values.selectedConnectionId).toBe('other-connection')+ biLogic.unmount()+ })++ test.each(['ready', 'failed', 'cancelled', 'missing'] as const)(+ 'handles chart-only changes with %s query results and runs changed pivot SQL',+ async (resultState) => {+ logic = sqlEditorLogic({ tabId: TAB_ID, monaco: createMockMonaco(), editor: createMockEditor() })+ logic.mount()+ const biLogic = biEditorLogic({ tabId: TAB_ID })+ biLogic.mount()+ biLogic.actions.restoreState({+ editorView: BIEditorView.BI,+ config: { ...config, columns: [timestampField] },+ })+ biLogic.actions.syncGeneratedQuery()+ logic.actions.setLastRunQuery(logic.values.sourceQuery)+ const dataLogic = dataNodeLogic({+ key: `data-warehouse-editor-data-node-${TAB_ID}`,+ query: logic.values.sourceQuery.source,+ autoLoad: false,+ })+ dataLogic.mount()+ if (resultState !== 'missing') {+ dataLogic.actions.setResponse({ results: [[1]], columns: ['1'], types: ['Int64'] })+ }+ if (resultState === 'failed') {+ dataLogic.actions.loadDataFailure('Query failed', { detail: 'Query failed' })+ } else if (resultState === 'cancelled') {+ dataLogic.actions.cancelQuery()+ }+ const runQuery = jest.spyOn(logic.actions, 'runQuery')+ jest.useFakeTimers()+ try {+ biLogic.actions.setAutoUpdate(true)+ biLogic.actions.setChartType(ChartDisplayType.ActionsTable)+ await jest.advanceTimersByTimeAsync(500)+ expect(logic.values.sourceQuery.display).toBe(ChartDisplayType.ActionsTable)+ expect(runQuery).toHaveBeenCalledTimes(resultState === 'ready' ? 0 : 1)+ biLogic.actions.setChartType(ChartDisplayType.TwoDimensionalHeatmap)+ await jest.advanceTimersByTimeAsync(500)+ expect(runQuery).toHaveBeenCalledTimes(resultState === 'ready' ? 1 : 2)+ } finally {+ jest.useRealTimers()+ runQuery.mockRestore()+ dataLogic.unmount()+ biLogic.unmount()+ }+ }+ )++ test.each(['disable', 'sql', 'clear', 'unchanged'] as const)(+ 'handles a pending automatic query when the worksheet is %s',+ async (transition) => {+ logic = sqlEditorLogic({ tabId: TAB_ID, monaco: createMockMonaco(), editor: createMockEditor() })+ logic.mount()+ const biLogic = biEditorLogic({ tabId: TAB_ID })+ biLogic.mount()+ biLogic.actions.restoreState({ editorView: BIEditorView.BI, config })+ const runQuery = jest.spyOn(logic.actions, 'runQuery')+ jest.useFakeTimers()+ try {+ biLogic.actions.setAutoUpdate(true)+ biLogic.actions.setLimit(10000)+ if (transition === 'disable') {+ biLogic.actions.setAutoUpdate(false)+ } else if (transition === 'sql') {+ biLogic.actions.setEditorView(BIEditorView.SQL)+ logic.actions.setQueryInput('SELECT 42')+ } else if (transition === 'clear') {+ biLogic.actions.resetConfig()+ }+ await jest.advanceTimersByTimeAsync(500)+ expect(runQuery).toHaveBeenCalledTimes(transition === 'unchanged' ? 1 : 0)+ } finally {+ jest.useRealTimers()+ runQuery.mockRestore()+ biLogic.unmount()+ }+ }+ )++ it('clears the displayed result when clearing the worksheet', async () => {+ logic = sqlEditorLogic({ tabId: TAB_ID, monaco: createMockMonaco(), editor: createMockEditor() })+ logic.mount()+ const biLogic = biEditorLogic({ tabId: TAB_ID })+ biLogic.mount()+ biLogic.actions.restoreState({ editorView: BIEditorView.BI, config })+ const dataLogic = dataNodeLogic({+ key: `data-warehouse-editor-data-node-${TAB_ID}`,+ query: { kind: NodeKind.HogQLQuery, query: 'SELECT 1' },+ autoLoad: false,+ })+ dataLogic.mount()+ dataLogic.actions.setResponse({ results: [[1]], columns: ['1'], types: ['Int64'] })+ expect(dataLogic.values.response).not.toBeNull()+ logic.actions.setLastRunQuery(logic.values.sourceQuery)++ await expectLogic(biLogic, () => biLogic.actions.resetConfig()).toFinishAllListeners()++ expect(dataLogic.values.response).toBeNull()+ expect(dataLogic.values.queryCancelled).toBe(false)+ expect(logic.values.lastRunQuery).toBeNull()+ expect(logic.values.queryInput).toBe('')+ dataLogic.unmount()biLogic.unmount()})it('restores BI mode and configuration from the URL and keeps changes in the hash', async () => {+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.SQL_EDITOR_BI_MODE], {+ [FEATURE_FLAGS.SQL_EDITOR_BI_MODE]: true,+ })logic = sqlEditorLogic({tabId: TAB_ID,monaco: createMockMonaco(),@@ -2544,6 +2744,10 @@ describe('sqlEditorLogic', () => {})await expectLogic(biLogic).toMatchValues({ editorView: BIEditorView.BI, config: persistedConfig })+ await expectLogic(logic, () => logic.actions.runQuery()).toFinishAllListeners()+ expect(logic.values.sourceQuery.display).toBe(ChartDisplayType.TwoDimensionalHeatmap)+ expect(biLogic.values.config.chartType).toBe(ChartDisplayType.TwoDimensionalHeatmap)+await expectLogic(biLogic, () => biLogic.actions.setFilterValue(0, 'purchase')).toFinishAllListeners()expect(router.values.hashParams.mode).toEqual(BIEditorView.BI)@@ -2664,12 +2868,19 @@ describe('sqlEditorLogic', () => {source: { table: 'persons' },}),])- expect(biLogic.values.activeExpressionEditorId).toEqual(biLogic.values.config.rows[0].id)+ const blankField = biLogic.values.config.rows[0]+ expect(biLogic.values.activeExpressionEditorId).toEqual(getBIShelfEditorKey('rows', blankField.id))expect(logic.values.queryInput).toEqual(['SELECT', ' count(*) AS count', 'FROM persons', 'LIMIT 1000'].join('\n'))expect(router.values.hashParams.bi).toEqual(biLogic.values.config)+ await expectLogic(biLogic, () =>+ biLogic.actions.addFieldToShelf(blankField, 'filters')+ ).toFinishAllListeners()++ expect(biLogic.values.activeExpressionEditorId).toEqual(getBIShelfEditorKey('filters', blankField.id))+biLogic.unmount()})diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsxindex dac49e618704..5c38b18d91c6 100644--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx@@ -119,7 +119,7 @@ import { dataWarehouseViewsLogic } from '../saved_queries/dataWarehouseViewsLogiimport type { DataWarehouseSavedQuerySummary } from '../saved_queries/dataWarehouseViewsLogic'import { validateSavedQueryName } from '../saved_queries/savedQueryNameValidation'import { captureBIEditorQueryRun, captureBIEditorQuerySaved } from './bi/biEditorAnalytics'-import { BIEditorState, parseBIEditorState } from './bi/biEditorTypes'+import { BIEditorState, BIEditorView, buildBIQuery, parseBIEditorState } from './bi/biEditorTypes'import { connectionSelectorLogic } from './connectionSelectorLogic'import { draftsLogic } from './draftsLogic'import { fixSQLErrorsLogic } from './fixSQLErrorsLogic'@@ -2255,12 +2255,19 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([})},runQuery: ({ queryOverride, switchTab }) => {- captureBIEditorQueryRun(getActiveBIEditorState())+ const biEditorState = getActiveBIEditorState()+ captureBIEditorQueryRun(biEditorState)+ const biQuery =+ !queryOverride && biEditorState?.editorView === BIEditorView.BI+ ? buildBIQuery(biEditorState.config)+ : nulllet query: stringif (queryOverride) {// Explicit override (e.g. user selected text and pressed Cmd+Enter)query = queryOverride+ } else if (biQuery) {+ query = biQuery.query} else {// No override — find the query under the cursorconst fullText = values.queryInput ?? ''@@ -2280,8 +2287,12 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([}}+ if (biQuery && query !== values.queryInput) {+ actions.setQueryInput(query)+ }const newSource = normalizeRawQuerySource({...values.sourceQuery.source,+ ...biQuery?.node.source,query,})@@ -2292,14 +2303,23 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([tags: { ...newSource.tags, productKey: 'sql_editor' },}- actions.setSourceQuery({- ...values.sourceQuery,- source: newSource,- })- actions.setLastRunQuery({+ const nextSourceQuery: DataVisualizationNode = {...values.sourceQuery,+ ...biQuery?.node,+ chartSettings: biQuery?.node.chartSettings+ ? {+ ...values.sourceQuery.chartSettings,+ ...biQuery.node.chartSettings,+ heatmap: {+ ...values.sourceQuery.chartSettings?.heatmap,+ ...biQuery.node.chartSettings.heatmap,+ },+ }+ : values.sourceQuery.chartSettings,source: newSource,- })+ }+ actions.setSourceQuery(nextSourceQuery)+ actions.setLastRunQuery(nextSourceQuery)if (!cache.umountDataNode) {cache.umountDataNode = dataNodeLogic({key: values.dataLogicKey,