All files / src/components/common/SearchBar SearchBar.tsx

89.79% Statements 44/49
81.13% Branches 43/53
100% Functions 15/15
91.48% Lines 43/47

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                                                                                              85x                                         45x 45x   45x 2x 1x               1x             1x       45x 11x 9x 9x   2x   45x   13x 9x         45x 13x   13x 13x 13x       45x   18x     18x 18x       45x 1x 1x     45x 1x 1x         1x 1x 1x       45x   45x                                                               7x 7x 7x           4x                               85x   625x 45x                                                                                  
import React, { memo, useEffect } from "react";
import { Box, SxProps, styled } from "@mui/material";
import Input, { InputProps } from "@mui/material/Input";
import { StyledIconButton } from "@common/IconButton";
import { CloseIcon, SearchIcon } from "@assets/rebrandIcons";
import { palette } from "@palette";
import { useAppDispatch } from "@redux/hooks";
import { updateSearchQuery } from "@redux/slices/fundraisers";
import { ActionCreatorWithPayload } from "@reduxjs/toolkit";
import {
  resetSearchQueryByKey,
  setSearchQueryByKey,
} from "@redux/slices/search";
import _ from "lodash";
 
type SearchBarProps = {
  onSubmit?: () => void;
  productType?: string;
  category?: string;
  formSx?: SxProps & {iconStroke?: string};
  subCategory?: string;
  customId?: string | number;
  sortBy?: string;
  otherParams?: Record<string, any>;
  onBlur?:
    | React.FocusEventHandler<HTMLTextAreaElement | HTMLInputElement>
    | undefined;
  handleChange?: (value: string) => void;
  stateAction?: ActionCreatorWithPayload<string, any>;
  queryKey?: string;
  transparent?: boolean;
  collapse?: () => void;
  IOCsetQueryString?:
    | React.Dispatch<React.SetStateAction<string>>
    | ((value: string) => void);
  IOCqueryString?: string;
  clearOnUnmount?: boolean;
  isExpandedByDefault?: boolean;
  initialValue?: string;
  inputSx?: SxProps;
  isDebounceSearch?: boolean;
  searchOnEnter?: boolean;
  customDeleteIcon?: React.ReactElement;
  customPlaceholder?: string;
  iconStroke?: string
};
 
const SearchBar: React.FC<SearchBarProps & InputProps> = ({
  formSx,
  onBlur,
  stateAction,
  handleChange,
  queryKey,
  transparent,
  collapse,
  IOCsetQueryString,
  IOCqueryString,
  clearOnUnmount = true,
  isExpandedByDefault,
  initialValue,
  inputSx,
  isDebounceSearch = false,
  searchOnEnter = false,
  customDeleteIcon,
  customPlaceholder,
  iconStroke,
  ...props
}) => {
  const [queryString, setQueryString] = React.useState<string>("");
  const dispatch = useAppDispatch();
 
  const searchQueryDispatcher = (value: string) => {
    if (queryKey) {
      dispatch(
        setSearchQueryByKey({
          queryKey,
          params: {
            value,
          },
        }),
      );
    } else Iif (stateAction) {
      // if we have a particular state for the search query
      dispatch(stateAction(value));
    } else {
      // else we store the search query in the default state
      // (in the future we need to change the default state.
      // now it's in the fundraiser state should be in more generic state)
      dispatch(updateSearchQuery(value));
    }
  };
 
  const startSearch = (searchValue: string) => {
    if (handleChange) {
      handleChange(searchValue);
      return;
    }
    searchQueryDispatcher(searchValue);
  };
  const debounceSearch = React.useMemo(
    () =>
      _.debounce((searchValue: string) => {
        startSearch(searchValue);
      }, 500),
    [],
  );
 
  useEffect(() => {
    Iif (initialValue) setQueryString(initialValue);
 
    return () => {
      if (clearOnUnmount && queryKey) dispatch(resetSearchQueryByKey(queryKey));
      isDebounceSearch && debounceSearch.cancel(); // Cancel the debounce function if the component is unmounting
    };
  }, [isDebounceSearch]);
 
  useEffect(() => {
    // Call the debounce function whenever queryString changes
    isDebounceSearch && debounceSearch(IOCqueryString ?? queryString);
 
    // Make sure to cancel the debounce on cleanup
    return () => {
      isDebounceSearch && debounceSearch.cancel();
    };
  }, [queryString, IOCqueryString, isDebounceSearch]);
 
  const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    startSearch(IOCqueryString ?? queryString);
  };
 
  const handleDeleteText = () => {
    if (IOCsetQueryString) {
      IOCsetQueryString("");
    } else E{
      setQueryString("");
    }
 
    startSearch("");
    Eif (collapse) {
      collapse();
    }
  };
 
  const showEraseIcon = !!IOCqueryString || !!queryString;
 
  return (
    <Box component="form" onSubmit={handleSubmit} sx={formSx}>
      <StyledInput
        transparent={transparent}
        placeholder={customPlaceholder || "Search..."}
        disableUnderline
        sx={inputSx}
        isExpandedByDefault={isExpandedByDefault}
        endAdornment={
          showEraseIcon ? (
            <StyledIconButton
              onClick={handleDeleteText}
              sx={{
                maxHeight: "18px",
                maxWidth: "18px",
              }}
              data-testid="search-input-clear-button"
            >
              {customDeleteIcon ? (
                customDeleteIcon
              ) : (
                <CloseIcon width={18} height={18} color={palette.gray[300]} />
              )}
            </StyledIconButton>
          ) : (
            <Box width={18} height={18} />
          )
        }
        startAdornment={
          <SearchIcon width={24} height={24} stroke={formSx?.iconStroke || palette.gray[200]} />
        }
        onChange={(e) => {
          const v = e.target.value.replace(/[!()]+/g, "");
          if (IOCsetQueryString) {
            IOCsetQueryString(v);
          } else E{
            setQueryString(v);
          }
        }}
        onKeyDown={(e) => {
          Iif (searchOnEnter && ["Enter", "NumpadEnter"].includes(e.code))
            handleSubmit(e as any);
        }}
        value={IOCqueryString ?? queryString}
        onBlur={onBlur}
        {...props}
      />
    </Box>
  );
};
 
type StyledInputProps = {
  transparent?: boolean;
  isExpandedByDefault?: boolean;
};
 
const StyledInput = styled(Input, {
  shouldForwardProp: (prop) =>
    prop !== "transparent" && prop !== "isExpandedByDefault",
})<StyledInputProps>(({ theme, transparent, isExpandedByDefault }) => ({
  background: transparent ? "transparent" : palette.common.white,
  border: `1px solid ${palette.neutral[10]}`,
  borderRadius: "90px",
  width: isExpandedByDefault ? "100%" : "350px",
  padding: "4px 12px",
  height: "32px",
 
  "& input": {
    fontSize: "14px",
    lineHeight: "16.8px",
    fontWeight: 350,
    color: palette.black[300],
    padding: 0,
    height: "24px",
  },
  "& input::-webkit-input-placeholder": {
    color: palette.gray[100],
  },
  "& input:placeholder-shown ~ div": {
    display: "none",
  },
  "&:has(input:focus)": {
    boxSizing: "border-box",
    outline: `none`,
  },
  "&:has(.Mui-disabled)": {
    background: palette.neutral[10],
    border: "none",
    outline: "none",
  },
  [theme.breakpoints.down("sm")]: {
    width: "100%",
    "& input": {
      fontSize: "16px",
      lineHeight: "19.2px",
    },
  },
}));
 
export default memo(SearchBar);