import { Controller } from "@hotwired/stimulus" import { createConsumer } from "@rails/actioncable" export default class extends Controller { static values = { boardId: Number, currentParticipantId: Number } connect() { this.channel = createConsumer().subscriptions.create( { channel: "BoardChannel", board_id: this.boardIdValue }, { received: (data) => { this._insertMessage(data) } } ) this.element.scrollTop = this.element.scrollHeight } disconnect() { if (this.channel) { this.channel.unsubscribe() } } _insertMessage(data) { const isMe = data.participant_id === this.currentParticipantIdValue // 最初の投稿の場合、"まだ投稿がありません"メッセージを消す const noPostsMessage = document.getElementById("no-posts-message") if (noPostsMessage) { noPostsMessage.remove() } const html = `
` this.element.insertAdjacentHTML('afterbegin', html) // this.element.scrollTop = 0 // 必要ならトップへスクロール } _escapeHtml(unsafe) { return unsafe .replace(/&/g, "&") .replace(//g, ">") .replace(/"/g, """) .replace(/'/g, "'") } }