The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
[FE-4400] feat(studio): shift-click range selection in Unified Logs (#50462)
Alaister Young89ae80073d26
diff --git a/apps/studio/components/interfaces/Settings/Logs/LogTable.tsx b/apps/studio/components/interfaces/Settings/Logs/LogTable.tsxindex 52826144ea3..f26d55e9197 100644--- a/apps/studio/components/interfaces/Settings/Logs/LogTable.tsx+++ b/apps/studio/components/interfaces/Settings/Logs/LogTable.tsx@@ -2,7 +2,13 @@ import { PermissionAction } from '@supabase/shared-types/out/constants'import { IS_PLATFORM, useParams } from 'common'import { Copy, Eye, EyeOff, Play } from 'lucide-react'import { Key, ReactNode, useCallback, useEffect, useMemo, useRef, useState } from 'react'-import DataGrid, { Column, RenderRowProps, Row } from 'react-data-grid'+import DataGrid, {+ Column,+ RenderCellProps,+ RenderRowProps,+ Row,+ useRowSelection,+} from 'react-data-grid'import { toast } from 'sonner'import {Button,@@ -30,7 +36,6 @@ import {formatLogsAsCsv,formatLogsAsJson,formatLogsAsMarkdown,- getShiftClickSelection,isDefaultLogPreviewFormat,} from './Logs.utils'import LogSelection from './LogSelection'@@ -74,6 +79,46 @@ interface Props {}type LogMap = { [id: string]: LogData }+/**+ * Checkbox cell for the multi-select column. Reads and writes the grid's own row+ * selection, which gives us react-data-grid's native shift-click range selection.+ */+const LogSelectCell = ({ row }: RenderCellProps<LogData>) => {+ const { isRowSelected, onRowSelectionChange } = useRowSelection()++ const handleSelect = (e: React.MouseEvent) => {+ e.stopPropagation()+ onRowSelectionChange({ row, checked: !isRowSelected, isShiftClick: e.shiftKey })+ }++ return (+ <div+ className="absolute group inset-0 flex justify-center px-2 items-center cursor-pointer"+ // Prevent a shift-click from starting a browser text selection across rows+ onMouseDown={(e) => {+ if (e.shiftKey) e.preventDefault()+ }}+ onClick={handleSelect}+ >+ <Checkbox+ className="group-hover:border-foreground-muted"+ checked={isRowSelected}+ // use onClick instead of onCheckedChange so the shift key is available for range selection+ onClick={handleSelect}+ />+ </div>+ )+}++const checkboxColumn: Column<LogData> = {+ key: 'multi-select',+ name: '',+ width: 32,+ maxWidth: 32,+ minWidth: 32,+ renderCell: (props) => <LogSelectCell {...props} />,+}+/*** Logs table view with focus side panel*@@ -107,8 +152,6 @@ export const LogTable = ({const [selectedLogId] = useSelectedLog()const [selectedRow, setSelectedRow] = useState<LogData | null>(null)const [selectedRows, setSelectedRows] = useState<Set<string>>(new Set())- // Last row key the user toggled, used as the start of a shift-click range- const selectionAnchorRef = useRef<string | null>(null)const [copiedFormat, setCopiedFormat] = useState<LogCopyFormat | null>(null)const triggerRef = useRef<HTMLDivElement>(null)const [activeRow, setActiveRow] = useState<LogData | null>(null)@@ -191,62 +234,13 @@ export const LogTable = ({[logDataRows, selectedRows, getRowKey])- const checkboxColumn: Column<LogData> = {- key: 'multi-select',- name: '',- width: 32,- maxWidth: 32,- minWidth: 32,- renderCell: ({ row }) => {- const key = getRowKey(row)- const toggle = (isShiftClick: boolean) => {- let next: Set<string>- if (isShiftClick) {- next = getShiftClickSelection({- orderedKeys: logDataRows.map(getRowKey),- selectedKeys: selectedRows,- anchorKey: selectionAnchorRef.current,- targetKey: key,- })- } else {- next = new Set(selectedRows)- if (next.has(key)) {- next.delete(key)- } else {- next.add(key)- }- }- selectionAnchorRef.current = next.size > 0 ? key : null- setSelectedRows(next)- if (next.size > 0) {- setSelectedRow(null)- onSelectedLogChange?.(null)- }- }- return (- <div- className="absolute group inset-0 flex justify-center px-2 items-center cursor-pointer"- // Prevent a shift-click from starting a browser text selection across rows- onMouseDown={(e) => {- if (e.shiftKey) e.preventDefault()- }}- onClick={(e) => {- e.stopPropagation()- toggle(e.shiftKey)- }}- >- <Checkbox- className="group-hover:border-foreground-muted"- checked={selectedRows.has(key)}- // use onClick instead of onCheckedChange so the shift key is available for range selection- onClick={(e: React.MouseEvent) => {- e.stopPropagation()- toggle(e.shiftKey)- }}- />- </div>- )- },+ const handleSelectedRowsChange = (nextSelectedRows: Set<string>) => {+ setSelectedRows(nextSelectedRows)+ // Checking a row switches from the single-row side panel to multi-select+ if (nextSelectedRows.size > 0) {+ setSelectedRow(null)+ onSelectedLogChange?.(null)+ }}const DEFAULT_COLUMNS = columnNames.map((v: keyof LogData, idx) => {@@ -313,7 +307,6 @@ export const LogTable = ({(row: LogData) => {// Regular single click — clear multi-select, open side panelsetSelectedRows(new Set())- selectionAnchorRef.current = nullsetSelectedRow(row)onSelectedLogChange?.(row)},@@ -332,7 +325,6 @@ export const LogTable = ({<Rowkey={key}{...props}- isRowSelected={false}selectedCellIdx={undefined}onClick={handleClick}onContextMenu={(e) => handleRowContextMenu(e, props.row)}@@ -389,7 +381,6 @@ export const LogTable = ({() => {if (selectedRows.size === logDataRows.length) {setSelectedRows(new Set())- selectionAnchorRef.current = null} else {setSelectedRows(new Set(logDataRows.map((row) => getRowKey(row))))setSelectedRow(null)@@ -410,7 +401,6 @@ export const LogTable = ({} else {next.add(key)}- selectionAnchorRef.current = next.size > 0 ? key : nullsetSelectedRows(next)},{ enabled: selectedRow !== null }@@ -429,7 +419,6 @@ export const LogTable = ({SHORTCUT_IDS.LOGS_PREVIEW_EXIT_SELECTION,() => {setSelectedRows(new Set())- selectionAnchorRef.current = null;(document.activeElement as HTMLElement | null)?.blur()},{ enabled: !selectionOpen && selectedRows.size > 0 }@@ -452,7 +441,6 @@ export const LogTable = ({useEffect(() => {if (isLoading) {setSelectedRows(new Set())- selectionAnchorRef.current = null}}, [isLoading])@@ -607,10 +595,7 @@ export const LogTable = ({onCopy={handleCopySelectedRows}queryType={queryType}sqlQuery={sqlQuery}- onClear={() => {- setSelectedRows(new Set())- selectionAnchorRef.current = null- }}+ onClear={() => setSelectedRows(new Set())}/></div><ContextMenu modal={false}>@@ -656,11 +641,9 @@ export const LogTable = ({)}}rows={logDataRows}- rowKeyGetter={(r) => {- if (!hasId) return JSON.stringify(r)- const row = r as LogData- return row.id- }}+ rowKeyGetter={getRowKey}+ selectedRows={selectedRows}+ onSelectedRowsChange={handleSelectedRowsChange}renderers={{renderRow: RowRenderer,noRowsFallback: !isLoading ? (diff --git a/apps/studio/components/interfaces/Settings/Logs/Logs.utils.test.ts b/apps/studio/components/interfaces/Settings/Logs/Logs.utils.test.tsindex 5c3820c4ea7..6091e922362 100644--- a/apps/studio/components/interfaces/Settings/Logs/Logs.utils.test.ts+++ b/apps/studio/components/interfaces/Settings/Logs/Logs.utils.test.ts@@ -13,7 +13,6 @@ import {genChartQuery,genDefaultQuery,getAuthLogSeverity,- getShiftClickSelection,parseMultigresEventMessage,} from './Logs.utils'@@ -352,120 +351,4 @@ describe('Logs.utils', () => {).not.toThrow()})})-- describe('getShiftClickSelection', () => {- const orderedKeys = ['a', 'b', 'c', 'd', 'e']-- test('selects the range downward from the anchor', () => {- const result = getShiftClickSelection({- orderedKeys,- selectedKeys: new Set(['b']),- anchorKey: 'b',- targetKey: 'd',- })- expect([...result].sort()).toEqual(['b', 'c', 'd'])- })-- test('selects the range upward from the anchor', () => {- const result = getShiftClickSelection({- orderedKeys,- selectedKeys: new Set(['d']),- anchorKey: 'd',- targetKey: 'b',- })- expect([...result].sort()).toEqual(['b', 'c', 'd'])- })-- test('toggles just the anchor when it is also the target', () => {- const added = getShiftClickSelection({- orderedKeys,- selectedKeys: new Set(),- anchorKey: 'c',- targetKey: 'c',- })- expect([...added]).toEqual(['c'])-- const removed = getShiftClickSelection({- orderedKeys,- selectedKeys: new Set(['c']),- anchorKey: 'c',- targetKey: 'c',- })- expect([...removed]).toEqual([])- })-- test('removes the range when it is already fully selected, keeping keys outside it', () => {- const result = getShiftClickSelection({- orderedKeys,- selectedKeys: new Set(['a', 'b', 'c', 'd']),- anchorKey: 'b',- targetKey: 'd',- })- expect([...result].sort()).toEqual(['a'])- })-- test('selects the whole range when it is only partially selected', () => {- const result = getShiftClickSelection({- orderedKeys,- selectedKeys: new Set(['c']),- anchorKey: 'b',- targetKey: 'd',- })- expect([...result].sort()).toEqual(['b', 'c', 'd'])- })-- test('falls back to adding the target when there is no anchor', () => {- const result = getShiftClickSelection({- orderedKeys,- selectedKeys: new Set(['a']),- anchorKey: null,- targetKey: 'c',- })- expect([...result].sort()).toEqual(['a', 'c'])- })-- test('falls back to removing the target when there is no anchor and it is selected', () => {- const result = getShiftClickSelection({- orderedKeys,- selectedKeys: new Set(['a', 'c']),- anchorKey: null,- targetKey: 'c',- })- expect([...result].sort()).toEqual(['a'])- })-- test('falls back to a plain toggle when the anchor is no longer in the rows', () => {- const result = getShiftClickSelection({- orderedKeys,- selectedKeys: new Set(),- anchorKey: 'gone',- targetKey: 'd',- })- expect([...result]).toEqual(['d'])- })-- test('falls back to a plain toggle when the target is not in the rows', () => {- const result = getShiftClickSelection({- orderedKeys,- selectedKeys: new Set(['a']),- anchorKey: 'a',- targetKey: 'gone',- })- expect([...result].sort()).toEqual(['a', 'gone'])- })-- test('does not mutate its inputs', () => {- const selectedKeys = new Set(['b'])- const keys = [...orderedKeys]- const result = getShiftClickSelection({- orderedKeys: keys,- selectedKeys,- anchorKey: 'b',- targetKey: 'd',- })- expect(result).not.toBe(selectedKeys)- expect([...selectedKeys]).toEqual(['b'])- expect(keys).toEqual(orderedKeys)- })- })})diff --git a/apps/studio/components/interfaces/Settings/Logs/Logs.utils.ts b/apps/studio/components/interfaces/Settings/Logs/Logs.utils.tsindex 1e626a8eab6..af8ba8714de 100644--- a/apps/studio/components/interfaces/Settings/Logs/Logs.utils.ts+++ b/apps/studio/components/interfaces/Settings/Logs/Logs.utils.ts@@ -962,52 +962,3 @@ export function buildLogsPrompt(rows: LogData[], queryType?: string, sqlQuery?:'\n\nWhat do these logs indicate? What steps can I take to resolve it? Keep your answer very concise and actionable. Max 2 or 3 bullet points.')}--/**- * Computes the next multi-select set after a shift-click on `targetKey`, extending- * the selection from `anchorKey` (the last row the user clicked). Every key between- * anchor and target (inclusive, in `orderedKeys` order) is added. If the whole range is- * already selected, the range is removed instead. Falls back to a plain toggle of- * `targetKey` when there is no usable anchor (null, or no longer in `orderedKeys`).- */-export function getShiftClickSelection({- orderedKeys,- selectedKeys,- anchorKey,- targetKey,-}: {- orderedKeys: string[]- selectedKeys: Set<string>- anchorKey: string | null- targetKey: string-}): Set<string> {- const next = new Set(selectedKeys)-- const anchorIndex = anchorKey === null ? -1 : orderedKeys.indexOf(anchorKey)- const targetIndex = orderedKeys.indexOf(targetKey)- const hasUsableAnchor = anchorIndex !== -1 && targetIndex !== -1-- if (!hasUsableAnchor) {- if (next.has(targetKey)) {- next.delete(targetKey)- } else {- next.add(targetKey)- }- return next- }-- const startIndex = Math.min(anchorIndex, targetIndex)- const endIndex = Math.max(anchorIndex, targetIndex)- const rangeKeys = orderedKeys.slice(startIndex, endIndex + 1)- const isRangeFullySelected = rangeKeys.every((key) => selectedKeys.has(key))-- rangeKeys.forEach((key) => {- if (isRangeFullySelected) {- next.delete(key)- } else {- next.add(key)- }- })-- return next-}diff --git a/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.tsx b/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.tsxindex 51da12236f5..7dd37f7a810 100644--- a/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.tsx+++ b/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.tsx@@ -132,6 +132,8 @@ export const UnifiedLogs = () => {const [sorting, setSorting] = useState<SortingState>(defaultColumnSorting)const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>(defaultColumnFilters)const [rowSelection, setRowSelection] = useState<RowSelectionState>({})+ // Last row the user toggled, used as the start of a shift-click range+ const selectionAnchorRef = useRef<string | null>(null)const [openRowId, setOpenRowId] = useState<string | undefined>(search.id ?? undefined)const [dock, setDock] = useLocalStorageQuery<'bottom' | 'right'>(@@ -257,7 +259,7 @@ export const UnifiedLogs = () => {// Generate dynamic columns based on current dataconst { columns: dynamicColumns, columnVisibility: dynamicColumnVisibility } = useMemo(() => {- return generateDynamicColumns({ data: flatData })+ return generateDynamicColumns({ data: flatData, selectionAnchorRef })}, [flatData])const table: Table<ColumnSchema> = useReactTable({diff --git a/apps/studio/components/interfaces/UnifiedLogs/components/Columns.tsx b/apps/studio/components/interfaces/UnifiedLogs/components/Columns.tsxindex a53b23bcfdd..a82914fa8f4 100644--- a/apps/studio/components/interfaces/UnifiedLogs/components/Columns.tsx+++ b/apps/studio/components/interfaces/UnifiedLogs/components/Columns.tsx@@ -1,4 +1,5 @@-import { ColumnDef } from '@tanstack/react-table'+import { ColumnDef, RowSelectionState } from '@tanstack/react-table'+import type { RefObject } from 'react'import { Checkbox, cn, Tooltip, TooltipContent, TooltipTrigger } from 'ui'import { STATUS_CODE_LABELS } from '../UnifiedLogs.constants'@@ -8,6 +9,7 @@ import { HoverCardTimestamp } from './HoverCardTimestamp'import { LogTypeIcon } from './LogTypeIcon'import { DataTableColumnLevelIndicator } from '@/components/ui/DataTable/DataTableColumn/DataTableColumnLevelIndicator'import { DataTableColumnStatusCode } from '@/components/ui/DataTable/DataTableColumn/DataTableColumnStatusCode'+import { getShiftClickRowSelection } from '@/lib/shift-click-selection'/*** Determines if a column should be hidden based on its values in the data.@@ -30,7 +32,13 @@ function shouldHideColumn(data: ColumnSchema[], columnKey: keyof ColumnSchema):}// Generate dynamic columns based on data-export function generateDynamicColumns({ data }: { data: ColumnSchema[] }): {+export function generateDynamicColumns({+ data,+ selectionAnchorRef,+}: {+ data: ColumnSchema[]+ selectionAnchorRef: RefObject<string | null>+}): {columns: ColumnDef<ColumnSchema>[]columnVisibility: Record<string, boolean>} {@@ -42,13 +50,48 @@ export function generateDynamicColumns({ data }: { data: ColumnSchema[] }): {{accessorKey: 'select',header: '',- cell: ({ row }) => {+ cell: ({ row, table }) => {+ const handleToggle = (isShiftClick: boolean) => {+ const currentSelection = table.getState().rowSelection+ const hasSelection = Object.values(currentSelection).some(Boolean)+ // An empty selection means no anchor, so resetRowSelection() (filter change, clear+ // button) drops the anchor without those paths having to touch the ref+ const anchorRowId = hasSelection ? selectionAnchorRef.current : null++ let next: RowSelectionState+ if (isShiftClick) {+ next = getShiftClickRowSelection({+ orderedRowIds: table.getRowModel().rows.map((tableRow) => tableRow.id),+ rowSelection: currentSelection,+ anchorRowId,+ targetRowId: row.id,+ })+ } else {+ next = { ...currentSelection }+ if (next[row.id]) {+ delete next[row.id]+ } else {+ next[row.id] = true+ }+ }++ selectionAnchorRef.current = Object.keys(next).length > 0 ? row.id : null+ table.setRowSelection(next)+ }+return (<CheckboxclassName="hit-area-2 hover:border-foreground-muted"checked={row.getIsSelected()}- onCheckedChange={(value) => row.toggleSelected(!!value)}- onClick={(e) => e.stopPropagation()}+ // Prevent a shift-click from starting a browser text selection across rows+ onMouseDown={(e) => {+ if (e.shiftKey) e.preventDefault()+ }}+ // use onClick instead of onCheckedChange so the shift key is available for range selection+ onClick={(e) => {+ e.stopPropagation()+ handleToggle(e.shiftKey)+ }}/>)},@@ -291,7 +334,9 @@ export function generateDynamicColumns({ data }: { data: ColumnSchema[] }): {return { columns, columnVisibility }}-// Static fallback columns+// Static fallback columns. These render before any data arrives, so nothing is selectable yet+// and the anchor never has to survive past this call.export const UNIFIED_LOGS_COLUMNS: ColumnDef<ColumnSchema>[] = generateDynamicColumns({data: [],+ selectionAnchorRef: { current: null },}).columnsdiff --git a/apps/studio/lib/shift-click-selection.test.ts b/apps/studio/lib/shift-click-selection.test.tsnew file mode 100644index 00000000000..b1f5f1cd5e5--- /dev/null+++ b/apps/studio/lib/shift-click-selection.test.ts@@ -0,0 +1,195 @@+import { describe, expect, test } from 'vitest'++import { getShiftClickRowSelection, getShiftClickSelection } from './shift-click-selection'++describe('getShiftClickSelection', () => {+ const orderedKeys = ['a', 'b', 'c', 'd', 'e']++ test('selects the range downward from the anchor', () => {+ const result = getShiftClickSelection({+ orderedKeys,+ selectedKeys: new Set(['b']),+ anchorKey: 'b',+ targetKey: 'd',+ })+ expect([...result].sort()).toEqual(['b', 'c', 'd'])+ })++ test('selects the range upward from the anchor', () => {+ const result = getShiftClickSelection({+ orderedKeys,+ selectedKeys: new Set(['d']),+ anchorKey: 'd',+ targetKey: 'b',+ })+ expect([...result].sort()).toEqual(['b', 'c', 'd'])+ })++ test('deselects the range when the target is already selected', () => {+ const result = getShiftClickSelection({+ orderedKeys,+ selectedKeys: new Set(['a', 'b', 'c', 'd']),+ anchorKey: 'a',+ targetKey: 'd',+ })+ // The anchor row itself is never modified, so 'a' stays selected+ expect([...result].sort()).toEqual(['a'])+ })++ test('leaves the anchor row untouched when it is not selected', () => {+ const result = getShiftClickSelection({+ orderedKeys,+ selectedKeys: new Set(),+ anchorKey: 'b',+ targetKey: 'd',+ })+ expect([...result].sort()).toEqual(['c', 'd'])+ })++ test('applies the target state to the whole range when it is partially selected', () => {+ const result = getShiftClickSelection({+ orderedKeys,+ selectedKeys: new Set(['c']),+ anchorKey: 'a',+ targetKey: 'd',+ })+ expect([...result].sort()).toEqual(['b', 'c', 'd'])+ })++ test('toggles just the target when it is also the anchor', () => {+ const added = getShiftClickSelection({+ orderedKeys,+ selectedKeys: new Set(),+ anchorKey: 'c',+ targetKey: 'c',+ })+ expect([...added]).toEqual(['c'])++ const removed = getShiftClickSelection({+ orderedKeys,+ selectedKeys: new Set(['c']),+ anchorKey: 'c',+ targetKey: 'c',+ })+ expect([...removed]).toEqual([])+ })++ test('falls back to adding the target when there is no anchor', () => {+ const result = getShiftClickSelection({+ orderedKeys,+ selectedKeys: new Set(['a']),+ anchorKey: null,+ targetKey: 'c',+ })+ expect([...result].sort()).toEqual(['a', 'c'])+ })++ test('falls back to removing the target when there is no anchor and it is selected', () => {+ const result = getShiftClickSelection({+ orderedKeys,+ selectedKeys: new Set(['a', 'c']),+ anchorKey: null,+ targetKey: 'c',+ })+ expect([...result].sort()).toEqual(['a'])+ })++ test('falls back to a plain toggle when the anchor is no longer in the rows', () => {+ const result = getShiftClickSelection({+ orderedKeys,+ selectedKeys: new Set(),+ anchorKey: 'gone',+ targetKey: 'd',+ })+ expect([...result]).toEqual(['d'])+ })++ test('falls back to a plain toggle when the target is not in the rows', () => {+ const result = getShiftClickSelection({+ orderedKeys,+ selectedKeys: new Set(['a']),+ anchorKey: 'a',+ targetKey: 'gone',+ })+ expect([...result].sort()).toEqual(['a', 'gone'])+ })++ test('does not mutate its inputs', () => {+ const selectedKeys = new Set(['b'])+ const keys = [...orderedKeys]+ const result = getShiftClickSelection({+ orderedKeys: keys,+ selectedKeys,+ anchorKey: 'b',+ targetKey: 'd',+ })+ expect(result).not.toBe(selectedKeys)+ expect([...selectedKeys]).toEqual(['b'])+ expect(keys).toEqual(orderedKeys)+ })+})++describe('getShiftClickRowSelection', () => {+ const orderedRowIds = ['a', 'b', 'c', 'd', 'e']++ test('selects the range between the anchor and the target', () => {+ const result = getShiftClickRowSelection({+ orderedRowIds,+ rowSelection: { b: true },+ anchorRowId: 'b',+ targetRowId: 'd',+ })+ expect(result).toEqual({ b: true, c: true, d: true })+ })++ test('deselects the range when the target is already selected', () => {+ const result = getShiftClickRowSelection({+ orderedRowIds,+ rowSelection: { a: true, b: true, c: true, d: true },+ anchorRowId: 'a',+ targetRowId: 'd',+ })+ expect(result).toEqual({ a: true })+ })++ test('falls back to a plain toggle when there is no anchor', () => {+ const added = getShiftClickRowSelection({+ orderedRowIds,+ rowSelection: { a: true },+ anchorRowId: null,+ targetRowId: 'c',+ })+ expect(added).toEqual({ a: true, c: true })++ const removed = getShiftClickRowSelection({+ orderedRowIds,+ rowSelection: { a: true, c: true },+ anchorRowId: null,+ targetRowId: 'c',+ })+ expect(removed).toEqual({ a: true })+ })++ test('ignores ids explicitly set to false and never returns false entries', () => {+ const result = getShiftClickRowSelection({+ orderedRowIds,+ rowSelection: { a: false, b: true, c: false },+ anchorRowId: 'b',+ targetRowId: 'd',+ })+ expect(result).toEqual({ b: true, c: true, d: true })+ expect(Object.values(result).every((isSelected) => isSelected === true)).toBe(true)+ })++ test('does not mutate the row selection it is given', () => {+ const rowSelection = { b: true }+ const result = getShiftClickRowSelection({+ orderedRowIds,+ rowSelection,+ anchorRowId: 'b',+ targetRowId: 'd',+ })+ expect(result).not.toBe(rowSelection)+ expect(rowSelection).toEqual({ b: true })+ })+})diff --git a/apps/studio/lib/shift-click-selection.ts b/apps/studio/lib/shift-click-selection.tsnew file mode 100644index 00000000000..6c184c30571--- /dev/null+++ b/apps/studio/lib/shift-click-selection.ts@@ -0,0 +1,73 @@+import type { RowSelectionState } from '@tanstack/react-table'++/**+ * Computes the next multi-select set after a shift-click on `targetKey`, matching+ * react-data-grid's native behavior: the target's new checked state (the opposite of+ * its current one) is applied to every key strictly between `anchorKey` (the last row+ * the user clicked) and the target, plus the target itself. The anchor row is left+ * untouched. Falls back to a plain toggle of `targetKey` when there is no usable anchor+ * (null, no longer in `orderedKeys`, or the target itself).+ */+export function getShiftClickSelection({+ orderedKeys,+ selectedKeys,+ anchorKey,+ targetKey,+}: {+ orderedKeys: string[]+ selectedKeys: Set<string>+ anchorKey: string | null+ targetKey: string+}): Set<string> {+ const next = new Set(selectedKeys)+ const isChecked = !selectedKeys.has(targetKey)++ const applyCheckedState = (key: string) => {+ if (isChecked) {+ next.add(key)+ } else {+ next.delete(key)+ }+ }++ applyCheckedState(targetKey)++ const anchorIndex = anchorKey === null ? -1 : orderedKeys.indexOf(anchorKey)+ const targetIndex = orderedKeys.indexOf(targetKey)+ const hasUsableAnchor = anchorIndex !== -1 && targetIndex !== -1 && anchorIndex !== targetIndex++ if (!hasUsableAnchor) return next++ const step = anchorIndex < targetIndex ? 1 : -1+ for (let index = anchorIndex + step; index !== targetIndex; index += step) {+ applyCheckedState(orderedKeys[index])+ }++ return next+}++/**+ * `getShiftClickSelection` for TanStack Table's `RowSelectionState` (a map of row id → true).+ */+export function getShiftClickRowSelection({+ orderedRowIds,+ rowSelection,+ anchorRowId,+ targetRowId,+}: {+ orderedRowIds: string[]+ rowSelection: RowSelectionState+ anchorRowId: string | null+ targetRowId: string+}): RowSelectionState {+ const selectedRowIds = new Set(Object.keys(rowSelection).filter((id) => rowSelection[id]))++ const next = getShiftClickSelection({+ orderedKeys: orderedRowIds,+ selectedKeys: selectedRowIds,+ anchorKey: anchorRowId,+ targetKey: targetRowId,+ })++ return Object.fromEntries([...next].map((id) => [id, true]))+}diff --git a/apps/studio/tests/features/logs/LogTable.test.tsx b/apps/studio/tests/features/logs/LogTable.test.tsxindex 27d9f1541ef..05e0d20b348 100644--- a/apps/studio/tests/features/logs/LogTable.test.tsx+++ b/apps/studio/tests/features/logs/LogTable.test.tsx@@ -1,10 +1,11 @@-import { screen, waitFor } from '@testing-library/react'+import { screen, waitFor, within } from '@testing-library/react'import userEvent from '@testing-library/user-event'import dayjs from 'dayjs'import customParseFormat from 'dayjs/plugin/customParseFormat'import relativeTime from 'dayjs/plugin/relativeTime'import timezone from 'dayjs/plugin/timezone'import utc from 'dayjs/plugin/utc'+import type { ComponentProps, Key, ReactNode } from 'react'import { expect, test, vi } from 'vitest'import { LogTable } from '@/components/interfaces/Settings/Logs/LogTable'@@ -17,32 +18,145 @@ dayjs.extend(relativeTime)vi.mock('next/router', () => import('next-router-mock'))-vi.mock('react-data-grid', () => ({- default: ({ columns, rows, renderers, role, headerRowHeight }: any) => (- <div role={role ?? 'table'}>- {headerRowHeight !== 0 && (- <div role="row">- {columns.map((col: any, colIdx: number) => (- <div key={colIdx} role="columnheader">- {col.renderHeaderCell ? col.renderHeaderCell({}) : col.name}- </div>- ))}- </div>- )}- {rows.map((row: any, rowIdx: number) => (- <div key={rowIdx} role="row">- {columns.map((col: any, colIdx: number) => (- <div key={colIdx} role="cell">- {col.renderCell?.({ row, rowIdx, isCellSelected: false })}- </div>- ))}+vi.mock('react-data-grid', async () => {+ const { createContext, useContext, useRef } = await import('react')++ type MockRow = Record<string, unknown>+ type MockColumn = {+ name?: string+ renderCell?: (props: { row: MockRow; rowIdx: number; isCellSelected: boolean }) => ReactNode+ renderHeaderCell?: (props: object) => ReactNode+ }+ // The subset of react-data-grid's `RenderRowProps` a custom row renderer reads, plus the+ // DOM props (onClick, onContextMenu, className, ...) the renderer forwards to the row element+ type MockRowProps = {+ row: MockRow+ rowIdx: number+ viewportColumns: MockColumn[]+ isRowSelected: boolean+ selectedCellIdx?: number+ } & ComponentProps<'div'>+ type SelectRowEvent = { row: MockRow; checked: boolean; isShiftClick: boolean }+ type MockDataGridProps = {+ columns: MockColumn[]+ rows: MockRow[]+ renderers?: {+ renderRow?: (key: Key, props: MockRowProps) => ReactNode+ noRowsFallback?: ReactNode+ }+ role?: string+ headerRowHeight?: number+ rowKeyGetter: (row: MockRow) => string+ selectedRows?: ReadonlySet<string>+ onSelectedRowsChange?: (selectedRows: Set<string>) => void+ }++ const RowSelectionContext = createContext<{+ isRowSelected: boolean+ onRowSelectionChange: (event: SelectRowEvent) => void+ }>({ isRowSelected: false, onRowSelectionChange: () => {} })++ // Mirrors react-data-grid's `Row`: renders the viewport columns and spreads the rest of+ // the props onto the row element, so only DOM props reach the DOM+ const MockRowRenderer = ({+ row,+ rowIdx,+ viewportColumns,+ isRowSelected,+ selectedCellIdx,+ ...props+ }: MockRowProps) => (+ <div role="row" {...props}>+ {viewportColumns.map((col, colIdx) => (+ <div key={colIdx} role="cell">+ {col.renderCell?.({ row, rowIdx, isCellSelected: false })}</div>))}- {rows.length === 0 && renderers?.noRowsFallback}</div>- ),- Row: ({ row, ...props }: any) => <div role="row" {...props} />,-}))+ )++ const MockDataGrid = ({+ columns,+ rows,+ renderers,+ role,+ headerRowHeight,+ rowKeyGetter,+ selectedRows,+ onSelectedRowsChange,+ }: MockDataGridProps) => {+ // Mirrors react-data-grid's own `selectRow`: the anchor is the last clicked row and a+ // shift-click applies the clicked row's new state to every row between the two+ const lastSelectedRowIdx = useRef(-1)++ const selectRow = ({ row, checked, isShiftClick }: SelectRowEvent) => {+ const nextSelectedRows = new Set<string>(selectedRows ?? [])+ const previousRowIdx = lastSelectedRowIdx.current+ const rowIdx = rows.indexOf(row)+ lastSelectedRowIdx.current = rowIdx++ const applyCheckedState = (targetRow: MockRow) => {+ if (checked) {+ nextSelectedRows.add(rowKeyGetter(targetRow))+ } else {+ nextSelectedRows.delete(rowKeyGetter(targetRow))+ }+ }++ applyCheckedState(row)++ if (isShiftClick && previousRowIdx !== -1 && previousRowIdx !== rowIdx) {+ const step = previousRowIdx < rowIdx ? 1 : -1+ for (let idx = previousRowIdx + step; idx !== rowIdx; idx += step) {+ applyCheckedState(rows[idx])+ }+ }++ onSelectedRowsChange?.(nextSelectedRows)+ }++ return (+ <div role={role ?? 'table'}>+ {headerRowHeight !== 0 && (+ <div role="row">+ {columns.map((col, colIdx) => (+ <div key={colIdx} role="columnheader">+ {col.renderHeaderCell ? col.renderHeaderCell({}) : col.name}+ </div>+ ))}+ </div>+ )}+ {rows.map((row, rowIdx) => {+ const rowProps: MockRowProps = {+ row,+ rowIdx,+ viewportColumns: columns,+ isRowSelected: selectedRows?.has(rowKeyGetter(row)) ?? false,+ }+ return (+ <RowSelectionContext.Provider+ key={rowIdx}+ value={{ isRowSelected: rowProps.isRowSelected, onRowSelectionChange: selectRow }}+ >+ {renderers?.renderRow ? (+ renderers.renderRow(rowKeyGetter(row), rowProps)+ ) : (+ <MockRowRenderer {...rowProps} />+ )}+ </RowSelectionContext.Provider>+ )+ })}+ {rows.length === 0 && renderers?.noRowsFallback}+ </div>+ )+ }++ return {+ default: MockDataGrid,+ Row: MockRowRenderer,+ useRowSelection: () => useContext(RowSelectionContext),+ }+})const fakeMicroTimestamp = dayjs().unix() * 1000@@ -357,30 +471,64 @@ test('shift-click without an anchor toggles only the clicked row', async () => {await screen.findByText('1 row selected')})-test('clears the shift-click anchor once the selection becomes empty', async () => {+test('shift-click on a selected row deselects back to the anchor, leaving the anchor checked', async () => {const user = userEvent.setup()render(<LogTable projectRef="projectRef" data={MULTI_SELECT_LOGS} />)await user.click(getRowCheckboxes()[1])- await user.click(getRowCheckboxes()[1])- expectCheckedIndexes([])-await shiftClick(user, getRowCheckboxes()[4])+ expectCheckedIndexes([1, 2, 3, 4])++ // Row 4 is now the anchor and is never modified, so only it stays checked+ await shiftClick(user, getRowCheckboxes()[1])expectCheckedIndexes([4])await screen.findByText('1 row selected')})-test('shift-click deselects a range that is already fully selected', async () => {+test('clicking a checked row again clears the selection', async () => {const user = userEvent.setup()render(<LogTable projectRef="projectRef" data={MULTI_SELECT_LOGS} />)+ await user.click(getRowCheckboxes()[2])+ expectCheckedIndexes([2])+ await screen.findByText('1 row selected')++ await user.click(getRowCheckboxes()[2])++ expectCheckedIndexes([])+ await waitFor(() => expect(screen.queryByText(/rows? selected/)).toBeNull())+})++test('checkbox clicks stay inside the checkbox column while a row click clears the selection', async () => {+ const user = userEvent.setup()+ const onSelectedLogChange = vi.fn()+ render(+ <LogTable+ projectRef="projectRef"+ data={MULTI_SELECT_LOGS}+ onSelectedLogChange={onSelectedLogChange}+ />+ )+await user.click(getRowCheckboxes()[1])- await shiftClick(user, getRowCheckboxes()[4])- expectCheckedIndexes([1, 2, 3, 4])+ await shiftClick(user, getRowCheckboxes()[3])- await shiftClick(user, getRowCheckboxes()[1])+ expectCheckedIndexes([1, 2, 3])+ await screen.findByText('3 rows selected')+ // Checking rows only closes the side panel (`null`), it never opens one for a log+ expect(onSelectedLogChange).not.toHaveBeenCalledWith(+ expect.objectContaining({ id: expect.any(String) })+ )+ const dataRows = screen+ .getAllByRole('row')+ .filter((row) => within(row).queryByRole('checkbox') !== null)+ await user.click(dataRows[4])++ expect(onSelectedLogChange).toHaveBeenCalledWith(+ expect.objectContaining({ id: MULTI_SELECT_LOGS[4].id })+ )expectCheckedIndexes([])await waitFor(() => expect(screen.queryByText(/rows? selected/)).toBeNull())})