|
| 1 | +import type { ReactNode, Ref } from 'react' |
| 2 | +import React, { Fragment } from 'react' |
| 3 | +import { TableCell, TableRow, type TableRowProps } from '../table' |
| 4 | +import { flexRender, type Row } from '@tanstack/react-table' |
| 5 | +import type { NavigationTarget } from '../link-box/link-box-utils' |
| 6 | +import { Clickable } from '../clickable' |
| 7 | +import { LinkBox } from '../link-box' |
| 8 | +import { forwardRef } from '@vtex/shoreline-utils' |
| 9 | + |
| 10 | +export const SimpleTableRow = forwardRef(function SimpleTableRow<T>( |
| 11 | + props: SimpleTableRowProps<T>, |
| 12 | + ref: Ref<HTMLDivElement> |
| 13 | +) { |
| 14 | + const { row, id, rowClick, renderDetail, children, ...otherProps } = props |
| 15 | + |
| 16 | + return ( |
| 17 | + <Fragment key={id}> |
| 18 | + <TableRow |
| 19 | + ref={ref} |
| 20 | + selected={row.getIsSelected()} |
| 21 | + expanded={row.getIsExpanded()} |
| 22 | + {...otherProps} |
| 23 | + > |
| 24 | + {row.getVisibleCells().map((cell) => { |
| 25 | + if (rowClick) { |
| 26 | + if (rowClick.type === 'action') { |
| 27 | + const { onClick } = rowClick |
| 28 | + |
| 29 | + return ( |
| 30 | + <Clickable onClick={() => onClick(row)} key={cell.id} asChild> |
| 31 | + <TableCell> |
| 32 | + {flexRender(cell.column.columnDef.cell, cell.getContext())} |
| 33 | + </TableCell> |
| 34 | + </Clickable> |
| 35 | + ) |
| 36 | + } |
| 37 | + |
| 38 | + if (rowClick.type === 'link') { |
| 39 | + const { getHref, target } = rowClick |
| 40 | + |
| 41 | + return ( |
| 42 | + <LinkBox |
| 43 | + href={getHref(row)} |
| 44 | + target={target} |
| 45 | + key={cell.id} |
| 46 | + asChild |
| 47 | + > |
| 48 | + <TableCell> |
| 49 | + {flexRender(cell.column.columnDef.cell, cell.getContext())} |
| 50 | + </TableCell> |
| 51 | + </LinkBox> |
| 52 | + ) |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + return ( |
| 57 | + <TableCell key={cell.id}> |
| 58 | + {flexRender(cell.column.columnDef.cell, cell.getContext())} |
| 59 | + </TableCell> |
| 60 | + ) |
| 61 | + })} |
| 62 | + </TableRow> |
| 63 | + {row.getIsExpanded() && ( |
| 64 | + <TableRow data-sl-detail-row selected={row.getIsSelected()}> |
| 65 | + <TableCell |
| 66 | + style={{ |
| 67 | + gridColumn: `1 / span ${row.getVisibleCells().length}`, |
| 68 | + }} |
| 69 | + > |
| 70 | + {renderDetail?.(row)} |
| 71 | + </TableCell> |
| 72 | + </TableRow> |
| 73 | + )} |
| 74 | + </Fragment> |
| 75 | + ) |
| 76 | +}) |
| 77 | + |
| 78 | +export interface SimpleTableRowProps<T> extends TableRowProps { |
| 79 | + row: Row<T> |
| 80 | + rowClick?: RowClick<T> |
| 81 | + renderDetail?: (row: Row<T>) => ReactNode |
| 82 | +} |
| 83 | + |
| 84 | +export type RowClick<T> = |
| 85 | + | { |
| 86 | + type: 'link' |
| 87 | + getHref: (row: Row<T>) => string |
| 88 | + target?: NavigationTarget | undefined |
| 89 | + } |
| 90 | + | { |
| 91 | + type: 'action' |
| 92 | + onClick: (row: Row<T>) => void |
| 93 | + } |
| 94 | + | undefined |
0 commit comments