|
| 1 | +import React, { useRef, useState } from "react"; |
| 2 | +import styled, { css } from "styled-components"; |
| 3 | + |
| 4 | +import { useNavigate, useParams, useSearchParams } from "react-router-dom"; |
| 5 | +import { useDebounce } from "react-use"; |
| 6 | +import { Searchbar } from "@kleros/ui-components-library"; |
| 7 | + |
| 8 | +import { isEmpty } from "utils/index"; |
| 9 | +import { decodeURIFilter, encodeURIFilter, useRootPath } from "utils/uri"; |
| 10 | + |
| 11 | +import { landscapeStyle } from "styles/landscapeStyle"; |
| 12 | +import { responsiveSize } from "styles/responsiveSize"; |
| 13 | + |
| 14 | +const Container = styled.div` |
| 15 | + display: flex; |
| 16 | + flex-direction: column; |
| 17 | + gap: ${responsiveSize(8, 16)}; |
| 18 | +
|
| 19 | + ${landscapeStyle( |
| 20 | + () => css` |
| 21 | + flex-direction: row; |
| 22 | + ` |
| 23 | + )} |
| 24 | +`; |
| 25 | + |
| 26 | +const StyledSearchbar = styled(Searchbar)` |
| 27 | + flex: 1; |
| 28 | + flex-basis: 310px; |
| 29 | +
|
| 30 | + input { |
| 31 | + font-size: 16px; |
| 32 | + height: 45px; |
| 33 | + padding-top: 0px; |
| 34 | + padding-bottom: 0px; |
| 35 | + } |
| 36 | +`; |
| 37 | + |
| 38 | +const Search: React.FC = () => { |
| 39 | + const { page, order, filter } = useParams(); |
| 40 | + const location = useRootPath(); |
| 41 | + const decodedFilter = decodeURIFilter(filter ?? "all"); |
| 42 | + const { id: searchValue, ...filterObject } = decodedFilter; |
| 43 | + const [search, setSearch] = useState(searchValue ?? ""); |
| 44 | + const initialRenderRef = useRef(true); |
| 45 | + const navigate = useNavigate(); |
| 46 | + const [searchParams] = useSearchParams(); |
| 47 | + |
| 48 | + useDebounce( |
| 49 | + () => { |
| 50 | + if (initialRenderRef.current && isEmpty(search)) { |
| 51 | + initialRenderRef.current = false; |
| 52 | + return; |
| 53 | + } |
| 54 | + initialRenderRef.current = false; |
| 55 | + const newFilters = isEmpty(search) ? { ...filterObject } : { ...filterObject, id: search }; |
| 56 | + const encodedFilter = encodeURIFilter(newFilters); |
| 57 | + navigate(`${location}/${page}/${order}/${encodedFilter}?${searchParams.toString()}`); |
| 58 | + }, |
| 59 | + 500, |
| 60 | + [search] |
| 61 | + ); |
| 62 | + |
| 63 | + return ( |
| 64 | + <Container> |
| 65 | + <StyledSearchbar |
| 66 | + dir="auto" |
| 67 | + type="text" |
| 68 | + placeholder="Search" |
| 69 | + value={search} |
| 70 | + onChange={(e) => setSearch(e.target.value)} |
| 71 | + /> |
| 72 | + </Container> |
| 73 | + ); |
| 74 | +}; |
| 75 | + |
| 76 | +export default Search; |
0 commit comments