All files / src/shared/SearchBar GiveSearchBar.tsx

87.5% Statements 35/40
84.61% Branches 22/26
84.61% Functions 11/13
89.47% Lines 34/38

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                                                              261x                       1729x 1729x   1729x 252x 252x 252x       1729x 282x 282x       1729x 5x       1729x         10x         10x   10x 5x     1729x 5x 5x 5x       1729x           1729x 295x 3x       1729x 2x 2x 2x       1729x                       1729x                                                               261x   19799x 1729x                                                                                                              
import { XIcon, MagnifyingGlassIcon } from "@phosphor-icons/react";
import { styled, useAppTheme } from "@theme/v2/Provider";
import GiveIconButton from "shared/IconButton/GiveIconButton";
import { typography } from "@theme/v2/typography";
import { GiveInput } from "shared/GiveInputs/GiveInput";
import { SxProps } from "@mui/material";
import { useState, useCallback, useEffect } from "react";
import { debounce } from "lodash";
 
export type GiveSearchBarProps = {
  hideUI?: any;
  handleChange?: (val: string, reason: string) => void;
  value: string;
  placeholder?: string;
  iconSize?: number;
  sx?: SxProps;
  searchOnEnter?: boolean;
  disabled?: boolean;
  handleClearSearch?: () => void;
  resetOnClose?: boolean;
  onInputClick?: () => void;
  onInputBlur?: () => void;
  inputRef?: any;
  /**
   * When true, the clear (X) button is always shown — even when the field is
   * empty. Clicking it only clears the value (it keeps focus and does not
   * collapse). Used by the compact, expandable search.
   */
  alwaysShowClear?: boolean;
};
 
const GiveSearchBar: React.FC<GiveSearchBarProps> = ({
  handleChange,
  value = "",
  placeholder,
  iconSize = 24,
  searchOnEnter = false,
  resetOnClose = true,
  onInputClick,
  onInputBlur,
  alwaysShowClear,
  ...props
}) => {
  const { palette } = useAppTheme();
  const [inputValue, setInputValue] = useState(value);
 
  const handleDeleteText = () => {
    setInputValue("");
    handleChange?.("", "onChange");
    props?.handleClearSearch?.();
  };
 
  //reset on close
  useEffect(() => {
    return () => {
      resetOnClose && handleDeleteText();
    };
  }, [resetOnClose]);
 
  const debouncedChangeHandler = useCallback(
    debounce((val: string, reason: string) => handleChange?.(val, reason), 400),
    [handleChange],
  );
 
  const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    // Allow letters (including Unicode/accented), numbers, spaces, and common punctuation used in names
    // Allows: letters with diacritics, apostrophes, hyphens, periods, commas, @, +, _, and spaces
    // Built via RegExp constructor so the Unicode-property `u` flag isn't
    // validated against the (ES5) compile target while preserving runtime behavior.
    const newValue = event?.target?.value.replace(
      new RegExp("[^\\p{L}\\p{N}\\p{Zs}''\\-–—.,@+_]", "gu"),
      "",
    );
 
    setInputValue(newValue);
 
    if (searchOnEnter) return;
    debouncedChangeHandler(newValue?.trim(), "onChange");
  };
 
  const handleKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
    event.stopPropagation();
    Eif (searchOnEnter && ["Enter", "NumpadEnter"].includes(event.key)) {
      handleChange?.(inputValue, "keyDown");
    }
  };
 
  const handleOnBlur = () => {
    onInputBlur?.();
    if (inputValue) return;
    handleChange?.("", "onChange");
  };
 
  useEffect(() => {
    if (value !== inputValue) {
      setInputValue(value);
    }
  }, [value]);
 
  const handleInputClick = (event: React.MouseEvent<HTMLInputElement>) => {
    event.stopPropagation();
    event.preventDefault();
    onInputClick?.();
  };
 
  const clearButton: JSX.Element | undefined =
    inputValue || alwaysShowClear ? (
      <GiveIconButton
        size="extraSmall"
        variant="filled"
        // Keep focus on the input so clearing does not blur/collapse it.
        onMouseDown={(e) => e.preventDefault()}
        onClick={handleDeleteText}
        Icon={XIcon}
        data-testid="clear-search-button"
      />
    ) : undefined;
 
  return (
    <StyledInput
      name="searchbar"
      placeholder={placeholder || "Search"}
      onChange={handleInputChange}
      onKeyDown={handleKeyDown}
      onBlur={handleOnBlur}
      onClick={handleInputClick}
      value={inputValue}
      disabled={!handleChange}
      rightContent={clearButton}
      leftContent={
        <MagnifyingGlassIcon
          width={iconSize}
          height={iconSize}
          fill={palette.icon?.["icon-secondary"]}
        />
      }
      sx={
        alwaysShowClear
          ? {
              "& .MuiInputBase-root input:placeholder-shown ~ div": {
                display: "flex",
              },
            }
          : undefined
      }
      {...props}
    />
  );
};
 
const StyledInput = styled(GiveInput, {
  shouldForwardProp: (prop) =>
    prop !== "handleClearSearch" && prop !== "hideUI",
})(({ theme }) => ({
  border: "none",
  "& .MuiInputBase-root": {
    borderRadius: "40px !important",
    padding: "8px 16px",
    height: "40px",
    "& > svg ": {
      flexShrink: "0",
    },
    "&.Mui-focused .MuiInputAdornment-root.MuiInputAdornment-positionStart svg path":
      {
        fill: theme.palette.primitive?.blue["100"],
      },
    "&:hover:not(.Mui-focused) svg path": {
      fill: theme.palette.icon?.["icon-primary"],
    },
    "& input": {
      fontSize: typography.bodyS.fontSize,
      lineHeight: typography.bodyS.lineHeight,
      fontWeight: typography.bodyS.fontWeight,
      color: theme.palette.text.primary,
      padding: 0,
      height: "24px",
      marginLeft: 0,
    },
    "& input::-webkit-input-placeholder": {
      color: theme.palette.text.secondary,
      opacity: 1,
    },
    ":hover:not(.Mui-disabled, .Mui-error):before": {
      borderBottom: "none",
    },
    "& input:placeholder-shown ~ div": {
      display: "none",
    },
    "& .MuiOutlinedInput-notchedOutline": {
      transition: "border-color 0.2s",
      zIndex: 0,
    },
    // This was added to fix the issue when content was not visible when focused
    "&.Mui-focused": {
      zIndex: 0,
      "& input": {
        position: "relative",
        zIndex: 1,
      },
      "& .MuiInputAdornment-root": {
        position: "relative",
        zIndex: 1,
      },
    },
  },
}));
 
export default GiveSearchBar;