| 1 |
import React from 'react' |
| 2 |
import classnames from 'classnames' |
| 3 |
import { __ } from '@wordpress/i18n' |
| 4 |
import type { Dispatch, Key, SetStateAction } from 'react' |
| 5 |
import type { ListTableColumn, ListTableRowsProps } from './ListTable' |
| 6 |
|
| 7 |
interface CheckboxCellProps<T, K extends Key> extends Pick<TableRowsProps<T, K>, 'getKey'> { |
| 8 |
item: T |
| 9 |
selected: Set<K> |
| 10 |
setSelected: Dispatch<SetStateAction<Set<K>>> |
| 11 |
} |
| 12 |
|
| 13 |
const CheckboxCell = <T, K extends Key>({ item, selected, setSelected, getKey }: CheckboxCellProps<T, K>) => |
| 14 |
<th scope="row" className="check-column"> |
| 15 |
<input |
| 16 |
id={`cb-select-${getKey(item)}`} |
| 17 |
type="checkbox" |
| 18 |
name="checked[]" |
| 19 |
aria-label={__('Select snippet', 'code-snippets')} |
| 20 |
checked={selected.has(getKey(item))} |
| 21 |
onChange={event => { |
| 22 |
setSelected(previous => { |
| 23 |
const updated = new Set(previous) |
| 24 |
|
| 25 |
if (event.target.checked) { |
| 26 |
updated.add(getKey(item)) |
| 27 |
} else { |
| 28 |
updated.delete(getKey(item)) |
| 29 |
} |
| 30 |
|
| 31 |
return updated |
| 32 |
}) |
| 33 |
}} |
| 34 |
/> |
| 35 |
</th> |
| 36 |
|
| 37 |
interface TableCellProps<T> { |
| 38 |
item: T |
| 39 |
column: ListTableColumn<T> |
| 40 |
} |
| 41 |
|
| 42 |
const TableCell = <T, >({ item, column }: TableCellProps<T>) => { |
| 43 |
const className = classnames(`${column.id}-column`, `column-${column.id}`, { hidden: column.isHidden }) |
| 44 |
|
| 45 |
return column.isHeading |
| 46 |
? <th className={className}>{column.render(item)}</th> |
| 47 |
: <td className={className}>{column.render(item)}</td> |
| 48 |
} |
| 49 |
|
| 50 |
export interface TableRowsProps<T, K extends Key> |
| 51 |
extends Pick<ListTableRowsProps<T, K>, 'getKey' | 'columns' | 'noItems' | 'rowClassName'> { |
| 52 |
items: T[] |
| 53 |
selected: Set<K> |
| 54 |
setSelected: Dispatch<SetStateAction<Set<K>>> |
| 55 |
} |
| 56 |
|
| 57 |
export const TableRows = <T, K extends Key>({ |
| 58 |
items, |
| 59 |
getKey, |
| 60 |
columns, |
| 61 |
noItems, |
| 62 |
selected, |
| 63 |
setSelected, |
| 64 |
rowClassName |
| 65 |
}: TableRowsProps<T, K> |
| 66 |
) => |
| 67 |
0 < items.length |
| 68 |
? items.map(item => |
| 69 |
<tr key={getKey(item)} className={rowClassName?.(item)}> |
| 70 |
<CheckboxCell {...{ item, selected, setSelected, getKey }} /> |
| 71 |
|
| 72 |
{columns.map(column => |
| 73 |
<TableCell key={column.id} item={item} column={column} />)} |
| 74 |
</tr> |
| 75 |
) |
| 76 |
: <tr className="no-items"> |
| 77 |
<td className="colspanchange" colSpan={columns.length}>{noItems}</td> |
| 78 |
</tr> |
| 79 |
|