CloudCannon / pagefind

Static low-bandwidth search at scale
https://pagefind.app
MIT License
3.22k stars 97 forks source link

UI: Allow to specify number of loaded results with triggerSearch method #571

Open Dasbando opened 4 months ago

Dasbando commented 4 months ago

I started implementing a query url parameter with the default UI on my website, so you can return to the results page to look at other results if you didn't find what you are looking for. The implementation isn't pretty, but it has mostly worked well. The only issue I encountered is that I have no way to tell the UI to load the same number of results that were loaded previously, so the user has to manually click "load more" and scroll to the result they looked at previously.

flyfoto commented 4 months ago

I would like this too, if it allows to share prepared queries with other people as a link. Where could I try your solution? Can you share your code and tell about its dependencies?

Dasbando commented 4 months ago

The basic idea is to get the input field e.g. via its class and attach an event listener that replaces the history state with the modified URL. Then you can just call triggerSearch when the site loads. Maybe I'll put together an example that doesn't depend on my framework and internal code.

Dasbando commented 4 months ago

@flyfoto

window.addEventListener('DOMContentLoaded', (event) => {
    const pagefindUi = new PagefindUI({ element: '#search' })

    const url = new URL(location.href)

    const input = document.querySelector('#search input')
    input.addEventListener('input', updateUrlParameter)
    const button = document.querySelector('#search button')
    button.addEventListener('click', updateUrlParameter)
    function updateUrlParameter(e) {
        if (input.value) url.searchParams.set('q', input.value)
        else url.searchParams.delete('q')
        history.replaceState(history.state, '', url)
    }

    pagefindUi.triggerSearch(url.searchParams.get('q'))
})
bglw commented 3 months ago

Nice, the addition of a loadResults count to the triggerSearch function is definitely achievable!

flyfoto commented 3 months ago

Thanks for the code sample @Dasbando - this works well for me! However I tired to store the filter conditions as well in the URL. I managed this part but could not figure out how to build them again and pass them to the PagefindUI?

Any ideas anyone?