: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
fix(customer-analytics): bound account column auto-sizing (#103982)
Arthur Moreira de Deusf15b82e60ca4
diff --git a/docs/internal/customer-analytics/accounts-table.md b/docs/internal/customer-analytics/accounts-table.mdindex 00c6495bd8b0..ac924cc9e720 100644--- a/docs/internal/customer-analytics/accounts-table.md+++ b/docs/internal/customer-analytics/accounts-table.md@@ -54,7 +54,7 @@ An explicit refresh uses the known mode for its request, then lets the response## Column widths-The Customer analytics Accounts list sizes new columns to their rendered header and loaded values.+The Customer analytics Accounts list sizes new columns to their rendered header and a bounded sample of 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.@@ -67,9 +67,14 @@ Saved widths and existing column defaults take precedence over automatic sizing:| 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.+`useAccountColumnAutoSizing.ts` builds a hidden measurement table from each automatic column's header and at most six body cells, rather than cloning the rendered table.+It ranks a fixed candidate window from the first and last loaded values, then favors the longest text and the most structurally complex renderers.+The measurement table preserves each column's rendered position, so boundary padding stays accurate.+This covers appended pages and common cells such as links, dates, numeric values, avatars, buttons, and multiline content while keeping measurement work bounded.+A value outside the sample can be wider than the selected candidates, so the 200px cap and manual resize control remain the fallback for unusual renderers.+Expanded rows are excluded.+Measurements run after render, reuse widths while the sampled markup is unchanged, update when changed or newly loaded content enters the sample, and remove the temporary table immediately.+Automatic widths stay local to the mounted table 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.diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.mdindex 09b77bffa491..1e4aa8bc4a14 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. 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.+`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 a bounded sample of loaded values, between 80px and 200px. `useAccountColumnAutoSizing` measures each header plus at most six body cells after render, including paging boundaries and candidates with long text or compound renderers. It ranks a fixed window from the first and last loaded cells, preserves rendered column positions in its measurement table, caches widths by stable column alias and sampled markup, remeasures changed samples, excludes expanded rows, and removes its small hidden measurement table immediately. Automatic widths remain local to the mounted table. 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/useAccountColumnAutoSizing.ts b/products/customer_analytics/frontend/components/Accounts/useAccountColumnAutoSizing.tsindex b86f8cb2add1..696f3c30ff74 100644--- a/products/customer_analytics/frontend/components/Accounts/useAccountColumnAutoSizing.ts+++ b/products/customer_analytics/frontend/components/Accounts/useAccountColumnAutoSizing.ts@@ -4,35 +4,217 @@ 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+const MIN_AUTO_COLUMN_WIDTH = 80+const MAX_AUTO_COLUMN_WIDTH = 200+const MAX_SAMPLED_BODY_CELLS = 6+const MAX_RANKED_BODY_CELLS = 40+const SORT_CONTROL_ATTRIBUTE_PREFIX = 'accounts-table-sort-'++type ColumnMeasurement = {+ columnName: string+ header: HTMLTableCellElement+ bodyCells: HTMLTableCellElement[]+ signature: string+}++type WidthCacheEntry = {+ signature: string+ width: number+}++type BodyCellRankingMetadata = {+ index: number+ normalizedTextLength: number+ descendantElementCount: number+}++function getNormalizedTextLength(cell: HTMLTableCellElement): number {+ return (cell.textContent ?? '').replace(/\s+/g, ' ').trim().length+}++function getBodyCellRankingMetadata(cell: HTMLTableCellElement, index: number): BodyCellRankingMetadata {+ return {+ index,+ normalizedTextLength: getNormalizedTextLength(cell),+ descendantElementCount: cell.querySelectorAll('*').length,+ }+}++function getRankedBodyCellIndexes(cellCount: number): number[] {+ if (cellCount <= MAX_RANKED_BODY_CELLS) {+ return Array.from({ length: cellCount }, (_, index) => index)+ }++ const cellsPerBoundary = MAX_RANKED_BODY_CELLS / 2+ return [+ ...Array.from({ length: cellsPerBoundary }, (_, index) => index),+ ...Array.from({ length: cellsPerBoundary }, (_, index) => cellCount - cellsPerBoundary + index),+ ]+}++function selectBodyCellsForMeasurement(cells: HTMLTableCellElement[]): HTMLTableCellElement[] {+ if (cells.length <= MAX_SAMPLED_BODY_CELLS) {+ return cells+ }++ const selectedIndexes = new Set([0, cells.length - 1])+ const candidateMetadata = getRankedBodyCellIndexes(cells.length).map((index) =>+ getBodyCellRankingMetadata(cells[index], index)+ )+ const candidatesByTextLength = [...candidateMetadata].sort(+ (left, right) => right.normalizedTextLength - left.normalizedTextLength || left.index - right.index+ )+ const candidatesByElementCount = [...candidateMetadata].sort(+ (left, right) => right.descendantElementCount - left.descendantElementCount || left.index - right.index+ )+ const candidateRankings = [candidatesByTextLength, candidatesByElementCount]++ // Boundary candidates cover appended pages. The rankings favor long text and compound renderers without cloning every row.+ for (let rank = 0; selectedIndexes.size < MAX_SAMPLED_BODY_CELLS; rank++) {+ for (const ranking of candidateRankings) {+ const candidate = ranking[rank]+ if (candidate !== undefined) {+ selectedIndexes.add(candidate.index)+ }+ if (selectedIndexes.size === MAX_SAMPLED_BODY_CELLS) {+ break+ }+ }+ }++ return [...selectedIndexes].sort((left, right) => left - right).map((index) => cells[index])+}++function measurementSignature(header: HTMLTableCellElement, bodyCells: HTMLTableCellElement[]): string {+ return [header, ...bodyCells].map((cell) => `${cell.className}:${cell.innerHTML}`).join('\u0000')+}++function getColumnMeasurements(table: HTMLTableElement, columnNames: Set<string>): ColumnMeasurement[] {+ const headerRow = Array.from(table.tHead?.rows ?? []).find((row) =>+ row.querySelector(`[data-attr^="${SORT_CONTROL_ATTRIBUTE_PREFIX}"]`)+ )+ if (!headerRow) {+ return []+ }++ const measurements: ColumnMeasurement[] = []+ for (const header of Array.from(headerRow.cells)) {+ const sortControl = header.querySelector<HTMLElement>(`[data-attr^="${SORT_CONTROL_ATTRIBUTE_PREFIX}"]`)+ const attribute = sortControl?.getAttribute('data-attr')+ const columnName = attribute?.startsWith(SORT_CONTROL_ATTRIBUTE_PREFIX)+ ? attribute.slice(SORT_CONTROL_ATTRIBUTE_PREFIX.length)+ : undefined+ if (!columnName || !columnNames.has(columnName)) {+ continue+ }++ const cells: HTMLTableCellElement[] = []+ for (const body of Array.from(table.tBodies)) {+ for (const row of Array.from(body.rows)) {+ if (row.classList.contains('LemonTable__expansion')) {+ continue+ }+ const cell = row.cells.item(header.cellIndex)+ if (cell && cell.colSpan === 1) {+ cells.push(cell)+ }+ }+ }+ const bodyCells = selectBodyCellsForMeasurement(cells)+ measurements.push({+ columnName,+ header,+ bodyCells,+ signature: measurementSignature(header, bodyCells),+ })+ }+ return measurements+}++function cloneMeasurementCell(cell: HTMLTableCellElement): HTMLTableCellElement {+ const clone = cell.cloneNode(true) as HTMLTableCellElement+ clone.removeAttribute('style')+ clone.style.maxWidth = 'none'+ clone.style.whiteSpace = 'nowrap'+ clone.removeAttribute('id')+ clone.querySelectorAll('[id]').forEach((element) => element.removeAttribute('id'))+ return clone+}++function measureColumns(table: HTMLTableElement, measurements: ColumnMeasurement[]): Record<string, number> {+ const measurementTable = document.createElement('table')+ measurementTable.className = table.classNamemeasurementTable.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'- })+ measurementTable.setAttribute('aria-hidden', 'true')++ const sourceHeaderCells = Array.from(measurements[0]?.header.parentElement?.children ?? []).filter(+ (cell): cell is HTMLTableCellElement => cell instanceof HTMLTableCellElement+ )+ const measurementsByHeader = new Map(measurements.map((measurement) => [measurement.header, measurement]))+ const headerRow = measurementTable.createTHead().insertRow()+ for (const header of sourceHeaderCells) {+ headerRow.appendChild(cloneMeasurementCell(header))+ }++ const body = measurementTable.createTBody()+ const sampleCount = Math.max(...measurements.map(({ bodyCells }) => bodyCells.length), 0)+ for (let sampleIndex = 0; sampleIndex < sampleCount; sampleIndex++) {+ const row = body.insertRow()+ for (const header of sourceHeaderCells) {+ const cell = measurementsByHeader.get(header)?.bodyCells[sampleIndex]+ row.appendChild(cell ? cloneMeasurementCell(cell) : document.createElement('td'))+ }+ }+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+ return Object.fromEntries(+ measurements.map(({ columnName, header }) => [+ columnName,+ Math.min(+ MAX_AUTO_COLUMN_WIDTH,+ Math.max(+ MIN_AUTO_COLUMN_WIDTH,+ Math.ceil(headerRow.cells[header.cellIndex].getBoundingClientRect().width)+ )+ ),+ ])+ )} finally {measurementTable.remove()}}+function getContentWidths(+ table: HTMLTableElement,+ columnNames: string[],+ widthCache: Map<string, WidthCacheEntry>+): Record<string, number> {+ const measurements = getColumnMeasurements(table, new Set(columnNames))+ const widths: Record<string, number> = {}+ const changedMeasurements: ColumnMeasurement[] = []++ for (const measurement of measurements) {+ const cached = widthCache.get(measurement.columnName)+ if (cached?.signature === measurement.signature) {+ widths[measurement.columnName] = cached.width+ } else {+ changedMeasurements.push(measurement)+ }+ }++ const measuredWidths = changedMeasurements.length > 0 ? measureColumns(table, changedMeasurements) : {}+ for (const measurement of changedMeasurements) {+ const width = measuredWidths[measurement.columnName]+ widths[measurement.columnName] = width+ widthCache.set(measurement.columnName, { signature: measurement.signature, width })+ }+ return widths+}+export function useAccountColumnAutoSizing(columns: Record<string, QueryContextColumn>,response: unknown,@@ -43,16 +225,20 @@ export function useAccountColumnAutoSizing(hasAutoSizedColumns: boolean} {const tableRef = useRef<HTMLDivElement>(null)+ const widthCache = useRef(new Map<string, WidthCacheEntry>())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) {+ if (!table || loading || response === null || response === undefined || columnNames.length === 0) {return}- const widths = getContentWidths(table, columnNames)- setContentWidths((previous) => (objectsEqual(previous, widths) ? previous : widths))+ const widths = getContentWidths(table, columnNames, widthCache.current)+ setContentWidths((previous) => {+ const next = { ...previous, ...widths }+ return objectsEqual(previous, next) ? previous : next+ })}, [columns, response, loading])const sizedColumns = useMemo(