Skip to content

Commit

Permalink
significantly simplify app.js #54 / #121
Browse files Browse the repository at this point in the history
  • Loading branch information
nelsonic committed Nov 23, 2022
1 parent 81fee57 commit 458a722
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 135 deletions.
130 changes: 40 additions & 90 deletions assets/js/app.js
Original file line number Diff line number Diff line change
@@ -1,113 +1,48 @@
// We import the CSS which is extracted to its own file by esbuild.
// Remove this line if you add a your own CSS build pipeline (e.g postcss).

// If you want to use Phoenix channels, run `mix help phx.gen.channel`
// to get started and then uncomment the line below.
import socket from "./user_socket.js"

// You can include dependencies in two ways.
//
// The simplest option is to put them in assets/vendor and
// import them using relative paths:
//
// import "../vendor/some-package.js"
//
// Alternatively, you can `npm install some-package --prefix assets` and import
// them using a path starting with the package name:
//
// import "some-package"
//

// Include phoenix_html to handle method=PUT/DELETE in forms and buttons.
import "phoenix_html"
// Establish Phoenix Socket and LiveView configuration.
// Establish Phoenix Socket:
import {Socket} from "phoenix"
import {LiveSocket} from "phoenix_live_view"
import topbar from "../vendor/topbar"

function formatInsertedAtString(datetime) {
const m = new Date(datetime)
const ul = document.getElementById('msg-list'); // list of messages.
const name = document.getElementById('name'); // name of message sender
const msg = document.getElementById('msg'); // message input field
let channel = socket.channel('room:lobby', {}); // connect to chat "room"

let dateString = m.getUTCFullYear() + "/" +
("0" + (m.getUTCMonth()+1)).slice(-2) + "/" +
("0" + m.getUTCDate()).slice(-2);
channel.on('shout', function (payload) { // listen for 'shout' event
render_message(payload)
});

let timeString = ("0" + m.getUTCHours()).slice(-2) + ":" +
("0" + m.getUTCMinutes()).slice(-2) + ":" +
("0" + m.getUTCSeconds()).slice(-2);
channel.join(); // join the channel.

return {
date: dateString,
time: timeString
}
function sendMessage() {
channel.push('shout', { // send the message to the server on "shout" channel
name: name.value || "guest", // get value of "name" of person sending the message. Set guest as default
message: msg.value, // get message text (value) from msg input field.
inserted_at: new Date() // datetime of when the message was isnerted
});
msg.value = ''; // reset the message input field for next message.
window.scrollTo(0, document.body.scrollHeight); // scroll to the end of the page on send
}

formatInsertedAtString("2022-10-12T12:28:19")

let csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content")
let liveSocket = new LiveSocket("/live", Socket, {params: {_csrf_token: csrfToken}})

// Show progress bar on live navigation and form submits
topbar.config({barColors: {0: "#29d"}, shadowColor: "rgba(0, 0, 0, .3)"})
window.addEventListener("phx:page-loading-start", info => topbar.show())
window.addEventListener("phx:page-loading-stop", info => topbar.hide())

// connect if there are any LiveViews on the page
liveSocket.connect()

// expose liveSocket on window for web console debug logs and latency simulation:
// >> liveSocket.enableDebug()
// >> liveSocket.enableLatencySim(1000) // enabled for duration of browser session
// >> liveSocket.disableLatencySim()
window.liveSocket = liveSocket


let channel = socket.channel('room:lobby', {}); // connect to chat "room"

channel.on('shout', function (payload) { // listen to the 'shout' event
// Get information from payload
const name = payload.name || 'guest';
const message = payload.message
const date = formatInsertedAtString(payload.inserted_at).date
const time = formatInsertedAtString(payload.inserted_at).time

let li = document.createElement("li"); // create new list item DOM element
// Message HTML with Tailwind CSS:
function render_message(payload) {
const li = document.createElement("li"); // create new list item DOM element
// Message HTML with Tailwind CSS Classes for layout/style:
li.innerHTML = `
<div class="flex flex-row w-[95%] mx-2 border-b-[1px] border-slate-300 py-1">
<div class="flex flex-row w-[95%] mx-2 border-b-[1px] border-slate-300 py-2">
<div class="text-left w-1/5 font-semibold text-slate-800 break-words">
${name}
${payload.name}
<div class="text-xs mr-1">
<span class="font-thin">${date}</span>
<span>${time}</span>
<span class="font-thin">${formatDate(payload.inserted_at)}</span>
<span>${formatTime(payload.inserted_at)}</span>
</div>
</div>
<div class="flex w-3/5 mx-1 grow">
${message}
${payload.message}
</div>
</div>
`
// Append to list
ul.appendChild(li);
});

channel.join(); // join the channel.


let ul = document.getElementById('msg-list'); // list of messages.
let name = document.getElementById('name'); // name of message sender
let msg = document.getElementById('msg'); // message input field

// function to be called on send
function sendMessage() {
console.log('sendMessage')
channel.push('shout', { // send the message to the server on "shout" channel
name: name.value || "guest", // get value of "name" of person sending the message. Set guest as default
message: msg.value, // get message text (value) from msg input field.
inserted_at: new Date() // datetime of when the message was isnerted
});
msg.value = ''; // reset the message input field for next message.
window.scrollTo(0, document.body.scrollHeight); // scroll to the end of the page on send
}

// "listen" for the [Enter] keypress event to send a message:
Expand All @@ -123,3 +58,18 @@ window.onload = function() {
sendMessage()
});
}

