:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(lemon-ui): add right-click to copy cell contents in tables (#69041)
ruby childs666df50b549c
diff --git a/frontend/src/lib/hooks/useCellCopyContextMenu.tsx b/frontend/src/lib/hooks/useCellCopyContextMenu.tsxnew file mode 100644index 000000000000..ffb83c76e31d--- /dev/null+++ b/frontend/src/lib/hooks/useCellCopyContextMenu.tsx@@ -0,0 +1,52 @@+import { useCallback, useState } from 'react'++import { IconCopy } from '@posthog/icons'++import { LemonButton } from 'lib/lemon-ui/LemonButton'+import { Popover } from 'lib/lemon-ui/Popover/Popover'+import { copyToClipboard } from 'lib/utils/copyToClipboard'++interface CellCopyMenuState {+ element: HTMLElement+ text: string+}++/** Shared state + popover for a right-click "Copy cell contents" affordance. Callers own the+ * cell-specific logic (extracting the copyable text, deciding when to fall back to the native+ * context menu) and call `openCopyMenu`/`closeCopyMenu`; this hook only owns the popover itself. */+export function useCellCopyContextMenu(): {+ closeCopyMenu: () => void+ openCopyMenu: (element: HTMLElement, text: string) => void+ copyMenu: JSX.Element+} {+ const [menu, setMenu] = useState<CellCopyMenuState | null>(null)++ const closeCopyMenu = useCallback(() => setMenu(null), [])+ const openCopyMenu = useCallback((element: HTMLElement, text: string) => setMenu({ element, text }), [])++ const copyMenu = (+ <Popover+ visible={!!menu}+ referenceElement={menu?.element ?? null}+ onClickOutside={closeCopyMenu}+ placement="bottom-start"+ overlay={+ <LemonButton+ icon={<IconCopy />}+ fullWidth+ size="small"+ onClick={() => {+ if (menu) {+ void copyToClipboard(menu.text, 'cell contents')+ }+ closeCopyMenu()+ }}+ >+ Copy cell contents+ </LemonButton>+ }+ />+ )++ return { closeCopyMenu, openCopyMenu, copyMenu }+}diff --git a/frontend/src/lib/lemon-ui/LemonTable/LemonTable.cellCopy.test.tsx b/frontend/src/lib/lemon-ui/LemonTable/LemonTable.cellCopy.test.tsxnew file mode 100644index 000000000000..c666b321956e--- /dev/null+++ b/frontend/src/lib/lemon-ui/LemonTable/LemonTable.cellCopy.test.tsx@@ -0,0 +1,99 @@+import '@testing-library/jest-dom'++import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'++import { initKeaTests } from '~/test/init'++import { extractCellText, LemonTable } from './LemonTable'++interface Row {+ name: string+}++const dataSource: Row[] = [{ name: 'All_callers' }]++/** Build a detached `<td>` with the given inner HTML so `extractCellText` can be tested in isolation. */+function cellWith(innerHTML: string): HTMLElement {+ const td = document.createElement('td')+ td.innerHTML = innerHTML+ return td+}++describe('extractCellText', () => {+ it('returns the plain text of a scalar cell', () => {+ expect(extractCellText(cellWith('All_callers'))).toBe('All_callers')+ })++ it('recovers text clipped by CSS ellipsis (full textContent is in the DOM)', () => {+ expect(extractCellText(cellWith('<span class="truncate">a-very-long-distinct-id-0199</span>'))).toBe(+ 'a-very-long-distinct-id-0199'+ )+ })++ it('joins visually-separated children with a space instead of smushing', () => {+ // `textContent` alone would yield "FooBar" — CSS spacing between siblings is not text.+ expect(extractCellText(cellWith('<span>Foo</span><span>Bar</span>'))).toBe('Foo Bar')+ })++ it('collapses internal whitespace and trims', () => {+ expect(extractCellText(cellWith(' <span>Enabled</span>\n <span>Stale</span> '))).toBe('Enabled Stale')+ })++ it('returns an empty string for an empty cell', () => {+ expect(extractCellText(cellWith(''))).toBe('')+ })+})++describe('LemonTable enableCellCopy gating', () => {+ beforeEach(() => {+ initKeaTests()+ })++ afterEach(() => {+ cleanup()+ })++ it('does not offer "Copy cell contents" on right-click unless enableCellCopy is set', () => {+ render(<LemonTable columns={[{ title: 'Name', dataIndex: 'name' }]} dataSource={dataSource} />)++ fireEvent.contextMenu(screen.getByText('All_callers').closest('td')!)++ expect(screen.queryByText('Copy cell contents')).not.toBeInTheDocument()+ })++ it('offers "Copy cell contents" on right-click when enableCellCopy is set', async () => {+ render(<LemonTable enableCellCopy columns={[{ title: 'Name', dataIndex: 'name' }]} dataSource={dataSource} />)++ fireEvent.contextMenu(screen.getByText('All_callers').closest('td')!)++ // The popover only mounts its overlay when visible, so finding the button proves the+ // right-click handler fired and opened the copy affordance.+ expect(await screen.findByText('Copy cell contents')).toBeInTheDocument()+ })++ it('closes an open copy menu when a non-copyable (empty) cell is right-clicked', async () => {+ render(+ <LemonTable+ enableCellCopy+ columns={[+ { title: 'Name', dataIndex: 'name' },+ { title: 'Blank', dataIndex: 'blank' },+ ]}+ dataSource={[{ name: 'All_callers', blank: '' }]}+ />+ )++ const nameCell = screen.getByText('All_callers').closest('td')!+ fireEvent.contextMenu(nameCell)+ expect(await screen.findByText('Copy cell contents')).toBeInTheDocument()++ // The Blank column's cell has no text, so right-clicking it must clear the open menu rather+ // than leave a stale popover pointing at the previous cell. The Popover unmounts its portal+ // on a delay, so wait for the button to leave the DOM.+ fireEvent.contextMenu(nameCell.nextElementSibling as HTMLElement)++ await waitFor(() => {+ expect(screen.queryByText('Copy cell contents')).not.toBeInTheDocument()+ })+ })+})diff --git a/frontend/src/lib/lemon-ui/LemonTable/LemonTable.tsx b/frontend/src/lib/lemon-ui/LemonTable/LemonTable.tsxindex f46d824ca99d..20251ec3b0fd 100644--- a/frontend/src/lib/lemon-ui/LemonTable/LemonTable.tsx+++ b/frontend/src/lib/lemon-ui/LemonTable/LemonTable.tsx@@ -9,6 +9,7 @@ import { IconInfo } from '@posthog/icons'import { LemonCheckbox } from '@posthog/lemon-ui'import { ScrollableShadows } from 'lib/components/ScrollableShadows/ScrollableShadows'+import { useCellCopyContextMenu } from 'lib/hooks/useCellCopyContextMenu'import { IconWithCount } from 'lib/lemon-ui/icons'import { LemonButtonWithDropdown } from 'lib/lemon-ui/LemonButton'import { More } from 'lib/lemon-ui/LemonButton/More'@@ -30,6 +31,21 @@ import { BulkSelectionConfig, BulkSelectionKey, useBulkSelection } from './useBu* unconditionally so hook order is stable, but its result is never read. */const UNUSED_ROW_KEY = (): string | number => 0+/** Text extracted from a cell for "Copy cell contents". Joins the cell's direct child nodes with a+ * space — using `textContent` on the whole cell would both smush visually-separated children+ * (e.g. a label plus a tag) together and lose nothing to `text-overflow` clipping, since+ * `textContent` always reflects the full DOM value regardless of CSS. Exported for testing. */+export function extractCellText(cell: HTMLElement): string {+ const parts: string[] = []+ cell.childNodes.forEach((node) => {+ const text = node.textContent?.trim()+ if (text) {+ parts.push(text)+ }+ })+ return parts.join(' ').replace(/\s+/g, ' ').trim()+}+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@@ -118,6 +134,11 @@ export interface LemonTableProps<T extends Record<string, any>, K extends BulkSe/** 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>+ /** Enable a right-click "Copy cell contents" affordance on each data cell. Off by default —+ * only opt in on data-result tables (query/insight/SQL result tables) where cells are scalar+ * values. Not for entity-list tables, where composed cells (dates, tags, avatars) would copy+ * a misleading rendered string. */+ enableCellCopy?: boolean}export function LemonTable<T extends Record<string, any>, K extends BulkSelectionKey = BulkSelectionKey>({@@ -162,6 +183,7 @@ export function LemonTable<T extends Record<string, any>, K extends BulkSelectiorowActions,hideSortingIndicatorWhenInactive = false,bulkSelection,+ enableCellCopy = false,}: LemonTableProps<T, K>): JSX.Element {if (bulkSelection && !bulkSelection.getKey && rowKey === undefined) {throw new Error(@@ -213,6 +235,23 @@ export function LemonTable<T extends Record<string, any>, K extends BulkSelectioconst scrollRef = useRef<HTMLDivElement>(null)+ const { closeCopyMenu, openCopyMenu, copyMenu } = useCellCopyContextMenu()++ // A single stable handler shared by every data cell keeps the per-cell cost to just a prop+ // reference (no extra components or DOM), so this stays cheap even on very large tables.+ const handleCellContextMenu = useCallback(+ (event: React.MouseEvent<HTMLTableCellElement>) => {+ const text = extractCellText(event.currentTarget)+ if (!text) {+ closeCopyMenu() // Nothing to copy — close any open menu and fall back to the native one+ return+ }+ event.preventDefault()+ openCopyMenu(event.currentTarget, text)+ },+ [closeCopyMenu, openCopyMenu]+ )+// Width calculation for pinned columnsconst { columnWidths: pinnedColumnWidths, tableRef } = useColumnWidths({columnKeys: pinnedColumns,@@ -744,6 +783,7 @@ export function LemonTable<T extends Record<string, any>, K extends BulkSelectiopinnedColumnWidths={pinnedColumnWidths}columns={columns}rowActions={rowActions}+ onCellContextMenu={enableCellCopy ? handleCellContextMenu : undefined}/>)})@@ -785,6 +825,7 @@ export function LemonTable<T extends Record<string, any>, K extends BulkSelectio</div></ScrollableShadows></div>+ {enableCellCopy && copyMenu}</>)}diff --git a/frontend/src/lib/lemon-ui/LemonTable/TableRow.tsx b/frontend/src/lib/lemon-ui/LemonTable/TableRow.tsxindex 240e2063031b..be6ac218a6d3 100644--- a/frontend/src/lib/lemon-ui/LemonTable/TableRow.tsx+++ b/frontend/src/lib/lemon-ui/LemonTable/TableRow.tsx@@ -25,6 +25,8 @@ export interface TableRowProps<T extends Record<string, any>> {pinnedColumnWidths?: number[]columns?: LemonTableColumn<T, any>[]rowActions?: (record: T, recordIndex: number) => React.ReactNode | null+ /** Right-click handler attached to every data cell, used to offer "Copy cell contents". */+ onCellContextMenu?: (event: React.MouseEvent<HTMLTableCellElement>) => void}function TableRowRaw<T extends Record<string, any>>({@@ -43,6 +45,7 @@ function TableRowRaw<T extends Record<string, any>>({pinnedColumnWidths,columns,rowActions,+ onCellContextMenu,}: TableRowProps<T>): JSX.Element {const [isRowExpandedLocal, setIsRowExpanded] = useState(false)const rowExpandable: number = Number(@@ -146,6 +149,16 @@ function TableRowRaw<T extends Record<string, any>>({const extraCellProps =isTableCellRepresentation(contents) && contents.props ? contents.props : {}+ // A column may supply its own onContextMenu via TableCellRepresentation; chain it+ // with the copy handler so the spread below can't silently clobber either one.+ const { onContextMenu: columnOnContextMenu, ...restCellProps } = extraCellProps+ const onCellContextMenuChained =+ columnOnContextMenu || onCellContextMenu+ ? (event: React.MouseEvent<HTMLTableCellElement>) => {+ columnOnContextMenu?.(event)+ onCellContextMenu?.(event)+ }+ : undefined// A cell that spans several columns is not bound by the width of the one it starts inconst spansColumns = extraCellProps.colSpan !== undefined && extraCellProps.colSpan !== 1const widthCap = spansColumns ? undefined : getColumnWidthCap(column)@@ -172,7 +185,8 @@ function TableRowRaw<T extends Record<string, any>>({...(widthCap ? { maxWidth: widthCap } : {}),...(isColumnSticky ? { left: `${leftPosition}px` } : {}),}}- {...extraCellProps}+ onContextMenu={onCellContextMenuChained}+ {...restCellProps}>{isTableCellRepresentation(contents) ? contents.children : contents}</td>diff --git a/frontend/src/scenes/data-warehouse/editor/OutputPane.cellCopy.test.ts b/frontend/src/scenes/data-warehouse/editor/OutputPane.cellCopy.test.tsnew file mode 100644index 000000000000..23e46c6bf8ca--- /dev/null+++ b/frontend/src/scenes/data-warehouse/editor/OutputPane.cellCopy.test.ts@@ -0,0 +1,29 @@+import { extractGridCellValue } from './OutputPane'++describe('extractGridCellValue', () => {+ it('returns the stringified value for a normal data cell', () => {+ expect(extractGridCellValue('name', { name: 'All_callers' })).toBe('All_callers')+ expect(extractGridCellValue('count', { count: 42 })).toBe('42')+ })++ it('returns null for the details column so it falls through to the native menu', () => {+ expect(extractGridCellValue('__details', { __details: 'anything' })).toBeNull()+ })++ it('returns null for null, undefined, and empty-string values', () => {+ expect(extractGridCellValue('name', { name: null })).toBeNull()+ expect(extractGridCellValue('name', {})).toBeNull()+ expect(extractGridCellValue('name', { name: '' })).toBeNull()+ })++ it('returns null for HogQLX-shaped values instead of copying the raw AST', () => {+ // These render as rich content; copying String(value) would put the internal AST on the clipboard.+ expect(extractGridCellValue('url', { url: '["__hx_tag", "a", {"href": "https://posthog.com"}]' })).toBeNull()+ })++ it('still copies a plain string that merely mentions __hx_tag', () => {+ expect(extractGridCellValue('note', { note: 'contains ["__hx_tag" midway' })).toBe(+ 'contains ["__hx_tag" midway'+ )+ })+})diff --git a/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx b/frontend/src/scenes/data-warehouse/editor/OutputPane.tsxindex b2356a4a06b8..0729a74a998a 100644--- a/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx+++ b/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx@@ -4,7 +4,15 @@ import 'react-data-grid/lib/styles.css'import clsx from 'clsx'import { BindLogic, useActions, useValues } from 'kea'import { useCallback, useMemo, useRef, useState } from 'react'-import DataGrid, { DataGridProps, RenderHeaderCellProps, SortColumn } from 'react-data-grid'+import DataGrid, {+ CellClickArgs,+ // CellMouseEvent, onCellContextMenu, and event.preventGridDefault() are beta-only APIs from the+ // exactly-pinned react-data-grid 7.0.0-beta.47; a manual bump could reshape them without a semver signal.+ CellMouseEvent,+ DataGridProps,+ RenderHeaderCellProps,+ SortColumn,+} from 'react-data-grid'import {IconCode,@@ -29,6 +37,7 @@ import { MCPUseCaseCard } from 'lib/components/MCPHint/MCPUseCaseCard'import { Resizer } from 'lib/components/Resizer/Resizer'import { type ResizerLogicProps, resizerLogic } from 'lib/components/Resizer/resizerLogic'import { TZLabel } from 'lib/components/TZLabel'+import { useCellCopyContextMenu } from 'lib/hooks/useCellCopyContextMenu'import { IconTableChart } from 'lib/lemon-ui/icons'import { Link } from 'lib/lemon-ui/Link'import { LoadingBar } from 'lib/lemon-ui/LoadingBar'@@ -588,6 +597,26 @@ interface OutputPaneProps {onShareTab?: () => void}+/** The copyable text for a right-clicked grid cell, or null when the cell should fall through to the+ * native context menu. Exported so the branches below (details column, empty value, HogQLX skip) are+ * unit-testable, mirroring extractCellText in LemonTable. */+export function extractGridCellValue(columnKey: string, row: Record<string, any>): string | null {+ if (columnKey === '__details') {+ return null+ }+ const value = row[columnKey]+ if (value === null || value === undefined || value === '') {+ return null+ }+ // HogQLX-shaped values render as rich content (links, sparklines, recording buttons) via+ // renderHogQLX; copying String(value) would put the internal AST JSON on the clipboard, so skip+ // them and let the native menu handle the cell instead.+ if (typeof value === 'string' && value.startsWith('["__hx_tag",') && value.endsWith(']')) {+ return null+ }+ return String(value)+}+export function OutputPane({ tabId, showToolbar = true, biMode = false, onShareTab }: OutputPaneProps): JSX.Element {const { activeTab } = useValues(outputPaneLogic)const { setActiveTab } = useActions(outputPaneLogic)@@ -1207,6 +1236,24 @@ const Content = ({const { loadingTimeSeconds } = useValues(dataNodeLogic)const [sortColumns, setSortColumns] = useState<SortColumn[]>([])+ const { closeCopyMenu, openCopyMenu, copyMenu } = useCellCopyContextMenu()++ // Right-click a results cell to copy its value. Unlike the LemonTable feature (which reads DOM+ // text), react-data-grid hands us the raw row value, so datetimes/numbers copy accurately.+ const handleGridCellContextMenu = useCallback(+ (args: CellClickArgs<any, any>, event: CellMouseEvent) => {+ const text = extractGridCellValue(args.column.key, args.row)+ if (text === null) {+ closeCopyMenu() // Not a copyable data cell — close any open menu and fall back to the native one+ return+ }+ event.preventGridDefault()+ event.preventDefault()+ openCopyMenu(event.currentTarget, text)+ },+ [closeCopyMenu, openCopyMenu]+ )+const sortedRows = useMemo(() => {if (!sortColumns.length) {return rows@@ -1355,7 +1402,9 @@ const Content = ({rows={sortedRows}sortColumns={sortColumns}onSortColumnsChange={setSortColumns}+ onCellContextMenu={handleGridCellContextMenu}/>+ {copyMenu}</TabScroller>)}</div>