Debian Codegraph @

install/freeipa-webui/src/components/layouts/DualListLayout/DualListLayout.tsx

raw
1 import React, { ReactNode, useState } from "react";
2 // PatternFly
3 import {
4 Flex,
5 FlexItem,
6 Button,
7 FormGroup,
8 TextInput,
9 DualListSelectorPane,
10 DualListSelectorList,
11 DualListSelectorListItem,
12 DualListSelectorControlsWrapper,
13 DualListSelectorControl,
14 DualListSelector,
15 } from "@patternfly/react-core";
16 // Layout
17 import SecondaryButton from "src/components/layouts/SecondaryButton";
18 import ModalWithFormLayout from "src/components/layouts/ModalWithFormLayout";
19 import SearchInputLayout from "src/components/layouts/SearchInputLayout";
20 //Icons
21 import {
22 AngleRightIcon,
23 AngleDoubleRightIcon,
24 AngleDoubleLeftIcon,
25 AngleLeftIcon,
26 InfoCircleIcon,
27 ExclamationTriangleIcon,
28 ArrowRightIcon,
29 } from "@patternfly/react-icons";
30 // RPC client
31 import { useGetIDListMutation, GenericPayload } from "src/services/rpc";
32
33 export type DualListTarget =
34 | "user"
35 | "group"
36 | "host"
37 | "hostgroup"
38 | "netgroup"
39 | "hbacsvc"
40 | "hbacsvcgroup"
41 | "sudorule"
42 | "sudocmd"
43 | "sudocmdgroup";
44
45 export interface DualListProps {
46 entry: string;
47 target: DualListTarget;
48 showModal: boolean;
49 onCloseModal: () => void;
50 onOpenModal: () => void;
51 spinning: boolean;
52 title: string;
53 addBtnName: string;
54 addSpinningBtnName: string;
55 action: (items: string[]) => void;
56 tableElementsList: string[];
57 availableOptions?: string[];
58 addExternalsOption?: boolean;
59 }
60
61 const searchItem = (onClick?: () => void) => {
62 return (
63 <DualListSelectorListItem
64 key={"search"}
65 data-cy={"item-search"}
66 onClick={onClick}
67 /* Omitting this will throw an error when selected */
68 onOptionSelect={() => {}}
69 >
70 <div key="initial-list" data-cy="dual-list-search-link">
71 <InfoCircleIcon className="pf-v6-u-info-color-100 pf-v6-u-mr-sm" />{" "}
72 Click here, or use the search field to find entries
73 </div>
74 </DualListSelectorListItem>
75 );
76 };
77
78 const searchingItem = () => {
79 return (
80 <DualListSelectorListItem
81 key={"searching"}
82 data-cy={"item-searching"}
83 /* Omitting this will throw an error when selected */
84 onOptionSelect={() => {}}
85 >
86 <div>
87 <InfoCircleIcon className="pf-v6-u-info-color-100 pf-v6-u-mr-sm" />{" "}
88 Searching ...
89 </div>
90 </DualListSelectorListItem>
91 );
92 };
93
94 const emptyItem = () => {
95 return (
96 <DualListSelectorListItem
97 key={"empty"}
98 data-cy={"item-empty"}
99 /* Omitting this will throw an error when selected */
100 onOptionSelect={() => {}}
101 >
102 <div id="disabled" data-cy="dual-list-no-matching-results">
103 <ExclamationTriangleIcon className="pf-v6-u-warning-color-100 pf-v6-u-mr-sm" />{" "}
104 No matching results
105 </div>
106 </DualListSelectorListItem>
107 );
108 };
109
110 type Status = "toSearch" | "searching" | "empty" | "valid";
111
112 interface Item {
113 id: string;
114 item: string;
115 isSelected: boolean;
116 dataCy: string;
117 }
118
119 const asItems = (options: string[]): Item[] =>
120 options.map((option) => ({
121 id: option,
122 item: option,
123 isSelected: false,
124 dataCy: `item-${option}`,
125 }));
126
127 // Dual list layout for updating an existing table, or for performing actions
128 // against entries
129 const DualListTableLayoutInner = (props: DualListProps) => {
130 const [availableOptions, setAvailableOptions] = useState<Item[]>(
131 asItems(props.availableOptions ?? [])
132 );
133 const [chosenOptions, setChosenOptions] = useState<Item[]>([]);
134 const [searchValue, setSearchValue] = React.useState("");
135 const [searchDisabled, setSearchIsDisabled] = useState<boolean>(false);
136 const [status, setStatus] = useState<Status>(
137 props.availableOptions !== undefined ? "valid" : "toSearch"
138 );
139
140 const updateAvailableOptions = (newList: string[]) => {
141 const filterData = newList.filter((item) => {
142 if (item === props.entry) {
143 return false;
144 }
145 return !props.tableElementsList.includes(item);
146 });
147
148 // Filter out options that have already been chosen
149 const cleanList = filterData.filter((item) => {
150 return !chosenOptions.some((itm) => {
151 return item === itm.item || item === props.entry;
152 });
153 });
154
155 if (cleanList.length === 0) {
156 setStatus("empty");
157 } else {
158 setAvailableOptions(asItems(cleanList));
159 setStatus("valid");
160 }
161 };
162
163 // Issue a search using a specific search value
164 const [retrieveIDs] = useGetIDListMutation({});
165 const submitSearchValue = () => {
166 setSearchIsDisabled(true);
167 if (props.availableOptions === undefined) {
168 retrieveIDs({
169 searchValue: props.availableOptions || searchValue,
170 sizeLimit: 200,
171 startIdx: 0,
172 stopIdx: 200,
173 entryType: props.target,
174 } as GenericPayload).then((result) => {
175 if (result && "data" in result) {
176 if (result.data && result.data.list) {
177 updateAvailableOptions(result.data.list);
178 } else {
179 updateAvailableOptions([]);
180 }
181 } else {
182 updateAvailableOptions([]);
183 }
184 setSearchIsDisabled(false);
185 });
186 } else {
187 updateAvailableOptions(props.availableOptions);
188 setSearchIsDisabled(false);
189 }
190 };
191
192 function doSearch() {
193 setStatus("searching");
194 submitSearchValue();
195 }
196
197 const searchValueData = {
198 searchValue: searchValue,
199 updateSearchValue: setSearchValue,
200 submitSearchValue: doSearch,
201 };
202
203 const onButtonClick = () => {
204 props.action(
205 chosenOptions
206 .map((item) => item.item)
207 .filter((item) => item !== null && item !== undefined)
208 );
209 props.onCloseModal();
210 };
211
212 const onOptionSelect = (
213 _event: React.MouseEvent | React.ChangeEvent | React.KeyboardEvent,
214 index: number,
215 isChosen: boolean
216 ) => {
217 if (isChosen) {
218 const newChosen = [...chosenOptions];
219 newChosen[index].isSelected = !chosenOptions[index].isSelected;
220 setChosenOptions(newChosen);
221 } else {
222 const newAvailable = [...availableOptions];
223 newAvailable[index].isSelected = !availableOptions[index].isSelected;
224 setAvailableOptions(newAvailable);
225 }
226 };
227
228 // Buttons that will be shown at the end of the form
229 const modalActions = [
230 <SecondaryButton
231 dataCy="modal-button-add"
232 key={"dual-list-" + props.target}
233 isDisabled={chosenOptions.length === 0 || props.spinning}
234 form="modal-form"
235 onClickHandler={onButtonClick}
236 spinnerAriaValueText={props.addSpinningBtnName}
237 spinnerAriaLabel={props.addSpinningBtnName}
238 isLoading={props.spinning}
239 >
240 {props.spinning ? props.addSpinningBtnName : props.addBtnName}
241 </SecondaryButton>,
242 <Button
243 data-cy="modal-button-cancel"
244 key={"cancel-new-" + props.target}
245 variant="link"
246 onClick={props.onCloseModal}
247 >
248 Cancel
249 </Button>,
250 ];
251
252 const moveSelected = (fromAvailable: boolean) => {
253 const sourceOptions = fromAvailable ? availableOptions : chosenOptions;
254 const destinationOptions = fromAvailable ? chosenOptions : availableOptions;
255 for (let i = 0; i < sourceOptions.length; i++) {
256 const option = sourceOptions[i];
257 if (option.isSelected) {
258 sourceOptions.splice(i, 1);
259 destinationOptions.push(option);
260 option.isSelected = false;
261 i--;
262 }
263 }
264
265 if (fromAvailable) {
266 setAvailableOptions([...sourceOptions]);
267 setChosenOptions([...destinationOptions]);
268 } else {
269 setChosenOptions([...sourceOptions]);
270 setAvailableOptions([...destinationOptions]);
271 }
272
273 setStatus("valid");
274 };
275
276 const moveAll = (fromAvailable: boolean) => {
277 availableOptions.forEach((option) => {
278 option.isSelected = false;
279 });
280 chosenOptions.forEach((option) => {
281 option.isSelected = false;
282 });
283
284 if (fromAvailable) {
285 setChosenOptions([...availableOptions, ...chosenOptions]);
286 setAvailableOptions([]);
287 } else {
288 setAvailableOptions([...chosenOptions, ...availableOptions]);
289 setChosenOptions([]);
290 }
291
292 setStatus("valid");
293 };
294
295 const getListItems = (status: Status): ReactNode[] => {
296 switch (status) {
297 case "toSearch":
298 return [searchItem(doSearch)];
299 case "searching":
300 return [searchingItem()];
301 case "empty":
302 return [emptyItem()];
303 case "valid":
304 return availableOptions.map((option, index) => (
305 <DualListSelectorListItem
306 key={option.id}
307 onOptionSelect={(e) => onOptionSelect(e, index, false)}
308 isSelected={option.isSelected}
309 data-cy={option.dataCy}
310 >
311 {option.item}
312 </DualListSelectorListItem>
313 ));
314 }
315 };
316
317 const getChosenOptionsStatus = (): string => {
318 const selectedOptions = chosenOptions.filter((option) => option.isSelected);
319 return `${selectedOptions.length} of ${chosenOptions.length} options selected`;
320 };
321
322 const getAvailableOptionsStatus = (): string => {
323 if (status === "valid") {
324 const selectedOptions = availableOptions.filter(
325 (option) => option.isSelected
326 );
327 return `${selectedOptions.length} of ${availableOptions.length} options selected`;
328 }
329 return "";
330 };
331
332 const fields = [
333 {
334 id: "dual-list-search",
335 pfComponent: (
336 <SearchInputLayout
337 dataCy="modal-search"
338 name="search"
339 ariaLabel="Search dual select list"
340 placeholder="Search for entries"
341 searchValueData={searchValueData}
342 isDisabled={searchDisabled}
343 />
344 ),
345 },
346 {
347 id: "dual-list-selector",
348 pfComponent: (
349 <DualListSelector data-cy="dual-list-selector">
350 <DualListSelectorPane
351 status={getAvailableOptionsStatus()}
352 data-cy="dual-list-left"
353 >
354 <DualListSelectorList>{getListItems(status)}</DualListSelectorList>
355 </DualListSelectorPane>
356 <DualListSelectorControlsWrapper>
357 <DualListSelectorControl
358 isDisabled={!availableOptions.some((option) => option.isSelected)}
359 onClick={() => moveSelected(true)}
360 aria-label="Add selected"
361 data-cy="dual-list-add-selected"
362 >
363 <AngleRightIcon />
364 </DualListSelectorControl>
365 <DualListSelectorControl
366 isDisabled={availableOptions.length === 0}
367 onClick={() => moveAll(true)}
368 aria-label="Add all"
369 data-cy="dual-list-add-all"
370 >
371 <AngleDoubleRightIcon />
372 </DualListSelectorControl>
373 <DualListSelectorControl
374 isDisabled={chosenOptions.length === 0}
375 onClick={() => moveAll(false)}
376 aria-label="Remove all"
377 data-cy="dual-list-remove-all"
378 >
379 <AngleDoubleLeftIcon />
380 </DualListSelectorControl>
381 <DualListSelectorControl
382 isDisabled={!chosenOptions.some((option) => option.isSelected)}
383 onClick={() => moveSelected(false)}
384 aria-label="Remove selected"
385 data-cy="dual-list-remove-selected"
386 >
387 <AngleLeftIcon />
388 </DualListSelectorControl>
389 </DualListSelectorControlsWrapper>
390 <DualListSelectorPane
391 isChosen
392 status={getChosenOptionsStatus()}
393 data-cy="dual-list-right"
394 >
395 <DualListSelectorList>
396 {chosenOptions.map((option, index) => (
397 <DualListSelectorListItem
398 key={option.id}
399 onOptionSelect={(e) => onOptionSelect(e, index, true)}
400 isSelected={option.isSelected}
401 data-cy={option.dataCy}
402 >
403 {option.item}
404 </DualListSelectorListItem>
405 ))}
406 </DualListSelectorList>
407 </DualListSelectorPane>
408 </DualListSelector>
409 ),
410 },
411 ];
412
413 if (props.addExternalsOption) {
414 const [externalValue, setExternalValue] = React.useState("");
415
416 const onAddExternalValue = () => {
417 setChosenOptions([...chosenOptions, ...asItems([externalValue])]);
418 setExternalValue("");
419 };
420
421 fields.push({
422 id: "form-externals",
423 pfComponent: (
424 <FormGroup
425 label="External"
426 fieldId="dual-list-external"
427 style={{ width: "45%" }}
428 >
429 <Flex>
430 <FlexItem>
431 <TextInput
432 data-cy="modal-textbox-external"
433 type="text"
434 id="dual-list-external"
435 name="dual-list-external"
436 aria-label="dual list external"
437 value={externalValue}
438 onChange={(_event, value) => setExternalValue(value)}
439 />
440 </FlexItem>
441 <FlexItem>
442 <Button
443 data-cy="modal-button-external-add"
444 title="Add external item to the chosen list"
445 size="sm"
446 variant="secondary"
447 icon={<ArrowRightIcon />}
448 iconPosition="right"
449 onClick={onAddExternalValue}
450 isDisabled={externalValue === ""}
451 >
452 Add
453 </Button>
454 </FlexItem>
455 </Flex>
456 </FormGroup>
457 ),
458 });
459 }
460
461 // Render component
462 return (
463 <ModalWithFormLayout
464 dataCy="dual-list-modal"
465 variantType="medium"
466 modalPosition="top"
467 title={props.title}
468 formId={"dual-list-" + props.target + "-modal"}
469 fields={fields}
470 show={props.showModal}
471 onClose={props.onCloseModal}
472 actions={modalActions}
473 />
474 );
475 };
476
477 const DualListTableLayout = (props: DualListProps) => {
478 if (!props.showModal) return null;
479 return <DualListTableLayoutInner {...props} />;
480 };
481
482 export default DualListTableLayout;