From 9415011b5fd192f1bafeaa9b6eacbb7921382a00 Mon Sep 17 00:00:00 2001 From: David Gay Date: Wed, 19 May 2021 22:53:38 -0400 Subject: Chat --- app/javascript/channels/chat_room_channel.js | 22 ++++++++++++++ app/javascript/controllers/chat_controller.js | 42 +++++++++++++++++++++++++++ 2 files changed, 64 insertions(+) create mode 100644 app/javascript/channels/chat_room_channel.js create mode 100644 app/javascript/controllers/chat_controller.js (limited to 'app/javascript') diff --git a/app/javascript/channels/chat_room_channel.js b/app/javascript/channels/chat_room_channel.js new file mode 100644 index 0000000..8dfa47f --- /dev/null +++ b/app/javascript/channels/chat_room_channel.js @@ -0,0 +1,22 @@ +import consumer from "./consumer" + +consumer.subscriptions.create("ChatRoomChannel", { + connected() { + // Called when the subscription is ready for use on the server + }, + + disconnected() { + // Called when the subscription has been terminated by the server + }, + + received(data) { + // Called when there's incoming data on the websocket for this channel + var node = document.createElement("P"); + node.innerHTML = data.html; + var chatOutputElement = document.getElementById("chat_output"); + chatOutputElement.appendChild(node); + chatOutputElement.scrollTo({ + top: chatOutputElement.scrollHeight, left: 0, behavior: 'smooth' + }); + } +}); diff --git a/app/javascript/controllers/chat_controller.js b/app/javascript/controllers/chat_controller.js new file mode 100644 index 0000000..d9cf1cb --- /dev/null +++ b/app/javascript/controllers/chat_controller.js @@ -0,0 +1,42 @@ +import { Controller } from "stimulus"; + +export default class extends Controller { + static targets = [ "message", "output" ]; + + connect() { + this.load(); + } + + send() { + let vm = this; + // TODO: Temporary hack. Should just run this after default event. + setTimeout(function() { + vm.messageTarget.value = ""; + vm.smoothScrollToBottom(); + }, 100); + } + + load() { + this.scrollToBottom(); + if (this.outputTarget.innerHTML.trim() === "") { + fetch("/chat_messages") + .then(response => response.text()) + .then(html => { + this.outputTarget.innerHTML = html; + this.scrollToBottom(); + }); + } + } + + scrollToBottom() { + this.outputTarget.scrollTop = this.outputTarget.scrollHeight; + } + + smoothScrollToBottom() { + this.outputTarget.scrollTo({ + top: this.outputTarget.scrollHeight, + left: 0, + behavior: 'smooth' + }); + } +} -- cgit v1.2.3