Debian Codegraph @

node/@patternfly/react-table/src/deprecated/components/Table/examples/LegacyTableFavoritable.tsx

raw
1 import { useCallback, useState } from 'react';
2 import { sortable } from '@patternfly/react-table';
3 import { Table, TableHeader, TableBody, TableProps } from '@patternfly/react-table/deprecated';
4 import { Checkbox } from '@patternfly/react-core';
5
6 interface Repository {
7 name: string;
8 branches: string;
9 prs: string;
10 workspaces: string;
11 lastCommit: string;
12 }
13
14 export const LegacyTableFavoritable: React.FunctionComponent = () => {
15 // In real usage, this data would come from some external source like an API via props.
16 const repositories: Repository[] = [
17 { name: 'one', branches: 'two', prs: 'a', workspaces: 'four', lastCommit: 'five' },
18 { name: 'a', branches: 'two', prs: 'k', workspaces: 'four', lastCommit: 'five' },
19 { name: 'p', branches: 'two', prs: 'b', workspaces: 'four', lastCommit: 'five' }
20 ];
21
22 // Index of the currently sorted column
23 // Note: if you intend to make columns reorderable, you may instead want to use a non-numeric key
24 // as the identifier of the sorted column. See the "Compound expandable" example.
25 const [activeSortIndex, setActiveSortIndex] = useState<number | null>(null);
26
27 // Sort direction of the currently sorted column
28 const [activeSortDirection, setActiveSortDirection] = useState<'asc' | 'desc' | null>(null);
29
30 // Favorite state is similar to selection state. See selectedRepoNames and associated code below.
31 const [favoriteRepoNames, setFavoriteRepoNames] = useState<string[]>([]);
32 const setRepoFavorited = (repo: Repository, isFavoriting = true) =>
33 setFavoriteRepoNames((prevFavorites) => {
34 const otherFavorites = prevFavorites.filter((r) => r !== repo.name);
35 return isFavoriting ? [...otherFavorites, repo.name] : otherFavorites;
36 });
37 const isRepoFavorited = (repo: Repository) => favoriteRepoNames.includes(repo.name);
38
39 // Since OnSort specifies sorted columns by index, we need sortable values for our object by column index.
40 // Note: We also memoize the sortable values with useCallback to prevent rows jumping around when you change
41 // the favorites while sorting on that column. Only updating the sort state will reorder the rows.
42 const getSortableRowValues = useCallback(
43 (repo: Repository): (boolean | string | number)[] => {
44 const { name, branches, prs, workspaces, lastCommit } = repo;
45 // Blank value for first column (select checkboxes)
46 return ['', isRepoFavorited(repo), name, branches, prs, workspaces, lastCommit];
47 },
48 [activeSortIndex, activeSortDirection]
49 );
50
51 // Note that we perform the sort as part of the component's render logic and not in onSort.
52 // We shouldn't store the list of data in state because we don't want to have to sync that with props.
53 let sortedRepositories = repositories;
54 if (activeSortIndex !== null) {
55 sortedRepositories = repositories.sort((a, b) => {
56 const aValue = getSortableRowValues(a)[activeSortIndex];
57 const bValue = getSortableRowValues(b)[activeSortIndex];
58 if (typeof aValue === 'number' || typeof aValue === 'boolean') {
59 // Numeric sort
60 if (activeSortDirection === 'asc') {
61 return (aValue as number) - (bValue as number);
62 }
63 return (bValue as number) - (aValue as number);
64 } else {
65 // String sort
66 if (activeSortDirection === 'asc') {
67 return (aValue as string).localeCompare(bValue as string);
68 }
69 return (bValue as string).localeCompare(aValue as string);
70 }
71 });
72 }
73
74 const isRepoSelectable = (repo: Repository) => repo.name !== 'a'; // Arbitrary logic for this example
75 const selectableRepos = repositories.filter(isRepoSelectable);
76
77 // In this example, selected rows are tracked by the repo names from each row. This could be any unique identifier.
78 // This is to prevent state from being based on row order index in case we later add sorting.
79 const [selectedRepoNames, setSelectedRepoNames] = useState<string[]>([]);
80 const setRepoSelected = (repo: Repository, isSelecting = true) =>
81 setSelectedRepoNames((prevSelected) => {
82 const otherSelectedRepoNames = prevSelected.filter((r) => r !== repo.name);
83 return isSelecting && isRepoSelectable(repo) ? [...otherSelectedRepoNames, repo.name] : otherSelectedRepoNames;
84 });
85 const selectAllRepos = (isSelecting = true) =>
86 setSelectedRepoNames(isSelecting ? selectableRepos.map((r) => r.name) : []);
87 const isRepoSelected = (repo: Repository) => selectedRepoNames.includes(repo.name);
88
89 const columns: TableProps['cells'] = [
90 { title: 'Repositories', transforms: [sortable] },
91 'Branches',
92 'Pull requests',
93 'Workspaces',
94 'Last commit'
95 ];
96 const rows: TableProps['rows'] = sortedRepositories.map((repo) => {
97 const favorited = isRepoFavorited(repo);
98 return {
99 favorited,
100 // The favorites button has defaults that can be overriden
101 favoritesProps: {
102 'aria-label': favorited ? 'Favorited' : 'Not favorited', // Defaults to 'Starred' / 'Not starred'
103 id: `favorites-button-${repo.name}`, // Defaults to `favorites-button-${rowIndex}`
104 'aria-labelledby': `favorites-button-${repo.name}` // Defaults to `favorites-button-${rowIndex}`
105 },
106 selected: isRepoSelected(repo),
107 disableSelection: !isRepoSelectable(repo),
108 cells: [repo.name, repo.branches, repo.prs, repo.workspaces, repo.lastCommit]
109 };
110 });
111
112 const [canSortFavorites, setCanSortFavorites] = useState(true);
113
114 return (
115 <div>
116 <Checkbox
117 label="Can sort favorites"
118 isChecked={canSortFavorites}
119 onChange={(_event, checked) => setCanSortFavorites(checked)}
120 aria-label="toggle can sort favorites checkbox"
121 id="toggle-can-sort-favorites"
122 name="toggle-can-sort-favorites"
123 />
124 <Table
125 // using this prop enables the favorites column
126 onFavorite={(_event, isFavoriting, rowIndex) => {
127 const repo = sortedRepositories[rowIndex];
128 setRepoFavorited(repo, isFavoriting);
129 }}
130 // if the onSort prop is detected, favorites can be sorted
131 // if you want to exclude favorites from sorting you can use this prop with a value of `false`
132 canSortFavorites={canSortFavorites}
133 onSelect={(_event, isSelecting, rowIndex) => {
134 if (rowIndex === -1) {
135 selectAllRepos(isSelecting);
136 } else {
137 const repo = sortedRepositories[rowIndex];
138 setRepoSelected(repo, isSelecting);
139 }
140 }}
141 onSort={(_event, index, direction) => {
142 setActiveSortIndex(index);
143 setActiveSortDirection(direction);
144 }}
145 sortBy={{
146 index: activeSortIndex,
147 direction: activeSortDirection
148 }}
149 aria-label="Favoritable Table"
150 cells={columns}
151 rows={rows}
152 >
153 <TableHeader />
154 <TableBody />
155 </Table>
156 </div>
157 );
158 };