Skip to content

Commit

Permalink
Draft
Browse files Browse the repository at this point in the history
  • Loading branch information
botisSmile committed Sep 29, 2023
1 parent d010652 commit 578b268
Showing 1 changed file with 104 additions and 69 deletions.
173 changes: 104 additions & 69 deletions front/example-app/src/components/SearchBar/SearchBar.tsx
Original file line number Diff line number Diff line change
@@ -1,111 +1,142 @@
import {
ChangeEvent,
FormEvent, useCallback,
FormEvent,
useCallback,
useContext,
useEffect,
useId,
useId, useRef,
useState,
} from 'react'
import {
Autocomplete, Box, Grid,
Autocomplete,
Box,
Grid,
IconButton,
InputAdornment,
InputLabel,
OutlinedInput, Typography,
OutlinedInput,
Typography,
styled,
} from '@mui/material'
import Search from '@mui/icons-material/Search'

import {catalogContext, configurationsContext, searchContext} from '../../contexts'
import * as React from "react";
import {
catalogContext,
configurationsContext,
searchContext,
} from '../../contexts'
import * as React from 'react'
import {
IGraphqlSearchProducts,
IGraphqlSearchProductsVariables,
ProductRequestType,
getSearchProductsQuery, joinUrlPath,
} from "@elastic-suite/gally-admin-shared";
import {useGraphqlApi} from "../../hooks";
import {IProduct} from "../../types";
getSearchProductsQuery,
joinUrlPath,
} from '@elastic-suite/gally-admin-shared'
import { useGraphqlApi } from '../../hooks'
import { IProduct } from '../../types'

const MIN_AUTOCOMPLETE_CHAR = 3

interface IProps {
shrink?: boolean
}

const StyledAutocomplete = styled(Autocomplete<IProduct, boolean, boolean, boolean>)(({ theme }) => ({
' .MuiInputBase-root': {
paddingRight: theme.spacing(1)
},
}))

/**
* Todo:
* régler les problèmes d'esline, typescripts et autre...
* terminer le style
*
*/

function SearchBar(props: IProps): JSX.Element {
const { shrink } = props
const searchId = useId()
const { onSearch, search: searchedText } = useContext(searchContext)
const { localizedCatalogId } = useContext(catalogContext)
const [search, setSearch] = useState('')
const controller = useRef<AbortController>()

const [products, setProducts, _load, debouncedLoad] = useGraphqlApi<IGraphqlSearchProducts>()
const [products, setProducts, _load, debouncedLoad] =
useGraphqlApi<IGraphqlSearchProducts>()
const baseUrl = useContext(configurationsContext)?.['base_url/media']

const options: IProduct[] = products.data?.products.collection.map((product) => {
return {
...product,
price: product.price?.[0]?.price,
}
}) ?? []
const options: IProduct[] =
products.data?.products.collection.map((product) => {
return {
...product,
price: product.price?.[0]?.price,
}
}) ?? []

console.log('render options', options)

const loadProducts = useCallback(
() => {
console.log('loadProducts', search)
if (localizedCatalogId) {
(querySearch: string) => {
console.log('loadProduct')
if (
localizedCatalogId &&
querySearch.trim() &&
querySearch.trim().length >= MIN_AUTOCOMPLETE_CHAR
) {
const variables: IGraphqlSearchProductsVariables = {
localizedCatalog: String(localizedCatalogId),
requestType: ProductRequestType.SEARCH,
currentPage: 1,
pageSize: 5,
search,
}
if (search) {
variables.search = search
search: querySearch,
}
console.log('dans le if')
controller.current = new AbortController()
return debouncedLoad(
getSearchProductsQuery(null, false),
variables as unknown as Record<string, unknown>
variables as unknown as Record<string, unknown>,
{signal: controller.current.signal}
)
}
console.log('setProduct(null)')
controller.current?.abort()
setProducts(null)
},
[
localizedCatalogId,
search,
debouncedLoad,
setProducts,
]
[localizedCatalogId, debouncedLoad, setProducts]
)
useEffect(() => {
setSearch(searchedText)
}, [searchedText])

useEffect(() => {
console.log('useEffect')
if (search && search.length >= MIN_AUTOCOMPLETE_CHAR) { // factoriser mettre ce bout de code dans onInputChange
console.log('useEffect - if', search)
loadProducts()
// setOptions(
// products.data?.products.collection.map((product) => {
// return {
// ...product,
// price: product.price?.[0]?.price,
// }
// }) ?? []
// )
console.log('useEffect - if', products)
} else {
setProducts(null)
}
console.log('useEffect', search)
loadProducts(search)
}, [loadProducts, search])

function handleSearchChange(_event: ChangeEvent<HTMLInputElement>, value: IProduct): void {
function handleSearchChange(
_event: ChangeEvent<HTMLInputElement>,
value: IProduct
): void {
console.log('handleSearchChange', value)
if (value) {
setSearch(value.name)
onSearch(value.name)
}
// let querySearch = ''
// if (value) {
// querySearch = value.name
// }
//
// setSearch(querySearch)
// if (querySearch.trim()) {
// onSearch(querySearch)
// }
}

function handleInputChange(
_event: React.SyntheticEvent,
value: string
): void {
console.log('handleInputChange', value)
setSearch(value)
}

function handleSubmit(event: FormEvent): void {
Expand All @@ -116,10 +147,9 @@ function SearchBar(props: IProps): JSX.Element {

return (
<form onSubmit={handleSubmit}>

<Autocomplete
<StyledAutocomplete
id={searchId}
sx={{ width: 300 }} // todo remplacer par du style comma à l'origine
sx={{ width: 280 }} // todo remplacer par du style comma à l'origine
getOptionLabel={(option): string =>
typeof option === 'string' ? option : option.name
}
Expand All @@ -130,16 +160,20 @@ function SearchBar(props: IProps): JSX.Element {
freeSolo
value={search}
onChange={handleSearchChange}
onInputChange={(_event, newInputSearch): void => {
console.log('onInputChange', newInputSearch)
setSearch(newInputSearch);
}}
renderInput={ ({InputLabelProps, InputProps, ...params}):React.ReactNode =>
onInputChange={handleInputChange}
renderInput={({
InputLabelProps,
InputProps,
...params
}): React.ReactNode => (
<>
<InputLabel {...InputLabelProps} shrink={shrink}>Search</InputLabel>
<InputLabel {...InputLabelProps} shrink={shrink}>
Search
</InputLabel>
<OutlinedInput
{...params}
{...InputProps}
sx={{ width: 281, paddingRight: 16}}
endAdornment={
<InputAdornment position="end">
<IconButton aria-label="search" edge="end" type="submit">
Expand All @@ -150,8 +184,8 @@ function SearchBar(props: IProps): JSX.Element {
label="Search"
/>
</>
}
renderOption={(props, option) :React.ReactNode =>
)}
renderOption={(props, option): React.ReactNode => (
<li {...props}>
<Grid container alignItems="center">
<Grid item sx={{ display: 'flex', width: 50 }}>
Expand All @@ -162,17 +196,18 @@ function SearchBar(props: IProps): JSX.Element {
src={joinUrlPath(baseUrl, option.image as string)}
/>
</Grid>
<Grid item sx={{ width: 'calc(100% - 50px)', wordWrap: 'break-word' }}>
<Box component="span">
{option.name}
</Box>
<Grid
item
sx={{ width: 'calc(100% - 50px)', wordWrap: 'break-word' }}
>
<Box component="span">{option.name}</Box>
<Typography variant="body2" color="text.secondary">
Sku: {option.sku} - ${option.price}
Sku: {option.sku} - ${option.price}
</Typography>
</Grid>
</Grid>
</li>
}
)}
/>
</form>
)
Expand Down

0 comments on commit 578b268

Please sign in to comment.