import { CocoComponent } from "@assets/js/base/coco"; export default CocoComponent("pollController", () => { return { polling: false, frame: null, pollTimer: null, get interval() { return parseInt(this.$root.dataset.interval || 0, 10); }, init() { this.frame = document.getElementById("polling-controller-frame"); this.observer = new MutationObserver(() => this.onUpdate()); this.observer.observe(this.$el, { attributes: true }); }, startPolling() { if (this.interval > 0 && !this.polling) { this.polling = true; this.queuePollRequest(500); } }, onUpdate() { this.$nextTick(() => { this.$dispatch("dom-updates:complete", { html: document }); // for compatability with legacy components }); this.queuePollRequest(); }, queuePollRequest(wait) { if (this.pollTimer) clearTimeout(this.pollTimer); if (this.interval > 0 && this.polling) { this.pollTimer = setTimeout( () => this.reloadFrame(), wait || this.interval ); } }, reloadFrame() { this.frame.addEventListener( "turbo:before-fetch-request", addStreamHeaders, { once: true } ); window.Turbo.visit(location.href, { frame: this.frame.id, action: "replace", }); }, destroy() { this.observer.disconnect(); this.polling = false; }, }; }); function addStreamHeaders(event) { const { headers } = event.detail.fetchOptions || {}; if (headers) { headers.Accept = ["text/vnd.turbo-stream.html", headers.Accept].join(", "); } }