All files / src/components DrawerSearchPanel.tsx

93.96% Statements 187/199
86.66% Branches 26/30
100% Functions 9/9
93.96% Lines 187/199

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 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 2721x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x   1x                                                                 1x 1x     1x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x   10x 10x 10x 10x 10x 10x 10x   10x 10x 10x   10x 10x 10x 10x 10x 10x 30x 30x 30x 10x     10x 10x 10x 10x 10x 10x 10x 10x 10x 1x 1x 10x         10x 10x 10x 10x   10x 1x 1x 1x 1x         1x   10x 3x 3x 2x 2x 2x 2x 2x 2x 2x 2x 3x           2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 3x   10x 2x 2x 2x 2x   10x 10x 10x 10x 1x 1x 1x 1x 1x 1x 1x 1x 1x   10x 10x 10x 10x 10x   10x 10x 10x 10x 10x 10x 10x         10x 10x 10x 10x 10x 10x 10x 1x 1x 1x 1x 1x 1x 1x             10x 10x   10x 10x 10x 10x 10x 10x 10x 10x 10x       10x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x   20x 20x   10x 10x 10x 10x 10x 10x 10x   10x   10x 10x 10x 10x 10x 10x   10x         10x   1x  
import TableColumns from '@/components/SearchPanel/TableColumns';
import { CACHE, DRAWER_INDEX, PANEL } from '@/constants/common';
import { useAppContext } from '@/context';
import { i18n, useLocale } from '@/helpers/i18n';
import { countActiveSearchFilters } from '@/helpers/searchFilters';
import { cstorage } from '@/utils/storage';
import ClearFiltersIcon from '@mui/icons-material/FilterAltOff';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import SearchIcon from '@mui/icons-material/Search';
import { Accordion, Box, Button, TextField, Typography } from '@mui/material';
import { FC, KeyboardEvent, SyntheticEvent, useEffect, useMemo } from 'react';
import ColumnDrawerSection from './ColumnDrawerSection';
import styles from './DrawerSearchPanel.module.scss';
import { StyledAccordionDetails, StyledAccordionSummary } from './StyledComponents';
import { Logger } from '@/utils/Logger';
import { getErrorMessage } from '@/helpers/exceptions';
 
const logger = new Logger('DrawerSearchPanel');
 
/**
 * Pre-search filter drawer. Renders the product-name field, then walks
 * `TableColumns()` in column-config order and emits one accordion section
 * per column with a `meta.drawer` payload (via `ColumnDrawerSection`). The
 * non-column "Results Limit" section is injected just before the `price`
 * entry to preserve its historical position.
 *
 * Adding, removing, or reordering a drawer-backed column in TableColumns.tsx
 * is reflected here automatically — no edits to this file are required.
 * @param props - Component props.
 * - `expandedAccordion` - Currently open accordion's panel id
 *   (e.g. `"search-country"`), or `false`.
 * - `onAccordionChange` - Factory from panelId to MUI Accordion's
 *   `onChange` handler.
 * @returns The search drawer body (title input, filter accordions, submit).
 * @example
 * ```tsx
 * const [expanded, setExpanded] = useState<string | false>(false);
 * const handleChange = (panel: string) => (_e: SyntheticEvent, isOpen: boolean) =>
 *   setExpanded(isOpen ? panel : false);
 *
 * <DrawerSearchPanel expandedAccordion={expanded} onAccordionChange={handleChange} />
 * // Renders (with current TableColumns config):
 * //   [Product name or keyword]
 * //   ▸ Supplier (0 selected)
 * //   ▸ Country (0 selected)
 * //   ▸ Shipping Type
 * //   ▸ Availability
 * //   ▸ Results Limit (15 per supplier)   ← non-column, injected before Price
 * //   ▸ Price Range
 * //   [Search]
 * ```
 * @source
 */
