Skip to content

Commit

Permalink
🌱 Add data attributes to table rows
Browse files Browse the repository at this point in the history
To enable easier and safer selection of table rows by
testing code, add some data attributes to the tr:

  - `data-item-id` - Holds the `idProperty` value of
    a table's items.  This is typically the item's id
    number but may be a frontend generated ID in some
    cases.

  - `data-item-name` - If the table property `dataNameProperty`
    is provided, hold the name property of a table's item.

Signed-off-by: Scott J Dickerson <[email protected]>
  • Loading branch information
sjd78 committed Jul 3, 2024
1 parent 5735197 commit 62be899
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 1 deletion.
11 changes: 10 additions & 1 deletion client/src/app/hooks/table-controls/types.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import { TableProps, TdProps, ThProps, TrProps } from "@patternfly/react-table";
import { ISelectionStateArgs, useSelectionState } from "@migtools/lib-ui";
import { DisallowCharacters, DiscriminatedArgs } from "@app/utils/type-utils";
import {
DisallowCharacters,
DiscriminatedArgs,
KeyWithValueType,
} from "@app/utils/type-utils";
import {
IFilterStateArgs,
ILocalFilterDerivedStateArgs,
Expand Down Expand Up @@ -314,6 +318,11 @@ export type IUseTableControlPropsArgs<
* The state for the columns feature. Returned by useColumnState.
*/
columnState: IColumnState<TColumnKey>;
/**
* Name of a field in TItem to use as the table row's `data-item-name` value. Without
* this property provided, the `data-item-name` is not added to the table row.
*/
dataNameProperty?: KeyWithValueType<TItem, string>;
};

/**
Expand Down
6 changes: 6 additions & 0 deletions client/src/app/hooks/table-controls/useTableControlProps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,9 @@ export const useTableControlProps = <
isItemSelected,
},
columnNames,
idProperty,
dataNameProperty,
tableName,
hasActionsColumn = false,
variant,
isFilterEnabled,
Expand Down Expand Up @@ -134,6 +137,9 @@ export const useTableControlProps = <
const getTrProps: PropHelpers["getTrProps"] = ({ item, onRowClick }) => {
const activeItemTrProps = getActiveItemTrProps({ item });
return {
id: `${tableName}-row-item-${item[idProperty]}`,
"data-item-id": item[idProperty],
"data-item-name": dataNameProperty && item[dataNameProperty],
...(isActiveItemEnabled && activeItemTrProps),
onRowClick: (event) =>
handlePropagatedRowClick(event, () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,7 @@ export const ApplicationsTable: React.FC = () => {
const tableControls = useLocalTableControls({
tableName: "applications",
idProperty: "id",
dataNameProperty: "name",
items: applications || [],
columnNames: {
name: "Name",
Expand Down

0 comments on commit 62be899

Please sign in to comment.