All files / store/components/SearchInput SearchInput.tsx

100% Statements 14/14
80% Branches 8/10
100% Functions 3/3
100% Lines 14/14

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                  1x       32x   32x 2x 2x 2x 2x 2x   2x 2x           32x 1x 1x     32x                                              
import { Button } from "@canonical/react-components";
import { ReactNode, RefObject } from "react";
import { useSearchParams } from "react-router-dom";
 
type Props = {
  searchRef: RefObject<HTMLInputElement>;
  searchSummaryRef?: RefObject<HTMLDivElement>;
};
 
export const SearchInput = ({
  searchRef,
  searchSummaryRef,
}: Props): ReactNode => {
  const [searchParams, setSearchParams] = useSearchParams();
 
  const onSubmit = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    Eif (searchRef?.current && searchRef.current.value) {
      searchParams.delete("page");
      searchParams.set("q", searchRef.current.value);
      setSearchParams(searchParams);
    }
    Eif (searchSummaryRef && searchSummaryRef.current) {
      searchSummaryRef.current.scrollIntoView({
        behavior: "smooth",
      });
    }
  };
 
  const onReset = () => {
    searchParams.delete("q");
    setSearchParams(searchParams);
  };
 
  return (
    <form className="p-search-box" onSubmit={onSubmit}>
      <label className="u-off-screen" htmlFor="search">
        Search Snapcraft
      </label>
      <input
        type="search"
        id="search"
        className="p-search-box__input"
        name="q"
        placeholder="Search Snapcraft"
        defaultValue={searchParams.get("q") || ""}
        ref={searchRef}
      />
      <Button type="reset" className="p-search-box__reset" onClick={onReset}>
        <i className="p-icon--close">Close</i>
      </Button>
      <Button type="submit" className="p-search-box__button">
        <i className="p-icon--search">Search</i>
      </Button>
    </form>
  );
};