Debian Codegraph @

install/freeipa-webui/src/pages/DNSZones/DnsResourceRecords.tsx

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