playa/staticfiles/playa/js/controllers/search_controller.js
Nicola Zangrandi 7bb8d8147d
Some checks failed
/ build (push) Failing after 33s
feat(playa): initial commit
2025-01-31 15:40:35 +01:00

73 lines
2.5 KiB
JavaScript

import { Controller } from "https://unpkg.com/@hotwired/stimulus@3.2.2/dist/stimulus.js"
export default class extends Controller {
static targets = ["input", "results", "loading", "addButton", "addSpinner", "message"]
static values = {
url: String
}
connect() {
this.timeout = null
document.addEventListener("turbo:before-fetch-request", () => this.showLoading())
document.addEventListener("turbo:before-fetch-response", () => this.hideLoading())
}
disconnect() {
document.removeEventListener("turbo:before-fetch-request", () => this.showLoading())
document.removeEventListener("turbo:before-fetch-response", () => this.hideLoading())
}
async addGame(event) {
event.preventDefault()
const form = event.target
const button = event.target.querySelector('button')
const spinner = event.target.querySelector('[data-search-target="addSpinner"]')
const message = event.target.querySelector('[data-search-target="message"]')
button.disabled = true
spinner.classList.remove('hidden')
message.textContent = ''
message.classList.add('hidden')
try {
const response = await fetch(form.action, {
method: 'POST',
body: new FormData(form),
headers: {
'X-CSRFToken': form.querySelector('[name="csrfmiddlewaretoken"]').value
}
})
const data = await response.json()
message.textContent = data.message
message.classList.remove('hidden', 'text-red-600')
message.classList.add(data.status === 'success' ? 'text-green-600' : 'text-red-600')
} catch (error) {
message.textContent = 'An error occurred while adding the game.'
message.classList.remove('hidden')
message.classList.add('text-red-600')
} finally {
button.disabled = false
spinner.classList.add('hidden')
}
}
search() {
clearTimeout(this.timeout)
this.timeout = setTimeout(() => {
const query = this.inputTarget.value
if (query.length > 2) {
const url = `${this.urlValue}?q=${encodeURIComponent(query)}`
Turbo.visit(url, { action: "replace" })
}
}, 300)
}
showLoading() {
this.loadingTarget.classList.remove("hidden")
}
hideLoading() {
this.loadingTarget.classList.add("hidden")
}
}