// Date & Time Formatting
function formatDate(datetime) {
const m = new Date(datetime);
return m.getUTCFullYear() + "/"
+ ("0" + (m.getUTCMonth()+1)).slice(-2) + "/"
+ ("0" + m.getUTCDate()).slice(-2);
}

function formatTime(datetime) {
const m = new Date(datetime);
return ("0" + m.getUTCHours()).slice(-2) + ":"
+ ("0" + m.getUTCMinutes()).slice(-2) + ":"
+ ("0" + m.getUTCSeconds()).slice(-2);
}
13 changes: 7 additions & 6 deletions lib/chat_web/templates/layout/root.html.heex
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,24 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<meta name="csrf-token" content={csrf_token_value()}>
<%= live_title_tag assigns[:page_title] || "Phoenix Chat", suffix: " · Tutorial!" %>
<script defer phx-track-static type="text/javascript" src={Routes.static_path(@conn, "/assets/app.js")}></script>
<script defer phx-track-static type="text/javascript"
src={Routes.static_path(@conn, "/assets/app.js")}></script>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body>
<header class="bg-slate-800 w-full h-[4rem] top-0 fixed flex flex-col justify-center z-10">
<nav class="flex flex-row justify-between items-center">
<h1 class="w-4/5 lg:text-3xl text-center font-mono text-white ml-4">
<nav class="flex flex-row justify-between items-center text-white">
<h1 class="w-4/5 md:text-3xl text-center font-mono ml-4">
Phoenix Chat Example
</h1>
<div class="float-right mr-3">
<%= if @loggedin do %>
<div class="flex flex-row justify-center items-center">
<img width="42px" src={@person.picture} />
<%= link "logout", to: "/logout", class: "bg-red-500 text-white rounded-xl px-3 py-2 ml-4 mr-1" %>
<img width="42px" src={@person.picture} class="rounded-full"/>
<%= link "logout", to: "/logout", class: "bg-red-600 rounded px-2 py-2 ml-2 mr-1" %>
</div>
<% else %>
<div class="bg-green-500 text-white rounded-xl px-3 py-2 w-full font-bold">
<div class="bg-green-500 rounded px-3 py-2 w-full font-bold">
<%= link "Login", to: "/login" %>
</div>
<% end %>
Expand Down
57 changes: 18 additions & 39 deletions lib/chat_web/templates/page/index.html.heex
Original file line number Diff line number Diff line change
@@ -1,42 +1,21 @@

<ul id='msg-list' phx-update="append" class="pa-1"> </ul>
<footer class="bg-slate-800 p-2 h-[3rem] fixed bottom-0 w-full flex justify-center">
<div class="w-full flex flex-row items-center">
<%= if @loggedin do %>
<input type="text" disabled class="hidden" id="name"
placeholder={person_name(@person)} value={person_name(@person)}
/>
<% else %>
<input
type="text"
class="grow-0 w-1/6 px-1.5 py-1.5 text-base font-normal
text-gray-700 bg-white bg-clip-padding
border border-solid border-gray-300 rounded
transition focus:text-gray-700 focus:border-blue-600 focus:outline-none
"
id="name"
placeholder="Name"
required="required"
/>
<% end %>

<input
type="text"
class="grow w-2/3 mx-2 px-2 py-1.5 text-base font-normal
text-gray-700 bg-white bg-clip-padding
border border-solid border-gray-300 rounded
transition ease-in-out focus:border-blue-600 focus:outline-none
"
id="msg"
placeholder="Your message"
required="required"
<ul id='msg-list' phx-update="append" class="pa-1"> </ul>
<footer class="bg-slate-800 p-2 h-[3rem] fixed bottom-0 w-full flex justify-center">
<div class="w-full flex flex-row items-center text-gray-700 focus:outline-none font-normal">
<%= if @loggedin do %>
<input type="text" disabled class="hidden" id="name"
placeholder={person_name(@person)} value={person_name(@person)}
/>
<% else %>
<input type="text" id="name" placeholder="Name" required
class="grow-0 w-1/6 px-1.5 py-1.5"/>
<% end %>

<button id="send"
class="text-white rounded-xl px-3 py-1.5
transition-colors duration-150 bg-sky-500 hover:bg-sky-600">
Send
</button>
<input type="text" id="msg" placeholder="Your message" required
class="grow w-2/3 mx-1 px-2 py-1.5"/>

</div>
</footer>
<button id="send" class="text-white bold rounded px-3 py-1.5
transition-colors duration-150 bg-sky-500 hover:bg-sky-600">
Send
</button>
</div>
</footer>

0 comments on commit 458a722

Please sign in to comment.