const DrawerSearchPanel: FC<{
  expandedAccordion: string | false;
  onAccordionChange: (panel: string) => (event: SyntheticEvent, isExpanded: boolean) => void;
}> = ({ expandedAccordion, onAccordionChange }) => {
  const {
    userSettings,
    setUserSettings,
    setDrawerTab,
    setPendingSearchQuery,
    searchFilters,
    setSearchFilters,
    selectedSuppliers,
    setSelectedSuppliers,
    setPanel,
  } = useAppContext();
 
  // How many advanced filters are set to a non-default value; gates the
  // "Clear all filters" button below.
  const activeFilterCount = countActiveSearchFilters({
    selectedSuppliers,
    searchFilters,
    userSettings,
  });
 
  // Re-render (and rebuild the memoized drawer configs below) when the UI
  // language changes, so the translated column/drawer labels update live.
  const locale = useLocale();
 
  // Collect columns that declared a drawer section in their meta, preserving
  // the order they appear in TableColumns(). The drawer configs carry i18n'd
  // labels, so recompute them when the locale changes.
  const drawerColumns = useMemo(
    () =>
      TableColumns().flatMap((column) => {
        const drawer = column.meta?.drawer;
        return drawer && column.id ? [{ id: column.id, drawer }] : [];
      }),
    [locale],
  );
 
  // Hydrate the title query field from the shared live search input value so
  // the drawer shows whatever the user last typed in any search input, even
  // if it hasn't been submitted yet.
  useEffect(() => {
    const loadSearchInput = async () => {
      try {
        const data = await cstorage.session.get([CACHE.SEARCH_INPUT]);
        const stored = data[CACHE.SEARCH_INPUT];
        if (typeof stored === 'string' && stored !== searchFilters.titleQuery) {
          setSearchFilters({ ...searchFilters, titleQuery: stored });
        }
      } catch (error) {
        logger.warn(`Failed to load search input from session storage: ${getErrorMessage(error)}`, {
          error,
        });
      }
    };
    loadSearchInput();
    // Run once on mount; we intentionally don't depend on searchFilters to avoid loops.
  }, []);
 
  const handleTitleQueryChange = async (value: string) => {
    setSearchFilters({ ...searchFilters, titleQuery: value });
    try {
      await cstorage.session.set({ [CACHE.SEARCH_INPUT]: value });
    } catch (error) {
      logger.warn(`Failed to persist search input to session storage: ${getErrorMessage(error)}`, {
        error,
      });
    }
  };
 
  const handleSearch = async (): Promise<void> => {
    const query = searchFilters.titleQuery.trim();
    if (!query) return;
    // Clear the live in-progress draft in session storage now that the query
    // has been promoted to a real search. We intentionally do NOT write
    // CACHE.QUERY or CACHE.SEARCH_IS_NEW_SEARCH here: those are consumed by
    // useSearch's mount effect, which would fire a duplicate performSearch in
    // parallel with the pendingSearchQuery path below. HistoryPanel.handleReSearch
    // follows the same single-path pattern.
    try {
      await cstorage.session.set({ [CACHE.SEARCH_INPUT]: '' });
    } catch (error) {
      logger.warn(
        `Failed to clear search input draft in session storage: ${getErrorMessage(error)}`,
        { error },
      );
    }
    // Clear the drawer's visible field to match the cleared draft so re-opening
    // the drawer doesn't show stale text from the just-submitted query.
    setSearchFilters({ ...searchFilters, titleQuery: '' });
    // Stage the query for ResultsTable's pendingSearchQuery effect to consume.
    // This works whether SearchPanel is already mounted (effect re-fires on the
    // context update) or is about to mount (fresh mount reads pendingSearchQuery
    // from context on first render).
    setPendingSearchQuery(query);
    setDrawerTab(DRAWER_INDEX.CLOSED);
    // Switch to the results panel so SearchPanel / ResultsTable mount if the
    // user triggered the search from the home panel. When already on RESULTS,
    // this is a harmless no-op.
    setPanel?.(PANEL.RESULTS);
  };
 
  const handleKeyDown = (e: KeyboardEvent) => {
    if (e.key === 'Enter') {
      void handleSearch();
    }
  };
 
  // Reset every advanced filter to its default, matching the set counted by
  // countActiveSearchFilters (including the supplier-exclusion checkbox, which goes with the
  // supplier selection). The title query is the search term, not a filter, so it's left untouched.
  const handleClearFilters = () => {
    setSelectedSuppliers([]);
    setSearchFilters({ ...searchFilters, availability: [], country: [], shippingType: [] });
    setUserSettings({
      ...userSettings,
      priceMin: undefined,
      priceMax: undefined,
      search: { ...userSettings.search, invertSuppliersSelection: false },
    });
  };
 
  const renderResultLimit = () => (
    <Accordion
      key="per-supplier-limit"
      expanded={expandedAccordion === 'per-supplier-limit'}
      onChange={onAccordionChange('per-supplier-limit')}
    >
      <StyledAccordionSummary expandIcon={<ExpandMoreIcon />}>
        <Typography>
          {i18n('drawer_results_limit')}
          {userSettings.suppliers?.resultLimit != null && (
            <span className={styles['accordion-hint']}>
              {' '}
              {i18n('drawer_results_limit_hint', [String(userSettings.suppliers.resultLimit)])}
            </span>
          )}
        </Typography>
      </StyledAccordionSummary>
      <StyledAccordionDetails>
        <TextField
          fullWidth
          size="small"
          label={i18n('drawer_results_limit_label')}
          value={userSettings.suppliers?.resultLimit ?? ''}
          onChange={(e) =>
            setUserSettings({
              ...userSettings,
              suppliers: {
                ...userSettings.suppliers,
                resultLimit: Number(e.target.value) || undefined,
              },
            })
          }
        />
      </StyledAccordionDetails>
    </Accordion>
  );
 
  return (
    <Box>
      {/* Title / Search Query */}
      <Box sx={{ p: '12px 16px' }}>
        <TextField
          autoFocus
          fullWidth
          label={i18n('drawer_product_name_label')}
          size="small"
          value={searchFilters.titleQuery}
          onChange={(e) => handleTitleQueryChange(e.target.value)}
          onKeyDown={handleKeyDown}
        />
      </Box>
 
      {drawerColumns.flatMap(({ id, drawer }) => {
        // "Results Limit" is a user setting (not a filter on a column), so it
        // has no column to anchor it to. Inject it right before the price
        // section to preserve its historical position in the drawer UX.
        const resultLimit = id === 'price' ? [renderResultLimit()] : [];
        return [
          ...resultLimit,
          <ColumnDrawerSection
            key={id}
            columnId={id}
            config={drawer}
            expandedAccordion={expandedAccordion}
            onAccordionChange={onAccordionChange}
          />,
        ];
      })}
 
      <Box sx={{ p: 2, display: 'flex', flexDirection: 'column', gap: 1 }}>
        <Button
          variant="text"
          fullWidth
          startIcon={<ClearFiltersIcon />}
          onClick={handleClearFilters}
          disabled={activeFilterCount === 0}
        >
          {i18n('drawer_clear_filters')}
        </Button>
        <Button
          variant="contained"
          fullWidth
          startIcon={<SearchIcon />}
          onClick={() => void handleSearch()}
          disabled={!searchFilters.titleQuery.trim()}
        >
          {i18n('drawer_search_button')}
        </Button>
      </Box>
    </Box>
  );
};
 
export default DrawerSearchPanel;