Skip to content

Instantly share code, notes, and snippets.

@cbilgili
Last active August 25, 2021 17:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cbilgili/c78f8e89515cd807f817f35d721570a6 to your computer and use it in GitHub Desktop.
Save cbilgili/c78f8e89515cd807f817f35d721570a6 to your computer and use it in GitHub Desktop.
Simple Chat with Hotwire Turbo Stimulusjs
<%= turbo_frame_tag "new_message", target: "_top" do %>
<%= form_with(model: [@message.room, @message], data: { controller: "reset-form", action: "turbo:submit-end->reset-form#reset" }) do |form| %>
<%= form.text_field :content, autocomplete: 'off', placeholder: 'Write your message...' %>
<%= button_tag(type: :submit) do %>
<i class="fa fa-paper-plane" aria-hidden="true"></i>
<% end %>
<%= form.submit "Send", data: {disable_with: false} %>
<% end %>
<% end %>
import { Controller } from "stimulus"
import { Turbo, cable } from "@hotwired/turbo-rails"
export default class extends Controller {
connect() {
console.log('connected');
this.initChannel();
this.scrollBottom();
}
initChannel() {
const channelName = document.querySelector("turbo-cable-stream-source").getAttribute('channel');
const signedStreamName = document.querySelector("turbo-cable-stream-source").getAttribute('signed-stream-name');
const scrollBottom = this.scrollBottom.bind(this)
this.channel = cable.subscribeTo({ 'channel': channelName, 'signed_stream_name': signedStreamName }, {
received(data) {
setTimeout(scrollBottom, 100);
}
});
}
reset() {
this.element.reset()
}
scrollBottom() {
console.log('scroll bottom');
document.querySelector("div.messages").scrollTop = document.querySelector("div.messages").scrollHeight
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment