All files / src/components/organizer/EventManagement EventSearch.tsx

90% Statements 63/70
88% Branches 44/50
88.23% Functions 15/17
89.39% Lines 59/66

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 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292                                                                                      2x                     2x 99x 99x   99x 99x     99x 30x 30x 30x 30x   30x 30x 30x 30x 30x         30x 14x 14x 14x               99x 50x 50x 19x   50x 15x   50x 9x   50x     50x       99x   99x 32x       99x 7x 7x     99x 1x 1x     99x 2x 2x     99x                     99x 1x 2x   1x           99x 1x 1x 1x       99x     99x                                                                                                 39x   50x       1x                   792x                               2x 2x                                                                                                    
/**
 * EventSearch Component
 *
 * Story 2.5.3 - Task 8b (GREEN Phase)
 * AC: 2 (Event List & Filters)
 * Wireframe: docs/wireframes/story-1.16-event-management-dashboard.md v1.0
 *
 * Event search and filters with URL persistence
 */
 
import React, { useEffect, useState } from 'react';
import {
  TextField,
  Select,
  MenuItem,
  FormControl,
  InputLabel,
  Stack,
  Chip,
  Button,
  InputAdornment,
  IconButton,
  Box,
  SelectChangeEvent,
  OutlinedInput,
  FormControlLabel,
  Checkbox,
} from '@mui/material';
import {
  Search as SearchIcon,
  Clear as ClearIcon,
  FilterList as FilterListIcon,
} from '@mui/icons-material';
import { useTranslation } from 'react-i18next';
import { useSearchParams } from 'react-router-dom';
import { useDebounce } from '@/hooks/useDebounce';
import type { EventFilters } from '@/types/event.types';
 
interface EventSearchProps {
  onFiltersChange: (filters: EventFilters) => void;
  filters: EventFilters;
}
 
const WORKFLOW_STATE_OPTIONS = [
  'CREATED',
  'TOPIC_SELECTION',
  'SPEAKER_IDENTIFICATION',
  'SLOT_ASSIGNMENT',
  'AGENDA_PUBLISHED',
  'EVENT_LIVE',
  'EVENT_COMPLETED',
  'ARCHIVED',
];
 
