import { Formik } from 'formik'; import { SetCollections, SetFiles } from 'pages/gallery'; import React, { useEffect, useState, useRef } from 'react'; import { Form } from 'react-bootstrap'; import styled from 'styled-components'; import constants from 'utils/strings/constants'; import * as Yup from 'yup'; import { File, getLocalFiles } from 'services/fileService'; import { Collection, getLocalCollections, getNonEmptyCollections, } from 'services/collectionService'; import { parseHumanDate, searchLocation } from 'services/searchService'; import { getFilesWithCreationDay, getFilesInsideBbox } from 'utils/search'; const Wrapper = styled.div<{ open: boolean }>` background-color: #111; color: #fff; min-height: 64px; align-items: center; box-shadow: 0 0 5px rgba(0, 0, 0, 0.7); margin-bottom: 10px; position: fixed; top: 0; width: 100%; display: flex; align-items: center; justify-content: center; z-index: 200; padding: 0 20%; display: ${(props) => (props.open ? 'flex' : 'none')}; `; interface formValues { searchPhrase: string; } interface Props { isOpen: boolean; setOpen: (value) => void; loadingBar: any; setFiles: SetFiles; setCollections: SetCollections; } export default function SearchBar(props: Props) { const [allFiles, setAllFiles] = useState([]); const [allCollections, setAllCollections] = useState([]); useEffect(() => { const main = async () => { setAllFiles(await getLocalFiles()); setAllCollections(await getLocalCollections()); }; main(); }, []); const searchBarRef = useRef(null); useEffect(() => { if (props.isOpen) { setTimeout(() => { searchBarRef.current?.focus(); }, 200); } }, [props.isOpen]); const searchFiles = async (values: formValues) => { props.loadingBar.current?.continuousStart(); let resultFiles: File[] = []; const searchedDate = parseHumanDate(values.searchPhrase); if (searchedDate != null) { const filesWithSameDate = getFilesWithCreationDay( allFiles, searchedDate ); resultFiles.push(...filesWithSameDate); } else { const bbox = await searchLocation(values.searchPhrase); if (bbox) { const filesTakenAtLocation = getFilesInsideBbox(allFiles, bbox); resultFiles.push(...filesTakenAtLocation); } } props.setFiles(resultFiles); props.setCollections( getNonEmptyCollections(allCollections, resultFiles) ); await new Promise((resolve) => setTimeout( () => resolve(props.loadingBar.current?.complete()), 5000 ) ); }; const closeSearchBar = ({ resetForm }) => { props.setOpen(false); props.setFiles(allFiles); props.setCollections(allCollections); resetForm(); }; return ( initialValues={{ searchPhrase: '' }} onSubmit={searchFiles} validationSchema={Yup.object().shape({ searchPhrase: Yup.string().required(constants.REQUIRED), })} validateOnChange={false} validateOnBlur={false} > {({ values, touched, errors, handleChange, handleSubmit, resetForm, }) => ( <>
closeSearchBar({ resetForm })} >
)}
); }