|
| 1 | +import { Controller } from "@hotwired/stimulus" |
| 2 | + |
| 3 | +export default class extends Controller { |
| 4 | + static values = { |
| 5 | + url: String, |
| 6 | + playing: Boolean |
| 7 | + } |
| 8 | + |
| 9 | + static targets = ["audio", "button", "prompt"] |
| 10 | + |
| 11 | + connect() { |
| 12 | + // If music was playing when page loaded, try to start it |
| 13 | + if (this.playingValue && this.hasAudioTarget) { |
| 14 | + this.audioTarget.play().then(() => { |
| 15 | + if (this.hasPromptTarget) this.promptTarget.classList.add("hidden") |
| 16 | + }).catch(e => { |
| 17 | + console.log("[Music] Autoplay blocked on connect:", e) |
| 18 | + // Show prompt for user to enable audio |
| 19 | + if (this.hasPromptTarget) this.promptTarget.classList.remove("hidden") |
| 20 | + }) |
| 21 | + } |
| 22 | + } |
| 23 | + |
| 24 | + toggle() { |
| 25 | + const isPlaying = !this.audioTarget.paused |
| 26 | + |
| 27 | + // Update UI immediately for responsive feel |
| 28 | + if (isPlaying) { |
| 29 | + this.audioTarget.pause() |
| 30 | + if (this.hasButtonTarget) delete this.buttonTarget.dataset.playing |
| 31 | + if (this.hasPromptTarget) this.promptTarget.classList.add("hidden") |
| 32 | + } else { |
| 33 | + this.audioTarget.play().catch(e => console.log("[Music] Autoplay blocked:", e)) |
| 34 | + if (this.hasButtonTarget) this.buttonTarget.dataset.playing = "true" |
| 35 | + } |
| 36 | + |
| 37 | + // Persist to server (will broadcast to other clients) |
| 38 | + fetch(this.urlValue, { |
| 39 | + method: "PATCH", |
| 40 | + headers: { |
| 41 | + "Content-Type": "application/json", |
| 42 | + "X-CSRF-Token": document.querySelector('meta[name="csrf-token"]').content |
| 43 | + } |
| 44 | + }) |
| 45 | + } |
| 46 | + |
| 47 | + // Called when participant clicks the "enable audio" prompt |
| 48 | + enableAudio() { |
| 49 | + if (this.hasAudioTarget) { |
| 50 | + this.audioTarget.play().then(() => { |
| 51 | + if (this.hasPromptTarget) this.promptTarget.classList.add("hidden") |
| 52 | + if (this.hasButtonTarget) this.buttonTarget.dataset.playing = "true" |
| 53 | + }).catch(e => console.log("[Music] Still blocked:", e)) |
| 54 | + } |
| 55 | + } |
| 56 | +} |
0 commit comments