All files / frontend/src/components/SukohForm/fields AccordionField.tsx

60.09% Statements 125/208
49.32% Branches 73/148
62.85% Functions 22/35
59% Lines 118/200

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607                                                                                                              8x 8x 8x 8x 8x     8x 8x 8x       8x 8x         8x         8x 8x     8x 8x 8x 8x     8x     8x 8x 8x     8x     8x 4x         4x       8x 4x     6x       8x 4x 8x       8x 4x 4x                     8x 4x 2x     2x 2x   2x 2x 2x   2x 2x 2x 2x 2x 2x   2x 2x   2x 2x     2x     2x 4x 4x 4x     4x 4x           4x       2x 8x     2x             2x     2x       8x 6x   2x 2x                       8x 2x 2x 2x           8x                                           8x                         8x                     8x 2x                                                           8x 2x                   8x                   8x                   8x                             8x 9x 2x   7x       8x         8x 7x 7x       7x 18x   7x   4x             3x         3x 2x         1x           1x       1x                                                     1x     1x     8x                                                                     2x 2x     2x 2x     2x     2x         2x                 2x               2x 2x   2x                                       2x                                                                                                     2x                   2x                                        
import { useState, useEffect, useMemo, useCallback, useRef } from 'react';
import { useNavigate, useLocation } from 'react-router';
import List from '@mui/material/List';
import ListItem from '@mui/material/ListItem';
import ListItemButton from '@mui/material/ListItemButton';
import ListItemIcon from '@mui/material/ListItemIcon';
import ListItemText from '@mui/material/ListItemText';
import FolderIcon from '@mui/icons-material/Folder';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import ChevronRightIcon from '@mui/icons-material/ChevronRight';
import IconButton from '@mui/material/IconButton';
import ClearIcon from '@mui/icons-material/Clear';
import AddIcon from '@mui/icons-material/Add';
import DragHandleIcon from '@mui/icons-material/DragHandle';
import Button from '@mui/material/Button';
import CircularProgress from '@mui/material/CircularProgress';
import { Accordion, AccordionItem } from '../../Accordion';
import DangerButton from '../../DangerButton';
import { useField, useRenderFields } from '../useField';
import service from '../../../services/service';
import { isValidAppThemeConfiguration } from '../../../utils/type-guards';
import { getBasePath, parseNestPath } from '../../../utils/nestPath';
import { getSubTargetIndex } from '../../../utils/findFieldByPath';
import type { AccordionField as AccordionFieldConfig, Field, DynFormFields } from '@quiqr/types';
import Box from '@mui/material/Box';
 
// Extended field type that adds properties used by dynamic field loading
interface ExtendedField {
  lazy?: boolean;
  lazyTemp?: boolean;
  arrayTitle?: boolean;
  compositeKey?: string;
  key: string;
  type: string;
  fields?: ExtendedField[];
  [key: string]: unknown;
}
 
interface Props {
  compositeKey: string;
}
 
/**
 * AccordionField - array of objects with collapsible items.
 * Supports add, delete, reorder operations, dynamic fields, and object-based storage.
 *
 * Full feature parity with legacy AccordionDynamic including:
 * - Drag-and-drop sorting with visual feedback
 * - arrayIndicesAreKeys mode (object-based storage)
 * - Dynamic fields loading via dynFormSearchKey
 * - Accordion state persistence
 * - Disabled items visual indication
 * - Theme-aware header colors
 */
