Debian Codegraph @

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