Debian Codegraph @

node/@patternfly/react-table/src/components/Table/utils/headerUtils.tsx

raw
1 import { scopeColTransformer, emptyCol, mapProps, emptyTD, parentId } from './transformers';
2 import {
3 selectable,
4 cellActions,
5 collapsible,
6 expandedRow,
7 editable,
8 favoritable,
9 sortableFavorites
10 } from './decorators';
11 import { defaultTitle } from './formatters';
12 import {
13 ICell,
14 IRow,
15 IActions,
16 IActionsResolver,
17 IAreActionsDisabled,
18 OnSelect,
19 OnCollapse,
20 OnRowEdit,
21 OnFavorite,
22 OnSort,
23 ISortBy
24 } from '../TableTypes';
25
26 /**
27 * Generate header with transforms and formatters from custom header object.
28 *
29 * @param {*} header with transforms, formatters, columnTransforms, and rest of header object.
30 * @param {*} title to be used as label in header config.
31 * @returns {*} header, label, transforms: Array, formatters: Array.
32 */
33 const generateHeader = (
34 { transforms: origTransforms, formatters: origFormatters, columnTransforms, header }: ICell,
35 title?: string | ICell
36 ) => ({
37 ...header,
38 label: title,
39 transforms: [
40 scopeColTransformer,
41 emptyCol,
42 ...(origTransforms || []),
43 ...(columnTransforms || []),
44 ...(header && header.hasOwnProperty('transforms') ? header.transforms : [])
45 ],
46 formatters: [...(origFormatters || []), ...(header && header.hasOwnProperty('formatters') ? header.formatters : [])]
47 });
48
49 interface ICustomCell {
50 cellFormatters?: ICell['cellFormatters'];
51 cellTransforms?: ICell['cellTransforms'];
52 columnTransforms?: ICell['columnTransforms'];
53 cell?: ICell;
54 }
55
56 /**
57 * Function to generate cell for header config to change look of each cell.
58 *
59 * @param {*} customCell config with cellFormatters, cellTransforms, columnTransforms and rest of cell config.
60 * @param {*} extra - extra
61 * @returns {*} cell, transforms: Array, formatters: Array.
62 */
63 const generateCell = (
64 { cellFormatters, cellTransforms, columnTransforms, cell }: ICustomCell,
65 // eslint-disable-next-line @typescript-eslint/no-unused-vars
66 extra: any
67 ) => ({
68 ...cell,
69 transforms: [
70 ...(cellTransforms || []),
71 ...(columnTransforms || []),
72 ...(cell && cell.hasOwnProperty('transforms') ? cell.transforms : []),
73 mapProps // This transform should be applied last so that props that are manually defined at the cell level will override all other transforms.
74 ],
75 formatters: [
76 defaultTitle,
77 ...(cellFormatters || []),
78 ...(cell && cell.hasOwnProperty('formatters') ? cell.formatters : [])
79 ]
80 });
81
82 /**
83 * Function to map custom simple object properties to expected format with property, header, cell, extra params
84 * and props.
85 *
86 * @param {*} column to be shown in header - either string or object with title, transformers and formatters (for cells as well).
87 * @param {*} extra additional object with callbacks for specific formatters.
88 * @param {*} key cell key to be shown in data-key.
89 * @param {*} props additional props for each cell.
90 * @returns {*} object with property, extraParams, header, cell and props.
91 */
92 const mapHeader = (column: ICell, extra: any, key: number, ...props: any) => {
93 const title = (column.hasOwnProperty('title') ? column.title : column) as string | ICell;
94 let dataLabel: string | ICell = `column-${key}`;
95 if (column.hasOwnProperty('dataLabel')) {
96 dataLabel = column.dataLabel;
97 } else if (typeof title === 'string') {
98 dataLabel = title;
99 }
100
101 return {
102 property: (typeof title === 'string' && title.toLowerCase().trim().replace(/\s/g, '-')) || `column-${key}`,
103 extraParams: extra,
104 data: column.data,
105 header: generateHeader(column, title),
106 cell: generateCell(column, extra),
107 props: {
108 'data-label': dataLabel,
109 'data-key': key,
110 ...(column.hasOwnProperty('props') ? column.props : {}),
111 ...props
112 }
113 };
114 };
115
116 export interface ISelectTransform {
117 onSelect: OnSelect;
118 canSelectAll: boolean;
119 }
120
121 /**
122 * Function to define select cell in first column.
123 *
124 * @param {*} extraObject with onSelect callback.
125 * @returns {*} object with empty title, tranforms - Array, cellTransforms - Array.
126 */
127 const selectableTransforms = ({ onSelect, canSelectAll }: ISelectTransform) => [
128 ...(onSelect
129 ? [
130 {
131 title: '',
132 transforms: (canSelectAll && [selectable]) || null,
133 cellTransforms: [selectable]
134 }
135 ]
136 : [])
137 ];
138
139 /**
140 * Function to define favorites cell in first column (or second column if rows are also selectable).
141 *
142 * @param {*} extraObject with onFavorite callback.
143 * @returns {*} object with empty title, tranforms - Array, cellTransforms - Array.
144 */
145 const favoritesTransforms = ({
146 onFavorite,
147 onSort,
148 sortBy,
149 canSortFavorites,
150 firstUserColumnIndex
151 }: {
152 onFavorite: OnFavorite;
153 onSort: OnSort;
154 sortBy: ISortBy;
155 canSortFavorites: boolean;
156 firstUserColumnIndex: number;
157 }): any => [
158 ...(onFavorite
159 ? [
160 {
161 title: '',
162 transforms:
163 onSort && canSortFavorites
164 ? [
165 scopeColTransformer,
166 sortableFavorites({
167 onSort,
168 // favorites should be just before the first user-defined column
169 columnIndex: firstUserColumnIndex - 1,
170 sortBy
171 })
172 ]
173 : [emptyTD],
174 cellTransforms: [favoritable]
175 }
176 ]
177 : [])
178 ];
179
180 /**
181 * Function to define actions in last column.
182 *
183 * @param {*} extraObject with actions array.
184 * @returns {*} object with empty title, tranforms - Array, cellTransforms - Array.
185 */
186 const actionsTransforms = ({
187 actions,
188 actionResolver,
189 areActionsDisabled
190 }: {
191 actions: IActions;
192 actionResolver: IActionsResolver;
193 areActionsDisabled: IAreActionsDisabled;
194 }) => [
195 ...(actionResolver || actions
196 ? [
197 {
198 title: '',
199 transforms: [emptyTD],
200 cellTransforms: [cellActions(actions, actionResolver, areActionsDisabled)]
201 }
202 ]
203 : [])
204 ];
205
206 export interface ICollapseTranform {
207 onCollapse: OnCollapse;
208 canCollapseAll: boolean;
209 // Account for additional added columns for full width
210 firstUserColumnIndex: number;
211 }
212
213 /**
214 * Function to define collapsible in first column.
215 *
216 * @param {*} header info with cellTransforms.
217 * @param {*} extraObject with onCollapse callback.
218 * @returns {*} object with empty title, tranforms - Array, cellTransforms - Array.
219 */
220 const collapsibleTransforms = (
221 header: (ICell | string)[],
222 { onCollapse, canCollapseAll, firstUserColumnIndex }: ICollapseTranform
223 ) => [
224 ...(onCollapse
225 ? [
226 {
227 title: '',
228 transforms: (canCollapseAll && [collapsible]) || null,
229 cellTransforms: [collapsible, expandedRow(header.length, firstUserColumnIndex)]
230 }
231 ]
232 : [])
233 ];
234
235 /**
236 * Function to add additional cell transforms to object.
237 *
238 * @param {*} cell to be expanded.
239 * @param {*} additional thing to be added to cellTransforms.
240 * @returns {*} object with title from cell and cellTransforms with additional in.
241 */
242 const addAdditionalCellTranforms = (cell: ICell, additional: any) => ({
243 ...(cell.hasOwnProperty('title') ? cell : { title: cell }),
244 cellTransforms: [...(cell.hasOwnProperty('cellTransforms') ? cell.cellTransforms : []), additional]
245 });
246
247 /**
248 * Function to change expanded row with additional transforms.
249 *
250 * @param {*} header info with cellTransforms.
251 * @param {*} extra object with onCollapse/onExpand function.
252 */
253 const expandContent = (header: (ICell | string)[], extra: any) => {
254 if (!extra.onCollapse && !extra.onExpand) {
255 return header;
256 }
257 return header.map((cell: ICell | string) => {
258 const parentIdCell = addAdditionalCellTranforms(cell as ICell, parentId);
259 return addAdditionalCellTranforms(parentIdCell as ICell, expandedRow(header.length));
260 });
261 };
262
263 /**
264 * Function to join parent and their children so they can be rendered in tbody.
265 *
266 * @param {*} rows raw data to find out if it's child or parent.
267 * @param {*} children data to render (array of react children).
268 */
269 export const mapOpenedRows = (rows: IRow[], children: any) =>
270 rows.reduce((acc: any, curr, key) => {
271 if (curr.hasOwnProperty('parent')) {
272 const parent = acc.length > 0 && acc[acc.length - 1];
273 if (parent) {
274 acc[acc.length - 1].rows = [...acc[acc.length - 1].rows, children[key]];
275 if (curr.hasOwnProperty('compoundParent')) {
276 // if this is compound expand, check for any open child cell
277 acc[acc.length - 1].isOpen = acc[acc.length - 1].rows.some((oneRow: IRow) =>
278 oneRow.props.rowData.cells.some((oneCell: ICell) => oneCell.props && oneCell.props.isOpen)
279 );
280 }
281 }
282 } else {
283 acc = [...acc, { ...curr, rows: [children[key]] }];
284 }
285 return acc;
286 }, []) as IRow[];
287
288 const rowEditTransforms = ({ onRowEdit }: { onRowEdit: OnRowEdit }) => [
289 ...(onRowEdit
290 ? [
291 {
292 title: '',
293 cellTransforms: [editable]
294 }
295 ]
296 : [])
297 ];
298
299 /**
300 * Function to calculate columns based on custom config.
301 * It adds some custom cells for collapse, select, if expanded row and actions.
302 *
303 * @param {*} headerRows custom object with described table header cells.
304 * @param {*} extra object with custom callbacks.
305 * @returns {*} expected object for react tabular table.
306 */
307 export const calculateColumns = (headerRows: (ICell | string)[], extra: any) =>
308 headerRows &&
309 [
310 ...collapsibleTransforms(headerRows, extra),
311 ...selectableTransforms(extra),
312 ...favoritesTransforms(extra),
313 ...expandContent(headerRows, extra),
314 ...rowEditTransforms(extra),
315 ...actionsTransforms(extra)
316 ].map((oneCol, key) => ({
317 ...mapHeader(oneCol as ICell, extra, key)
318 }));