Debian Codegraph @

install/freeipa-webui/src/pages/IdPReferences/IdpReferences.tsx

raw
1 import React from "react";
2 // PatternFly
3 import {
4 Flex,
5 FlexItem,
6 PageSection,
7 PaginationVariant,
8 ToolbarItemVariant,
9 } from "@patternfly/react-core";
10 import {
11 InnerScrollContainer,
12 OuterScrollContainer,
13 } from "@patternfly/react-table";
14 // Data types
15 import { IDPServer } from "src/utils/datatypes/globalDataTypes";
16 // Hooks
17 import { addAlert } from "src/store/Global/alerts-slice";
18 import useUpdateRoute from "src/hooks/useUpdateRoute";
19 import useListPageSearchParams from "src/hooks/useListPageSearchParams";
20 import useApiError from "src/hooks/useApiError";
21 // Redux
22 import { useAppDispatch, useAppSelector } from "src/store/hooks";
23 // RPC
24 import {
25 useGetIdpEntriesQuery,
26 useSearchIdpEntriesMutation,
27 } from "src/services/rpcIdp";
28 // Utils
29 import { isIdpServerSelectable } from "src/utils/utils";
30 // Components
31 import { FetchBaseQueryError } from "@reduxjs/toolkit/query";
32 import { SerializedError } from "@reduxjs/toolkit";
33 import ToolbarLayout, {
34 ToolbarItem,
35 } from "src/components/layouts/ToolbarLayout";
36 import SearchInputLayout from "src/components/layouts/SearchInputLayout";
37 import SecondaryButton from "src/components/layouts/SecondaryButton";
38 import HelpTextWithIconLayout from "src/components/layouts/HelpTextWithIconLayout";
39 import PaginationLayout from "src/components/layouts/PaginationLayout";
40 import TitleLayout from "src/components/layouts/TitleLayout";
41 import GlobalErrors from "src/components/errors/GlobalErrors";
42 import MainTable from "src/components/tables/MainTable";
43 import BulkSelectorPrep from "src/components/BulkSelectorPrep";
44 // Modals
45 import AddModal from "src/components/modals/IdpReferences/AddModal";
46 import DeleteModal from "src/components/modals/IdpReferences/DeleteModal";
47
48 const IdpReferences = () => {
49 const dispatch = useAppDispatch();
50
51 // Update current route data to Redux and highlight the current page in the Nav bar
52 const { browserTitle } = useUpdateRoute({
53 pathname: "identity-provider-references",
54 });
55
56 // Set the page title to be shown in the browser tab
57 React.useEffect(() => {
58 document.title = browserTitle;
59 }, [browserTitle]);
60
61 // Retrieve API version from environment data
62 const apiVersion = useAppSelector(
63 (state) => state.global.environment.api_version
64 ) as string;
65
66 // URL parameters: page number, page size, search value
67 const { page, setPage, perPage, setPerPage, searchValue, setSearchValue } =
68 useListPageSearchParams();
69
70 // Handle API calls errors
71 const globalErrors = useApiError([]);
72
73 // Page indexes
74 const firstUserIdx = (page - 1) * perPage;
75 const lastUserIdx = page * perPage;
76
77 // States
78 const [idpReferences, setIdpReferences] = React.useState<IDPServer[]>([]);
79 const [isSearchDisabled, setIsSearchDisabled] =
80 React.useState<boolean>(false);
81 const [totalCount, setTotalCount] = React.useState<number>(0);
82
83 // API calls
84 const idpsResponse = useGetIdpEntriesQuery({
85 searchValue: searchValue,
86 apiVersion,
87 sizelimit: 100,
88 startIdx: firstUserIdx,
89 stopIdx: lastUserIdx,
90 });
91
92 const { data, isLoading, error } = idpsResponse;
93
94 // Handle data when the API call is finished
95 React.useEffect(() => {
96 if (idpsResponse.isFetching) {
97 setShowTableRows(false);
98 // Reset selected elements on refresh
99 setTotalCount(0);
100 globalErrors.clear();
101 return;
102 }
103
104 // API response: Success
105 if (idpsResponse.isSuccess && idpsResponse.data && data !== undefined) {
106 const listResult = data.result.results;
107 const totalCount = data.result.totalCount;
108 const listSize = data.result.count;
109 const elementsList: IDPServer[] = [];
110
111 for (let i = 0; i < listSize; i++) {
112 elementsList.push(listResult[i].result);
113 }
114
115 setTotalCount(totalCount);
116 // Update the list of elements
117 setIdpReferences(elementsList);
118 // Show table elements
119 setShowTableRows(true);
120 }
121
122 // API response: Error
123 if (
124 !idpsResponse.isLoading &&
125 idpsResponse.isError &&
126 idpsResponse.error !== undefined
127 ) {
128 // This normally happens when the user is not authorized to view the data
129 // So instead of adding an error, refresh page
130 window.location.reload();
131 }
132 }, [idpsResponse]);
133
134 // Selected elements
135 const [selectedElements, setSelectedElements] = React.useState<IDPServer[]>(
136 []
137 );
138 const [selectedPerPage, setSelectedPerPage] = React.useState<number>(0);
139
140 const clearSelectedElements = () => {
141 const emptyList: IDPServer[] = [];
142 setSelectedElements(emptyList);
143 };
144
145 // Refresh button handling
146 const refreshData = () => {
147 // Hide table
148 setShowTableRows(false);
149
150 // Reset selected elements on refresh
151 setTotalCount(0);
152
153 idpsResponse.refetch().then(() => {
154 setShowTableRows(true);
155 });
156 };
157
158 // 'Delete' button state
159 const [isDeleteButtonDisabled, setIsDeleteButtonDisabled] =
160 React.useState<boolean>(true);
161
162 const [isDeletion, setIsDeletion] = React.useState(false);
163
164 // Table-related shared functionality
165 // - Selectable checkboxes on table
166 const selectableIdpRefsTable = idpReferences.filter(isIdpServerSelectable); // elements per Table
167
168 const updateSelectedIdpRefs = (idpRef: IDPServer[], isSelected: boolean) => {
169 let newSelectedIdpRefs: IDPServer[] = [];
170 if (isSelected) {
171 newSelectedIdpRefs = JSON.parse(JSON.stringify(selectedElements));
172 for (let i = 0; i < idpRef.length; i++) {
173 if (
174 selectedElements.find(
175 (selectedIdpRef) => selectedIdpRef.cn[0] === idpRef[i].cn[0]
176 )
177 ) {
178 // Already in the list
179 continue;
180 }
181 // Add element to list
182 newSelectedIdpRefs.push(idpRef[i]);
183 }
184 } else {
185 // Remove element
186 for (let i = 0; i < selectedElements.length; i++) {
187 let found = false;
188 for (let ii = 0; ii < idpRef.length; ii++) {
189 if (selectedElements[i].cn[0] === idpRef[ii].cn[0]) {
190 found = true;
191 break;
192 }
193 }
194 if (!found) {
195 // Keep this valid selected entry
196 newSelectedIdpRefs.push(selectedElements[i]);
197 }
198 }
199 }
200 setSelectedElements(newSelectedIdpRefs);
201 setIsDeleteButtonDisabled(newSelectedIdpRefs.length === 0);
202 };
203
204 // - Helper method to set the selected entries from the table
205 const setIdpRefsSelected = (idpRef: IDPServer, isSelecting = true) => {
206 if (isIdpServerSelectable(idpRef)) {
207 updateSelectedIdpRefs([idpRef], isSelecting);
208 }
209 };
210
211 // Always refetch data when the component is loaded.
212 // This ensures the data is always up-to-date.
213 React.useEffect(() => {
214 idpsResponse.refetch();
215 }, []);
216
217 // Show table rows
218 const [showTableRows, setShowTableRows] = React.useState(!isLoading);
219
220 // Show table rows only when data is fully retrieved
221 React.useEffect(() => {
222 if (showTableRows !== !isLoading) {
223 setShowTableRows(!isLoading);
224 }
225 }, [isLoading]);
226
227 // Search API call
228 const [searchEntry] = useSearchIdpEntriesMutation();
229
230 const submitSearchValue = () => {
231 searchEntry({
232 searchValue: searchValue,
233 apiVersion,
234 sizelimit: 100,
235 startIdx: 0,
236 stopIdx: 200, // Search will consider a max. of elements
237 }).then((result) => {
238 if ("data" in result) {
239 const searchError = result.data?.error as
240 | FetchBaseQueryError
241 | SerializedError;
242
243 if (searchError) {
244 // Error
245 let error: string | undefined = "";
246 if ("error" in searchError) {
247 error = searchError.error;
248 } else if ("message" in searchError) {
249 error = searchError.message;
250 }
251 dispatch(
252 addAlert({
253 name: "submit-search-value-error",
254 title: error || "Error when searching for IdPs",
255 variant: "danger",
256 })
257 );
258 } else {
259 // Success
260 const listResult = result.data?.result.results || [];
261 const listSize = result.data?.result.count || 0;
262 const totalCount = result.data?.result.totalCount || 0;
263 const elementsList: IDPServer[] = [];
264
265 for (let i = 0; i < listSize; i++) {
266 elementsList.push(listResult[i].result);
267 }
268
269 setTotalCount(totalCount);
270 setIdpReferences(elementsList);
271 setShowTableRows(true);
272 }
273 setIsSearchDisabled(false);
274 }
275 });
276 };
277
278 // Data wrappers
279 // TODO: Better separation of concerts
280 // - 'PaginationLayout'
281 const paginationData = {
282 page,
283 perPage,
284 updatePage: setPage,
285 updatePerPage: setPerPage,
286 updateSelectedPerPage: setSelectedPerPage,
287 updateShownElementsList: setIdpReferences,
288 totalCount,
289 };
290
291 // SearchInputLayout
292 const searchValueData = {
293 searchValue,
294 updateSearchValue: setSearchValue,
295 submitSearchValue,
296 };
297
298 // - 'BulkSelectorrep'
299 const bulkSelectorData = {
300 selected: selectedElements,
301 updateSelected: updateSelectedIdpRefs,
302 selectableTable: selectableIdpRefsTable,
303 nameAttr: "cn",
304 };
305
306 const selectedPerPageData = {
307 selectedPerPage,
308 updateSelectedPerPage: setSelectedPerPage,
309 };
310
311 // Modals functionality
312 const [showAddModal, setShowAddModal] = React.useState(false);
313 const [showDeleteModal, setShowDeleteModal] = React.useState(false);
314
315 const onOpenAddModal = () => {
316 setShowAddModal(true);
317 };
318
319 const onCloseAddModal = () => {
320 setShowAddModal(false);
321 };
322
323 const onOpenDeleteModal = () => {
324 setShowDeleteModal(true);
325 };
326
327 const onCloseDeleteModal = () => {
328 setShowDeleteModal(false);
329 };
330
331 // List of Toolbar items
332 const toolbarItems: ToolbarItem[] = [
333 {
334 key: 0,
335 element: (
336 <BulkSelectorPrep
337 list={idpReferences}
338 shownElementsList={idpReferences}
339 elementData={bulkSelectorData}
340 buttonsData={{
341 updateIsDeleteButtonDisabled: setIsDeleteButtonDisabled,
342 }}
343 selectedPerPageData={selectedPerPageData}
344 />
345 ),
346 },
347 {
348 key: 1,
349 element: (
350 <SearchInputLayout
351 dataCy="search"
352 name="search"
353 ariaLabel="Search subIds"
354 placeholder="Search"
355 searchValueData={searchValueData}
356 isDisabled={isSearchDisabled}
357 />
358 ),
359 toolbarItemVariant: ToolbarItemVariant.label,
360 toolbarItemGap: { default: "gapMd" },
361 },
362 {
363 key: 2,
364 toolbarItemVariant: ToolbarItemVariant.separator,
365 },
366 {
367 key: 3,
368 element: (
369 <SecondaryButton
370 dataCy="idp-references-button-refresh"
371 onClickHandler={refreshData}
372 isDisabled={!showTableRows}
373 >
374 Refresh
375 </SecondaryButton>
376 ),
377 },
378 {
379 key: 4,
380 element: (
381 <SecondaryButton
382 dataCy="idp-references-button-delete"
383 isDisabled={isDeleteButtonDisabled || !showTableRows}
384 onClickHandler={onOpenDeleteModal}
385 >
386 Delete
387 </SecondaryButton>
388 ),
389 },
390 {
391 key: 5,
392 element: (
393 <SecondaryButton
394 dataCy="idp-references-button-add"
395 isDisabled={!showTableRows}
396 onClickHandler={onOpenAddModal}
397 >
398 Add
399 </SecondaryButton>
400 ),
401 },
402 {
403 key: 6,
404 toolbarItemVariant: ToolbarItemVariant.separator,
405 },
406 {
407 key: 7,
408 element: <HelpTextWithIconLayout textContent="Help" />,
409 },
410 {
411 key: 8,
412 element: (
413 <PaginationLayout
414 list={idpReferences}
415 paginationData={paginationData}
416 widgetId="pagination-options-menu-top"
417 isCompact={true}
418 />
419 ),
420 toolbarItemAlignment: { default: "alignEnd" },
421 },
422 ];
423
424 // Render component
425 return (
426 <div>
427 <PageSection hasBodyWrapper={false}>
428 <TitleLayout
429 id="Identity Provider references page"
430 headingLevel="h1"
431 text="Identity Provider references"
432 />
433 </PageSection>
434 <PageSection hasBodyWrapper={false} isFilled={false}>
435 <Flex direction={{ default: "column" }}>
436 <FlexItem>
437 <ToolbarLayout toolbarItems={toolbarItems} />
438 </FlexItem>
439 <FlexItem style={{ flex: "0 0 auto" }}>
440 <OuterScrollContainer>
441 <InnerScrollContainer
442 style={{ height: "60vh", overflow: "auto" }}
443 >
444 {error !== undefined && error ? (
445 <GlobalErrors errors={globalErrors.getAll()} />
446 ) : (
447 <MainTable
448 tableTitle="Identity Provider references table"
449 shownElementsList={idpReferences}
450 pk="cn"
451 keyNames={["cn", "ipaidpclientid", "ipaidpscope"]}
452 columnNames={[
453 "Identity Provider reference name",
454 "Client identifier",
455 "Scope",
456 ]}
457 hasCheckboxes={true}
458 pathname="identity-provider-references"
459 showTableRows={showTableRows}
460 showLink={true}
461 elementsData={{
462 isElementSelectable: isIdpServerSelectable,
463 selectedElements,
464 selectableElementsTable: selectableIdpRefsTable,
465 setElementsSelected: setIdpRefsSelected,
466 clearSelectedElements,
467 }}
468 buttonsData={{
469 updateIsDeleteButtonDisabled: (value) =>
470 setIsDeleteButtonDisabled(value),
471 isDeletion,
472 updateIsDeletion: (value) => setIsDeletion(value),
473 }}
474 paginationData={{
475 selectedPerPage,
476 updateSelectedPerPage: setSelectedPerPage,
477 }}
478 />
479 )}
480 </InnerScrollContainer>
481 </OuterScrollContainer>
482 </FlexItem>
483 <FlexItem style={{ flex: "0 0 auto", position: "sticky", bottom: 0 }}>
484 <PaginationLayout
485 list={idpReferences}
486 paginationData={paginationData}
487 variant={PaginationVariant.bottom}
488 widgetId="pagination-options-menu-bottom"
489 />
490 </FlexItem>
491 </Flex>
492 </PageSection>
493 <AddModal
494 isOpen={showAddModal}
495 onCloseModal={onCloseAddModal}
496 onRefresh={refreshData}
497 title="Add Identity Provider reference"
498 />
499 <DeleteModal
500 show={showDeleteModal}
501 onClose={onCloseDeleteModal}
502 selectedData={{
503 selectedElements,
504 clearSelectedElements,
505 }}
506 buttonsData={{
507 updateIsDeleteButtonDisabled: setIsDeleteButtonDisabled,
508 updateIsDeletion: setIsDeletion,
509 }}
510 columnNames={[
511 "Identity Provider reference name",
512 "Client identifier",
513 "Scope",
514 ]}
515 keyNames={["cn", "ipaidpclientid", "ipaidpscope"]}
516 onRefresh={refreshData}
517 />
518 </div>
519 );
520 };
521
522 export default IdpReferences;