Skip to content

Instantly share code, notes, and snippets.

@rakhi2104
Created March 12, 2019 12:45
Show Gist options
  • Save rakhi2104/3c3d52f8dc1a92fbf330d188cada0f17 to your computer and use it in GitHub Desktop.
Save rakhi2104/3c3d52f8dc1a92fbf330d188cada0f17 to your computer and use it in GitHub Desktop.
Firebase Chat
function signIn() {
var provider = new firebase.auth.GoogleAuthProvider();
firebase
.auth()
.signInWithPopup(provider)
.then(result => {
// perform action
});
}
function signOut() {
// inactive status update
firebase.auth().signOut();
}
function initFirebaseAuth() {
// Listen to auth changes
}
function saveMessage(messageText) {
// save msg to DB
}
var query = firebase.database().ref("messages");
function loadMessages(state) {
messagesListSpinnerElement.setAttribute("hidden", "false");
document.getElementById("messages-list").innerHTML = "";
query.on("value", async snapshot => {
if (snapshot.val()) {
await Object.keys(snapshot.val()).forEach(async key => {
document.getElementById("messages-list").innerHTML += generateMessage(
await snapshot.val()[key]
);
});
await (snapshot.val() ||
messagesListSpinnerElement.setAttribute("hidden", "true"));
} else {
document.getElementById("messages-list").innerHTML = "";
document.getElementById(
"messages-list"
).innerHTML += `<li class="center"> No Messages yet</li>`;
}
});
}
function loadRoomMembers() {
// Load Chat Room Members
}
function onMessageFormSubmit(e) {
// submit message
}
function authStateObserver(user) {
loadRoomMembers();
loadMessages();
if (user) {
// activate elements
} else {
// deactivate elements
}
}
// Function to generate message
function generateMessage(message) {
var MessageItem = null;
var currentUser = "x";
var SENDER_PROFILE = null;
var senderID = message.sender.uid;
if (firebase.auth().currentUser) {
currentUser = firebase.auth().currentUser.uid;
}
if (message.type === "message") {
if (senderID !== currentUser) {
SENDER_PROFILE =
`<span class="sender-profile"><img title="` +
message.sender.email +
`" src="` +
message.sender.profileURL +
`" class="border-circle" />` +
message.sender.name +
`</span>`;
}
var MESSAGE_TEMPLATE =
`<li>` +
(SENDER_PROFILE !== null ? SENDER_PROFILE : "") +
`<div class="message-container"> <div class="mdl-shadow--2dp message-` +
(senderID === currentUser ? "sent" : "received") +
`">` +
message.text +
`<span class="message-time">` +
timeFormat(message.timestamp) +
`</span></div></div></li>`;
MessageItem = MESSAGE_TEMPLATE;
} else {
MessageItem = `<li class="message-info">` + message.text + "</li>";
}
return MessageItem;
}
// DOM Elements
// Declared here ...
initFirebaseAuth();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment