-
Notifications
You must be signed in to change notification settings - Fork 37
feat: add SearchBar to Store on Client #1328
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
biliesilva
wants to merge
3
commits into
main
Choose a base branch
from
feat/add-search-bar-to-store-with-fuzzy-search
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 2 commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
e482940
feat: add SearchBarDiscover component and integrate into TopNavBar
biliesilva abaa608
feat(SearchBarDiscover): improve API integration and add debounce effect
biliesilva 9f3546c
refactor(SearchBarDiscover): remove unused state and optimize search …
biliesilva File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
81 changes: 81 additions & 0 deletions
81
src/frontend/components/UI/SearchBarDiscover/index.module.scss
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,81 @@ | ||
.SearchBar { | ||
grid-area: search; | ||
width: 48px; | ||
position: relative; | ||
display: inline-flex; | ||
border-radius: var(--space-3xs); | ||
padding: var(--space-3xs); | ||
background: none; | ||
transition: 250ms; | ||
border-radius: 1000px; | ||
} | ||
|
||
div.SearchBar:has(*:focus), | ||
div.SearchBar:has(input:not(:placeholder-shown)) { | ||
width: 500px; | ||
background: var(--background-base); | ||
} | ||
|
||
div.SearchBar:has(*:focus) > button, | ||
div.SearchBar:has(input:not(:placeholder-shown)) > button { | ||
border: transparent; | ||
} | ||
|
||
.autoComplete { | ||
position: absolute; | ||
top: 100%; | ||
max-height: 200px; | ||
width: 100%; | ||
background-color: var(--background-base); | ||
overflow: auto; | ||
list-style: none; | ||
margin: -2px -4px; | ||
display: none; | ||
padding: var(--space-xs) var(--space-md); | ||
text-align: left; | ||
overflow-x: hidden; | ||
z-index: 1000; | ||
border-radius: var(--space-sm); | ||
} | ||
|
||
.SearchBar:focus-within ul.autoComplete { | ||
display: block; | ||
} | ||
|
||
.autoComplete li { | ||
padding: var(--space-sm); | ||
} | ||
|
||
.autoComplete li:hover { | ||
cursor: pointer; | ||
} | ||
|
||
.searchButton { | ||
padding: var(--space-2xs) var(--space-2xs) 0 var(--space-2xs); | ||
} | ||
|
||
.clearSearchButton { | ||
padding-right: var(--space-md); | ||
transition: color 250ms; | ||
background: transparent; | ||
border: none; | ||
color: var(--text-weak); | ||
} | ||
|
||
.searchBarInput { | ||
width: 100%; | ||
appearance: none; | ||
background: transparent; | ||
color: var(--text-weak); | ||
padding: 0 var(--space-lg); | ||
border: none; | ||
outline: none; | ||
transition: color 250ms; | ||
} | ||
|
||
@media screen and (max-width: 1280px) { | ||
div.SearchBar:has(*:focus), | ||
div.SearchBar:has(input:not(:placeholder-shown)) { | ||
width: 243px; | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,241 @@ | ||
import React, { useEffect, useMemo, useRef, useState, useCallback } from 'react' | ||
import { useTranslation } from 'react-i18next' | ||
import { useNavigate } from 'react-router-dom' | ||
import './index.module.scss' | ||
import { faXmark } from '@fortawesome/free-solid-svg-icons' | ||
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' | ||
import { Images } from '@hyperplay/ui' | ||
import TopNavBarStyles from '../TopNavBar/index.module.scss' | ||
import Fuse from 'fuse.js' | ||
|
||
type ListingApi = { | ||
project_meta?: { name?: string } | ||
project_name?: string | ||
id?: string | ||
project_id?: string | ||
account_name?: string | ||
account_meta?: { name?: string } | ||
} | ||
|
||
type GameResult = { | ||
title: string | ||
appId: string | ||
storeUrl: string | ||
accountName: string | ||
projectName: string | ||
} | ||
|
||
export default function SearchBarDiscover() { | ||
const { t } = useTranslation() | ||
const navigate = useNavigate() | ||
const input = useRef<HTMLInputElement>(null) | ||
const [filterText, setFilterText] = useState('') | ||
const [allGames, setAllGames] = useState<GameResult[]>([]) | ||
const [searchResults, setSearchResults] = useState<GameResult[]>([]) | ||
const [loading, setLoading] = useState(false) | ||
const [searching, setSearching] = useState(false) | ||
|
||
useEffect(() => { | ||
let ignore = false | ||
const fetchGames = async () => { | ||
setLoading(true) | ||
try { | ||
const res = await fetch( | ||
'https://developers.hyperplay.xyz/api/v2/listings?pageSize=100' | ||
) | ||
const data = await res.json() | ||
|
||
const listings = Array.isArray(data) ? data : [] | ||
const mapped: GameResult[] = listings | ||
.map((listing: ListingApi) => ({ | ||
title: | ||
(listing.project_meta?.name ?? | ||
listing.project_name ?? | ||
listing.id) || | ||
'', | ||
appId: | ||
(listing.project_id ?? listing.id ?? listing.project_name) || '', | ||
storeUrl: | ||
listing.account_name && listing.project_name | ||
? `/store/game/${listing.account_name}/${listing.project_name}` | ||
: '', | ||
accountName: | ||
listing.account_name || listing.account_meta?.name || '', | ||
projectName: listing.project_name || '' | ||
})) | ||
.filter( | ||
(game) => | ||
game.title && | ||
game.title.trim() !== '' && | ||
game.accountName && | ||
game.projectName | ||
) | ||
if (!ignore) { | ||
setAllGames(mapped) | ||
console.log('Total games loaded:', mapped.length) | ||
console.log('Sample games:', mapped.slice(0, 3)) | ||
biliesilva marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
} | ||
} catch (e) { | ||
if (!ignore) setAllGames([]) | ||
} finally { | ||
if (!ignore) setLoading(false) | ||
} | ||
} | ||
fetchGames() | ||
return () => { | ||
ignore = true | ||
} | ||
}, []) | ||
|
||
const searchGames = async (searchText: string) => { | ||
if (!searchText.trim()) { | ||
setSearchResults([]) | ||
return | ||
} | ||
|
||
setSearching(true) | ||
try { | ||
const res = await fetch( | ||
`https://developers.hyperplay.xyz/api/v2/listings?search=${encodeURIComponent( | ||
searchText | ||
)}&pageSize=20` | ||
) | ||
const data = await res.json() | ||
|
||
const listings = Array.isArray(data) ? data : [] | ||
const mapped: GameResult[] = listings | ||
.map((listing: ListingApi) => ({ | ||
title: | ||
(listing.project_meta?.name ?? | ||
listing.project_name ?? | ||
listing.id) || | ||
'', | ||
appId: | ||
(listing.project_id ?? listing.id ?? listing.project_name) || '', | ||
storeUrl: | ||
listing.account_name && listing.project_name | ||
? `/store/game/${listing.account_name}/${listing.project_name}` | ||
: '', | ||
accountName: listing.account_name || listing.account_meta?.name || '', | ||
projectName: listing.project_name || '' | ||
})) | ||
.filter( | ||
(game) => | ||
game.title && | ||
game.title.trim() !== '' && | ||
game.accountName && | ||
game.projectName | ||
) | ||
|
||
setSearchResults(mapped) | ||
} catch (e) { | ||
console.error('Search error:', e) | ||
setSearchResults([]) | ||
} finally { | ||
setSearching(false) | ||
} | ||
} | ||
|
||
// Debounce effect | ||
useEffect(() => { | ||
const timeoutId = setTimeout(() => { | ||
if (filterText.trim()) { | ||
searchGames(filterText) | ||
} else { | ||
setSearchResults([]) | ||
} | ||
}, 300) // 300ms | ||
biliesilva marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
return () => clearTimeout(timeoutId) | ||
}, [filterText]) | ||
|
||
const fuse = useMemo(() => { | ||
biliesilva marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
return new Fuse(allGames, { | ||
keys: ['title', 'accountName', 'projectName', 'appId'], | ||
threshold: 0.4, | ||
includeScore: true, | ||
minMatchCharLength: 1, | ||
ignoreLocation: true, | ||
useExtendedSearch: true, | ||
findAllMatches: true | ||
}) | ||
}, [allGames]) | ||
|
||
const filteredGames = useMemo(() => { | ||
biliesilva marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
if (!filterText) return [] | ||
|
||
const localResult = fuse.search(filterText) | ||
const localGames = localResult | ||
.sort((a, b) => a.score! - b.score!) | ||
.slice(0, 5) | ||
.map((item) => item.item) | ||
|
||
const apiGames = searchResults.filter( | ||
(apiGame) => | ||
!localGames.some((localGame) => localGame.appId === apiGame.appId) | ||
) | ||
|
||
return [...localGames, ...apiGames].slice(0, 10) | ||
}, [fuse, filterText, searchResults]) | ||
|
||
const showAutoComplete = filteredGames.length > 0 && filterText.length > 0 | ||
|
||
const onClear = useCallback(() => { | ||
biliesilva marked this conversation as resolved.
Show resolved
Hide resolved
|
||
setFilterText('') | ||
if (input.current) { | ||
input.current.value = '' | ||
input.current.focus() | ||
} | ||
}, [input]) | ||
|
||
function handleGameClick(game: GameResult) { | ||
navigate( | ||
`/store-page?store-url=https://store.hyperplay.xyz/game/${game.accountName}/${game.projectName}`, | ||
biliesilva marked this conversation as resolved.
Show resolved
Hide resolved
|
||
{ | ||
state: { | ||
fromHyperPlayStore: true | ||
} | ||
} | ||
) | ||
} | ||
|
||
return ( | ||
<div className="SearchBar" data-testid="searchBar"> | ||
<button | ||
className={TopNavBarStyles.iconButton} | ||
onClick={() => input.current?.focus()} | ||
> | ||
<Images.MagnifyingGlass fill="var(--icon-neutral)" /> | ||
</button> | ||
<input | ||
ref={input} | ||
data-testid="searchInput" | ||
placeholder={t('search')} | ||
id="search" | ||
className="searchBarInput" | ||
value={filterText} | ||
onChange={(e) => setFilterText(e.target.value)} | ||
/> | ||
{loading} | ||
{searching} | ||
{showAutoComplete ? ( | ||
<> | ||
<ul className="autoComplete body-sm"> | ||
{filteredGames.map((game) => ( | ||
<li | ||
key={game.appId} | ||
className="search-result-item" | ||
onClick={() => handleGameClick(game)} | ||
> | ||
{game.title} | ||
</li> | ||
))} | ||
</ul> | ||
<button className="clearSearchButton" onClick={onClear} tabIndex={-1}> | ||
<FontAwesomeIcon icon={faXmark} /> | ||
</button> | ||
</> | ||
) : null} | ||
</div> | ||
) | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.