export const EventSearch: React.FC<EventSearchProps> = ({ onFiltersChange, filters }) => {
  const { t } = useTranslation('events');
  const [searchParams, setSearchParams] = useSearchParams();
 
  const [searchQuery, setSearchQuery] = useState(filters.search || '');
  const [showArchived, setShowArchived] = useState(filters.includeArchived ?? false);
 
  // Parse URL params on mount
  useEffect(() => {
    const workflowStateParam = searchParams.get('workflowState');
    const yearParam = searchParams.get('year');
    const searchParam = searchParams.get('search');
    const includeArchivedParam = searchParams.get('includeArchived');
 
    const urlFilters: EventFilters = {};
    if (workflowStateParam) urlFilters.workflowState = workflowStateParam.split(',');
    if (yearParam) urlFilters.year = parseInt(yearParam, 10);
    if (searchParam) urlFilters.search = searchParam;
    Iif (includeArchivedParam !== null) {
      urlFilters.includeArchived = includeArchivedParam === 'true';
    }
 
    // Only apply URL filters if they exist
    if (Object.keys(urlFilters).length > 0) {
      onFiltersChange(urlFilters);
      if (searchParam) setSearchQuery(searchParam);
      Iif (includeArchivedParam !== null) {
        setShowArchived(includeArchivedParam === 'true');
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []); // Only on mount
 
  // Update URL when filters change
  useEffect(() => {
    const params = new URLSearchParams();
    if (filters.workflowState && filters.workflowState.length > 0) {
      params.set('workflowState', filters.workflowState.join(','));
    }
    if (filters.year) {
      params.set('year', filters.year.toString());
    }
    if (filters.search) {
      params.set('search', filters.search);
    }
    Iif (filters.includeArchived !== undefined) {
      params.set('includeArchived', filters.includeArchived.toString());
    }
    setSearchParams(params);
  }, [filters, setSearchParams]);
 
  // Debounced search
  const debouncedSearchQuery = useDebounce(searchQuery, 300);
 
  useEffect(() => {
    onFiltersChange({ ...filters, search: debouncedSearchQuery });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [debouncedSearchQuery]);
 
  const handleSearchChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const value = event.target.value;
    setSearchQuery(value);
  };
 
  const handleClearSearch = () => {
    setSearchQuery('');
    onFiltersChange({ ...filters, search: '' });
  };
 
  const handleWorkflowStateChange = (event: SelectChangeEvent<string[]>) => {
    const value = event.target.value as string[];
    onFiltersChange({ ...filters, workflowState: value.length > 0 ? value : undefined });
  };
 
  const handleShowArchivedChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const checked = event.target.checked;
    setShowArchived(checked);
 
    // Update the includeArchived flag
    onFiltersChange({
      ...filters,
      includeArchived: checked,
    });
  };
 
  const handleRemoveWorkflowState = (workflowStateToRemove: string) => {
    const newWorkflowStates = (filters.workflowState || []).filter(
      (s) => s !== workflowStateToRemove
    );
    onFiltersChange({
      ...filters,
      workflowState: newWorkflowStates.length > 0 ? newWorkflowStates : undefined,
    });
  };
 
  const handleClearAll = () => {
    setSearchQuery('');
    setShowArchived(false);
    onFiltersChange({ includeArchived: false });
  };
 
  // Count active filters
  const activeFilterCount =
    (filters.workflowState?.length || 0) + (filters.year ? 1 : 0) + (filters.search ? 1 : 0);
 
  return (
    <Box data-testid="filter-container">
      <Stack spacing={2} data-testid="event-filters">
        {/* Row 1: Search and Filters */}
        <Stack spacing={2} direction={{ xs: 'column', sm: 'row' }} alignItems="stretch">
          {/* Search Input */}
          <FormControl fullWidth>
            <TextField
              placeholder={t('dashboard.searchEvents')}
              value={searchQuery}
              onChange={handleSearchChange}
              aria-label={t('filters.searchAriaLabel')}
              inputProps={{
                'data-testid': 'event-search-input',
              }}
              InputProps={{
                startAdornment: (
                  <InputAdornment position="start">
                    <SearchIcon data-testid="search-icon" />
                  </InputAdornment>
                ),
                endAdornment: searchQuery && (
                  <InputAdornment position="end">
                    <IconButton
                      onClick={handleClearSearch}
                      size="small"
                      aria-label={t('filters.clearSearchAriaLabel')}
                    >
                      <ClearIcon />
                    </IconButton>
                  </InputAdornment>
                ),
              }}
            />
          </FormControl>
 
          {/* Workflow State Filter */}
          <FormControl sx={{ minWidth: { sm: 200 } }}>
            <InputLabel id="workflow-state-filter-label">
              {t('dashboard.filter.workflowState')}
            </InputLabel>
            <Select
              data-testid="filter-status"
              labelId="workflow-state-filter-label"
              multiple
              value={filters.workflowState || []}
              onChange={handleWorkflowStateChange}
              input={<OutlinedInput label={t('dashboard.filter.workflowState')} />}
              renderValue={(selected) => (
                <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
                  {selected.map((value) => (
                    <Chip
                      key={value}
                      label={t(`workflow.states.${value.toLowerCase()}`)}
                      size="small"
                      onDelete={() => handleRemoveWorkflowState(value)}
                      onMouseDown={(e) => e.stopPropagation()}
                      aria-label={`Remove ${t(`workflow.states.${value.toLowerCase()}`).toLowerCase()} filter`}
                    />
                  ))}
                </Box>
              )}
              aria-label={t('dashboard.filter.workflowState')}
            >
              {WORKFLOW_STATE_OPTIONS.map((workflowState) => (
                <MenuItem key={workflowState} value={workflowState}>
                  {t(`workflow.states.${workflowState.toLowerCase()}`)}
                </MenuItem>
              ))}
            </Select>
          </FormControl>
 
          {/* Year Filter */}
          <FormControl sx={{ minWidth: { sm: 150 } }}>
            <TextField
              data-testid="filter-year"
              type="number"
              label={t('dashboard.filter.year')}
              placeholder={t('dashboard.filter.allYears')}
              value={filters.year || ''}
              onChange={(e) => {
                const value = e.target.value ? parseInt(e.target.value, 10) : undefined;
                onFiltersChange({ ...filters, year: value });
              }}
              inputProps={{
                min: 2000,
                max: 2100,
                step: 1,
                'aria-label': 'Filter by year',
              }}
            />
          </FormControl>
        </Stack>
 
        {/* Row 2: Show Archived Toggle */}
        <Box>
          <FormControlLabel
            control={
              <Checkbox
                checked={showArchived}
                onChange={handleShowArchivedChange}
                data-testid="show-archived-checkbox"
              />
            }
            label={t('dashboard.filter.showArchived')}
          />
        </Box>
      </Stack>
 
      {/* Active Filters & Clear All */}
      {activeFilterCount > 0 && (
        <Stack direction="row" spacing={2} alignItems="center" mt={2}>
          <Chip
            icon={<FilterListIcon />}
            label={t('dashboard.filter.activeFilters', { count: activeFilterCount })}
            size="small"
            variant="outlined"
            aria-label={t('dashboard.filter.filtersActiveAriaLabel', { count: activeFilterCount })}
          />
          <Button
            size="small"
            onClick={handleClearAll}
            startIcon={<ClearIcon />}
            aria-label={t('filters.clearAllAriaLabel')}
          >
            {t('dashboard.filter.clearAll')}
          </Button>
        </Stack>
      )}
    </Box>
  );
};