function AccordionField({ compositeKey }: Props) {
  const { field, value, setValue } = useField<Record<string, unknown>[] | Record<string, Record<string, unknown>>>(compositeKey);
  const renderFields = useRenderFields();
  const config = field as AccordionFieldConfig;
  const navigate = useNavigate();
  const location = useLocation();
 
  // Check if this accordion is being navigated to directly
  const nestPath = parseNestPath(location.pathname);
  const fieldPath = compositeKey.replace(/^root\./, '');
  const isDirectTarget = nestPath === fieldPath;
 
  // Check if nestPath targets a child item of this accordion
  // e.g., nestPath="content_blocks[0].button" when fieldPath="content_blocks"
  const subTargetIndex = getSubTargetIndex(nestPath, fieldPath);
  const isSubTarget = subTargetIndex !== null;
 
  // When the nestPath targets a specific sub-field within an accordion item
  // (e.g., "content_blocks[0].button"), extract that sub-field key ("button").
  // When null, nestPath targets the accordion item itself (e.g., "content_blocks[0]").
  const subFieldKey = (isSubTarget && nestPath && subTargetIndex !== null)
    ? nestPath.slice(`${fieldPath}[${subTargetIndex}].`.length) || null
    : null;
 
  // State for accordion expansion - auto-expand if directly navigated to or sub-targeted
  const [expandedIndex, setExpandedIndex] = useState<number | null>(isSubTarget ? subTargetIndex : null);
  const [isExpanded, setIsExpanded] = useState(isDirectTarget || isSubTarget);
 
  // State for drag and drop (state for re-rendering, refs for event handlers)
  const [dragFromIndex, setDragFromIndex] = useState<number | null>(null);
  const [dragToIndex, setDragToIndex] = useState<number | null>(null);
  const dragFromIndexRef = useRef<number | null>(null);
  const dragToIndexRef = useRef<number | null>(null);
 
  // State for theme-aware header colors
  const [headerBackgroundColor, setHeaderBackgroundColor] = useState('#efefef');
 
  // State for dynamic fields
  const [dynFields, setDynFields] = useState<Record<string, ExtendedField[]>>({});
  const [dynFieldsEmpty, setDynFieldsEmpty] = useState<ExtendedField[]>([]);
  const [shouldSaveAccordionState, setShouldSaveAccordionState] = useState(false);
 
  // Determine if we're in arrayIndicesAreKeys mode
  const arrayIndicesAreKeys = config.arrayIndicesAreKeys === true;
 
  // Normalize value based on mode
  const normalizedValue = useMemo(() => {
    Iif (arrayIndicesAreKeys) {
      return (value && typeof value === 'object' && !Array.isArray(value))
        ? value as Record<string, Record<string, unknown>>
        : {};
    }
    return Array.isArray(value) ? value : [];
  }, [value, arrayIndicesAreKeys]);
 
  // Get items as array for rendering
  const items = useMemo(() => {
    Iif (arrayIndicesAreKeys) {
      return Object.entries(normalizedValue as Record<string, Record<string, unknown>>);
    }
    return (normalizedValue as Record<string, unknown>[]).map((item, index) => [String(index), item] as [string, Record<string, unknown>]);
  }, [normalizedValue, arrayIndicesAreKeys]);
 
  // Find the field marked as arrayTitle for displaying item labels
  const arrayTitleField = useMemo(() => {
    const fields = config.fields as ExtendedField[] | undefined;
    return fields?.find((f) => f.arrayTitle === true);
  }, [config.fields]);
 
  // Load theme preferences on mount
  useEffect(() => {
    service.api.readConfKey('prefs').then((prefs) => {
      Iif (isValidAppThemeConfiguration(prefs)) {
        if (prefs.interfaceStyle === 'quiqr10-dark') {
          setHeaderBackgroundColor('#666');
        } else {
          setHeaderBackgroundColor('#efefef');
        }
      }
    });
  }, []);
 
  // Process dynamic fields when value changes
  useEffect(() => {
    if (arrayIndicesAreKeys || !config.dynFormSearchKey) {
      return;
    }
 
    const baseFields = config.fields as ExtendedField[];
    setDynFieldsEmpty(baseFields);
 
    const processItems = async () => {
      const newDynFields: Record<string, ExtendedField[]> = {};
      const itemsArray = normalizedValue as Record<string, unknown>[];
 
      for (let childIndex = 0; childIndex < itemsArray.length; childIndex++) {
        const item = itemsArray[childIndex];
        const componentKey = `item-${childIndex}`;
        const searchKey = config.dynFormSearchKey!;
        const searchVal = item[searchKey];
        const dynFormObjectRoot = config.dynFormObjectRoot ?? 'dynamics';
 
        try {
          const extraFields = await service.api.getDynFormFields(dynFormObjectRoot, { key: searchKey, val: searchVal }) as DynFormFields | string | null;
 
          Eif (extraFields && typeof extraFields === 'object' && extraFields.fields && extraFields.fields.length > 0) {
            setShouldSaveAccordionState(true);
 
            // Cast fields to ExtendedField[] for processing
            const rawFields = extraFields.fields as ExtendedField[];
 
            // Process extra fields and set composite keys
            const processedExtraFields = rawFields.map((extrField) => {
              const processed: ExtendedField = { ...extrField };
              processed.compositeKey = `${compositeKey}.${extrField.key}`;
              processed.lazy = true;
 
              // Process nested fields
              if ('fields' in processed && Array.isArray(processed.fields)) {
                processed.fields = processed.fields.map((nestedField) => ({
                  ...nestedField,
                  compositeKey: `${processed.compositeKey}.${nestedField.key}`
                }));
              }
 
              return processed;
            });
 
            // Merge with base fields, replacing any with matching keys
            const cleanedBaseFields = baseFields.filter((obj) => {
              return !processedExtraFields.find((x) => x.key === obj.key);
            });
 
            newDynFields[componentKey] = [...cleanedBaseFields, ...processedExtraFields];
          }
        } catch (error) {
          console.error('Error loading dynamic fields:', error);
        }
      }
 
      setDynFields(newDynFields);
    };
 
    processItems();
  }, [value, config.dynFormSearchKey, config.dynFormObjectRoot, config.fields, arrayIndicesAreKeys, compositeKey]);
 
  // Restore last open accordion state
  useEffect(() => {
    if (!shouldSaveAccordionState) return;
 
    service.api.getCurrentFormAccordionIndex().then((pathPlusIndex) => {
      Iif (typeof pathPlusIndex === 'string' && pathPlusIndex) {
        const arr = pathPlusIndex.split(' ');
        const index = parseInt(arr[1], 10);
 
        if (arr.length === 2 && index >= 0 && arr[0] === compositeKey) {
          setExpandedIndex(index);
        }
      }
    });
  }, [compositeKey, shouldSaveAccordionState]);
 
  // Get item label from arrayTitle field
  const getItemLabel = useCallback((item: Record<string, unknown>, index: number | string): string => {
    Eif (arrayTitleField && item[arrayTitleField.key]) {
      const label = String(item[arrayTitleField.key]);
      return label.length > 100 ? label.substring(0, 100) + '...' : label;
    }
    return arrayIndicesAreKeys ? String(index) : `Item ${Number(index) + 1}`;
  }, [arrayTitleField, arrayIndicesAreKeys]);
 
  // Handle adding a new item
  const handleAdd = useCallback(() => {
    const newItem: Record<string, unknown> = {};
 
    // Initialize with defaults from field definitions
    const fields = config.fields as Field[] | undefined;
    fields?.forEach((f) => {
      if ('default' in f && f.default !== undefined) {
        newItem[f.key] = f.default;
      }
    });
 
    if (arrayIndicesAreKeys) {
      const objValue = normalizedValue as Record<string, Record<string, unknown>>;
      const newKey = `key-${Math.random().toString(36).substring(2, 11)}`;
      setValue({ ...objValue, [newKey]: newItem });
    } else {
      const arrValue = normalizedValue as Record<string, unknown>[];
      setValue([...arrValue, newItem]);
    }
  }, [config.fields, arrayIndicesAreKeys, normalizedValue, setValue]);
 
  // Handle deleting an item
  const handleDelete = useCallback((indexOrKey: number | string) => {
    if (arrayIndicesAreKeys) {
      const objValue = { ...(normalizedValue as Record<string, Record<string, unknown>>) };
      delete objValue[String(indexOrKey)];
      setValue(objValue);
    } else {
      const arrValue = [...(normalizedValue as Record<string, unknown>[])];
      arrValue.splice(Number(indexOrKey), 1);
      setValue(arrValue);
    }
  }, [arrayIndicesAreKeys, normalizedValue, setValue]);
 
  // Handle swapping items (for drag and drop)
  const handleSwap = useCallback((fromIndex: number, toIndex: number) => {
    if (fromIndex === toIndex || arrayIndicesAreKeys) return;
 
    const arrValue = [...(normalizedValue as Record<string, unknown>[])];
    const temp = arrValue[fromIndex];
    arrValue[fromIndex] = arrValue[toIndex];
    arrValue[toIndex] = temp;
    setValue(arrValue);
  }, [arrayIndicesAreKeys, normalizedValue, setValue]);
 
  // Drag and drop handlers
  const handleDragStart = useCallback((index: number) => {
    return (e: React.MouseEvent) => {
      e.stopPropagation();
      // Update both state (for rendering) and refs (for event handler)
      setDragFromIndex(index);
      setDragToIndex(index);
      dragFromIndexRef.current = index;
      dragToIndexRef.current = index;
      setExpandedIndex(null); // Collapse during drag
 
      // Add document mouseup listener
      const mouseUpHandler = () => {
        const fromIdx = dragFromIndexRef.current;
        const toIdx = dragToIndexRef.current;
 
        if (fromIdx !== null && toIdx !== null && fromIdx !== toIdx) {
          handleSwap(fromIdx, toIdx);
        }
 
        // Clear both state and refs
        setDragFromIndex(null);
        setDragToIndex(null);
        dragFromIndexRef.current = null;
        dragToIndexRef.current = null;
        document.removeEventListener('mouseup', mouseUpHandler);
      };
 
      document.addEventListener('mouseup', mouseUpHandler);
    };
  }, [handleSwap]);
 
  const handleDragEnter = useCallback((index: number) => {
    return () => {
      if (dragFromIndexRef.current !== null) {
        // Update both state (for rendering) and ref (for event handler)
        setDragToIndex(index);
        dragToIndexRef.current = index;
      }
    };
  }, []);
 
  // Handle accordion expand/collapse change
  const handleAccordionChange = useCallback((index: number) => {
    const newIndex = expandedIndex === index ? null : index;
    setExpandedIndex(newIndex);
 
    if (shouldSaveAccordionState && newIndex !== null) {
      service.api.setCurrentFormAccordionIndex(`${compositeKey} ${newIndex}`);
    }
  }, [expandedIndex, shouldSaveAccordionState, compositeKey]);
 
  // Navigate to this accordion field (for collapsed view)
  const handleNavigateToAccordion = useCallback(() => {
    const basePath = getBasePath(location.pathname);
    // Navigate using this accordion's own full path (which preserves any ancestor
    // array indices, e.g. "content_blocks[4].logos"), mirroring NestField. Rebuilding
    // the path from the URL's current nest path would drop the parent item index and
    // produce an unresolvable path like "content_blocks.logos".
    navigate(`${basePath}/nest/${encodeURIComponent(fieldPath)}`);
  }, [location.pathname, fieldPath, navigate]);
 
  // Toggle expanded view (for expanded header - collapse back)
  const handleToggleExpand = useCallback(() => {
    // When collapsing from expanded view, navigate back
    if (isExpanded && isDirectTarget) {
      // Navigate back to parent
      const basePath = getBasePath(location.pathname);
      navigate(basePath);
    } else {
      setIsExpanded(!isExpanded);
      if (!isExpanded) {
        setExpandedIndex(null);
      }
    }
  }, [isExpanded, isDirectTarget, location.pathname, navigate]);
 
  // Get fields for a specific item (with dynamic fields support)
  const getFieldsForItem = useCallback((componentKey: string): Field[] => {
    if (dynFieldsEmpty.length > 0 && componentKey in dynFields) {
      return dynFields[componentKey] as Field[];
    }
    return (dynFieldsEmpty.length > 0 ? dynFieldsEmpty : config.fields) as Field[];
  }, [dynFields, dynFieldsEmpty, config.fields]);
 
  // Determine item count for display
  const itemCount = items.length;
 
  // Focused sub-field view: when the nestPath targets a specific sub-field of this
  // accordion item (e.g., "content_blocks[0].button"), render only that sub-field's
  // children. This is the "nest focused" state — the breadcrumb handles back navigation.
  if (isSubTarget && subFieldKey !== null) {
    const componentKey = `item-${subTargetIndex}`;
    const itemFields = getFieldsForItem(componentKey);
    // subFieldKey may be a deeper path (e.g. "logos[2].image" when the target sits inside
    // a nested accordion). The immediate child is its first segment; anything beyond it is
    // resolved recursively by the child field reading the same global nestPath.
    const childKey = subFieldKey.split(/[.[]/)[0];
    const targetField = itemFields.find((f) => f.key === childKey);
 
    if (!targetField) {
      // Dynamic fields are still loading for this item
      return (
        <Box sx={{ display: 'flex', alignItems: 'center', p: 1, gap: 1 }}>
          <CircularProgress size={16} />
        </Box>
      );
    }
 
    const itemPath = `${fieldPath}[${subTargetIndex}]`;
 
    // A nested accordion renders itself: it reads the global nestPath and either shows its
    // own item list (when it is the target) or drills further (when the path continues
    // through it). Flattening its children here would break that list/drill behaviour.
    if (targetField.type === 'accordion') {
      return <>{renderFields(itemPath, [targetField as Field])}</>;
    }
 
    // Nest/section sub-fields delegate their own rendering to the parent, so render their
    // children; those children self-resolve against the global nestPath for deeper paths.
    Iif ('fields' in targetField && Array.isArray(targetField.fields)) {
      const childPath = `${itemPath}.${childKey}`;
      return <>{renderFields(childPath, targetField.fields as Field[])}</>;
    }
 
    // Leaf sub-field — render the field itself.
    return <>{renderFields(itemPath, [targetField as Field])}</>;
  }
 
  // Collapsed view - navigate to accordion view
  Iif (!isExpanded) {
    return (
      <List style={{ marginBottom: 16, padding: 0 }}>
        <ListItem disablePadding>
          <ListItemButton
            style={{
              padding: '20px 16px',
              border: 'solid 1px #d8d8d8',
              borderRadius: '7px',
            }}
            onClick={handleNavigateToAccordion}
          >
            <ListItemIcon>
              <FolderIcon />
            </ListItemIcon>
            <ListItemText
              primary={config.title ?? config.key}
              secondary={`${itemCount} items`}
            />
            <ChevronRightIcon />
          </ListItemButton>
        </ListItem>
      </List>
    );
  }
 
  // Determine the path for child fields
  const childPath = compositeKey.replace(/^root\./, '');
 
  // Check if sorting is enabled
  const enableSort = !arrayIndicesAreKeys && config.disableSort !== true;
 
  // Expanded view - show accordion items
  return (
    <>
      <List style={{ marginBottom: 0, padding: 0 }}>
        <ListItem disablePadding>
          <ListItemButton
            style={{
              padding: '20px 16px',
              border: 'solid 1px #d8d8d8',
              borderRadius: '7px 7px 0 0',
            }}
            onClick={handleToggleExpand}
          >
            <ListItemIcon>
              <FolderIcon />
            </ListItemIcon>
            <ListItemText primary={config.title ?? config.key} />
            <ExpandMoreIcon />
          </ListItemButton>
        </ListItem>
      </List>
 
      <div
        style={{
          border: 'solid 1px #d8d8d8',
          borderTop: 'none',
          borderRadius: '0 0 7px 7px',
          padding: '16px',
          marginBottom: '16px',
        }}
      >
        <Accordion
          index={expandedIndex}
          onChange={handleAccordionChange}
        >
          {items.map(([keyOrIndex, item], index) => {
            const componentKey = `item-${keyOrIndex}`;
            const itemPath = arrayIndicesAreKeys
              ? `${childPath}.${keyOrIndex}`
              : `${childPath}[${index}]`;
            const itemData = item as Record<string, unknown>;
            const itemDisabled = itemData.disabled === true;
 
            // Get the fields for this item (may include dynamic fields)
            const itemFields = getFieldsForItem(componentKey);
 
            // Calculate head style
            let headStyle: React.CSSProperties = {
              backgroundColor: headerBackgroundColor,
            };
 
            // Style for dragging item
            Iif (index === dragFromIndex) {
              headStyle = {
                ...headStyle,
                backgroundColor: '#e2e2e2',
                opacity: 0.5,
              };
            }
 
            // Style for disabled items
            Iif (itemDisabled) {
              headStyle = {
                ...headStyle,
                color: '#cccccc',
              };
            }
 
            // Render drag indicator bar
            let beforeItem: React.ReactNode = null;
            let afterItem: React.ReactNode = null;
 
            Iif (dragFromIndex !== null && dragToIndex !== null && index === dragToIndex && dragFromIndex !== dragToIndex) {
              const indicator = (
                <div
                  style={{
                    margin: '18px 0',
                    height: '8px',
                    background: '#00bcd4',
                    borderRadius: 3,
                  }}
                />
              );
 
              if (dragFromIndex < dragToIndex) {
                afterItem = indicator;
              } else {
                beforeItem = indicator;
              }
            }
 
            const accordionItem = (
              <AccordionItem
                key={componentKey}
                label={getItemLabel(itemData, arrayIndicesAreKeys ? keyOrIndex : index)}
                headStyle={headStyle}
                bodyStyle={{ padding: '16px 16px 0px 16px' }}
                body={renderFields(itemPath, itemFields)}
                active={expandedIndex === index}
                onHeadClick={() => handleAccordionChange(index)}
                wrapperProps={{
                  onMouseEnter: handleDragEnter(index),
                }}
                headerRightItems={[
                  enableSort && (
                    <IconButton
                      key="drag"
                      size="small"
                      style={{ minWidth: 40, cursor: 'move' }}
                      onClick={(e) => e.stopPropagation()}
                      onMouseDown={handleDragStart(index)}
                      aria-label="sort"
                    >
                      <DragHandleIcon />
                    </IconButton>
                  ),
                  config.disableDelete !== true && (
                    <DangerButton
                      key="delete"
                      onClick={(e: React.MouseEvent, loaded: boolean) => {
                        e.stopPropagation();
                        if (loaded) {
                          handleDelete(arrayIndicesAreKeys ? keyOrIndex : index);
                        }
                      }}
                      loadedProps={{}}
                      loadedButton={
                        <IconButton size="small" color="secondary" aria-label="delete">
                          <ClearIcon />
                        </IconButton>
                      }
                      button={
                        <IconButton size="small" aria-label="delete">
                          <ClearIcon />
                        </IconButton>
                      }
                    />
                  ),
                ].filter(Boolean)}
              />
            );
 
            // If we need to show drag indicators, wrap in Fragment
            Iif (beforeItem || afterItem) {
              return (
                <Box key={componentKey}>
                  {beforeItem}
                  {accordionItem}
                  {afterItem}
                </Box>
              );
            }
 
            return accordionItem;
          })}
        </Accordion>
 
        {config.disableCreate !== true && (
          <Button
            style={{ marginTop: 10 }}
            endIcon={<AddIcon />}
            variant="contained"
            onClick={handleAdd}
          >
            Add
          </Button>
        )}
      </div>
    </>
  );
}
 
export default AccordionField;