All files / src/shared/GiveExportModal/components ExportSelectComponent.tsx

95.12% Statements 39/41
88.23% Branches 45/51
86.66% Functions 13/15
95% Lines 38/40

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                                  171x                 171x 171x 171x 171x 171x 171x 171x 171x       171x     171x 5x   5x 1x     5x 5x       171x 171x 27x 2x 2x           171x                           6x 6x 6x 1x 1x     6x                                           1x 1x                 5x               1x                                                                                                         203x 8x     203x                         4x                                                   26x             1x    
import { Box, Stack } from "@mui/material";
import { PlusIcon, XIcon } from "@phosphor-icons/react";
import GiveButton from "@shared/Button/GiveButton";
import GiveSelect, { GiveSelectOption } from "@shared/GiveInputs/GiveSelect";
import { useFormContext } from "react-hook-form";
import { ContextOptions, SelectField } from "../giveExportTypes";
import { useAppTheme } from "@theme/v2/Provider";
import { useEffect, useRef, useState } from "react";
import ContextualMenu from "@shared/ContextualMenu/ContextualMenu";
import { useCustomThemeV2 } from "@theme/hooks/useCustomThemeV2";
import GiveThumbnail from "@shared/Thumbnail/GiveThumbnail";
import GiveText from "@shared/Text/GiveText";
import { isEmpty, isFunction } from "lodash";
import GiveLink from "@shared/Link/GiveLink";
import { ThumbnailType } from "@shared/Thumbnail/getIconType";
 
function ExportSelectComponent({ field }: { field: SelectField }) {
  const { setValue, watch, trigger } = useFormContext();
 
  const {
    optionsList = [],
    fetchNextPage,
    isLoading,
    clearSearch,
    searchQuery,
    setSearchQuery,
  } = field.contextMenuProps ?? {};
  const theme = useAppTheme();
  const { isMobileView } = useCustomThemeV2();
  const addButtonRef = useRef<any | null>(null);
  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);
  const selectedValue = watch(field.fieldName);
  const hasCustomList = Boolean(field.customListValuesName);
  const handleClose = () => {
    setAnchorEl(null);
  };
 
  const selectedItems: ContextOptions[] = hasCustomList
    ? watch(field.customListValuesName) || []
    : [];
  const handleMenuMultiSelectObject = (option: ContextOptions) => {
    const exists = selectedItems.some((item) => item.value === option?.value);
 
    const updated = exists
      ? selectedItems.filter((item) => item.value !== option?.value)
      : [...selectedItems, option];
 
    setValue(field.customListValuesName, updated);
    trigger();
  };
 
  // Only treat "custom" as contextual-menu-enabled if the field is configured for it.
  const isCustom = hasCustomList && selectedValue === "custom";
  useEffect(() => {
    if (isCustom && addButtonRef.current) {
      setAnchorEl(addButtonRef.current);
      setValue(field.customListValuesName, [], {
        shouldValidate: true,
      });
    }
  }, [isCustom]);
  // optionsList
  return (
    <Stack>
      <GiveSelect
        // Provide a stable `name` so the underlying input gets a predictable test id:
        // `data-testid="custom-input-${name}"`
        name={field.fieldName}
        value={selectedValue}
        useContextualMenu
        withIconOffset={false}
        contextualMenuProps={{
          color: isMobileView ? "secondary" : "tertiary",
          texture: isMobileView ? "solid" : "blurred",
        }}
        onChange={(e) => {
          const isAll = e.target.value === "all";
          setValue(field.fieldName, e.target.value);
          if (isAll && hasCustomList) {
            setValue(field.customListValuesName, []);
            setAnchorEl(null);
          }
 
          trigger();
        }}
        style={{
          marginBottom: isCustom ? "8px" : "0",
        }}
        options={field.options as GiveSelectOption[]}
      />
      {hasCustomList && !isEmpty(selectedItems) && (
        <>
          <Box
            justifyContent="space-between"
            alignItems="center"
            display="flex"
            mt="8px"
          >
            <GiveText color="secondary" fontSize="14px">
              Selected
            </GiveText>
 
            <GiveLink
              component="button"
              onClick={() => {
                setValue(field.customListValuesName, []);
                trigger();
              }}
              color="destructive"
            >
              Remove All
            </GiveLink>
          </Box>
          <Stack marginTop="8px" gap="8px">
            {selectedItems?.map((item) => {
              return (
                <Stack
                  flexDirection="row"
                  borderRadius="8px"
                  sx={{
                    cursor: "pointer",
                  }}
                  p="8px"
                  onClick={() => handleMenuMultiSelectObject(item)}
                  alignItems="center"
                  bgcolor={theme.palette.primitive?.transparent["darken-5"]}
                  justifyContent="space-between"
                  key={item.value}
                >
                  <Stack gap="8px" alignItems="center" flexDirection="row">
                    {!item.hideImage && (
                      <Image
                        ImageURL={item?.ImageURL || ""}
                        type={field.thumbType}
                      />
                    )}
                    <GiveText fontWeight={400} fontSize="12px">
                      {item.label}
                    </GiveText>
                  </Stack>
                  <XIcon />
                </Stack>
              );
            })}
          </Stack>
        </>
      )}
 
      <Box width="100%" ref={addButtonRef}>
        {isCustom && (
          <GiveButton
            size="small"
            color="light"
            variant="filled"
            sx={{
              borderRadius: "8px",
              width: "100%",
              marginTop: "8px",
            }}
            onClick={(e: React.MouseEvent<HTMLButtonElement>) => {
              setAnchorEl(e.currentTarget);
            }}
            label="Add"
            startIcon={
              <PlusIcon fill={theme.palette.text.primary} size="18px" />
            }
          />
        )}
      </Box>
 
      {hasCustomList && (
        <ContextualMenu
          anchorEl={anchorEl}
          color={isMobileView ? "primary" : "tertiary"}
          texture={isMobileView ? "solid" : "blurred"}
          options={optionsList?.map((option) => {
            const isSelected = selectedItems?.some(
              (item: any) => item?.label === option?.label,
            );
 
            return {
              description: option?.description,
              text: option?.label,
              ...(!option?.hideImage && {
                Image: (
                  <Image
                    ImageURL={option?.ImageURL || ""}
                    type={field.thumbType}
                  />
                ),
              }),
              value: option?.value,
              isSelected: isSelected,
              onClick: () => handleMenuMultiSelectObject(option),
              checkedIconType:
                (option?.checkedIcon as "Plus" | "Check") ?? "Check",
            };
          })}
          handleClose={handleClose}
          {...(isFunction(setSearchQuery) && {
            searchBarProps: {
              value: searchQuery ?? "",
              handleChange: setSearchQuery,
            },
          })}
          menuWidth={405}
          onCloseEmptyState={clearSearch}
          emptySection="empty-search"
          onEndReached={fetchNextPage}
          isLoading={isLoading}
          isMultiSelect
        />
      )}
    </Stack>
  );
}
 
export default ExportSelectComponent;
 
const Image = ({
  ImageURL,
  type = "avatar",
}: {
  ImageURL: string;
  type?: ThumbnailType;
}) => (
  <GiveThumbnail imageUrl={ImageURL} size="extra_extra_small" type={type} />
);