summaryrefslogtreecommitdiff
path: root/app/javascript/controllers/chat_controller.js
blob: d9cf1cb9380601189c60efd1f0394a987a71d5be (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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'
    });
  }
}