All files / src/components/SearchBar SearchBar.tsx

0% Statements 0/33
0% Branches 0/38
0% Functions 0/7
0% Lines 0/33

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                                                                                                                                                                                                                                                                                                                                                                                                                               
import { SearchIcon } from "@chakra-ui/icons";
import {
  Input,
  InputGroup,
  InputLeftElement,
  InputProps,
  InputRightElement,
  useDisclosure,
  Button,
  IconButton,
} from "@chakra-ui/react";
import {
  useContext,
  createContext,
  FunctionComponent,
  useEffect,
  useRef,
  ChangeEventHandler,
  FormEventHandler,
} from "react";
import testIds from "./testIds";
import { useAnalytics } from "../../contexts/Analytics";
import { clickEvent, eventName } from "../../contexts/Analytics/util";
import { useCatalogSearch } from "../../hooks/useCatalogSearch";
import { useSearch } from "../../hooks/useSearch";
import { Form } from "../Form";
 
export interface SearchBarProps
  extends Omit<InputProps, "onChange" | "value" | "onSubmit"> {
  "data-event"?: string;
  defaultQuery?: string;
  hasButton?: boolean;
  value?: string;
  onChange?: ChangeEventHandler<HTMLInputElement>;
  onSubmit?: FormEventHandler<HTMLFormElement>;
}
 
const SearchBarState = createContext<
  { dataEvent?: string; query: string; isOpen: boolean } | undefined
>(undefined);
 
export const useSearchBarState = () => {
  const state = useContext(SearchBarState);
 
  if (!state) {
    throw new Error("This component must be a child of a <SearchBar />");
  }
 
  return state;
};
 
/**
 * Exposes a Search component that provides a default search implementation. This behavior can be overridden by defining `value`, `onChange`, and `onSubmit` props.
 * Additionally, it's behavior can be extended with `<SearchOverlay />` and `<SearchSuggestions />`
 * ```tsx
 * // Minimal use-case
 * import { SearchBar } from "components/SearchBar";
 * <SearchBar />
 *
 * // With extended behavior
 * import { SearchBar, SearchOverlay, SearchSuggestions } from "components/SearchBar";
 *
 * <SearchBar>
 *   <SearchOverlay />
 *   <SearchSuggestions />
 * </SearchBar>
 * ```
 */
export const SearchBar: FunctionComponent<SearchBarProps> = ({
  children,
  "data-event": dataEvent,
  hasButton,
  onSubmit,
  value,
  onChange,
  ...inputProps
}) => {
  const disclosure = useDisclosure();
  const inputRef = useRef<HTMLInputElement | null>(null);
  const searchAPI = useCatalogSearch();
  const catalog = useSearch();
  const { trackCustomEvent } = useAnalytics();
 
  const roundedCatalogLength = Math.floor((catalog.length ?? 0) / 100) * 100;
 
  const placeholder = `Search ${
    roundedCatalogLength > 0 ? `${roundedCatalogLength}+ ` : ""
  }construct libraries`;
 
  useEffect(() => {
    // Handle closing disclosures when user clicks outside of input.
    // We cannot rely on the input's onBlur due to left & right elements (icon / button) triggering it
    const clickListener = (e: MouseEvent) => {
      if (!inputRef.current || !e.target) {
        return;
      }
 
      if (!inputRef.current.contains(e.target as Node)) {
        disclosure.onClose();
      }
    };
 
    // Closes disclosures when Esc key is pressed
    const kbdListener = (e: KeyboardEvent) => {
      if (e.key === "Escape") {
        inputRef.current?.blur?.();
        disclosure.onClose();
      }
    };
 
    window.addEventListener("keyup", kbdListener);
    window.addEventListener("click", clickListener);
 
    return () => {
      window.removeEventListener("keyup", kbdListener);
      window.removeEventListener("click", clickListener);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
 
  return (
    <SearchBarState.Provider
      value={{
        dataEvent,
        query: value ?? searchAPI.query,
        isOpen: disclosure.isOpen,
      }}
    >
      <Form
        color="initial"
        onSubmit={onSubmit ?? searchAPI.onSubmit}
        pos="relative"
      >
        <InputGroup pos="relative" zIndex={disclosure.isOpen ? 3 : "initial"}>
          {hasButton && (
            <InputLeftElement>
              <SearchIcon
                color="textTertiary"
                data-testid={testIds.searchIcon}
              />
            </InputLeftElement>
          )}
 
          <Input
            _placeholder={{ color: "textTertiary" }}
            bg="bgSecondary"
            boxShadow={disclosure.isOpen ? "base" : "none"}
            color="textSecondary"
            data-testid={testIds.input}
            focusBorderColor="brand.500"
            onChange={onChange ?? searchAPI.onQueryChange}
            onFocus={() => {
              disclosure.onOpen();
 
              if (dataEvent) {
                trackCustomEvent(
                  clickEvent({ name: eventName(dataEvent, "Input") })
                );
              }
            }}
            placeholder={placeholder}
            pr={hasButton ? { base: "none", md: "9rem" } : undefined}
            ref={inputRef}
            value={value ?? searchAPI.query}
            {...inputProps}
          />
 
          {hasButton ? (
            <InputRightElement
              display={{ base: "none", md: "initial" }}
              w="auto"
            >
              <Button
                borderLeftRadius="0"
                colorScheme="brand"
                data-event={
                  dataEvent ? eventName(dataEvent, "Submit Button") : undefined
                }
                data-testid={testIds.searchButton}
                fontSize="0.875rem"
                type="submit"
                w="9rem"
              >
                Find constructs
              </Button>
            </InputRightElement>
          ) : (
            <InputRightElement>
              <IconButton
                aria-label="Run search"
                data-event={
                  dataEvent ? eventName(dataEvent, "Submit Icon") : undefined
                }
                data-testid={testIds.searchIcon}
                icon={<SearchIcon />}
                type="submit"
                variant="ghost"
              ></IconButton>
            </InputRightElement>
          )}
        </InputGroup>
 
        {children}
      </Form>
    </SearchBarState.Provider>
  );
};