-
Notifications
You must be signed in to change notification settings - Fork 0
/
DropDownList.tsx
82 lines (70 loc) · 2.17 KB
/
DropDownList.tsx
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
import { DEFAULT_PADDING_HORIZONTAL, DEFAULT_PADDING_VERTICAL, HEADER_HEIGHT } from '@/app/constants';
import styles from './dropdown.module.css';
import { translateGenre } from '@/app/shared/translateGenre';
import classNames from 'classnames';
import { Genre } from '@/store/features/filterSlice';
import { useAppDispatch } from '@/store/hooks';
import { useCallback, useContext, useLayoutEffect } from 'react';
import { setGenre } from '@/store/features/filterSlice';
import { Cinema } from '@/app/types';
import { AppContext } from '@/app/page';
export interface Coords {
x: number | undefined;
y: number | undefined;
}
interface DropDownListProps {
coords: Coords | undefined;
variants: (Genre | Cinema)[];
isOpen: boolean;
close: () => void;
setCurrentName: (value: Genre | Cinema) => void;
}
function isCinema (value: Genre | Cinema): value is Cinema {
return typeof value === "object";
}
export default function DropDownList ({
coords,
variants,
isOpen,
close,
setCurrentName,
}: DropDownListProps) {
const dispatch = useAppDispatch();
const { setCinemaId } = useContext(AppContext);
const x = coords?.x,
y = coords?.y;
const setValueHandler = useCallback((value: Genre | Cinema) => {
if (isCinema(value)) {
!!setCinemaId && setCinemaId(value.id);
} else {
dispatch(setGenre(value));
}
close();
setCurrentName(value);
// fixing error when filter at the bottom of the page
window.scrollTo({top: 0});
}, [dispatch, close, setCurrentName, setCinemaId]);
if (!x || !y) {
return null;
}
let position = {
top: y + HEADER_HEIGHT + DEFAULT_PADDING_VERTICAL + window.scrollY,
left: x + DEFAULT_PADDING_HORIZONTAL
};
const mods = [
{[styles.open]: isOpen},
];
return (
<ul className={classNames(styles.list, ...mods)} style={position}>
{!!variants && variants.map((variant, id) => <li key={id}>
<button
className={styles.button}
onClick={() => setValueHandler(variant)}
>
{typeof variant === 'object' && variant.name}
{typeof variant !== 'object' && translateGenre(variant)}
</button>
</li>)}
</ul>
)
}