import { useState, type KeyboardEvent, type MouseEvent } from "react"; /** * Makes the rows of a table open a detail panel. Spread `rowProps(item)` onto the row: a click or Enter on the row opens it, but * a click on a button, link or tick-box inside the row does its own thing and leaves the panel alone. */ export function useRowDetail() { const [selected, setSelected] = useState(null); function rowProps(item: T) { return { className: "row-clickable", tabIndex: 0, "aria-haspopup": "dialog" as const, onClick: (e: MouseEvent) => { if ((e.target as HTMLElement).closest("a, button, input, select, textarea, label, summary")) return; // The row takes the focus, so it is what the keyboard comes back to when the panel closes. e.currentTarget.focus({ preventScroll: true }); setSelected(item); }, onKeyDown: (e: KeyboardEvent) => { if (e.key === "Enter" && e.target === e.currentTarget) { e.preventDefault(); setSelected(item); } }, }; } return { selected, close: () => setSelected(null), rowProps }; }