Files
akkounts/app/javascript/controllers/nostr_continue_controller.js

64 lines
1.5 KiB
JavaScript

import { Controller } from "@hotwired/stimulus"
const POLL_INTERVAL = 1500
const MAX_ATTEMPTS = 120
export default class extends Controller {
static targets = [ "status", "error" ]
static values = { statusUrl: String }
connect () {
this.attempts = 0
this.stopped = false
this.poll()
}
disconnect () {
this.stopped = true
clearTimeout(this.timer)
}
async poll () {
if (this.stopped) return
this.attempts += 1
try {
const response = await fetch(this.statusUrlValue, {
credentials: "include",
headers: { "Accept": "application/json" }
})
const data = await response.json().catch(() => ({}))
if (data.status === "connected") {
this.statusTarget.textContent = "Signed in. Redirecting…"
window.location.href = data.redirect_url || "/"
return
}
if (!response.ok || data.status === "failed" || data.status === "expired") {
this.showError(data.error || "Login failed. Please try again.")
return
}
if (this.attempts >= MAX_ATTEMPTS) {
this.showError("Timed out waiting for your signer. Please try again.")
return
}
this.timer = setTimeout(() => this.poll(), POLL_INTERVAL)
} catch (error) {
if (this.attempts >= MAX_ATTEMPTS) {
this.showError(error.message)
return
}
this.timer = setTimeout(() => this.poll(), POLL_INTERVAL)
}
}
showError (message) {
this.errorTarget.textContent = message
this.errorTarget.classList.remove("hidden")
}
}