Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

4.8 KB
Raw Blame
"use client";

import { LoadingSpinner, useRouterStuff } from "@dub/ui";
import { CircleXmark, Magnifier } from "@dub/ui/icons";
import { cn } from "@dub/utils";
import {
  forwardRef,
  useCallback,
  useEffect,
  useImperativeHandle,
  useRef,
  useState,
} from "react";
import { useDebouncedCallback } from "use-debounce";

type SearchBoxProps = {
  value: string;
  loading?: boolean;
  showClearButton?: boolean;
  onChange: (value: string) => void;
  onChangeDebounced?: (value: string) => void;
  debounceTimeoutMs?: number;
  inputClassName?: string;
  placeholder?: string;
};

export const SearchBox = forwardRef(
  (
    {
      value,
      loading,
      showClearButton = true,
      onChange,
      onChangeDebounced,
      debounceTimeoutMs = 500,
      inputClassName,
      placeholder,
    }: SearchBoxProps,
    forwardedRef,
  ) => {
    const inputRef = useRef<HTMLInputElement>(null);
    useImperativeHandle(forwardedRef, () => inputRef.current);

    const debounced = useDebouncedCallback(
      (value) => onChangeDebounced?.(value),
      debounceTimeoutMs,
    );

    const onKeyDown = useCallback((e: KeyboardEvent) => {
      const target = e.target as HTMLElement;
      // only focus on filter input when:
      // - user is not typing in an input or textarea
      // - there is no existing modal backdrop (i.e. no other modal is open)
      if (
        e.key === "/" &&
        target.tagName !== "INPUT" &&
        target.tagName !== "TEXTAREA"
      ) {
        e.preventDefault();
        inputRef.current?.focus();
      } else if (e.key === "Escape") {
        inputRef.current?.blur();
      }
    }, []);

    useEffect(() => {
      document.addEventListener("keydown", onKeyDown);
      return () => document.removeEventListener("keydown", onKeyDown);
    }, [onKeyDown]);

    return (
      <div className="relative">
        <div className="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-4">
          {loading && value.length > 0 ? (
            <LoadingSpinner className="h-4 w-4" />
          ) : (
            <Magnifier className="h-4 w-4 text-neutral-400" />
          )}
        </div>
        <input
          ref={inputRef}
          type="text"
          className={cn(
            "peer w-full rounded-lg border border-neutral-200 px-10 text-black outline-none placeholder:text-neutral-400 sm:text-sm",
            "transition-all focus:border-neutral-500 focus:ring-4 focus:ring-neutral-200",
            inputClassName,
          )}
          placeholder={placeholder || "Search..."}
          value={value}
          onChange={(e) => {
            onChange(e.target.value);
            debounced(e.target.value);
          }}
          autoCapitalize="none"
        />
        {showClearButton && value.length > 0 && (
          <button
            onClick={() => {
              // Or a pending keystroke lands after this and restores the term.
              debounced.cancel();
              onChange("");
              onChangeDebounced?.("");
            }}
            className="pointer-events-auto absolute inset-y-0 right-0 flex items-center pr-4"
          >
            <CircleXmark className="h-4 w-4 text-neutral-600" />
          </button>
        )}
      </div>
    );
  },
);

export function SearchBoxPersisted({
  urlParam = "search",
  resetParamsOnChange = [],
  onChange,
  onChangeDebounced,
  ...props
}: {
  urlParam?: string;
  /** Params to clear whenever the search changes, e.g. a stale sort. */
  resetParamsOnChange?: string[];
} & Partial<SearchBoxProps>) {
  const { queryParams, searchParams } = useRouterStuff();

  const [value, setValue] = useState(searchParams.get(urlParam) ?? "");
  const [debouncedValue, setDebouncedValue] = useState(value);

  // Set URL param when debounced value changes
  useEffect(() => {
    // Parens matter: `!==` binds tighter than `??`, so without them this reads
    // `get() ?? ("" !== debouncedValue)` and never skips.
    if ((searchParams.get(urlParam) ?? "") !== debouncedValue)
      queryParams(
        debouncedValue === ""
          ? { del: [urlParam, "page", ...resetParamsOnChange] }
          : {
              set: { [urlParam]: debouncedValue },
              del: ["page", ...resetParamsOnChange],
            },
      );
  }, [debouncedValue]);

  // Set value when URL param changes
  useEffect(() => {
    const search = searchParams.get(urlParam);
    // Only update if the value and debouncedValue are synced (the user isn't actively typing)
    // Same precedence trap.
    if ((search ?? "") !== value && value === debouncedValue)
      setValue(search ?? "");
  }, [searchParams.get(urlParam)]);

  return (
    <SearchBox
      value={value}
      onChange={(value) => {
        setValue(value);
        onChange?.(value);
      }}
      onChangeDebounced={(value) => {
        setDebouncedValue(value);
        onChangeDebounced?.(value);
      }}
      {...props}
    />
  );
}