All files / src/components/Filter index.tsx

50.47% Statements 107/212
32.45% Branches 61/188
40.63% Functions 26/64
50.97% Lines 105/206

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 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621                                              4x                                                   4x                   6x   6x                                       4x                       4x 4x   4x 4x 4x   4x 4x   4x   4x 4x   4x   4x   4x 2x       4x 2x       4x 2x 2x         4x 2x       4x 4x   4x 4x     4x 2x 2x 2x 2x   2x     2x       2x               2x   2x     2x 2x       4x 4x 2x 2x 2x   2x         2x           4x     4x 2x         4x 2x         4x       4x       4x                   4x 2x 2x       4x 4x     4x   2x 2x   2x                                                       4x           4x                             4x       4x           4x                               4x                 4x                 4x 2x     2x     2x 2x     4x 2x 2x     4x         4x               4x                       4x 2x 2x                 4x 2x     2x       4x 2x     2x       4x 2x               4x 2x               4x 2x   2x                                                           4x 2x   2x                                                           4x                                                                                                                                                                                               8x                                                                                    
import React, { FC, useCallback, useEffect, useMemo, useReducer, useRef, useState } from 'react';
import { useMedia } from 'ag-ems-ui-library';
import { useTranslation } from 'react-i18next';
import {
  differenceInDays,
  format,
  formattedNow,
  getDateInXDay,
  getNextDay,
  isLater,
  now,
  removeQueryParam,
  setQueryParam
} from '../../helpers';
import { SvgIcon } from '../SvgIcon';
import { FilterSelect } from './FilterSelect';
import { FilterPopup, FilterPopupTab, FilterPopupTabs } from './FilterPopup';
import { DataRangeDates, DataRangePopupContent } from '../DataRange';
import { Location } from '../Location';
import { navigate } from 'gatsby';
import { FilterCategory } from './FilterCategory';
import { FilterPopover } from './FilterPopover';
 
const styles = require('./Filter.module.css');
 
export interface FilterOptionType {
  id: number;
  name: string;
}
 
export interface FilterCategoryType {
  value: string;
  label: string;
}
 
export type FilterType = {
  locationId?: string,
  startDate?: string,
  endDate?: string,
  sortId?: number | null,
  categoryIds?: string[],
  themeIds?: string[]
}
 
type Action = {
  type: string,
  payload?: FilterType
}
 
const defaultValues: FilterType = {
  locationId: '',
  startDate: format(now, 'yyyy-MM-dd'),
  endDate: format(getNextDay(now), 'yyyy-MM-dd'),
  sortId: null,
  categoryIds: [],
  themeIds: []
};
 
export function filterReducer(state: FilterType, action: Action) {
  switch (action.type) {
    case 'set':
      return { ...state, ...action.payload };
    case 'reset':
      // TODO: wrong
      return defaultValues;
    default:
      throw new Error('Not action');
  }
}
 
