Feat: Adding Search prefixes to homepage search
This commit is contained in:
1 parent
623851bd70
commit
4f56edc4fc
6 files changed
+222
-5
No files matched your search
@@ -2,17 +2,34 @@
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Catalog\ProductCard;
|
||||
use App\Catalog\ProductListing;
|
||||
use App\Catalog\ProductListingPage;
|
||||
use Modules\Core\Catalog\Services\ProductSearchService;
|
||||
|
||||
class SearchController extends Controller
|
||||
{
|
||||
public function __construct(private readonly ProductListingPage $listingPage) {}
|
||||
/** Live search answers from this many characters on. */
|
||||
public const LIVE_MIN_CHARS = 3;
|
||||
|
||||
/** How many products the live search dropdown lists. */
|
||||
private const LIVE_LIMIT = 6;
|
||||
|
||||
public function __construct(
|
||||
private readonly ProductListingPage $listingPage,
|
||||
private readonly ProductSearchService $search,
|
||||
) {}
|
||||
|
||||
public function show(string $locale)
|
||||
{
|
||||
$query = trim((string) request()->query('q', ''));
|
||||
|
||||
// The search overlay's live results: the same endpoint, asked for by
|
||||
// its <turbo-frame id="search-suggestions"> as the shopper types.
|
||||
if (request()->header('Turbo-Frame') === 'search-suggestions') {
|
||||
return $this->suggestions($query);
|
||||
}
|
||||
|
||||
if ($query === '') {
|
||||
return redirect()->route('products');
|
||||
}
|
||||
@@ -28,4 +45,27 @@ public function show(string $locale)
|
||||
|
||||
return view('search.index', [...$data, 'query' => $query]);
|
||||
}
|
||||
|
||||
/**
|
||||
* The first few matches and how many there are in all — the dropdown
|
||||
* under the search overlay. Empty below LIVE_MIN_CHARS characters.
|
||||
*/
|
||||
private function suggestions(string $query)
|
||||
{
|
||||
$products = collect();
|
||||
$total = 0;
|
||||
|
||||
if (mb_strlen($query) >= self::LIVE_MIN_CHARS) {
|
||||
$result = $this->search->search($query, perPage: self::LIVE_LIMIT);
|
||||
$products = collect($result->products->items())->map(ProductCard::fromIndexed(...));
|
||||
$total = $result->products->total();
|
||||
}
|
||||
|
||||
return view('search.suggestions', [
|
||||
'query' => $query,
|
||||
'products' => $products,
|
||||
'total' => $total,
|
||||
'searched' => mb_strlen($query) >= self::LIVE_MIN_CHARS,
|
||||
]);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user