82 lines
2.1 KiB
Elixir
82 lines
2.1 KiB
Elixir
|
|
<div class="row justify-content-md-center my-3">
|
||
|
|
<div class="col-8">
|
||
|
|
<textarea rows="5" class="form-control" id="messageInput" placeholder="Message..."></textarea>
|
||
|
|
<button type="button" class="btn btn-primary my-2" id="sendButton" disabled>Send</button>
|
||
|
|
</div>
|
||
|
|
</div>
|
||
|
|
|
||
|
|
<div class="row justify-content-md-center">
|
||
|
|
<div class="col-8">
|
||
|
|
<ul id="messageOutput">
|
||
|
|
<%= for m <- @messages do %>
|
||
|
|
<li id="<%= m.id %>">
|
||
|
|
<p><a href="#<% m.id%>">>><%= m.id %></a> <%= m.inserted_at %></p>
|
||
|
|
<p><%= m.text %></p>
|
||
|
|
</li>
|
||
|
|
<% end %>
|
||
|
|
</ul>
|
||
|
|
</div>
|
||
|
|
</div>
|
||
|
|
|
||
|
|
<script type="text/javascript">
|
||
|
|
let input;
|
||
|
|
$(document).ready(() => {
|
||
|
|
const NEW_MSG = "new_msg";
|
||
|
|
let room = window.room;
|
||
|
|
let socket = window.socket;
|
||
|
|
let channel = socket.channel("room:" + room, {});
|
||
|
|
channel.join()
|
||
|
|
.receive("ok", resp => console.log("Joined successfully", resp))
|
||
|
|
.receive("error", resp => console.log("Could not join", resp));
|
||
|
|
input = $("#messageInput")[0];
|
||
|
|
let output = $("#messageOutput");
|
||
|
|
let sendbutton = $("#sendButton")[0];
|
||
|
|
|
||
|
|
function sendMessage() {
|
||
|
|
try {
|
||
|
|
let message_text = input.value;
|
||
|
|
// empty and space-only messages not allowed
|
||
|
|
if (message_text.match(/^[\s]*$/m)) {
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
try {
|
||
|
|
input.disabled = true;
|
||
|
|
channel.push(NEW_MSG, {body: message_text});
|
||
|
|
} finally {
|
||
|
|
input.value = "";
|
||
|
|
}
|
||
|
|
} finally {
|
||
|
|
input.disabled = false;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
channel.on(NEW_MSG, payload => {
|
||
|
|
console.log(payload);
|
||
|
|
let body = payload.body;
|
||
|
|
let now = new Date();
|
||
|
|
let messageItem = $("<li>").html(
|
||
|
|
`<p>${now.toISOString()}</p><p>${body}</p>`
|
||
|
|
);
|
||
|
|
output.prepend(messageItem);
|
||
|
|
});
|
||
|
|
|
||
|
|
input.onkeydown = (e => {
|
||
|
|
if (e.keyCode == 13 && e.shiftKey) {
|
||
|
|
sendMessage();
|
||
|
|
}
|
||
|
|
|
||
|
|
sendButton.disabled = input.value === "";
|
||
|
|
});
|
||
|
|
|
||
|
|
input.onkeyup = (e => {
|
||
|
|
if (e.keyCode == 13 && e.shiftKey) {
|
||
|
|
input.value = "";
|
||
|
|
input.disabled = false;
|
||
|
|
}
|
||
|
|
});
|
||
|
|
|
||
|
|
$("#messageInput").attr("placeholder", "Message to :" + room);
|
||
|
|
});
|
||
|
|
|
||
|
|
</script>
|