Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, { useEffect, useState, useRef } from 'react';
- import style from './filteredSuggestions.scss';
- import axios from 'axios';
- import { AppendToLog } from 'Utils/Helper';
- import { HandleError, HandleResponse } from 'Handlers/Response';
- function FilteredList({ suggestionsList, language, filterValue, index, handleSuggestionClick, inputRef }) {
- const [suggestions, setSuggestions] = useState([]);
- const [filteredSuggestions, setFilteredSuggestions] = useState([]);
- const [selectedIndex, setSelectedIndex] = useState(-1);
- const selectedIndexRef = useRef(selectedIndex);
- selectedIndexRef.current = selectedIndex;
- const [showSuggestion, setShowSuggestion] = useState(false);
- const [exception, setException] = useState(null);
- const [isFetching, setIsFetching] = useState(false);
- const axiosCancelSource = axios.CancelToken.source();
- const fetchSpecializations = async () => {
- if (isFetching) return; // Semaphor zapobiegający równoczesnym żądaniom
- setIsFetching(true);
- const url = `/?do=TAJNE.ZRODLO.DANYCH`;
- try {
- const response = await axios({
- method: 'post',
- url: url,
- cancelToken: axiosCancelSource.token,
- });
- handleSpecializationsResponse(response);
- } catch (error) {
- if (axios.isCancel(error)) {
- AppendToLog(error.message);
- } else {
- HandleError(error, true);
- }
- } finally {
- setIsFetching(false); // Zwolnienie semafora po zakończeniu żądania
- }
- };
- const handleSpecializationsResponse = (response) => {
- try {
- if (HandleResponse(response, true)) {
- setSuggestions(response?.data?.result?.specializations);
- }
- } catch (error) {
- setException(error);
- }
- };
- useEffect(() => {
- fetchSpecializations();
- }, []); // Wywołanie funkcji po montażu komponentu
- useEffect(() => {
- if (suggestionsList) {
- setSuggestions(suggestionsList);
- } else {
- setSuggestions([
- { 'en': 'Artificial Intelligence', 'pl': 'Sztuczna Inteligencja' },
- { 'en': 'Machine Learning', 'pl': 'Uczenie Maszynowe' },
- { 'en': 'Deep Learning', 'pl': 'Głębokie Uczenie' },
- { 'en': 'Neural Networks', 'pl': 'Sieci Neuronowe' },
- { 'en': 'Data Mining', 'pl': 'Zbieranie Danych' },
- { 'en': 'Big Data', 'pl': 'Duże Dane' },
- ]);
- }
- }, [suggestionsList]);
- useEffect(() => {
- if (filterValue) {
- const filtered = suggestions.filter(item => item[language]?.toLowerCase().includes(filterValue.toLowerCase()));
- setFilteredSuggestions(filtered);
- //setShowSuggestion(true);
- } else {
- setFilteredSuggestions([]);
- }
- }, [filterValue, suggestions, language]);
- useEffect(() => {
- const handleKeyDown = (e) => {
- let newIndex = selectedIndexRef.current;
- if (e.keyCode === 40) { // down arrow
- newIndex = newIndex < filteredSuggestions.length - 1 ? newIndex + 1 : newIndex;
- setSelectedIndex(newIndex);
- } else if (e.keyCode === 38) { // up arrow
- newIndex = newIndex > 0 ? newIndex - 1 : 0;
- setSelectedIndex(newIndex);
- } else if (e.keyCode === 13) { // ENTER
- simulateEnter(newIndex); // Passing the current index as an argument
- }
- };
- window.addEventListener('keydown', handleKeyDown);
- return () => {
- window.removeEventListener('keydown', handleKeyDown);
- };
- }, [filteredSuggestions.length]);
- const simulateEnter = (currentIndex) => {
- if (currentIndex >= 0 && currentIndex < filteredSuggestions.length) {
- handleSuggestionClick(filteredSuggestions[currentIndex], index);
- }
- };
- const handleMouseEnter = (currentIndex) => {
- if (currentIndex >= 0 && currentIndex < filteredSuggestions.length) {
- handleSuggestionClick(filteredSuggestions[currentIndex], index);
- }
- };
- useEffect(() => {
- let isMounted = true;
- let timeoutId = null;
- // const checkIfFocused = () => {
- // if (inputRef.current === document.activeElement) {
- // if (isMounted) {
- // console.log(`Input ${language} is focused`);
- // setShowSuggestion(true);
- // }
- // }
- // else {
- // console.log(`Input ${language} is not focused`);
- // timeoutId = setTimeout(() => {
- // if (isMounted) setShowSuggestion(false); // Aktualizacja stanu tylko jeśli komponent jest zamontowany
- // }, 0);
- // }
- // };
- // checkIfFocused();
- const focusListener = () => setShowSuggestion(true);
- const blurListener = async () => {
- //console.log('blurListener');
- await new Promise(resolve => timeoutId = setTimeout(resolve, 200));
- if (isMounted) setShowSuggestion(false);
- };
- inputRef.current?.addEventListener('focus', focusListener);
- inputRef.current?.addEventListener('blur', blurListener);
- return () => {
- isMounted = false;
- inputRef.current?.removeEventListener('focus', focusListener);
- inputRef.current?.removeEventListener('blur', blurListener);
- // Czyszczenie dla setTimeout
- if (timeoutId) {
- clearTimeout(timeoutId);
- }
- };
- }, [inputRef]);
- return (
- showSuggestion && (
- <div className={style['suggestions-list']}>
- {filteredSuggestions.map((item, _index) => (
- <div key={_index}
- onClick={() => { handleMouseEnter(_index); }}
- //onMouseEnter={() => handleMouseEnter(_index)}
- className={`${style['suggestion-item']} ${selectedIndex === _index ? style['selected'] : ''}`}
- >
- {item[language]}
- </div>
- ))}
- </div>
- )
- );
- }
- export default FilteredList;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement