Skip to content

Commit

Permalink
Draft
Browse files Browse the repository at this point in the history
  • Loading branch information
botisSmile committed Oct 5, 2023
1 parent 1f586e8 commit 2276d25
Showing 1 changed file with 105 additions and 41 deletions.
146 changes: 105 additions & 41 deletions front/example-app/src/components/SearchBar/SearchBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,33 +21,57 @@ import {
import Search from '@mui/icons-material/Search'

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

const MIN_AUTOCOMPLETE_CHAR = 3

interface IProps {
shrink?: boolean
}

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

function getCategoryPathLabel(path: string[], categories: ICategory[], separator = '/'): string
{
let label = ''
console.log('path', path)
if (path.length > 0) {
const category = categories.find((category: ICategory) => category.id === path[0])
path.shift()
console.log('newPath', path)
// label = category?.name +
// (category?.children.length > 0 ? '/' : '') +
// getCategoryPathLabel(path, category?.children ?? [], separator)
label = `${category?.name}/${getCategoryPathLabel(path, category.children, separator)}`
}

return label.split('/').join(' / ');
}

/**
* Todo:
* régler les problèmes d'esline, typescripts et autre...
Expand All @@ -64,43 +88,68 @@ function SearchBar(props: IProps): JSX.Element {
const controller = useRef<AbortController>()

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


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

console.log('render options', options)
options.concat(products.data?.categories.collection ?? [])

options = products.data?.categories.collection ?? [];


console.log('options', options)
console.log('categorues', products.data?.categories.collection ?? [])

// console.log('render options', options)

const loadProducts = useCallback(
(querySearch: string) => {
console.log('loadProduct')
// console.log('loadProduct')
if (
localizedCatalogId &&
querySearch.trim() &&
querySearch.trim().length >= MIN_AUTOCOMPLETE_CHAR
) {
const variables: IGraphqlSearchProductsVariables = {
const productVariables: IGraphqlSearchProductsVariables = {
localizedCatalog: String(localizedCatalogId),
requestType: ProductRequestType.SEARCH,
currentPage: 1,
pageSize: 5,
search: querySearch,
}
console.log('dans le if')

const categoryVariables: IGraphqlSearchDocumentsVariables = {
entityType: 'category',
localizedCatalog: String(localizedCatalogId),
currentPage: 1,
pageSize: 5,
search: querySearch,
}

const variables = {
...productVariables,
...addPrefixKeyObject(categoryVariables, 'category')
}

// console.log('dans le if')
controller.current = new AbortController()
return debouncedLoad(
getSearchProductsQuery(null, false),
variables as unknown as Record<string, unknown>,
{signal: controller.current.signal}
)
}
console.log('setProduct(null)')
// console.log('setProduct(null)')
controller.current?.abort()
setProducts(null)
},
Expand All @@ -111,47 +160,47 @@ function SearchBar(props: IProps): JSX.Element {
}, [searchedText])

useEffect(() => {
console.log('useEffect', search)
// console.log('useEffect', search)
loadProducts(search)
}, [loadProducts, search])

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

function handleSubmit(event: FormEvent): void {
event.preventDefault()
console.log('submit', search)
// console.log('submit', search)
onSearch(search)
}

return (
<form onSubmit={handleSubmit}>
<StyledAutocomplete
id={searchId}
sx={{ width: 280 }} // todo remplacer par du style comma à l'origine
sx={{ width: 280 }} // todo remplacer par du style comme à l'origine
getOptionLabel={(option): string =>
typeof option === 'string' ? option : option.name
typeof option === 'string' ? option : 'sku' in option ? option.name : option.id
}
filterOptions={(x: IProduct[]): IProduct[] => x}
options={options}
Expand Down Expand Up @@ -188,23 +237,38 @@ function SearchBar(props: IProps): JSX.Element {
renderOption={(props, option): React.ReactNode => (
<li {...props}>
<Grid container alignItems="center">
<Grid item sx={{ display: 'flex', width: 50 }}>
<img
height="50px"
style={{ objectFit: 'contain' }}
alt={option.name}
src={joinUrlPath(baseUrl, option.image as string)}
/>
</Grid>
<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}
</Typography>
</Grid>
{'sku' in option &&
<>
<Grid item sx={{ display: 'flex', width: 50 }}>
<img
height="50px"
style={{ objectFit: 'contain' }}
alt={option.name}
src={joinUrlPath(baseUrl, option.image as string)}
/>
</Grid>
<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}
</Typography>
</Grid>
</>}
{'source' in option &&

<Grid
item
sx={{ width: 'calc(100% - 50px)', wordWrap: 'break-word' }}
>
<Box component="span">{option.source.name }</Box>
<Typography variant="body2" color="text.secondary">
<Box component="span">{getCategoryPathLabel((option.source.path as string).split('/'), categories)}</Box>
</Typography>
</Grid>
}
</Grid>
</li>
)}
Expand Down

0 comments on commit 2276d25

Please sign in to comment.