Debian Codegraph @

pkg/lib/cockpit-components-dynamic-list.tsx

raw
1 // SPDX-License-Identifier: LGPL-2.1-or-later
2 import React from 'react';
3 import cockpit from "cockpit";
4 import { Button } from "@patternfly/react-core/dist/esm/components/Button";
5 import { EmptyState, EmptyStateBody } from "@patternfly/react-core/dist/esm/components/EmptyState";
6 import { FormFieldGroup, FormFieldGroupHeader } from "@patternfly/react-core/dist/esm/components/Form";
7 import { HelperText, HelperTextItem } from "@patternfly/react-core/dist/esm/components/HelperText";
8
9 import './cockpit-components-dynamic-list.scss';
10
11 type ValidationError = Record<string, string>;
12
13 interface DynamicListItem {
14 key: number;
15 [field: string]: string | number | null;
16 }
17
18 interface DynamicListFormProps {
19 emptyStateString: string;
20 onChange: (list: (DynamicListItem | undefined)[]) => void;
21 id: string;
22 itemcomponent: React.ComponentType<{
23 idx: number;
24 item: DynamicListItem;
25 id: string;
26 onChange: (idx: number, field: string, value: string | null) => void;
27 removeitem: (idx: number) => void;
28 additem: () => void;
29 options?: Record<string, unknown> | undefined;
30 validationFailed?: ValidationError | undefined;
31 onValidationChange?: ((value: ValidationError) => void) | undefined;
32 }>;
33 label: string;
34 actionLabel: string;
35 default?: Record<string, string | number | null>;
36 formclass?: string;
37 options?: Record<string, unknown>;
38 /*
39 * An array where each item represents a validation error of the corresponding row component index.
40 * A row is strictly mapped to an item of the array by its index.
41 * Example: Let's have a dynamic form, where each row consists of 2 fields: name and email. Then a validation array of
42 * these rows would look like this:
43 * [
44 * { name: "Name must not be empty }, // first row
45 * { }, // second row
46 * { name: "Name cannot contain a number", email: "Email must contain '@'" } // third row
47 * ]
48 */
49 validationFailed?: (ValidationError | undefined)[];
50 /*
51 * Handler function which updates the parent's component's validation object.
52 * Its parameter is an array the same structure as 'validationFailed'.
53 */
54 onValidationChange?: (validation: (ValidationError | undefined)[]) => void;
55 helperText?: string;
56 }
57
58 interface DynamicListFormState {
59 list: (DynamicListItem | undefined)[];
60 }
61
62 // Dynamic list with a variable number of rows. Each row is a custom component, usually an input field(s).
63 export class DynamicListForm extends React.Component<DynamicListFormProps, DynamicListFormState> {
64 keyCounter: number;
65
66 constructor(props: DynamicListFormProps) {
67 super(props);
68 this.state = {
69 list: [],
70 };
71 this.keyCounter = 0;
72 this.removeItem = this.removeItem.bind(this);
73 this.addItem = this.addItem.bind(this);
74 this.onItemChange = this.onItemChange.bind(this);
75 }
76
77 removeItem(idx: number) {
78 const validationFailedDelta = this.props.validationFailed ? [...this.props.validationFailed] : [];
79 // We also need to remove any error messages which the item (row) may have contained
80 delete validationFailedDelta[idx];
81 this.props.onValidationChange?.(validationFailedDelta);
82
83 this.setState(state => {
84 const items = [...state.list];
85 // keep the list structure, otherwise all the indexes shift and the ID/key mapping gets broken
86 delete items[idx];
87
88 return { list: items };
89 }, () => this.props.onChange(this.state.list));
90 }
91
92 addItem() {
93 this.setState(state => {
94 return { list: [...state.list, { key: this.keyCounter++, ...this.props.default }] };
95 }, () => this.props.onChange(this.state.list));
96 }
97
98 onItemChange(idx: number, field: string, value: string | null) {
99 this.setState(state => {
100 const items = [...state.list];
101 const item = items[idx];
102 cockpit.assert(item, "item at index does not exist");
103 item[field] = value || null;
104 return { list: items };
105 }, () => this.props.onChange(this.state.list));
106 }
107
108 render () {
109 const { id, label, actionLabel, formclass, emptyStateString, helperText, validationFailed, onValidationChange } = this.props;
110 const dialogValues = this.state;
111 return (
112 <FormFieldGroup header={
113 <FormFieldGroupHeader
114 titleText={{ text: label, id: id + "-title" }}
115 actions={<Button variant="secondary" className="btn-add" onClick={this.addItem}>{actionLabel}</Button>}
116 />
117 } className={"dynamic-form-group " + formclass}>
118 {
119 dialogValues.list.some(item => item !== undefined)
120 ? <>
121 {dialogValues.list.map((item, idx) => {
122 if (item === undefined)
123 return null;
124
125 return React.createElement(this.props.itemcomponent, {
126 idx,
127 item,
128 id: id + "-" + idx,
129 key: idx,
130 onChange: this.onItemChange,
131 removeitem: this.removeItem,
132 additem: this.addItem,
133 options: this.props.options,
134 validationFailed: validationFailed && validationFailed[idx],
135 onValidationChange: (value: ValidationError) => {
136 // Dynamic list consists of multiple rows. Therefore validationFailed object is presented as an array where each item represents a row
137 // Each row/item then consists of key-value pairs, which represent a field name and it's validation error
138 const delta = validationFailed ? [...validationFailed] : [];
139 // Update validation of only a single row
140 delta[idx] = value;
141
142 // If a row doesn't contain any fields with errors anymore, we delete the item of the array
143 // Deleting an item of an array replaces an item with an "empty item".
144 // This guarantees that an array of validation errors maps to the correct rows
145 if (Object.keys(delta[idx]).length == 0)
146 delete delta[idx];
147
148 onValidationChange?.(delta);
149 },
150 });
151 })
152 }
153 {helperText &&
154 <HelperText>
155 <HelperTextItem>{helperText}</HelperTextItem>
156 </HelperText>
157 }
158 </>
159 : <EmptyState>
160 <EmptyStateBody>
161 {emptyStateString}
162 </EmptyStateBody>
163 </EmptyState>
164 }
165 </FormFieldGroup>
166 );
167 }
168 }