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.

feat(lemon-table): rule of three - move bulk selection to lemon table (#57963)

Paul D'Ambra6eb763cb84da
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 80875502b99f..14da4a51a286 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -96,18 +96,22 @@ snapshots:
hash: v1.k794b7964.b1d9dcf611e6103856c1e579471fcc8d15e5ede8d778f58119af30defd021088.yuhFcITo9oT9yqz-ilwd1uzRK-Q9jRg3C9olYPw_hu4
components-alerts-quiet-hours-fields--default--light:
hash: v1.k794b7964.a2293bde4bb0b7ca27dfd7ee41226407780d9848000a22b9ccd5903674163749.AY5DM6ohNxpR3I4WEpxtTkkrtEij5AAL_VJOYjJXkko
- components-bulkupdatetagspopover--add-mode--dark:
- hash: v1.k794b7964.c5a3ec413ef4ad2ee955fd467ab59482f7c20aca2e7cc9856472c9245119f6fb.9oSSrwMTUQDjDNYoTidpTv1r8_5TdKnP0j5_Wbc24lc
- components-bulkupdatetagspopover--add-mode--light:
- hash: v1.k794b7964.1f8c2007bc78ae1258bc950f9e120a51972545ccd2f74e92a5008a41e25e77f3.APyQYtd6ozQYv9TNxr-ux25ikKYl8D2oqxUL5tv2X04
- components-bulkupdatetagspopover--remove-mode--dark:
- hash: v1.k794b7964.08255603facd8f9690777650572946568a8a67cf1f60ae9107a5e57c4ae2448f.6ZaA7NYuOFxWr4unq-LXQvKiLdSRg7RiYEIX-8q57_E
- components-bulkupdatetagspopover--remove-mode--light:
- hash: v1.k794b7964.7735bb23d9df03eb1b96d60eb641d9630988d2d95f5eb7f3801555b03be4fcd4.qS5NlT8yovIICCy02HdKal4hScC6b1yn-7LtjwiC7U8
- components-bulkupdatetagspopover--replace-mode--dark:
- hash: v1.k794b7964.3f3babb0eaa296f54fc0decb47682d561e9c49dd57adf2b60149e8b4cb4aec2f.WIzr4OnalGzurLAw9cBJcGMrK9pHzvhLhTjs5W4nQQo
- components-bulkupdatetagspopover--replace-mode--light:
- hash: v1.k794b7964.91e36b28d1e3844c5fb498aa4cc30bec73f3c85ed7c5be07221505657d80ef40.T9utABklZMumF-GSALbzQdypSq0ababXP3T7Lv68sdQ
+ components-bulkupdatetagsbutton--add-mode--dark:
+ hash: v1.k794b7964.ba66e3fd796ded95414954112b8e8ad07474b5be373cb4e98ecf3e56d8f61aab.jgsY9nY4c4c5rgf0ML5534zPOMlCIbIubJMaH2hRaig
+ components-bulkupdatetagsbutton--add-mode--light:
+ hash: v1.k794b7964.bdeff3ffa5f086ef81b099aa68f8343e086561c8c16003f7111b0c857c301f98.0RvnQ-YB-KABmt75anXwk3txhnet53EYQUCqfJ0VbU8
+ components-bulkupdatetagsbutton--closed--dark:
+ hash: v1.k794b7964.8a24fb21a71abb594a602f884319369622e9ff6bc8bcf7eb3a98150f231c7f11.GW8aRN4_mLjZn6I8wj0M7kbJsHNsz2mRzpsxqy9J3js
+ components-bulkupdatetagsbutton--closed--light:
+ hash: v1.k794b7964.b02dec65fc27f9a3d595eb121034a53017ffc06f4626b2b3a322087774e4f5c0.6QbrqTlrOcPu_36qRGXdxPGDwMj7IlaXj7lPg4r1ylg
+ components-bulkupdatetagsbutton--remove-mode--dark:
+ hash: v1.k794b7964.e495160ca5fae1981bcfacb0fd03325272706856074445fcaae33fa8eac28540.muBxDo_TfsAtT-b5xg72MXQ09P7N5emaTx2cRSfaiAY
+ components-bulkupdatetagsbutton--remove-mode--light:
+ hash: v1.k794b7964.d60627ec07354d5f52a684ac086b7a79c1f80e69922ad8045a9646f6212f7d2b.NocLOei5AdVpcSp5Z__ESfeJckSYWNgyFiOx0x8QiaU
+ components-bulkupdatetagsbutton--replace-mode--dark:
+ hash: v1.k794b7964.f04904fa63c957d681811fa5169ef3c8ae91c586248d1d288ad212e355ccf2fe.YcxQ1_WnvIYVrLew9xyurIg3yC5FFvr3XkVyOBFq0EE
+ components-bulkupdatetagsbutton--replace-mode--light:
+ hash: v1.k794b7964.379cf8e29d15c49e9dced0e75d7dc6c25936204286649beef587801633564121.wYCp32fZHjbDeJb5u_l7qYy823rCGHUMZIBfMRYfMYY
components-cards-button-tile-card--template--dark:
hash: v1.k794b7964.ea8f8f9e593a467027450a8ba4241c3b3160387a41dcbd2a7fa6fc3e3299fffa.AE40xjOLMiJfje4e2EC8Mpc00oXcDCL9gVW8xqGnblQ
components-cards-button-tile-card--template--light:
@@ -3000,6 +3004,14 @@ snapshots:
hash: v1.k794b7964.2496b73d402ac7675459ba9c4907611190b909e72f5688c59d653948466fdf4e.xytn22NqQA2ZtUpc7Kdh0aS9DN_cPBH8YGnTTUhmF0I
lemon-ui-lemon-table--stealth--light:
hash: v1.k794b7964.2f8811ffba12b3a41728553bd97cb50df586aa2fc6f39fdbe27fb1a3b05f515c.rT3cQl-y4vzpsRiRzKqRgpOHLkRjka1C4IfdNNLDeBM
+ lemon-ui-lemon-table--with-bulk-selection-nothing-selected--dark:
+ hash: v1.k794b7964.d8a3ded706df19e45d084dd4e38e23934b7256367324a3c12ca784ef278d007f._oX-4LZqneMp4U_fbgaiJKBvz-qexiYALGMEhvVwwyc
+ lemon-ui-lemon-table--with-bulk-selection-nothing-selected--light:
+ hash: v1.k794b7964.6b787b98404bc74f827fa3e78dc087d54d9e313b7eea1a0735388a926b31378f.ZEKrOFkieiHabBPgQsz8wdwZYyJOCXTDewNLK6apEEE
+ lemon-ui-lemon-table--with-bulk-selection-two-selected--dark:
+ hash: v1.k794b7964.d144bbfd3cf2dedfa4fa2d33982b141beeaa1d5ed9c671ea6ad6af0412410d51.r7vMxzq__W1_0hyNVO-RTDAzi3DFnAkFf2KE_xMUBH8
+ lemon-ui-lemon-table--with-bulk-selection-two-selected--light:
+ hash: v1.k794b7964.ccf8678c7587aac626871864be691994e48657cba88e5e3d09e84a7824f80860.SOwODJorbbCNh1BtzcxJjpdfoAvx0zNcACj94NjCOUg
lemon-ui-lemon-table--with-cell-actions--dark:
hash: v1.k794b7964.ff9c32e64b48b9c8cd6b7aee426ad871750504c61826e5c4e0d1c3624fdf1802.ubsc393AEuOfe9hpCM2OBWvHNSuD2SUENLS7BH-gnZ8
lemon-ui-lemon-table--with-cell-actions--light:
diff --git a/frontend/src/lib/components/BulkActions/BulkActionToolbar.tsx b/frontend/src/lib/components/BulkActions/BulkActionToolbar.tsx
deleted file mode 100644
index f32b1f780589..000000000000
--- a/frontend/src/lib/components/BulkActions/BulkActionToolbar.tsx
+++ /dev/null
@@ -1,54 +0,0 @@
-import { useActions, useValues } from 'kea'
-import { ReactNode } from 'react'
-
-import { IconPencil } from '@posthog/icons'
-import { LemonButton } from '@posthog/lemon-ui'
-
-import { Popover } from 'lib/lemon-ui/Popover'
-import { BulkTaggableResource, listSelectionLogic } from 'lib/logic/listSelectionLogic'
-
-import { BulkUpdateTagsPopover } from './BulkUpdateTagsPopover'
-
-export function BulkActionToolbar({
- resource,
- children,
-}: {
- resource: BulkTaggableResource
- children?: ReactNode
-}): JSX.Element | null {
- const logic = listSelectionLogic({ resource })
- const { selectedCount, bulkTagsPopoverVisible, bulkUpdateTagsResponseLoading } = useValues(logic)
- const { clearSelection, showBulkTagsPopover, hideBulkTagsPopover } = useActions(logic)
-
- if (selectedCount === 0) {
- return null
- }
-
- return (
- <div className="flex items-center gap-2">
- <span className="text-muted text-sm">
- {selectedCount} item{selectedCount !== 1 ? 's' : ''} selected
- </span>
- <LemonButton type="secondary" size="small" onClick={clearSelection}>
- Clear
- </LemonButton>
- <Popover
- visible={bulkTagsPopoverVisible}
- onClickOutside={hideBulkTagsPopover}
- overlay={<BulkUpdateTagsPopover resource={resource} />}
- placement="bottom-end"
- >
- <LemonButton
- type="secondary"
- size="small"
- icon={<IconPencil />}
- onClick={showBulkTagsPopover}
- loading={bulkUpdateTagsResponseLoading}
- >
- Update tags
- </LemonButton>
- </Popover>
- {children}
- </div>
- )
-}
diff --git a/frontend/src/lib/components/BulkActions/BulkUpdateTagsButton.stories.tsx b/frontend/src/lib/components/BulkActions/BulkUpdateTagsButton.stories.tsx
new file mode 100644
index 000000000000..051f89ebe444
--- /dev/null
+++ b/frontend/src/lib/components/BulkActions/BulkUpdateTagsButton.stories.tsx
@@ -0,0 +1,65 @@
+import type { Meta, StoryObj } from '@storybook/react'
+import { screen, within } from '@testing-library/dom'
+import userEvent from '@testing-library/user-event'
+
+import { useStorybookMocks } from '~/mocks/browser'
+
+import { BulkUpdateTagsButton } from './BulkUpdateTagsButton'
+
+const RESOURCE = 'feature_flags' as const
+const SELECTED_IDS = [1, 2, 3]
+
+const meta: Meta<typeof BulkUpdateTagsButton> = {
+ title: 'Components/BulkUpdateTagsButton',
+ component: BulkUpdateTagsButton,
+ parameters: { layout: 'fullscreen' },
+ decorators: [
+ function MocksDecorator(Story) {
+ useStorybookMocks({
+ get: {
+ '/api/projects/:team_id/tags': ['production', 'staging', 'beta', 'internal'],
+ },
+ })
+ // Reserve enough viewport for the popover (placement: 'bottom-end') to render
+ // entirely within the snapshot. The popover content is ~320px wide and ~360px tall.
+ return (
+ <div className="flex items-start justify-end p-4" style={{ minHeight: 480, minWidth: 420 }}>
+ <Story />
+ </div>
+ )
+ },
+ ],
+ args: { resource: RESOURCE, selectedIds: SELECTED_IDS },
+}
+export default meta
+
+type Story = StoryObj<typeof BulkUpdateTagsButton>
+
+async function openAndPickAction(canvasElement: HTMLElement, action: 'Add' | 'Remove' | 'Replace all'): Promise<void> {
+ const canvas = within(canvasElement)
+ const trigger = await canvas.findByRole('button', { name: 'Update tags' })
+ await userEvent.click(trigger)
+ // Popover overlay renders to a portal, so query at the document level rather than canvas.
+ const segment = await screen.findByRole('button', { name: action })
+ await userEvent.click(segment)
+}
+
+export const Closed: Story = {}
+
+export const AddMode: Story = {
+ play: async ({ canvasElement }) => {
+ await openAndPickAction(canvasElement, 'Add')
+ },
+}
+
+export const RemoveMode: Story = {
+ play: async ({ canvasElement }) => {
+ await openAndPickAction(canvasElement, 'Remove')
+ },
+}
+
+export const ReplaceMode: Story = {
+ play: async ({ canvasElement }) => {
+ await openAndPickAction(canvasElement, 'Replace all')
+ },
+}
diff --git a/frontend/src/lib/components/BulkActions/BulkUpdateTagsButton.tsx b/frontend/src/lib/components/BulkActions/BulkUpdateTagsButton.tsx
new file mode 100644
index 000000000000..e19a0c810dee
--- /dev/null
+++ b/frontend/src/lib/components/BulkActions/BulkUpdateTagsButton.tsx
@@ -0,0 +1,135 @@
+import { useActions, useValues } from 'kea'
+import { useState } from 'react'
+
+import { IconPencil } from '@posthog/icons'
+import { LemonBanner, LemonButton, LemonInputSelect, lemonToast } from '@posthog/lemon-ui'
+
+import api from 'lib/api'
+import { LemonSegmentedButton } from 'lib/lemon-ui/LemonSegmentedButton'
+import { Popover } from 'lib/lemon-ui/Popover'
+import { projectLogic } from 'scenes/projectLogic'
+
+import { tagsModel } from '~/models/tagsModel'
+
+export type BulkTagAction = 'add' | 'remove' | 'set'
+
+export interface BulkUpdateTagsResult {
+ updated: Array<{ id: number; tags: string[] }>
+ skipped: Array<{ id: number; reason: string }>
+}
+
+export type BulkTaggableResource = 'feature_flags' | 'dashboards' | 'insights'
+
+interface BulkUpdateTagsButtonProps {
+ resource: BulkTaggableResource
+ selectedIds: ReadonlyArray<number>
+ onSuccess?: () => void
+}
+
+export function BulkUpdateTagsButton({ resource, selectedIds, onSuccess }: BulkUpdateTagsButtonProps): JSX.Element {
+ const [visible, setVisible] = useState(false)
+ const [tagAction, setTagAction] = useState<BulkTagAction>('add')
+ const [selectedTags, setSelectedTags] = useState<string[]>([])
+ const [loading, setLoading] = useState(false)
+
+ const { tags } = useValues(tagsModel)
+ const { loadTags } = useActions(tagsModel)
+ const { currentProjectId } = useValues(projectLogic)
+
+ const open = (): void => {
+ loadTags()
+ setVisible(true)
+ }
+
+ const close = (): void => {
+ setVisible(false)
+ setTagAction('add')
+ setSelectedTags([])
+ }
+
+ const submit = async (): Promise<void> => {
+ setLoading(true)
+ try {
+ const response = (await api.create(`api/projects/${currentProjectId}/${resource}/bulk_update_tags/`, {
+ ids: Array.from(selectedIds),
+ action: tagAction,
+ tags: selectedTags,
+ })) as BulkUpdateTagsResult
+ const { updated, skipped } = response
+ if (skipped.length === 0) {
+ lemonToast.success(`Updated tags on ${updated.length} item${updated.length !== 1 ? 's' : ''}`)
+ } else {
+ lemonToast.warning(
+ `Updated tags on ${updated.length} item${updated.length !== 1 ? 's' : ''}. ${skipped.length} skipped due to permissions.`
+ )
+ }
+ close()
+ loadTags()
+ onSuccess?.()
+ } catch {
+ lemonToast.error('Failed to update tags')
+ } finally {
+ setLoading(false)
+ }
+ }
+
+ return (
+ <Popover
+ visible={visible}
+ onClickOutside={close}
+ placement="bottom-end"
+ overlay={
+ <div className="p-3 space-y-3 w-80">
+ <div className="font-medium text-sm">
+ Update tags for {selectedIds.length} item{selectedIds.length !== 1 ? 's' : ''}
+ </div>
+ <LemonSegmentedButton
+ value={tagAction}
+ onChange={setTagAction}
+ options={[
+ { value: 'add' as const, label: 'Add' },
+ { value: 'remove' as const, label: 'Remove' },
+ { value: 'set' as const, label: 'Replace all' },
+ ]}
+ size="small"
+ fullWidth
+ />
+ <LemonInputSelect
+ mode="multiple"
+ allowCustomValues
+ value={selectedTags}
+ options={(tags as string[]).map((t: string) => ({ key: t, label: t }))}
+ onChange={setSelectedTags}
+ placeholder="Enter tags..."
+ data-attr="bulk-tag-input"
+ />
+ {tagAction === 'set' && (
+ <LemonBanner type="warning">
+ This will replace all existing tags on the selected items.
+ </LemonBanner>
+ )}
+ <div className="flex gap-2 justify-end">
+ <LemonButton size="small" type="secondary" onClick={close}>
+ Cancel
+ </LemonButton>
+ <LemonButton
+ size="small"
+ type="primary"
+ onClick={() => void submit()}
+ loading={loading}
+ disabledReason={
+ selectedTags.length === 0 && tagAction !== 'set' ? 'Select at least one tag' : undefined
+ }
+ >
+ {tagAction === 'add' ? 'Add tags' : tagAction === 'remove' ? 'Remove tags' : 'Replace tags'}
+ </LemonButton>
+ </div>
+ </div>
+ }
+ >
+ <LemonButton type="secondary" size="small" icon={<IconPencil />} onClick={open}>
+ Update tags
+ </LemonButton>
+ </Popover>
+ )
+}
diff --git a/frontend/src/lib/components/BulkActions/BulkUpdateTagsPopover.stories.tsx b/frontend/src/lib/components/BulkActions/BulkUpdateTagsPopover.stories.tsx
deleted file mode 100644
index e4ddc0c329f7..000000000000
--- a/frontend/src/lib/components/BulkActions/BulkUpdateTagsPopover.stories.tsx
+++ /dev/null
@@ -1,62 +0,0 @@
-import type { Meta, StoryObj } from '@storybook/react'
-import { useActions } from 'kea'
-
-import { LemonButton } from '@posthog/lemon-ui'
-
-import { useDelayedOnMountEffect } from 'lib/hooks/useOnMountEffect'
-import { Popover } from 'lib/lemon-ui/Popover'
-import { BulkTagAction, listSelectionLogic } from 'lib/logic/listSelectionLogic'
-
-import { useStorybookMocks } from '~/mocks/browser'
-
-import { BulkUpdateTagsPopover } from './BulkUpdateTagsPopover'
-
-const RESOURCE = 'feature_flags' as const
-
-const meta: Meta<typeof BulkUpdateTagsPopover> = {
- title: 'Components/BulkUpdateTagsPopover',
- component: BulkUpdateTagsPopover,
- parameters: {
- layout: 'centered',
- },
-}
-export default meta
-
-type Story = StoryObj<typeof BulkUpdateTagsPopover>
-
-function MockedPopover({ action }: { action: BulkTagAction }): JSX.Element {
- useStorybookMocks({
- get: {
- '/api/projects/:team_id/tags': ['production', 'staging', 'beta', 'internal'],
- },
- })
- const { setSelectedIds, setPopoverTagAction, setPopoverSelectedTags } = useActions(
- listSelectionLogic({ resource: RESOURCE })
- )
-
- useDelayedOnMountEffect(() => {
- setSelectedIds([1, 2, 3])
- setPopoverTagAction(action)
- setPopoverSelectedTags(['production', 'beta'])
- }, 10)
-
- return (
- <Popover visible overlay={<BulkUpdateTagsPopover resource={RESOURCE} />}>
- <LemonButton type="secondary" size="small">
- Update tags
- </LemonButton>
- </Popover>
- )
-}
-
-export const AddMode: Story = {
- render: () => <MockedPopover action="add" />,
-}
-
-export const RemoveMode: Story = {
- render: () => <MockedPopover action="remove" />,
-}
-
-export const ReplaceMode: Story = {
- render: () => <MockedPopover action="set" />,
-}
diff --git a/frontend/src/lib/components/BulkActions/BulkUpdateTagsPopover.tsx b/frontend/src/lib/components/BulkActions/BulkUpdateTagsPopover.tsx
deleted file mode 100644
index 7232e157b300..000000000000
--- a/frontend/src/lib/components/BulkActions/BulkUpdateTagsPopover.tsx
+++ /dev/null
@@ -1,77 +0,0 @@
-import { useActions, useValues } from 'kea'
-
-import { LemonBanner, LemonButton, LemonInputSelect } from '@posthog/lemon-ui'
-
-import { LemonSegmentedButton } from 'lib/lemon-ui/LemonSegmentedButton'
-import { BulkTaggableResource, listSelectionLogic } from 'lib/logic/listSelectionLogic'
-
-import { tagsModel } from '~/models/tagsModel'
-
-export function BulkUpdateTagsPopover({ resource }: { resource: BulkTaggableResource }): JSX.Element {
- const { tags } = useValues(tagsModel)
-
- const logic = listSelectionLogic({ resource })
- const { bulkUpdateTagsResponseLoading, selectedCount, popoverTagAction, popoverSelectedTags } = useValues(logic)
- const { bulkUpdateTags, hideBulkTagsPopover, setPopoverTagAction, setPopoverSelectedTags } = useActions(logic)
-
- const handleSubmit = (): void => {
- bulkUpdateTags({ action: popoverTagAction, tags: popoverSelectedTags })
- }
-
- return (
- <div className="p-3 space-y-3 w-80">
- <div className="font-medium text-sm">
- Update tags for {selectedCount} item{selectedCount !== 1 ? 's' : ''}
- </div>
-
- <LemonSegmentedButton
- value={popoverTagAction}
- onChange={setPopoverTagAction}
- options={[
- { value: 'add' as const, label: 'Add' },
- { value: 'remove' as const, label: 'Remove' },
- { value: 'set' as const, label: 'Replace all' },
- ]}
- size="small"
- fullWidth
- />
-
- <LemonInputSelect
- mode="multiple"
- allowCustomValues
- value={popoverSelectedTags}
- options={tags.map((t) => ({ key: t, label: t }))}
- onChange={setPopoverSelectedTags}
- placeholder="Enter tags..."
- data-attr="bulk-tag-input"
- />
-
- {popoverTagAction === 'set' && (
- <LemonBanner type="warning">This will replace all existing tags on the selected items.</LemonBanner>
- )}
-
- <div className="flex gap-2 justify-end">
- <LemonButton size="small" type="secondary" onClick={hideBulkTagsPopover}>
- Cancel
- </LemonButton>
- <LemonButton
- size="small"
- type="primary"
- onClick={handleSubmit}
- loading={bulkUpdateTagsResponseLoading}
- disabledReason={
- popoverSelectedTags.length === 0 && popoverTagAction !== 'set'
- ? 'Select at least one tag'
- : undefined
- }
- >
- {popoverTagAction === 'add'
- ? 'Add tags'
- : popoverTagAction === 'remove'
- ? 'Remove tags'
- : 'Replace tags'}
- </LemonButton>
- </div>
- </div>
- )
-}
diff --git a/frontend/src/lib/components/BulkActions/SelectionCheckbox.tsx b/frontend/src/lib/components/BulkActions/SelectionCheckbox.tsx
deleted file mode 100644
index bca35177cf4c..000000000000
--- a/frontend/src/lib/components/BulkActions/SelectionCheckbox.tsx
+++ /dev/null
@@ -1,34 +0,0 @@
-import { useActions, useValues } from 'kea'
-
-import { LemonCheckbox } from '@posthog/lemon-ui'
-
-import { BulkTaggableResource, listSelectionLogic, PageItem } from 'lib/logic/listSelectionLogic'
-
-export function SelectionCheckbox({
- resource,
- id,
- index,
- allPageItems,
- disabledReason,
- ariaLabel,
-}: {
- resource: BulkTaggableResource
- id: number
- index: number
- allPageItems: PageItem[]
- disabledReason?: string
- ariaLabel?: string
-}): JSX.Element {
- const logic = listSelectionLogic({ resource })
- const { selectedIdsSet } = useValues(logic)
- const { toggleSelection } = useActions(logic)
-
- return (
- <LemonCheckbox
- checked={selectedIdsSet.has(id)}
- onChange={() => toggleSelection(id, index, allPageItems)}
- disabledReason={disabledReason}
- aria-label={ariaLabel}
- />
- )
-}
diff --git a/frontend/src/lib/lemon-ui/LemonTable/BulkSelectionBar.tsx b/frontend/src/lib/lemon-ui/LemonTable/BulkSelectionBar.tsx
new file mode 100644
index 000000000000..76b31bc7e86b
--- /dev/null
+++ b/frontend/src/lib/lemon-ui/LemonTable/BulkSelectionBar.tsx
@@ -0,0 +1,33 @@
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+
+import { BulkSelectionConfig, BulkSelectionContext, BulkSelectionKey } from './useBulkSelection'
+
+export interface BulkSelectionBarProps<T extends Record<string, any>, K extends BulkSelectionKey = BulkSelectionKey> {
+ context: BulkSelectionContext<T, K>
+ config: BulkSelectionConfig<T, K>
+ noun: [string, string]
+}
+
+export function BulkSelectionBar<T extends Record<string, any>, K extends BulkSelectionKey = BulkSelectionKey>({
+ context,
+ config,
+ noun,
+}: BulkSelectionBarProps<T, K>): JSX.Element | null {
+ if (context.selectedCount === 0) {
+ return null
+ }
+ const [singular, plural] = noun
+ const word = context.selectedCount === 1 ? singular : plural
+
+ return (
+ <div className="flex items-center justify-end gap-2 min-h-9 px-1 LemonTable__bulk-selection-bar">
+ <span className="text-secondary text-sm">
+ {context.selectedCount} {word} selected
+ </span>
+ <LemonButton type="secondary" size="small" onClick={context.clearSelection}>
+ Clear
+ </LemonButton>
+ {config.renderActions(context)}
+ </div>
+ )
+}
diff --git a/frontend/src/lib/lemon-ui/LemonTable/LemonTable.stories.tsx b/frontend/src/lib/lemon-ui/LemonTable/LemonTable.stories.tsx
index e741839ee438..f6e1397cd7fa 100644
--- a/frontend/src/lib/lemon-ui/LemonTable/LemonTable.stories.tsx
+++ b/frontend/src/lib/lemon-ui/LemonTable/LemonTable.stories.tsx
@@ -514,3 +514,55 @@ export const WithHorizontalAndVerticalOverflow: Story = {
)
},
}
+
+const BULK_SELECTION_COLUMNS: LemonTableColumns<MockPerson> = [
+ { title: 'Name', dataIndex: 'name' },
+ { title: 'Occupation', dataIndex: 'occupation' },
+]
+
+const BULK_SELECTION_PEOPLE = MANY_PEOPLE.slice(0, 5)
+
+function BulkSelectionTable({ initialSelected }: { initialSelected: string[] }): JSX.Element {
+ return (
+ <LemonTable
+ columns={BULK_SELECTION_COLUMNS}
+ dataSource={BULK_SELECTION_PEOPLE}
+ rowKey="name"
+ bulkSelection={{
+ getKey: (person: MockPerson): string => person.name,
+ initialSelectedKeys: initialSelected,
+ noun: ['person', 'people'],
+ rowAriaLabel: (person: MockPerson) => `Select ${person.name}`,
+ headerAriaLabel: 'Select all people on this page',
+ renderActions: (ctx) => (
+ <>
+ <LemonButton
+ type="secondary"
+ size="small"
+ onClick={() => alert(`Editing ${ctx.selectedCount} person(s)`)}
+ >
+ Edit selected
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ status="danger"
+ size="small"
+ icon={<IconTrash />}
+ onClick={() => alert(`Deleting ${ctx.selectedKeys.join(', ')}`)}
+ >
+ Delete selected
+ </LemonButton>
+ </>
+ ),
+ }}
+ />
+ )
+}
+
+export const WithBulkSelectionNothingSelected: Story = {
+ render: () => <BulkSelectionTable initialSelected={[]} />,
+}
+
+export const WithBulkSelectionTwoSelected: Story = {
+ render: () => <BulkSelectionTable initialSelected={['Werner C.', 'Ursula Z.']} />,
+}
diff --git a/frontend/src/lib/lemon-ui/LemonTable/LemonTable.tsx b/frontend/src/lib/lemon-ui/LemonTable/LemonTable.tsx
index 07a5a3935973..94ecc0ab958a 100644
--- a/frontend/src/lib/lemon-ui/LemonTable/LemonTable.tsx
+++ b/frontend/src/lib/lemon-ui/LemonTable/LemonTable.tsx
@@ -6,6 +6,7 @@ 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 { ScrollableShadows } from 'lib/components/ScrollableShadows/ScrollableShadows'
import { IconWithCount } from 'lib/lemon-ui/icons'
@@ -16,13 +17,19 @@ import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
import { useColumnWidths } from '../../hooks/useColumnWidths'
import { PaginationAuto, PaginationControl, PaginationManual, usePagination } from '../PaginationControl'
import { Tooltip } from '../Tooltip'
+import { BulkSelectionBar } from './BulkSelectionBar'
import { determineColumnKey, getStickyColumnInfo } from './columnUtils'
import { LemonTableLoader } from './LemonTableLoader'
import { Sorting, SortingIndicator, getNextSorting } from './sorting'
import { TableRow } from './TableRow'
-import { ExpandableConfig, LemonTableColumnGroup, LemonTableColumns } from './types'
+import { ExpandableConfig, LemonTableColumn, LemonTableColumnGroup, LemonTableColumns } from './types'
+import { BulkSelectionConfig, BulkSelectionKey, useBulkSelection } from './useBulkSelection'
-export interface LemonTableProps<T extends Record<string, any>> {
+/** 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
+
+export interface LemonTableProps<T extends Record<string, any>, K extends BulkSelectionKey = BulkSelectionKey> {
/** Table ID that will also be used in pagination to add uniqueness to search params (page + order). */
id?: string
columns: LemonTableColumns<T>
@@ -96,9 +103,12 @@ export interface LemonTableProps<T extends Record<string, any>> {
rowActions?: (record: T, recordIndex: number) => React.ReactNode | null
/** Whether to hide the sorting indicator when no sort is active. Defaults to false. */
hideSortingIndicatorWhenInactive?: boolean
+ /** Enable bulk-selection — adds a leading checkbox column and renders the consumer-provided
+ * action bar above the table whenever any rows are selected. */
+ bulkSelection?: BulkSelectionConfig<T, K>
}
-export function LemonTable<T extends Record<string, any>>({
+export function LemonTable<T extends Record<string, any>, K extends BulkSelectionKey = BulkSelectionKey>({
id,
columns: rawColumns,
dataSource = [],
@@ -136,7 +146,13 @@ export function LemonTable<T extends Record<string, any>>({
allowContentScroll = false,
rowActions,
hideSortingIndicatorWhenInactive = false,
-}: LemonTableProps<T>): JSX.Element {
+ bulkSelection,
+}: LemonTableProps<T, K>): JSX.Element {
+ if (bulkSelection && !bulkSelection.getKey && rowKey === undefined) {
+ throw new Error(
+ 'LemonTable `bulkSelection` requires either `bulkSelection.getKey` or a `rowKey` (string or function) to identify rows'
+ )
+ }
/** Search param that will be used for storing and syncing sorting */
const currentSortingParam = id ? `${id}_order` : 'order'
@@ -167,7 +183,7 @@ export function LemonTable<T extends Record<string, any>>({
[location, searchParams, hashParams, push, useURLForSorting, onSort, currentSortingParam]
)
- const columnGroups = useMemo(
+ const baseColumnGroups = useMemo(
() =>
(rawColumns.length > 0 && 'children' in rawColumns[0]
? rawColumns
@@ -178,14 +194,14 @@ export function LemonTable<T extends Record<string, any>>({
]) as LemonTableColumnGroup<T>[],
[rawColumns]
)
- const columns = useMemo(() => columnGroups.flatMap((group) => group.children), [columnGroups])
+ const baseColumns = useMemo(() => baseColumnGroups.flatMap((group) => group.children), [baseColumnGroups])
const scrollRef = useRef<HTMLDivElement>(null)
// Width calculation for pinned columns
const { columnWidths: pinnedColumnWidths, tableRef } = useColumnWidths({
columnKeys: pinnedColumns,
- columns,
+ columns: baseColumns,
})
/** Sorting. */
@@ -207,7 +223,7 @@ export function LemonTable<T extends Record<string, any>>({
const sortedDataSource = useMemo(() => {
if (currentSorting) {
const { columnKey: sortColumnKey, order: sortOrder } = currentSorting
- const sorter = columns.find(
+ const sorter = baseColumns.find(
(searchColumn) => searchColumn.sorter && determineColumnKey(searchColumn, 'sorting') === sortColumnKey
)?.sorter
if (typeof sorter === 'function') {
@@ -215,9 +231,91 @@ export function LemonTable<T extends Record<string, any>>({
}
}
return dataSource
- }, [dataSource, currentSorting, columns])
+ }, [dataSource, currentSorting, baseColumns])
const paginationState = usePagination(sortedDataSource, pagination, id)
+
+ const resolveRowKey = useMemo<(record: T) => K>(() => {
+ if (bulkSelection?.getKey) {
+ return bulkSelection.getKey
+ }
+ if (typeof rowKey === 'function') {
+ return (record: T): K => rowKey(record, 0) as K
+ }
+ if (typeof rowKey === 'string') {
+ const key = rowKey
+ return (record: T): K => record[key] as K
+ }
+ // The constructor throws above if `bulkSelection` is set without a key source, so this
+ // sentinel is only reached when `bulkSelection` is undefined and the hook's results aren't
+ // consumed anyway.
+ return UNUSED_ROW_KEY as unknown as (record: T) => K
+ }, [bulkSelection, rowKey])
+
+ const bulk = useBulkSelection<T, K>({
+ pageRecords: paginationState.dataSourcePage,
+ getKey: resolveRowKey,
+ isRowSelectable: bulkSelection?.isRowSelectable,
+ initialSelectedKeys: bulkSelection?.initialSelectedKeys,
+ })
+
+ const effectiveNoun = bulkSelection?.noun ?? nouns
+ const selectionColumn = useMemo<LemonTableColumn<T, undefined> | null>(() => {
+ if (!bulkSelection) {
+ return null
+ }
+ return {
+ key: '__bulk-selection__',
+ width: 32,
+ title: (
+ <LemonCheckbox
+ checked={bulk.isSomeOnPageSelected ? 'indeterminate' : bulk.isAllOnPageSelected}
+ onChange={bulk.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
+ }
+ />
+ ),
+ render: function RenderBulkSelectionCell(_, record: T, recordIndex: number) {
+ const key = resolveRowKey(record)
+ const pageIndex = recordIndex - paginationState.currentStartIndex
+ const gate = bulkSelection.isRowSelectable ? bulkSelection.isRowSelectable(record, pageIndex) : true
+ const disabledReason: string | null =
+ gate === false
+ ? 'Selection disabled'
+ : typeof gate === 'object' && gate !== null
+ ? gate.disabledReason
+ : null
+ return (
+ <LemonCheckbox
+ checked={bulk.selectedKeysSet.has(key)}
+ onChange={(_value, event) =>
+ bulk.toggleRow(key, pageIndex, (event.nativeEvent as MouseEvent).shiftKey ?? false)
+ }
+ disabledReason={disabledReason}
+ aria-label={bulkSelection.rowAriaLabel?.(record)}
+ />
+ )
+ },
+ }
+ }, [bulkSelection, bulk, resolveRowKey, paginationState.currentStartIndex, effectiveNoun])
+
+ const columnGroups = useMemo<LemonTableColumnGroup<T>[]>(() => {
+ if (!selectionColumn) {
+ return baseColumnGroups
+ }
+ return baseColumnGroups.map((group, index) =>
+ index === 0
+ ? {
+ ...group,
+ children: [selectionColumn as LemonTableColumn<T, keyof T | undefined>, ...group.children],
+ }
+ : group
+ )
+ }, [baseColumnGroups, selectionColumn])
+
+ const columns = useMemo(() => columnGroups.flatMap((group) => group.children), [columnGroups])
const previousPageRef = useRef<number | null>(null)
useEffect(() => {
@@ -261,350 +359,359 @@ export function LemonTable<T extends Record<string, any>>({
)
return (
- <div
- id={id}
- className={clsx(
- 'LemonTable',
- size && size !== 'middle' && `LemonTable--${size}`,
- inset && 'LemonTable--inset',
- loading && disableTableWhileLoading && 'LemonTable--loading',
- embedded && 'LemonTable--embedded',
- rowRibbonColor !== undefined && `LemonTable--with-ribbon`,
- stealth && 'LemonTable--stealth',
- !uppercaseHeader && 'LemonTable--lowercase-header',
- allowContentScroll && 'h-full min-h-0 overflow-hidden',
- className
- )}
- // eslint-disable-next-line react/forbid-dom-props
- style={style}
- data-attr={dataAttr}
- >
- <ScrollableShadows
- innerClassName={hideScrollbar ? 'hide-scrollbar' : undefined}
- direction={allowContentScroll ? undefined : 'horizontal'}
- scrollRef={scrollRef}
+ <>
+ {bulkSelection && <BulkSelectionBar context={bulk.context} config={bulkSelection} noun={effectiveNoun} />}
+ <div
+ id={id}
+ className={clsx(
+ 'LemonTable',
+ size && size !== 'middle' && `LemonTable--${size}`,
+ inset && 'LemonTable--inset',
+ loading && disableTableWhileLoading && 'LemonTable--loading',
+ embedded && 'LemonTable--embedded',
+ rowRibbonColor !== undefined && `LemonTable--with-ribbon`,
+ stealth && 'LemonTable--stealth',
+ !uppercaseHeader && 'LemonTable--lowercase-header',
+ allowContentScroll && 'h-full min-h-0 overflow-hidden',
+ className
+ )}
+ // eslint-disable-next-line react/forbid-dom-props
+ style={style}
+ data-attr={dataAttr}
>
- <div className="LemonTable__content">
- <table ref={tableRef}>
- <colgroup>
- {isRowExpansionToggleShown && <col style={{ width: '1%' }} /> /* Expand/collapse column */}
- {columns
- .filter((column) => !column.isHidden)
- .map((column, index) => (
- // eslint-disable-next-line react/forbid-dom-props
- <col
- key={`LemonTable-col-${index}`}
- // width:0 has no effect in auto-layout tables (ignored by Safari).
- // width:1% is a standard workaround to shrink a column to its content.
- style={{ width: column.width === 0 ? '1%' : column.width }}
- />
- ))}
- </colgroup>
- {showHeader && (
- <thead>
- {columnGroups.some((group) => group.title) && (
- <tr className="LemonTable__row--grouping">
- {
- isRowExpansionToggleShown && (
- <th className="LemonTable__toggle" />
- ) /* Expand/collapse */
- }
- {columnGroups.map((columnGroup, columnGroupIndex) =>
- columnGroupIndex === 0 && firstColumnSticky ? (
- <React.Fragment key={`LemonTable-th-group-${columnGroupIndex}`}>
+ <ScrollableShadows
+ innerClassName={hideScrollbar ? 'hide-scrollbar' : undefined}
+ direction={allowContentScroll ? undefined : 'horizontal'}
+ scrollRef={scrollRef}
+ >
+ <div className="LemonTable__content">
+ <table ref={tableRef}>
+ <colgroup>
+ {
+ isRowExpansionToggleShown && (
+ <col style={{ width: '1%' }} />
+ ) /* Expand/collapse column */
+ }
+ {columns
+ .filter((column) => !column.isHidden)
+ .map((column, index) => (
+ // eslint-disable-next-line react/forbid-dom-props
+ <col
+ key={`LemonTable-col-${index}`}
+ // width:0 has no effect in auto-layout tables (ignored by Safari).
+ // width:1% is a standard workaround to shrink a column to its content.
+ style={{ width: column.width === 0 ? '1%' : column.width }}
+ />
+ ))}
+ </colgroup>
+ {showHeader && (
+ <thead>
+ {columnGroups.some((group) => group.title) && (
+ <tr className="LemonTable__row--grouping">
+ {
+ isRowExpansionToggleShown && (
+ <th className="LemonTable__toggle" />
+ ) /* Expand/collapse */
+ }
+ {columnGroups.map((columnGroup, columnGroupIndex) =>
+ columnGroupIndex === 0 && firstColumnSticky ? (
+ <React.Fragment key={`LemonTable-th-group-${columnGroupIndex}`}>
+ <th
+ colSpan={1}
+ className="LemonTable__boundary LemonTable__header--sticky"
+ >
+ {columnGroup.title}
+ </th>
+ <th colSpan={columnGroup.children.length - 1} />
+ </React.Fragment>
+ ) : (
<th
- colSpan={1}
- className="LemonTable__boundary LemonTable__header--sticky"
+ key={`LemonTable-th-group-${columnGroupIndex}`}
+ colSpan={columnGroup.children.length}
+ className="LemonTable__boundary"
>
{columnGroup.title}
</th>
- <th colSpan={columnGroup.children.length - 1} />
- </React.Fragment>
- ) : (
- <th
- key={`LemonTable-th-group-${columnGroupIndex}`}
- colSpan={columnGroup.children.length}
- className="LemonTable__boundary"
- >
- {columnGroup.title}
- </th>
- )
- )}
- </tr>
- )}
- <tr>
- {!!expandable && <th className="LemonTable__toggle" /> /* Expand/collapse */}
- {columnGroups.flatMap((columnGroup, columnGroupIndex) =>
- columnGroup.children
- .filter((column) => !column.isHidden)
- .map((column, columnIndex) => {
- const columnKey = determineColumnKey(column) ?? `${columnIndex}`
- const stickyInfo = getStickyColumnInfo(
- columnKey,
- pinnedColumns,
- pinnedColumnWidths,
- columns
)
- const { isSticky: isPinned, leftPosition } = stickyInfo
+ )}
+ </tr>
+ )}
+ <tr>
+ {!!expandable && <th className="LemonTable__toggle" /> /* Expand/collapse */}
+ {columnGroups.flatMap((columnGroup, columnGroupIndex) =>
+ columnGroup.children
+ .filter((column) => !column.isHidden)
+ .map((column, columnIndex) => {
+ const columnKey = determineColumnKey(column) ?? `${columnIndex}`
+ const stickyInfo = getStickyColumnInfo(
+ columnKey,
+ pinnedColumns,
+ pinnedColumnWidths,
+ columns
+ )
+ const { isSticky: isPinned, leftPosition } = stickyInfo
- return (
- <th
- key={`LemonTable-th-${columnGroupIndex}-${columnKey}`}
- className={clsx(
- 'LemonTable__header',
- column.sorter && 'LemonTable__header--actionable',
- columnIndex === 0 && 'LemonTable__boundary',
- firstColumnSticky &&
- columnGroupIndex === 0 &&
- columnIndex === 0 &&
- 'LemonTable__header--sticky',
- isPinned && 'LemonTable__header--pinned',
- column.className
- )}
- /* eslint-disable-next-line react/forbid-dom-props */
- style={{
- textAlign: column.align,
- ...(isPinned ? { left: `${leftPosition}px` } : {}),
- }}
- >
- <div
- className="LemonTable__header-content"
+ return (
+ <th
+ key={`LemonTable-th-${columnGroupIndex}-${columnKey}`}
+ className={clsx(
+ 'LemonTable__header',
+ column.sorter && 'LemonTable__header--actionable',
+ columnIndex === 0 && 'LemonTable__boundary',
+ firstColumnSticky &&
+ columnGroupIndex === 0 &&
+ columnIndex === 0 &&
+ 'LemonTable__header--sticky',
+ isPinned && 'LemonTable__header--pinned',
+ column.className
+ )}
/* eslint-disable-next-line react/forbid-dom-props */
style={{
- justifyContent:
- column.align === 'center'
- ? 'center'
- : column.align === 'right'
- ? 'flex-end'
- : 'flex-start',
+ textAlign: column.align,
+ ...(isPinned ? { left: `${leftPosition}px` } : {}),
}}
- onClick={
- column.sorter
- ? (event) => {
- const target = event.target as HTMLElement
-
- // Check if the click happened on the checkbox input, label, or its specific SVG (LemonCheckbox__box)
- if (
- target.closest('.LemonCheckbox') ||
- target.classList.contains(
- 'LemonCheckbox__box'
- ) ||
- target.tagName.toLowerCase() ===
- 'label' ||
- target.tagName.toLowerCase() ===
- 'input' ||
- target.closest(
- '[data-attr="table-header-more"]'
- )
- ) {
- return // Do nothing if the click is on the checkbox or more button
- }
-
- const nextSorting = getNextSorting(
- currentSorting,
- determineColumnKey(column, 'sorting'),
- disableSortingCancellation,
- column.defaultSortOrder
- )
-
- setLocalSorting(nextSorting)
- }
- : undefined
- }
>
<div
- className={clsx(
- 'flex items-center',
- column?.fullWidth && 'w-full',
- column.sorter && 'cursor-pointer'
- )}
+ className="LemonTable__header-content"
/* eslint-disable-next-line react/forbid-dom-props */
- style={
- maxHeaderWidth
- ? { maxWidth: maxHeaderWidth }
+ style={{
+ justifyContent:
+ column.align === 'center'
+ ? 'center'
+ : column.align === 'right'
+ ? 'flex-end'
+ : 'flex-start',
+ }}
+ onClick={
+ column.sorter
+ ? (event) => {
+ const target = event.target as HTMLElement
+
+ // Check if the click happened on the checkbox input, label, or its specific SVG (LemonCheckbox__box)
+ if (
+ target.closest('.LemonCheckbox') ||
+ target.classList.contains(
+ 'LemonCheckbox__box'
+ ) ||
+ target.tagName.toLowerCase() ===
+ 'label' ||
+ target.tagName.toLowerCase() ===
+ 'input' ||
+ target.closest(
+ '[data-attr="table-header-more"]'
+ )
+ ) {
+ return // Do nothing if the click is on the checkbox or more button
+ }
+
+ const nextSorting = getNextSorting(
+ currentSorting,
+ determineColumnKey(column, 'sorting'),
+ disableSortingCancellation,
+ column.defaultSortOrder
+ )
+
+ setLocalSorting(nextSorting)
+ }
: undefined
}
>
- {column.tooltip ? (
- <Tooltip title={column.tooltip}>
- <div className="flex items-center">
- {column.title}
- <IconInfo className="ml-1 text-base" />
- </div>
- </Tooltip>
- ) : (
- column.title
- )}
- {column.sorter &&
- (() => {
- const columnKey = determineColumnKey(
- column,
- 'sorting'
- )
- const isActiveSort =
- currentSorting?.columnKey === columnKey
- const order = isActiveSort
- ? currentSorting.order
- : null
-
- // Hide indicator if inactive and hideSortingIndicatorWhenInactive is true
- if (
- hideSortingIndicatorWhenInactive &&
- !isActiveSort
- ) {
- return null
- }
-
- return (
- <Tooltip
- title={() => {
- const nextSorting = getNextSorting(
- currentSorting,
- columnKey,
- disableSortingCancellation,
- column.defaultSortOrder
- )
- return `Click to ${
- nextSorting
- ? nextSorting.order === 1
- ? 'sort ascending'
- : 'sort descending'
- : 'cancel sorting'
- }`
- }}
- >
- <SortingIndicator order={order} />
- </Tooltip>
- )
- })()}
- </div>
- {column.more &&
- (column.moreIcon ? (
- <LemonButtonWithDropdown
- aria-label="more"
- data-attr="table-header-more"
- icon={
- column.moreFilterCount !== undefined &&
- column.moreFilterCount > 0 ? (
- <IconWithCount
- count={column.moreFilterCount}
- showZero={false}
- status="danger"
+ <div
+ className={clsx(
+ 'flex items-center',
+ column?.fullWidth && 'w-full',
+ column.sorter && 'cursor-pointer'
+ )}
+ /* eslint-disable-next-line react/forbid-dom-props */
+ style={
+ maxHeaderWidth
+ ? { maxWidth: maxHeaderWidth }
+ : undefined
+ }
+ >
+ {column.tooltip ? (
+ <Tooltip title={column.tooltip}>
+ <div className="flex items-center">
+ {column.title}
+ <IconInfo className="ml-1 text-base" />
+ </div>
+ </Tooltip>
+ ) : (
+ column.title
+ )}
+ {column.sorter &&
+ (() => {
+ const columnKey = determineColumnKey(
+ column,
+ 'sorting'
+ )
+ const isActiveSort =
+ currentSorting?.columnKey === columnKey
+ const order = isActiveSort
+ ? currentSorting.order
+ : null
+
+ // Hide indicator if inactive and hideSortingIndicatorWhenInactive is true
+ if (
+ hideSortingIndicatorWhenInactive &&
+ !isActiveSort
+ ) {
+ return null
+ }
+
+ return (
+ <Tooltip
+ title={() => {
+ const nextSorting =
+ getNextSorting(
+ currentSorting,
+ columnKey,
+ disableSortingCancellation,
+ column.defaultSortOrder
+ )
+ return `Click to ${
+ nextSorting
+ ? nextSorting.order ===
+ 1
+ ? 'sort ascending'
+ : 'sort descending'
+ : 'cancel sorting'
+ }`
+ }}
>
- {column.moreIcon}
- </IconWithCount>
- ) : (
- column.moreIcon
+ <SortingIndicator order={order} />
+ </Tooltip>
)
- }
- dropdown={{
- placement: 'bottom-end',
- actionable: true,
- overlay: column.more,
- }}
- size="small"
- className="ml-1"
- />
- ) : (
- <More
- overlay={column.more}
- className="ml-1"
- data-attr="table-header-more"
- />
- ))}
- </div>
- </th>
- )
- })
- )}
- {rowActions && <th className="w-0" />}
- </tr>
- <tr className="LemonTable__loader-row">
- <th colSpan={headerLoaderColSpan} className="LemonTable__loader-host">
- <LemonTableLoader loading={loading} tag="div" />
- </th>
- </tr>
- </thead>
- )}
- <tbody>
- {paginationState.dataSourcePage.length ? (
- paginationState.dataSourcePage.map((record, rowIndex) => {
- const rowKeyDetermined = rowKey
- ? typeof rowKey === 'function'
- ? rowKey(record, rowIndex)
- : (record[rowKey] ?? rowIndex)
- : paginationState.currentStartIndex + rowIndex
- const rowClassNameDetermined =
- typeof rowClassName === 'function'
- ? rowClassName(record, rowIndex)
- : rowClassName
- const rowRibbonColorDetermined =
- typeof rowRibbonColor === 'function'
- ? rowRibbonColor(record, rowIndex) || 'var(--color-border-primary)'
- : rowRibbonColor
- const rowStatusDetermined =
- typeof rowStatus === 'function' ? rowStatus(record, rowIndex) : rowStatus
-
- return (
- <TableRow
- key={`LemonTable-tr-${rowKeyDetermined}`}
- record={record}
- recordIndex={paginationState.currentStartIndex + rowIndex}
- rowKeyDetermined={rowKeyDetermined}
- rowClassNameDetermined={rowClassNameDetermined}
- rowRibbonColorDetermined={rowRibbonColorDetermined}
- rowStatusDetermined={rowStatusDetermined}
- columnGroups={columnGroups}
- onRow={onRow}
- expandable={expandable}
- rowCount={paginationState.dataSourcePage.length}
- firstColumnSticky={firstColumnSticky}
- pinnedColumns={pinnedColumns}
- pinnedColumnWidths={pinnedColumnWidths}
- columns={columns}
- rowActions={rowActions}
- />
- )
- })
- ) : loading ? (
- Array(loadingSkeletonRows)
- .fill(null)
- .map((_, rowIndex) => (
- <tr key={`LemonTable-tr-${rowIndex} ph-no-capture`}>
- {columnGroups.flatMap((columnGroup, columnGroupIndex) =>
- columnGroup.children.map((column, columnIndex) => (
- <td
- key={`LemonTable-td-${columnGroupIndex}-${columnIndex}`}
- className={clsx(
- columnIndex === columnGroup.children.length - 1 &&
- 'LemonTable__boundary',
- firstColumnSticky &&
- columnIndex === 0 &&
- 'LemonTable__cell--sticky',
- column.className
- )}
- >
- <LemonSkeleton />
- </td>
- ))
- )}
- </tr>
- ))
- ) : (
- <tr className="LemonTable__empty-state">
- <td colSpan={columns.length + Number(!!expandable)}>
- {emptyState || `No ${nouns[1]}`}
- </td>
- </tr>
+ })()}
+ </div>
+ {column.more &&
+ (column.moreIcon ? (
+ <LemonButtonWithDropdown
+ aria-label="more"
+ data-attr="table-header-more"
+ icon={
+ column.moreFilterCount !== undefined &&
+ column.moreFilterCount > 0 ? (
+ <IconWithCount
+ count={column.moreFilterCount}
+ showZero={false}
+ status="danger"
+ >
+ {column.moreIcon}
+ </IconWithCount>
+ ) : (
+ column.moreIcon
+ )
+ }
+ dropdown={{
+ placement: 'bottom-end',
+ actionable: true,
+ overlay: column.more,
+ }}
+ size="small"
+ className="ml-1"
+ />
+ ) : (
+ <More
+ overlay={column.more}
+ className="ml-1"
+ data-attr="table-header-more"
+ />
+ ))}
+ </div>
+ </th>
+ )
+ })
+ )}
+ {rowActions && <th className="w-0" />}
+ </tr>
+ <tr className="LemonTable__loader-row">
+ <th colSpan={headerLoaderColSpan} className="LemonTable__loader-host">
+ <LemonTableLoader loading={loading} tag="div" />
+ </th>
+ </tr>
+ </thead>
)}
- </tbody>
- </table>
- {footer && <div className="LemonTable__footer">{footer}</div>}
-
- <PaginationControl {...paginationState} nouns={nouns} />
- <div className="LemonTable__overlay" />
- </div>
- </ScrollableShadows>
- </div>
+ <tbody>
+ {paginationState.dataSourcePage.length ? (
+ paginationState.dataSourcePage.map((record, rowIndex) => {
+ const rowKeyDetermined = rowKey
+ ? typeof rowKey === 'function'
+ ? rowKey(record, rowIndex)
+ : (record[rowKey] ?? rowIndex)
+ : paginationState.currentStartIndex + rowIndex
+ const rowClassNameDetermined =
+ typeof rowClassName === 'function'
+ ? rowClassName(record, rowIndex)
+ : rowClassName
+ const rowRibbonColorDetermined =
+ typeof rowRibbonColor === 'function'
+ ? rowRibbonColor(record, rowIndex) || 'var(--color-border-primary)'
+ : rowRibbonColor
+ const rowStatusDetermined =
+ typeof rowStatus === 'function' ? rowStatus(record, rowIndex) : rowStatus
+
+ return (
+ <TableRow
+ key={`LemonTable-tr-${rowKeyDetermined}`}
+ record={record}
+ recordIndex={paginationState.currentStartIndex + rowIndex}
+ rowKeyDetermined={rowKeyDetermined}
+ rowClassNameDetermined={rowClassNameDetermined}
+ rowRibbonColorDetermined={rowRibbonColorDetermined}
+ rowStatusDetermined={rowStatusDetermined}
+ columnGroups={columnGroups}
+ onRow={onRow}
+ expandable={expandable}
+ rowCount={paginationState.dataSourcePage.length}
+ firstColumnSticky={firstColumnSticky}
+ pinnedColumns={pinnedColumns}
+ pinnedColumnWidths={pinnedColumnWidths}
+ columns={columns}
+ rowActions={rowActions}
+ />
+ )
+ })
+ ) : loading ? (
+ Array(loadingSkeletonRows)
+ .fill(null)
+ .map((_, rowIndex) => (
+ <tr key={`LemonTable-tr-${rowIndex} ph-no-capture`}>
+ {columnGroups.flatMap((columnGroup, columnGroupIndex) =>
+ columnGroup.children.map((column, columnIndex) => (
+ <td
+ key={`LemonTable-td-${columnGroupIndex}-${columnIndex}`}
+ className={clsx(
+ columnIndex === columnGroup.children.length - 1 &&
+ 'LemonTable__boundary',
+ firstColumnSticky &&
+ columnIndex === 0 &&
+ 'LemonTable__cell--sticky',
+ column.className
+ )}
+ >
+ <LemonSkeleton />
+ </td>
+ ))
+ )}
+ </tr>
+ ))
+ ) : (
+ <tr className="LemonTable__empty-state">
+ <td colSpan={columns.length + Number(!!expandable)}>
+ {emptyState || `No ${nouns[1]}`}
+ </td>
+ </tr>
+ )}
+ </tbody>
+ </table>
+ {footer && <div className="LemonTable__footer">{footer}</div>}
+
+ <PaginationControl {...paginationState} nouns={nouns} />
+ <div className="LemonTable__overlay" />
+ </div>
+ </ScrollableShadows>
+ </div>
+ </>
)
}
diff --git a/frontend/src/lib/lemon-ui/LemonTable/index.ts b/frontend/src/lib/lemon-ui/LemonTable/index.ts
index f375acd2dffa..f257dc2d5954 100644
--- a/frontend/src/lib/lemon-ui/LemonTable/index.ts
+++ b/frontend/src/lib/lemon-ui/LemonTable/index.ts
@@ -2,3 +2,9 @@ export type { LemonTableProps } from './LemonTable'
export { LemonTable } from './LemonTable'
export type { Sorting } from './sorting'
export type { ExpandableConfig, LemonTableColumn, LemonTableColumnGroup, LemonTableColumns } from './types'
+export type {
+ BulkSelectionConfig,
+ BulkSelectionContext,
+ BulkSelectionKey,
+ BulkSelectionRowGate,
+} from './useBulkSelection'
diff --git a/frontend/src/lib/lemon-ui/LemonTable/useBulkSelection.test.ts b/frontend/src/lib/lemon-ui/LemonTable/useBulkSelection.test.ts
new file mode 100644
index 000000000000..051e62a9d37f
--- /dev/null
+++ b/frontend/src/lib/lemon-ui/LemonTable/useBulkSelection.test.ts
@@ -0,0 +1,179 @@
+import { act, renderHook } from '@testing-library/react'
+
+import { BulkSelectionRowGate, useBulkSelection } from './useBulkSelection'
+
+interface Row {
+ id: number
+ canEdit?: boolean
+}
+
+const PAGE: Row[] = [
+ { id: 1, canEdit: true },
+ { id: 2, canEdit: true },
+ { id: 3, canEdit: false },
+ { id: 4, canEdit: true },
+]
+
+const getKey = (row: Row): number => row.id
+const editableGate = (row: Row): BulkSelectionRowGate => (row.canEdit ? true : { disabledReason: 'no permission' })
+
+describe('useBulkSelection', () => {
+ it('starts with no selection', () => {
+ const { result } = renderHook(() => useBulkSelection({ pageRecords: PAGE, getKey }))
+ expect(result.current.selectedKeys).toEqual([])
+ expect(result.current.isAllOnPageSelected).toBe(false)
+ expect(result.current.isSomeOnPageSelected).toBe(false)
+ })
+
+ it('toggleRow toggles a single row in and out of the selection', () => {
+ const { result } = renderHook(() => useBulkSelection({ pageRecords: PAGE, getKey }))
+ act(() => result.current.toggleRow(2, 1))
+ expect(result.current.selectedKeys).toEqual([2])
+ expect(result.current.isSomeOnPageSelected).toBe(true)
+ act(() => result.current.toggleRow(2, 1))
+ expect(result.current.selectedKeys).toEqual([])
+ })
+
+ it('toggleAllOnPage selects every row when none of the page is selected', () => {
+ const { result } = renderHook(() => useBulkSelection({ pageRecords: PAGE, getKey }))
+ act(() => result.current.toggleAllOnPage())
+ expect(result.current.selectedKeys.sort()).toEqual([1, 2, 3, 4])
+ expect(result.current.isAllOnPageSelected).toBe(true)
+ })
+
+ it('toggleAllOnPage skips rows that fail the selectable gate', () => {
+ const { result } = renderHook(() =>
+ useBulkSelection({ pageRecords: PAGE, getKey, isRowSelectable: editableGate })
+ )
+ act(() => result.current.toggleAllOnPage())
+ expect(result.current.selectedKeys.sort()).toEqual([1, 2, 4])
+ expect(result.current.isAllOnPageSelected).toBe(true)
+ })
+
+ it('toggleAllOnPage clears the page when everything on it is already selected', () => {
+ const { result } = renderHook(() => useBulkSelection({ pageRecords: PAGE, getKey }))
+ act(() => result.current.toggleAllOnPage())
+ act(() => result.current.toggleAllOnPage())
+ expect(result.current.selectedKeys).toEqual([])
+ })
+
+ it('isSomeOnPageSelected is true while a partial subset of the page is selected', () => {
+ const { result } = renderHook(() => useBulkSelection({ pageRecords: PAGE, getKey }))
+ act(() => result.current.toggleRow(1, 0))
+ expect(result.current.isSomeOnPageSelected).toBe(true)
+ expect(result.current.isAllOnPageSelected).toBe(false)
+ })
+
+ it('setSelectedKeys deduplicates and replaces the existing selection', () => {
+ const { result } = renderHook(() => useBulkSelection({ pageRecords: PAGE, getKey }))
+ act(() => result.current.setSelectedKeys([1, 1, 2, 3]))
+ expect(result.current.selectedKeys.sort()).toEqual([1, 2, 3])
+ })
+
+ it('clearSelection empties the selection', () => {
+ const { result } = renderHook(() => useBulkSelection({ pageRecords: PAGE, getKey }))
+ act(() => result.current.setSelectedKeys([1, 2]))
+ act(() => result.current.clearSelection())
+ expect(result.current.selectedKeys).toEqual([])
+ })
+
+ it('selectedRecords reflects only records currently on the page', () => {
+ const { result, rerender } = renderHook(
+ ({ pageRecords }: { pageRecords: Row[] }) => useBulkSelection({ pageRecords, getKey }),
+ { initialProps: { pageRecords: PAGE } }
+ )
+ act(() => result.current.setSelectedKeys([1, 999]))
+ expect(result.current.context.selectedRecords.map((r) => r.id)).toEqual([1])
+ expect(result.current.context.selectedKeys).toEqual([1, 999])
+ rerender({ pageRecords: [{ id: 999, canEdit: true }] })
+ expect(result.current.context.selectedRecords.map((r) => r.id)).toEqual([999])
+ })
+
+ it.each([
+ { scenario: 'no initial selection', initial: undefined, expected: [] },
+ { scenario: 'empty array initial selection', initial: [], expected: [] },
+ { scenario: 'a populated initial selection', initial: [1, 3], expected: [1, 3] },
+ { scenario: 'a deduplicated initial selection', initial: [1, 1, 2, 1], expected: [1, 2] },
+ ])('honours initialSelectedKeys at mount: $scenario', ({ initial, expected }) => {
+ const { result } = renderHook(() =>
+ useBulkSelection<Row>({ pageRecords: PAGE, getKey, initialSelectedKeys: initial })
+ )
+ expect([...result.current.selectedKeys].sort()).toEqual(expected.sort())
+ })
+
+ it('ignores changes to initialSelectedKeys after mount (it is uncontrolled)', () => {
+ const { result, rerender } = renderHook(
+ ({ initial }: { initial: number[] }) =>
+ useBulkSelection<Row>({ pageRecords: PAGE, getKey, initialSelectedKeys: initial }),
+ { initialProps: { initial: [1] } }
+ )
+ expect(result.current.selectedKeys).toEqual([1])
+ rerender({ initial: [2, 3] })
+ expect(result.current.selectedKeys).toEqual([1])
+ })
+
+ describe('shift-click range selection', () => {
+ it.each([
+ {
+ scenario: 'forward range from anchor 1 to 3',
+ anchorIndex: 1,
+ shiftIndex: 3,
+ expected: [2, 3, 4],
+ },
+ {
+ scenario: 'backward range from anchor 3 to 1',
+ anchorIndex: 3,
+ shiftIndex: 1,
+ expected: [2, 3, 4],
+ },
+ ])('selects rows for $scenario', ({ anchorIndex, shiftIndex, expected }) => {
+ const { result } = renderHook(() => useBulkSelection({ pageRecords: PAGE, getKey }))
+ const anchorKey = PAGE[anchorIndex].id
+ const shiftKey = PAGE[shiftIndex].id
+
+ act(() => result.current.toggleRow(anchorKey, anchorIndex))
+ act(() => result.current.toggleRow(shiftKey, shiftIndex, true))
+
+ expect([...result.current.selectedKeys].sort()).toEqual(expected.sort())
+ })
+
+ it('skips non-selectable rows in the shift-click range', () => {
+ const { result } = renderHook(() =>
+ useBulkSelection({ pageRecords: PAGE, getKey, isRowSelectable: editableGate })
+ )
+ act(() => result.current.toggleRow(1, 0))
+ act(() => result.current.toggleRow(4, 3, true))
+ // Row at index 2 (id 3) has `canEdit: false` and must be excluded
+ expect([...result.current.selectedKeys].sort()).toEqual([1, 2, 4])
+ })
+
+ it('deselects only rows inside the shift-click range without disturbing others', () => {
+ const { result } = renderHook(() => useBulkSelection({ pageRecords: PAGE, getKey }))
+ act(() => result.current.setSelectedKeys([1, 2, 3, 4]))
+ act(() => result.current.toggleRow(1, 0))
+ act(() => result.current.toggleRow(3, 2, true))
+ expect([...result.current.selectedKeys].sort()).toEqual([4])
+ })
+
+ it('falls back to single-row toggle when no previous anchor is set', () => {
+ const { result } = renderHook(() => useBulkSelection({ pageRecords: PAGE, getKey }))
+ act(() => result.current.toggleRow(2, 1, true))
+ expect(result.current.selectedKeys).toEqual([2])
+ })
+
+ it('updates the anchor on every toggle so the next shift-click ranges from the latest click', () => {
+ const { result } = renderHook(() => useBulkSelection({ pageRecords: PAGE, getKey }))
+ act(() => result.current.toggleRow(1, 0))
+ act(() => result.current.toggleRow(2, 1))
+ act(() => result.current.toggleRow(4, 3, true))
+ expect([...result.current.selectedKeys].sort()).toEqual([1, 2, 3, 4])
+ })
+
+ it('does not extend a range when shift is not held', () => {
+ const { result } = renderHook(() => useBulkSelection({ pageRecords: PAGE, getKey }))
+ act(() => result.current.toggleRow(1, 0))
+ act(() => result.current.toggleRow(4, 3))
+ expect([...result.current.selectedKeys].sort()).toEqual([1, 4])
+ })
+ })
+})
diff --git a/frontend/src/lib/lemon-ui/LemonTable/useBulkSelection.ts b/frontend/src/lib/lemon-ui/LemonTable/useBulkSelection.ts
new file mode 100644
index 000000000000..de3187f01dc5
--- /dev/null
+++ b/frontend/src/lib/lemon-ui/LemonTable/useBulkSelection.ts
@@ -0,0 +1,188 @@
+import { ReactNode, useCallback, useMemo, useRef, useState } from 'react'
+
+export type BulkSelectionKey = string | number
+
+export type BulkSelectionRowGate = true | false | { disabledReason: string }
+
+export interface BulkSelectionContext<T, K extends BulkSelectionKey = BulkSelectionKey> {
+ /** Every key currently selected, including those on pages other than the current one. */
+ selectedKeys: ReadonlyArray<K>
+ /** Records on the current page that are selected. Records on other pages aren't available here. */
+ selectedRecords: ReadonlyArray<T>
+ /** Total number of selected keys (== selectedKeys.length). */
+ selectedCount: number
+ /** Clear the entire selection. */
+ clearSelection: () => void
+ /** Replace the selection with the given keys (e.g. for "select all matching across pages"). */
+ setSelectedKeys: (keys: ReadonlyArray<K>) => void
+}
+
+export interface BulkSelectionConfig<T extends Record<string, any>, K extends BulkSelectionKey = BulkSelectionKey> {
+ /** Render bulk action UI shown above the table whenever `selectedCount > 0`. */
+ renderActions: (ctx: BulkSelectionContext<T, K>) => ReactNode
+ /** Per-row gate. Return `false` or `{ disabledReason }` to disable that row's checkbox. */
+ isRowSelectable?: (record: T, rowIndex: number) => BulkSelectionRowGate
+ /** Override how a record is mapped to a selection key. Defaults to LemonTable's `rowKey`.
+ * The function MUST be deterministic per-record (depend on the record only, not the row
+ * index) — selection identity is keyed by the return value, so an index-dependent rowKey
+ * would collapse selection to whatever the function returns at index 0. */
+ getKey?: (record: T) => K
+ /** aria-label for the per-row checkbox (receives the record). */
+ rowAriaLabel?: (record: T) => string
+ /** aria-label for the header "select all on page" checkbox. */
+ headerAriaLabel?: string
+ /** Singular/plural noun used in "N items selected". Defaults to ['item', 'items']. */
+ noun?: [string, string]
+ /** Initial selection (uncontrolled). Read once on mount; later changes are ignored.
+ * Useful for stories and test scaffolds that want to render the bar pre-populated. */
+ initialSelectedKeys?: ReadonlyArray<K>
+}
+
+export interface UseBulkSelectionResult<T, K extends BulkSelectionKey = BulkSelectionKey> {
+ selectedKeys: K[]
+ selectedKeysSet: Set<K>
+ isAllOnPageSelected: boolean
+ isSomeOnPageSelected: boolean
+ /** True when there is at least one selectable row on the page. Used to decide whether the
+ * header checkbox does anything. */
+ pageHasSelectableRows: boolean
+ toggleRow: (key: K, rowIndex: number, shiftKeyHeld?: boolean) => void
+ toggleAllOnPage: () => void
+ clearSelection: () => void
+ setSelectedKeys: (keys: ReadonlyArray<K>) => void
+ context: BulkSelectionContext<T, K>
+}
+
+export interface UseBulkSelectionParams<T extends Record<string, any>, K extends BulkSelectionKey = BulkSelectionKey> {
+ pageRecords: T[]
+ getKey: (record: T) => K
+ isRowSelectable?: (record: T, rowIndex: number) => BulkSelectionRowGate
+ initialSelectedKeys?: ReadonlyArray<K>
+}
+
+function gateAllowsSelection(gate: BulkSelectionRowGate): boolean {
+ return gate === true
+}
+
+export function useBulkSelection<T extends Record<string, any>, K extends BulkSelectionKey = BulkSelectionKey>({
+ pageRecords,
+ getKey,
+ isRowSelectable,
+ initialSelectedKeys,
+}: UseBulkSelectionParams<T, K>): UseBulkSelectionResult<T, K> {
+ const [selectedKeys, setSelectedKeysState] = useState<K[]>(() =>
+ initialSelectedKeys ? Array.from(new Set(initialSelectedKeys)) : []
+ )
+ const previouslyCheckedIndexRef = useRef<number | null>(null)
+
+ const selectedKeysSet = useMemo(() => new Set(selectedKeys), [selectedKeys])
+
+ const selectableKeysOnPage = useMemo<K[]>(() => {
+ const keys: K[] = []
+ pageRecords.forEach((record, index) => {
+ const gate: BulkSelectionRowGate = isRowSelectable ? isRowSelectable(record, index) : true
+ if (gateAllowsSelection(gate)) {
+ keys.push(getKey(record))
+ }
+ })
+ return keys
+ }, [pageRecords, getKey, isRowSelectable])
+
+ const isAllOnPageSelected =
+ selectableKeysOnPage.length > 0 && selectableKeysOnPage.every((key) => selectedKeysSet.has(key))
+ const isSomeOnPageSelected = !isAllOnPageSelected && selectableKeysOnPage.some((key) => selectedKeysSet.has(key))
+
+ const setSelectedKeys = useCallback((keys: ReadonlyArray<K>): void => {
+ setSelectedKeysState(Array.from(new Set(keys)))
+ }, [])
+
+ const clearSelection = useCallback((): void => {
+ setSelectedKeysState([])
+ previouslyCheckedIndexRef.current = null
+ }, [])
+
+ const toggleRow = useCallback(
+ (key: K, rowIndex: number, shiftKeyHeld: boolean = false): void => {
+ // Capture the anchor index *outside* the state setter — it could be invoked
+ // asynchronously (concurrent rendering) and re-reading the ref then would already see
+ // the value we're about to write below.
+ const previouslyCheckedIndex = previouslyCheckedIndexRef.current
+ previouslyCheckedIndexRef.current = rowIndex
+ setSelectedKeysState((current) => {
+ const currentSet = new Set(current)
+
+ if (shiftKeyHeld && previouslyCheckedIndex !== null) {
+ const start = Math.min(previouslyCheckedIndex, rowIndex)
+ const end = Math.max(previouslyCheckedIndex, rowIndex)
+ const rangeKeys: K[] = []
+ for (let i = start; i <= end; i++) {
+ const record = pageRecords[i]
+ if (!record) {
+ continue
+ }
+ const gate: BulkSelectionRowGate = isRowSelectable ? isRowSelectable(record, i) : true
+ if (gateAllowsSelection(gate)) {
+ rangeKeys.push(getKey(record))
+ }
+ }
+ const isDeselecting = currentSet.has(key)
+ if (isDeselecting) {
+ const rangeSet = new Set(rangeKeys)
+ return current.filter((k) => !rangeSet.has(k))
+ }
+ return Array.from(new Set([...current, ...rangeKeys]))
+ }
+
+ if (currentSet.has(key)) {
+ return current.filter((k) => k !== key)
+ }
+ return [...current, key]
+ })
+ },
+ [pageRecords, getKey, isRowSelectable]
+ )
+
+ const toggleAllOnPage = useCallback((): void => {
+ if (selectableKeysOnPage.length === 0) {
+ return
+ }
+ setSelectedKeysState((current) => {
+ const currentSet = new Set(current)
+ const allSelected = selectableKeysOnPage.every((key) => currentSet.has(key))
+ if (allSelected) {
+ const pageSet = new Set(selectableKeysOnPage)
+ return current.filter((k) => !pageSet.has(k))
+ }
+ return Array.from(new Set([...current, ...selectableKeysOnPage]))
+ })
+ }, [selectableKeysOnPage])
+
+ const selectedRecords = useMemo<T[]>(
+ () => pageRecords.filter((record) => selectedKeysSet.has(getKey(record))),
+ [pageRecords, selectedKeysSet, getKey]
+ )
+
+ const context = useMemo<BulkSelectionContext<T, K>>(
+ () => ({
+ selectedKeys,
+ selectedRecords,
+ selectedCount: selectedKeys.length,
+ clearSelection,
+ setSelectedKeys,
+ }),
+ [selectedKeys, selectedRecords, clearSelection, setSelectedKeys]
+ )
+
+ return {
+ selectedKeys,
+ selectedKeysSet,
+ isAllOnPageSelected,
+ isSomeOnPageSelected,
+ pageHasSelectableRows: selectableKeysOnPage.length > 0,
+ toggleRow,
+ toggleAllOnPage,
+ clearSelection,
+ setSelectedKeys,
+ context,
+ }
+}
diff --git a/frontend/src/lib/logic/listSelectionLogic.test.ts b/frontend/src/lib/logic/listSelectionLogic.test.ts
deleted file mode 100644
index dfb0c39237c5..000000000000
--- a/frontend/src/lib/logic/listSelectionLogic.test.ts
+++ /dev/null
@@ -1,385 +0,0 @@
-import { expectLogic } from 'kea-test-utils'
-
-import { initKeaTests } from '~/test/init'
-
-import { getSelectionState, listSelectionLogic, PageItem } from './listSelectionLogic'
-
-/** Helper: create a PageItem[] where all items are editable */
-function editable(...ids: number[]): PageItem[] {
- return ids.map((id) => ({ id, isEditable: true }))
-}
-
-describe('listSelectionLogic', () => {
- let logic: ReturnType<typeof listSelectionLogic.build>
-
- beforeEach(() => {
- initKeaTests()
- logic = listSelectionLogic({ resource: 'feature_flags' })
- logic.mount()
- })
-
- describe('getSelectionState (pure function)', () => {
- it.each([
- { selectedIds: [1, 2, 3], editableIds: [], expected: { isAllSelected: false, isSomeSelected: false } },
- {
- selectedIds: [1, 2, 3],
- editableIds: [1, 2, 3],
- expected: { isAllSelected: true, isSomeSelected: false },
- },
- {
- selectedIds: [1, 2, 3, 4, 5],
- editableIds: [1, 2, 3],
- expected: { isAllSelected: true, isSomeSelected: false },
- },
- { selectedIds: [1], editableIds: [1, 2, 3], expected: { isAllSelected: false, isSomeSelected: true } },
- { selectedIds: [4, 5], editableIds: [1, 2, 3], expected: { isAllSelected: false, isSomeSelected: false } },
- { selectedIds: [], editableIds: [1, 2, 3], expected: { isAllSelected: false, isSomeSelected: false } },
- { selectedIds: [], editableIds: [], expected: { isAllSelected: false, isSomeSelected: false } },
- ])('getSelectionState($selectedIds, $editableIds) → $expected', ({ selectedIds, editableIds, expected }) => {
- expect(getSelectionState(selectedIds, editableIds)).toEqual(expected)
- })
- })
-
- describe('initial state', () => {
- it('starts with no selected IDs', () => {
- expectLogic(logic).toMatchValues({
- selectedIds: [],
- selectedCount: 0,
- previouslyCheckedIndex: null,
- shiftKeyHeld: false,
- })
- })
- })
-
- describe('toggleSelection (single click, no shift)', () => {
- it('adds an unselected item to selectedIds', async () => {
- await expectLogic(logic, () => {
- logic.actions.toggleSelection(10, 0, editable(10, 20, 30))
- })
- .toDispatchActions(['toggleSelection', 'setSelectedIds'])
- .toMatchValues({ selectedIds: [10] })
- })
-
- it('removes a selected item from selectedIds', async () => {
- logic.actions.setSelectedIds([10, 20])
-
- await expectLogic(logic, () => {
- logic.actions.toggleSelection(10, 0, editable(10, 20, 30))
- })
- .toDispatchActions(['toggleSelection', 'setSelectedIds'])
- .toMatchValues({ selectedIds: [20] })
- })
-
- it('updates previouslyCheckedIndex to the clicked index', async () => {
- await expectLogic(logic, () => {
- logic.actions.toggleSelection(10, 2, editable(10, 20, 30))
- })
- .toDispatchActions(['toggleSelection', 'setPreviouslyCheckedIndex'])
- .toMatchValues({ previouslyCheckedIndex: 2 })
- })
-
- it('updates previouslyCheckedIndex when deselecting', async () => {
- logic.actions.setSelectedIds([10])
-
- await expectLogic(logic, () => {
- logic.actions.toggleSelection(10, 1, editable(10, 20, 30))
- })
- .toDispatchActions(['toggleSelection', 'setPreviouslyCheckedIndex'])
- .toMatchValues({ previouslyCheckedIndex: 1 })
- })
-
- it('selecting a second item appends to existing selection', async () => {
- logic.actions.setSelectedIds([10])
-
- await expectLogic(logic, () => {
- logic.actions.toggleSelection(20, 1, editable(10, 20, 30))
- })
- .toDispatchActions(['toggleSelection', 'setSelectedIds'])
- .toMatchValues({ selectedIds: expect.arrayContaining([10, 20]) })
- })
- })
-
- describe('toggleSelection with shift-click', () => {
- it('selects a range of IDs when clicking forward from anchor', async () => {
- logic.actions.setPreviouslyCheckedIndex(0)
- logic.actions.setShiftKeyHeld(true)
-
- await expectLogic(logic, () => {
- logic.actions.toggleSelection(30, 2, editable(10, 20, 30))
- })
- .toDispatchActions(['toggleSelection', 'setSelectedIds'])
- .toMatchValues({ selectedIds: expect.arrayContaining([10, 20, 30]) })
- })
-
- it('selects a range of IDs when clicking backward from anchor', async () => {
- logic.actions.setPreviouslyCheckedIndex(2)
- logic.actions.setShiftKeyHeld(true)
-
- await expectLogic(logic, () => {
- logic.actions.toggleSelection(10, 0, editable(10, 20, 30))
- })
- .toDispatchActions(['toggleSelection', 'setSelectedIds'])
- .toMatchValues({ selectedIds: expect.arrayContaining([10, 20, 30]) })
- })
-
- it('deselects a range when the clicked item is already selected', async () => {
- logic.actions.setSelectedIds([10, 20, 30])
- logic.actions.setPreviouslyCheckedIndex(0)
- logic.actions.setShiftKeyHeld(true)
-
- await expectLogic(logic, () => {
- logic.actions.toggleSelection(30, 2, editable(10, 20, 30))
- })
- .toDispatchActions(['toggleSelection', 'setSelectedIds'])
- .toMatchValues({ selectedIds: [] })
- })
-
- it('preserves existing selections outside the range when selecting', async () => {
- logic.actions.setSelectedIds([99])
- logic.actions.setPreviouslyCheckedIndex(0)
- logic.actions.setShiftKeyHeld(true)
-
- await expectLogic(logic, () => {
- logic.actions.toggleSelection(20, 1, editable(10, 20, 30))
- })
- .toDispatchActions(['toggleSelection', 'setSelectedIds'])
- .toMatchValues({
- selectedIds: expect.arrayContaining([99, 10, 20]),
- })
- })
-
- it('preserves existing selections outside the range when deselecting', async () => {
- logic.actions.setSelectedIds([10, 20, 99])
- logic.actions.setPreviouslyCheckedIndex(0)
- logic.actions.setShiftKeyHeld(true)
-
- await expectLogic(logic, () => {
- logic.actions.toggleSelection(20, 1, editable(10, 20, 30))
- })
- .toDispatchActions(['toggleSelection', 'setSelectedIds'])
- .toMatchValues({ selectedIds: [99] })
- })
-
- it('selects a single item when anchor equals clicked index', async () => {
- logic.actions.setPreviouslyCheckedIndex(1)
- logic.actions.setShiftKeyHeld(true)
-
- await expectLogic(logic, () => {
- logic.actions.toggleSelection(20, 1, editable(10, 20, 30))
- })
- .toDispatchActions(['toggleSelection', 'setSelectedIds'])
- .toMatchValues({ selectedIds: [20] })
- })
-
- it('falls back to single toggle when previouslyCheckedIndex is null', async () => {
- logic.actions.setShiftKeyHeld(true)
-
- await expectLogic(logic, () => {
- logic.actions.toggleSelection(20, 1, editable(10, 20, 30))
- })
- .toDispatchActions(['toggleSelection', 'setSelectedIds'])
- .toMatchValues({ selectedIds: [20] })
- })
-
- it('updates previouslyCheckedIndex to the clicked index after shift-click', async () => {
- logic.actions.setPreviouslyCheckedIndex(0)
- logic.actions.setShiftKeyHeld(true)
-
- await expectLogic(logic, () => {
- logic.actions.toggleSelection(30, 2, editable(10, 20, 30))
- })
- .toDispatchActions(['toggleSelection', 'setPreviouslyCheckedIndex'])
- .toMatchValues({ previouslyCheckedIndex: 2 })
- })
-
- it('skips non-editable items in a shift-click range', async () => {
- // Page: [editable:10, non-editable:20, editable:30, editable:40]
- const items: PageItem[] = [
- { id: 10, isEditable: true },
- { id: 20, isEditable: false },
- { id: 30, isEditable: true },
- { id: 40, isEditable: true },
- ]
- logic.actions.setPreviouslyCheckedIndex(0)
- logic.actions.setShiftKeyHeld(true)
-
- await expectLogic(logic, () => {
- logic.actions.toggleSelection(40, 3, items)
- })
- .toDispatchActions(['toggleSelection', 'setSelectedIds'])
- .toMatchValues({ selectedIds: expect.arrayContaining([10, 30, 40]) })
-
- // Non-editable item 20 must NOT be selected
- expect(logic.values.selectedIds).not.toContain(20)
- })
-
- it('deselects only editable items in a shift-click range with non-editable items', async () => {
- const items: PageItem[] = [
- { id: 10, isEditable: true },
- { id: 20, isEditable: false },
- { id: 30, isEditable: true },
- ]
- logic.actions.setSelectedIds([10, 30])
- logic.actions.setPreviouslyCheckedIndex(0)
- logic.actions.setShiftKeyHeld(true)
-
- await expectLogic(logic, () => {
- logic.actions.toggleSelection(30, 2, items)
- })
- .toDispatchActions(['toggleSelection', 'setSelectedIds'])
- .toMatchValues({ selectedIds: [] })
- })
- })
-
- describe('selectAllOnPage', () => {
- it('selects all editable IDs when none are selected', async () => {
- await expectLogic(logic, () => {
- logic.actions.selectAllOnPage(editable(10, 20, 30))
- })
- .toDispatchActions(['selectAllOnPage', 'setSelectedIds'])
- .toMatchValues({ selectedIds: expect.arrayContaining([10, 20, 30]) })
- })
-
- it('selects all editable IDs when only some are selected', async () => {
- logic.actions.setSelectedIds([10])
-
- await expectLogic(logic, () => {
- logic.actions.selectAllOnPage(editable(10, 20, 30))
- })
- .toDispatchActions(['selectAllOnPage', 'setSelectedIds'])
- .toMatchValues({ selectedIds: expect.arrayContaining([10, 20, 30]) })
- })
-
- it('deselects all page IDs when all are already selected', async () => {
- logic.actions.setSelectedIds([10, 20, 30])
-
- await expectLogic(logic, () => {
- logic.actions.selectAllOnPage(editable(10, 20, 30))
- })
- .toDispatchActions(['selectAllOnPage', 'setSelectedIds'])
- .toMatchValues({ selectedIds: [] })
- })
-
- it('preserves selections from other pages when deselecting the current page', async () => {
- logic.actions.setSelectedIds([10, 20, 30, 99, 100])
-
- await expectLogic(logic, () => {
- logic.actions.selectAllOnPage(editable(10, 20, 30))
- })
- .toDispatchActions(['selectAllOnPage', 'setSelectedIds'])
- .toMatchValues({ selectedIds: expect.arrayContaining([99, 100]) })
- })
-
- it('preserves selections from other pages when selecting the current page', async () => {
- logic.actions.setSelectedIds([99, 100])
-
- await expectLogic(logic, () => {
- logic.actions.selectAllOnPage(editable(10, 20, 30))
- })
- .toDispatchActions(['selectAllOnPage', 'setSelectedIds'])
- .toMatchValues({ selectedIds: expect.arrayContaining([99, 100, 10, 20, 30]) })
- })
-
- it('does not add duplicates when re-selecting already selected items', async () => {
- logic.actions.setSelectedIds([10])
-
- await expectLogic(logic, () => {
- logic.actions.selectAllOnPage(editable(10, 20))
- })
- .toDispatchActions(['selectAllOnPage', 'setSelectedIds'])
- .toMatchValues({
- selectedIds: expect.arrayContaining([10, 20]),
- selectedCount: 2,
- })
- })
-
- it('does nothing when page is empty and nothing is selected', async () => {
- await expectLogic(logic, () => {
- logic.actions.selectAllOnPage([])
- })
- .toDispatchActions(['selectAllOnPage', 'setSelectedIds'])
- .toMatchValues({ selectedIds: [] })
- })
-
- it('only selects editable items when page has a mix of editable and non-editable', async () => {
- const items: PageItem[] = [
- { id: 10, isEditable: true },
- { id: 20, isEditable: false },
- { id: 30, isEditable: true },
- ]
-
- await expectLogic(logic, () => {
- logic.actions.selectAllOnPage(items)
- })
- .toDispatchActions(['selectAllOnPage', 'setSelectedIds'])
- .toMatchValues({ selectedIds: expect.arrayContaining([10, 30]) })
-
- expect(logic.values.selectedIds).not.toContain(20)
- })
- })
-
- describe('clearSelection', () => {
- it('resets selectedIds to empty', async () => {
- logic.actions.setSelectedIds([1, 2, 3])
-
- await expectLogic(logic, () => {
- logic.actions.clearSelection()
- })
- .toDispatchActions(['clearSelection'])
- .toMatchValues({ selectedIds: [] })
- })
-
- it('resets previouslyCheckedIndex to null', async () => {
- logic.actions.setPreviouslyCheckedIndex(5)
-
- await expectLogic(logic, () => {
- logic.actions.clearSelection()
- })
- .toDispatchActions(['clearSelection'])
- .toMatchValues({ previouslyCheckedIndex: null })
- })
-
- it('resets both selectedIds and previouslyCheckedIndex together', async () => {
- logic.actions.setSelectedIds([1, 2])
- logic.actions.setPreviouslyCheckedIndex(3)
-
- await expectLogic(logic, () => {
- logic.actions.clearSelection()
- })
- .toDispatchActions(['clearSelection'])
- .toMatchValues({ selectedIds: [], previouslyCheckedIndex: null })
- })
- })
-
- describe('selectors', () => {
- it('selectedCount returns the number of selected IDs', async () => {
- await expectLogic(logic, () => {
- logic.actions.setSelectedIds([1, 2, 3])
- })
- .toDispatchActions(['setSelectedIds'])
- .toMatchValues({ selectedCount: 3 })
- })
-
- it('selectedCount is 0 when nothing is selected', () => {
- expectLogic(logic).toMatchValues({ selectedCount: 0 })
- })
-
- it('selectedIdsSet returns a Set containing the selected IDs', async () => {
- await expectLogic(logic, () => {
- logic.actions.setSelectedIds([10, 20, 30])
- })
- .toDispatchActions(['setSelectedIds'])
- .toMatchValues({ selectedIdsSet: new Set([10, 20, 30]) })
- })
-
- it('selectedIdsSet returns an empty Set when nothing is selected', () => {
- expectLogic(logic).toMatchValues({ selectedIdsSet: new Set() })
- })
-
- it('selectedIdsSet supports membership testing', async () => {
- logic.actions.setSelectedIds([10, 20])
- expect(logic.values.selectedIdsSet.has(10)).toBe(true)
- expect(logic.values.selectedIdsSet.has(30)).toBe(false)
- })
- })
-})
diff --git a/frontend/src/lib/logic/listSelectionLogic.ts b/frontend/src/lib/logic/listSelectionLogic.ts
deleted file mode 100644
index 6834a702bd94..000000000000
--- a/frontend/src/lib/logic/listSelectionLogic.ts
+++ /dev/null
@@ -1,219 +0,0 @@
-import { actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
-import { loaders } from 'kea-loaders'
-
-import { lemonToast } from '@posthog/lemon-ui'
-
-import api from 'lib/api'
-import { projectLogic } from 'scenes/projectLogic'
-
-import { tagsModel } from '~/models/tagsModel'
-
-import type { listSelectionLogicType } from './listSelectionLogicType'
-
-export type BulkTagAction = 'add' | 'remove' | 'set'
-
-export interface BulkUpdateTagsResult {
- updated: Array<{ id: number; tags: string[] }>
- skipped: Array<{ id: number; reason: string }>
-}
-
-export type BulkTaggableResource = 'feature_flags' | 'dashboards' | 'insights'
-
-export interface PageItem {
- id: number
- isEditable: boolean
-}
-
-export interface ListSelectionLogicProps {
- resource: BulkTaggableResource
-}
-
-/**
- * Compute whether all/some editable items on the current page are selected.
- * Exported as a helper so each scene can call it with its own displayed items
- * without the shared logic needing to know about the item type.
- */
-export function getSelectionState(
- selectedIds: number[],
- editableIds: number[]
-): { isAllSelected: boolean; isSomeSelected: boolean } {
- if (editableIds.length === 0) {
- return { isAllSelected: false, isSomeSelected: false }
- }
- const selectedSet = new Set(selectedIds)
- const allSelected = editableIds.every((id) => selectedSet.has(id))
- const someSelected = editableIds.some((id) => selectedSet.has(id)) && !allSelected
- return { isAllSelected: allSelected, isSomeSelected: someSelected }
-}
-
-export const listSelectionLogic = kea<listSelectionLogicType>([
- path((key) => ['lib', 'logic', 'listSelectionLogic', key]),
- props({} as ListSelectionLogicProps),
- key(({ resource }) => resource),
-
- connect(() => ({
- values: [projectLogic, ['currentProjectId']],
- })),
-
- actions({
- setSelectedIds: (ids: number[]) => ({ ids }),
- toggleSelection: (id: number, index: number, allPageItems: PageItem[]) => ({ id, index, allPageItems }),
- selectAllOnPage: (allPageItems: PageItem[]) => ({ allPageItems }),
- clearSelection: true,
- setShiftKeyHeld: (shiftKeyHeld: boolean) => ({ shiftKeyHeld }),
- setPreviouslyCheckedIndex: (index: number | null) => ({ index }),
- showBulkTagsPopover: true,
- hideBulkTagsPopover: true,
- setPopoverTagAction: (tagAction: BulkTagAction) => ({ tagAction }),
- setPopoverSelectedTags: (tags: string[]) => ({ tags }),
- }),
-
- reducers({
- selectedIds: [
- [] as number[],
- {
- setSelectedIds: (_, { ids }) => ids,
- clearSelection: () => [],
- },
- ],
- shiftKeyHeld: [
- false as boolean,
- {
- setShiftKeyHeld: (_, { shiftKeyHeld }) => shiftKeyHeld,
- },
- ],
- previouslyCheckedIndex: [
- null as number | null,
- {
- setPreviouslyCheckedIndex: (_, { index }) => index,
- clearSelection: () => null,
- },
- ],
- bulkTagsPopoverVisible: [
- false as boolean,
- {
- showBulkTagsPopover: () => true,
- hideBulkTagsPopover: () => false,
- clearSelection: () => false,
- },
- ],
- popoverTagAction: [
- 'add' as BulkTagAction,
- {
- setPopoverTagAction: (_, { tagAction }) => tagAction,
- hideBulkTagsPopover: () => 'add',
- },
- ],
- popoverSelectedTags: [
- [] as string[],
- {
- setPopoverSelectedTags: (_, { tags }) => tags,
- hideBulkTagsPopover: () => [],
- },
- ],
- }),
-
- loaders(({ values, props: logicProps }) => ({
- bulkUpdateTagsResponse: [
- null as BulkUpdateTagsResult | null,
- {
- bulkUpdateTags: async ({ action, tags }: { action: BulkTagAction; tags: string[] }) => {
- const response = await api.create(
- `api/projects/${values.currentProjectId}/${logicProps.resource}/bulk_update_tags/`,
- { ids: values.selectedIds, action, tags }
- )
- return response as BulkUpdateTagsResult
- },
- },
- ],
- })),
-
- selectors({
- selectedCount: [(s) => [s.selectedIds], (ids: number[]) => ids.length],
- selectedIdsSet: [(s) => [s.selectedIds], (ids: number[]) => new Set(ids)],
- }),
-
- listeners(({ values, actions }) => ({
- showBulkTagsPopover: () => {
- tagsModel.actions.loadTags()
- },
-
- toggleSelection: ({ id, index, allPageItems }) => {
- const { selectedIds, shiftKeyHeld, previouslyCheckedIndex } = values
-
- if (shiftKeyHeld && previouslyCheckedIndex !== null) {
- const start = Math.min(previouslyCheckedIndex, index)
- const end = Math.max(previouslyCheckedIndex, index)
- const idsInRange = allPageItems
- .slice(start, end + 1)
- .filter((item) => item.isEditable)
- .map((item) => item.id)
-
- const isDeselecting = selectedIds.includes(id)
- if (isDeselecting) {
- const rangeSet = new Set(idsInRange)
- actions.setSelectedIds(selectedIds.filter((sid) => !rangeSet.has(sid)))
- } else {
- actions.setSelectedIds([...new Set([...selectedIds, ...idsInRange])])
- }
- } else {
- const isSelected = selectedIds.includes(id)
- if (isSelected) {
- actions.setSelectedIds(selectedIds.filter((sid) => sid !== id))
- } else {
- actions.setSelectedIds([...selectedIds, id])
- }
- }
-
- actions.setPreviouslyCheckedIndex(index)
- },
-
- selectAllOnPage: ({ allPageItems }) => {
- const editableIds = allPageItems.filter((item) => item.isEditable).map((item) => item.id)
- const { selectedIds } = values
- const selectedSet = new Set(selectedIds)
- const allSelected = editableIds.length > 0 && editableIds.every((id) => selectedSet.has(id))
-
- if (allSelected) {
- const pageIdSet = new Set(editableIds)
- actions.setSelectedIds(selectedIds.filter((id) => !pageIdSet.has(id)))
- } else {
- actions.setSelectedIds([...new Set([...selectedIds, ...editableIds])])
- }
- },
-
- bulkUpdateTagsSuccess: ({ bulkUpdateTagsResponse }) => {
- if (bulkUpdateTagsResponse) {
- const { updated, skipped } = bulkUpdateTagsResponse
- if (skipped.length === 0) {
- lemonToast.success(`Updated tags on ${updated.length} item${updated.length !== 1 ? 's' : ''}`)
- } else {
- lemonToast.warning(
- `Updated tags on ${updated.length} item${updated.length !== 1 ? 's' : ''}. ${skipped.length} skipped due to permissions.`
- )
- }
- actions.hideBulkTagsPopover()
- actions.clearSelection()
- tagsModel.actions.loadTags()
- }
- },
-
- bulkUpdateTagsFailure: () => {
- lemonToast.error('Failed to update tags')
- },
- })),
-
- afterMount(({ actions, cache }) => {
- cache.disposables.add(() => {
- const onKeyChange = (event: KeyboardEvent): void => {
- actions.setShiftKeyHeld(event.shiftKey)
- }
- window.addEventListener('keydown', onKeyChange)
- window.addEventListener('keyup', onKeyChange)
- return () => {
- window.removeEventListener('keydown', onKeyChange)
- window.removeEventListener('keyup', onKeyChange)
- }
- }, 'shiftKeyListener')
- }),
-])
diff --git a/frontend/src/scenes/dashboard/dashboards/DashboardsTable.tsx b/frontend/src/scenes/dashboard/dashboards/DashboardsTable.tsx
index bde4c28258cf..0d2027ad8ed1 100644
--- a/frontend/src/scenes/dashboard/dashboards/DashboardsTable.tsx
+++ b/frontend/src/scenes/dashboard/dashboards/DashboardsTable.tsx
@@ -1,11 +1,9 @@
import { useActions, useValues } from 'kea'
import { IconHome, IconLock, IconPin, IconPinFilled, IconShare } from '@posthog/icons'
-import { LemonCheckbox } from '@posthog/lemon-ui'
import { AccessControlAction } from 'lib/components/AccessControlAction'
-import { BulkActionToolbar } from 'lib/components/BulkActions/BulkActionToolbar'
-import { SelectionCheckbox } from 'lib/components/BulkActions/SelectionCheckbox'
+import { BulkUpdateTagsButton } from 'lib/components/BulkActions/BulkUpdateTagsButton'
import { moveToLogic } from 'lib/components/FileSystem/MoveTo/moveToLogic'
import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
@@ -17,7 +15,6 @@ import { atColumn, createdAtColumn, createdByColumn } from 'lib/lemon-ui/LemonTa
import { LemonTableLink } from 'lib/lemon-ui/LemonTable/LemonTableLink'
import { Link } from 'lib/lemon-ui/Link'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { getSelectionState, listSelectionLogic } from 'lib/logic/listSelectionLogic'
import { accessLevelSatisfied } from 'lib/utils/accessControlUtils'
import { DashboardEventSource } from 'lib/utils/eventUsageLogic'
import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'
@@ -73,51 +70,7 @@ export function DashboardsTable({
const { openMoveToModal } = useActions(moveToLogic)
const { itemsByRef } = useValues(projectTreeDataLogic)
- const dashboardSelection = listSelectionLogic({ resource: 'dashboards' })
- const { selectedIds } = useValues(dashboardSelection)
- const { selectAllOnPage } = useActions(dashboardSelection)
-
- const allPageItems = (dashboards as DashboardType[]).map((d) => ({
- id: d.id,
- isEditable: accessLevelSatisfied(
- AccessControlResourceType.Dashboard,
- d.user_access_level,
- AccessControlLevel.Editor
- ),
- }))
- const editableIds = allPageItems.filter((item) => item.isEditable).map((item) => item.id)
-
- const { isAllSelected, isSomeSelected } = getSelectionState(selectedIds, editableIds)
-
const columns: LemonTableColumns<DashboardType> = [
- {
- key: 'selection',
- width: 32,
- title: (
- <LemonCheckbox
- checked={isSomeSelected ? 'indeterminate' : isAllSelected}
- onChange={() => selectAllOnPage(allPageItems)}
- aria-label="Select all dashboards on this page"
- />
- ),
- render: function Render(_: unknown, dashboard: DashboardType, index: number) {
- const canEdit = accessLevelSatisfied(
- AccessControlResourceType.Dashboard,
- dashboard.user_access_level,
- AccessControlLevel.Editor
- )
- return (
- <SelectionCheckbox
- resource="dashboards"
- id={dashboard.id}
- index={index}
- allPageItems={allPageItems}
- disabledReason={!canEdit ? DASHBOARD_CANNOT_EDIT_MESSAGE : undefined}
- ariaLabel={`Select dashboard ${dashboard.name}`}
- />
- )
- },
- },
{
width: 0,
dataIndex: 'pinned',
@@ -302,11 +255,6 @@ export function DashboardsTable({
return (
<>
<DashboardsFiltersBar extraActions={extraActions} />
- {selectedIds.length > 0 && (
- <div className="flex items-center justify-end gap-2 min-h-12">
- <BulkActionToolbar resource="dashboards" />
- </div>
- )}
<LemonTable
data-attr="dashboards-table"
pagination={{ pageSize: 100 }}
@@ -319,6 +267,29 @@ export function DashboardsTable({
onSort={tableSortingChanged}
emptyState="No dashboards matching your filters!"
nouns={['dashboard', 'dashboards']}
+ bulkSelection={{
+ 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) => (
+ <BulkUpdateTagsButton
+ resource="dashboards"
+ selectedIds={ctx.selectedKeys}
+ onSuccess={() => {
+ ctx.clearSelection()
+ dashboardsModel.actions.loadDashboards()
+ }}
+ />
+ ),
+ }}
/>
</>
)
diff --git a/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.ts b/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.ts
index cb5b78d22fa8..8ab8febdb554 100644
--- a/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.ts
+++ b/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.ts
@@ -5,7 +5,6 @@ import { router } from 'kea-router'
import api, { PaginatedResponse } from 'lib/api'
import { Sorting } from 'lib/lemon-ui/LemonTable/sorting'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { listSelectionLogic } from 'lib/logic/listSelectionLogic'
import { tabAwareActionToUrl } from 'lib/logic/scenes/tabAwareActionToUrl'
import { tabAwareScene } from 'lib/logic/scenes/tabAwareScene'
import { tabAwareUrlToAction } from 'lib/logic/scenes/tabAwareUrlToAction'
@@ -55,7 +54,6 @@ export const dashboardsLogic = kea<dashboardsLogicType>([
tabAwareScene(),
connect(() => ({
values: [userLogic, ['user'], featureFlagLogic, ['featureFlags'], tagsModel, ['tags']],
- actions: [listSelectionLogic({ resource: 'dashboards' }), ['bulkUpdateTagsSuccess']],
})),
actions({
setCurrentTab: (tab: DashboardsTab) => ({ tab }),
@@ -275,9 +273,6 @@ export const dashboardsLogic = kea<dashboardsLogicType>([
},
})),
listeners(({ actions, values }) => ({
- bulkUpdateTagsSuccess: () => {
- dashboardsModel.actions.loadDashboards()
- },
setSearch: ({ search }) => {
actions.loadSearchedDashboards({ search, tags: values.filters.tags ?? [] })
},
diff --git a/frontend/src/scenes/feature-flags/FeatureFlags.tsx b/frontend/src/scenes/feature-flags/FeatureFlags.tsx
index 8e2ab6515865..1d14b6cfe35c 100644
--- a/frontend/src/scenes/feature-flags/FeatureFlags.tsx
+++ b/frontend/src/scenes/feature-flags/FeatureFlags.tsx
@@ -3,14 +3,14 @@ import { combineUrl, router } from 'kea-router'
import { useState } from 'react'
import { IconLock, IconPlusSmall, IconTrash } from '@posthog/icons'
-import { LemonButton, LemonCheckbox, LemonDialog, LemonTag, lemonToast } from '@posthog/lemon-ui'
+import { LemonButton, LemonDialog, LemonTag, lemonToast } from '@posthog/lemon-ui'
+import api from 'lib/api'
import { AccessControlAction } from 'lib/components/AccessControlAction'
import { ActivityLog } from 'lib/components/ActivityLog/ActivityLog'
import { AppShortcut } from 'lib/components/AppShortcuts/AppShortcut'
import { keyBinds } from 'lib/components/AppShortcuts/shortcuts'
-import { BulkActionToolbar } from 'lib/components/BulkActions/BulkActionToolbar'
-import { SelectionCheckbox } from 'lib/components/BulkActions/SelectionCheckbox'
+import { BulkUpdateTagsButton } from 'lib/components/BulkActions/BulkUpdateTagsButton'
import { FeatureFlagHog } from 'lib/components/hedgehogs'
import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'
import { ProductIntroduction } from 'lib/components/ProductIntroduction/ProductIntroduction'
@@ -25,7 +25,7 @@ import { LemonTabs } from 'lib/lemon-ui/LemonTabs'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { featureFlagLogic as enabledFeaturesLogic } from 'lib/logic/featureFlagLogic'
import { WrappingLoadingSkeleton } from 'lib/ui/WrappingLoadingSkeleton/WrappingLoadingSkeleton'
-import { pluralize } from 'lib/utils'
+import { pluralize, toParams } from 'lib/utils'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
import { cn } from 'lib/utils/css-classes'
import { deleteWithUndo } from 'lib/utils/deleteWithUndo'
@@ -312,7 +312,7 @@ export const scene: SceneExport = {
productKey: ProductKey.FEATURE_FLAGS,
}
-export function OverViewTab({
+export function OverviewTab({
flagPrefix = '',
searchPlaceholder = 'Search for feature flags (or experiment keys)',
nouns = ['feature flag', 'feature flags'],
@@ -333,21 +333,13 @@ export function OverViewTab({
const newFeatureFlagUrl = featureFlagsV2Enabled ? urls.featureFlagTemplates() : urls.featureFlag('new')
const isProductIntroVisible = shouldShowEmptyState || !user?.has_seen_product_intro_for?.[ProductKey.FEATURE_FLAGS]
- const {
- selectedCount,
- isAllSelected,
- isSomeSelected,
- bulkDeleteResponseLoading,
- showSelectAllMatchingBanner,
- totalMatchingCount,
- allMatchingSelected,
- matchingFlagIdsLoading,
- } = useValues(flagSelectionLogic)
- const { selectAllOnPage, selectAllMatching, bulkDeleteFlags } = useActions(flagSelectionLogic)
-
- const allPageItems = displayedFlags
- .filter((f: FeatureFlagType) => f.id !== null)
- .map((f: FeatureFlagType) => ({ id: f.id as number, isEditable: f.can_edit }))
+ const { currentProjectId } = useValues(projectLogic)
+ const { paramsFromFilters } = useValues(featureFlagsLogic({}))
+ const { bulkDeleteResponseLoading } = useValues(flagSelectionLogic)
+ const { bulkDeleteFlags } = useActions(flagSelectionLogic)
+
+ const [matchingFlagIds, setMatchingFlagIds] = useState<readonly number[] | null>(null)
+ const [matchingFlagIdsLoading, setMatchingFlagIdsLoading] = useState(false)
const page = filters.page || 1
const startCount = (page - 1) * FLAGS_PER_PAGE + 1
@@ -356,34 +348,6 @@ export function OverViewTab({
const flagCountText = `${startCount}${endCount - startCount > 1 ? '-' + endCount : ''} of ${pluralize(effectiveCount, 'flag')}`
const columns: LemonTableColumns<FeatureFlagType> = [
- {
- key: 'selection',
- width: 32,
- title: (
- <LemonCheckbox
- checked={isSomeSelected ? 'indeterminate' : isAllSelected}
- onChange={() => selectAllOnPage(allPageItems)}
- aria-label="Select all feature flags on this page"
- />
- ),
- render: function Render(_: unknown, featureFlag: FeatureFlagType, index: number) {
- if (featureFlag.id === null) {
- return null
- }
- return (
- <SelectionCheckbox
- resource="feature_flags"
- id={featureFlag.id}
- index={index}
- allPageItems={allPageItems}
- disabledReason={
- !featureFlag.can_edit ? "You don't have permission to edit this feature flag." : undefined
- }
- ariaLabel={`Select feature flag ${featureFlag.key}`}
- />
- )
- },
- },
{
title: 'Key',
dataIndex: 'key',
@@ -552,52 +516,6 @@ export function OverViewTab({
{!isProductIntroVisible && <ApprovalsPromoBanner />}
<PendingApprovalsBanner />
<div>{filtersSection}</div>
- {selectedCount > 0 && (
- <div className="flex items-center justify-end gap-2 min-h-9">
- <BulkActionToolbar resource="feature_flags">
- {allMatchingSelected && (
- <span className="text-muted text-sm">All {selectedCount} matching flags selected</span>
- )}
- {showSelectAllMatchingBanner && (
- <LemonButton
- type="secondary"
- size="small"
- onClick={selectAllMatching}
- loading={matchingFlagIdsLoading}
- >
- Select all {totalMatchingCount} matching flags
- </LemonButton>
- )}
- <LemonButton
- type="primary"
- status="danger"
- size="small"
- icon={<IconTrash />}
- loading={bulkDeleteResponseLoading}
- onClick={() => {
- const description = `Are you sure you want to delete ${selectedCount} feature flag${selectedCount !== 1 ? 's' : ''}? This action cannot be undone.`
- LemonDialog.open({
- title: `Delete ${selectedCount} feature flag${selectedCount !== 1 ? 's' : ''}?`,
- description,
- primaryButton: {
- children: 'Delete',
- status: 'danger',
- onClick: () => bulkDeleteFlags(),
- size: 'small',
- },
- secondaryButton: {
- children: 'Cancel',
- type: 'tertiary',
- size: 'small',
- },
- })
- }}
- >
- {bulkDeleteResponseLoading ? 'Deleting…' : 'Delete selected'}
- </LemonButton>
- </BulkActionToolbar>
- </div>
- )}
<BulkDeleteResultsModal />
<LemonTable
@@ -622,6 +540,103 @@ export function OverViewTab({
page: 1,
})
}
+ bulkSelection={{
+ getKey: (flag: FeatureFlagType): number => flag.id ?? -1,
+ isRowSelectable: (flag: FeatureFlagType) =>
+ flag.id === null
+ ? false
+ : flag.can_edit
+ ? true
+ : { disabledReason: "You don't have permission to edit this feature flag." },
+ rowAriaLabel: (flag: FeatureFlagType) => `Select feature flag ${flag.key}`,
+ headerAriaLabel: 'Select all feature flags on this page',
+ noun: ['flag', 'flags'],
+ renderActions: (ctx) => {
+ const totalMatchingCount = effectiveCount
+ const selectedKeysSet = new Set(ctx.selectedKeys)
+ const isAllMatchingSelected =
+ matchingFlagIds !== null &&
+ ctx.selectedCount === matchingFlagIds.length &&
+ matchingFlagIds.every((id) => selectedKeysSet.has(id))
+ const showSelectAllMatchingBanner =
+ !isAllMatchingSelected &&
+ ctx.selectedCount >= FLAGS_PER_PAGE &&
+ totalMatchingCount > ctx.selectedCount
+ return (
+ <>
+ {isAllMatchingSelected && (
+ <span className="text-muted text-sm">
+ All {ctx.selectedCount} matching flags selected
+ </span>
+ )}
+ {showSelectAllMatchingBanner && (
+ <LemonButton
+ type="secondary"
+ size="small"
+ loading={matchingFlagIdsLoading}
+ onClick={async () => {
+ setMatchingFlagIdsLoading(true)
+ try {
+ const { limit, offset, ...filters } = paramsFromFilters
+ const response = (await api.get(
+ `api/projects/${currentProjectId}/feature_flags/matching_ids/?${toParams(filters)}`
+ )) as { ids: number[]; total: number }
+ setMatchingFlagIds(response.ids)
+ ctx.setSelectedKeys(response.ids)
+ } finally {
+ setMatchingFlagIdsLoading(false)
+ }
+ }}
+ >
+ Select all {totalMatchingCount} matching flags
+ </LemonButton>
+ )}
+ <BulkUpdateTagsButton
+ resource="feature_flags"
+ selectedIds={ctx.selectedKeys}
+ onSuccess={() => {
+ ctx.clearSelection()
+ setMatchingFlagIds(null)
+ }}
+ />
+ <LemonButton
+ type="primary"
+ status="danger"
+ size="small"
+ icon={<IconTrash />}
+ loading={bulkDeleteResponseLoading}
+ onClick={() => {
+ const description = `Are you sure you want to delete ${ctx.selectedCount} feature flag${ctx.selectedCount !== 1 ? 's' : ''}? This action cannot be undone.`
+ LemonDialog.open({
+ title: `Delete ${ctx.selectedCount} feature flag${ctx.selectedCount !== 1 ? 's' : ''}?`,
+ description,
+ primaryButton: {
+ children: 'Delete',
+ status: 'danger',
+ onClick: () => {
+ bulkDeleteFlags({
+ ids: [...ctx.selectedKeys],
+ allMatching: isAllMatchingSelected,
+ })
+ ctx.clearSelection()
+ setMatchingFlagIds(null)
+ },
+ size: 'small',
+ },
+ secondaryButton: {
+ children: 'Cancel',
+ type: 'tertiary',
+ size: 'small',
+ },
+ })
+ }}
+ >
+ {bulkDeleteResponseLoading ? 'Deleting…' : 'Delete selected'}
+ </LemonButton>
+ </>
+ )
+ },
+ }}
/>
</SceneContent>
)
@@ -698,7 +713,7 @@ export function FeatureFlags(): JSX.Element {
{
key: FeatureFlagsTab.OVERVIEW,
label: 'Overview',
- content: <OverViewTab />,
+ content: <OverviewTab />,
},
...(showProjectsTab
? [
diff --git a/frontend/src/scenes/feature-flags/flagSelectionLogic.ts b/frontend/src/scenes/feature-flags/flagSelectionLogic.ts
index dadead58d388..6a2c4c6290d0 100644
--- a/frontend/src/scenes/feature-flags/flagSelectionLogic.ts
+++ b/frontend/src/scenes/feature-flags/flagSelectionLogic.ts
@@ -3,13 +3,9 @@ import { loaders } from 'kea-loaders'
import { beforeUnload } from 'kea-router'
import api from 'lib/api'
-import { listSelectionLogic } from 'lib/logic/listSelectionLogic'
-import { toParams } from 'lib/utils'
import { projectLogic } from 'scenes/projectLogic'
-import { FeatureFlagType } from '~/types'
-
-import { FLAGS_PER_PAGE, featureFlagsLogic } from './featureFlagsLogic'
+import { featureFlagsLogic } from './featureFlagsLogic'
import type { flagSelectionLogicType } from './flagSelectionLogicType'
export type FlagRolloutState = 'fully_rolled_out' | 'not_rolled_out' | 'partial'
@@ -26,45 +22,17 @@ export interface BulkDeleteResult {
errors: Array<{ id: number; key?: string; reason: string }>
}
-const selectionLogic = listSelectionLogic({ resource: 'feature_flags' })
-
export const flagSelectionLogic = kea<flagSelectionLogicType>([
path(['scenes', 'feature-flags', 'flagSelectionLogic']),
connect(() => ({
- values: [
- projectLogic,
- ['currentProjectId'],
- featureFlagsLogic({}),
- ['featureFlags', 'count', 'paramsFromFilters', 'displayedFlags'],
- selectionLogic,
- [
- 'selectedIds as selectedFlagIds',
- 'selectedCount',
- 'bulkTagsPopoverVisible',
- 'bulkUpdateTagsResponseLoading',
- ],
- ],
- actions: [
- featureFlagsLogic({}),
- ['loadFeatureFlags'],
- selectionLogic,
- [
- 'setSelectedIds as setSelectedFlagIds',
- 'toggleSelection as toggleFlagSelection',
- 'selectAllOnPage',
- 'clearSelection',
- 'showBulkTagsPopover',
- 'hideBulkTagsPopover',
- ],
- ],
+ values: [projectLogic, ['currentProjectId'], featureFlagsLogic({}), ['paramsFromFilters']],
+ actions: [featureFlagsLogic({}), ['loadFeatureFlags']],
})),
actions({
- selectAllMatching: true,
showResultsModal: (result: BulkDeleteResult) => ({ result }),
hideResultsModal: true,
- setAllMatchingSelected: (allMatchingSelected: boolean) => ({ allMatchingSelected }),
}),
reducers({
@@ -75,48 +43,25 @@ export const flagSelectionLogic = kea<flagSelectionLogicType>([
hideResultsModal: () => null,
},
],
- allMatchingSelected: [
- false as boolean,
- {
- setAllMatchingSelected: (_, { allMatchingSelected }) => allMatchingSelected,
- clearSelection: () => false,
- toggleFlagSelection: () => false,
- selectAllOnPage: () => false,
- },
- ],
}),
loaders(({ values }) => ({
- matchingFlagIds: [
- null as { ids: number[]; total: number } | null,
- {
- loadMatchingFlagIds: async () => {
- const { limit, offset, ...filters } = values.paramsFromFilters
- const response = await api.get(
- `api/projects/${values.currentProjectId}/feature_flags/matching_ids/?${toParams(filters)}`
- )
- return response as { ids: number[]; total: number }
- },
- },
- ],
bulkDeleteResponse: [
null as BulkDeleteResult | null,
{
- bulkDeleteFlags: async () => {
- const { allMatchingSelected, selectedFlagIds, paramsFromFilters, currentProjectId } = values
-
- if (allMatchingSelected) {
- const { limit, offset, ...filters } = paramsFromFilters
+ bulkDeleteFlags: async ({ ids, allMatching }: { ids: number[]; allMatching: boolean }) => {
+ if (allMatching) {
+ const { limit, offset, ...filters } = values.paramsFromFilters
const response = await api.create(
- `api/projects/${currentProjectId}/feature_flags/bulk_delete/`,
+ `api/projects/${values.currentProjectId}/feature_flags/bulk_delete/`,
{ filters }
)
return response as BulkDeleteResult
}
-
- const response = await api.create(`api/projects/${currentProjectId}/feature_flags/bulk_delete/`, {
- ids: selectedFlagIds,
- })
+ const response = await api.create(
+ `api/projects/${values.currentProjectId}/feature_flags/bulk_delete/`,
+ { ids }
+ )
return response as BulkDeleteResult
},
},
@@ -124,69 +69,16 @@ export const flagSelectionLogic = kea<flagSelectionLogicType>([
})),
selectors({
- currentPageFlags: [(s) => [s.featureFlags], (featureFlags): FeatureFlagType[] => featureFlags?.results || []],
- isAllSelected: [
- (s) => [s.selectedFlagIds, s.currentPageFlags],
- (selectedIds: number[], flags: FeatureFlagType[]) => {
- const editableIds = flags
- .filter((f) => f.can_edit)
- .map((f) => f.id)
- .filter((id: number | null): id is number => id !== null)
- if (editableIds.length === 0) {
- return false
- }
- return editableIds.every((id) => selectedIds.includes(id))
- },
- ],
- isSomeSelected: [
- (s) => [s.selectedFlagIds, s.currentPageFlags],
- (selectedIds: number[], flags: FeatureFlagType[]) => {
- const editableIds = flags
- .filter((f) => f.can_edit)
- .map((f) => f.id)
- .filter((id: number | null): id is number => id !== null)
- return (
- editableIds.some((id) => selectedIds.includes(id)) &&
- !editableIds.every((id) => selectedIds.includes(id))
- )
- },
- ],
resultsModalVisible: [(s) => [s.bulkDeleteResult], (result: BulkDeleteResult | null) => result !== null],
- showSelectAllMatchingBanner: [
- (s) => [s.selectedCount, s.count, s.allMatchingSelected],
- (selectedCount: number, totalCount: number, allMatchingSelected: boolean) => {
- if (allMatchingSelected) {
- return false
- }
- return selectedCount >= FLAGS_PER_PAGE && totalCount > selectedCount
- },
- ],
- totalMatchingCount: [(s) => [s.count], (count: number) => count],
}),
listeners(({ actions }) => ({
- selectAllMatching: () => {
- actions.loadMatchingFlagIds()
- },
- loadMatchingFlagIdsSuccess: ({ matchingFlagIds }) => {
- if (matchingFlagIds) {
- actions.setSelectedFlagIds(matchingFlagIds.ids)
- actions.setAllMatchingSelected(true)
- }
- },
- loadMatchingFlagIdsFailure: () => {
- actions.setAllMatchingSelected(false)
- },
bulkDeleteFlagsSuccess: ({ bulkDeleteResponse }) => {
if (bulkDeleteResponse) {
actions.showResultsModal(bulkDeleteResponse)
- actions.clearSelection()
actions.loadFeatureFlags()
}
},
- [selectionLogic.actionTypes.bulkUpdateTagsSuccess]: () => {
- actions.loadFeatureFlags()
- },
})),
beforeUnload(({ values }) => ({
diff --git a/frontend/src/scenes/saved-insights/SavedInsights.tsx b/frontend/src/scenes/saved-insights/SavedInsights.tsx
index e2f0538676a3..5db6a4f51778 100644
--- a/frontend/src/scenes/saved-insights/SavedInsights.tsx
+++ b/frontend/src/scenes/saved-insights/SavedInsights.tsx
@@ -31,15 +31,14 @@ import {
IconVideoCamera,
IconWarning,
} from '@posthog/icons'
-import { LemonCheckbox, LemonSelectOptions } from '@posthog/lemon-ui'
+import { LemonSelectOptions } from '@posthog/lemon-ui'
import { AccessControlAction } from 'lib/components/AccessControlAction'
import { ActivityLog } from 'lib/components/ActivityLog/ActivityLog'
import { Alerts } from 'lib/components/Alerts/views/Alerts'
import { AppShortcut } from 'lib/components/AppShortcuts/AppShortcut'
import { keyBinds } from 'lib/components/AppShortcuts/shortcuts'
-import { BulkActionToolbar } from 'lib/components/BulkActions/BulkActionToolbar'
-import { SelectionCheckbox } from 'lib/components/BulkActions/SelectionCheckbox'
+import { BulkUpdateTagsButton } from 'lib/components/BulkActions/BulkUpdateTagsButton'
import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'
import { TZLabel } from 'lib/components/TZLabel'
import { FEATURE_FLAGS } from 'lib/constants'
@@ -57,7 +56,6 @@ import { LemonTabs } from 'lib/lemon-ui/LemonTabs'
import { LemonTag } from 'lib/lemon-ui/LemonTag/LemonTag'
import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { getSelectionState, listSelectionLogic } from 'lib/logic/listSelectionLogic'
import { isNonEmptyObject } from 'lib/utils'
import { accessLevelSatisfied } from 'lib/utils/accessControlUtils'
import { cn } from 'lib/utils/css-classes'
@@ -759,57 +757,13 @@ export function SavedInsights(): JSX.Element {
const { insights, insightsLoading, filters, sorting, pagination, alertModalId, usingFilters } =
useValues(savedInsightsLogic)
- const insightSelection = listSelectionLogic({ resource: 'insights' })
- const { selectedIds } = useValues(insightSelection)
- const { selectAllOnPage } = useActions(insightSelection)
-
const { currentProjectId } = useValues(projectLogic)
const summarizeInsight = useSummarizeInsight()
const showHomeTab = useFeatureFlag('PRODUCT_ANALYTICS_HOME_TAB')
const { tab } = filters
- const allPageItems = insights.results.map((insight) => ({
- id: insight.id,
- isEditable: accessLevelSatisfied(
- AccessControlResourceType.Insight,
- insight.user_access_level,
- AccessControlLevel.Editor
- ),
- }))
- const editableIds = allPageItems.filter((item) => item.isEditable).map((item) => item.id)
-
- const { isAllSelected, isSomeSelected } = getSelectionState(selectedIds, editableIds)
-
const columns: LemonTableColumns<QueryBasedInsightModel> = [
- {
- key: 'selection',
- width: 32,
- title: (
- <LemonCheckbox
- checked={isSomeSelected ? 'indeterminate' : isAllSelected}
- onChange={() => selectAllOnPage(allPageItems)}
- aria-label="Select all insights on this page"
- />
- ),
- render: function Render(_: unknown, insight: QueryBasedInsightModel, index: number) {
- const canEdit = accessLevelSatisfied(
- AccessControlResourceType.Insight,
- insight.user_access_level,
- AccessControlLevel.Editor
- )
- return (
- <SelectionCheckbox
- resource="insights"
- id={insight.id}
- index={index}
- allPageItems={allPageItems}
- disabledReason={!canEdit ? "You don't have permission to edit this insight." : undefined}
- ariaLabel={`Select insight ${insight.name || 'Untitled'}`}
- />
- )
- },
- },
{
key: 'id',
width: 32,
@@ -1063,11 +1017,6 @@ export function SavedInsights(): JSX.Element {
}
/>
<ReloadInsight />
- {selectedIds.length > 0 && (
- <div className="flex items-center justify-end min-h-9">
- <BulkActionToolbar resource="insights" />
- </div>
- )}
<LemonTable
loading={insightsLoading}
columns={columns}
@@ -1093,6 +1042,30 @@ export function SavedInsights(): JSX.Element {
</div>
) : undefined
}
+ bulkSelection={{
+ getKey: (insight: QueryBasedInsightModel): number => insight.id,
+ isRowSelectable: (insight: QueryBasedInsightModel) =>
+ accessLevelSatisfied(
+ AccessControlResourceType.Insight,
+ insight.user_access_level,
+ AccessControlLevel.Editor
+ )
+ ? true
+ : { disabledReason: "You don't have permission to edit this insight." },
+ rowAriaLabel: (insight: QueryBasedInsightModel) =>
+ `Select insight ${insight.name || 'Untitled'}`,
+ headerAriaLabel: 'Select all insights on this page',
+ renderActions: (ctx) => (
+ <BulkUpdateTagsButton
+ resource="insights"
+ selectedIds={ctx.selectedKeys}
+ onSuccess={() => {
+ ctx.clearSelection()
+ loadInsights()
+ }}
+ />
+ ),
+ }}
/>
</>
)}
diff --git a/frontend/src/scenes/saved-insights/savedInsightsLogic.ts b/frontend/src/scenes/saved-insights/savedInsightsLogic.ts
index 3f6bfafc921e..ede3d8c217af 100644
--- a/frontend/src/scenes/saved-insights/savedInsightsLogic.ts
+++ b/frontend/src/scenes/saved-insights/savedInsightsLogic.ts
@@ -8,7 +8,6 @@ import { dayjs } from 'lib/dayjs'
import { Sorting } from 'lib/lemon-ui/LemonTable'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { PaginationManual } from 'lib/lemon-ui/PaginationControl'
-import { listSelectionLogic } from 'lib/logic/listSelectionLogic'
import { tabAwareActionToUrl } from 'lib/logic/scenes/tabAwareActionToUrl'
import { tabAwareScene } from 'lib/logic/scenes/tabAwareScene'
import { tabAwareUrlToAction } from 'lib/logic/scenes/tabAwareUrlToAction'
@@ -86,7 +85,6 @@ export const savedInsightsLogic = kea<savedInsightsLogicType>([
tabAwareScene(),
connect(() => ({
values: [teamLogic, ['currentTeamId'], sceneLogic, ['activeSceneId']],
- actions: [listSelectionLogic({ resource: 'insights' }), ['bulkUpdateTagsSuccess']],
logic: [eventUsageLogic],
})),
actions({
@@ -381,9 +379,6 @@ export const savedInsightsLogic = kea<savedInsightsLogicType>([
actions.loadInsights()
}
},
- bulkUpdateTagsSuccess: () => {
- actions.loadInsights()
- },
})),
tabAwareActionToUrl(({ values }) => {
const changeUrl = ():