import { Controller } from 'stimulus' import { Liquid } from 'liquidjs' const lunr = require("lunr") require("lunr-languages/lunr.stemmer.support")(lunr) require("lunr-languages/lunr.es")(lunr) export default class extends Controller { static targets = [ 'q' ] connect () { this.element.addEventListener('submit', async event => { event.stopPropagation() event.preventDefault() this.search() }) const q = window.location.search.match(/^\?q=(?.*)&?/) if (q) this.qTarget.value = decodeURI(q.groups.q) // There can only be one if (!window.search_fetching) this.fetch() } async search () { const q = this.qTarget.value if (!q || q === '') return const main = document.querySelector('main') const results = window.index.search(q).map(r => window.data.find(a => a.id == r.ref)) const site = await this.site() const request = await fetch('assets/templates/results.html') const template = await request.text() const html = await this.engine.parseAndRender(template, { q, site, results }) const title = `${site.i18n.search.title} - ${q}` window.history.pushState({ q }, title, `?q=${encodeURI(q)}`) document.title = title main.innerHTML = html } async fetch () { window.search_fetching = true let response if (!window.data) { response = await fetch('data.json') window.data = await response.json() } if (!window.index) { response = await fetch('idx.json') const idx = await response.json() window.index = lunr.Index.load(idx) } if (this.qTarget.value !== '') this.search() } /* * Liquid renderer * * @return Liquid */ get engine () { if (!window.liquid) window.liquid = new Liquid() return window.liquid } async site () { if (!window.site) { const data = await fetch('assets/data/site.json') window.site = await data.json() } return window.site } }