Feat: Adding Search prefixes to homepage search

This commit is contained in:
arvanitakis committed 2026-10-19 17:32:35 +03:00
1 parent 623851bd70
commit 4f56edc4fc
6 files changed
+222 -5

No files matched your search

+41 -1
View File
@@ -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,
]);
}
}
+74
View File
@@ -0,0 +1,74 @@
<?php
namespace App\Support;
use Illuminate\Support\HtmlString;
use Normalizer;
/**
* Underlines the words of a product name that a search query matched, for
* the live search dropdown: every word starting with one of the query's
* words ("click" → "Edamame _Clicker_"), ignoring case and accents the way
* Meilisearch does ("παπ" → "_Παπάκι_"). Typo matches aren't marked — the
* name is shown as is.
*/
final class SearchHighlight
{
public static function name(string $name, string $query, string $class = 'underline underline-offset-4'): HtmlString
{
$terms = array_values(array_filter(preg_split('/[^\p{L}\p{N}]+/u', self::fold($query)) ?: []));
$chars = mb_str_split($name);
if ($terms === [] || $chars === []) {
return new HtmlString(e($name));
}
// One folded character per original one, so positions line up.
$folded = array_map(self::fold(...), $chars);
$html = '';
$i = 0;
$count = count($chars);
while ($i < $count) {
if (! self::isWordChar($chars[$i])) {
$html .= e($chars[$i++]);
continue;
}
$end = $i;
while ($end < $count && self::isWordChar($chars[$end])) {
$end++;
}
$word = implode('', array_slice($chars, $i, $end - $i));
$foldedWord = implode('', array_slice($folded, $i, $end - $i));
$matched = collect($terms)->contains(fn (string $term) => str_starts_with($foldedWord, $term));
$html .= $matched ? '<span class="'.e($class).'">'.e($word).'</span>' : e($word);
$i = $end;
}
return new HtmlString($html);
}
/**
* Lower case, without accents; Greek final sigma as σ.
*/
private static function fold(string $text): string
{
if (class_exists(Normalizer::class)) {
$text = preg_replace('/\p{Mn}+/u', '', Normalizer::normalize($text, Normalizer::FORM_D) ?: $text);
}
return strtr(mb_strtolower($text), [
'ά' => 'α', 'έ' => 'ε', 'ή' => 'η', 'ί' => 'ι', 'ό' => 'ο', 'ύ' => 'υ', 'ώ' => 'ω',
'ϊ' => 'ι', 'ϋ' => 'υ', 'ΐ' => 'ι', 'ΰ' => 'υ', 'ς' => 'σ',
]);
}
private static function isWordChar(string $char): bool
{
return (bool) preg_match('/[\p{L}\p{N}]/u', $char);
}
}
+19
View File
@@ -241,6 +241,25 @@ @layer components {
}
}
/* The page behind is dimmed while searching, fading with the overlay. */
#search-overlay::backdrop {
background-color: rgb(0 0 0 / 0);
transition:
background-color 0.2s ease,
display 0.2s allow-discrete,
overlay 0.2s allow-discrete;
}
#search-overlay:popover-open::backdrop {
background-color: rgb(0 0 0 / 0.3);
}
@starting-style {
#search-overlay:popover-open::backdrop {
background-color: rgb(0 0 0 / 0);
}
}
/* ── Shared underline-slide animation ────────────────────────── */
.underline-slide {
background-image: linear-gradient(currentColor, currentColor);
+30 -1
View File
@@ -4,8 +4,17 @@ import { Controller } from '@hotwired/stimulus'
// header has no fixed height below `lg`, so on open we copy its current height
// onto --search-overlay-h and move focus into the field. Escape / click-away
// close come from the Popover API; the fade is CSS (#search-overlay).
//
// Live search: as the shopper types (from minChars characters, after a short
// pause), the results frame under the bar loads the same /search endpoint the
// form submits to; SearchController answers that frame with the first few
// matches. Turbo cancels a frame's previous request when its src changes, so
// only the latest query's results land.
export default class extends Controller {
static targets = ['input']
static targets = ['input', 'form', 'results']
static values = { minChars: { type: Number, default: 3 } }
#timer = null
connect() {
this.element.addEventListener('toggle', this.#onToggle)
@@ -13,6 +22,26 @@ export default class extends Controller {
disconnect() {
this.element.removeEventListener('toggle', this.#onToggle)
clearTimeout(this.#timer)
}
suggest() {
clearTimeout(this.#timer)
this.#timer = setTimeout(() => this.#load(), 250)
}
#load() {
const query = this.inputTarget.value.trim()
if (query.length < this.minCharsValue) {
this.resultsTarget.removeAttribute('src')
this.resultsTarget.innerHTML = ''
return
}
const url = new URL(this.formTarget.action, window.location.href)
url.searchParams.set('q', query)
this.resultsTarget.src = url.toString()
}
#onToggle = (event) => {
@@ -4,18 +4,25 @@
close come for free). The header's search button opens it via popovertarget.
The `nav-search` controller measures the header on open (→ --search-overlay-h,
since the header isn't a fixed height below `lg`) and focuses the field.
Fade transition lives in app.css (#search-overlay).
Fade transition and the dimmed page behind live in app.css (#search-overlay).
Live search: from 3 characters, the `nav-search` controller points the
<turbo-frame id="search-suggestions"> under the bar at the same /search
endpoint, which answers that frame with the first few matches
(search/suggestions.blade.php). Enter still goes to the full results page.
--}}
<div
id="search-overlay"
popover
data-controller="nav-search"
class="fixed w-full inset-x-0 top-0 bottom-auto m-0 h-[var(--search-overlay-h)] border-0 bg-brand p-0"
data-nav-search-min-chars-value="{{ \App\Http\Controllers\SearchController::LIVE_MIN_CHARS }}"
class="fixed w-full inset-x-0 top-0 bottom-auto m-0 border-0 bg-transparent p-0"
>
<form
method="get"
action="{{ route('search') }}"
class="flex h-full items-center gap-6 px-10"
data-nav-search-target="form"
class="flex h-[var(--search-overlay-h)] items-center gap-6 bg-brand px-10"
>
<label for="search-overlay-input" class="sr-only">{{ __('storefront.shop.search_label') }}</label>
<input
@@ -25,6 +32,7 @@ class="flex h-full items-center gap-6 px-10"
required
autocomplete="off"
data-nav-search-target="input"
data-action="input->nav-search#suggest"
placeholder="{{ __('storefront.search.placeholder') }}"
class="min-w-0 flex-1 appearance-none border-0 border-b border-black bg-transparent pb-2 placeholder:text-black/60 focus:outline-none [&::-webkit-search-cancel-button]:appearance-none"
>
@@ -38,4 +46,6 @@ class="shrink-0 text-black transition-opacity hover:opacity-70"
<x-ui.icon name="close" :size="44" />
</button>
</form>
<turbo-frame id="search-suggestions" data-nav-search-target="results"></turbo-frame>
</div>
@@ -0,0 +1,45 @@
{{--
Live search results under the search overlay — the answer to its
<turbo-frame id="search-suggestions"> (SearchController::suggestions()).
Up to six products (thumbnail, name with the matched words underlined,
price), then a link to the full results page. Empty below 3 characters.
Vars: $query (string), $products (Collection of ProductCard arrays),
$total (int), $searched (bool)
--}}
<turbo-frame id="search-suggestions">
@if ($searched)
<div class="max-h-[calc(100dvh-var(--search-overlay-h))] overflow-y-auto bg-white border-b border-black">
@forelse ($products as $product)
<a
href="{{ $product['href'] }}"
data-turbo-frame="_top"
class="flex items-center gap-5 border-b border-neutral-300 px-10 py-4 transition-colors hover:bg-neutral-100 focus-visible:bg-neutral-100 focus-visible:outline-none"
>
<span class="flex aspect-[251/335] w-16 shrink-0 items-center justify-center overflow-hidden border border-black bg-white">
@if ($product['image'])
<img src="{{ $product['image'] }}" alt="" loading="lazy" class="block h-auto w-full">
@endif
</span>
<span class="min-w-0 flex-1">{{ \App\Support\SearchHighlight::name((string) $product['name'], $query) }}</span>
@if ($product['price'] !== null)
<span class="shrink-0"><x-ui.price :amount="$product['price']" /></span>
@endif
</a>
@empty
<p class="px-10 py-6 text-neutral-500">{{ __('storefront.shop.no_products') }}</p>
@endforelse
@if ($total > 0)
<a
href="{{ route('search', ['q' => $query]) }}"
data-turbo-frame="_top"
class="flex items-center justify-between px-10 py-5 font-medium uppercase tracking-wide transition-colors hover:bg-neutral-100 focus-visible:bg-neutral-100 focus-visible:outline-none"
>
{{ trans_choice('storefront.search.view_all', $total, ['count' => $total]) }}
<x-ui.icon name="arrow-right" :size="20" />
</a>
@endif
</div>
@endif
</turbo-frame>