Skip to content

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

fix(customer-analytics): size new account columns to content (#98636)

Arthur Moreira de Deus583040ebf9e8
diff --git a/docs/internal/customer-analytics-accounts-table.md b/docs/internal/customer-analytics-accounts-table.md
new file mode 100644
index 000000000000..0875d8911e2c
--- /dev/null
+++ b/docs/internal/customer-analytics-accounts-table.md
@@ -0,0 +1,26 @@
+# Accounts table column widths
+
+The Customer analytics Accounts list sizes new columns to their rendered header and loaded values.
+Automatic widths have an 80px minimum and a 200px maximum.
+Short values use less space, while long values stop the column from growing beyond 200px.
+
+Saved widths and existing column defaults take precedence over automatic sizing:
+
+| Column | Default width |
+| ------------------------------------------ | ------------------------------- |
+| Account and tags | 280px |
+| Notes | 80px |
+| Relationships | 220px |
+| Custom properties and other account fields | Fit content, from 80px to 200px |
+
+`useAccountColumnAutoSizing.ts` measures a hidden copy of the rendered table without width constraints.
+It excludes expanded rows from the measurement and removes the copy before the browser paints.
+Automatic widths update when loaded data changes and are not saved to browser storage.
+
+Users can still drag column header boundaries to resize columns, including beyond 200px.
+`accountsViewsLogic` stores manual widths per team and column in browser local storage, independently of saved views.
+Hiding a column does not discard its saved width.
+Automatic sizing uses the existing resized-table layout and does not change scroll controls.
+
+The `ManyColumns` story in `AccountsTab.stories.tsx` covers six added custom properties alongside native and relationship columns.
+Its browser assertions check content-dependent widths, the 200px cap, horizontal scrolling, and the row expansion control.
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 4aa741d3db9d..9875e8d20baf 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -4,6 +4,10 @@ config:
team: '2'
repo: 3d760a0a-0763-477d-89ee-f1e4e92cdd78
snapshots:
+ scenes-app-customer-analytics-accounts--many-columns--dark:
+ hash: v1.k794b7964.bbcafae15f682dd892236c17af7ae5920df61f4a14f1c2b298977ba77b6bacb2.xumXP9yIhqUxrM69J_MjvUCNMHuL2PwIgLs3u3PbCP0
+ scenes-app-customer-analytics-accounts--many-columns--light:
+ hash: v1.k794b7964.41369848fe476522e301d6e10665de13e88a1a8a64c4a17a2adc81306f24b64e.kaZ8ldUFXD5oEmnfoaB6ag8wg77wYPwSi0dCsHVX6Lk
ai-observability-create-prompt-experiment-modal--default--dark:
hash: v1.k794b7964.af0ce5703adcc074ea6c3afc8715d537a646698123a78625e6ec847123b26ae2.ypACU5Xagre6WeI4z7UlQ6w7oY0ieM1C-GnZs93KDkY
ai-observability-create-prompt-experiment-modal--default--light:
diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
index f6d42c11109c..539b9f6d663d 100644
--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md
+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
@@ -63,7 +63,7 @@ AccountsTabContent ── binds dataNodeLogic(ACCOUNTS_TABLE_DATA_NODE_KEY, acc
## Data & query model
-`accountsLogic.accountsTableQueryPlan` translates selected columns, filters, custom-property display windows, tile filters, and server-side sort into a typed `AccountsTableQuery`. Unsupported saved columns and filters are omitted instead of switching execution engines. `AccountsTable` reads each keyed `AccountsTableRow` directly through `accountsTableCell`; there is no positional-row compatibility transform. Every column can be resized from its header down to 80px. Widths save automatically in one team-scoped local storage dictionary keyed by stable column alias. A column keeps its width when a view hides it, then restores it when another view shows it.
+`accountsLogic.accountsTableQueryPlan` translates selected columns, filters, custom-property display windows, tile filters, and server-side sort into a typed `AccountsTableQuery`. Unsupported saved columns and filters are omitted instead of switching execution engines. `AccountsTable` reads each keyed `AccountsTableRow` directly through `accountsTableCell`; there is no positional-row compatibility transform. Custom properties and other fields without a saved or column-specific width size to their rendered headers and loaded values, between 80px and 200px. `useAccountColumnAutoSizing` measures a hidden, unconstrained copy of the table after data loads. Automatic widths remain local to the mounted table and update with its data. They use the same table sizing as manually resized columns. Existing defaults, manual resizing, and horizontal scrolling stay unchanged. Every column can be resized from its header down to 80px. See [Accounts table layout](../../../../../docs/internal/customer-analytics-accounts-table.md). Widths save automatically in one team-scoped local storage dictionary keyed by stable column alias. A column keeps its width when a view hides it, then restores it when another view shows it.
Search matches the account name and external ID as substrings.
A complete email address also matches accounts that list it under `known_emails`.
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsx
index 6add5d6c73d8..baca22b947b0 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsx
@@ -16,6 +16,8 @@ import type {
UserCustomerAnalyticsConfigApi,
} from 'products/customer_analytics/frontend/generated/api.schemas'
+import { ACCOUNTS_DEFAULT_COLUMNS, customPropertyAlias } from './accountsColumnConfigLogic'
+
const QUERY_ENDPOINT = '/api/projects/:team_id/accounts_table_query/'
const ACCOUNT_RETRIEVE_ENDPOINT = 'api/projects/:team_id/accounts/:account_id/'
const ACCOUNT_NOTEBOOKS_ENDPOINT = 'api/projects/:team_id/accounts/:account_id/notebooks/'
@@ -73,7 +75,10 @@ const RELATIONSHIP_DEFINITIONS = {
],
}
-function buildAccountsTableQueryResponse(rows: AccountRow[]): Record<string, unknown> {
+function buildAccountsTableQueryResponse(
+ rows: AccountRow[],
+ customProperties: Record<string, string> = {}
+): Record<string, unknown> {
return {
kind: 'AccountsTableQuery',
results: rows.map(([account, tags, noteCount, csm, accountExecutive, accountOwner]) => ({
@@ -89,7 +94,7 @@ function buildAccountsTableQueryResponse(rows: AccountRow[]): Record<string, unk
'66666666-7777-8888-9999-aaaaaaaaaaaa': accountExecutive,
'bbbbbbbb-cccc-dddd-eeee-ffffffffffff': accountOwner,
},
- customProperties: {},
+ customProperties,
customPropertyHistory: {},
})),
hasMore: false,
@@ -274,7 +279,8 @@ const EXPANDED_ROW_TEST_OPTIONS = {
}
function mockAccountsTableQuery(
- rows: AccountRow[]
+ rows: AccountRow[],
+ customProperties: Record<string, string> = {}
): (info: MockResolverInfo) => Promise<[number, unknown] | undefined> {
return async ({ request }) => {
const body = (await request.json()) as { query?: { kind?: string; metrics?: unknown[] } }
@@ -292,7 +298,7 @@ function mockAccountsTableQuery(
metricsResults: [rows.length],
},
]
- : [200, buildAccountsTableQueryResponse(rows)]
+ : [200, buildAccountsTableQueryResponse(rows, customProperties)]
}
return undefined
}
@@ -357,6 +363,109 @@ export const Default: Story = {
],
}
+const ADDITIONAL_COLUMN_DEFINITIONS: CustomPropertyDefinitionApi[] = (
+ [
+ { name: 'Subscription cost', display_type: 'currency' },
+ { name: 'Onboarding progress', display_type: 'percent' },
+ { name: 'Seats', display_type: 'number' },
+ { name: 'Deployment region', display_type: 'text' },
+ { name: 'Plan', display_type: 'text' },
+ { name: 'Account description', display_type: 'text' },
+ ] satisfies Pick<CustomPropertyDefinitionApi, 'name' | 'display_type'>[]
+).map((definition, index) => ({
+ ...definition,
+ id: `00000000-0000-0000-0000-00000000000${index}`,
+ is_canonical: false,
+ source: null,
+ has_workflow_reference: false,
+ created_at: '2026-05-01T00:00:00Z',
+ created_by: null,
+ updated_at: null,
+ references: [],
+}))
+
+const ADDITIONAL_COLUMN_VALUES = Object.fromEntries(
+ [
+ '12345.67',
+ '0.75',
+ '250',
+ 'Europe',
+ 'Enterprise',
+ 'A long account description that needs more than one column width',
+ ].map((value, index) => [ADDITIONAL_COLUMN_DEFINITIONS[index].id, value])
+)
+
+export const ManyColumns: Story = {
+ render: () => <App />,
+ parameters: {
+ pageUrl: `${urls.customerAnalyticsAccounts()}#view=${encodeURIComponent(
+ JSON.stringify({
+ columns: [
+ ...ACCOUNTS_DEFAULT_COLUMNS,
+ 'csm',
+ 'external_id',
+ ...ADDITIONAL_COLUMN_DEFINITIONS.map(
+ ({ id }) => `accounts.custom_properties.values.\`${id}\` AS ${customPropertyAlias(id)}`
+ ),
+ ],
+ })
+ )}`,
+ testOptions: {
+ waitForSelector: `[data-attr="accounts-table-sort-${customPropertyAlias(ADDITIONAL_COLUMN_DEFINITIONS[5].id)}"]`,
+ viewport: { width: 1280, height: 960 },
+ },
+ },
+ decorators: [
+ mswDecorator({
+ get: {
+ 'api/projects/:team_id/column_configurations/': { count: 0, next: null, results: [] },
+ 'api/environments/:team_id/customer_journeys/': { count: 0, next: null, results: [] },
+ 'api/projects/:team_id/custom_property_definitions/': {
+ count: ADDITIONAL_COLUMN_DEFINITIONS.length,
+ next: null,
+ previous: null,
+ results: ADDITIONAL_COLUMN_DEFINITIONS,
+ },
+ },
+ post: {
+ [QUERY_ENDPOINT]: mockAccountsTableQuery(SAMPLE_ROWS, ADDITIONAL_COLUMN_VALUES),
+ },
+ }),
+ ],
+ play: async ({ canvasElement }) => {
+ await within(canvasElement).findAllByText('Enterprise', {}, { timeout: 15000 })
+ await waitFor(() => {
+ const widths: number[] = []
+ for (const definition of ADDITIONAL_COLUMN_DEFINITIONS) {
+ const header = canvasElement
+ .querySelector(`[data-attr="accounts-table-sort-${customPropertyAlias(definition.id)}"]`)
+ ?.closest('th')
+ const width = header?.getBoundingClientRect().width ?? 0
+ if (width < 80 || width > 200) {
+ throw new Error('New account columns must size between 80px and 200px')
+ }
+ widths.push(width)
+ }
+ if (widths[4] <= widths[2] || widths.at(-1) !== 200) {
+ throw new Error('Column sizes must account for values wider than the header and cap long content')
+ }
+ const expansionToggle = canvasElement.querySelector('.DataTable .LemonTable__toggle')
+ if (!expansionToggle || expansionToggle.getBoundingClientRect().width === 0) {
+ throw new Error('Automatic column widths must leave the row expansion control visible')
+ }
+ const scrollContainer = canvasElement.querySelector<HTMLElement>('.DataTable .ScrollableShadows__inner')
+ if (!scrollContainer || scrollContainer.scrollWidth <= scrollContainer.clientWidth) {
+ throw new Error('Account columns must scroll inside the table when they do not fit')
+ }
+ scrollContainer.scrollLeft = scrollContainer.scrollWidth
+ if (scrollContainer.scrollLeft === 0) {
+ throw new Error('The last account column must be reachable by scrolling')
+ }
+ scrollContainer.scrollLeft = 0
+ })
+ },
+}
+
export const Empty: Story = {
render: () => <App />,
decorators: [
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsTable.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsTable.tsx
index 9a2c96e220f4..b1716ccdef59 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountsTable.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountsTable.tsx
@@ -51,6 +51,7 @@ import { accountsLogic, customPropertySavingKey, savingRoleKey } from './account
import { AccountsTableNameCell } from './AccountsTableNameCell'
import { accountsTableCell, isAccountsTableRow } from './accountsTableQuery'
import { accountsViewsLogic } from './accountsViewsLogic'
+import { useAccountColumnAutoSizing } from './useAccountColumnAutoSizing'
// Shape the name renderer uses from the keyed AccountsTableRow identity fields.
type AccountNameCellData = { name: string; external_id: string | null; id: string; logo_domain: string | null }
@@ -896,20 +897,25 @@ export function AccountsTable(): JSX.Element {
query: accountsQuerySource,
} as DataNodeLogicProps)
)
- const contextColumns = useContextColumns()
+ const {
+ tableRef,
+ columns: contextColumns,
+ hasAutoSizedColumns,
+ } = useAccountColumnAutoSizing(useContextColumns(), response, responseLoading)
const expandable = useExpandable()
const dataTableContext = useMemo<QueryContext<DataTableNode>>(
() => ({
columns: contextColumns,
tableLayout: 'fixed',
- tableStyle: Object.keys(columnWidths).length > 0 ? { width: 'max-content' } : undefined,
+ tableStyle:
+ hasAutoSizedColumns || Object.keys(columnWidths).length > 0 ? { width: 'max-content' } : undefined,
expandable,
dataTableRowsTransformer: sortedRowsTransformer,
dataNodeLogicKey: ACCOUNTS_TABLE_DATA_NODE_KEY,
emptyStateHeading: 'There are no matching accounts for this query',
emptyStateDetail: 'Try adjusting the filters or refreshing',
}),
- [contextColumns, columnWidths, expandable, sortedRowsTransformer]
+ [contextColumns, columnWidths, hasAutoSizedColumns, expandable, sortedRowsTransformer]
)
// A null source means the query is still waiting on the relationship
// definitions — same skeleton as the initial fetch, not an empty table.
@@ -917,7 +923,7 @@ export function AccountsTable(): JSX.Element {
return <AccountsTableSkeleton />
}
return (
- <div className="@container">
+ <div ref={tableRef} className="@container">
<DataTable
uniqueKey="customer-analytics-accounts-table"
query={accountsDataTableQuery}
diff --git a/products/customer_analytics/frontend/components/Accounts/useAccountColumnAutoSizing.ts b/products/customer_analytics/frontend/components/Accounts/useAccountColumnAutoSizing.ts
new file mode 100644
index 000000000000..b86f8cb2add1
--- /dev/null
+++ b/products/customer_analytics/frontend/components/Accounts/useAccountColumnAutoSizing.ts
@@ -0,0 +1,76 @@
+import { RefObject, useLayoutEffect, useMemo, useRef, useState } from 'react'
+
+import { objectsEqual } from 'lib/utils/objects'
+
+import { QueryContextColumn } from '~/queries/types'
+
+function getContentWidths(table: HTMLTableElement, columnNames: string[]): Record<string, number> {
+ const measurementTable = table.cloneNode(true) as HTMLTableElement
+ measurementTable.removeAttribute('style')
+ measurementTable.classList.remove('table-fixed')
+ measurementTable.classList.add('fixed', 'invisible', 'pointer-events-none', 'table-auto', 'w-max!', 'min-w-0')
+ measurementTable.inert = true
+ measurementTable
+ .querySelectorAll('colgroup, tfoot, .LemonTable__expansion, .LemonTable__loader-row')
+ .forEach((element) => element.remove())
+ measurementTable.querySelectorAll<HTMLElement>('th, td').forEach((cell) => {
+ cell.style.maxWidth = 'none'
+ cell.style.whiteSpace = 'nowrap'
+ })
+ table.parentElement?.appendChild(measurementTable)
+ try {
+ const widths: Record<string, number> = {}
+ for (const header of measurementTable.querySelectorAll<HTMLTableCellElement>('thead th')) {
+ const sortControl = header.querySelector<HTMLElement>('[data-attr^="accounts-table-sort-"]')
+ const columnName = sortControl?.getAttribute('data-attr')?.slice('accounts-table-sort-'.length)
+ if (columnName && columnNames.includes(columnName)) {
+ widths[columnName] = Math.min(200, Math.max(80, Math.ceil(header.getBoundingClientRect().width)))
+ }
+ }
+ return widths
+ } finally {
+ measurementTable.remove()
+ }
+}
+
+export function useAccountColumnAutoSizing(
+ columns: Record<string, QueryContextColumn>,
+ response: unknown,
+ loading: boolean
+): {
+ tableRef: RefObject<HTMLDivElement>
+ columns: Record<string, QueryContextColumn>
+ hasAutoSizedColumns: boolean
+} {
+ const tableRef = useRef<HTMLDivElement>(null)
+ const [contentWidths, setContentWidths] = useState<Record<string, number>>({})
+
+ useLayoutEffect(() => {
+ const table = tableRef.current?.querySelector<HTMLTableElement>('.LemonTable__content > table')
+ const columnNames = Object.keys(columns).filter((key) => columns[key].width === undefined)
+ if (!table || loading || !response || columnNames.length === 0) {
+ return
+ }
+ const widths = getContentWidths(table, columnNames)
+ setContentWidths((previous) => (objectsEqual(previous, widths) ? previous : widths))
+ }, [columns, response, loading])
+
+ const sizedColumns = useMemo(
+ () =>
+ Object.fromEntries(
+ Object.entries(columns).map(([key, column]) => [
+ key,
+ { ...column, width: column.width ?? contentWidths[key] },
+ ])
+ ),
+ [columns, contentWidths]
+ )
+
+ return {
+ tableRef,
+ columns: sizedColumns,
+ hasAutoSizedColumns: Object.keys(columns).some(
+ (key) => columns[key].width === undefined && contentWidths[key] !== undefined
+ ),
+ }
+}