CharrafiMed / global-search-modal

Enhances filamentphp's global search by transforming it into a modal for a better user experience
https://filamentphp.com/plugins/charrafimed-global-search-modal
84 stars 19 forks source link

Unnecessary queries when search is empty #74

Closed vittosheva closed 1 week ago

vittosheva commented 3 weeks ago

After Installing your package and configuring GlobalSearch for almost every Resource in my project (more than 20), I noticed slowness. So using Laravel Debugbar I discover an unusual number of queries, even though when I didn't start searching anything.

So, I'm trying to help with a little modification to your Livewire GlobalSearchModal component. After this change the site don't make unnecessary queries. Obviously when you search is when you'll be using that queries.

Hope it helps.

public function getResults(): ?GlobalSearchResults
{
        // Early return if the search is empty
        $search = trim($this->search);

        // THIS IS MY SOLUTION
        if (empty($this->search)) {
            return null;
        }
        // THIS IS MY SOLUTION

        $results = Filament::getGlobalSearchProvider()->getResults($search);

        if (!$results || !$this->getConfigs()->isMustHighlightQueryMatches()) {
            return $results;
        }

        $classes = $this->getConfigs()->getHighlightQueryClasses() ?? 'text-primary-500 font-semibold hover:underline';
        $styles = $this->getConfigs()->getHighlightQueryStyles() ?? '';

        // Apply highlighting to search results
        foreach ($results->getCategories() as &$categoryResults) {
            foreach ($categoryResults as &$result) {
                $result->highlightedTitle = Highlighter::make(
                    text: $result->title,
                    pattern: $search,
                    styles: $styles,
                    classes: $classes
                );
            }
        }

        return $results;
}
CharrafiMed commented 2 weeks ago

hey @vittosheva! Try to start the search by clicking the space on your keyboard. did you notice something?