import { Controller } from '@hotwired/stimulus' // The search overlay is a [popover] that must sit exactly over the header. The // 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', 'form', 'results'] static values = { minChars: { type: Number, default: 3 } } #timer = null connect() { this.element.addEventListener('toggle', this.#onToggle) } 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) => { if (event.newState !== 'open') return const header = this.element.closest('header') if (header) { this.element.style.setProperty('--search-overlay-h', `${header.offsetHeight}px`) } requestAnimationFrame(() => this.inputTarget.focus()) } }