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(lemon-table): avoid rerendering rows on bulk selection (#130375)

posthog[bot]726ddf7e8239
diff --git a/frontend/src/lib/lemon-ui/LemonTable/BulkSelectionCheckbox.tsx b/frontend/src/lib/lemon-ui/LemonTable/BulkSelectionCheckbox.tsx
new file mode 100644
index 000000000000..99a3864a5d66
--- /dev/null
+++ b/frontend/src/lib/lemon-ui/LemonTable/BulkSelectionCheckbox.tsx
@@ -0,0 +1,20 @@
+import { useContext } from 'react'
+
+import { LemonCheckbox, LemonCheckboxProps } from '../LemonCheckbox'
+import { bulkSelectionContext } from './bulkSelectionContext'
+import { BulkSelectionKey } from './useBulkSelection'
+
+export function BulkSelectionCheckbox({
+ selectionKey,
+ ...props
+}: Omit<LemonCheckboxProps, 'checked'> & { selectionKey?: BulkSelectionKey }): JSX.Element {
+ const { selectedKeysSet, isAllOnPageSelected, isSomeOnPageSelected } = useContext(bulkSelectionContext)
+ const checked =
+ selectionKey === undefined
+ ? isSomeOnPageSelected
+ ? 'indeterminate'
+ : isAllOnPageSelected
+ : selectedKeysSet.has(selectionKey)
+
+ return <LemonCheckbox {...props} checked={checked} />
+}
diff --git a/frontend/src/lib/lemon-ui/LemonTable/LemonTable.test.tsx b/frontend/src/lib/lemon-ui/LemonTable/LemonTable.test.tsx
index ca5c1e387cce..cb454679c338 100644
--- a/frontend/src/lib/lemon-ui/LemonTable/LemonTable.test.tsx
+++ b/frontend/src/lib/lemon-ui/LemonTable/LemonTable.test.tsx
@@ -35,6 +35,43 @@ describe('LemonTable', () => {
afterEach(cleanup)
+ it('updates bulk checkboxes without rendering data cells again', () => {
+ const renderCell = jest.fn((_: unknown, row: Row) => row.name)
+ const renderActions = jest.fn((_context: { selectedKeys: ReadonlyArray<string | number> }) => (
+ <span>Bulk actions</span>
+ ))
+ render(
+ <LemonTable
+ dataSource={DATA}
+ rowKey="id"
+ columns={[{ title: 'Name', render: renderCell }]}
+ bulkSelection={{
+ rowAriaLabel: (row) => `Select ${row.name}`,
+ headerAriaLabel: 'Select page',
+ renderActions,
+ }}
+ />
+ )
+ renderCell.mockClear()
+
+ fireEvent.click(screen.getByLabelText('Select alpha'))
+
+ expect(screen.getByLabelText('Select alpha')).toBeChecked()
+ expect(screen.getByLabelText('Select beta')).not.toBeChecked()
+ expect(screen.getByLabelText('Select page').closest('.LemonCheckbox')).toHaveClass(
+ 'LemonCheckbox--indeterminate'
+ )
+ expect(renderActions.mock.calls.at(-1)?.[0]).toMatchObject({ selectedKeys: [1] })
+ expect(renderCell).not.toHaveBeenCalled()
+
+ fireEvent.click(screen.getByLabelText('Select page'))
+ for (const row of DATA) {
+ expect(screen.getByLabelText(`Select ${row.name}`)).toBeChecked()
+ }
+ expect(screen.getByLabelText('Select page')).toBeChecked()
+ expect(renderCell).not.toHaveBeenCalled()
+ })
+
it.each([
{ children: 'plain data', props: { title: 'data title' } },
{ props: { dangerouslySetInnerHTML: { __html: '<b>plain data</b>' } } },
diff --git a/frontend/src/lib/lemon-ui/LemonTable/LemonTable.tsx b/frontend/src/lib/lemon-ui/LemonTable/LemonTable.tsx
index e8d1f4ce59d0..dab0ddd5d9a6 100644
--- a/frontend/src/lib/lemon-ui/LemonTable/LemonTable.tsx
+++ b/frontend/src/lib/lemon-ui/LemonTable/LemonTable.tsx
@@ -7,7 +7,6 @@ import { router } from 'kea-router'
import React, { HTMLProps, useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { IconInfo } from '@posthog/icons'
-import { LemonCheckbox } from '@posthog/lemon-ui'
import { useCellCopyContextMenu } from 'lib/hooks/useCellCopyContextMenu'
import { IconWithCount } from 'lib/lemon-ui/icons'
@@ -20,6 +19,8 @@ import { useColumnWidths } from '../../hooks/useColumnWidths'
import { PaginationAuto, PaginationControl, PaginationManual, usePagination } from '../PaginationControl'
import { Tooltip } from '../Tooltip'
import { BulkSelectionBar } from './BulkSelectionBar'
+import { BulkSelectionCheckbox } from './BulkSelectionCheckbox'
+import { bulkSelectionContext } from './bulkSelectionContext'
import {
determineColumnKey,
getColumnWidthCap,
@@ -37,6 +38,7 @@ import { BulkSelectionConfig, BulkSelectionKey, useBulkSelection } from './useBu
/** Sentinel passed to `useBulkSelection` when `bulkSelection` is undefined — the hook still runs
* unconditionally so hook order is stable, but its result is never read. */
const UNUSED_ROW_KEY = (): string | number => 0
+const DEFAULT_NOUNS: [string, string] = ['entry', 'entries']
/** Text extracted from a cell for "Copy cell contents". Joins the cell's direct child nodes with a
* space — using `textContent` on the whole cell would both smush visually-separated children
@@ -197,7 +199,7 @@ export function LemonTable<T extends Record<string, any>, K extends BulkSelectio
useURLForSorting = true,
loadingSkeletonRows = 1,
emptyState,
- nouns = ['entry', 'entries'],
+ nouns = DEFAULT_NOUNS,
className,
style,
tableStyle,
@@ -399,6 +401,7 @@ export function LemonTable<T extends Record<string, any>, K extends BulkSelectio
clearSelectionKey: bulkSelection?.clearSelectionKey,
})
+ const { toggleRow, toggleAllOnPage, pageHasSelectableRows } = bulk
const effectiveNoun = bulkSelection?.noun ?? nouns
const selectionColumn = useMemo<LemonTableColumn<T, undefined> | null>(() => {
if (!bulkSelection) {
@@ -408,12 +411,11 @@ export function LemonTable<T extends Record<string, any>, K extends BulkSelectio
key: '__bulk-selection__',
width: 32,
title: (
- <LemonCheckbox
- checked={bulk.isSomeOnPageSelected ? 'indeterminate' : bulk.isAllOnPageSelected}
- onChange={bulk.toggleAllOnPage}
+ <BulkSelectionCheckbox
+ onChange={toggleAllOnPage}
aria-label={bulkSelection.headerAriaLabel ?? `Select all ${effectiveNoun[1]} on this page`}
disabledReason={
- !bulk.pageHasSelectableRows ? `No ${effectiveNoun[1]} on this page can be selected` : null
+ !pageHasSelectableRows ? `No ${effectiveNoun[1]} on this page can be selected` : null
}
/>
),
@@ -428,10 +430,10 @@ export function LemonTable<T extends Record<string, any>, K extends BulkSelectio
? gate.disabledReason
: null
return (
- <LemonCheckbox
- checked={bulk.selectedKeysSet.has(key)}
+ <BulkSelectionCheckbox
+ selectionKey={key}
onChange={(_value, event) =>
- bulk.toggleRow(key, pageIndex, (event.nativeEvent as MouseEvent).shiftKey ?? false)
+ toggleRow(key, pageIndex, (event.nativeEvent as MouseEvent).shiftKey ?? false)
}
disabledReason={disabledReason}
aria-label={bulkSelection.rowAriaLabel?.(record)}
@@ -439,7 +441,15 @@ export function LemonTable<T extends Record<string, any>, K extends BulkSelectio
)
},
}
- }, [bulkSelection, bulk, resolveRowKey, paginationState.currentStartIndex, effectiveNoun])
+ }, [
+ bulkSelection,
+ toggleRow,
+ toggleAllOnPage,
+ pageHasSelectableRows,
+ resolveRowKey,
+ paginationState.currentStartIndex,
+ effectiveNoun,
+ ])
const columnGroups = useMemo<LemonTableColumnGroup<T>[]>(() => {
if (!selectionColumn) {
@@ -600,7 +610,7 @@ export function LemonTable<T extends Record<string, any>, K extends BulkSelectio
)
return (
- <>
+ <bulkSelectionContext.Provider value={bulk}>
{bulkSelection && <BulkSelectionBar context={bulk.context} config={bulkSelection} noun={effectiveNoun} />}
<div
id={id}
@@ -1102,7 +1112,7 @@ export function LemonTable<T extends Record<string, any>, K extends BulkSelectio
</ScrollableShadows>
</div>
{enableCellCopy && copyMenu}
- </>
+ </bulkSelectionContext.Provider>
)
}
diff --git a/frontend/src/lib/lemon-ui/LemonTable/bulkSelectionContext.ts b/frontend/src/lib/lemon-ui/LemonTable/bulkSelectionContext.ts
new file mode 100644
index 000000000000..94f3edb9d8df
--- /dev/null
+++ b/frontend/src/lib/lemon-ui/LemonTable/bulkSelectionContext.ts
@@ -0,0 +1,7 @@
+import { createContext } from 'react'
+
+import { UseBulkSelectionResult } from './useBulkSelection'
+
+export const bulkSelectionContext = createContext<
+ Pick<UseBulkSelectionResult<never>, 'selectedKeysSet' | 'isAllOnPageSelected' | 'isSomeOnPageSelected'>
+>({ selectedKeysSet: new Set(), isAllOnPageSelected: false, isSomeOnPageSelected: false })
diff --git a/frontend/src/lib/lemon-ui/LemonTable/useBulkSelection.ts b/frontend/src/lib/lemon-ui/LemonTable/useBulkSelection.ts
index fe0e170a343b..aac578287fc2 100644
--- a/frontend/src/lib/lemon-ui/LemonTable/useBulkSelection.ts
+++ b/frontend/src/lib/lemon-ui/LemonTable/useBulkSelection.ts
@@ -196,16 +196,30 @@ export function useBulkSelection<T extends Record<string, any>, K extends BulkSe
[selectedKeys, selectedRecords, clearSelection, setSelectedKeys]
)
- return {
- selectedKeys,
- selectedKeysSet,
- isAllOnPageSelected,
- isSomeOnPageSelected,
- pageHasSelectableRows: selectableKeysOnPage.length > 0,
- toggleRow,
- toggleAllOnPage,
- clearSelection,
- setSelectedKeys,
- context,
- }
+ return useMemo(
+ () => ({
+ selectedKeys,
+ selectedKeysSet,
+ isAllOnPageSelected,
+ isSomeOnPageSelected,
+ pageHasSelectableRows: selectableKeysOnPage.length > 0,
+ toggleRow,
+ toggleAllOnPage,
+ clearSelection,
+ setSelectedKeys,
+ context,
+ }),
+ [
+ selectedKeys,
+ selectedKeysSet,
+ isAllOnPageSelected,
+ isSomeOnPageSelected,
+ selectableKeysOnPage.length,
+ toggleRow,
+ toggleAllOnPage,
+ clearSelection,
+ setSelectedKeys,
+ context,
+ ]
+ )
}
diff --git a/products/dashboards/frontend/dashboards/DashboardsTable.test.tsx b/products/dashboards/frontend/dashboards/DashboardsTable.test.tsx
index 89cda4784b4f..459dc2e21e7d 100644
--- a/products/dashboards/frontend/dashboards/DashboardsTable.test.tsx
+++ b/products/dashboards/frontend/dashboards/DashboardsTable.test.tsx
@@ -20,20 +20,28 @@ jest.mock('./DashboardsFiltersBar', () => ({ DashboardsFiltersBar: () => null })
// Render the row menu's overlay inline, so the row actions are assertable without driving a popover open.
jest.mock('lib/lemon-ui/LemonButton/More', () => ({ More: ({ overlay }: any) => <div>{overlay}</div> }))
+let mockUseRealTable = false
let mockCtx: { selectedKeys: number[]; clearSelection: jest.Mock; setSelectedKeys: jest.Mock }
jest.mock('lib/lemon-ui/LemonTable', () => ({
- LemonTable: ({ bulkSelection, columns, dataSource }: any) => (
- <div>
- {bulkSelection ? bulkSelection.renderActions(mockCtx) : null}
- {dataSource.map((row: any) => (
- <div key={row.id}>
- {columns.map((column: any, index: number) =>
- column.render ? <span key={index}>{column.render(row[column.dataIndex], row)}</span> : null
- )}
- </div>
- ))}
- </div>
- ),
+ LemonTable: (props: any) => {
+ if (mockUseRealTable) {
+ const ActualLemonTable = jest.requireActual('lib/lemon-ui/LemonTable').LemonTable
+ return <ActualLemonTable {...props} />
+ }
+ const { bulkSelection, columns, dataSource } = props
+ return (
+ <div>
+ {bulkSelection ? bulkSelection.renderActions(mockCtx) : null}
+ {dataSource.map((row: any) => (
+ <div key={row.id}>
+ {columns.map((column: any, index: number) =>
+ column.render ? <span key={index}>{column.render(row[column.dataIndex], row)}</span> : null
+ )}
+ </div>
+ ))}
+ </div>
+ )
+ },
}))
describe('DashboardsTable move to folder', () => {
@@ -46,6 +54,7 @@ describe('DashboardsTable move to folder', () => {
afterEach(cleanup)
beforeEach(() => {
+ mockUseRealTable = false
jest.clearAllMocks()
;(useActions as jest.Mock).mockReturnValue({
unpinDashboard: jest.fn(),
@@ -92,6 +101,18 @@ describe('DashboardsTable move to folder', () => {
)
}
+ it('checks a dashboard after one click and uses that selection for bulk move', () => {
+ mockUseRealTable = true
+ renderTable([1, 2])
+
+ fireEvent.click(screen.getByLabelText('Select dashboard Dashboard 1'))
+
+ expect(screen.getByLabelText('Select dashboard Dashboard 1')).toBeChecked()
+ expect(screen.getByLabelText('Select dashboard Dashboard 2')).not.toBeChecked()
+ fireEvent.click(screen.getByText('Move to folder'))
+ expect(moveDashboardsToFolder).toHaveBeenCalledWith([1], 'bulk', expect.any(Function))
+ })
+
it('keeps insights by default and passes the delete insights option on submit', () => {
const openForm = jest.spyOn(LemonDialog, 'openForm').mockImplementation(() => {})
renderTable([1, 2], [1, 2])
diff --git a/products/dashboards/frontend/dashboards/DashboardsTable.tsx b/products/dashboards/frontend/dashboards/DashboardsTable.tsx
index 7b7f49adae9d..f79f39758abc 100644
--- a/products/dashboards/frontend/dashboards/DashboardsTable.tsx
+++ b/products/dashboards/frontend/dashboards/DashboardsTable.tsx
@@ -1,5 +1,6 @@
import { useActions, useValues } from 'kea'
import posthog from 'posthog-js'
+import { useMemo } from 'react'
import { IconFolder, IconHome, IconLock, IconPin, IconPinFilled, IconShare, IconTrash } from '@posthog/icons'
@@ -16,6 +17,7 @@ import { LemonRow } from 'lib/lemon-ui/LemonRow'
import { LemonTable, LemonTableColumn, LemonTableColumns } from 'lib/lemon-ui/LemonTable'
import { atColumn, createdAtColumn, createdByColumn } from 'lib/lemon-ui/LemonTable/columnUtils'
import { LemonTableLink } from 'lib/lemon-ui/LemonTable/LemonTableLink'
+import { BulkSelectionConfig } from 'lib/lemon-ui/LemonTable/useBulkSelection'
import { Link } from 'lib/lemon-ui/Link'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { accessLevelSatisfied } from 'lib/utils/accessControlUtils'
@@ -365,6 +367,78 @@ export function DashboardsTable({
},
]
+ const bulkSelection = useMemo<BulkSelectionConfig<DashboardType, number>>(
+ () => ({
+ barClassName: 'mb-2 flex-wrap',
+ getKey: (dashboard: DashboardType): number => dashboard.id,
+ isRowSelectable: (dashboard: DashboardType) =>
+ accessLevelSatisfied(
+ AccessControlResourceType.Dashboard,
+ dashboard.user_access_level,
+ AccessControlLevel.Editor
+ )
+ ? true
+ : { disabledReason: DASHBOARD_CANNOT_EDIT_MESSAGE },
+ rowAriaLabel: (dashboard: DashboardType) => `Select dashboard ${dashboard.name}`,
+ headerAriaLabel: 'Select all dashboards on this page',
+ renderActions: (ctx) => (
+ <>
+ <BulkMoveToFolderButton ctx={ctx} filedIds={filedDashboardIds} onMove={moveDashboardsToFolder} />
+ <BulkUpdateTagsButton
+ resource="dashboards"
+ selectedIds={ctx.selectedKeys}
+ onSuccess={() => {
+ ctx.clearSelection()
+ dashboardsModel.actions.loadDashboards()
+ }}
+ />
+ <LemonButton
+ size="small"
+ type="primary"
+ status="danger"
+ icon={<IconTrash />}
+ loading={bulkDeleteResponseLoading || dashboardsLoading}
+ disabledReason={ctx.selectedKeys.length > 100 ? 'Select at most 100 dashboards' : undefined}
+ data-attr="dashboards-bulk-delete"
+ onClick={() => {
+ const ids = [...ctx.selectedKeys]
+ const noun = ids.length === 1 ? 'dashboard' : 'dashboards'
+ LemonDialog.openForm({
+ title: `Delete ${ids.length} ${noun}?`,
+ initialValues: { deleteInsights: false },
+ content: (
+ <LemonField
+ name="deleteInsights"
+ help="This only deletes insights that are not on any remaining dashboard."
+ >
+ {({ value, onChange }) => (
+ <LemonCheckbox
+ checked={!!value}
+ onChange={onChange}
+ label="Delete the selected dashboards' insights"
+ data-attr="bulk-delete-dashboard-insights-checkbox"
+ />
+ )}
+ </LemonField>
+ ),
+ onSubmit: ({ deleteInsights }) =>
+ bulkDeleteDashboards({
+ ids,
+ deleteInsights,
+ onStillSelected: ctx.setSelectedKeys,
+ }),
+ primaryButtonProps: { children: 'Delete dashboards', status: 'danger' },
+ })
+ }}
+ >
+ Delete selected
+ </LemonButton>
+ </>
+ ),
+ }),
+ [filedDashboardIds, moveDashboardsToFolder, bulkDeleteResponseLoading, dashboardsLoading, bulkDeleteDashboards]
+ )
+
return (
<>
<DashboardsFiltersBar extraActions={extraActions} />
@@ -382,80 +456,7 @@ export function DashboardsTable({
onSort={tableSortingChanged}
emptyState="No dashboards matching your filters!"
nouns={['dashboard', 'dashboards']}
- bulkSelection={{
- barClassName: 'mb-2 flex-wrap',
- getKey: (dashboard: DashboardType): number => dashboard.id,
- isRowSelectable: (dashboard: DashboardType) =>
- accessLevelSatisfied(
- AccessControlResourceType.Dashboard,
- dashboard.user_access_level,
- AccessControlLevel.Editor
- )
- ? true
- : { disabledReason: DASHBOARD_CANNOT_EDIT_MESSAGE },
- rowAriaLabel: (dashboard: DashboardType) => `Select dashboard ${dashboard.name}`,
- headerAriaLabel: 'Select all dashboards on this page',
- renderActions: (ctx) => (
- <>
- <BulkMoveToFolderButton
- ctx={ctx}
- filedIds={filedDashboardIds}
- onMove={moveDashboardsToFolder}
- />
- <BulkUpdateTagsButton
- resource="dashboards"
- selectedIds={ctx.selectedKeys}
- onSuccess={() => {
- ctx.clearSelection()
- dashboardsModel.actions.loadDashboards()
- }}
- />
- <LemonButton
- size="small"
- type="primary"
- status="danger"
- icon={<IconTrash />}
- loading={bulkDeleteResponseLoading || dashboardsLoading}
- disabledReason={
- ctx.selectedKeys.length > 100 ? 'Select at most 100 dashboards' : undefined
- }
- data-attr="dashboards-bulk-delete"
- onClick={() => {
- const ids = [...ctx.selectedKeys]
- const noun = ids.length === 1 ? 'dashboard' : 'dashboards'
- LemonDialog.openForm({
- title: `Delete ${ids.length} ${noun}?`,
- initialValues: { deleteInsights: false },
- content: (
- <LemonField
- name="deleteInsights"
- help="This only deletes insights that are not on any remaining dashboard."
- >
- {({ value, onChange }) => (
- <LemonCheckbox
- checked={!!value}
- onChange={onChange}
- label="Delete the selected dashboards' insights"
- data-attr="bulk-delete-dashboard-insights-checkbox"
- />
- )}
- </LemonField>
- ),
- onSubmit: ({ deleteInsights }) =>
- bulkDeleteDashboards({
- ids,
- deleteInsights,
- onStillSelected: ctx.setSelectedKeys,
- }),
- primaryButtonProps: { children: 'Delete dashboards', status: 'danger' },
- })
- }}
- >
- Delete selected
- </LemonButton>
- </>
- ),
- }}
+ bulkSelection={bulkSelection}
/>
</>
)