All files / src/components/HeaderSearch HeaderSearch.tsx

0% Statements 0/37
0% Branches 0/34
0% Functions 0/9
0% Lines 0/37

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                                                                                                                                                                                                                                                                                     
'use client';
 
import { useQuery } from '@apollo/client/react';
import {
  Combobox,
  Group,
  Loader,
  Text,
  TextInput,
  useCombobox,
} from '@mantine/core';
import { useDebouncedValue } from '@mantine/hooks';
import { IconSearch } from '@tabler/icons-react';
import type { Route } from 'next';
import { useRouter } from 'next/navigation';
import { useTranslations } from 'next-intl';
import { useEffect, useState } from 'react';
import { GET_LATEST_RECIPES } from '@/lib/graphql/queries';
import type { RecipeBase } from '@/types/recipe';
 
export const HeaderSearch = () => {
  const t = useTranslations('headerSearch');
  const router = useRouter();
  const [searchQuery, setSearchQuery] = useState('');
  const [debouncedSearch] = useDebouncedValue(searchQuery, 800);
  const combobox = useCombobox({
    onDropdownClose: () => combobox.resetSelectedOption(),
  });
  const [isFocused, setIsFocused] = useState(false);
 
  const shouldSearch = debouncedSearch.length >= 4;
 
  const { data, loading } = useQuery<{
    getRecipes?: { recipes: RecipeBase[] };
  }>(GET_LATEST_RECIPES, {
    variables: {
      limit: 5,
      filter: { title: debouncedSearch },
    },
    skip: !shouldSearch,
  });
 
  useEffect(() => {
    if (!shouldSearch) {
      combobox.closeDropdown();
    } else if (isFocused && loading) {
      combobox.openDropdown();
    }
  }, [shouldSearch, loading, isFocused, combobox]);
 
  const recipes = data?.getRecipes?.recipes || [];
  const hasNoResults = shouldSearch && !loading && recipes.length === 0;
 
  const options = recipes.map((recipe: RecipeBase) => (
    <Combobox.Option value={recipe.slug || recipe.id} key={recipe.id}>
      <Group>
        <Text size="sm">{recipe.title}</Text>
      </Group>
    </Combobox.Option>
  ));
 
  return (
    <Combobox
      onOptionSubmit={(optionValue) => {
        setSearchQuery('');
        combobox.closeDropdown();
        router.push(`/recipes/${optionValue}` as Route);
      }}
      store={combobox}
      withinPortal={true}
      transitionProps={{
        transition: 'fade',
        duration: 200,
        timingFunction: 'ease',
      }}
    >
      <Combobox.Target>
        <TextInput
          placeholder={t('placeholder')}
          value={searchQuery}
          onChange={(event) => {
            setSearchQuery(event.currentTarget.value);
            combobox.resetSelectedOption();
            if (event.currentTarget.value.length < 4) {
              combobox.closeDropdown();
            } else if (recipes.length > 0) {
              combobox.openDropdown();
            }
          }}
          onClick={() => {
            if (shouldSearch && recipes.length > 0) {
              combobox.openDropdown();
            }
          }}
          onFocus={() => {
            setIsFocused(true);
            if (shouldSearch && recipes.length > 0) {
              combobox.openDropdown();
            }
          }}
          onBlur={() => {
            setIsFocused(false);
            combobox.closeDropdown();
          }}
          rightSection={
            loading ? <Loader size={18} /> : <IconSearch size={18} />
          }
          radius="xl"
          size="sm"
          w={{ base: 200, md: 300, lg: 400 }}
          display={{ base: 'none', sm: 'block' }}
        />
      </Combobox.Target>
 
      <Combobox.Dropdown display={{ base: 'none', sm: 'block' }}>
        <Combobox.Options>
          {loading && (
            <Combobox.Empty>
              <Text size="sm" c="dimmed">
                {t('searching')}
              </Text>
            </Combobox.Empty>
          )}
 
          {!loading && options.length > 0 && options}
 
          {hasNoResults && (
            <Combobox.Empty>
              <Text size="sm" c="dimmed">
                {t('noResults')}
              </Text>
            </Combobox.Empty>
          )}
        </Combobox.Options>
      </Combobox.Dropdown>
    </Combobox>
  );
};