import { Controller } from "@hotwired/stimulus"; // Connects to data-controller="comments-mercure" export default class extends Controller { static values = { coordinate: String } static targets = ["list", "loading"]; connect() { const coordinate = this.coordinateValue; const topic = `/comments/${coordinate}`; const hubUrl = window.MercureHubUrl || (document.querySelector('meta[name="mercure-hub"]')?.content); console.log('[comments-mercure] connect', { coordinate, topic, hubUrl }); if (!hubUrl) return; const url = new URL(hubUrl); url.searchParams.append('topic', topic); this.eventSource = new EventSource(url.toString()); this.eventSource.onopen = () => { console.log('[comments-mercure] EventSource opened', url.toString()); }; this.eventSource.onerror = (e) => { console.error('[comments-mercure] EventSource error', e); }; this.eventSource.onmessage = (event) => { console.log('[comments-mercure] Event received', event.data); const data = JSON.parse(event.data); this.profiles = data.profiles || {}; if (this.hasLoadingTarget) this.loadingTarget.style.display = 'none'; if (this.hasListTarget) { if (data.comments && data.comments.length > 0) { this.listTarget.innerHTML = data.comments.map((item) => { const zapData = this.parseZapAmount(item) || {}; const zapAmount = zapData.amount; const zapperPubkey = zapData.zapper; const parsedContent = this.parseContent(item.content); const isZap = item.kind === 9735; const displayPubkey = isZap ? (zapperPubkey || item.pubkey) : item.pubkey; const profile = this.profiles[displayPubkey]; const displayName = profile?.name || displayPubkey; return `