"use client" import * as React from "react" import type { FinderGroup } from "./finder-panel-view" /** * Which group and which row a finder panel has selected. The row falls back to * the first visible one, so changing group (or the rows) never leaves the detail * pane pointing at something that is no longer listed. */ export function useFinderSelection({ groups, rows, getRowId, getRowGroupId, defaultGroupId, }: { groups: FinderGroup[] rows: T[] getRowId: (row: T) => string | number getRowGroupId: (row: T) => string defaultGroupId?: string }) { const firstGroupId = defaultGroupId ?? groups[0]?.id ?? "all" const [selectedGroupId, setSelectedGroupId] = React.useState(firstGroupId) const [selectedRowId, setSelectedRowId] = React.useState(null) const visibleRows = React.useMemo(() => { if (selectedGroupId === "all") return rows return rows.filter(r => getRowGroupId(r) === selectedGroupId) }, [rows, selectedGroupId, getRowGroupId]) const resolvedRowId = React.useMemo(() => { if ( selectedRowId !== null && visibleRows.some(r => getRowId(r) === selectedRowId) ) { return selectedRowId } return visibleRows[0] ? getRowId(visibleRows[0]) : null }, [selectedRowId, visibleRows, getRowId]) const handleSelectGroup = React.useCallback( (id: string) => { setSelectedGroupId(id) const nextRows = id === "all" ? rows : rows.filter(r => getRowGroupId(r) === id) setSelectedRowId(nextRows[0] ? getRowId(nextRows[0]) : null) }, [rows, getRowGroupId, getRowId], ) const selectedRow = resolvedRowId !== null ? (visibleRows.find(r => getRowId(r) === resolvedRowId) ?? null) : null return { selectedGroupId, setSelectedRowId, visibleRows, resolvedRowId, selectedRow, handleSelectGroup, } }