export const Filter: FC<{
  slug: string;
  quantity: number;
  locations: any[];
  fixed?: boolean;
  filters: FilterType;
  updateFilters: (action: Action) => void;
  config?: any;
  loading?: boolean;
  onConfirm?: (isGlobal: boolean) => void;
  maxInterval?: number;
}> = ({
  slug,
  quantity,
  locations,
  fixed = false,
  filters,
  updateFilters,
  config,
  loading,
  onConfirm,
  maxInterval
}) => {
  const { t } = useTranslation();
  const isMobile = useMedia('(max-width: 1024px)');
 
  const filterRef = useRef<HTMLDivElement>(null);
  const filterControlsRef = useRef<HTMLDivElement>(null);
  const filterSqueezeRef = useRef<HTMLDivElement>(null);
 
  const [isShowFilter, setIsShowFilter] = useState(false);
  const [activeTab, setActiveTab] = useState('location');
 
  const [filtersLocal, setFiltersLocal] = useReducer(filterReducer, filters);
 
  const [showCategoryPopover, setShowCategoryPopover] = useState(false);
  const [showThemePopover, setShowThemePopover] = useState(false);
 
  const [startFirst, setStartFirst] = useState(true);
 
  const firstTime = useRef(true);
 
  const minDate = useMemo(
    () => !startFirst ? filters.startDate : formattedNow,
    [startFirst, filters.startDate]
  );
 
  const maxDate = useMemo(
    () => !startFirst && filters.startDate && maxInterval ? getDateInXDay(filters.startDate, maxInterval) : '',
    [startFirst, filters.startDate]
  );
 
  const minButtonDate = useMemo(() => {
      const min = filters.endDate && maxInterval ? getDateInXDay(filters.endDate, -maxInterval) : formattedNow;
      return isLater(min, formattedNow) ? min : formattedNow;
    },
    [filters.endDate]
  );
 
  const maxButtonDate = useMemo(
    () => filters.startDate && maxInterval ? getDateInXDay(filters.startDate, maxInterval) : '',
    [filters.startDate]
  );
 
  const setterLocal = useCallback((payload: FilterType) => setFiltersLocal({ type: 'set', payload }), []);
  const setterGlobal = useCallback((payload: FilterType) => updateFilters({ type: 'set', payload }), []);
 
  const confirmHandler = (isGlobal: boolean = false) => {
    Iif (!!onConfirm) onConfirm(isGlobal);
  };
 
  useEffect(() => {
    const url = typeof window !== 'undefined' ? new URL(location.href) : null;
    const startDate = url?.searchParams.get('startDate');
    const endDate = url?.searchParams.get('endDate');
    const sortId = url?.searchParams.get('sortId');
 
    const categories = config?.category
      ? url?.searchParams.get('categories')
      : null;
    const themes = config?.theme
      ? url?.searchParams.get('themes')
      : null;
 
    const payload = {
      ...(startDate && { startDate }),
      ...(endDate && { endDate }),
      ...(sortId && { sortId: +sortId }),
      ...(categories && { categoryIds: decodeURIComponent(categories).split(',') }),
      ...(themes && { themeIds: decodeURIComponent(themes).split(',') })
    }
 
    updateFilters({ type: 'set', payload });
 
    Iif (locations.length === 1) {
      navigateLocation(locations[0].value);
    }
    Eif (typeof window !== 'undefined') {
      window.addEventListener('scroll', getScrollHandler());
    }
  }, []);
 
  useEffect(() => {
    if (!firstTime.current && filters.startDate && filters.endDate) {
      setQueryParam('startDate', filters.startDate);
      setQueryParam('endDate', filters.endDate);
      filters.sortId ? setQueryParam('sortId', filters.sortId.toString()) : removeQueryParam('sortId');
 
      Iif (config?.category) {
        filters.categoryIds?.length
          ? setQueryParam('categories', encodeURIComponent(filters.categoryIds.join(',')))
          : removeQueryParam('categories');
      }
      Iif (config?.theme) {
        filters.themeIds?.length
          ? setQueryParam('themes', encodeURIComponent(filters.themeIds.join(',')))
          : removeQueryParam('themes');
      }
    }
    firstTime.current = false;
  }, [filters]);
 
  useEffect(() => {
    Iif (showCategoryPopover) {
      setterLocal({ categoryIds: filters?.categoryIds });
    }
  }, [showCategoryPopover]);
 
  useEffect(() => {
    Iif (showThemePopover) {
      setterLocal({ themeIds: filters?.themeIds });
    }
  }, [showThemePopover]);
 
  const setStart = (value: string) => {
    setterGlobal({ startDate: value, endDate: '' });
  };
 
  const setEnd = (value: string) => {
    setterGlobal({ endDate: value });
  };
 
  const selectHandler = (value: string) => {
    if (startFirst) {
      setStart(value);
      setStartFirst(false);
    } else {
      setEnd(value);
      setStartFirst(true);
    }
  };
 
  useEffect(() => {
    Eif (filterSqueezeRef.current) {
      filterSqueezeRef.current.style.width = `${filterSqueezeRef.current.scrollWidth}px`;
    }
  }, [isMobile]);
 
  const locationName = useMemo(() => {
    return locations.find(loc => loc.value === filters.locationId)?.name
  }, [locations, filters.locationId]);
 
  const getScrollHandler = () => {
    let timeout;
    let scrollY = window.scrollY;
    const body = document.querySelector('body');
 
    return () => {
      if (timeout) {
        cancelAnimationFrame(timeout);
      }
 
      timeout = requestAnimationFrame(() => {
        if (body?.style.position === 'fixed' || fixed) {
          return;
        }
        if (scrollY > window.scrollY) {
          if (filterRef.current && filterRef.current.classList.contains(styles.shift)) {
            filterRef.current.classList.remove(styles.shift);
          }
        }
        scrollY = window.scrollY;
 
        if (filterRef.current && filterControlsRef.current && filterSqueezeRef.current) {
          if (filterControlsRef.current.getBoundingClientRect().top <= 0) {
            filterSqueezeRef.current.style.width = `${filterSqueezeRef.current.scrollWidth}px`;
            filterRef.current.classList.replace(styles.unsticky, styles.sticky);
          } else {
            filterRef.current.classList.replace(styles.sticky, styles.unsticky);
          }
        }
      });
    };
  };
 
  const shift = () => {
    if (filterRef.current && filterControlsRef.current) {
      filterRef.current.classList.toggle(styles.shift);
    }
  };
 
  const showFilters = () => {
    if (filters.startDate && filters.endDate) {
      setterLocal({ startDate: filters.startDate, endDate: filters.endDate });
    }
 
    if (filters?.categoryIds) {
      setterLocal({ categoryIds: filters.categoryIds });
    }
    if (filters?.themeIds) {
      setterLocal({ themeIds: filters.themeIds });
    }
 
    setIsShowFilter(true);
  }
 
  const closeFilters = () => {
    setIsShowFilter(false);
  }
 
  const showLocationFilter = () => {
    setActiveTab('location');
    setterLocal({ locationId: filters.locationId });
    showFilters();
  }
 
  const showDatesFilter = (which: 'start' | 'end' = 'start') => {
    setActiveTab('dates');
    setStartFirst(true);
    if (filters.startDate && filters.endDate) {
      setterLocal({ startDate: filters.startDate, endDate: filters.endDate });
    }
 
    if (which === 'end') {
      setStartFirst(false);
    }
 
    if (isMobile) {
      showFilters();
    }
  }
 
  const showCategoryFilter = () => {
    if (isMobile) {
      setActiveTab('filters');
      showFilters();
    } else {
      setShowCategoryPopover(true);
    }
  }
 
  const showThemeFilter = () => {
    if (isMobile) {
      setActiveTab('filters');
      showFilters();
    } else {
      setShowThemePopover(true);
    }
  }
 
  const selectStartDate = (value) => {
    const payload: { startDate, endDate? } = {
      startDate: value
    }
    Iif (filters.endDate && isLater(value, filters.endDate)) {
      payload.endDate = format(getNextDay(value), 'yyyy-MM-dd');
    }
    setterGlobal({ ...payload });
    confirmHandler(true);
  }
 
  const selectEndDate = (value) => {
    setterGlobal({ endDate: value });
    confirmHandler(true);
  }
 
  const navigateLocation = (value) => {
    const urlSearch = typeof window !== 'undefined' ? new URL(window.location.href).search : null;
    value ? navigate(`/${slug}/${value}${urlSearch}`) : navigate(`/${slug}${urlSearch}`);
  };
 
  const readyHandler = () => {
    if (activeTab === 'location') {
      navigateLocation(filters.locationId);
    }
    confirmHandler();
    closeFilters();
  }
 
  const resetHandler = () => {
    if (activeTab === 'location') {
      setterGlobal({ locationId: '' })
    }
    if (activeTab === 'dates') {
      setterGlobal({ startDate: '', endDate: '' });
    }
    if (activeTab === 'filters') {
      setterGlobal({ categoryIds: [], themeIds: [] });
    }
  }
 
  const filterPopupText = useMemo(() => {
    Eif ((activeTab === 'location' || activeTab === 'filters') && quantity !== undefined) {
      return `${quantity} ${t('results')}`;
    }
    if (activeTab === 'dates' && filters.startDate && filters.endDate) {
      const duration = differenceInDays(new Date(filters.endDate), new Date(filters.startDate)) + 1;
      return `${duration} ${t('day', { count: duration })}`;
    }
    return;
  }, [activeTab, filters.startDate, filters.endDate, quantity]);
 
  const selectedCategories = useMemo(() => {
    Iif (config?.category?.options && filters.categoryIds?.length) {
      return config.category.options.filter(it => filters.categoryIds?.includes(it.value));
    } else {
      return [];
    }
  }, [filters.categoryIds]);
 
  const selectedThemes = useMemo(() => {
    Iif (config?.theme?.options && filters.themeIds?.length) {
      return config.theme.options.filter(it => filters.themeIds?.includes(it.value));
    } else {
      return [];
    }
  }, [filters.themeIds]);
 
  const categoryFilter = useMemo(() =>
    config?.category
      ? <FilterCategory
        selected={filters.categoryIds}
        options={config.category.options}
        onChange={categoryIds => setterGlobal({ categoryIds })}
      />
      : null, [config, filters.categoryIds]);
 
  const themeFilter = useMemo(() =>
    config?.theme
      ? <FilterCategory
        selected={filters.themeIds}
        options={config.theme.options}
        onChange={themeIds => setterGlobal({ themeIds })}
      />
      : null, [config, filters.themeIds]);
 
  const categoryButton = useMemo(() => {
    const length = selectedCategories.length;
 
    return config?.category
      ? <div className={styles.FilterControlWrapper}>
        <button type="button" className={styles.FilterControl} onClick={showCategoryFilter}>
        <span>
          {length
            ? `${selectedCategories[0].label} ${length > 1 ? ' ' + t('andMore', { quantity: length - 1 }) : ''}`
            : t('categories')
          }
        </span>
          <SvgIcon icon={{ name: 'sort-down', width: 12, height: 12, fill: '#144154' }} />
        </button>
        <FilterPopover
          text={`${quantity} ${t('results')}`}
          isOpen={showCategoryPopover}
          onClose={() => {
            setShowCategoryPopover(false);
            setterGlobal({ categoryIds: filtersLocal.categoryIds });
          }}
          cancelHandler={() => setterGlobal({ categoryIds: [] })}
          confirmHandler={() => {
            setShowCategoryPopover(false);
            confirmHandler();
          }}
        >
          {categoryFilter}
        </FilterPopover>
      </div>
      : null
  }, [selectedCategories, showCategoryPopover, categoryFilter, filtersLocal.categoryIds]);
 
  const themeButton = useMemo(() => {
    const length = selectedThemes.length;
 
    return config?.theme
      ? <div className={styles.FilterControlWrapper}>
        <button type="button" className={styles.FilterControl} onClick={showThemeFilter}>
        <span>
          {length
            ? `${selectedThemes[0].label} ${length > 1 ? ' ' + t('andMore', { quantity: length - 1 }) : ''}`
            : t('themes')
          }
        </span>
          <SvgIcon icon={{ name: 'sort-down', width: 12, height: 12, fill: '#144154' }} />
        </button>
        <FilterPopover
          text={`${quantity} ${t('results')}`}
          isOpen={showThemePopover}
          onClose={() => {
            setShowThemePopover(false);
            setterGlobal({ themeIds: filtersLocal.themeIds });
          }}
          cancelHandler={() => setterGlobal({ themeIds: [] })}
          confirmHandler={() => {
            setShowThemePopover(false);
            confirmHandler();
          }}
        >
          {themeFilter}
        </FilterPopover>
      </div>
      : null
  }, [selectedThemes, showThemePopover, themeFilter, filtersLocal.themeIds]);
 
  return <>
    <div className={`${styles.Filter} ${fixed ? styles.fixed : styles.unsticky}`} ref={filterRef}>
      <Location
        classes={`${styles.FilterField} mb-2`}
        locations={locations}
        value={filters.locationId ?? ''}
        name={locationName}
        placeholder={t('locationSelect')}
        onChange={navigateLocation}
        onClick={showLocationFilter}
      />
      <DataRangeDates
        classes={`${styles.FilterDates} mb-1`}
        startDate={filters.startDate as string}
        endDate={filters.endDate as string}
        maxInterval={maxInterval}
        selectStartDate={selectStartDate}
        selectEndDate={selectEndDate}
        onStartClick={() => showDatesFilter()}
        onEndClick={() => showDatesFilter('end')}
        startLabel={t('entry')}
        endLabel={t('exit')}
        popupMobile={false}
      />
 
      <div className={`${styles.FilterControls}`} ref={filterControlsRef}>
        <div className={styles.FilterLeft}>
          <div className={`${styles.FilterSqueezable} only-sm`} ref={filterSqueezeRef}>
            <button type="button" className={styles.FilterButton} onClick={showLocationFilter}>
              <SvgIcon icon={{ name: 'map-marker-alt', width: 16, height: 16, fill: '#144154' }} />
              <span>{locationName || t('locationSelect')}</span>
            </button>
            {filters.startDate && filters.endDate && (
              <button type="button" className={styles.FilterButton} onClick={() => showDatesFilter()}>
                <SvgIcon icon={{ name: 'calendar-alt', width: 16, height: 16, fill: '#144154' }} />
                <span>{format(filters.startDate, 'dd.MM.')} - {format(filters.endDate, 'dd.MM.')}</span>
              </button>
            )}
          </div>
          <FilterSelect
            label={t('price')}
            selected={filters.sortId}
            options={[
              { id: 1, name: t('ascending') },
              { id: 2, name: t('descending') }
            ]}
            onChange={value => {
              setterGlobal({ sortId: value });
              confirmHandler(true);
            }}
          />
          {categoryButton}
          {themeButton}
        </div>
        <div className={`${styles.FilterRight} only-sm`}>
          <button type="button" className={styles.FilterFilter} onClick={showFilters}>
            <SvgIcon icon={{ name: 'filter', width: 16, height: 16, fill: '#144154' }} />
            <span>{t('filter')}</span>
          </button>
        </div>
      </div>
 
      <button type="button" className={`${styles.FilterHitch} only-sm`} aria-label={'Show filters'} onClick={shift} />
    </div>
 
    <FilterPopup
      isOpen={isShowFilter}
      cancelHandler={resetHandler}
      confirmHandler={readyHandler}
      text={filterPopupText}
      loading={loading}
    >
      <FilterPopupTabs>
        <FilterPopupTab current={activeTab === 'location'} onClick={() => {
          setActiveTab('location')
        }}>
          {t('location')}
        </FilterPopupTab>
 
        <FilterPopupTab current={activeTab === 'dates'} onClick={() => {
          setActiveTab('dates')
        }}>
          {t('date', { count: 2 })}
        </FilterPopupTab>
 
        {(config?.category || config?.theme) &&
        <FilterPopupTab current={activeTab === 'filters'} onClick={() => {
          setActiveTab('filters')
        }}>
          {t('filters')}
        </FilterPopupTab>}
      </FilterPopupTabs>
 
      <div className={`${styles.FilterContent} ${activeTab === 'location' ? styles.show : ''}`}>
        <ul className={styles.FilterLocations}>
          {locations.map((loc, index) => {
            return (
              <li
                key={index}
                className={`${styles.FilterLocation} ${loc.value === filters.locationId ? styles.current : ''}`}
              >
                <button type="button" onClick={() => setterGlobal({ locationId: loc.value })}>{loc.name}</button>
              </li>
            );
          })}
        </ul>
      </div>
 
      <div className={`${styles.FilterContent} ${activeTab === 'dates' ? styles.show : ''}`}>
        <DataRangePopupContent
          startDate={filters.startDate as string}
          endDate={filters.endDate as string}
          minDate={minDate as string}
          maxDate={maxDate as string}
          minButtonDate={minButtonDate as string}
          maxButtonDate={maxButtonDate as string}
          setStartDate={date => setterGlobal({ startDate: date as string })}
          setEndDate={date => setterGlobal({ endDate: date as string })}
          selectHandler={selectHandler}
          startLabel={t('entry')}
          endLabel={t('exit')}
          startFirst={startFirst}
          onStartClick={() => setStartFirst(true)}
          onEndClick={() => setStartFirst(false)}
        />
      </div>
 
      {(config?.category || config?.theme) &&
      <div className={`${styles.FilterContent} ${styles.scrollable} ${activeTab === 'filters' ? styles.show : ''}`}>
        {config?.category && <h3 className={styles.FilterTitle}>{t('categories')}</h3>}
        {categoryFilter}
        {config?.theme && <h3 className={styles.FilterTitle}>{t('themes')}</h3>}
        {themeFilter}
      </div>}
 
    </FilterPopup>
  </>;
};