frontend/сomponents/search/index.tsx

80 lines
2.6 KiB
TypeScript
Raw Normal View History

2022-10-22 00:34:07 +03:00
import React, { useState } from "react";
2022-10-22 19:11:56 +03:00
import { AutoComplete, Input, Tag } from 'antd';
2022-10-22 00:34:07 +03:00
import { fetcher } from "../../pages/api/fetch";
2022-10-22 19:11:56 +03:00
import { useAppDispatch, useAppSelector } from "../../hooks";
import { hints, INode, products } from "../../store/reducers/nodesInputReducer";
import { createHints, search } from "../../store/reducers/asyncActions";
2022-10-22 21:01:16 +03:00
import styles from "./search.module.css"
2022-10-22 00:34:07 +03:00
export const Search: React.FC<{onData:(data:any)=>void}> = (props) =>{
const [data, setData] = useState("")
2022-10-22 19:11:56 +03:00
const [tags, setTags] = useState(new Array<JSX.Element>())
const [searchOptions, setSearchOptions] = useState(new Array<INode>())
const dispatch = useAppDispatch();
const getHints = useAppSelector(hints);
const [autoCompleteValue, setAutoCompleteValue] = useState("")
const onChange = (text:string) =>{
if (text.length >= 3 && text.length%3 == 0){
dispatch(
createHints({word:text, hints:getHints.length == 0? []: getHints.map((el)=>el.value)})
)
}
setData(text)
}
const addTag = (value:INode) => {
let color = "red"
switch((value as any).type ){
case "Category":
color = "gold"
break
case "Name":
color = "green"
break
case "All":
color = "gray"
break
}
let tag = <Tag
color={color}
closable
style={{ marginRight: 3 }}
>
{value.value.length <13? value.value:value.value.slice(0,10)+"..."}
</Tag>
setTags(tags.concat([tag]))
}
const onSelect = (value:string, type:INode) =>{
addTag(type)
setSearchOptions(searchOptions.concat([type]))
setAutoCompleteValue("")
}
2022-10-22 00:34:07 +03:00
const onEnter = (value:any) => {
2022-10-22 19:11:56 +03:00
dispatch(search(searchOptions))
2022-10-22 00:34:07 +03:00
}
return(
2022-10-22 19:11:56 +03:00
<AutoComplete
2022-10-22 22:40:21 +03:00
dropdownMatchSelectWidth={252}
2022-10-22 19:11:56 +03:00
options={getHints.map((el)=>el.value)}
onSelect={onSelect as any}
value={autoCompleteValue}
onChange={(e)=>setAutoCompleteValue(e)}
>
<Input.Search prefix={tags}
2022-10-22 22:40:21 +03:00
style={{ width: "50vw" }}
color="red-6"
2022-10-22 21:01:16 +03:00
className={styles.search}
2022-10-22 19:11:56 +03:00
onChange={(e)=>onChange(e.target.value)}
value={data}
onSearch={(e) => onEnter(e)}
size="large"
placeholder="Поиск товара"
enterButton />
</AutoComplete>
2022-10-22 00:34:07 +03:00
);
}