61 lines · 1.7 KB
import { useNavigate } from "@tanstack/react-router";
import { useId } from "react";
import { inputClass } from "~/ui/Field";
import { Icon } from "~/ui/Icon";
import { cn } from "~/utils/cn";

const SIZES = {
  sm: { input: "h-8 pl-8 text-xs", icon: "left-2.5 size-3.5" },
  lg: { input: "h-12 pl-11 text-base", icon: "left-4 size-4.5" },
} as const;

type Props = {
  size?: keyof typeof SIZES;
  defaultValue?: string;
  placeholder?: string;
  autoFocus?: boolean;
  className?: string;
};

/** Global search box; submits to `/search?q=`. */
export function SearchForm({
  size = "sm",
  defaultValue,
  placeholder = "Search repositories, issues and code…",
  autoFocus,
  className,
}: Props) {
  const navigate = useNavigate();
  const id = useId();
  const sizing = SIZES[size];
  return (
    <search className={cn("relative block", className)}>
      <form
        onSubmit={(event) => {
          event.preventDefault();
          const q = new FormData(event.currentTarget).get("q");
          void navigate({ to: "/search", search: { q: typeof q === "string" ? q : "" } });
        }}
      >
        <label htmlFor={id} className="sr-only">