Files
3dealer/resources/js/stimulus/nav-search-controller.js

107 lines
3.8 KiB
JavaScript

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.
//
// ARIA combobox: the input keeps focus while ArrowUp/ArrowDown move
// aria-selected over the options (aria-activedescendant points at the current
// one) and Enter follows it; with nothing highlighted, Enter submits the form
// as usual. Each load's hidden summary is copied into the persistent
// role="status" region so screen readers announce the result count.
export default class extends Controller {
static targets = ['input', 'form', 'results', 'status', 'summary', 'listbox', 'option']
static values = { minChars: { type: Number, default: 3 } }
#timer = null
#active = -1
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 = ''
this.statusTarget.textContent = ''
return
}
const url = new URL(this.formTarget.action, window.location.href)
url.searchParams.set('q', query)
this.resultsTarget.src = url.toString()
}
navigate(event) {
const options = this.optionTargets
if (options.length === 0) return
if (event.key === 'ArrowDown') {
event.preventDefault()
this.#highlight((this.#active + 1) % options.length)
} else if (event.key === 'ArrowUp') {
event.preventDefault()
this.#highlight(this.#active <= 0 ? options.length - 1 : this.#active - 1)
} else if (event.key === 'Enter' && this.#active >= 0) {
event.preventDefault()
options[this.#active].click()
}
}
summaryTargetConnected(summary) {
this.statusTarget.textContent = summary.textContent
}
listboxTargetConnected() {
this.#active = -1
this.inputTarget.setAttribute('aria-expanded', 'true')
this.inputTarget.removeAttribute('aria-activedescendant')
}
listboxTargetDisconnected() {
this.#active = -1
this.inputTarget.setAttribute('aria-expanded', 'false')
this.inputTarget.removeAttribute('aria-activedescendant')
}
#highlight(index) {
this.#active = index
this.optionTargets.forEach((option, i) => option.setAttribute('aria-selected', String(i === index)))
const option = this.optionTargets[index]
this.inputTarget.setAttribute('aria-activedescendant', option.id)
option.scrollIntoView({ block: 'nearest' })
}
#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())
}
}